README Source History Refs Reviews Compare Notes Search Review guide Make the product spec the sole documentation authority 84e9bff609f8ab42e07e22591a7f2bd7f60ec2ad
Oliver Jan Krylow <oliver@bugabinga.net > · 4 Aug 2026
SSH signature · not checked
Browse files Compare with HEAD
The previous docs mixed product contracts with hosting, delivery, and implementation workflow, making requirements harder to find and easier to contradict. Preserve product behavior and research evidence while dropping plans and forge concepts.
The rewritten documentation surface spans `README.md`, `CLAUDE.md`, `docs/`, and two capture adapters.
Changed files (11) Diff layout Auto Unified Split
.claude/skills/capture/references/tape.md Modified +2 / −2 text lines
24 24 - `FontSize` ≥ 16; **20 is the default here**.- `FontSize` ≥ 16; **20 is the default here**.25 25 - Columns ≈ `(Width − 2·Padding) / (FontSize × 0.6)`. The defaults- Columns ≈ `(Width − 2·Padding) / (FontSize × 0.6)`. The defaults26 26 (`Width 1200`, `Padding 12`, `FontSize 20`) yield a ~98×27 grid — about (`Width 1200`, `Padding 12`, `FontSize 20`) yield a ~98×27 grid — about27 - right for a full-screen TUI rendered into a ~ 900 px- wide PR body .27 + right for a full-screen TUI rendered at approximately 900 px wide.28 28 - Wider app? Prefer 1600×800 @ FontSize 18 (~145 cols) over shrinking the- Wider app? Prefer 1600×800 @ FontSize 18 (~145 cols) over shrinking the29 - font further. Below 14 pt, text in a PR is decoration, not evidence.29 + font further. Below 14 pt, text is decoration, not evidence.30 30 - `Set Theme "Catppuccin Mocha"` (or any high-contrast dark theme) and- `Set Theme "Catppuccin Mocha"` (or any high-contrast dark theme) and31 31 `Set Padding 12` keep edges and colors readable. `Set Padding 12` keep edges and colors readable..pi/prompts/capture.md Modified +1 / −1 text lines
2 2 name: capturename: capture3 - description: Capture TUI screenshots and recordings for PRs, QA, debugging.3 + description: Capture TUI screenshots and recordings for QA and debugging.4 4 argument-hint: "[target]"argument-hint: "[target]"+37 / −90 text lines
3 - Rust coding agent TUI. Phase: spec/planning. No production code until specs4 - are final; disposable spec-validation prototypes live under `prototypes/`3 + Rust coding-agent TUI. Product behavior is specified; production crates remain skeletal.7 5 ## Architecture ## Architecture 10 - smith/ (types, StreamFn, AgentTool, Lua, config)11 - → smith-ai/ | smith-core/ | smith-tui/ (parallel) 12 - → smith-harness/ (wiring, plugins, SDK)13 - → smith-cli/ (binary) 9 + → smith-core | smith-ai | smith-tui14 + Rust owns typed contracts and high-frequency primitives. Lua owns user-facing tools, commands, themes, keybindings, prompts, layouts, and plugin behavior.18 - | Decision | Rationale |19 - |----------|-----------|20 - | Latest stable Rust, ed. 2024 | Rolling MSRV follows stable compiler |21 - | mlua + LuaJIT | Performance, coroutines |22 - | CBOR sessions | Compact, binary-safe |23 - | Secret proxy (no keychain) | Cross-platform |24 - | XDG dirs | Linux standards |25 - | jj VCS | Modern DVCS |26 - | StreamFn abstraction | Decouples agent from providers |27 - | Lua plugins with sandbox | Safe extensibility |28 - | Rust widgets, Lua layout | Performance + flexibility |29 - | Cargo-only build system | Single entry point, no make/just/scripts |18 + - `docs/SPEC.md` — complete product contract.19 + - `docs/PROJECT-INVARIANTS.md` — development boundaries.20 + - `docs/research/` — retained evidence, never authority.21 + - `prototypes/` — isolated evidence, never production dependencies.33 - CLAUDE.md is a navigation index. Do not mirror individual source-of-truth file34 - lists here; use the canonical directories and docs tree instead.36 - One specification sits at the top:38 - - **What to build — `docs/SPEC.md`.** The canonical specification for every39 - smith artifact: the app, the site, the book, and the documentation.41 - Bound by the invariants, and supported by the rest:43 - - **Invariants — `docs/PROJECT-INVARIANTS.md`.** Non-negotiable rules every44 - contributor, tool, and agent follows: build system, directory structure,45 - coding standards, version control. Overriding one needs explicit approval.46 - - Research: `docs/research/` — ecosystem research and tool analysis47 - (evidence, non-normative).48 - - Plans: `docs/plans/` — execution plans (non-normative); `README.md` indexes them.49 - - Prototypes: `prototypes/` — spec-validation prototypes and their plan.51 - Former `docs/design/` subsystem docs and the P1–P20 prototype report are fully52 - absorbed into `docs/SPEC.md` and deleted (see git history).23 + Do not create parallel specifications or duplicate source-of-truth lists.56 - 1. Spec before code. No production `.rs` until `docs/SPEC.md` covers the57 - work; prototype `.rs` under `prototypes/` is sanctioned by SPEC §18.58 - 2. CLAUDE.md is the navigation index. `docs/SPEC.md` is the canonical project spec.59 - 3. Every spec section answers: interfaces, data, errors, tests — as named60 - shapes and behavior, not code. Exact only at boundaries others program61 - against (files, wire formats, CLI, config, Lua SDK); code blocks are62 - illustrative unless the section says otherwise.63 - 4. Open questions: stop and ask. No guessing.64 - 5. Invoke spec work: `/smith <topic>`. Commands are defined once,65 - harness-agnostically, in `.claude/skills/<name>/SKILL.md`66 - (smith, pioneer, handmade, sabotnik, capture); `.pi/prompts/` holds thin67 - pi adapters that defer to them. `.agents/skills` symlinks to68 - `.claude/skills` so harnesses that discover skills there read the same70 - 6. Cargo is the sole build system. See `docs/PROJECT-INVARIANTS.md` §1.71 - 7. Agents must not modify `docs/SPEC.md` or `docs/PROJECT-INVARIANTS.md` without approval.27 + 1. Specify product behavior before production implementation.28 + 2. Product requirements belong only in `docs/SPEC.md`.29 + 3. Exact boundaries include files, wire formats, CLI, configuration, RPC, and Lua SDK.30 + 4. Stop on open design questions; never guess.31 + 5. Cargo is the sole build interface.32 + 6. Modifying the specification, invariants, dependency membership, toolchain, Cargo config, or CI requires explicit owner approval.33 + 7. Keep research citations and evidence, but do not promote research prose into requirements.34 + 8. Keep generated output, scratch state, credentials, and captures out of git.75 - Commits argue the **why**, not the **what**. The diff already lists what76 - changed — never retype it. A message earns its place by recording the77 - motivation, the reasoning, and what was deliberately *not* done and why.38 + Canonical skills live under `.claude/skills/`; `.pi/prompts/` contains thin adapters and `.agents/skills` links to the same definitions.79 - - **No AI attribution, ever.** No `Co-Authored-By`, no "Generated with", no80 - session links, no tool bylines. These commits are the author's.81 - - **Subject:** one imperative line naming the decision or its effect, not the82 - mechanic — "Drop the Lua bytecode cache", not "remove BytecodeCache struct".83 - No ALL-CAPS verdicts, no emoji. (Prefix policy: PROJECT-INVARIANTS §7.)84 - - **Body:** one to three short paragraphs. The motivation, the alternative85 - dropped and the single cost that killed it, and the one number or fact that86 - settled it. If it wants more than that, the overflow belongs elsewhere.87 - - **One grep-able anchor.** Exactly one sentence naming the concrete surface88 - touched — `SPEC §N`, a file, a config key, a `prototypes/pNN` dir — as a89 - range or count, never a per-item roster. This is what keeps `git bisect` and90 - `blame` meaningful. "Don't enumerate" is not "don't be specific."91 - - **Where detail lives instead:** per-file change lists → the diff; benchmark92 - tables and raw measurements → the prototype dir and its `PLAN.md` result93 - block; the decision plus its driving number → the commit body, in prose.94 - - **One commit, one decision.** If the anchor won't fit one sentence, split.95 - - **Banned:** superlatives, "successfully / robustly / cleanly", caps-lock96 - findings, emoji, and every attribution trailer.40 + - `/smith <topic>` — product specification work.41 + - `/pioneer <claim>` — isolated prototype evidence.42 + - `/handmade <scope>` — remove needless complexity.43 + - `/sabotnik <scope>` — harden Rust.44 + - `/capture <target>` — TUI evidence.98 - ## Agent output discipline 100 - Every agent is **terse — essentials only**. Reports are:48 + - Signed, imperative subject, no type prefix required.49 + - Explain why; the diff already explains what.50 + - One commit, one decision.51 + - Name one concrete changed surface in the body.52 + - No AI attribution, generated-by text, session links, emoji, or superlatives.53 + - Integrate by signed fast-forward to `trunk`; never force-push without explicit approval.102 - - **Findings/actions as one-line bullets, most severe first.** No preamble, no103 - praise, no "what holds up well" tour, no restating the diff or issue back.104 - - **A clean result is one line** — "No blocking findings." — not an essay. Say105 - the fewest words that carry the decision and the one reason for it.106 - - **No meta-narration** of what you're about to do or just did. Post the verdict107 - and the findings that change it; drop everything else.109 - Thoroughness is in the *reasoning*, not the word count. A wall of text is a110 - defect, not diligence.57 + Report only findings and actions that affect the decision. Use one-line bullets, most severe first. A clean result is `No blocking findings.`+38 / −88 text lines
3 - A coding-agent TUI written in Rust, extended in Lua.3 + A fast, extensible coding-agent TUI written in Rust and extended in Lua.5 - > **Status: specification.** Smith is being specified before it is built. The6 - > workspace crates are stubs; the product described below does not run yet.7 - > [`docs/SPEC.md`](docs/SPEC.md) is the canonical description of what it will8 - > be, and it is considerably further along than the code.5 + > **Status: specification.** Product behavior is specified; production crates are still skeletal.12 - [pi](https://github.com/earendil-works/pi) is Smith's starting point and its13 - philosophical ancestor. It is well designed, and it hits a sweet spot: handle14 - the annoying LLM details, stay minimal, stay extensible. Smith exists because15 - two of its costs are structural rather than incidental — they follow from16 - implementation choices that cannot be patched out from the outside.18 - **The runtime.** Node and npm carry a dependency-security surface that has to19 - be re-audited continuously, and a performance floor a terminal UI keeps20 - bumping into. Smith is a single Rust binary. The targets it is specified21 - against are a stripped release under 20MB and `--help` under 100ms22 - (§13) — targets, not measurements, until there is something to measure.11 + - an interactive terminal UI;12 + - non-interactive evaluation;13 + - JSON-RPC over stdio for alternate frontends;14 + - provider-independent streaming;15 + - append-only branching sessions with deterministic replay;16 + - VCS operation-level undo and time travel;17 + - a sandboxed Lua plugin system used by built-ins and user extensions alike.24 - **Sharing extensions.** This is the deeper one. pi's extension mechanism has25 - good hooks and a broadly stable API, but its audience is a single developer or26 - a small team. Extensions are hard to share across a community, because a27 - principled interface and an IPC channel are missing. The symptom is visible in28 - the ecosystem: dozens of separate subagent extensions, some of them29 - dependencies of other extensions that needed subagent functionality, with no30 - common contract to depend on. For a consumer of community extensions that is a31 - mess, and the rational response is to give up and maintain your own — which is32 - the outcome an extension system is supposed to prevent.19 + Smith is not a Pi fork and does not preserve Pi APIs or data formats.34 - Smith's answer is to make the plugin API the *only* extension API. Everything35 - user-visible — tools, slash commands, themes, keybindings, prompts, layouts,36 - feature UI — is a Lua plugin, and the built-in tools are written against the37 - same interface third-party plugins get (§9). An interface its own author must38 - use is one that stays honest. Plugins declare identity and dependencies in a39 - manifest, run sandboxed, and talk over a typed, versioned SDK rather than40 - reaching into internals.42 - Two more things fall out of the design rather than being features bolted on:44 - - **Provider independence.** The agent loop depends on `StreamFn` — a request45 - in, a stream of provider events out — and on nothing else (§5.4). Providers46 - are adapted to that shape, so the loop has no idea which one it is talking48 - - **Sessions you can replay.** Conversation state is a tree, stored as CBOR,49 - and a recorded trace can be re-executed deterministically without touching a50 - live provider (§6.5, §6.6, §6.11).52 - **Who it is for.** People who live in a terminal, want their coding agent to53 - start instantly and stay out of the way, and expect to reshape it — and to be54 - able to use what someone else built without adopting their dependency tree.56 - **What Smith is not.** Not a pi fork and not pi-compatible: no shared data, no57 - shared formats, no code lineage. Not a GUI, not an IDE plugin, and not an58 - onboarding wizard — the first run has no setup flow, and a missing credential59 - is reported as an error that names the env var to set.63 - Interactive TUI, a non-interactive eval mode, and a JSON-RPC stdio mode, over64 - one agent loop (§1). Conversation history is a tree you can navigate, separate65 - from a VCS-backed timeline of what your files looked like — moving through the66 - conversation does not move your working copy, and vice versa. Mid-run67 - corrections queue as steers rather than forcing a cancel.72 - smith/ shared types, StreamFn, AgentTool, config, Lua runtime73 - smith-ai/ providers, auth, model registry, provider streams74 - smith-core/ agent loop, sessions, tools75 - smith-tui/ terminal UI76 - smith-harness/ wiring, plugin management, the Lua SDK78 - xtask/ custom build tasks24 + smith/ shared contracts25 + smith-core/ agent runtime and sessions26 + smith-ai/ providers and authentication27 + smith-tui/ terminal frontend28 + smith-harness/ orchestration and Lua SDK30 + xtask/ Cargo orchestration81 - `docs/` holds project management rather than code: the specification, the82 - invariants every contributor and agent follows, research notes, and execution83 - plans. `prototypes/` holds disposable programs written to prove or disprove a84 - specific spec claim (§18).33 + The agent runtime depends on `StreamFn`, not concrete providers. Rust owns typed contracts and high-frequency primitives; Lua owns user-facing extensibility.88 - Cargo is the only build system for the Rust workspace — there is no Makefile,89 - justfile, or script to learn, and anything cargo does not do natively lives in37 + Cargo is the only build interface.93 40 cargo checkcargo check95 - cargo run -p xtask -- check 41 + cargo test -- workspace 42 + cargo fmt --all --check43 + cargo run -p xtask -- check98 - Smith tracks latest stable Rust on edition 2024. A pinned nightly is used for 99 - exactly one thing — the `cargo-pup` architecture gate — and never for product46 + Smith follows latest stable Rust on edition 2024.104 - - [`docs/SPEC.md`](docs/SPEC.md) — what to build. Canonical.105 - - [`docs/PROJECT-INVARIANTS.md`](docs/PROJECT-INVARIANTS.md) — the rules that 106 - do not bend without explicit approval.107 - - [`CLAUDE.md`](CLAUDE.md) — the navigation index .50 + - [`docs/SPEC.md`](docs/SPEC.md) — complete product contract.51 + - [`docs/PROJECT-INVARIANTS.md`](docs/PROJECT-INVARIANTS.md) — development boundaries. 52 + - [`docs/research/`](docs/research/) — retained evidence and ecosystem research.53 + - [`prototypes/`](prototypes/) — isolated validation programs.54 + - [`CLAUDE.md`](CLAUDE.md) — repository navigation and agent rules .109 - Section marks above (§N) refer to `docs/SPEC.md`.58 + - Source: <https://vcs.bugabinga.net/smith>59 + - CI: <https://ci.bugabinga.net>docs/PROJECT-INVARIANTS.md Modified +87 / −498 text lines
1 1 # Project Invariants # Project Invariants 3 - These invariants govern the smith codebase. They are non-negotiable rules that every contributor, tool, and agent must follow. Violations require explicit approval to override.3 + These rules govern Smith development. Changing one requires explicit owner approval.5 - ## 1. Cargo Is the Sole Build System and Entry Point 5 + ## 1. Product Authority 7 - **Invariant:** `cargo` is the only build system. No `make`, `just`, `npm`, `pnpm`, or custom scripts outside of cargo.7 + - `docs/SPEC.md` is the complete product contract.8 + - The specification contains product requirements only.9 + - Research is evidence, never authority.10 + - Production Rust work starts only after the relevant product behavior is specified.11 + - Prototypes may validate uncertain claims but MUST NOT become production dependencies.9 - **Implication:** Every developer-facing task must be reachable via `cargo`:10 - - Build: `cargo build`, `cargo check`11 - - Test: `cargo test`, `cargo nextest run`12 - - Lint: `cargo clippy`, `cargo fmt`14 - - Custom tasks: `cargo run -p xtask -- <cmd>`16 - **xtask boundary:** Any task not handled natively by cargo lives in the `xtask/` workspace crate. xtask is the single extension point for custom automation.15 + Cargo is the sole build interface.18 - **Automation is orchestration, not a second build system.** Any automation19 - delegates product work to `cargo` / `cargo run -p xtask -- <cmd>` and carries no20 - business logic of its own.23 - - Makefile, justfile, package.json, build.sh24 - - Custom scripts outside Cargo25 - - Shell scripts in repo root or scripts/26 - - Any build step that requires tools not installable via `cargo install`, with three named exceptions, all confined to gates and release builds: pinned nightly rustup components required by the `cargo-pup` architecture gate; the **toolchains** the cross-compilers drive — the `zig` toolchain `cargo-zigbuild` needs, and the host **LLVM/clang** installation `cargo-xwin` needs (it fetches the Microsoft SDK, not the compiler that consumes it); and the **platform SDKs** themselves — the Microsoft C runtime and Windows SDK that `cargo-xwin` fetches, and a macOS SDK where a C dependency's darwin headers demand one (§4, *Cross-compilation*). The cross-compilers themselves are `cargo install`-able; the exception covers the external toolchains and SDKs they drive, nothing else28 - **Scope:** this invariant governs the **Rust workspace** — the app, its crates,29 - and their build. The published **web site** is a separate artifact and is exempt,30 - narrowly: the Astro site may carry its own `package.json` and Node build **confined31 - to `site/`** (never the workspace root). The **book** stays inside the rule — it32 - is mdBook, which is `cargo install`-able — so the site exemption remains confined33 - there. No lockfile or `package.json` may appear at the repo root or inside any36 - ## 2. Directory Separation: Code vs. Project Management 39 - smith/ # ← code (crates, Cargo, .rs)40 - ├── Cargo.toml # workspace root49 - ├── rust-toolchain.toml52 - docs/ # ← project management (spec, research)53 - ├── SPEC.md # canonical project specification (self-contained;54 - │ # subsystem design content lives here)55 - ├── research/ # ecosystem research, tool analysis (evidence,57 - │ ├── RESEARCH-NOTES.md58 - │ ├── TERMINAL-CAPABILITIES-RESEARCH.md59 - │ ├── TESTING-STRATEGY-RESEARCH.md60 - │ ├── CI-PATTERNS-RESEARCH.md61 - │ └── CRATE-ECOSYSTEM-RESEARCH.md62 - ├── plans/ # execution plans (non-normative)63 - │ ├── README.md # plans index + coverage64 - │ ├── WALKING-SKELETON.md # first vertical slice — implementation entry65 - │ ├── TASK-BREAKDOWN.md # crate build order66 - │ └── PLUGIN-DOC-PLAN.md # doc-SDK tooling67 - └── PROJECT-INVARIANTS.md # this file69 - prototypes/ # ← disposable spec-validation prototypes70 - ├── CLAUDE.md # prototype rules71 - └── PLAN.md # prototype plan + result blocks22 + cargo run -p xtask -- <command>74 - Former `docs/design/` subsystem docs were fully absorbed into `docs/SPEC.md`75 - and deleted (2026-07-15; see git history).25 + Forbidden production build surfaces:77 - **Rule:** Code review gates on `src/`, `Cargo.toml`, `tests/`. Project management review gates on `docs/`. No code in `docs/`, no specs in `src/`.30 + - root `package.json`;31 + - Python, Node, or shell as a second build system.79 - ## 3. Build Invariants 33 + `xtask` MAY orchestrate installed tools but MUST contain no product logic. Any CI definition MUST delegate to Cargo or xtask.81 - ### 3.1 Rust Toolchain 35 + Workspace version starts at `0.1.0` under Apache-2.0. Release builds use optimization level 3, thin LTO, one codegen unit, stripped symbols, and aborting panics.83 - **Policy:** Smith follows latest stable Rust. Do not pin a numeric MSRV in docs or manifests unless release engineering later creates a formal support window.37 + ## 3. Repository Layout 85 - **Nightly exception:** `cargo-pup` architecture linting runs on pinned nightly `nightly-2026-01-22` because it uses rustc internals. Nightly may be used only by the pup gate. Stable remains required for build, test, run, and release.91 - components = ["rustfmt", "clippy"]40 + smith/ shared contracts41 + smith-core/ agent runtime42 + smith-ai/ provider integrations43 + smith-tui/ terminal frontend44 + smith-harness/ orchestration and Lua plugins46 + xtask/ Cargo orchestration47 + docs/SPEC.md product contract48 + docs/research/ retained evidence49 + prototypes/ isolated disposable proofs94 - ### 3.2 Clippy — Zero Warning Policy 52 + Product code lives in crates. Product requirements live in `docs/SPEC.md`. Research and prototypes MUST NOT define runtime behavior.96 - **Invariant:** All workspace crates compile with zero warnings. No exceptions for shipped code.56 + - Use latest stable Rust and edition 2024.57 + - Product code MUST compile without warnings.58 + - Workspace lints live in root `Cargo.toml`; target flags MUST NOT weaken them.59 + - Library crates forbid unsafe code.60 + - `smith-cli` MAY use unsafe only for unavoidable terminal operations behind a documented, tested safe abstraction.61 + - Shipped libraries MUST NOT use `unwrap`, `expect`, `panic`, `todo`, or `unimplemented` for external failures.62 + - Use rustfmt defaults from `rustfmt.toml` and the project policy in `.clippy.toml`.100 - **`[workspace.lints]` in the workspace root, inherited by every crate via101 - `[lints] workspace = true` — never `rustflags`.** A `[target.<triple>].rustflags`102 - key *replaces* `[build].rustflags` instead of merging, so a target carrying any103 - flag of its own would build with the whole wall switched off; Android needs104 - exactly such a flag (§8a). Lint tables are per-crate and target-independent, and105 - apply only to workspace crates rather than leaking denials into dependencies.107 - Denied: the clippy **all / pedantic / suspicious / complexity / perf / style /108 - correctness** groups; **`unwrap_used`, `expect_used`, `panic`, `todo`,109 - `unimplemented`, `print_stdout`, `print_stderr`**; **`missing_docs`,110 - `rustdoc::missing_crate_level_docs`, `rustdoc::broken_intra_doc_links`**. Warned:111 - `clippy::nursery`, `rustdoc::invalid_html_tags`, `rustdoc::bare_urls`.66 + - Root `[workspace.dependencies]` is the single dependency registry.67 + - Crates inherit shared dependencies from the workspace.68 + - New or removed third-party dependencies require owner approval.69 + - Version bumps are maintenance unless they change API compatibility, Rust requirements, architecture, or binary/compile budgets.70 + - Heavy dependencies stay in the crate that owns their concern.71 + - An incremental crate edit MUST rebuild only that crate and its reverse-dependency closure.72 + - Cold-build time and crate count are regression-gated once a full-workspace baseline exists.73 + - Product code MUST NOT depend on prototype crates.113 - `.cargo/config.toml` carries only what cannot be a lint — the Android link flag114 - and the sparse registry protocol.117 - # .clippy.toml — configuration VALUES only; enablement lives in [workspace.lints]118 - cognitive-complexity-threshold = 25119 - # No msrv key: lint policy follows latest stable Rust.77 + Before integration, run the smallest complete applicable gate. At minimum:80 + cargo fmt --all --check81 + cargo test --workspace84 + Rust changes additionally require applicable clippy, architecture, documentation, and product-acceptance checks. A failing check MUST NOT be skipped, weakened, or deleted to obtain green output.125 - cargo clippy --workspace --all-targets --all-features86 + Release verification requires at least 80% workspace coverage, more than 80% mutation score, and Criterion scenarios `session_encode_1000`, `session_decode_1000`, `widget_render_100`, `agent_loop_turn`, `config_resolve_3level`, `trace_filter_10000`, and `plugin_load_10`. Benchmark regression above 5% warns; above 10% blocks release.128 - #### Escape Hatch Policy 88 + ## 7. Protected Decisions 130 - `#[allow(...)]` is permitted **only** with a documented reason:90 + Agents MUST obtain explicit owner approval before modifying:134 - #[allow(clippy::unwrap_used)]93 + - `docs/PROJECT-INVARIANTS.md`;94 + - root `Cargo.toml` dependency membership;95 + - `.cargo/config.toml`;96 + - `rust-toolchain.toml`;97 + - CI definitions under `.ci/`.137 - #[expect(clippy::unwrap_used, reason = "mutex never poisoned — sole accessor" )]138 - let guard = mutex.lock ().unwrap ();99 + Agents MAY freely modify specified implementation and test code within those boundaries.141 - **Preferred:** Use `#[expect(lint, reason = "...")]` (Rust 1.81+). It suppresses the lint AND warns if the lint is not actually triggered, catching stale allows.101 + ## 8. Version Control 143 - **Registry:** Project-wide exceptions are documented in `.clippy.toml` with rationale. No scattered `#[allow]` attributes.104 + - Canonical origin: `git@vcs.bugabinga.net:smith.git`.105 + - Canonical branch: `trunk`.106 + - Integrate by signed fast-forward.107 + - Never force-push without explicit owner approval.108 + - Never add merge commits.109 + - Delete topic branches after integration.110 + - Commit messages explain why, use imperative subjects, and contain no AI attribution.145 - **Proc-macro output:** Derive macros (serde/ciborium and similar) may trigger warnings under `-D warnings` from generated code or intentionally generated fields. Use `#[expect(..., reason = "...")]` on the deriving item or narrowest containing module. Do not edit generated output or silence warnings crate-wide.147 - ### 3.3 Format — Enforced 151 - CI fails on unformatted code. No manual formatting debates — rustfmt is the authority.114 + - Source: `https://vcs.bugabinga.net/smith`.115 + - CI: `https://ci.bugabinga.net`.116 + - Luci discovers `.ci/*.kdl` from the public source repository.117 + - CI configuration is orchestration only and MUST call Cargo or xtask.118 + - Credentials, mutable automation state, and provider output MUST NOT enter the repository.153 - ### 3.4 Unsafe Code — Forbidden by Default 120 + ## 10. Generated State 157 - #![forbid(unsafe_code)]160 - **Exception:** `smith-cli` binary crate may use `unsafe` for OS-specific terminal manipulation **only** when:161 - 1. No safe alternative exists in the ecosystem162 - 2. Wrapped in a safe abstraction with `// SAFETY:` comment163 - 3. The safe wrapper is unit-tested independently164 - 4. Approved in PROJECT-INVARIANTS with documented rationale166 - **Clippy enforcement:**168 - - D clippy::undocumented_unsafe_blocks171 - Every `unsafe` block must have a `// SAFETY:` comment explaining:172 - - What invariant makes this safe173 - - Why no safe alternative exists174 - - What could go wrong if the invariant is violated176 - ### 3.5 unwrap, expect, panic — Prohibited in Libraries 180 - - D clippy::unwrap_used181 - - D clippy::expect_used185 - | Context | `unwrap()` | `expect()` | `panic!()` |186 - |---------|-----------|-----------|-----------|187 - | Library code (`smith/`, `smith-core/`, etc.) | **Prohibited** — use `?` or `match` | **Allowed only** with message explaining guaranteed invariant | **Prohibited** — use `Result` |188 - | Test code | **Allowed** | **Allowed** | **Allowed** |189 - | `smith-cli` / `xtask` | **Allowed** with justification comment | **Allowed** with justification comment | **Allowed** with justification comment |191 - **Rationale:** In a TUI, a panic corrupts terminal state (raw mode, alternate screen). Never acceptable in library code.193 - ### 3.6 Documentation — Required and Enforced 196 - cargo doc --workspace --no-deps199 - **Doc lints (in `[workspace.lints]`, §3.2):**202 - - D rustdoc::missing_crate_level_docs203 - - D rustdoc::broken_intra_doc_links204 - - W rustdoc::invalid_html_tags205 - - W rustdoc::bare_urls208 - **Standard:** Every public item must answer:209 - - **What** does this do? (one-line summary)210 - - **Why** would I use it? (context/purpose)211 - - **How** do I use it? (example for complex types)212 - - **When** does it panic/error? (invariants, error conditions)214 - **All library crates:** `#![warn(missing_docs)]` in `lib.rs`.216 - ### 3.7 Dependency Audit 221 - - Duplicate versions of the same crate (without explicit exception)222 - - Unmaintained crates (`cargo-deny` advisory-db)223 - - Crates with incompatible licenses225 - ## 4. xtask Responsibilities 227 - xtask is the single extension point for tasks cargo does not handle natively.229 - ### Required Commands 231 - | Command | Purpose | Frequency |232 - |---------|---------|-----------|233 - | `cargo run -p xtask -- check` | Full CI check: fmt, clippy, arch, pup, test, doc | CI |234 - | `cargo run -p xtask -- test` | Run all tests (delegates to `cargo nextest run`) | Every commit |235 - | `cargo run -p xtask -- lint` | Clippy + rustfmt check | Every commit |236 - | `cargo run -p xtask -- fmt` | Auto-format (delegates to `cargo fmt`) | On demand |237 - | `cargo run -p xtask -- fetch-providers` | Fetch models.dev + catwalk → `providers.json` | On demand |238 - | `cargo run -p xtask -- doc-test` | Extract + run Lua code blocks from docs | CI |239 - | `cargo run -p xtask -- verify-docs` | Completeness checks (every API documented) | CI |240 - | `cargo run -p xtask -- doc-gen` | Generate man pages + docs bundle | Release |241 - | `cargo run -p xtask -- spec-verify` | Verify spec cross-references, check for stale links | CI |242 - | `cargo run -p xtask -- arch` | Stable architecture checks: dependency graph, forbidden imports, module hygiene | CI |243 - | `cargo run -p xtask -- pup` | Required cargo-pup architecture gate on pinned nightly | CI |244 - | `cargo run -p xtask -- audit` | `cargo deny check` + security audit | CI |245 - | `cargo run -p xtask -- bench` | Run criterion benchmarks | Nightly |246 - | `cargo run -p xtask -- coverage` | Generate coverage report (tarpaulin) | CI |247 - | `cargo run -p xtask -- mutants` | Run mutation testing (cargo-mutants) | Nightly |248 - | `cargo run -p xtask -- release` | Build release binary for all targets, archive + checksum | Release |250 - ### Cross-compilation 252 - SPEC §14 states what a release must guarantee — one host, MSVC-ABI on Windows, a253 - glibc floor below the build host, no target silently dropped. This is the encoding254 - that currently satisfies it:256 - This table is the **single** encoding of how each target is built; §8a points257 - here rather than restating it.259 - | Target family | Cross-compiler | Proven by |261 - | Linux (glibc, musl) | `cargo-zigbuild` — supports a minimum-glibc suffix on the target triple | unproven |262 - | macOS | `cargo-zigbuild` — needs a macOS SDK only where a C dependency pulls darwin headers | unproven |263 - | Windows (MSVC) | `cargo-xwin` — fetches Microsoft's CRT and Windows SDK; **using it accepts Microsoft's licence**, an owner-approved condition of shipping Windows artifacts | **unproven** — SPEC §18 prototype required before the matrix relies on it |264 - | Android (Bionic) | **unproven** — outside both tools' stated support; SPEC §18 prototype decides before the matrix claims it | — |265 - | FreeBSD, OpenBSD, riscv64 (best-effort) | **unproven** — same; best-effort targets may be skipped, but the skip is reported | — |267 - `cargo-zigbuild` supports Linux and macOS only, which is why Windows needs the268 - second tool rather than a GNU-ABI substitute — SPEC §14 forbids that substitution269 - outright, so "cheaper to produce" is not an argument available here.271 - Both cross-compilers need something the host must already have: `zig` for one,272 - an LLVM/clang installation for the other (`cargo-xwin` fetches Microsoft's SDK273 - but not the compiler that consumes it). §1 names both as exceptions.275 - The **Proven by** column is load-bearing, not commentary: SPEC §14 forbids the276 - matrix claiming a target whose cross-build no prototype has exercised. Windows277 - MSVC is listed here as the intended encoding and marked unproven — the release278 - matrix may not depend on `cargo-xwin` until a §18 prototype builds with it.279 - This table is an implementation choice and may change with the ecosystem; the280 - guarantees in SPEC §14 may not.282 - ### xtask Implementation Rule 283 - xtask commands must be thin orchestrators. They delegate to cargo, nextest, clippy, etc. No heavy logic in xtask. No business logic. Just task coordination.285 - ## 5. Agent Boundary Contract 287 - Files that coding agents MUST NOT modify without explicit user approval:288 - - `docs/PROJECT-INVARIANTS.md`289 - - `docs/SPEC.md` (source of truth — agents read, don't edit without approval)290 - - `.claude/settings.json`291 - - `Cargo.toml` workspace root292 - - adding or removing a crate in any `Cargo.toml` `[dependencies]` (version293 - bumps are maintenance — see the dependency rule below)294 - - `.cargo/config.toml`295 - - `rust-toolchain.toml`297 - **Adding a dependency is a spec decision; bumping one is maintenance.** A new298 - third-party crate — or removing one — changes the architecture, crate set,299 - compile budget, and siloing, so a worker agent escalates to the spec owner and300 - never introduces a crate on its own initiative. The canonical set is SPEC §2.3301 - and the change follows the spec-approval path. A **version bump** of an302 - already-approved crate is routine upkeep, not a spec decision: it may be done303 - by a dedicated dependency-maintenance agent or automation, provided it passes304 - every gate — build, tests, clippy, `cargo deny`, and the §13.1 compile-budget305 - regression gate. A bump that is semver-incompatible, raises the toolchain MSRV,306 - or trips the compile-budget gate escalates like a new dependency, because it307 - can change behavior or cost. Prototypes under `prototypes/` are exempt from all308 - of this (SPEC §18): adding a crate to validate it before production is their309 - job, and that evidence is what gets escalated.311 - Files that coding agents MAY modify freely:312 - - `*/src/*.rs` (implementation)313 - - `*/tests/*.rs` (tests)314 - - `xtask/src/*.rs` (xtask commands)315 - - `benches/*.rs` (benchmarks)317 - Files that coding agents SHOULD read before modifying:318 - - `docs/SPEC.md` (the canonical spec)319 - - `CLAUDE.md` (project overview)321 - ### Integrity rules (absolute) 323 - Binding on every agent, tool, and automation, with no gated exception — these324 - protect the meaning of a green build:325 - - never modify CI configuration to make a failing run pass,326 - - never modify, delete, or skip a test to get green,327 - - never merge on a red or bypassed gate.329 - ## 6. Spec-Code Relationship 331 - 1. **Spec before code.** No `.rs` changes without corresponding `docs/SPEC.md` coverage (or documented exception).332 - 2. **The spec lives at `docs/SPEC.md`.** Code lives in crate directories.333 - 3. **Cross-references are unidirectional:** the spec may reference code paths; code does NOT reference the spec.334 - 4. **Spec changes require `cargo run -p xtask -- spec-verify` once xtask exists.**336 - ## 7. Version Control 338 - - **VCS:** the repository is **git**, hosted at339 - `git@vcs.bugabinga.net:smith.git`. `jj` (Jujutsu) is git-compatible and may be340 - used locally, but git is canonical and load-bearing.341 - - **History is linear.** Integrate by signed fast-forward; never create merge342 - commits or force-push.343 - - **Commits on `trunk` are signed.** Every commit that lands on `trunk` carries a344 - valid owner or agent signature.345 - - **Commit messages:** plain imperative subject naming the decision or its346 - effect; no required type prefix; argue *why*, not *what*; no AI attribution.347 - - **Branch naming:** `feature/description` or `fix/description`; delete topic348 - branches after integration.350 - ## 8. Performance Invariants 352 - - **Binary size:** Release binary < 20MB (stripped).353 - - **Startup time:** `smith --help` < 100ms.354 - - **TUI frame time:** `terminal.draw()` < 2ms (16ms budget for 60fps).355 - - **Session encode:** 1000 entries < 5ms.356 - - **Agent loop turn:** LLM call + tool execution < 30s (with timeout).358 - Benchmarks tracked with criterion. Baselines stored in `target/criterion/`. Regressions > 10% fail CI.360 - ## 8a. Release Artifact Invariants 364 - | Platform | Triple | Rust Tier | Status |365 - |----------|--------|-----------|--------|366 - | Windows x86_64 | `x86_64-pc-windows-msvc` | Tier 1 | Required |367 - | Windows ARM64 | `aarch64-pc-windows-msvc` | Tier 1 | Required |368 - | macOS Intel | `x86_64-apple-darwin` | Tier 2 | Required |369 - | macOS Apple Silicon | `aarch64-apple-darwin` | Tier 1 | Required |370 - | Linux x86_64 (glibc) | `x86_64-unknown-linux-gnu` | Tier 1 | Required |371 - | Linux ARM64 (glibc) | `aarch64-unknown-linux-gnu` | Tier 1 | Required |372 - | Linux x86_64 (musl) | `x86_64-unknown-linux-musl` | Tier 2 | Required (static) |373 - | Linux ARM64 (musl) | `aarch64-unknown-linux-musl` | Tier 2 | Required (static) |374 - | Android ARM64 (Bionic) | `aarch64-linux-android` | Tier 2 | Required |375 - | Linux riscv64 (glibc) | `riscv64gc-unknown-linux-gnu` | Tier 2 | Best-effort |376 - | Linux riscv64 (musl) | `riscv64gc-unknown-linux-musl` | Tier 2 | Best-effort |377 - | FreeBSD x86_64 | `x86_64-unknown-freebsd` | Tier 2 | Best-effort |378 - | OpenBSD x86_64 | `x86_64-unknown-openbsd` | Tier 3 | Best-effort |380 - **Android is a shipping platform, not only a development one** (owner decision,381 - 2026-07-25). Android/Termux on `aarch64-linux-android` is both the environment smith382 - is developed in *and* a required release artifact: a terminal-first coding agent is383 - used on a phone, not merely built for one. It is a third libc — **Bionic**, beside384 - glibc and musl — which is why it gets its own row rather than a Linux variant.385 - Bionic does not carry the compiler-rt builtins Rust expects, so vendored LuaJIT386 - fails to link `__clear_cache` unless they are linked explicitly; that flag lives in387 - `.cargo/config.toml` and is normative for this target, not a local workaround. This388 - table and `docs/SPEC.md` §14 must agree — a target listed in one and absent from the393 - Each release produces:394 - - `smith-{triple}-v{version}.{ext}` — platform-specific archive (zip for Windows, tar.gz for Unix)395 - - `checksums-sha256.txt` — SHA256 checksums of all archives397 - Nothing else. No install scripts, no package manifests, no distribution metadata.410 - No debug info in release builds. Debug symbols are produced only by the default (dev) profile.414 - 1. `cargo run -p xtask -- release` — builds every target, creates archives,415 - generates checksums. Which cross-compiler each target family uses is the §4416 - *Cross-compilation* table, not restated here: no single tool builds them all,417 - and saying otherwise is what sent the release pipeline at `cargo-zigbuild` for418 - Windows, which it does not support.419 - 2. Best-effort targets — riscv64, FreeBSD, OpenBSD — build natively where420 - possible and are skipped otherwise. A skip is reported, never silent421 - (SPEC §14); a *required* target that fails stops the release.423 - No automated distribution or code signing exists yet; these remain deferred.425 - See `docs/research/RELEASE-BUILD-RESEARCH.md` for cross-platform build tooling analysis.427 - ## 9. Testing Invariants 429 - See `docs/SPEC.md` for comprehensive testing strategy. Invariants here:431 - - **100% unit coverage** for `smith/` (pure types, no I/O).432 - - **≥ 95% coverage** for `smith-core/`.433 - - **≥ 90% coverage** for `smith-ai/`.434 - - **≥ 85% coverage** for `smith-tui/` (widget rendering via TestBackend).435 - - **≥ 90% coverage** for `smith-harness/`.436 - - **≥ 80% coverage** for `smith-cli/`.437 - - **Mutation score > 80%** caught by tests (nightly gate).438 - - **All benchmarks pass** without regression > 10% (nightly gate).439 - - **Architecture gates pass:** `cargo run -p xtask -- arch` and `cargo run -p xtask -- pup`.441 - ## 10. Cargo Workspace Structure 459 - license = "Apache-2.0"462 - - `smith/`: Foundation crate — shared types, config, errors, Lua runtime.463 - - `smith-core/`: Agent loop, session management, tool registry, compaction.464 - - `smith-ai/`: Provider implementations, model registry, auth, streaming.465 - - `smith-tui/`: Terminal UI — widgets, layout, theme, event handling.466 - - `smith-harness/`: Plugin system, SDK, event bridge, commands.467 - - `smith-cli/`: Binary entry point, argument parsing, session CLI.468 - - `xtask/`: Build automation, task orchestration.471 - ## 11. Architecture Invariants 473 - Allowed internal crate dependencies are fixed:475 - | Crate | May depend on |476 - |-------|---------------|478 - | `smith-core` | `smith` |479 - | `smith-ai` | `smith` |480 - | `smith-tui` | `smith` |481 - | `smith-harness` | `smith`, `smith-core`, `smith-ai`, `smith-tui` |482 - | `smith-cli` | `smith`, `smith-harness` |486 - - `smith` must never depend on any downstream crate.487 - - `smith-core`, `smith-ai`, and `smith-tui` must not depend on each other.488 - - `smith-cli` must not depend directly on `smith-core`, `smith-ai`, or `smith-tui`.489 - - `mod.rs` files contain only module declarations and re-exports.490 - - Wildcard imports are forbidden outside tests.492 - **Dependency siloing (incremental-build invariant).** Heavy or fast-moving493 - third-party crates attach at the leaf crate that owns the concern —494 - `reqwest`/`tokio` in `smith-ai`, `syntastica`/`ratatui` in `smith-tui`,495 - `jj-lib`/`gix` behind `smith-core`/`smith-harness` — and MUST NOT propagate up496 - into `smith`. The foundation crate is depended on by every other crate, so any497 - churn or heavy dependency there invalidates the whole workspace's incremental498 - cache; keeping it minimal is what lets an edit to one leaf crate rebuild499 - without touching the others' compiled artifacts. `smith` carries only small,500 - stable, universally-shared code (its one heavy dependency, `mlua`, is a locked501 - exception because the SDK type surface needs it).504 - - `cargo run -p xtask -- arch` verifies stable Rust metadata/source invariants.505 - - `cargo run -p xtask -- pup` runs `cargo +nightly-2026-01-22 pup`.506 - - `cargo run -p xtask -- check` includes both gates.508 - ### Nightly Toolchain Exception 510 - Smith production code uses stable Rust.512 - Exception: `cargo-pup` architecture linting runs on pinned nightly513 - `nightly-2026-01-22` because it uses rustc internals.516 - - Nightly may be used only by the pup gate.517 - - Stable remains required for build, test, run, and release.518 - - Nightly breakage is fixed by updating pup/toolchain config, not by moving smith production code to nightly.519 - - Pup failure blocks commit, PR, and release.523 - | Date | Change | Author |524 - |------|--------|--------|525 - | 2026-07-25 | §4 becomes the single cross-compiler mapping, with a proven-by column; §1 exception widened to the host LLVM `cargo-xwin` needs and repointed at §4; §8a release pipeline stops naming one tool for every target (user-approved) | smith-spec |526 - | 2026-07-19 | §7 switch rebase→squash merge: rebase-merge can't be signed, so squash is the only method that satisfies signed-commits + linear history; one-PR-one-decision keeps squash = one-commit-per-decision (user-directed) | smith-spec |527 - | 2026-07-18 | §1 scope note: Astro site exempt from the package.json ban, confined to `site/`; book stays mdBook (cargo-native) (user-directed) | smith-spec |528 - | 2026-07-16 | §7 drop Conventional Commits mandate; commit/PR style moves to CLAUDE.md; no AI attribution (user-approved) | smith-spec |529 - | 2026-07-16 | AGENTS.md files renamed to CLAUDE.md repo-wide; references updated (user-directed) | smith-spec |530 - | 2026-07-15 | §8a CI wording scoped to release automation; §4 fetch-providers source models.dev; §1 zig/cargo-zigbuild exception (user-approved) | smith-spec |531 - | 2026-07-15 | §2 tree: design/ absorbed into SPEC.md and deleted; prototypes/ added (user-approved) | smith-spec |532 - | 2026-05-23 | Add architecture gates and pinned-nightly pup exception | smith-spec |533 - | 2026-05-22 | Initial invariants | smith-spec |122 + Generated files, build outputs, scratch workspaces, credentials, captures, and local caches MUST remain ignored and untracked. Repository history MUST contain source, contracts, retained research, and deliberate fixtures only.+1229 / −2340 text lines
1 + # Smith Product Specification 3 - Smith is a Rust coding-agent TUI. This document describes the desired project4 - state. It is the canonical specification for architecture, crates, interfaces,5 - configuration, plugins, CLI behavior, build gates, and testing.3 + This file is the sole canonical product contract. Normative terms **MUST**, **MUST NOT**, **SHOULD**, and **MAY** define product requirements. Unless a declaration is explicitly described as shape-level, names, values, paths, formats, signatures, and observable behavior in this document are exact contracts.9 - Smith is a fast, extensible AI coding agent with:11 - - interactive terminal UI,12 - - non-interactive eval mode,13 - - JSON-RPC stdio mode,15 - - provider-independent agent loop,16 - - deterministic session storage and replay,17 - - built-in coding tools implemented through the same plugin API as user tools.9 + Smith MUST be a fast, extensible AI coding agent with:19 - Core design principles:11 + - an interactive terminal UI;12 + - non-interactive evaluation;13 + - JSON-RPC 2.0 over standard input/output;14 + - a Lua plugin system;15 + - a provider-independent agent loop;16 + - deterministic session storage and replay; and17 + - built-in coding tools implemented through the same Lua plugin API as user tools.21 - - **Spec before code.** No production Rust exists without a matching spec.22 - - **Cargo only.** No Makefile, justfile, package scripts, or root shell scripts.23 - - **Stable Rust for product code.** Pinned nightly is allowed only for the24 - required cargo-pup architecture gate.25 - - **Deep modules.** Public interfaces are small, honest, and typed.26 - - **Sinks, not pipes.** Cross-crate behavior flows through explicit typed27 - requests, streams, events, or hooks. No hidden downstream cascades.28 - - **Everything user-visible is a plugin.** Tools, slash commands, themes,29 - keybindings, prompts, layouts, and feature UI are Lua plugins.30 - - **LLM is the only untrusted actor.** Local user, local plugins, local files,31 - and Smith itself are trusted.32 - - **Pi is Smith's philosophical ancestor, not a dependency.** Smith improves33 - on pi's ideas with no data or format coupling to it.34 - - **Exact at boundaries, shapes inside.** This spec is exact where others35 - program against it — files, wire formats, CLI, config, Lua SDK — and36 - shape-level (named types, behavior, properties) for internal Rust. Code37 - blocks are illustrative unless a section says otherwise.19 + Cross-crate behavior MUST use explicit typed requests, streams, events, intents, or hooks. Hidden downstream cascades are forbidden. Public interfaces MUST remain small, typed, and honest.21 + Every user-visible tool, slash command, theme, keybinding, prompt, layout, and feature UI MUST be supplied as a Lua plugin. Binary commands provide process lifecycle and transport entrypoints only. Built-in and user plugins MUST receive the same SDK.41 - The product, as a user meets it. Each scene pins observable behavior; the42 - cited sections own the contracts. Three features that must never blur:43 - **tree navigation** moves through the conversation tree (§6.5, files44 - untouched), **time travel** moves workspace file state through the VCS45 - operation timeline (§9.13), and **replay** re-executes a recorded trace46 - (§6.11, never the live session).23 + Smith MUST NOT depend on Pi or couple to Pi APIs, data, or formats.48 - **First run.** `smith` in a project directory. No config exists; defaults49 - apply (§5.6). Capabilities probe once, fail-conservative (§8.3). The default50 - layout plugin renders status bar (model, context %, cost), message history,51 - input, hint bar — all border panels closed; panels are strictly opt-in52 - (§8.7). The empty history shows a few dim hint lines (active model, how to53 - begin, `smith help`) that vanish at the first entry. No wizard, no54 - onboarding. Startup under 100ms (§13).25 + Files, wire formats, CLI behavior, configuration, and Lua SDK boundaries are exact. Internal Rust declarations are shape-level contracts unless this specification explicitly makes a symbol or representation exact.56 - **First message, no auth.** The user types; auth resolution fails fast57 - before the first stream (§7.4). The error is the guidance: a recoverable58 - error (§5.8) renders in history naming the missing credential, the env var59 - to set, and `/auth login <provider>` for OAuth (§9.11); the message stays in60 - the input for immediate resend. The failure teaches; no setup flow exists.62 - **First task.** Text streams as it arrives. Tool calls render as collapsed63 - one-liners that expand on selection (§8.10); cost and context tick live in64 - the status bar. `!cargo test` runs directly and lands as a bash-execution65 - entry (§6.5). Every mutating tool records a VCS operation invisibly (§9.13)66 - — no commit prompts, no jj exposed.29 + Running `smith` in an unconfigured workspace MUST apply defaults without a wizard, onboarding flow, or setup prompt. Capabilities MUST be probed once and failures MUST be interpreted conservatively.68 - **Steering.** Mid-run, the user types a correction and enters — it queues as69 - a steer; a modifier queues a follow-up instead (§6.1). The queue renders70 - between history and input (§8.11). In-flight tools finish, never-started71 - calls skip, the steer lands, the model re-plans. Cancel keys pop the queue72 - newest-first; only an empty queue aborts.31 + The default Lua layout plugin MUST render:74 - **Tree navigation.** A refactor went sideways. `/tree` shows the session75 - tree; the user switches the leaf to the pre-refactor entry. The conversation76 - rewinds; files do not (§6.5). A new message from here is a new branch,33 + - a status bar showing the active model, context percentage, and accumulated cost;79 - **Time travel.** The files are still wrong. The time-travel timeline shows80 - the VCS operations recorded around each entry; the user inspects op diffs81 - and restores the workspace to the pre-refactor op (`/undo`, or restore from82 - the timeline). Tree navigation answers "where were we in the conversation";83 - time travel answers "what did the files look like." The timeline bridges84 - them by offering the restore for the op recorded at the current entry — but85 - they are separate axes.38 + All optional bordered panels MUST initially be closed and MUST be strictly opt-in. Empty history MUST show a few dim hints containing the active model, how to begin, and `smith help`; those hints MUST disappear after the first entry. Startup MUST make the interactive product ready in less than 100 ms.87 - **Model switching.** `ctrl+l` cycles a configured shortlist; `/model` opens88 - a fuzzy picker. Both operate on resolver names (§5.7) — aliases, groups,89 - buckets — as first-class vocabulary, with the picker showing what each name90 - resolves to. Raw provider/model IDs are the fallback, not the interface.40 + ### Missing authentication 92 - **Leaving and returning.** Quit restores the terminal (§10). `smith93 - continue` resumes the last session in cwd — same leaf (§6.5 replay rule),94 - queues empty (§6.1, process-ephemeral), accumulated cost in the status bar.95 - `smith attach` fuzzy-picks among sessions.42 + Authentication resolution MUST complete before the first provider stream. Failure MUST be fast, recoverable, and rendered in history. A missing-authentication diagnostic MUST name:97 - **Replay.** To understand yesterday's session: `smith replay <session>98 - --speed 2` re-plays it visually; `--compare` re-executes tools and diffs99 - current outputs against recorded ones (§6.11). Replay reads the trace and100 - never touches the live session.44 + - the missing credential;45 + - the environment variable to set; and46 + - `/auth login <provider>` when that provider offers OAuth.48 + The unsent message MUST remain in the input for immediate resend. Smith MUST NOT start a setup flow.107 - smith/ foundation crate: shared types, StreamFn, AgentTool, config, Lua runtime, errors108 - smith-core/ agent loop, sessions, tools, hooks, compaction, cost, trace, replay109 - smith-ai/ LLM providers, auth, model registry, provider streams, MuxProvider110 - smith-tui/ terminal events, widgets, layout primitives, render loop, themes111 - smith-harness/ orchestration, plugin system, SDK, event bridge, built-ins, help112 - smith-cli/ binary entry point, clap CLI, session commands, eval/rpc/replay113 - xtask/ Cargo-only automation52 + Assistant text and thinking UI MUST update incrementally as provider events arrive. Tool calls MUST initially render as collapsed one-line entries and MUST expand when selected. Cost and context usage MUST update live in the status bar.116 - ### 2.2 Allowed Internal Dependencies 54 + Input beginning with `!`, such as `!cargo test`, MUST execute directly and create a user-bash session entry. Session entries MUST also be capable of representing `!!` user-bash commands and their output.118 - | Crate | May depend on |119 - |-------|---------------|56 + Every successful mutating tool MUST invisibly record a VCS operation. Smith MUST NOT prompt for commits or expose the underlying VCS implementation.58 + ### Steering and follow-ups 60 + Submitting normal input during an active run MUST queue a steer. Submitting with the configured modifier MUST queue a follow-up. The combined queue MUST render between history and input.62 + A steer MUST let already-running tools finish, skip tool calls not yet started, insert the steering messages, and make the model re-plan. Cancel actions MUST remove queued items newest-first; a user cancel MUST abort only when the queue is empty. Queue contents are process-ephemeral and MUST be empty after session continuation.64 + ### Independent navigation axes 66 + Conversation navigation, workspace restoration, and replay MUST remain distinct:68 + 1. `/tree` MUST display the append-only session tree and permit switching the current leaf to an earlier entry. Switching MUST rewind conversation context without changing workspace files. Sending from a historical entry MUST silently create a sibling path in the same session.69 + 2. Workspace time travel MUST navigate the VCS operation timeline independently. The timeline MUST show operations associated with entries, inspect operation diffs, and restore an earlier operation. `/undo` and the timeline MUST restore the applicable earlier operation. The timeline MUST offer restoration of the operation recorded at the current conversation entry without coupling leaf movement to restoration.70 + 3. Replay MUST read a recorded trace and MUST never execute against or mutate the live session. Visual replay and compare execution are replay operations, not conversation or VCS navigation.72 + A plugin MAY offer a combined action that explicitly invokes both leaf switching and `smith.vcs.op_restore`, but the underlying axes MUST remain separately addressable.76 + `ctrl+l` MUST cycle a configured model shortlist. `/model` MUST open a fuzzy picker. Both MUST primarily expose resolver names—aliases, groups, and buckets—and the picker MUST show each name's resolved plan. Raw provider/model IDs MUST remain available only as a fallback interface.78 + ### Exit, continuation, attachment, and replay 80 + Quitting and every fatal path MUST restore the terminal.82 + `smith continue` MUST resume the latest session for the current working directory at the same current leaf, with empty process queues and accumulated cost still visible. `smith attach` without an identifier MUST fuzzy-pick among sessions.84 + `smith replay <session> --speed 2` MUST visually replay the selected trace at twice recorded speed. `--compare` MUST re-execute tools in a replay execution context and diff new outputs against recorded outputs. Replay MUST not write to the source session or invoke tools against its live agent state.90 + | Crate | Required responsibility |92 + | `smith` | Foundation types, `StreamFn`, `AgentTool`, configuration, Lua runtime, and shared errors; no business logic. |93 + | `smith-core` | Agent loop, sessions, tools, hooks, compaction, cost, traces, and replay. |94 + | `smith-ai` | Providers, authentication, model registry, provider streams, and `MuxProvider`. |95 + | `smith-tui` | Terminal events, widgets, layout primitives, render loop, and themes. |96 + | `smith-harness` | Orchestration, plugin system, SDK, event bridge, built-ins, and help. |97 + | `smith-cli` | Executable entrypoint, CLI, session commands, eval, RPC, and replay dispatch. |99 + ### Internal dependency graph 101 + | Crate | MAY depend on |103 + | `smith` | no internal crate |121 104 | `smith-core` | `smith` || `smith-core` | `smith` |122 105 | `smith-ai` | `smith` || `smith-ai` | `smith` |123 106 | `smith-tui` | `smith` || `smith-tui` | `smith` |124 107 | `smith-harness` | `smith`, `smith-core`, `smith-ai`, `smith-tui` || `smith-harness` | `smith`, `smith-core`, `smith-ai`, `smith-tui` |125 108 | `smith-cli` | `smith`, `smith-harness` || `smith-cli` | `smith`, `smith-harness` |130 - - `smith` depending on any downstream crate.131 - - `smith-core`, `smith-ai`, and `smith-tui` depending on each other.132 - - `smith-cli` depending directly on `smith-core`, `smith-ai`, or `smith-tui`.133 - - Wildcard imports outside tests.134 - - `mod.rs` containing anything except module declarations and re-exports.135 - - Public API leaking from implementation modules unless explicitly listed here.112 + - `smith` MUST NOT depend on a downstream crate.113 + - `smith-core`, `smith-ai`, and `smith-tui` MUST NOT depend on one another.114 + - `smith-cli` MUST NOT depend directly on `smith-core`, `smith-ai`, or `smith-tui`.115 + - `smith` MUST NOT re-export `smith-core` domain types; callers MUST import a domain type from its owning crate.116 + - `mod.rs` files MUST contain only module declarations and re-exports.117 + - Crate roots and dedicated public-API modules MAY declare public API.118 + - Other implementation-module items MUST remain crate-private unless an exception names the crate, implementation path, exact symbols, and reason. No such exceptions exist in version 1.137 - Implementation-module public API exceptions are declared only in this table. An138 - exception names the crate, the implementation-module path, the exact public139 - symbols allowed there, and the reason the symbol cannot live at the crate root or140 - in a dedicated public API module. An empty table means no exceptions.142 - | Crate | Implementation module | Allowed public symbols | Reason |122 + ### Product directories 124 + `config_dir`, `data_dir`, and `cache_dir` mean the final Smith-specific directories below. Callers MUST NOT append another `smith` component.126 + | Platform | `config_dir` | `data_dir` | `cache_dir` |143 127 |---|---|---|---||---|---|---|---|144 - | _none_ | _none_ | _none_ | _none_ |146 - Crate roots and dedicated public API modules may declare public API normally.147 - Every other public item under an implementation module must either be private to148 - its crate or appear in the exception table above.152 - - `cargo run -p xtask -- arch` checks stable Cargo metadata and source153 - invariants not covered by pup, including the implementation-module exception154 - table above: any public item in an implementation module that is absent from155 - the table fails the gate with crate, module path, and symbol name.156 - - `cargo run -p xtask -- pup` runs `cargo +nightly-2026-01-22 pup`.157 - - `cargo run -p xtask -- print-modules` prints crate roots from Cargo metadata158 - plus cargo-pup submodule output.159 - - `cargo run -p xtask -- check` includes `arch` and `pup`.161 - ### 2.3 Workspace Manifest 181 - license = "Apache-2.0"184 - Required shared dependencies:187 - mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }189 - serde = { version = "1", features = ["derive"] }191 - tokio = { version = "1", features = ["full"] }192 - clap = { version = "4", features = ["derive"] }204 - tracing-subscriber = { version = "0.3", features = ["env-filter"] }205 - reqwest = { version = "0.12", features = ["json", "stream"] }207 - unicode-width = "0.2"208 - unicode-segmentation = "1"209 - syntastica = { version = "0.6", default-features = false, features = ["runtime-c2rust"] }210 - syntastica-parsers = "0.6"211 - fuzzy-matcher = "0.3"216 - grep-searcher = "0.1"217 - gix = { version = "0.85", default-features = false, features = ["blame", "blob-diff", "revision", "sha1", "blocking-network-client", "worktree-mutation"] }224 - uuid = { version = "1", features = ["v7"] }229 - criterion = { version = "0.5", features = ["async_tokio"] }232 - zip = { version = "2", default-features = false, features = ["deflate"] }237 - This list is the canonical dependency registry. Adding or removing a crate here238 - is a spec decision (PROJECT-INVARIANTS §5): worker agents escalate to the spec239 - owner and never introduce a dependency on their own; a prototype under240 - `prototypes/` validates a candidate first, and its evidence is what the241 - decision rests on. Version bumps of an already-listed crate are maintenance,242 - not a spec decision — routine bumps ride the CI gates (build, tests,243 - `cargo deny`, the §13.1 compile budget), while a semver-breaking, MSRV-raising,244 - or budget-tripping bump escalates like a new dependency. Heavy dependencies245 - attach at the crate that owns the concern and never propagate up into `smith`246 - (PROJECT-INVARIANTS §11 dependency-siloing invariant), so a leaf-crate edit247 - never rebuilds an unrelated crate's dependency tree.249 - Two version constraints are load-bearing (prototype-decided, p25/p26): `gix`250 - is pinned to the version `jj-lib` pulls (0.85) so the two never compile a251 - duplicate gix tree, and `jj-lib` is pinned exact because it is pre-1.0 with a252 - roughly monthly, unstable API — the `smith.vcs.*` façade (§9.13) absorbs the253 - upgrade churn. `jj-lib`'s transitive `kstring` resolves to a version needing254 - rustc 1.96; until stable Rust reaches it, `Cargo.lock` pins `kstring = 2.0.2`.255 - This is a lockfile pin of a dependency, not a declaration of Smith's own MSRV,256 - so PROJECT-INVARIANTS §3.1 stands; it self-heals once stable ≥ 1.96.268 - [profile.release.package."*"]272 - ## 3. Toolchain, Lints, and Build Gates 274 - ### 3.1 Rust Toolchain 276 - `rust-toolchain.toml`:281 - components = ["rustfmt", "clippy"]284 - Smith follows latest stable Rust. Do not pin a numeric MSRV unless release285 - engineering creates a formal support window.289 - - `cargo-pup` uses pinned `nightly-2026-01-22` because it depends on rustc internals.290 - - Nightly is used only by the pup gate.291 - - Stable remains required for build, test, run, and release.292 - - Nightly breakage is fixed by updating pup/toolchain config, not by moving293 - product code to nightly.294 - - Pup failure blocks commit, PR, and release.298 - **Zero warnings.** A warning is an error; nothing merges or releases with one299 - (PROJECT-INVARIANTS §3).301 - Denied for every workspace crate: the `clippy` **all / pedantic / suspicious /302 - complexity / perf / style / correctness** groups; the restriction lints303 - **`unwrap_used`, `expect_used`, `panic`, `todo`, `unimplemented`,304 - `print_stdout`, `print_stderr`**; and the documentation lints **`missing_docs`,305 - `rustdoc::missing_crate_level_docs`, `rustdoc::broken_intra_doc_links`**.306 - Warned, not denied: `clippy::nursery`, `rustdoc::invalid_html_tags`,307 - `rustdoc::bare_urls`. Escape hatches follow §3.3.309 - **Enforcement is uniform across targets.** The wall applies identically to every310 - target in the §14 matrix; no per-target build configuration may weaken it. This is311 - a requirement, not a preference — the obvious encoding (global compiler flags) has312 - the property that a target needing any flag of its own silently loses every lint,313 - and a required release target needs exactly that. Whatever mechanism carries the314 - wall must therefore be immune to per-target override, and must not impose smith's315 - denials on third-party dependencies. `PROJECT-INVARIANTS` §3.2 records the316 - encoding that satisfies this.318 - Every library crate has:321 - #![forbid(unsafe_code)]322 - #![warn(missing_docs)]325 - `smith-cli` may use unsafe only for OS terminal manipulation when no safe326 - alternative exists, wrapped in a tested safe abstraction with `// SAFETY:`.328 - ### 3.3 Clippy Policy 331 - - No `unwrap`, `expect`, `panic`, `todo`, `unimplemented` in shipped library code.332 - - Tests may use `unwrap`, `expect`, and `panic`.333 - - `smith-cli` and `xtask` may use them only with a justification comment.334 - - Prefer `#[expect(lint, reason = "...")]` over `#[allow]`.339 - cognitive-complexity-threshold = 25344 - `cargo run -p xtask -- audit` runs:348 - cargo audit --deny warnings351 - `deny.toml` allows Apache-2.0, MIT, and Unicode-DFS-2016. Duplicate versions are352 - warned unless explicitly accepted.356 - Root `pup.ron` exists and is required. Cargo-pup is the pinned-nightly source357 - architecture lint gate. `xtask arch` remains the stable Cargo metadata gate.359 - Initial pup rules enforce:362 - - no wildcard imports,363 - - `smith-core` imports no `smith-ai`, `smith-tui`, `smith-harness`, `smith-cli`,364 - - `smith-ai` imports no `smith-core`, `smith-tui`, `smith-harness`, `smith-cli`,365 - - `smith-tui` imports no `smith-core`, `smith-ai`, `smith-harness`, `smith-cli`.367 - Crate-boundary module match patterns must include the crate root. Use368 - `^crate($|::.*)`, not only `^crate::.*`. Cargo-pup sees root-owned items in369 - `lib.rs`/`main.rs` under the crate name itself.371 - Required boundary patterns:374 - matches: Module("^smith_core($|::.*)")375 - matches: Module("^smith_ai($|::.*)")376 - matches: Module("^smith_tui($|::.*)")379 - `cargo pup print-modules` is not a complete module inventory. It can omit crate380 - roots and can emit synthetic `unknown_crate` for crates with no child `mod`381 - items. Developer-facing module inventory uses `cargo run -p xtask -- print-modules`,382 - which prefixes crate roots from stable Cargo metadata and then prints383 - cargo-pup-discovered submodules.388 - rustup component add --toolchain nightly-2026-01-22 rust-src rustc-dev llvm-tools-preview389 - cargo +nightly-2026-01-22 install cargo_pup395 - cargo +nightly-2026-01-22 pup398 - ## 4. Runtime Directories and Files 400 - Smith uses XDG-style directories via `dirs`.402 - | Platform | Config | Data | Cache |403 - |----------|--------|------|-------|
404 128 | Linux | `~/.config/smith/` | `~/.local/share/smith/` | `~/.cache/smith/` || Linux | `~/.config/smith/` | `~/.local/share/smith/` | `~/.cache/smith/` |405 - | macOS | `~/Library/Application Support/smith/` | same | `~/Library/Caches/smith/` |129 + | macOS | `~/Library/Application Support/smith/` | ` ~/Library/Application Support/smith/ ` | `~/Library/Caches/smith/` |406 130 | Windows | `%APPDATA%\smith\` | `%LOCALAPPDATA%\smith\` | `%LOCALAPPDATA%\smith\cache\` || Windows | `%APPDATA%\smith\` | `%LOCALAPPDATA%\smith\` | `%LOCALAPPDATA%\smith\cache\` |132 + When platform paths coincide, their children MUST coexist in that directory. The required layout is:412 136 sessions/ sessions/413 137 {session-id}.session {session-id}.session414 138 {session-id}.trace {session-id}.trace418 144 {project-hash}/ {project-hash}/419 145 jj-state/ jj-state/424 150 config.lua config.lua425 151 auth.json auth.json428 - Session files are plaintext length-prefixed CBOR sequences. Trace files are429 - compressed deterministic replay logs. Secrets in sessions are plaintext after430 - local registration (§6.7, §11).154 + Workspace-local plugins MUST live at `.smith/plugins/<org>/<name>/`.432 - ## 5. Shared Crate: `smith` 156 + ### Persistent formats 434 - `smith` owns shared types and utilities. It has no business logic and no435 - downstream dependencies.158 + `{session-id}.session` MUST be an unencrypted sequence of length-prefixed CBOR records. Its canonical filename MUST be exactly `{session-id}.session`. The initial metadata record(s) MUST expose enough session-header information for metadata-only discovery without reading the complete body.437 - Exposed surface (names, not module layout):160 + `{session-id}.trace` MUST be a compressed deterministic replay log as specified under Core. Session and trace paths MUST be derived from the same `SessionId`.439 - - the shared types of §5.1–§5.3 (IDs, messages, provider types, tool types:440 - `AgentTool`, `AgentToolResult`, `AgentToolUpdate`, `ToolExecutionMode`),442 - - `LuaRuntime` (§5.5),444 - - the model-resolution types (§5.7): `ModelAlias`, `ModelGroup`,445 - `ProviderBucket`, `ModelResolver`, `ResolvedModel`, `ResolveError`,446 - - `SmithError` (§5.8).162 + Plaintext secrets MAY be persisted only in secret-registration session entries and `auth.json` under the local trust model. Other session content and every trace representation MUST obey the secret-proxy rules.448 - `smith` must not re-export `smith-core` types. Domain types are imported from451 - ### 5.1 IDs and Messages 166 + VCS state MUST live at `data_dir/vcs/{project-hash}/jj-state`. The only Smith-managed VCS state item placed in the workspace root MUST be a `.jj` symlink. In a colocated Git workspace, `git_target` MUST be rewritten to the absolute `.git` path. Plugins MUST see only the stable `smith.vcs.*` contract, never implementation-native objects.453 - Required shared types:455 - - `EntryId(String)` — UUID v7, time-sortable.456 - - `SessionId(String)`.457 - - `SecretId(String)`.170 + ### Required `smith` exports 172 + The `smith` crate MUST expose:174 + - IDs and message types;175 + - provider request, event, usage, error, and model-metadata types;176 + - `AgentTool`, `AgentToolResult`, `AgentToolUpdate`, `ToolExecutionMode`, `ToolDefinition`, and `ToolDefinitionSpec`;180 + - `ModelAlias`, `ModelGroup`, `ProviderBucket`, `ModelResolver`, `ResolvedModel`, and `ResolveError`; and183 + ### IDs, roles, content, and messages 185 + The required ID types are:187 + - `EntryId(String)`, containing a time-sortable UUID v7;188 + - `SessionId(String)`;189 + - `SecretId(String)`; and458 190 - `VcsOpId(String)`.- `VcsOpId(String)`.459 - - `Role`: `System`, `User`, `Assistant`, `Tool`.460 - - `ContentBlock` — the authoritative content representation:462 - - `Image { data, media_type }`,463 - - `ToolCall { id, name, arguments (JSON) }`,464 - - `ToolResult { id, result, is_error }`,465 - - `Thinking { content, provider_metadata? }` — `provider_metadata` is opaque466 - and preserved, never consumed by Smith; provider adapters attach it (e.g.467 - thinking signatures) and replay it on later requests (§7.2), so signed468 - thinking round-trips across turns.469 - - `Message { role, content: list of ContentBlock }`.
471 - Roles say who speaks; entry kinds say what happened. Tool results are472 - `Tool`-role messages carrying `ToolResult` blocks — there is no tool-result473 - role. Events like user bash executions are `SessionEntry` kinds (§6.5), not192 + `Role` MUST have exactly these variants:476 - ### 5.2 Provider Types 195 + System | User | Assistant | Tool478 - - `ProviderUsage` tracks input, output, cache read/write, and total tokens.479 - - `StopReason`: `EndTurn`, `ToolUse`, `OverMaxTokens`, `Aborted`, `StopSequence`, `Error`.480 - - `ThinkingLevel`: `Off`, `Minimal`, `Low`, `Medium`, `High`, `XHigh`.482 - - `TextDelta { text }`,483 - - `ThinkingDelta { text, provider_metadata? }` — `provider_metadata` is484 - opaque, optional, and attached by the provider adapter to the delta whose485 - thinking text it authenticates,486 - - `ToolCall { id, name, arguments }` — assembled and complete; partial487 - argument chunks are joined at the provider boundary (§7.2),488 - - `Done { usage, stop_reason }`,489 - - `Error(ProviderError)`.490 - - `ProviderError` kinds — the failover-relevant classification consumed by491 - `MuxProvider` (§7.5), each carrying a message: `RateLimit`, `AuthFailed`,492 - `Network`, `ServerError`, `InvalidRequest`, `ModelNotFound`, `Timeout`.493 - - `ProviderRequest` contains messages, system prompt, model/provider IDs, tool494 - definitions, thinking level, token limit, and stop sequences.198 + `ContentBlock` is the authoritative message-content representation and MUST support exactly these shapes:202 + Image { data, media_type }203 + ToolCall { id, name, arguments }204 + ToolResult { id, result, is_error }205 + Thinking { content, provider_metadata? }498 - - `ToolDefinitionSpec` is serializable metadata for LLM function calling and500 - - `ToolDefinition` is runtime definition used by providers and the agent loop.501 - - `AgentTool` is async and `Send + Sync`.502 - - `ToolExecutionMode`: sequential or parallel according to tool metadata.503 - - `AgentToolResult` returns content blocks, error flag, and optional updates.504 - - Tool updates are v1 completion metadata: `AgentToolUpdate` values are surfaced505 - in the final `AgentToolResult`, not streamed live while the tool runs.506 - - Tool arguments are JSON and validated with `jsonschema`.208 + `ToolCall.arguments` MUST be JSON. `provider_metadata` MUST be opaque: Smith MUST preserve, store, and replay it without interpretation or consumption. Provider adapters MUST attach metadata required for later turns, including signed-thinking signatures.210 + `Message` MUST contain `role` and a list of `ContentBlock` values named `content`. Roles identify speakers; session-entry kinds identify events. A tool result MUST be a `Tool`-role message containing `ToolResult`; a distinct tool-result role is forbidden. User bash execution and similar activity MUST be represented by session-entry kinds, not new roles.214 + `ProviderUsage` MUST track:224 + `StopReason` MUST have exactly:227 + EndTurn | ToolUse | OverMaxTokens | Aborted | StopSequence | Error230 + `ThinkingLevel` MUST have exactly:233 + Off | Minimal | Low | Medium | High | XHigh236 + `ProviderEvent` MUST support:240 + ThinkingDelta { text, provider_metadata? }241 + ToolCall { id, name, arguments }242 + Done { usage, stop_reason }246 + `ThinkingDelta.provider_metadata` is optional and opaque. An adapter MUST attach it to the delta whose thinking text it authenticates. A provider-boundary `ToolCall` MUST be complete; vendor-specific partial argument chunks MUST be joined before crossing this boundary.248 + `ProviderError` MUST classify failures with exactly these variants, each carrying a message:260 + `ProviderRequest` MUST contain:275 + `ToolDefinitionSpec` MUST be serializable metadata suitable for LLM function calling and plugin metadata. `ToolDefinition` MUST be the runtime definition consumed by providers and the agent loop.277 + `AgentTool` MUST be asynchronous, `Send`, and `Sync`. `ToolExecutionMode` MUST select sequential or parallel execution according to tool metadata.279 + `AgentToolResult` MUST contain content blocks, an error flag, and optional updates. `AgentToolUpdate` is version-1 completion metadata: updates MUST appear in the final `AgentToolResult` and MUST NOT stream live while a tool is running.281 + Tool arguments MUST be JSON and MUST be validated against the tool's JSON Schema before execution.510 285 `StreamFn` is the provider abstraction consumed by `smith-core`:`StreamFn` is the provider abstraction consumed by `smith-core`:512 - - input: `ProviderRequest`,513 - - output: async stream of `ProviderEvent`,514 - - no dependency on `smith-ai`.288 + ProviderRequest -> asynchronous stream of ProviderEvent516 - This permits `smith-core` and `smith-ai` to build independently.291 + It MUST have no dependency on `smith-ai`.518 - The agent loop assembles consecutive `ThinkingDelta` events into a519 - `ContentBlock::Thinking`. It concatenates `text` in arrival order and carries520 - forward every non-empty `provider_metadata` value into the assembled block. If a521 - provider emits more than one metadata value for one assembled thinking block,522 - the block stores them in arrival order inside the opaque metadata payload;523 - Smith still never interprets them. This is the only route by which signed524 - thinking metadata crosses the `StreamFn` boundary and becomes available for525 - provider replay (§7.2).293 + The agent loop MUST assemble consecutive `ThinkingDelta` events into one `ContentBlock::Thinking` by concatenating text in arrival order. Every non-empty metadata value MUST enter the assembled block. Multiple values MUST be stored in arrival order within its opaque metadata payload. Smith MUST NOT interpret those values. This assembly MUST be the sole route by which signed-thinking metadata crosses `StreamFn` into persisted content and later provider replay.295 + ### Restricted `LuaRuntime` 529 - `LuaRuntime` wraps mlua + LuaJIT + `mlua-pkg` custom require.297 + `LuaRuntime` MUST provide LuaJIT with custom `require` searchers. Only these standard libraries are permitted:531 - Allowed standard libraries:300 + string, table, math, coroutine, utf8, package538 - - `package` with custom searchers.303 + `package` MUST use only the host's custom searchers. The following globals MUST be removed:306 + io, os, debug, getfenv, setfenv309 + Host APIs MUST be obtained with:548 - Smith host APIs are exposed through `require("smith")`.312 + local smith = require("smith")550 - No bytecode cache. The cache's premise is disproved (p17): loading cached551 - bytecode saves ~285µs per 2000-line module over compiling source (LuaJIT552 - compiles fast; stripped bytecode is even larger than source), while cached553 - bytecode is the most dangerous input path possible — LuaJIT has no bytecode554 - verifier, and corrupted images segfault the VM (~20% of trials) or silently555 - execute wrong code (~12%).315 + Lua bytecode caching is forbidden. Every Lua source load, including manifests, configuration, plugin entry files, required modules, and content stored in a `.lua` file, MUST explicitly request text-only chunk mode. Binary chunks and binary auto-detection MUST be rejected.557 - Binary chunks are therefore forbidden entirely: **every Lua source load558 - specifies text-only chunk mode explicitly**. mlua's default mode accepts559 - binary chunks auto-detected inside `.lua` files (p17) — relying on the560 - default would let a plugin ship raw bytecode past the loader.319 + Lua MUST be the configuration language. Rust MUST define and validate schemas; Lua MUST supply values. Effective configuration MUST apply these layers from lowest to highest precedence:564 - Lua is the configuration language. Rust defines schemas; Lua supplies values.566 - Cascade order, later overrides earlier:568 - 1. Rust type defaults/ schema, 569 - 2. built-in Lua defaults, 570 - 3. plugin contributions, 571 - 4. user config at `config_dir/smith/ config.lua`, 321 + 1. Rust type defaults and schema; 322 + 2. built-in Lua defaults; 323 + 3. plugin contributions; 324 + 4. `config_dir/config.lua`; 572 325 5. CLI flags.5. CLI flags.574 - Invalid values are rejected with clear errors. Unknown keys warn in the575 - top-level schema context and fail in strict contexts (`models.*`,576 - `compaction.*` — anywhere a typo silently changes behavior).327 + Later layers MUST override earlier layers. Cross-layer merging MUST recursively merge leaf fields for table-valued keys. Scalars and lists are leaves and MUST replace prior values wholesale.578 - Cross-layer merge is leaf-field recursive for table-valued keys; scalars579 - AND lists are leaves that replace wholesale (prototype-proven, p16: under580 - layer-replace, a user overriding one keybinding wipes the builtin581 - `ctrl+c = abort` binding, and a plugin contributing one alias clobbers the582 - builtin alias map). Same rule family as §7.3's registry merge.329 + Invalid values MUST produce clear path-qualified errors. Unknown keys MUST warn in the top-level schema context. Unknown keys MUST fail in strict contexts, including every `models.*` and `compaction.*` context where a typo could silently change behavior.584 - The cascade is re-evaluated at runtime by host configuration reload (§9.19).331 + The full applicable cascade MUST be re-evaluated on runtime host-configuration reload. A valid configuration includes this shape:600 - ### 5.7 Models, Aliases, Groups, Buckets345 + ### Models, aliases, groups, and buckets602 - `ModelMetadata` includes:347 + `ModelMetadata` MUST include provider ID, model ID, context window, maximum output tokens, cost when known, and capabilities for thinking, vision, tool use, and streaming.604 - - provider/model IDs,608 - - capabilities: thinking, vision, tool use, streaming.610 - `ModelResolver` is pure. It resolves:349 + `ModelResolver` MUST resolve through this chain:613 - requested name → alias → group → bucket/account → provider/model metadata352 + requested name -> alias -> group -> bucket/account -> provider/model metadata616 - Rules (prototype-proven, p18):355 + Resolution MUST perform no I/O. `resolve` MUST be a pure function of validated configuration, requested name, and rotation cursors. Identical inputs and cursors MUST yield an identical ordered plan. `MuxProvider`, not the resolver, MUST own cursors and advance each rotation node by one step per provider request.618 - - no I/O during resolution. Purity and round-robin reconcile by exporting619 - rotation state: `resolve` is a pure function of (validated config,620 - requested name, rotation cursors); the cursors are owned and advanced by621 - `MuxProvider` (§7.5), one step per rotation node per provider request.622 - Same cursors → same plan, always,623 - - cycles detected at config load and reported with the full path624 - (`cycle detected at config load: a → b → a`); DAG diamonds do not626 - - load-time rejections: a name defined as more than one kind (alias AND627 - group, all kinds named in the error), empty groups, empty bucket account628 - lists, dangling references (referrer named), duplicate members within one629 - group list, and buckets whose target is not a concrete model. Unknown630 - requested name is the only resolve-time error,631 - - DAG-induced duplicate candidates (two paths reaching the same632 - provider/model/account) survive flattening; Mux deduplicates identical633 - candidates before attempting them,634 - - `ResolvedModel` carries metadata needed by `smith-core`.357 + Configuration loading and reload MUST validate the whole graph and MUST:359 + - detect a real cycle and report its complete path, for example `cycle detected at config load: a → b → a`;360 + - accept DAG diamonds without false cycle reports;361 + - reject a name defined as multiple kinds and name every conflicting kind;362 + - reject empty groups;363 + - reject buckets with empty account lists;364 + - reject dangling references and name the referrer;365 + - reject duplicate members within one group list; and366 + - reject a bucket target that is not a concrete model.638 - - `FailoverStrategy`: ordered or round-robin.639 - - `BucketStrategy`: account rotation policy; bucket accounts are individual640 - failover candidates under §7.5.641 - - Rate limits fail over immediately.642 - - Non-rate-limit transient errors retry before failover; the retry count is643 - the `providers.retry_count` config key, default `2`.368 + After successful validation, an unknown requested name MUST be the only resolution-time error.370 + Duplicate candidates reached through distinct DAG paths to the same provider/model/account MUST survive resolver flattening. `MuxProvider` MUST deduplicate identical candidates immediately before attempting them. `ResolvedModel` MUST carry all metadata required by `smith-core`.647 - `SmithError` is the shared error enum. It wraps the domain errors defined at648 - their subsystems: `ProviderError` (§5.2), auth (§7.4), tool errors including649 - the §9.12 codes, config validation (§5.6), Lua (§5.5), I/O, session/trace650 - codec (§6.6, §6.11), and model resolution (§5.7).372 + `FailoverStrategy` MUST support `ordered` and `round-robin`. `BucketStrategy` MUST define account rotation, and every account in a bucket MUST be an individual failover candidate. `providers.retry_count` MUST configure general retry count and default to `2`.652 - Recoverability is the load-bearing property of every error path:654 - - **Recoverable** (the default): the failure surfaces to the user and/or the655 - LLM as content — error tool results (§6.4), UI notifications, plugin656 - diagnostics (§9.17) — and the loop continues. Provider failures (§7.5),657 - tool errors, plugin faults and OOM (§9.14, §9.17), and rejected config658 - reloads (§9.19) are all recoverable.659 - - **Fatal**: the process cannot continue safely — unrecoverable terminal660 - state, invalid startup config, providers exhausted in non-interactive eval.661 - Fatal paths restore the terminal (§10) and exit nonzero with a diagnostic.376 + `SmithError` MUST wrap subsystem errors for:663 - Shipped library code never panics for external failures; internal impossible664 - states use debug assertions.380 + - tools, including defined tool error codes;381 + - configuration validation;384 + - session and trace codecs; and666 - ## 6. Core Crate: `smith-core` 387 + Recoverability MUST be the default. A recoverable failure MUST become user- or model-visible content—such as an error tool result, history diagnostic, UI notification, or plugin diagnostic—and MUST leave the process able to continue.668 - `smith-core` owns pure business logic: agent loop, sessions, tools, hooks,669 - secret proxy, compaction, cost, trace, and replay. It depends only on `smith`.389 + Provider failures where another operation remains possible, tool errors, plugin faults, plugin out-of-memory errors, and rejected configuration reloads MUST be recoverable. A failure MUST be fatal only when safe continuation is impossible, including unrecoverable terminal state, invalid startup configuration, or exhaustion of every provider during non-interactive eval. Fatal paths MUST restore the terminal, emit a diagnostic, and exit nonzero.671 - Responsibilities (names, not module layout): the agent loop (§6.1), agent and672 - engine events (§6.2–§6.3), hooks (§6.4), session model and format (§6.5–§6.6),673 - secret proxy (§6.7), system prompt (§6.8), compaction and cost (§6.9), tool674 - registry (§6.10), trace and replay (§6.11).391 + Shipped library code MUST NOT panic on external failures or plugin input. Impossible internal states MAY use debug assertions.680 - - receives an `AgentContext`, `AgentLoopConfig`, `StreamFn`, tool registry, and event sender,681 - - streams model responses,682 - - emits `AgentEvent`,683 - - executes tool calls,684 - - handles steering/follow-up messages,685 - - repeats until stop criteria.397 + The agent loop MUST accept an `AgentContext`, `AgentLoopConfig`, `StreamFn`, tool registry, and event sender. It MUST stream provider responses, emit `AgentEvent` values, execute tool calls, process steering and follow-ups, and continue until a stop criterion is met.687 - Steering and follow-up semantics:689 - - **Follow-up**: FIFO queue consulted when the run would otherwise end —690 - instead of `agent_end`, the loop dequeues the next follow-up as a fresh691 - user message and starts a new turn cycle.692 - - **Steering**: delivers at the next safe boundary — after the current693 - provider stream completes, or after in-flight tool execution finishes.694 - Never-started tool calls from the current assistant message resolve as695 - error-flagged synthetic results (`skipped: user steered`) so every call696 - has a result on the wire; the model re-plans with the steer visible. All697 - queued steers drain FIFO as user messages before the next provider call.698 - Prototype-proven boundary rules (p14):699 - - parallel execution (§5.3): **wait-for-all-in-flight** — once a steer is700 - queued, no new call starts; every already-started call runs to701 - completion; only never-started calls skip,702 - - steer arriving mid-stream: no call of that assistant message has703 - started, so ALL of them skip — none executes,704 - - transcript ordering: real results first (completion order in parallel705 - mode), then synthetics in original call order, then the drained steers,706 - - skipped calls emit `ToolExecutionStart`/`ToolExecutionEnd` with error707 - flag and reason, per the §6.4 blocked-call contract.708 - - Interactive input during an active run is a steer by default; a modifier709 - submits it as a follow-up (§8.11). Plugins override default user-message710 - behavior through the `input` hook (§9.8) and send programmatically via711 - `smith.send_message` (§9.10).712 - - Queues are ephemeral process state: queued messages become session entries713 - when delivered, never when queued — the session records only what the model714 - saw. Compaction (§6.9) neither consumes nor drops the queues.715 - - Cancel keys pop the queue before they abort: see §8.11. A delivered abort716 - (§12) ends the run; whatever remains queued stays queued and is surfaced by717 - the TUI for the user to send, edit, or discard. An abort can leave the718 - session tail with an assistant message whose tool calls have no results719 - (no next request exists to carry synthetics); request assembly after720 - resume must repair such a dangling tail by synthesizing aborted-results721 - for the unanswered calls (p14).401 + - an outer loop for turns and follow-up user messages; and402 + - an inner loop for provider streaming, tool calls, and steering.723 - The loop uses two nested loops:404 + `AgentLoopConfig` MUST support:725 - - outer loop: turns and follow-up messages,726 - - inner loop: provider streaming, tool calls, steering.406 + - `max_tool_calls_per_turn`, default `100`;407 + - `max_turns_per_user_message`, default `50`;408 + - sequential or parallel tool execution;409 + - `model_metadata` for context and cost calculations; and410 + - typed hook callbacks.412 + Every runtime state MUST be interruptible. Ctrl+C and programmatic abort MUST set an abort signal. Provider streaming and tool execution MUST observe it and terminate cleanly, subject only to the non-preemptible Lua rule under Concurrency.730 - - `max_tool_calls_per_turn` default `100`,731 - - `max_turns_per_user_message` default `50`,732 - - tool execution mode: sequential or parallel,733 - - `model_metadata` for context/cost,414 + ### Follow-up and steering semantics 416 + Follow-ups MUST be held FIFO. Immediately before a run would emit `AgentEnd`, the loop MUST inspect the follow-up queue. If one exists, it MUST dequeue it as a fresh user message and begin a new outer turn cycle instead of ending.738 - - Ctrl+C or programmatic abort sets an abort signal.739 - - Streaming and tool execution check it and bail cleanly.740 - - Every state is interruptible.418 + A steer MUST be delivered at the next safe boundary: after the current provider stream completes or after in-flight tools finish. Before the next provider request, all queued steers MUST drain FIFO as user messages.420 + Once a steer is queued during parallel tool execution, no additional call from that assistant message may start. Calls already started MUST finish. Calls never started MUST receive error-flagged synthetic tool results whose content is exactly `skipped: user steered`.744 - `AgentEvent` is source of truth for agent behavior:422 + A steer arriving during provider streaming MUST cause every tool call produced by that assistant message to skip; none may execute. Parallel transcript ordering MUST be:746 - - `AgentStart`, `AgentEnd`,747 - - `TurnStart`, `TurnEnd`,748 - - `MessageStart`, `MessageUpdate`, `MessageEnd`,749 - - `ToolExecutionStart`, `ToolExecutionUpdate`, `ToolExecutionEnd`,750 - - `TextDelta`, `ThinkingDelta`,424 + 1. real results in completion order;425 + 2. synthetic results in original tool-call order; then426 + 3. drained steering messages in FIFO order.753 - `AgentEvent::to_session_entry(timestamp)` returns a `SessionEntry` only for754 - conversation-relevant completed events.428 + Every skipped call MUST emit `ToolExecutionStart` and `ToolExecutionEnd`. The end event MUST carry the error flag and skip reason. Every tool call represented on a provider wire message MUST ultimately receive a result unless abort occurs before any subsequent request can carry synthetic results.756 - ### 6.3 Engine Events 430 + Interactive active-run input MUST default to steering; a modifier MUST select follow-up. Plugins MAY override default input behavior through the `input` hook and MAY send messages through `smith.send_message`.758 - `EngineEvent` wraps `AgentEvent` and adds harness-level events:432 + Both queues MUST remain process-ephemeral. An item MUST become a session entry only when delivered, so persisted sessions contain only messages seen by the model. Compaction MUST neither consume nor discard queued messages.761 - - steering/follow-up,763 - - provider/model changes,764 - - errors and shutdown.434 + A user cancel MUST pop queued items according to TUI queue rules before aborting. Programmatic abort MAY be delivered independently; after any delivered abort, undelivered queue items MUST remain available for sending, editing, or discarding. An aborted assistant tail MAY contain tool calls without results. Request assembly after resume MUST repair that tail by synthesizing aborted results for every unanswered call.766 - `EngineEvent` is consumed by `smith-harness` and `smith-tui`. It is the767 - frontend stream: every frontend (the built-in TUI in-process, §8; any RPC768 - client out-of-process, §10.4) consumes `EngineEvent` and submits intents back.769 - Some variants — TUI-internal UI state changes — are in-process-frontend-private770 - and are not exposed out-of-process.436 + ### Agent and engine events 438 + `AgentEvent` MUST be the source of truth for agent behavior and MUST include:774 - Core hook result types:443 + MessageStart, MessageUpdate, MessageEnd444 + ToolExecutionStart, ToolExecutionUpdate, ToolExecutionEnd445 + TextDelta, ThinkingDelta776 - - `BeforeToolCallResult`: allow, block, replace args, cancel.777 - - `AfterToolCallResult`: keep, replace result, retry, cancel.778 - - `ShouldStopAfterTurn`: stop or continue.779 - - `PrepareNextTurn`: mutate queued prompts/messages.780 - - `TransformContext`: mutate LLM context before provider request.449 + `AgentEvent::to_session_entry(timestamp)` MUST return a `SessionEntry` only for completed, conversation-relevant events. Streaming deltas and incomplete lifecycle events MUST NOT independently become transcript entries.782 - Blocked-call contract (prototype-proven, p07): a blocked tool call never783 - executes the tool, still emits `ToolExecutionStart` and `ToolExecutionEnd`784 - (with error flag and the block reason) so the UI can show it, and feeds the785 - block reason to the provider as an error tool result so the model can react.451 + `EngineEvent` MUST wrap `AgentEvent` and add events for session lifecycle, steering and follow-up handling, UI state changes, provider and model changes, errors, and shutdown. Every frontend MUST consume `EngineEvent` and submit typed intents. TUI-private panel, resize, selection, focus, and scrolling variants MAY remain private to the in-process frontend and MUST NOT be exposed out of process.787 - `smith-harness` translates Lua plugin event returns into these core hook results.789 - ### 6.5 Session Model 455 + The hook API MUST provide these exact result types and choices:457 + - `BeforeToolCallResult`: allow, block, replace arguments, or cancel;458 + - `AfterToolCallResult`: keep, replace result, retry, or cancel;459 + - `ShouldStopAfterTurn`: stop or continue;460 + - `PrepareNextTurn`: mutate queued prompts/messages; and461 + - `TransformContext`: mutate LLM context before a provider request.798 - - created/updated timestamps.463 + A blocked tool call MUST NOT execute. It MUST still emit `ToolExecutionStart` and `ToolExecutionEnd`; the end MUST carry an error flag and block reason. The provider MUST receive the reason as an error tool result. Lua event-return tables MUST be translated into these core types.800 - Sessions are branching trees. A branch is emergent, not stored: the path from801 - root to a leaf. `ctx.session.branch()` (§9.9) returns the current path.802 - "Immutable once created" means entries are append-only and never rewritten —803 - working from an older point creates a new child, never edits history. `/tree`804 - and history/time-travel features are Lua plugins over this core state.467 + `Session` MUST contain:808 - - **append**: adds an entry as a child of the current leaf; the leaf advances809 - to it. Appending while the leaf sits on a non-leaf entry creates a fork810 - point implicitly — there is no explicit branch operation.811 - - **switch leaf**: moves the current leaf to any entry, recorded by appending812 - a leaf-switch metadata entry. On load, the leaf is resolved by replaying813 - surviving entries in file order: an append moves the leaf to itself, a814 - leaf-switch moves it to its target — the last surviving entry decides815 - (prototype-proven, p12; the naive "last switch target" rule yields a stale816 - leaf once appends follow a switch). A leaf-switch whose target was lost to817 - §6.6 recovery is ignored on replay. Leaf state rides the append-only818 - recovery guarantees, and leaf history is replayable for free.819 - - **read path**: returns the root→leaf path. The LLM context is built from820 - the current path only (through compaction, §6.9); sibling branches are821 - invisible to the model.822 - - **fork**: clones entries up to a given entry into a new `SessionId` and823 - session file (the `session_before_fork` event, §9.8). Distinct from in-tree824 - branching, which stays in one file.826 - No branch deletion or pruning exists in v1. A session has a single writer:827 - one agent loop appends to it at a time.479 + A session MUST be an append-only branching tree with one writer at a time. Only one agent loop may append. A branch MUST be derived as the root-to-leaf path, never stored as a separate mutable object. `ctx.session.branch()` MUST return the current path. Existing entries MUST never be rewritten. Continuing from an older entry MUST append a new child and create an in-tree fork silently.829 - Recovery meets the tree (p12): a §6.6-skipped entry can be a parent or a830 - switch target. Orphaned subtrees (parent missing) are detached and reported —831 - unreachable from the root, never silently grafted; dangling leaf-switches are832 - ignored during leaf replay.834 - Leaf switches never touch the working tree. Filesystem time travel is plugin835 - policy, not core behavior: the time-travel plugin (§9.11) pairs leaf switches836 - with `smith.vcs.op_restore` using the `VcsOpId` stored in entries.837 - Conversation navigation alone is never destructive.483 + - An ordinary append MUST add a child of the current leaf and move the leaf to the new entry.484 + - An ordinary append while positioned on a non-leaf entry MUST create a fork implicitly.839 - `SessionEntry` variants include:486 + Leaf-switch behavior:845 - - system prompt snapshot,846 - - compaction summary,847 - - secret registration,848 - - model/provider change,850 - - user bash execution (`!`/`!!` commands and their output),851 - - leaf switch (tree navigation),852 - - metadata entries needed for migration and replay.488 + - A switch MUST target any surviving entry and MUST be recorded by appending leaf-switch metadata.489 + - Loading MUST resolve the current leaf by replaying surviving records in file order.490 + - During replay, an ordinary append MUST move the leaf to itself; a leaf-switch operation MUST move it to its target.491 + - The last surviving replayed operation MUST determine the leaf.492 + - A leaf switch whose target was lost during recovery MUST be ignored.493 + - Switching MUST NOT modify workspace files.854 - Every entry has a stable `EntryId`, optional parent, and timestamp. New entry855 - kinds are forward-compatible by construction: readers preserve unknown856 - variants (§6.6), so adding a kind never breaks older sessions or readers.495 + Path reads MUST return only root through current leaf. LLM context MUST use only that path after compaction folding; siblings MUST remain invisible.858 - ### 6.6 Session Format 497 + Session forking is distinct from in-tree branching. Forking MUST clone entries through a specified entry into a new `SessionId` and new session file and MUST emit `session_before_fork`. Version 1 MUST NOT support branch deletion or pruning.860 - Session files are length-prefixed CBOR sequences:499 + If recovery loses a parent, its subtree MUST remain detached, be reported as orphaned, remain unreachable from the root, and MUST NOT be grafted elsewhere. Conversation navigation alone MUST never alter files. Filesystem time travel remains plugin policy and MAY explicitly pair a switch with the entry's `VcsOpId` through `smith.vcs.op_restore`.501 + ### Session entries and codec 503 + Every `SessionEntry` MUST have a stable `EntryId`, optional parent, and timestamp. Supported variants MUST include:509 + - system-prompt snapshot;510 + - compaction summary;511 + - secret registration;512 + - model/provider change;514 + - user bash execution, including `!` and `!!` command and output;516 + - metadata required for migration and replay.518 + Readers MUST preserve a well-formed unknown entry variant as raw data so future variants survive rewrite or migration round trips.520 + The file framing is exact:863 523 u32 BE len | CBOR entry bytes | u32 BE len | CBOR entry bytes | ...u32 BE len | CBOR entry bytes | u32 BE len | CBOR entry bytes | ...866 - Properties (recovery boundaries prototype-proven, p06):526 + Recovery MUST obey these boundaries:868 - - truncated tail stops parsing; prior entries survive,869 - - a corrupt entry BODY is precisely skippable with a warning — the intact870 - length prefix bounds the damage,871 - - a corrupt LENGTH PREFIX desynchronizes framing: entries before it survive,872 - everything after is unrecoverable and indistinguishable from truncation,873 - - unknown-vs-corrupt is decided by two-stage decode (raw CBOR, then typed):874 - well-formed CBOR with an unknown variant tag is preserved raw and survives875 - rewrite roundtrips; invalid CBOR is corrupt and skipped,876 - - `smith session dump` outputs JSONL,877 - - session discovery is keyed by canonical `{session-id}.session` filenames.528 + - A truncated tail MUST stop parsing and preserve every prior record.529 + - A corrupt entry body with an intact length prefix MUST be skipped by exactly that length and MUST produce a warning.530 + - A corrupt length prefix desynchronizes framing; prior entries survive and the remainder is unrecoverable and MUST be treated as truncation.531 + - Decoding MUST occur in two stages: raw CBOR, then typed decoding.532 + - Well-formed CBOR with an unknown variant tag MUST remain raw and survive a rewrite round trip.533 + - Invalid CBOR MUST be classified as a corrupt body and skipped when its framing is intact.535 + `smith session dump` MUST emit JSONL. Session discovery MUST recognize only canonical `{session-id}.session` names.881 - The secret proxy prevents LLM exposure of registered secrets. Smith provides882 - the masking mechanics only; secret *detection* mechanisms are out of scope883 - for core and belong to plugins.885 - **Registry.** The proxy holds a table of `SecretId → plaintext + label`.539 + #### Registry and registration 888 - - automatic: every credential the auth resolver loads (§7.4) — provider keys889 - can never enter context, even via a tool reading a config file,890 - - automatic: values of a plugin's `declared secrets` (§9.2) when read through892 - - explicit: the built-in `/secret` command (§9.11),893 - - plugins: `smith.secret.register(value, label)` (§9.10). Detection plugins894 - (pattern-based or otherwise) inspect content through the §9.8 `input` /895 - `tool_result` hooks and register what they find; the mechanism is theirs,896 - the mechanics are Smith's.541 + The secret registry MUST map each `SecretId` to plaintext and a label. Core masking MUST operate only on registered secrets; discovery or heuristic detection MUST remain plugin-defined.898 - **Masking at ingestion.** Scanning is exact substring matching against899 - registered values — no heuristics in core. Content is masked to `smith:sec:N`900 - placeholders *before* it becomes a session entry. Plaintext exists in exactly901 - one entry kind: the secret-registration entry (preserved structurally by902 - compaction but masked in provider rendering, §6.9). The ingestion scan runs903 - after plugin `input`/`tool_result` hooks, so a value registered during those904 - hooks is masked in the very content that surfaced it. On resume, the table905 - rebuilds by scanning session entries backward for registration entries, and906 - the `SecretId` allocator resumes past the highest id seen — a reused id would907 - silently alias older placeholders (p13).543 + Registration paths are:909 - Masking and rehydration rules (prototype-proven, p13):545 + - automatically for every credential loaded by the auth resolver;546 + - automatically when a plugin reads one of its declared secrets through the SDK;547 + - explicitly through `/secret`; and548 + - programmatically through `smith.secret.register(value, label)`.911 - - masking is **longest-match-first** in a single left-to-right pass that912 - never rescans emitted placeholder text — any other order provably leaks913 - residue of an overlapping secret,914 - - rehydration is likewise single-pass; produced plaintext is never rescanned,915 - - registration rejects values matching the placeholder grammar916 - (`smith:sec:<digits>`) with a diagnostic — accepting them aliases917 - legitimate placeholders,918 - - re-registering identical plaintext is idempotent and returns the existing919 - id (detector hooks re-see the same token on every occurrence),920 - - placeholder ids parse as the maximal digit run (`smith:sec:12` is id 12,921 - never id 1 followed by `2`).550 + Detection plugins MAY inspect `input` and `tool_result` hook content and register values. Registration MUST:923 - **Rehydration.** Placeholders turn back into plaintext at exactly one layer:924 - immediately before tool execution (subprocess and tool `execute`, Rust and925 - Lua alike). Session content, provider requests, traces, and events carry926 - placeholders only. Replay with compare (§6.11) re-executes tools and927 - therefore rehydrates from the session's registration entries; trace files928 - themselves stay masked. A placeholder whose ID is not registered passes929 - through untouched — never rehydrated, never an error.552 + - reject a value matching `smith:sec:<digits>` and return a diagnostic;553 + - be idempotent by exact plaintext and return the existing `SecretId`; and554 + - after resume, allocate above the greatest ID found in the session.931 - **Display.** The TUI renders placeholders masked with their label932 - (`‹secret: github-token›`); display matches context content. The local user933 - can recover plaintext from registration entries via `smith session dump`.556 + Placeholder parsing MUST consume the maximal digit run: `smith:sec:12` means ID `12`, never ID `1` followed by `2`.935 - **Limits.** An unregistered secret is not protected — by design. The scan936 - applies to post-transform content only, with exact case- and937 - encoding-sensitive matching: a hook that re-encodes a secret while938 - transforming (§9.8) launders the derived form past the scan (p13) —939 - pre-transform text is never persisted, so this is a stated boundary, not a940 - bug. The protection target is the remote LLM; the trust model is §11's, and941 - core does no best-effort guessing.558 + #### Ingestion masking 943 - ### 6.8 System Prompt 560 + Masking MUST use exact, case-sensitive, encoding-sensitive substring matching against registered plaintext. It MUST run before content becomes a normal session entry and after the plugin `input` or `tool_result` hook, allowing a hook to register a value and mask that same content.945 - `SystemPromptBuilder` composes:562 + Matching MUST be longest-match-first in one left-to-right pass. Emitted placeholders MUST NOT be rescanned. Plaintext MUST occur in session entries only inside secret-registration entries. On resume, the registry MUST rebuild by scanning those entries backward.948 - - active model/tool capabilities,949 - - plugin prompt contributions,950 - - project/context facts,951 - - safety and tool-use instructions,564 + Pre-transform input MUST NOT be persisted. Only post-hook, post-transform content is scanned. If a hook re-encodes a registered secret, that derived representation is outside protection.568 + A placeholder MUST be rehydrated only immediately before tool execution, including subprocess execution and Rust or Lua `execute` calls. Rehydration MUST be one pass and produced plaintext MUST NOT be rescanned. Ordinary session content, provider requests, trace files, and public events MUST contain placeholders, not plaintext. Secret-registration public events and traces MUST expose only ID/label/redacted data even though the session registration record retains plaintext.570 + Compare replay MUST obtain plaintext from secret-registration entries in the source session file and MUST NOT obtain it from the trace. An unknown placeholder ID MUST pass through unchanged without error.572 + #### Display and local trust 574 + The TUI MUST display a placeholder as a masked label, for example `‹secret: provider-token›`. Displayed content MUST correspond to the same masked context content. `smith.secret.list()` and RPC MUST never reveal plaintext. A trusted local user MUST be able to recover registration plaintext through the local CLI `smith session dump`; RPC dump MUST redact it.576 + An unregistered secret receives no protection. Core MUST NOT guess secrets. The protection target is the remote LLM/provider boundary, not the trusted local user, plugins, or files.580 + `SystemPromptBuilder` MUST compose:583 + - active model and tool capabilities;584 + - plugin prompt contributions;585 + - workspace and context facts;586 + - safety and tool-use instructions; and952 587 - user overrides.- user overrides.954 - Plugins may transform prompts through typed hooks. No hidden global prompt mutation.589 + Plugins MAY transform prompts only through typed hooks. Hidden global mutation is forbidden. The prompt MUST tell the agent to discover capabilities through `smith help --search`, `smith help --guide`, and `smith help --example`; it MUST NOT embed the complete SDK reference.956 - The system prompt bootstraps SDK self-learning: it teaches the agent to957 - discover plugin/SDK capabilities through `smith help --search`, `--guide`, and958 - `--example` (§10.2) instead of embedding the full SDK reference inline.591 + ### Append-only compaction 960 - ### 6.9 Compaction and Cost 593 + Compaction MUST neither rewrite nor delete history. Storage MUST retain every entry verbatim and remain memory-bounded through lazy loading.962 - Compaction never rewrites history. Entries are append-only (§6.5), so963 - compaction is a mask applied at context-assembly time, not a storage595 + A pass MUST append a summary entry on the current path containing:966 - - **Storage never shrinks.** The session file keeps every entry verbatim;967 - memory stays bounded by lazy loading (§13.2).968 - - **A compaction pass appends a summary entry** to the current path,969 - recording the covered span (from/to `EntryId`), the summary text, and970 - before/after token estimates.971 - - **Context assembly folds the path** (§6.5 read path): spans covered by a972 - summary entry collapse into the summary; trim-masked content collapses973 - into stubs. What the model sees is the folded path; the file is untouched.601 + before token estimate975 - Because the summary rides the path like any entry, branching needs no976 - special case: switching the leaf to a pre-compaction entry yields a path977 - without the summary — full history visible again, eligible to re-compact978 - (producing a sibling summary on that branch) — and branches created after979 - the compaction point inherit the mask.605 + Context assembly MUST fold only the current root-to-leaf path. Summary-covered spans MUST collapse to their summary; trim-masked tool results and thinking MUST collapse to stubs. Raw storage MUST remain unchanged.981 - Fold rules (prototype-proven, p12):607 + Switching to an entry before a summary MUST expose a path without that summary, restore full visibility on that path, and permit a sibling summary. A descendant path created after a compaction point MUST inherit its mask.983 - - **Span well-formedness**: a covered span is a contiguous ancestor segment984 - of the path the summary was appended to (`from` an ancestor of `to`; `to`985 - an ancestor of the summary entry). Well-formed compaction cannot produce a986 - span crossing a fork point; a violating span is file damage — the fold987 - ignores that summary, shows the span raw, and diagnoses. Never a partial989 - - **Summaries nest**: re-compaction on an already-compacted path always990 - covers the prior summary entry. The fold applies the outermost (latest)991 - covering span; inner summaries are subsumed.992 - - **Metadata entries inside a covered span fold away** with the span — leaf993 - resolution and replay read raw storage (§6.5), never the folded path, so609 + A valid covered span MUST be one contiguous ancestor segment of the path on which the summary was appended: `from` MUST be an ancestor of `to`, and `to` an ancestor of the summary. A span crossing a fork or violating those rules MUST be diagnosed and ignored in full; its raw content MUST appear without partial collapse.996 - Trigger (prototype-proven at ±1 token, p21): before each agent provider997 - request — summarization requests are exempt from the trigger check, or the998 - rule would be self-referential — when the estimated folded-path tokens999 - STRICTLY exceed the threshold:611 + Re-compacting an already compacted path MUST cover the prior summary entry. Folding MUST apply the outermost, latest covering span, subsuming nested inner summaries. Metadata in a covered span MUST fold with it. Leaf resolution and trace/session replay MUST always read raw storage, not folded context.613 + ### Compaction trigger, budget, and ladder 615 + Before every agent provider request except a summarization request, compaction MUST trigger only when estimated folded-path tokens strictly exceed:1002 618 threshold = floor(threshold_fraction × context_window) − output_reserve_tokensthreshold = floor(threshold_fraction × context_window) − output_reserve_tokens1005 - All three values are named config keys (§5.6; reloadable per §9.19), with1006 - the strict validity rule `recency_fraction + reserve_fraction <1007 - threshold_fraction`, rejected at config load — otherwise the recency window1008 - can dominate the budget and a triggered round can NEVER fit (the ladder1009 - cannot touch the window), re-running the full ladder on every request1010 - forever. Runtime guards back the static rule: a round whose protected1011 - window alone exceeds the threshold reports and stops rather than spinning,1012 - and a ladder pass that makes no progress aborts the round.621 + The strict `compaction.*` schema MUST expose reloadable `threshold_fraction`, `output_reserve_tokens`, `recency_fraction`, `reserve_fraction`, `iteration_limit`, and `compaction_model` values. It MUST reject:1014 - Trim ladder, cheapest first, repeated until the context fits or the1015 - configured iteration limit is reached:1017 - 1. mask old tool-result bodies to stubs (dominant bytes per the memory1019 - 2. mask old thinking blocks,1020 - 3. LLM-summarize the oldest span. Summarization uses the active model unless1021 - the `compaction_model` config key selects another (resolved via §5.7, so1022 - aliases/groups work); its usage is tracked as normal cost.1024 - Survives the trim ladder (never stubbed or discarded by a compaction round —1025 - distinct from escaping a later covering span at fold time, which nothing1028 - - secret registrations (§6.7) — these survive *structurally*: hoisted out of1029 - collapsed spans so resume and rehydration keep working, but they hold1030 - plaintext, so the provider rendering masks/excludes them (§6.7 — a1031 - verbatim-to-provider reading would ship plaintext to the LLM),1032 - - the system prompt snapshot,1033 - - existing compaction summary entries (they are summarizer input),1034 - - the recency window: the most recent entries up to a configured fraction of1035 - the context window (token-budget based, so it adapts to model size).1037 - A round cannot re-enter itself: it runs synchronously at the only trigger1038 - site, before the agent's provider request. Reaching the iteration limit1039 - terminates the round and reports — the request proceeds over budget, and1040 - `session_compact` carries the outcome (fit, iteration-limit, no-progress,1043 - `session_before_compact` (§9.8, blockable) may veto the round, adjust the1044 - span, or replace the summarization prompt; `session_compact` reports the1049 - - v1 heuristic: chars/4,1050 - - exact tokenizer is not required in core.1054 - - consumes `ProviderUsage`,1055 - - multiplies by `ModelMetadata.cost`,1056 - - tracks input/output/cache tokens and running total.1058 - ### 6.10 Tool Registry 1060 - `ToolRegistry` stores shared, thread-safe `AgentTool` handles by name.1064 - - duplicate registration follows harness plugin precedence,1065 - - arguments are JSON-schema validated,1066 - - final tool errors become tool-result content for the LLM,1067 - - transient failures may retry according to tool policy.1069 - ### 6.11 Trace and Replay 1071 - Trace files capture deterministic replay data:1073 - - file header with magic/version/session ID,1074 - - compressed via block-level zstd (p20 measurements): ~4KiB blocks, entries1075 - under 64B never compressed individually, per-block raw-fallback flag —1076 - a trace never exceeds its uncompressed framed size by more than the fixed1077 - per-block header (9B/block; per-entry compression inflates small entries),1078 - - provider requests/events,1079 - - tool calls/results,1080 - - **session-entry appends** — every entry appended to the session (leaf1081 - switches, compaction summaries, steer/follow-up deliveries, secret1082 - registrations with plaintext redacted idempotently; compare-mode1083 - rehydration reads the session file's registration entries, never the1084 - trace). Without this kind the reconstruction guarantee is unmeetable1085 - (p20: the remaining kinds rebuild zero session entries),1086 - - TUI events as opaque JSON,1087 - - plugin events as opaque JSON,1088 - - VCS operation IDs,1089 - - agent state snapshots — taken at every run end and abort, carrying the1090 - current leaf, both message queues, and the abort flag (p20: abort-time1091 - queue state is otherwise lost).1095 - - preserves event order,1096 - - enough data to reconstruct session state,1097 - - compare mode can re-execute tools and diff outputs,1098 - - replay can run real-time, speed multiplier, or max speed.1103 - - max-speed reconstruction,1104 - - compare old vs new tool outputs,1105 - - fast-forward to turn range.1107 - ## 7. AI Crate: `smith-ai` 1109 - `smith-ai` owns concrete provider integrations. It depends only on `smith`.1111 - ### 7.1 Provider Trait 1113 - `Provider` is thread-safe and object-safe (usable as a trait object without1114 - async-trait machinery — a prototype-verified property). It exposes:1116 - - identity: id and display name,1117 - - auth validation, failing fast before the first stream (§7.4),1118 - - `stream`: takes a `ProviderRequest`, returns a boxed async stream of1119 - `ProviderEvent` — a plain method returning a stream, not an async method.1121 - `provider_to_stream_fn` adapts a shared `Provider` handle into the `StreamFn`1122 - consumed by `smith-core`.1124 - ### 7.2 Provider Implementations 1131 - - OpenAI-compatible local/remote endpoints.1133 - Provider implementations normalize vendor wire formats into `ProviderEvent`.1135 - Quirks handled at provider boundary:1137 - - streaming vs non-streaming APIs,1138 - - partial tool-call argument chunks,1139 - - thinking/reasoning fields (reasoning text may arrive inside `content` before1140 - the final answer on some OpenAI-compatible endpoints),1141 - - provider-specific stop reasons,1142 - - cache usage fields,1143 - - model capability flags.1145 - Error detection: some providers return errors as plain JSON bodies with1146 - HTTP 200 instead of SSE (prototype-proven against a live OpenAI-compatible1147 - endpoint). A provider implementation must detect a non-streaming JSON error1148 - body on a streaming request and convert it to `ProviderEvent::Error` — never1149 - hang waiting for SSE frames that will not come.1151 - ### 7.3 Model Registry 1153 - `providers.json` is bundled in `smith-ai/src/providers.json`. That checked-in1154 - file is authoritative at runtime.1156 - `fetch-providers` is a bootstrap and maintenance aid, not an automatic truth1160 - cargo run -p xtask -- fetch-providers624 + recency_fraction + reserve_fraction >= threshold_fraction1163 - Data source priority for generated suggestions:627 + A round MUST run synchronously at that sole trigger site and MUST NOT re-enter itself. If the protected recency window alone exceeds the threshold, it MUST report that condition and stop. If a ladder pass makes no progress, the round MUST abort.1165 - 1. models.dev (`https://models.dev/api.json` — the open, community-maintained1166 - model database with a CI-validated schema),1167 - 2. catwalk provider configs,1168 - 3. later shared provider repositories after review.629 + The ladder MUST run in this order and repeat until context fits or `iteration_limit` is reached:1170 - Merge rule (prototype-proven, p05):631 + 1. mask old tool-result bodies to stubs;632 + 2. mask old thinking blocks; then633 + 3. summarize the oldest eligible span with an LLM.1172 - - merge by provider/model ID at LEAF-FIELD granularity — a recursive1173 - field-level merge; subtree or whole-model replacement would clobber curated1174 - registry values (e.g. structured cost objects),1175 - - models.dev primary,1176 - - catwalk fills gaps (missing field, missing model, missing provider),1177 - - unknown provider fields are preserved for forward compatibility but ignored1178 - by v1. Preservation is semantic (value-equal), not byte-for-byte — default1179 - JSON tooling reorders keys. Unknown fields must never appear in generated635 + Summarization MUST use the active model unless `compaction_model` chooses another. Aliases and groups MUST resolve normally. Summarization usage MUST enter normal cost accounting.1182 - Conflict policy: some conflicts cannot be auto-merged and are excluded from the1183 - suggestion and reported explicitly:637 + Every round MUST protect from ladder trimming:1185 - - type-mismatch-vs-curated: a source proposes a value whose structure differs1186 - from the hand-curated registry value (curated value kept). With schema1187 - validation at boundary 1, this class remains reachable only on1188 - schema-unconstrained (unknown) fields — real data contains live precedent1189 - (p19: `interleaved` is a bool on 32 models and an object on 613).639 + - secret-registration entries, structurally hoisted from collapsed spans while excluded or masked in provider rendering;640 + - the system-prompt snapshot;641 + - existing compaction summaries used as summarizer input;642 + - a token-budget recency window containing newest entries up to `recency_fraction` of model context.1191 - (The former ambiguous-primary-source class is dropped: duplicate model IDs1192 - collapse at JSON parse time and are undetectable post-parse — p19. Detecting1193 - them would require raw duplicate-key lexing, deferred until evidence demands644 + Protection from the ladder does not exempt an entry from a later valid covering fold.1196 - `fetch-providers` exits non-zero while unresolved conflicts remain, so PR1197 - automation can never auto-merge a corrupting suggestion. Its outputs are the1198 - suggested file, a reviewable source-attributed patch, and a machine-readable646 + At the iteration limit, the round MUST terminate, report, and let the provider request proceed over budget. `session_compact` MUST report exactly one of:1201 - `replace_models` is a plugin provider-override flag (`smith.provider.*`,1202 - §9.10), not a `fetch-providers` merge input.649 + fit | iteration-limit | no-progress | recency-dominates1204 - **Canonical schema.** Smith does not invent a provider/model schema — it adopts1205 - the models.dev shape and keeps a pinned local snapshot: a JSON Schema at1206 - `smith-ai/src/providers.schema.json`. The pin procedure (p19: `api.json`1207 - carries no in-band version and models.dev publishes no standalone schema1208 - artifact) is: retrieval date + content sha256 of the reviewed snapshot,1209 - recorded beside the schema; upstream evolution is reviewed like a dependency652 + The blockable `session_before_compact` hook MAY veto the round, adjust its span, or replace its summarization prompt. `session_compact` MUST report the resulting outcome.1212 - The schema is validated with the `jsonschema` workspace crate at three1213 - boundaries (p19, executed against the full real registry — 166 providers,654 + ### Token and cost accounting 1216 - 1. `fetch-providers` source data — source fragments are partial by design,1217 - so boundary 1 validates types only (`required` clauses apply post-merge);1218 - an invalid field is excised at the source boundary with a report, not a1220 - 2. the merged result and the checked-in `providers.json` (full schema,1222 - 3. provider tables passed to `smith.provider.register` at runtime (§9.10).656 + Version 1 token estimation MUST use `chars / 4`; an exact tokenizer is not required. Cost tracking MUST consume `ProviderUsage`, multiply known usage categories by `ModelMetadata.cost`, and track input, output, cache-read, cache-write, total tokens, and running total cost. A model whose pricing is unknown MUST be excluded from monetary cost tracking rather than treated as zero-cost.1224 - Registry shapes follow models.dev naming, with real-data optionality (p19):1225 - `cost` (USD per million tokens: `input`, `output`, `cache_read`,1226 - `cache_write`, optionally `reasoning`, `input_audio`, `output_audio`; tiered1227 - fields `tiers`/`context_over_200k` are preserved, not consumed) — `cost` is1228 - always an object when present, never a scalar, and is OPTIONAL (absent on1229 - 398/5666 real models: such models are priced-unknown and excluded from cost1230 - tracking, never defaulted to zero); `limit` (`context`, `output` required1231 - for chat models, `input` optional); modalities; capability flags1232 - (`attachment`, `reasoning`, `tool_call`, `structured_output`, `temperature`)1233 - are tri-state — absent means unknown, treated as false for gating and1234 - preserved as absent. Unknown fields remain schema-legal1235 - (`additionalProperties` allowed) per the preservation rule above.1237 - Mapping into `ModelMetadata` (§5.7):660 + `ToolRegistry` MUST store shared, thread-safe `AgentTool` handles by name. Duplicate registration MUST follow plugin precedence. Arguments MUST be JSON-Schema validated. Final failures MUST become error tool-result content visible to the model. A transient tool failure MAY retry only according to that tool's policy.1239 - | §5.7 field | models.dev source |1240 - |------------|-------------------|664 + A trace MUST have a header containing magic, version, and session ID. It MUST use block-level zstd compression with approximately 4 KiB blocks.666 + - Entries smaller than 64 bytes MUST NOT be compressed individually.667 + - Every block MUST carry a raw-fallback flag.668 + - A trace MUST NOT exceed its uncompressed framed size by more than the fixed 9-byte header for each block.670 + Traces MUST capture, in order:672 + - provider requests and provider events;673 + - tool calls and results;674 + - every session-entry append, including leaf switches, summaries, delivered steers/follow-ups, and secret registrations;675 + - TUI events as opaque JSON;676 + - plugin events as opaque JSON;677 + - VCS operation IDs; and678 + - an agent-state snapshot at every run end and abort.680 + A state snapshot MUST contain the current leaf, both message queues, and abort flag. Secret-registration trace records MUST redact plaintext idempotently. Compare rehydration MUST use the session file, never trace data.682 + Trace processing MUST preserve event order and contain enough information to reconstruct session state. Replay MUST support visual replay, real-time playback, a speed multiplier, maximum-speed reconstruction, old/new tool-output comparison, and fast-forward to a turn range.684 + Replay MUST read the trace without modifying the source session. Compare mode MUST re-execute tools and diff outputs. Tool execution MUST use `--sandbox <path>` when supplied; otherwise mutating comparison MUST use an isolated temporary replay workspace, never the live session state.688 + ### Provider contract 690 + `Provider` MUST be thread-safe and object-safe and expose:692 + - provider ID and display name;693 + - authentication validation that fails before its first stream; and694 + - `stream(ProviderRequest)`, returning a boxed asynchronous stream of `ProviderEvent`.696 + `stream` MUST be a plain method returning a stream, not an async method. `provider_to_stream_fn` MUST adapt a shared `Provider` handle into the `StreamFn` consumed by core.698 + ### Required providers and normalization 700 + Smith MUST integrate:705 + - OpenAI-compatible local and remote endpoints.707 + Each adapter MUST normalize its vendor wire format into `ProviderEvent` and handle at its boundary:709 + - streaming and non-streaming APIs;710 + - partial tool-call argument chunks;711 + - thinking/reasoning fields, including reasoning text delivered inside `content` before a final answer;712 + - provider-specific stop reasons;713 + - cache-usage fields; and714 + - model-capability flags.716 + If a streaming request receives a non-streaming JSON error body, including with HTTP status 200, the adapter MUST emit `ProviderEvent::Error` and MUST NOT wait indefinitely for SSE frames.718 + ### Bundled model registry 720 + `smith-ai/src/providers.json` MUST be bundled into the product and authoritative at runtime. Its canonical bundled schema MUST be `smith-ai/src/providers.schema.json` and MUST use the models.dev provider/model shape.722 + The bundled registry and every provider table passed to `smith.provider.register` MUST satisfy the full schema. Unknown fields MUST be legal through `additionalProperties`, preserved semantically, and ignored when version 1 does not consume them. `replace_models` MUST be the provider-override flag for replacing a provider's models.724 + A model record MUST support:726 + - `cost`, when present, as an object with USD-per-million-token fields `input`, `output`, `cache_read`, and `cache_write`, plus optional `reasoning`, `input_audio`, and `output_audio`;727 + - tiered cost fields `tiers` and `context_over_200k`, preserved but not consumed in version 1;728 + - `limit`, with required `context` and `output` for chat models and optional `input`;729 + - input and output modalities;730 + - tri-state capability fields `attachment`, `reasoning`, `tool_call`, `structured_output`, and `temperature`; and731 + - `reasoning_options`, preserved but not consumed in version 1.733 + `cost` MUST NOT be scalar. Missing cost means unknown pricing: the model MUST be omitted from cost tracking and MUST NOT default to zero. An absent capability is unknown, MUST act as false for gating, and MUST remain absent when preserved.735 + Eligible records MUST map to `ModelMetadata` as follows:737 + | `ModelMetadata` field | Registry source |1241 739 | context window | `limit.context` || context window | `limit.context` |1242 - | max output tokens | `limit.output` |740 + | maximum output tokens | `limit.output` |1243 741 | cost | `cost` || cost | `cost` |1244 742 | thinking | `reasoning` || thinking | `reasoning` |1245 - | vision | `"image"` in `modalities.input` |743 + | vision | presence of `"image"` in `modalities.input` |1246 744 | tool use | `tool_call` || tool use | `tool_call` |1247 - | streaming | assumed true; provider config may disable |745 + | streaming | `true` unless provider configuration disables it |1249 - `structured_output`, `temperature`, and `attachment` are not represented in v11250 - `ModelMetadata` and are preserved, not consumed. (`reasoning_options` —1251 - thinking-effort levels on 3578 real models — is a candidate for §5.21252 - ThinkingLevel configuration; preserved, consumption deferred.)747 + `structured_output`, `temperature`, and `attachment` MUST be preserved in the registry but MUST NOT appear in version-1 `ModelMetadata`.1254 - Mapping eligibility (p19): only chat-capable models map into1255 - `ModelMetadata` — `"text"` in `modalities.output` and `limit.context > 0`.1256 - Image/video generator models (limit 0) stay in the registry but are not1257 - resolvable as chat models.749 + Only chat-capable models may map: `modalities.output` MUST contain `"text"`, and `limit.context` MUST be greater than zero. Image/video generators with zero context MUST remain in the registry but MUST NOT resolve as chat models.1259 - Provider config correctness cannot be fully automated because Smith does not1260 - have all provider accounts, subscriptions, API keys, or regional access.1261 - Generated changes require review before commit.753 + The auth resolver MUST support credentials from:1265 - Auth resolver sources:755 + - environment variables;756 + - `config_dir/auth.json`; and757 + - plaintext Lua configuration when explicitly supplied.1267 - - environment variables,1268 - - `config_dir/smith/auth.json` (§4),1269 - - plaintext Lua config values when explicitly supplied.759 + Smith MUST NOT use an OS keychain or encrypt credential storage. Every loaded credential MUST be registered with the secret proxy. Authentication errors MUST be resolved before the first provider stream.1271 - No OS keychain. No encryption.761 + Each provider's registry `auth_types` map MUST declare supported methods:1273 - Auth errors fail fast before first provider stream.763 + - `api_key`, including its `env_var`;765 + - `organization`, representing an organization-scoped credential such as an API key plus organization ID.1275 - Auth methods per provider are declared in the registry's `auth_types` map:1276 - `api_key` (with its `env_var` name), `oauth`, and `organization` (org-scoped1277 - key, e.g. OpenAI: api key + org ID). `AuthMethod` mirrors these three.767 + `AuthMethod` MUST mirror exactly `api_key`, `oauth`, and `organization`.1279 - `auth.json` is a per-provider object map:769 + `auth.json` MUST be a per-provider object map, for example :1291 - OAuth module supports mocked OAuth flow in tests and provider-specific OAuth1292 - where configured. OAuth per provider is configured with `id`, `name`,1293 - `auth_url`, `token_url`, `scope`, and `client_id`; credentials are1294 - `access_token`, `refresh_token`, `expires_at` (Unix seconds), auto-refreshed on1295 - expiry. The login flow surfaces the auth URL to the user, receives the code via1296 - a local callback HTTP server on a random port (or manual paste), exchanges it1297 - for credentials, and persists them to `auth.json`.1301 - `MuxProvider` wraps multiple providers/accounts for resolved groups and buckets.1303 - Behavior, keyed by the `ProviderError` kinds (§5.2):1305 - - `RateLimit`: immediate failover,1306 - - `AuthFailed`, `Network`, `ServerError`: retry configured count then failover,1307 - - `InvalidRequest`, `ModelNotFound`: no retry, immediate failover,1308 - - `Timeout`: retry once then failover,1309 - - exhausted providers emit `ProviderEvent::Error`.1311 - ## 8. TUI Crate: `smith-tui`1313 - `smith-tui` owns terminal primitives, normalized events, widgets, themes, and1314 - render loop. It depends only on `smith`.1316 - **Frontend boundary.** `smith-tui` is the built-in *in-process frontend* — one1317 - consumer of the `EngineEvent` stream (§6.3) that renders it and feeds intents1318 - (prompt submit, steer, command, abort) back. It is not privileged as *the* UI:1319 - the same event-out/intent-in surface is exposed out-of-process by `smith rpc`1320 - (§10.4), which is the canonical boundary for additional frontends (web, native,1321 - mobile). Those are RPC clients and link no smith Rust code. The render model1322 - below — cells, borders, ratatui `Rect`s — is deliberately terminal-specific and1323 - is **not** a cross-UI abstraction: a browser or GPU frontend brings its own1324 - rendering and consumes only the event/intent surface, never smith's widgets.1330 - - `ratatui` for layout/widgets/TestBackend snapshots,1331 - - `crossterm` for terminal I/O, event polling, raw mode, alternate screen,1332 - Kitty keyboard protocol flags, and terminal capability probes.1336 - `TuiEvent` normalizes crossterm events:1341 - - focus gained/lost,1344 - Keyboard events include normalized key code, modifiers, and press/repeat/release1345 - kind. Mouse events include button, scroll, position, and modifiers.1347 - ### 8.3 Terminal Capabilities1349 - `TerminalCapabilities` records:1353 - - Kitty keyboard protocol,1357 - - Kitty graphics / sixel availability.1359 - No terminfo database. Probe directly. Unsupported optional features degrade to1360 - plain text without user-facing error.1364 - - capabilities are probed once per session at startup, with a 100ms timeout1365 - per probe; on timeout the capability is treated as absent (fail1367 - - image protocol is `ImageProtocol::{Kitty, Sixel}`; the capability is1368 - detected but has no v1 consumer — inline image rendering is deferred1370 - - Kitty keyboard protocol flags are pushed on TUI startup and popped on1371 - shutdown (including error/signal paths, §10),1372 - - synchronized output (`CSI ?2026 h/l`) wraps render passes when the terminal1375 - ### 8.4 Component Trait1377 - Components render into ratatui buffers and handle normalized `TuiEvent`.1381 - - rendering is deterministic,1382 - - focus handling is explicit,1383 - - event handlers return consumed/not-consumed,1384 - - cached state has explicit invalidation.781 + Provider OAuth configuration MUST support:1391 - new → enter terminal → run event/render loop → shutdown → restore terminal1394 - The render loop ticks at 16ms. Event polling runs on a blocking thread and sends1395 - normalized events over channels. `TuiApp` is created/driven by `smith-harness`.792 + Stored OAuth credentials MUST contain `access_token`, `refresh_token`, and `expires_at` as Unix seconds. Expired credentials MUST refresh automatically.794 + `/auth login <provider>` MUST:796 + 1. surface the authorization URL;797 + 2. receive the authorization code from a local callback HTTP server on a random port or manual paste;798 + 3. exchange the code for credentials; and799 + 4. persist them to `config_dir/auth.json`.1406 - Every state is interruptible.801 + OAuth MUST permit mocked flows and provider-specific configuration.1410 - Required widget set includes:805 + `MuxProvider` MUST wrap providers/accounts for resolved groups and buckets. It MUST consume the deterministic resolver plan, deduplicate identical provider/model/account candidates before attempts, and apply this exact policy per candidate:1421 - - progress/cost/context indicators,1422 - - tool call/result views,1424 - - syntax-highlighted code,1429 - - border layout panels.807 + | `ProviderError` | Required behavior |809 + | `RateLimit` | Fail over immediately. |810 + | `AuthFailed` | Retry `providers.retry_count`, then fail over. |811 + | `Network` | Retry `providers.retry_count`, then fail over. |812 + | `ServerError` | Retry `providers.retry_count`, then fail over. |813 + | `InvalidRequest` | Do not retry; fail over immediately. |814 + | `ModelNotFound` | Do not retry; fail over immediately. |815 + | `Timeout` | Retry once, then fail over. |1431 - Syntax highlighting uses `syntastica` with the `runtime-c2rust` runtime (no C1432 - runtime dependencies; prototype-proven). Diffs use `similar` and support1433 - unified and side-by-side modes. Fuzzy matching uses `fuzzy-matcher`.817 + Authentication validation and any resulting `AuthFailed` handling MUST occur before opening a provider stream. `providers.retry_count` MUST default to `2`. Rate limiting MUST never consume retries. When all candidates are exhausted, `MuxProvider` MUST emit `ProviderEvent::Error`; exhaustion in eval mode MUST be fatal.1435 - Overlays (modals, fuzzy search, autocomplete) are positioned by an anchor1436 - model: nine anchors (`Center`, four corners, four edge-centers) plus1437 - `offset_x`/`offset_y` and optional margin; overlay `width`/`max_height` are1438 - `Size::Absolute(cells)` or `Size::Percent`.821 + ### Frontend boundary 1442 - Rust provides primitives; Lua defines layout.823 + `smith-tui` is the built-in in-process frontend. It MUST consume `EngineEvent` and return intents for prompt submission, steering, commands, and abort. It MUST NOT be privileged as the only UI. `smith rpc` MUST expose the same event-out/intent-in engine boundary for external frontends.1444 - Primitives and their shapes:825 + An out-of-process frontend MUST be an RPC client and MUST NOT link Smith Rust code. Terminal cells, borders, widgets, buffers, and `Rect` rendering are terminal-only. Other frontends MUST consume engine events/intents and render independently.1446 - - `column` / `row`: child list, stacked vertically/horizontally,1447 - - `box`: single child, optional `width`/`height` (`Size`), optional border1448 - (`BorderStyle::{Single, Double, Rounded, Thick, None}` + optional title),1449 - - `expanded`: single child, takes remaining space after fixed siblings,1450 - - `scrollable`: single child, direction vertical/horizontal/both,1451 - - `overlay`: single child + overlay options (§8.6 anchor model),1452 - - `spacer`: optional fixed `Size`,1453 - - `tabs`: labeled child list + active index,1454 - - `split`: two children, horizontal/vertical, `split_ratio: f32`.827 + ### Normalized events 1456 - One predefined border layout exists: center + north/east/south/west panels,1457 - each panel carrying `visible`, `size`, and its own layout. Panels are invisible1458 - when empty. Default layout is a Lua plugin.829 + `TuiEvent` MUST normalize:1460 - Composition rules (prototype-proven, p27):834 + - focus gained/lost; and1462 - - `overlay` floats over its container area and is excluded from the flow1463 - tiling set — flow siblings still tile as if it were absent, and the overlay1464 - is positioned by the §8.6 anchor model. Overlays may cover flow content by1465 - design (modals, command palette, autocomplete).1466 - - `tabs` reserves a one-row tab bar; the active child gets the remaining area.1467 - - `scrollable` is layout-transparent — a viewport over its child, not an axis1469 - - `Size::Percent` rounds to the nearest cell.837 + Keyboard events MUST include normalized key code, modifiers, and kind `press`, `repeat`, or `release`. Mouse events MUST include button, scroll, position, and modifiers.1471 - **Resolution (prototype-proven, p27).** Layout resolution never re-enters Lua1472 - on the render path. A plugin builds the layout on change (`set_center_layout`,1473 - `set_*_panel`); the harness converts that Lua tree once into an owned Rust1474 - `LayoutTree` that retains no Lua handle (`Send + 'static`, so it can be built1475 - off the render thread) and drops the Lua value. Every frame, a pure resolver1476 - maps `(LayoutTree, terminal size) → Rect per widget slot` — deterministic for1477 - equal inputs, zero Lua calls in the loop. This is what keeps §12's plugin-1478 - thread round-trips (~81µs, serialized) off the §13 2ms frame budget; measured1479 - per-frame resolution is ~0.4µs (release p99 < 0.8µs) across 80×24 to 400×100.839 + ### Terminal capabilities 841 + `TerminalCapabilities` MUST record:1483 - Themes are Lua tables validated by Rust schemas (prototype-proven, p08).846 + Kitty keyboard protocol1485 - Theme values cover status bar, messages, assistant content, tool call/result,1486 - errors, input, borders, selections, diffs, syntax groups, and accents.854 + Capabilities MUST be probed directly without a terminfo database, once per session startup, with a 100 ms timeout per probe. Probes SHOULD run concurrently so they do not extend the product startup budget. Timeout MUST mean absence. Unsupported optional behavior MUST silently degrade to plain text.856 + Image protocol MUST use `ImageProtocol::{Kitty, Sixel}`. Detection is required, but version 1 MUST NOT render inline images.1490 - - The Rust schema defines the required key set and nesting; every section above1491 - is a named table of color/style values.1492 - - Colors are `#rrggbb` strings. Named/ANSI-indexed colors are not part of the1494 - - A missing required key or malformed value is a validation error carrying the1495 - exact key path (e.g. `theme.status_bar.fg: expected "#rrggbb"`). Unknown keys1497 - - A user theme that fails validation at runtime does not abort Smith: it falls1498 - back to the built-in default theme with a visible warning naming the path858 + Kitty keyboard flags MUST be pushed on TUI startup and popped on every shutdown path, including errors and signals. When synchronized output is supported, each render pass MUST be enclosed by `CSI ?2026 h` and `CSI ?2026 l`.1501 - ### 8.9 Virtual Scroll 860 + ### Components and lifecycle 1503 - Message history uses virtual scrolling. `sticky_bottom` defaults true and turns1504 - false when user scrolls up. New content does not move viewport until user returns1505 - to bottom or submits input.862 + Components MUST render deterministically into terminal buffers, handle normalized `TuiEvent`, manage focus explicitly, report whether an event was consumed, and explicitly invalidate cached state.1507 - ### 8.10 Tool Rendering 864 + `TuiApp` MUST follow:1509 - Tools may register `renderCall` and `renderResult` Lua renderers. TUI receives1510 - structured render instructions from harness, not arbitrary terminal writes.867 + new -> enter terminal -> event/render loop -> shutdown -> restore terminal1512 - ### 8.11 Input Queue 870 + The render loop MUST tick every 16 ms. Event polling MUST run on a blocking thread and send normalized events through channels. `smith-harness` MUST create and drive `TuiApp`.1514 - Queued steering and follow-up messages (§6.1) appear in one visually combined1515 - queue between message history and input:872 + Application states MUST be exactly:1517 - - follow-ups render above steers; within each kind, oldest to newest — steers1518 - sit nearest the input because they deliver soonest,1519 - - the two kinds are visually distinct within the shared queue,1520 - - a promote/demote action toggles a queued message between steer and1521 - follow-up; the item lands at the NEWEST position of its new kind (its1522 - ordering within the other kind is meaningless — consequence, p22: a1523 - promote→demote round trip of a non-newest item does not restore the1524 - original order). The item keeps its original enqueue time,1525 - - Up-arrow cycles newest-to-oldest through the queued messages; selecting1526 - one edits it. While edited, the message is OUT of the queue. Re-sending1527 - returns it to its remembered `(kind, index-within-kind)` position, clamped1528 - to the kind block's current length; if the kind changed while it was out,1529 - it lands newest of the new kind (p22 — this replaces "best effort").1530 - Re-sending it empty removes it,1531 - - while the queue is non-empty, the cancel keys (Ctrl+C/Esc by default,1532 - rebindable §9.11) remove queued messages in ENQUEUE-TIME order, newest1533 - first, across both kinds — undo semantics: the most recently submitted1534 - message un-queues first, which provably diverges from visual-bottom-first1535 - (p22) — *instead of* their default action; only with an empty queue do1536 - they abort the run (§12). While a message is being edited it is not in1537 - the queue: cancel pops the remaining items first, and with the rest1538 - empty, cancel discards the edit (restoring the item) before it can abort.875 + Idle | Thinking | ToolRunning | ToolResult | Error | Exiting1540 - ### 8.12 Deferred Scope (v1) 878 + Every state MUST be interruptible.1542 - Explicitly out of v1 TUI scope:1544 - - vim-style normal-mode editing,1545 - - inline image rendering (Kitty graphics protocol),1546 - - split-pane resizing (the `split` primitive exists; interactive resize does1548 - - multiple simultaneous sessions.882 + The TUI MUST provide:1550 - ## 9. Harness Crate: `smith-harness` 884 + - text and truncated text;889 + - status bar and hint bar;891 + - progress, cost, and context indicators;892 + - tool-call and tool-result views;893 + - unified and side-by-side diff views;894 + - syntax-highlighted code;897 + - scrollable viewport;899 + - border-layout panels.1552 - `smith-harness` wires all subsystems and owns plugin management.901 + ### Overlay and layout contracts 903 + Overlays, including modals, fuzzy search, and autocomplete, MUST support anchors `Center`, all four corners, and all four edge centers; `offset_x`; `offset_y`; optional margin; and `width`/`max_height` as `Size::Absolute(cells)` or `Size::Percent`.1557 - - load model registry and auth,1558 - - resolve active model,1559 - - create provider and `StreamFn`,1562 - - expose SDK to Lua,1563 - - bridge core events to plugin events,1564 - - translate plugin returns into core hooks,1565 - - coordinate TUI, eval, and RPC modes.905 + Rust MUST provide layout primitives; Lua MUST define layout trees. Required primitives are:1567 - ### 9.1 Harness Structure 907 + - `column`: children stacked vertically;908 + - `row`: children stacked horizontally;909 + - `box`: one child, optional `width` and `height` as `Size`, and optional border/title; border style MUST be `BorderStyle::{Single, Double, Rounded, Thick, None}`;910 + - `expanded`: one child taking space left after fixed siblings;911 + - `scrollable`: one child with vertical, horizontal, or both directions;912 + - `overlay`: one child and the overlay options above;913 + - `spacer`: optional fixed `Size`;914 + - `tabs`: labeled children and active index; and915 + - `split`: two children, horizontal or vertical orientation, and `split_ratio: f32`.917 + One predefined border layout MUST expose center, north, east, south, and west panels. Every panel MUST carry `visible`, `size`, and its own layout. Empty panels MUST be invisible. The default layout MUST be a Lua plugin.1577 - - optional `TuiApp`,919 + Composition is exact:1581 - ### 9.2 Plugin Identity and Manifest 921 + - An `overlay` floats over its container and remains outside flow tiling; siblings tile as if absent and overlap is allowed.922 + - `tabs` reserves one terminal row for labels and gives all remaining area to the active child.923 + - `scrollable` is layout-transparent: it is a viewport, not an axis partition.924 + - `Size::Percent` rounds to the nearest terminal cell.1583 - Plugin names are mandatory and namespaced:926 + ### Layout ownership and resolution 928 + Layout resolution MUST NOT enter Lua on a render path. On `set_center_layout` or `set_*_panel`, the harness MUST convert the Lua tree once to an owned Rust `LayoutTree` and drop the Lua value.930 + `LayoutTree` MUST retain no Lua handle and MUST be `Send + 'static`, allowing off-render-thread construction. Every frame MUST use a pure resolver:933 + (LayoutTree, terminal size) -> Rect for each widget slot936 + Equal inputs MUST produce equal outputs with zero frame-loop Lua calls. Across terminal sizes 80×24 through 400×100, resolution SHOULD remain approximately 0.4 µs and release-build p99 MUST remain below 0.8 µs.940 + A theme MUST be a Lua table validated by a Rust schema. Named nested tables MUST cover status bar, messages, assistant content, tool calls, tool results, errors, input, borders, selections, diffs, syntax groups, and accents. Every named section MUST contain color and style values.942 + Colors MUST be `#rrggbb`. Named or ANSI-indexed colors MUST NOT be accepted by the version-1 schema. Missing required keys and malformed values MUST produce the exact path, for example:945 + theme.status_bar.fg: expected "#rrggbb"948 + Unknown keys MUST warn. An invalid user theme MUST NOT abort Smith; the built-in default MUST be activated and a visible warning MUST name the path error.950 + ### History and tool rendering 952 + History MUST use virtual scrolling. `sticky_bottom` MUST default to `true`. Upward user scrolling MUST set it to `false`; while false, new content MUST NOT move the viewport. Following MUST resume when the user reaches bottom or submits input.954 + Tools MAY register Lua `renderCall` and `renderResult` renderers. The harness MUST translate their output to structured render instructions. A plugin MUST NOT write arbitrary terminal output through this mechanism.956 + ### Combined input queue 958 + Steers and follow-ups MUST render as one visually combined queue between history and input:960 + - Follow-ups MUST appear above steers.961 + - Within each kind, items MUST appear oldest to newest.962 + - Steers therefore sit nearest the input because they deliver sooner.963 + - The kinds MUST remain visually distinct.964 + - Promote/demote MUST toggle kind and place the item newest in the destination kind while preserving original enqueue time. A round trip need not restore its prior within-kind position.965 + - Up-arrow MUST cycle queued messages newest to oldest.966 + - Selecting an item for editing MUST remove it from the queue.967 + - Re-sending an edited item MUST restore its remembered `(kind, index-within-kind)` position, clamped to current destination length.968 + - If its kind changed while edited, re-send MUST place it newest in the new kind.969 + - Re-sending empty edited text MUST delete it.970 + - While queued items exist, cancel keys—`Ctrl+C` and `Esc` by default, both rebindable—MUST remove the newest enqueue time across both kinds instead of their normal action.971 + - Only an empty queue permits user cancel to abort.972 + - An edited item is outside the queue. Cancel MUST first remove all remaining queued items; when none remain, the next cancel MUST discard the edit and restore it before any later cancel may abort.974 + ### Version-1 TUI exclusions 976 + Version 1 MUST NOT provide:978 + - Vim-style normal-mode editing;979 + - inline Kitty image rendering;980 + - interactive split-pane resizing, although `split` exists; or981 + - multiple simultaneous sessions in one TUI.983 + ## Harness and Lua SDK 985 + ### Harness composition 987 + `smith-harness` MUST load configuration, model registry, and authentication; resolve the active model; create providers and `StreamFn`; create the agent; load/manage plugins; expose the Lua SDK; bridge core and plugin events; translate plugin returns to core hooks; and coordinate TUI, eval, and RPC modes.989 + `Harness` MUST contain:996 + authentication resolver1003 + ### Plugin identity and locations 1005 + Every plugin name is mandatory and MUST be:1586 1008 <org>/<name><org>/<name>1011 + Both components MUST contain only lowercase ASCII letters, digits, `_`, and `-`. `smith/*` is reserved for built-ins. Installed global code MUST live at `data_dir/plugins/<org>/<name>/`; workspace code MUST live at `.smith/plugins/<org>/<name>/`; persistent plugin data MUST live at `data_dir/data/<org>/<name>/`.1591 - - `org` and `name` use lowercase ASCII letters, numbers, `_`, and `-`.1592 - - `smith/*` is reserved for built-in plugins.1593 - - Installed global plugins live under `data_dir/smith/plugins/<org>/<name>/`.1594 - - Project plugins live under `.smith/plugins/<org>/<name>/`.1596 - Every plugin has a mandatory Lua manifest file named `smith-plugin.lua` in the1597 - plugin root. Plugin authors create it. Manifest loading uses a restricted1598 - manifest environment — an empty Lua environment with no globals, no Smith SDK,1599 - and no host I/O — so the chunk can only build and return a pure data table.1600 - A manifest that reaches for `os`/`require`/any global, or that contains1601 - function values, is rejected (prototype-proven, p04).1015 + Every plugin root MUST contain `smith-plugin.lua`. The manifest chunk MUST run in an empty environment with no globals, Smith SDK, or host I/O and MUST only construct and return pure data. Access to `os`, `require`, or any other global, and any function-valued field, MUST reject the manifest.1603 - Required manifest fields:1017 + Required fields are :1613 - Optional manifest fields:1027 + Optional fields are :1622 - - `heap_limit` (bytes, §9.14),1623 - - `interfaces` — list of interface names this package exports descriptors for1625 - - `implements` — list of interface names this package implements (§9.6).1627 - If `smith_api` is absent, Smith treats it as `1`.1042 + `heap_limit` is bytes. `interfaces` lists exported interface descriptors; `implements` lists implemented interface names. If omitted, `smith_api` MUST default to integer generation `1`. The host MUST validate the manifest before executing entry code.1629 - Smith validates manifests before loading plugin code.1044 + ### Plugin API compatibility 1631 - ### 9.3 Plugin API Compatibility1046 + Plugin API versions MUST be integer generations, not semantic-version ranges. Generation `1` is the default. From Smith `1.0.0` onward, generation `1` MUST remain supported permanently. Future breaking APIs MUST use explicit generations `2`, `3`, and later.1633 - Smith plugin API uses integer generations, not semver ranges.1048 + A plugin MUST opt into a newer generation explicitly. A generation newer than the host supports MUST prevent loading. `smith plugins` MUST list the plugin as disabled and report both required and supported generations; silent or best-effort loading across an unknown generation is forbidden.1635 - - API generation `1` is the default.1636 - - If `smith_api` is absent, the plugin uses API generation `1`.1637 - - From Smith `1.0.0` onward, API generation `1` is stable permanently.1638 - - Future breaking plugin APIs use new generations (`2`, `3`, ...).1639 - - Plugins opt in to a newer generation by setting `smith_api = 2`.1640 - - A plugin declaring a generation newer than Smith supports does not load.1641 - `smith plugins` shows it as disabled with required/supported API generations.1050 + ### Loading and registration precedence 1643 - Smith must keep API generation `1` working. Silent best-effort loading across1644 - unknown generations is forbidden.1052 + A plugin entry MUST return a registration table or factory. Loading MUST occur in this order:1646 - ### 9.4 Plugin Loading1648 - Lua plugins return registration tables/factories from their entry file. Plugin1651 - 1. Load manifest in manifest environment.1652 - 2. Validate name, version, source, API range , dependencies, and declared secrets.1653 - 3. Load entry Lua source in restricted runtime.1054 + 1. Load the manifest in its isolated environment.1055 + 2. Validate name, version, source, API generation , dependencies, and declared secrets.1056 + 3. Load entry Lua source in the restricted runtime.1654 1057 4. Collect registrations.4. Collect registrations.1655 - 5. Materialize Rust -side handles.1656 - 6. Register into tool/event/command/provider/TUI registries.1058 + 5. Materialize host -side handles.1059 + 6. Register tools, events, commands, providers, interfaces, and TUI contributions.1658 - No Rust trait-object plugin API exists. Canonical plugin loading is the Lua1659 - registration pipeline above.1061 + Lua registration is canonical. Smith MUST NOT expose a Rust trait-object plugin API.1661 - ### 9.5 Plugin Install and Uninstall1063 + Plugins MUST load by precedence:1663 - Supported install sources for v1:1066 + 2. global user plugins;1067 + 3. workspace-local plugins;1068 + 4. explicit CLI/configuration overrides.1665 - - local directory path,1070 + Later registrations MUST override earlier registrations unless a registration explicitly defines duplication as an error.1668 - No central registry exists in v1.1072 + ### Installation and uninstallation 1670 - `smith install <path-or-git-url>`:1074 + Version 1 MUST install from a local directory or Git URL and MUST NOT require or expose a central plugin registry.1672 - - resolves the source into a temporary staging area,1673 - - reads and validates the manifest, namespace, and API compatibility in1674 - staging — a rejected plugin never touches the plugins root,1675 - - copies into `data_dir/smith/plugins/<org>/<name>/` only after validation,1676 - - refuses duplicates unless `--force`,1677 - - does not run plugin entry code during install (prototype-proven, p04).1077 + smith install <path-or-git-url> [--force]1681 - - A duplicate is defined as: the destination directory1682 - `data_dir/smith/plugins/<org>/<name>/` already exists, regardless of version.1683 - - `--force` is full replacement: remove the old plugin directory, then place the1684 - new one. Plugin data under `data_dir/smith/data/<org>/<name>/` survives a1686 - - Git installs strip the `.git` directory: an installed plugin is a pure file1687 - snapshot, not a working clone. Updates go through reinstall.1082 + 1. resolve the source into temporary staging;1083 + 2. read and validate manifest, namespace, and API compatibility in staging outside the global plugin root;1084 + 3. leave the entire global plugin root untouched on failure;1085 + 4. copy validated code to `data_dir/plugins/<org>/<name>/`;1086 + 5. refuse an existing destination unless `--force` is present; and1087 + 6. never execute entry code during installation.1689 - Git URL installs go through Smith's internal git boundary, implemented with1690 - `gix` — no runtime dependency on a `git` binary (prototype-decided, p25: gix1691 - clones a repo at a ref byte-for-byte identical to shell-out). Local clone adds1692 - five first-party gix crates over the §2.3 VCS-query baseline; the https1693 - transport's TLS/async stack is mostly already paid for by the §2.3 `reqwest`1694 - and `tokio` requirements, and gix's http transport is configured to share1695 - reqwest's TLS backend rather than ship a second one. Shell-out was rejected:1696 - zero build cost, but it forces a compatible `git` on every user's PATH for a1089 + Any existing destination directory is a duplicate regardless of version. `--force` MUST fully replace code while preserving `data_dir/data/<org>/<name>/`. A Git installation MUST omit `.git` and produce an immutable file snapshot; update is reinstallation.1699 - ` smith uninstall <org>/<name>`: 1092 + smith uninstall <org>/<name> [--purge-data] 1701 - - removes installed plugin code,1702 - - keeps plugin data by default,1703 - - supports `--purge-data` to remove `data_dir/smith/data/<org>/<name>/`,1704 - - never removes project plugins.1095 + Uninstall MUST remove installed global code, retain plugin data by default, remove `data_dir/data/<org>/<name>/` only with `--purge-data`, and MUST NOT remove a workspace-local plugin.1706 - ### 9.6 Plugin Interface Modules1097 + ### Plugin interfaces 1708 - Interfaces are plain Lua descriptor tables validated at runtime. This design is1709 - prototype-proven (p02, p03); the typed-Lua (Teal) and annotation-schema1710 - candidates are rejected.1099 + An interface package MUST export a pure-data descriptor with:1712 - **Why Teal is rejected.** Teal's compile-time guarantees evaporate at the1713 - runtime boundary: Smith embeds LuaJIT, so Teal ships as compiled Lua and the1714 - host must re-validate conformance regardless — Teal would be additive toolchain1715 - cost, not a replacement for runtime descriptors. Making official interfaces1716 - Teal-authored would also split the ecosystem into typed and plain-Lua authors,1717 - the exact fragmentation §9.6 exists to prevent. The authoring-time typing Teal1718 - would provide is delivered instead by LuaLS annotations (below and §9.10)1719 - without a compile step.1101 + - `name`: `<org>/<name>`;1102 + - `generation`: an integer interface generation distinct from plugin API and reload-domain generations;1103 + - `functions`: a map from function name to `{ params, returns }`, using typed named parameters that MAY be optional; and1104 + - `events`: bus topic names.1721 - **Generated typing.** Interface descriptors mechanically generate LuaLS stub1722 - files (`---@class`/`---@field`/`---@param` annotations derived from the1723 - descriptor's `functions` table) as part of `cargo run -p xtask -- doc-gen`.1724 - Plugin authors targeting an interface get editor-time type checking against1725 - the same descriptor the runtime validates — one source of truth, two1106 + The same descriptor MUST drive runtime validation and generated LuaLS stubs using `---@class`, `---@field`, and `---@param`. Interface-only, implementation-only, externally referenced implementation, and combined interface/implementation packages MUST all work through manifest `interfaces` and `implements`.1728 - **Descriptor.** An interface package exports a descriptor: a pure data table1729 - with `name` (`<org>/<name>`), `generation` (integer — the interface's own1730 - version, distinct from the plugin API generation of §9.3 and the reload domain1731 - generation of §9.16), `functions` (map of function name → `{ params, returns }`1732 - with typed, optionally-optional named parameters), and `events` (list of bus1108 + An adapter entry MUST export:1735 - **Ecosystem shapes.** Interface-only packages, implementation-only packages,1736 - implementations referencing external interfaces, and combined packages are all1737 - supported through two manifest fields (§9.2): `interfaces` (list of interface1738 - names this package exports descriptors for) and `implements` (list of interface1739 - names this package implements).1111 + adapts = "<org>/<name>"1741 - **Adapters.** An adapter is an implementation package whose entry exports1742 - `adapts = "<org>/<name>"` (the wrapped plugin) plus a `make(wrapped)` factory1743 - returning a conforming implementation. The plugin manager injects the wrapped1744 - plugin's exports into `make`.1114 + and a `make(wrapped)` factory returning a conforming implementation. The manager MUST inject the wrapped plugin's exports into `make`.1746 - **Binding.** User config selects the implementation backing an interface:1116 + Configuration MUST select an implementation with:1749 1119 interfaces = { ["community/subagent"] = "org/name" }interfaces = { ["community/subagent"] = "org/name" }1752 - Binding precedence: explicit config binding, else the last-loaded plugin1753 - declaring `implements` for that interface (§9.7 order). Conformance is checked1754 - at bind time. A conformance failure names the plugin, interface and generation,1755 - every missing/mis-shaped export with its exact path, the exports the plugin1756 - actually provides, and any installed adapter for it.1122 + Binding precedence is:1758 - **Views.** Consumers receive an interface view: only declared functions are1759 - visible (implementation-private fields are hidden), and arguments are validated1760 - against the descriptor at call time with errors naming function and parameter.1761 - A resolved binding is a singleton: all consumers of an interface share the one1762 - bound implementation instance.1124 + 1. explicit configuration;1125 + 2. otherwise, the last-loaded plugin declaring `implements` for that interface.1764 - ### 9.7 Plugin Precedence 1127 + Conformance MUST be checked at bind time. Failure MUST report the plugin, interface name/generation, every missing or malformed export with exact path, exports actually provided, and any adapter installed for that plugin.1129 + Consumers MUST receive a view exposing only declared functions; private fields MUST be hidden. Calls MUST validate descriptor arguments and name the failing function and parameter. Each resolved binding MUST be a singleton shared by all consumers.1768 - 1. built-in plugins,1769 - 2. global user plugins,1771 - 4. explicit CLI/config overrides.1131 + ### Plugin event bridge 1773 - Later registrations override earlier ones unless registration marks duplicate as1133 + Every Lua event table MUST contain `type`. The catalog and blocking behavior are:1776 - ### 9.8 Event Bridge 1135 + | Event | May block | Required behavior |1137 + | `resources_discover` | No | Contribute skill, prompt, and theme paths. |1138 + | `session_start`, `session_shutdown` | No | Report started/loaded/reloaded and shutdown lifecycle. |1139 + | `session_before_switch` | Yes | Run before leaf/session switching. |1140 + | `session_before_fork` | Yes | Run before session clone/fork. |1141 + | `session_before_compact` | Yes | Customize or block compaction. |1142 + | `session_compact`, `session_tree` | No | Completed notifications. |1143 + | `before_agent_start` | No | May inject messages or modify system prompt. |1144 + | `agent_start`, `agent_end`, `turn_start`, `turn_end` | No | Agent lifecycle. |1145 + | `model_select` | No | Active model changed. |1146 + | `message_start`, `message_update`, `message_end` | No | Message streaming lifecycle. |1147 + | `thinking_delta`, `text_delta` | No | Token deltas. |1148 + | `tool_execution_start` | No | Execution began or call was blocked. |1149 + | `tool_call` | Yes | Runs before execution. |1150 + | `tool_execution_update`, `tool_result`, `tool_execution_end` | No | Updates and completion; `tool_result` may modify result. |1151 + | `input` | No | Intercept, transform, or mark input handled. |1152 + | `user_bash` | No | User `!` and `!!` commands. |1153 + | `context` | No | Modify messages before an LLM call. |1154 + | `before_provider_request`, `after_provider_response` | No | Inspect/replace request; observe response. |1155 + | `config_changed` | No | Carries changed configuration paths. |1156 + | `plugin_loaded`, `plugin_unloaded` | No | Plugin lifecycle. |1157 + | `panel_toggle`, `resize` | No | TUI lifecycle. |1158 + | `provider_registered` | No | Emitted after provider addition/override. |1159 + | VCS events | No | Report VCS operations. |1160 + | error events | No | Report classified errors. |1161 + | `shutdown` | No | Host shutdown. |1778 - Lua receives event tables with a `type` field. The canonical event catalog and1779 - per-event blocking capability:1163 + Handler return contracts are exact:1781 - | Event | Can block | Notes |1782 - |-------|-----------|-------|1783 - | `resources_discover` | No | contribute skill/prompt/theme paths |1784 - | `session_start`, `session_shutdown` | No | started/loaded/reloaded; shutting down |1785 - | `session_before_switch` | **Yes** | before switching sessions |1786 - | `session_before_fork` | **Yes** | before forking/cloning |1787 - | `session_before_compact` | **Yes** | can customize compaction |1788 - | `session_compact`, `session_tree` | No | completed notifications |1789 - | `before_agent_start` | No | may inject messages, modify system prompt |1790 - | `agent_start`, `agent_end`, `turn_start`, `turn_end` | No | lifecycle |1791 - | `model_select` | No | model changed |1792 - | `message_start`, `message_update`, `message_end` | No | streaming lifecycle |1793 - | `thinking_delta`, `text_delta` | No | token deltas |1794 - | `tool_execution_start` | No | execution began or call was blocked (§6.4) |1795 - | `tool_call` | **Yes** | before tool executes (§6.4 blocked-call contract) |1796 - | `tool_execution_update`, `tool_result`, `tool_execution_end` | No | `tool_result` may modify the result |1797 - | `input` | No | may intercept/transform/mark handled |1798 - | `user_bash` | No | user `!`/`!!` commands |1799 - | `context` | No | may modify messages before LLM call |1800 - | `before_provider_request`, `after_provider_response` | No | inspect/replace payload; response received |1801 - | `config_changed` | No | §9.19, carries changed key paths |1802 - | `plugin_loaded`, `plugin_unloaded` | No | plugin lifecycle |1803 - | `panel_toggle`, `resize` | No | TUI |1804 - | `provider_registered` | No | after provider add/override |1805 - | VCS events | No | §9.13 operations |1806 - | errors | No | §9.17 |1807 - | shutdown | No | host shutdown (§10, §12) |1167 + { block = true, reason = "..." }1168 + { args = replacement }1809 - Handler return-table contracts (Lua-facing, one per §6.4 hook capability):1173 + { content = replacement }1176 + nil -- keep original1811 - - `tool_call` → `{ block = true, reason = "..." }` or1812 - `{ args = <replacement> }` or `{ cancel = true }` or nil/`{}` (allow),1813 - - `tool_result` → `{ content = <replacement> }` or `{ retry = true }` or1814 - `{ cancel = true }` or nil (keep),1815 - - `turn_end` → `{ stop = true }` to end the agent loop after this turn1816 - (ShouldStopAfterTurn), or nil (continue),1817 - - `input` → `{ action = "handled" | "continue", text = <transformed>? }`,1818 - - `context` → `{ messages = <modified> }` or nil,1819 - - `session_before_*` → `{ block = true, reason = "..." }` or nil,1820 - - all other events: return value ignored.1179 + { stop = true } -- ShouldStopAfterTurn1822 - The bridge maps these into `AgentLoopConfig` hooks (§6.4).1183 + { action = "handled" | "continue", text = transformed_or_nil }1824 - ### 9.9 Extension Contexts 1186 + { messages = modified }1190 + { block = true, reason = "..." }1828 - - `ExtensionContext`: agent lifecycle, model, context, tools, config, logging.1829 - - `ExtensionCommandContext`: slash command args, selection, output, session.1830 - - `ExtensionUIContext`: selection, confirm, prompt, status, layout, widget APIs.1194 + All other return values MUST be ignored. The bridge MUST translate accepted returns into `AgentLoopConfig` hooks.1832 - The `ctx` table passed to event handlers, tool `execute`, and command handlers1196 + ### Extension contexts 1198 + The SDK MUST expose:1200 + - `ExtensionContext` for agent lifecycle, model, context, tools, config, and logging;1201 + - `ExtensionCommandContext` for slash-command arguments, selection, output, and session; and1202 + - `ExtensionUIContext` for selection, confirmation, prompt, status, layout, and widgets.1204 + Event handlers, tool `execute`, and command handlers MUST receive this context shape:1838 1209 notify = function(message, level) end, -- "info"|"success"|"error"|"warning" notify = function(message, level) end, -- "info"|"success"|"error"|"warning"1839 - confirm = function(title, message) end, -- -> bool1840 - select = function(title, items) end, -- -> chosen item1841 - input = function(title, placeholder) end, -- -> string1210 + confirm = function(title, message) end, -- -> bool1211 + select = function(title, items) end, -- -> chosen item1212 + input = function(title, placeholder) end, -- -> string1842 1213 set_status = function(key, text) end, set_status = function(key, text) end,1843 1214 set_widget = function(key, lines) end, set_widget = function(key, lines) end,1845 - session = { -- read-only1216 + session = { -- read-only1846 1217 id = "...", name = "...", id = "...", name = "...",1847 - entries = function() end, -- -> table1848 - entry_count = function() end, -- -> number1849 - branch = function() end, -- -> table1218 + entries = function() end, -- -> table1219 + entry_count = function() end, -- -> number1220 + branch = function() end, -- -> table1851 1222 model = { id = "...", provider = "..." }, model = { id = "...", provider = "..." },1852 - cwd = "/path/to/project",1223 + cwd = "/path/to/workspace",1853 1224 signal = AbortSignal, signal = AbortSignal,1854 1225 shutdown = function() end, shutdown = function() end,1860 - SDK namespaces include:1231 + `require("smith")` MUST expose:1868 - - `smith.command.*`,1869 - - `smith.provider.*`,1876 - - `smith.config.*` (read access; `smith.config.reload()` triggers §9.19),1877 - - `smith.secret.*` (`register(value, label)`, `list()` — labels/ids only,1878 - never plaintext; §6.7),1879 - - `smith.shortcut.*` (keyboard shortcut registration),1880 - - `smith.credentials.*` (`get(provider)`/`set(provider, value)` over the §7.41882 - - `smith.active_tools.*` (`get()`/`all()`/`set(names)`),1883 - - `smith.send_message(text, { deliver_as = "steer" | "followUp" })` and1884 - `smith.send_user_message(text)`,1886 - - `smith.shutdown()`,1239 + - `smith.command.*`;1240 + - `smith.provider.*`;1247 + - `smith.config.*`, with read access and `smith.config.reload()`;1248 + - `smith.secret.*`, including `register(value, label)` and `list()`; `list()` MUST expose only IDs and labels;1249 + - `smith.shortcut.*`;1250 + - `smith.credentials.*`, including `get(provider)` and `set(provider, value)` over auth storage;1251 + - `smith.active_tools.*`, including `get()`, `all()`, and `set(names)`;1252 + - `smith.send_message(text, { deliver_as = "steer" | "followUp" })`;1253 + - `smith.send_user_message(text)`;1255 + - `smith.shutdown()`; and1887 1256 - `smith.getContextUsage()`.- `smith.getContextUsage()`.1889 - Core registration shapes:1258 + Registration signatures MUST support:1892 1261 smith.tool.register({smith.tool.register({1893 1262 name = "my_tool", name = "my_tool",1894 1263 description = "shown to the LLM", description = "shown to the LLM",1895 - parameters = { --[[ JSON-schema table, validated per §5.3 ]] },1264 + parameters = { -- JSON Schema table1896 1266 execute = function(input, ctx) execute = function(input, ctx)1897 1267 return { content = { { type = "text", text = "..." } } } return { content = { { type = "text", text = "..." } } }1913 - `smith.provider.register(name, table)` merges into an existing provider or adds1914 - a new one. Merge rules: `base_url`/`api_key`/`api` override; `headers` merge1915 - per-key; `oauth` replaces whole; `models` merge by ID field-by-field (same1916 - rules recursively); omitted fields keep existing values; `replace_models =1917 - true` drops all existing models first. `smith.provider.unregister(name)` and1918 - `smith.provider.unregister_model(provider, model_id)` remove entries. All1919 - tables are validated against the §7.3 schema.1283 + Every tool parameter table MUST validate as JSON Schema.1921 - All public Lua SDK functions carry LuaLS/EmmyLua `---@` annotations. LuaLS is the1922 - canonical annotation dialect; no other dialect is supported. Every public binding1923 - declares, at minimum:1285 + ### Provider registration1925 - - `---@param` for each argument (name, type, description),1926 - - `---@return` for each result (type, description),1287 + `smith.provider.register(name, table)` MUST add a provider or merge an existing provider with these rules:1289 + - `base_url`, `api_key`, and `api` override prior values;1290 + - `headers` merge by key;1291 + - `oauth` replaces the entire prior value;1292 + - `models` merge by model ID, then recursively field by field under the same rules;1293 + - omitted fields retain prior values; and1294 + - `replace_models = true` removes existing models before applying new models.1296 + `smith.provider.unregister(name)` MUST remove one provider. `smith.provider.unregister_model(provider, model_id)` MUST remove one model. Every provider table MUST pass the bundled full schema.1298 + ### Public binding annotations1300 + Every public Lua SDK function MUST have LuaLS/EmmyLua `---@` annotations; LuaLS is the only supported annotation dialect. Each binding MUST declare:1302 + - `---@param` for every argument, with name, type, and description;1303 + - `---@return` for every result, with type and description; and1927 1304 - a `---@usage` block with a runnable example.- a `---@usage` block with a runnable example.1929 - Runtime argument schemas (used for validation) and generated docs both derive1930 - from these annotations, so annotations and runtime behavior stay in sync. The1931 - `xtask verify-docs` gate fails if any public binding lacks required annotations.1306 + Runtime argument schemas and generated documentation MUST derive from these annotations so runtime validation and documentation remain synchronized.1933 - ### 9.11 Built-in Plugins1308 + ### Built-in plugins and commands1935 - Built-ins are Lua plugins, not Rust special cases:1310 + Built-ins MUST be Lua plugins, not host-language feature special cases. They MUST provide:1937 - - tools: `read`, `write`, `edit`, `bash`, `find`, `grep`, `ls`,1938 - - slash commands: `/undo`, `/redo`, `/history`, `/tree`, `/reload-config`,1939 - `/secret` (§6.7), `/auth login <provider>` (§7.4 OAuth flow), `/model`1940 - (fuzzy picker over §5.7 resolver names), replay/time-travel,1943 - - default keybindings,1312 + - tools `read`, `write`, `edit`, `bash`, `find`, `grep`, and `ls`;1313 + - slash commands `/undo`, `/redo`, `/history`, `/tree`, `/reload-config`, `/secret`, `/auth login <provider>`, `/model`, and replay/time-travel commands;1315 + - default layout, keybindings, theme, and prompts.1947 - ### 9.12 Built-in Tool Specs1317 + `/model` MUST be a fuzzy picker over resolver names.1319 + ### Built-in tool contracts1949 1321 #### `read`#### `read`1954 - - `offset?: number`,1960 - - supports line windowing,1961 - - rejects binary content or returns explicit binary metadata,1962 - - output is bounded for LLM context.1329 + `read` MUST read text files, support line windows, bound output for LLM context, and either reject binary input or return explicit binary metadata.1964 1331 #### `write` #### `write`1969 - - `content: string`.1973 - - creates parent dirs as needed,1974 - - writes atomically with temp file + rename,1975 - - records VCS op when mutation succeeds.1338 + `write` MUST create missing parent directories, write atomically through temporary-file-plus-rename, and record a VCS operation after success.1977 1340 #### `edit` #### `edit`1344 + old_text: exact string1346 + allow_multiple?: bool1984 - - `allow_multiple?: bool`.1349 + Execution order and error codes are exact:1986 - Behavior (ordering is the contract):1988 - 1. read the file (`ENOENT`),1989 - 2. validate: non-empty `old_text`, non-binary content (`EEMPTY`, `EBINARY`),1990 - 3. count exact matches: zero fails; multiple fails unless `allow_multiple`1991 - (`ENOMATCH`, `EMULTI`),1992 - 4. re-read and hash immediately before write; fail if the file changed1994 - 5. write atomically via temp file + rename (`ELOCK`),1995 - 6. return change count and before/after hashes.1351 + 1. Read the file; missing file returns `ENOENT`.1352 + 2. Reject empty `old_text` with `EEMPTY` and binary content with `EBINARY`.1353 + 3. Count exact matches; zero returns `ENOMATCH`; multiple returns `EMULTI` unless `allow_multiple` is true.1354 + 4. Immediately before writing, re-read and hash; any change returns `ESTALE`.1355 + 5. Atomically write using temporary-file-plus-rename; locking/write conflict returns `ELOCK`.1356 + 6. Return replacement count and before/after hashes, then record the VCS operation.1997 1358 #### `bash` #### `bash`2001 - - `command: string`,2002 - - `timeout?: number`,1366 + `bash` MUST execute off the UI thread, capture stdout, stderr, and exit status, enforce timeout, include output-truncation metadata, and observe abort.1368 + #### `find`, `grep`, and `ls` 2007 - - executes subprocess on tool thread,2008 - - captures stdout/stderr/status,2010 - - records output truncation metadata,1370 + - `find` MUST honor gitignore-style files and return sorted paths subject to limits.1371 + - `grep` MUST support context lines, glob filters, case-insensitive matching, literal and regular-expression modes, and match limits.1372 + - `ls` MUST return alphabetically sorted entries, suffix directories, bound output, and return explicit errors.2015 - Uses `ignore` crate. Respects gitignore-style files. Returns sorted paths with2020 - Uses `grep`, `grep-regex`, and `grep-searcher`. Supports context lines, glob,2021 - case-insensitive search, literal/regex modes, match limits.2025 - Lists directory entries sorted alphabetically, with directory suffix, bounded2026 - output, and explicit errors.2030 - Smith uses jj internally for operation-level undo/redo/time travel, hidden2031 - behind `smith.vcs.*`, integrated with the `jj-lib` crate — no runtime2032 - dependency on a `jj` binary (prototype-decided, p26). Shell-out was rejected on2033 - the hot path: jj runs on every mutating tool, and a real `jj` invocation costs2034 - ~12.5 ms against ~0.003 ms for the same read in-process, so per-turn spawn2035 - overhead would accumulate for nothing. Embedding costs +186 crates over an2036 - empty baseline, but much of that tree — gix, regex, futures, serde — is already2037 - required by §2.3, and jj-lib builds on stable Rust (§2.3 records the pins that2038 - keep it there). The pre-1.0, monthly-moving jj-lib API is the price; the2039 - `smith.vcs.*` façade is what contains its churn, so an upgrade never reaches2044 - - actual `.jj` lives under `data_dir/smith/vcs/{project-hash}/jj-state`,2045 - - project root contains only `.jj` symlink,2046 - - colocated git repos rewrite jj `git_target` to absolute `.git` path.2048 - Plugins interact only through `smith.vcs.*`.2050 - `smith.vcs.*` exposes:1376 + The read-only API is exact:2055 1379 smith.vcs.status() -- { modified={}, added={}, deleted={}, renamed={} }smith.vcs.status() -- { modified={}, added={}, deleted={}, renamed={} }2062 1386 smith.vcs.evolog(rev) -- logical change evolutionsmith.vcs.evolog(rev) -- logical change evolution2065 - Mutations (explicit, validated inputs):1389 + The mutation API MUST accept explicit validated inputs:2068 1392 smith.vcs.commit(message)smith.vcs.commit(message)2077 1401 smith.vcs.workspace_add(name, opts)smith.vcs.workspace_add(name, opts)2080 - Lua receives stable smith-shaped tables; jj/gix implementation details never2081 - leak through this surface.1404 + Implementation-native details MUST remain hidden behind these Smith-shaped tables.2083 - `gix` is used only for targeted structured queries behind `smith.vcs.*`.1406 + ### Plugin sandbox and heap limits1408 + Local plugins are trusted but constrained to SDK capabilities. Raw `io`, `os`, and `debug` MUST be unavailable; filesystem/environment access MUST use the SDK. Version 1 MUST NOT implement path capabilities. Built-in and user plugins MUST receive identical APIs.2087 - Plugins are trusted but constrained to Smith SDK APIs:1410 + A plugin MAY declare `heap_limit` in bytes; configuration MAY override it and MUST win. Every plugin MUST own a separate Lua state and heap-limit domain. Shared-state per-plugin limits MUST NOT be offered.2089 - - no raw `io`, `os`, or `debug`,2090 - - filesystem/env access only through SDK,2091 - - no path capability system in v1,2092 - - built-in and user plugins use same API.1412 + The limit MUST be exact where the target supports enforcement. Exceeding it MUST be a recoverable plugin memory error. A target unable to enforce limits MUST loudly reject heap-limit configuration and MUST NOT silently apply zero or an ineffective limit.2094 - **Heap limit.** A plugin may be given a Lua heap limit via the optional2095 - `heap_limit` manifest field (§9.2) or config override; when both are set, the2096 - config override wins (§5.6 cascade: user config over plugin contributions).2097 - Prototype-proven (p10, p11) semantics:1414 + The limit MUST include the plugin Lua heap and host-created Lua values. Host allocations held on behalf of the plugin are outside that heap limit and MUST be bounded through whole-domain teardown. After out-of-memory, whole-domain replacement SHOULD be used rather than in-place retry.2099 - - The limit's domain is the plugin's own Lua state — one `mlua::Lua` per2100 - plugin (matching the §9.16 domain model). Per-plugin limits in a shared Lua2101 - state are not attributable and are not offered.2102 - - Enforcement is `Lua::set_memory_limit()`; under the locked vendored-LuaJIT2103 - feature set this enforces exactly, and breach surfaces as a recoverable2104 - memory error handled by the §9.17 error model. Targets where mlua reports2105 - memory control as unavailable must fail heap-limit configuration loudly,2106 - never enforce silently at zero; per-target enforcement is CI-verified.2107 - - The limit covers the plugin's Lua heap only, including host-created Lua2108 - values. Host-side Rust allocations held for a plugin are invisible to it2109 - and are bounded by domain teardown (§9.16) instead.2110 - - After a plugin OOM, the preferred recovery is whole-domain replacement2111 - (§9.16) rather than in-place retry.1416 + ### Dependency resolution2113 - ### 9.15 Dependency Resolution2115 - Plugins may declare dependencies on other plugins in their manifest2116 - (`dependencies`, §9.2). v1 resolves dependencies from already-available plugins2117 - only; there is no central registry and no network resolution.2119 - Each dependency entry names a plugin and a minimum API generation:1418 + A dependency MUST name a plugin and minimum Smith API generation:2122 1421 dependencies = {dependencies = {2127 - Resolution runs once per plugin set (built-in, global, project) after manifests2128 - load and before entry code runs:1426 + Version 1 MUST resolve only already-available plugins and MUST NOT perform network dependency resolution or semantic-version range solving.2130 - 1. Build the dependency graph from validated manifests.2131 - 2. Fail loading a plugin whose declared dependency is absent from the resolved2132 - set. The plugin is disabled with a diagnostic naming the missing dependency.2133 - 3. Fail loading a plugin whose dependency is present but supports a lower API2134 - generation than requested.2135 - 4. Detect cycles. A dependency cycle disables every plugin in the cycle with a2136 - diagnostic listing the cycle path. Smith never partially loads a cycle.2137 - 5. Load plugins in topological order so a dependency's registrations exist before2138 - its dependents run.1428 + After manifests load and before entry execution, each built-in, global, and workspace plugin set MUST be resolved by:2140 - v1 does not solve version ranges. `dependencies` express presence and API2141 - generation only. Semver range solving is deferred until a registry exists.2142 - Precedence (§9.7) still applies: a later plugin may override an earlier2143 - registration even across a dependency edge.1430 + 1. building a graph from validated manifests;1431 + 2. disabling a plugin with an absent dependency and reporting that dependency;1432 + 3. disabling a plugin whose dependency supports a lower API generation than requested;1433 + 4. detecting cycles, disabling every plugin in each cycle, reporting the complete path, and never partially loading it; and1434 + 5. loading topologically so dependency registrations exist before dependent entry code.2145 - ### 9.16 Plugin Hot-Reload1436 + Dependencies express only presence and API generation. Normal registration precedence MUST still apply, including overrides across dependency edges.2147 - Smith reloads a single plugin without restarting the process or losing the active2148 - session. Reload is whole-domain replacement, not in-place mutation.1438 + ### Plugin domains and hot reload2150 - **Plugin domain.** Each loaded plugin instance owns one reload domain. The domain2151 - owns all reloadable plugin state:1440 + A reload MUST replace a complete plugin domain, never mutate one in place. A domain MUST own:2153 - - the plugin's `mlua` runtime state and registry handles,2154 - - registered tool/ command/ provider/ shortcut/ interface descriptors, 2155 - - event subscriptions, including `smith.bus` subscriptions (§9.18), 2156 - - TUI layout/widget registrations and render caches,2157 - - host-side scratch allocations and any cancellation token for plugin tasks.1442 + - Lua runtime and registry handles;1443 + - tool, command, provider, shortcut, and interface registrations; 1444 + - event and `smith.bus` subscriptions; 1445 + - TUI layouts/widgets and render caches;1446 + - host scratch allocations; and1447 + - cancellation tokens for plugin tasks.2159 - Nothing plugin-owned may outlive its domain. Registrations are keyed by domain2160 - generation so teardown removes them deterministically. A callback, task, or2161 - subscription that escapes its domain is a reload defect; the loader rejects2162 - registrations that cannot be tied to the domain.1449 + Nothing plugin-owned may outlive its domain. Every registration MUST be keyed by domain generation; registrations that cannot be tied to a domain MUST be rejected. Raw callback handles MUST remain only in the generation-keyed registry. Every dispatch MUST verify the active generation before entering Lua. An inactive generation MUST be rejected diagnostically and MUST NOT begin execution. The loader MUST audit for escaped registrations associated with inactive generations.2164 - **Callback discipline** (prototype-proven, p11): plugin callbacks are reachable2165 - exclusively through the generation-keyed registry. The host never clones or2166 - stashes a raw callback handle outside it — invoking a raw `mlua` function after2167 - its domain dropped is an unrecoverable panic, not a catchable error. Every2168 - dispatch path (hook, tool, command, bus) checks the callback's domain generation2169 - against the active set before touching any Lua value; stale generations are2170 - rejected with a diagnostic and the callback does not run. An audit sweep over2171 - the registries (anything registered under a non-active generation) is the2172 - loader's escape-detection mechanism.1451 + Reload MUST be requestable by:2174 - **Triggers.** Reload is requested by:1453 + - `smith plugins reload <org>/<name>`;1454 + - workspace-local file change when watch reload is enabled; and1455 + - reinstallation of a loaded plugin.2176 - - the `smith plugins reload <org>/<name>` CLI/command path,2177 - - a project plugin file change when watch-reload is enabled in config,2178 - - reinstall of an already-loaded plugin.1457 + Built-in `smith/*` plugins MUST use the same mechanism.2180 - Built-in `smith/*` plugins reload by the same mechanism.1459 + For plugin `P` with active domain `D` and candidate `D'`, reload MUST:2182 - **Sequence.** For a reload of plugin `P`:1461 + 1. construct `D'` and validate/load its manifest, entry, and registrations in isolation;1462 + 2. on failure, drop `D'`, retain `D`, and report the error;1463 + 3. on success, atomically replace registrations and subscriptions with `D'`, mark `D` retired, and activate `D'`; and1464 + 4. drop `D` after its allowed in-flight work and deferred bus dispatch complete, tearing down its Lua state, registrations, subscriptions, caches, and scratch memory.2184 - 1. Construct a new domain `D'` and load `P`'s manifest and entry code into it.2185 - 2. If load or registration fails, drop `D'` and keep the old domain `D` active.2186 - The old plugin keeps running. Reload reports failure with the load error.2187 - 3. On success, atomically swap `D'` in for `D`: new registrations replace old,2188 - subscriptions transfer to `D'`, then drop `D`.2189 - 4. Dropping `D` tears down its Lua state, registrations, subscriptions, caches,2190 - and scratch memory. Repeated reloads must plateau in live memory after2191 - warmup; no stale callback from `D` may run after the swap. The plateau is2192 - the enforceable observable — an instantaneous RSS decrease per teardown is2193 - not required, since small freed heaps are legitimately retained by the2194 - allocator for reuse (p11 evidence, `prototypes/PLAN.md`).1466 + Reload MUST be all-or-nothing. Failure MUST leave the old domain and bindings active and no candidate state. Repeated reloads MUST plateau in live memory after warmup; immediate RSS reduction is not required.2196 - **Rollback.** Reload is all-or-nothing. Either `D'` fully replaces `D`, or `D`2197 - remains and no partial state from `D'` survives. A failed reload never leaves the2198 - plugin unregistered.1468 + Domain teardown MUST wait for an executing Lua callback; Lua MUST NOT be preempted. A bus handler follows the condemned/deferred rules below. A tool invocation already running under `D` MUST finish under its pinned domain and deliver its result; invocations begun after swap MUST use `D'`. No new stale callback may begin after swap.2200 - **In-flight hooks.** Teardown cannot preempt Lua (§12): dropping `D` waits2201 - for `D`'s currently executing hook to finish; a hook in flight during a bus2202 - dispatch follows the §9.18 condemned/deferred rule (p15, p23).1470 + Reload MUST preserve session identity/entries, agent state, and other plugin domains. If `P` backs an interface, candidate binding and conformance MUST be revalidated before commit. Existing interface views MUST transparently dispatch their next call to `D'`. Conformance failure MUST roll back. Dependents MUST NOT reload; stable names MUST rebind, and a removed registration MUST produce a normal missing-registration error on next use.2204 - **Session continuity.** Reload does not reset the session. Session entries, agent2205 - state, and other plugins' state are untouched. In-flight tool executions from the2206 - old domain run to completion under `D`; their results are still delivered. New2207 - invocations after the swap use `D'`.2209 - **Interface bindings.** If the reloaded plugin backs an interface binding2210 - (§9.6), the swap re-resolves the binding to `D'` and re-runs bind-time2211 - conformance against it. Consumers' interface views rebind transparently — the2212 - next call through a view dispatches into `D'`. A conformance failure is a2213 - reload failure: rollback keeps `D` and its binding active.1474 + Every plugin error MUST include plugin name and phase and MUST NOT corrupt the host, terminal, or another plugin.2215 - **Dependents.** Reloading `P` does not reload its dependents (§9.15). Dependents2216 - keep their handles to `P`'s registrations by stable name; the swap rebinds those2217 - names to `D'`. A reload that removes a registration a dependent relies on surfaces2218 - as a normal missing-registration error at next use, not a crash.1476 + - **Manifest/validation:** invalid name/version, unsupported `smith_api`, or missing/cyclic dependency MUST disable the plugin, list the reason in `smith plugins`, and allow unrelated plugins to load.1477 + - **Entry load:** Lua failure or invalid collected registration MUST discard all partial registrations and disable the plugin. During reload, the old domain MUST remain active.1478 + - **Event handler:** the host MUST catch and log through `smith.log`; treat the return as absent; continue other handlers. For blocking events, failure means no decision and MUST NOT block.1479 + - **Tool execute:** a Lua error or returned tool error MUST become a normal error tool result; host and loop MUST continue.1480 + - **Bus handler:** the host MUST catch/log and continue later subscribers.1481 + - **Out of memory:** the host MUST report a recoverable memory error and MAY replace the domain.2220 - ### 9.17 Plugin Error Model1483 + Host library code MUST NOT panic on plugin input.2222 - Plugin faults are isolated. A plugin error never corrupts the host, the terminal,2223 - or another plugin. Errors are classified by phase:1485 + ### Inter-plugin bus2225 - - **Manifest/validation error** (bad name, bad version, unsupported `smith_api`,2226 - missing/cyclic dependency): the plugin does not load. It is disabled and listed2227 - by `smith plugins` with the reason. Other plugins load normally.2228 - - **Entry-load error** (Lua error while running entry code or collecting2229 - registrations): the plugin's partial registrations are discarded, the plugin is2230 - disabled with the error, and loading continues for the rest of the set. On2231 - reload (§9.16) this is a failed reload and the old domain is kept.2232 - - **Event-handler error** (Lua error inside a subscribed handler): the error is2233 - caught, logged through `smith.log`, and the handler's result is treated as2234 - absent. A non-blocking event proceeds; a blocking event (e.g. `tool_call`) is2235 - treated as no decision — it does not block. One handler's failure never2236 - prevents other handlers for the same event from running.2237 - - **Tool-execute error** (Lua error or returned error inside a plugin tool): it2238 - surfaces to the agent as a normal tool error result, not a host crash. The2239 - agent loop continues and the model may react to the error.2240 - - **Bus-handler error** (§9.18): same isolation as event-handler errors — caught,2241 - logged, other subscribers still run.2243 - Host library code never panics on plugin input (PROJECT-INVARIANTS §3.5). Plugin2244 - errors carry the plugin name and phase so `smith plugins` and logs attribute them2247 - ### 9.18 Inter-Plugin Messaging Bus2249 - `smith.bus.*` is a namespaced publish/subscribe channel for plugin-defined2250 - messages. It is separate from core lifecycle events (§9.8): the bus carries custom2251 - plugin topics, not engine events, and plugins cannot emit core event types on it.1487 + `smith.bus.*` is the only sanctioned direct plugin-to-plugin messaging channel. It MUST remain separate from lifecycle events, and plugins MUST NOT emit core event types through it.2256 - -- Subscribe to a topic. Returns a handle usable to unsubscribe.
2257 1490 local handle = smith.bus.on("acme/index-ready", function(payload, ctx)local handle = smith.bus.on("acme/index-ready", function(payload, ctx)2258 1491 ctx.ui.notify("index has " .. payload.count .. " files", "info") ctx.ui.notify("index has " .. payload.count .. " files", "info")2261 - -- Publish to a topic. Delivers to all current subscribers.
2262 1494 smith.bus.emit("acme/index-ready", { count = 128 })smith.bus.emit("acme/index-ready", { count = 128 })2265 1495 smith.bus.off(handle)smith.bus.off(handle)2270 - - **Topic names are namespaced** `<org>/<topic>`, using the same character set as2271 - plugin names (§9.2). A plugin may emit any topic; convention is to emit under2272 - its own `org`. `smith/*` topics are reserved for built-in plugins.2273 - - **Payloads are plain Lua data tables** — the same value shape passed across the2274 - SDK boundary. No functions, userdata, or host handles cross the bus.2275 - - **Delivery is synchronous, in registration order,** on the plugin thread2276 - (§12) within the current tick. Emitting during delivery enqueues to ONE2277 - global FIFO — regardless of topic — delivered strictly after the current2278 - dispatch completes in emit order; the bus never re-enters2279 - (prototype-proven, p23: max dispatch depth 1).2280 - - **Teardown during dispatch** (§9.16 interaction, p23): a domain torn down2281 - mid-dispatch is condemned immediately — its remaining deliveries in the2282 - current dispatch are skipped with a diagnostic — and the actual drop is2283 - deferred until the dispatch queue drains. A handler may therefore safely2284 - request its own domain's teardown and complete normally.2285 - - **Subscriptions are domain-owned** (§9.16). A subscription is dropped when its2286 - plugin's domain is torn down on reload or unload, so no stale subscriber2288 - - **A subscriber error is isolated** (§9.17): caught, logged, remaining2289 - subscribers still receive the message.2290 - - **No delivery guarantee across load order:** a message emitted before a2291 - subscriber loads is not replayed. The bus is fire-and-forget, not a queue.1500 + - Topics MUST use `<org>/<topic>` and the plugin-name character set. `smith/*` is reserved for built-ins. A plugin MAY emit any nonreserved topic; its own organization is conventional.1501 + - Payloads MUST be top-level plain Lua data tables. Functions, userdata, and host handles MUST NOT cross the bus.1502 + - Delivery MUST be synchronous, on the plugin thread, in subscriber-registration order within the current tick.1503 + - An emit during delivery MUST enter one global FIFO regardless of topic and run only after the current dispatch, in emit order.1504 + - The bus MUST never re-enter; maximum dispatch depth is `1`.1505 + - If teardown is requested during dispatch, the domain MUST be condemned immediately. Remaining deliveries to it MUST be skipped with a diagnostic; actual drop MUST wait until the entire dispatch FIFO drains.1506 + - A handler MAY request its own teardown and MUST finish normally.1507 + - Subscriptions MUST be domain-owned and removed on unload/reload; stale subscribers MUST not survive.1508 + - Subscriber errors MUST not prevent later subscribers.1509 + - Messages emitted before subscriber load MUST not replay. The bus is fire-and-forget, not durable.2293 - The bus is the only sanctioned direct plugin-to-plugin channel. Plugins otherwise2294 - compose through shared tool/command/provider registries and the core event1511 + Plugins MAY also compose through stable registries and the core event bridge. 2297 - ### 9.19 Host Configuration Reload 1513 + ### Runtime configuration reload 2299 - Smith reloads its own configuration at runtime without restarting the process or2300 - losing the active session. Host reload follows the same contract shape as plugin2301 - reload (§9.16): validate fully, swap atomically, roll back on failure.1515 + Reload MUST preserve the process and active session and use validate-then-atomic-swap semantics. It MUST re-evaluate layers 1–4. Layer-5 CLI flags are resolved once, MUST remain unchanged, and MUST continue to override the candidate.2303 - **Scope.** A host reload re-evaluates config cascade layers 1–4 (§5.6). CLI2304 - flags (layer 5) are per-invocation: resolved at process start, they continue to2305 - override the reloaded layers unchanged.1517 + Reload triggers are:2307 - **Triggers.** Reload is requested by:1520 + - `smith.config.reload()`;1521 + - `config_dir/config.lua` change when config watch reload is enabled;1522 + - RPC `config/reload`; and1523 + - automatic cascade re-evaluation after every plugin reload, whether or not layer-3 contributions changed.2309 - - the built-in `/reload-config` slash command (§9.11), a Lua plugin calling the2310 - `smith.config.reload()` primitive (§9.10),2311 - - a change to `config_dir/smith/config.lua` when watch-reload is enabled in2312 - config (same setting family as plugin watch-reload, §9.16),2313 - - a plugin reload (§9.16), which may change layer-3 contributions; after the2314 - domain swap the cascade is re-evaluated automatically,2315 - - in RPC mode (§10.2), the `config/reload` JSON-RPC method. The response reports2316 - success with the changed key paths, or the validation failure verbatim.1525 + `config/reload` MUST return success with changed paths or the validation failure verbatim. Eval mode MUST read configuration at startup and MUST NOT expose runtime reload.2318 - Eval mode reads config at startup and has no runtime reload trigger.1527 + Reload order is exact:2320 - **Sequence.** For a host reload:1529 + 1. Evaluate the cascade into a candidate.1530 + 2. Validate every value against host schemas.1531 + 3. Validate the complete alias/group/bucket graph, not only the active chain.1532 + 4. If any step fails, report all failures together with exact key paths, discard the candidate, retain active configuration, and permit a later retry.1533 + 5. Atomically activate a valid candidate.1534 + 6. Apply theme, keybindings, active tool set, then resolved model/provider, in that order.1535 + 7. Re-render the TUI with the new theme on the next frame.1536 + 8. Emit `config_changed` with changed paths and no secrets.2322 - 1. Re-evaluate the cascade into a candidate config. Validate every value against2323 - the Rust schemas, and re-run model resolution (§5.7) as whole-graph2324 - validation — every alias/group/bucket, not just the active model's chain2325 - (p16: a concrete CLI model otherwise masks a latent alias cycle into the2327 - 2. If evaluation, validation, or resolution fails, discard the candidate and2328 - keep the active config. ALL failures are reported together, each with its2329 - exact key path; nothing partially applies, and a later valid reload is2331 - 3. On success, atomically swap the candidate in as the active config.2332 - 4. Apply effects in order: theme, keybindings, active tool set, resolved2333 - model/provider. TUI re-renders with the new theme on the next frame.2334 - 5. Emit the `config_changed` plugin event (§9.8) carrying the changed key2335 - paths. Plugins read the new values through their contexts (§9.9); the2336 - event does not carry secrets. Diff rules (prototype-proven, p16): the2337 - diff is computed over the post-CLI *effective* config (a CLI-masked2338 - change is not reported); list-valued keys diff as one path; added and2339 - removed keys count as changed paths; an idempotent reload emits the2340 - event with an empty path list.1538 + Changed-path calculation MUST compare effective post-CLI configuration, omit changes masked by CLI values, treat a list-valued key as one path, include additions/removals, and emit an empty list for an idempotent reload.2342 - **Continuity.** Reload is invisible to in-flight work:1540 + An in-flight turn MUST retain the model, tools, and system prompt captured at its start; the next turn MUST use new values. Running tools MUST finish with old values. Session identity, entries, and plugin domains MUST remain unchanged. Configuration reload MUST NOT load, unload, or reload plugin code.2344 - - an in-flight agent turn keeps the resolved model, tools, and system prompt it2345 - started with; the next turn uses the new config,2346 - - running tool executions complete under the old values,2347 - - the session, its entries, and plugin domains are untouched — a config reload2348 - never loads, unloads, or reloads plugin code.1542 + The following are fixed for process lifetime and MUST NOT hot-reload:2350 - **Restart-only.** The following are fixed for the process lifetime and never1545 + - config, data, and cache directory locations;1546 + - active session identity and storage paths;1547 + - run mode: interactive, eval, or RPC; and1548 + - bundled `providers.json`.2353 - - CLI flags (layer 5),2354 - - config/data/cache directory locations (§4),2355 - - the active session identity and storage paths,2356 - - the run mode (interactive, eval, RPC),2357 - - the bundled `providers.json` (§7.3) — runtime provider changes go through2358 - `smith.provider.*` plugin overrides, not registry reload.1550 + Runtime provider changes MUST use `smith.provider.*`. Credential resolution MUST NOT be cached across reload; the next provider stream MUST resolve from the new effective configuration and auth sources.2360 - Credential resolution (§7.4) is not cached across reloads: the next provider2361 - stream after a reload resolves auth against the new config values.2363 - ## 10. CLI Crate: `smith-cli` 2365 - Binary name: `smith`.1556 + The executable MUST be `smith`. Global options are exact:2367 - ### 10.1 Global Flags 1560 + --provider <provider>1561 + --session <id-or-name>2370 - - `--provider <provider>`2371 - - `--session <id-or-name>`1566 + Commands and behavior are:1568 + - `smith` MUST start the interactive TUI in a new automatically named session.1569 + - `smith new <name>` MUST start a new named interactive session.1570 + - `smith attach [id-or-name]` MUST attach to that session; no argument MUST open fuzzy selection.1571 + - `smith continue` MUST continue the latest current-working-directory session.1572 + - `smith resume` MUST fuzzy-select among sessions in the current working directory.1573 + - `smith session list [--cwd]` MUST list sessions.1574 + - `smith session dump [id] [--last N] [--output path]` MUST write JSONL.1575 + - `smith plugins` MUST list every plugin, including disabled plugins and each reason.1576 + - `smith plugins reload <org>/<name>` MUST atomically reload one loaded plugin.1577 + - `smith install <plugin> [--force]` MUST install a local-path or Git-source plugin under the installation contract.1578 + - `smith uninstall <plugin> [--purge-data]` MUST uninstall under the retention contract.1579 + - `smith eval <prompt> [--json] [--session id]` MUST run non-interactive evaluation.1580 + - `smith rpc` MUST run JSON-RPC 2.0 over stdin/stdout and include `config/reload`.1581 + - `smith completions <shell>` MUST generate completions for the requested shell.1582 + - `smith help [topic] [--search q] [--list] [--examples] [--example name] [--guide name]` MUST select help, search, listing, examples, and guides. Dotted function addressing is required: `smith help tool.register` resolves `register` under `tool`.1583 + - `smith replay <session> [--speed f64] [--compare] [--sandbox path] [--turns N] [--from-turn N] [--format text|json|summary] [--continue-on-diff bool]` MUST apply the selected replay controls.1585 + Interactive slash commands MUST be registered by Lua plugins and MUST NOT be binary subcommands.2379 - - `smith` starts interactive TUI with new auto-named session.1587 + The entrypoint MUST parse CLI input, resolve configuration, create `Harness`, and dispatch to interactive, eval, RPC, replay, session, plugin, or help handling. Errors and signals MUST restore terminal state. Fatal commands MUST diagnose and exit nonzero.1589 + ### RPC projection model 2383 - - `smith new <name>` — new named interactive session.2384 - - `smith attach [id-or-name]` — attach; fuzzy select if no arg.2385 - - `smith continue` — continue last session in cwd.2386 - - `smith resume` — fuzzy select session in cwd.2387 - - `smith session list [--cwd]` — list sessions.2388 - - `smith session dump [id] [--last N] [--output path]` — JSONL dump.2389 - - `smith plugins` — list plugins, including disabled plugins with their reason.2390 - - `smith plugins reload <org>/<name>` — reload a single loaded plugin (§9.16).2391 - - `smith install <plugin>` — install plugin.2392 - - `smith uninstall <plugin>` — uninstall plugin.2393 - - `smith eval <prompt> [--json] [--session id]` — non-interactive eval.2394 - - `smith rpc` — JSON-RPC 2.0 over stdio; `config/reload` (§9.19) is one method,2395 - the projection rule is §10.4.2396 - - `smith completions <shell>` — generate shell completions (`clap_complete`).2397 - - `smith help [topic] [--search q] [--list] [--examples] [--example name] [--guide name]`.2398 - Topics support dotted function addressing: `smith help tool.register`2399 - resolves the `register` entry within the `tool` topic.2400 - - `smith replay <session> [--speed f64] [--compare] [--sandbox path]2401 - [--turns N] [--from-turn N] [--format text|json|summary] [--continue-on-diff bool]`.1591 + `smith rpc` MUST expose JSON-RPC 2.0 bidirectionally over standard input/output. Its catalog MUST be a structural projection of the Lua SDK, not a direct mirror. Every surface has independent origin (SDK-mirrored or RPC-only) and shape (data request/response, callback, or notification).2403 - Interactive slash commands are registered by Lua plugins, not clap subcommands.1593 + These data/configuration surfaces MUST project as client request to server response methods:2407 - `main` uses tokio, parses clap, resolves config, creates `Harness`, dispatches to2408 - interactive/eval/rpc/replay/session/plugin/help command handlers.1616 + Callback-bearing APIs MUST invert direction:2410 - `smith-cli` restores terminal state on errors and signals.1618 + - `tool.register`, including `execute`;1619 + - command handlers and autocomplete callbacks; and1620 + - `bus.on` callbacks.2412 - ### 10.4 RPC Method Projection 1622 + Registration originates client-to-server. Invocation MUST be a server-to-client JSON-RPC request whose reply is awaited. Other non-callback operations in a projected callback namespace MAY remain ordinary client-to-server requests. Callback registration therefore requires bidirectional RPC.2414 - The `smith rpc` catalog is not a mirror of the Lua SDK (§9.10) — projecting2415 - the SDK onto JSON-RPC is a structural transform, prototype-proven (p24), and2416 - the method list is derived from it rather than enumerated here. Two2417 - independent axes classify each surface: *origin* (mirrored from §9.10 vs an2418 - RPC-only addition) and *shape* (data request/response, callback, or1624 + Headless RPC MUST omit Lua-runtime-only `tui` and `shortcut` surfaces because it has no terminal or keyboard.2421 - - **Data and config-mutation namespaces mirror** as request→response methods:2422 - `fs`, `search`, `env`, `time`, `log`, `provider`, `alias`, `group`,2423 - `bucket`, `vcs`, `config`, `secret`, `active_tools`, `credentials`,2424 - `send_message`, `abort`, `shutdown`, `getContextUsage`.2425 - - **Callback-taking functions invert direction.** `tool.register` (its2426 - `execute`), `command` handlers/autocomplete, and `bus.on` cannot travel as2427 - data; registering one means the engine issues a server→client REQUEST to2428 - run the client's handler and awaits the reply. RPC that registers behavior2429 - is therefore bidirectional, not a one-way call.2430 - - **Events (§9.8) are server→client notifications** — except blocking events2431 - (`tool_call`, `session_before_*`), which are server→client REQUESTS so the2432 - client can answer block/allow/replace. A pure observer client that2433 - registers nothing still needs the reverse channel for these.2434 - - **A driver namespace has no §9.10 origin** and is RPC-only: `session/open`,2435 - `session/attach`, `session/list`, `session/dump`, `session/snapshot`,2436 - `session/fork`, `session/subscribe`, `prompt/submit`, `command/run`. Lua2437 - never needs these because a plugin already runs inside a live session; an RPC2438 - client must drive one from outside. `session/dump` returns persisted state2439 - (transcript, tree, leaf, folds); `session/snapshot` returns the *ephemeral*2440 - process state a live tail cannot replay — the steering/follow-up queue2441 - (§6.1) and in-flight run status — which a mid-session attach needs and which2442 - is never a session entry (prototype-proven, p28).2443 - - **Lua-runtime-only surfaces are omitted** in headless RPC: `tui`,2444 - `shortcut` (no terminal, no keyboard).1626 + ### RPC-only driver methods 2446 - Framing (line-delimited JSON vs `Content-Length`) is an implementation choice2447 - settled when `smith rpc` is built.1628 + External clients MUST receive these RPC-only methods:2449 - **RPC is the multi-frontend boundary.** An RPC client is a frontend peer of the2450 - built-in TUI (§8), so its event surface is an adapter over the `EngineEvent`2451 - stream (§6.3) — the same source the TUI consumes — not the plugin bridge2452 - (§9.8). It is an adapter, not a mirror, by three rules: non-blocking events2453 - project to notifications; blocking events (`tool_call`, `session_before_*`)2454 - project to server→client requests the client answers; and frontend-private2455 - `EngineEvent` variants (panel toggle, resize, selection/focus/scroll) are2456 - omitted. Prototype-proven sufficient for a full alternative UI (p28: a headless2457 - client reconstructed transcript, tools, steering queue, tree/leaf, model, cost,2458 - fold, and secret placeholders from the wire alone), subject to:2460 - - two notification payload guarantees the reconstruction depends on —2461 - `session_compact` carries the covered span `{summary_id, start, end}` (the2462 - fold is assembly-time and storage-invisible, §6.9), and `session_tree`2463 - carries `{id, parent, kind}` plus the leaf (branches are emergent, §6.5);2464 - - `session/snapshot` for mid-session attach, since the live notification tail2465 - has no replay and the steering queue + run status are ephemeral (above);2466 - - cost/context is poll-only via `getContextUsage` in v1 (no push event); a2467 - `context_usage` notification may be added if a live indicator warrants it.1642 + `session/dump` MUST return persisted transcript, tree, current leaf, and fold state, with secret registration plaintext redacted. `session/snapshot` MUST return ephemeral queue state and in-flight run status needed for mid-session attachment; this state MUST NOT be persisted as a session entry.2469 - Secret plaintext never crosses the wire — only `smith:sec:N` placeholders and2470 - their labels (§6.7), tap-verified in p28.1644 + ### RPC frontend event boundary 2472 - ## 11. Security Model 1646 + RPC MUST be a peer frontend to the TUI. Its event stream MUST adapt the same `EngineEvent` stream, not dispatch through the Lua plugin bridge. Public event names and hook responses MAY project the equivalent plugin-event vocabulary, but their source of truth MUST remain `EngineEvent` and core hooks.1648 + Nonblocking events MUST be server-to-client notifications. Blocking `tool_call` and `session_before_*` events MUST be server-to-client requests accepting allow/block/replace responses according to their hook contracts. Even an observer that registers no behavior MUST support this reverse request channel and return a neutral response.2480 - - session/config/cache files.1650 + Frontend-private events for panel toggling, resizing, selection, focus, and scrolling MUST be omitted.1652 + The wire MUST let a headless frontend reconstruct transcript, tools, combined steering/follow-up queue, conversation tree/current leaf, model, cost, folds, and secret placeholders, with these exact rules:2485 - - provider network response content.1654 + - `session_compact` notifications MUST contain `covered_span: { summary_id, start, end }`. Folds are assembled at runtime and raw persisted entries remain unchanged.1655 + - `session_tree` notifications MUST contain `{ id, parent, kind }` records and the current leaf; branches remain emergent.1656 + - Mid-session attachment MUST use `session/snapshot`; notifications have no replay and omit reconstructible prior ephemeral state.1657 + - Cost/context usage MUST be polling-only through `getContextUsage` in version 1. No push event is required; a future `context_usage` notification is permitted.2487 - Security mechanisms:1659 + Secret plaintext MUST never cross RPC. Only `smith:sec:N` placeholders and labels/IDs MAY cross.2489 - 1. Tool registry (§6.10) controls which tools the LLM can invoke.2490 - 2. Secret proxy (§6.7) prevents real secrets from reaching LLM context.2491 - 3. Restricted Lua runtime (§5.5) removes raw OS/file APIs.2492 - 4. Users configure active tools; no confirmation-dialog security theater.1661 + RPC transport framing is intentionally selectable: line-delimited JSON and `Content-Length` framing are both permitted.2494 - Credential storage follows §7.4: plaintext, no keychain, no encryption.2496 - ## 12. Concurrency and Async 1667 + Smith MUST treat the local user, operating system, filesystem, local plugins, Smith code, and local session/configuration/cache files as trusted. It MUST treat the remote LLM and provider network-response content as untrusted. Provider/LLM response data is the only untrusted content domain in the version-1 product model.2500 - - engine/main: owns harness event loop and agent state,2501 - - UI thread: render/event polling, never blocks engine,2502 - - tool thread pool: subprocess/file/plugin tool execution,2503 - - provider async tasks: streaming HTTP,2504 - - **plugin thread**: one dedicated OS thread owns every plugin's `mlua`2505 - state (states are `!Send`; the mlua `send` feature is never enabled).2506 - Lua values never cross a thread boundary; states are created on this2507 - thread and dropped on it (prototype-proven, p15).1669 + ### Required controls 2509 - Plugin dispatch (prototype-proven, p15 — hook round-trip median 81µs):2510 - hook, bus, and plugin-callback dispatch is a channel actor. The engine2511 - sends a plain-data request and awaits a reply; requests execute serially2512 - in arrival order across ALL plugins; only plain data crosses the boundary.2513 - This is the thread §9.18's delivery rules run on.1671 + 1. `ToolRegistry` MUST determine which tools the LLM may invoke.1672 + 2. The secret proxy MUST prevent registered plaintext secrets from entering LLM context, traces, public events, or RPC.1673 + 3. Restricted Lua MUST expose no raw operating-system or filesystem APIs.1674 + 4. Users MUST configure active tools. Confirmation dialogs MUST NOT be treated as a security boundary.1675 + 5. Credentials MUST remain plaintext in permitted local storage, with no keychain integration or encryption.1677 + The plugin sandbox is a constrained product API, not a hostile-code security boundary. Version 1 MUST NOT perform heuristic secret discovery in core and MUST NOT implement filesystem path capabilities.2517 - - `tokio` in `smith-ai`, `smith-core`, and harness orchestration,2518 - - TUI rendering is sync on UI thread,2519 - - tool execution runs off the UI thread.1681 + ### Execution domains 2523 - - UI keypress acknowledged within 16ms — unaffected by plugin CPU (p15:2524 - a hostile 200ms hook left the UI heartbeat under 6ms),2525 - - engine never blocks on UI,2526 - - every long operation observes abort, with one proven carve-out:2527 - **in-flight Lua execution cannot be preempted** (LuaJIT has no usable2528 - interrupt; debug hooks do not fire inside compiled traces). Abort2529 - abandons the pending hook *dispatch* — the engine drops the reply and2530 - continues; the hook runs to completion and its late reply is discarded.2531 - Hard cancellation of runaway Lua is domain teardown (§9.16), never2532 - in-place interruption.1683 + - The engine/main domain MUST own the harness event loop and agent state.1684 + - The UI side MUST render and poll input without blocking the engine. Rendering MUST remain synchronous on the UI render thread; blocking terminal polling MUST use its dedicated poller thread and channels.1685 + - A tool thread pool MUST execute subprocess, file, and host-side plugin-tool work off the UI thread. Lua portions MUST dispatch to the plugin actor rather than move Lua values to the pool.1686 + - Provider HTTP streaming MUST use asynchronous tasks.1687 + - One dedicated operating-system plugin thread MUST own every plugin Lua state. Lua states MUST be created and dropped there; Lua values MUST never cross a thread boundary.2534 - Hook budget (soft, since preemption is impossible): a hook blocks only its2535 - dispatching turn plus queued plugin dispatches (head-of-line — all plugins2536 - share the one plugin thread); it never blocks the engine runtime, UI, or2537 - tool pool. A hook exceeding the configured soft deadline is reported as a2538 - plugin diagnostic (§9.17), not killed.2540 - ## 13. Performance Requirements 1691 + Hooks, bus calls, and plugin callbacks MUST use channel-actor dispatch:2542 - - Release binary < 20MB stripped.2543 - - `smith --help` < 100ms.2544 - - TUI frame draw < 2ms within 16ms frame budget.2545 - - Session encode 1000 entries < 5ms.2546 - - Agent loop turn target < 30s excluding provider/network stalls beyond timeout.2547 - - Bench regressions fail nightly/release gates (thresholds in §17.9).1693 + - The engine sends a plain-data request and awaits asynchronously.1694 + - Only plain data may cross the boundary.1695 + - Requests MUST execute serially in arrival order across all plugins.1696 + - Bus ordering and domain-generation rules MUST execute on this thread.2549 - ### 13.1 Compile-Time Budget 1698 + ### Responsiveness and cancellation 2551 - Compile time is budgeted on two distinct axes, because they answer different1700 + A UI keypress MUST be acknowledged within 16 ms, including while plugin CPU work runs. The engine MUST never synchronously block the UI.2554 - - **Incremental rebuild is the governing dev/agent metric.** After a one-crate2555 - edit, the rebuild recompiles that crate and its reverse-dependency closure2556 - only — never an unrelated leaf crate or its heavy dependency tree. This is a2557 - structural guarantee of the workspace split + dependency siloing2558 - (PROJECT-INVARIANTS §11), not just a time target; the edit→check loop that2559 - dominates agent and dev work depends on it.2560 - - **Cold build and crate count are a CI-cost sub-budget.** The full transitive2561 - tree (mlua/LuaJIT, jj-lib, gix, reqwest+tokio, aws-lc/TLS, syntastica) is2562 - paid once and cached; the gate is on *regression* — a dependency change that2563 - materially grows cold build or crate count fails CI the same way a2564 - binary-size or bench regression does. Exact thresholds are set from the2565 - first real full-workspace build.1702 + Every long-running operation MUST observe abort except already executing Lua. Lua cannot be preempted. On abort, the engine MUST abandon a pending hook dispatch, drop its reply receiver, and continue; Lua may finish, and its late reply MUST be discarded. Any hard cancellation of runaway Lua MUST occur only by whole-domain teardown, never in-place interruption, and normal teardown MUST wait for currently executing Lua.2567 - A single TLS backend is shared across `reqwest` and `gix` rather than shipping1704 + Hook deadlines are soft. A hook MAY block only its own dispatching turn and queued plugin dispatches; the shared plugin thread creates head-of-line blocking only inside plugin dispatch. It MUST NOT block the UI, tool pool, or engine runtime. Exceeding the configured soft deadline MUST produce a plugin diagnostic and MUST NOT kill the hook.2570 - ### 13.2 Memory Policy 2572 - Prototype-proven against the measured session corpus (p09; see2573 - `docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):1708 + The product MUST satisfy:2575 - - **Session discovery is lazy and metadata-only.** Discovery reads session2576 - headers, never full bodies: O(session count), not O(corpus bytes).2577 - - **Virtual scroll materializes at most viewport rows per frame.** Row2578 - formatting stops at the visible window (lazy wrap); a single multi-MiB2579 - message must not be fully formatted to render its visible slice.2580 - - **Arenas are scratch-only.** `bumpalo` is permitted solely for phase-local2581 - render/request scratch in measured hot paths. Persisted and session data use2582 - stable IDs and owned strings — never arena references. No custom or unsafe2583 - arena code. Arena references never cross async, thread, or persistence2585 - - **Keep/drop gates for arena use** weigh allocator-call pressure, elapsed2586 - time, and peak/plateau stability — not allocation count alone. Render-frame2587 - scratch is a clear win; request-build scratch is marginal — arenas are not a2588 - latency win where serialization dominates (p09 measurements,2589 - `prototypes/PLAN.md`).2590 - - **Provider request assembly** at compaction-scale contexts has a transient2591 - peak of a small multiple of the serialized request size and must release it2592 - fully after send; peak memory (not just CPU) is a test gate.1710 + - each stripped release binary is smaller than 20 MB;1711 + - interactive startup is less than 100 ms;1712 + - `smith --help` completes in less than 100 ms;1713 + - a TUI frame draw completes in less than 2 ms within the 16 ms frame budget;1714 + - layout resolution over 80×24 through 400×100 has release-build p99 below 0.8 µs, with approximately 0.4 µs as the target;1715 + - encoding a 1,000-entry session completes in less than 5 ms;1716 + - UI keypress acknowledgment is at most 16 ms; and1717 + - an agent-loop turn SHOULD complete in less than 30 seconds, excluding provider/network stalls beyond configured timeout.2594 - ## 14. Release Artifacts 1719 + A release MUST NOT exceed a mandatory threshold because of a performance regression.2598 - | Platform | Triple | Status |2599 - |----------|--------|--------|1723 + Session discovery MUST be lazy and metadata-only: it MUST read session headers, never complete bodies, and perform work proportional to session count rather than corpus bytes.1725 + Virtual scrolling MUST materialize no more than viewport rows per frame. Row formatting MUST stop at the visible window through lazy wrapping; showing a slice of a multi-MiB message MUST NOT format the complete message.1727 + Arenas MUST be scratch-only and phase-local to measured rendering or request scratch. Persisted/session data MUST use stable IDs and owned strings, never arena references. Custom or unsafe arena implementations MUST NOT be used. Arena references MUST NOT cross asynchronous, thread, or persistence boundaries.1729 + Arena decisions MUST consider allocator-call pressure, elapsed time, and peak/plateau stability, not allocation count alone. Render-frame scratch qualifies; request-build scratch MUST NOT be presumed faster when serialization dominates.1731 + Provider request assembly at compaction-scale contexts MUST have transient peak memory no greater than a small multiple of serialized request size and MUST release that transient memory fully after send. Peak memory, not CPU alone, is an acceptance requirement.1733 + ## Release Artifacts 1737 + | Platform | Target triple | Obligation |2600 1739 | Windows x86_64 | `x86_64-pc-windows-msvc` | required || Windows x86_64 | `x86_64-pc-windows-msvc` | required |2601 1740 | Windows ARM64 | `aarch64-pc-windows-msvc` | required || Windows ARM64 | `aarch64-pc-windows-msvc` | required |2602 1741 | macOS Intel | `x86_64-apple-darwin` | required || macOS Intel | `x86_64-apple-darwin` | required |2611 1750 | FreeBSD x86_64 | `x86_64-unknown-freebsd` | best-effort || FreeBSD x86_64 | `x86_64-unknown-freebsd` | best-effort |2612 1751 | OpenBSD x86_64 | `x86_64-unknown-openbsd` | best-effort || OpenBSD x86_64 | `x86_64-unknown-openbsd` | best-effort |2614 - **Three libcs, not two.** glibc and musl cover the Linux rows; **Android is2615 - Bionic**, which is why it is its own row rather than a Linux variant. Bionic does2616 - not carry the compiler-rt builtins Rust expects to find, so the Android target2617 - links against them explicitly — the flag lives in `.cargo/config.toml` (§3.2) and2618 - is normative for this target, not a local workaround. A toolchain that cannot2619 - supply them cannot produce this artifact.1753 + Linux glibc, Linux musl, and Android Bionic MUST remain distinct libc targets. Android MUST link the compiler-runtime builtins required by Rust; an environment unable to supply them cannot produce the required artifact.2621 - **Required means release-blocking.** A required target that fails to build stops2622 - the release; a best-effort target that fails is reported in the release notes and2623 - skipped, and its absence is never a reason to hold the other artifacts. Android is2624 - required because a terminal-first coding agent is used on a phone, not only built2625 - for one — it is a shipping platform, not a development convenience.1755 + Failure of a required target MUST stop release. A best-effort failure MUST be skipped, documented with its reason in release notes, and MUST NOT block other artifacts. Every target MUST be accounted for as built or skipped; none may be silently omitted. The matrix MUST be cross-compiled from one host wherever a target permits it.1757 + ### Names and guarantees 2629 - - `smith-{triple}-v{version}.{zip|tar.gz}`,2630 - - `checksums-sha256.txt`.1759 + Every built target MUST produce:2632 - **One host builds the matrix.** Producing thirteen targets must not require2633 - thirteen build environments. The release is cross-compiled from a single host2634 - wherever a target allows it; CI installs toolchains and invokes `xtask release`,2635 - holding no build logic of its own (PROJECT-INVARIANTS §1). Which cross-compilers2636 - achieve this is an implementation choice, not a spec commitment — it changes as2639 - Three properties the artifacts must have, whatever builds them:2641 - - **Windows artifacts are MSVC-ABI.** A GNU-ABI binary is a different artifact —2642 - different C++ exception handling, different C runtime — so it is never a2643 - substitute for a target the matrix lists as MSVC, however much easier it is to2645 - - **glibc artifacts run on glibc 2.28 or newer** — Debian 10, RHEL 8, Ubuntu2646 - 18.10. The floor is a property of the release, not of whatever the build machine2647 - happens to ship: linking against the builder's glibc silently narrows who can run2648 - smith, and by an amount nobody stated. Raising the floor drops users, so it is a2649 - spec change, not a build detail.2650 - - **No target is silently dropped.** Each release accounts for every target as2651 - built, or skipped with a reason. A required target that fails to build stops the2652 - release (above); quietly shipping a short matrix is a defect, not a degraded2655 - Where a target's cross-build is unproven, a prototype (§18) establishes it before2656 - the matrix claims it — an unverified target is a promise, not a platform.2658 - No install scripts, package manifests, distribution metadata, or code signing in v1.2664 - | Command | Purpose |2665 - |---------|---------|2666 - | `check` | fmt + clippy + arch + pup + test + doc |2667 - | `test` | all tests via nextest |2668 - | `lint` | clippy + rustfmt check |2669 - | `fmt` | auto-format |2670 - | `fetch-providers` | generate `smith-ai/src/providers.json` |2671 - | `doc-test` | run Lua `@usage`, guide blocks, examples |2672 - | `verify-docs` | verify SDK/API docs completeness |2673 - | `doc-gen` | generate man pages and docs bundle |2674 - | `spec-verify` | verify SPEC links and project invariants |2675 - | `arch` | stable architecture checks |2676 - | `pup` | pinned-nightly cargo-pup gate |2677 - | `print-modules` | module inventory: Cargo metadata crate roots + cargo-pup submodules |2678 - | `audit` | cargo-deny + cargo-audit |2679 - | `bench` | criterion benchmarks |2680 - | `coverage` | tarpaulin coverage |2681 - | `mutants` | cargo-mutants mutation testing |2682 - | `release` | build archives and checksums |2684 - xtask commands are thin orchestrators. No business logic.2686 - ## 16. Documentation 2688 - - `docs/SPEC.md` is the canonical spec.2689 - - `docs/PROJECT-INVARIANTS.md` contains non-negotiable repository invariants.2690 - - No standing design docs: subsystem design content lives in this spec. Any2691 - future exploratory design doc is non-canonical and cannot contradict2693 - - SDK docs are generated from Lua `---@` annotations and `@usage` blocks.2694 - - `smith help` resolves docs in order: (1) embedded in the binary via2695 - `include_str!`, (2) install directory `<prefix>/share/smith/docs/`,2696 - (3) `SMITH_DOCS_PATH` environment override (development). First hit wins.2698 - Documentation gates:2700 - - every Rust SDK function has Lua binding docs,2701 - - every Lua binding has annotations,2702 - - every annotated function has usage,2703 - - every event appears in at least one example,2704 - - no documented function missing in code,2705 - - no public SDK function undocumented.2711 - Every commit, scoped to the touched crates and their reverse-dependency2712 - closure (`-p <crate>`), so the §13.1 incremental guarantee is realized rather2713 - than erased by a full-workspace `--all-features` sweep:2717 - cargo clippy -p < touched...> --all-targets -- -D warnings2718 - cargo run -p xtask -- arch2719 - cargo +nightly-2026-01-22 pup -p < touched...> 2720 - cargo nextest run --profile fast -p < touched...> 2721 - cargo test --doc -p < touched...> 1762 + smith-{triple}-v{version}.{zip|tar.gz}2724 - The full `--workspace --all-features` clippy/build/test sweep runs in the2725 - medium tier (§17.2), not per-commit. Blocks push.2732 - - serialization snapshots,2734 - - architecture gates.2736 - ### 17.2 Medium Tier 2738 - Every PR: the fast tier (§17.1, with `--profile default` instead of `fast`),2742 - cargo tarpaulin --out Lcov2743 - cargo nextest run --profile integration2744 - cargo doc --workspace --no-deps1768 + checksums-sha256.txt1771 + Windows artifacts MUST use the MSVC ABI; GNU ABI MUST NOT substitute. Linux glibc artifacts MUST run on glibc 2.28 or newer, including Debian 10, RHEL 8, and Ubuntu 18.10. Raising that minimum is a product-specification change.1773 + Version 1 MUST NOT ship install scripts, package manifests, distribution metadata, or code signing.2754 - cargo nextest run --profile thorough2755 - cargo mutants --test-tool= nextest2756 - cargo bench -- --baseline main1777 + `smith help` is the product documentation interface and MUST support topic lookup, dotted SDK addressing, full listing, text search, examples, named runnable examples, and named guides through the exact CLI flags above.2759 - Blocks release if mutation score <80% or benchmark regression exceeds threshold.1779 + Documentation lookup MUST use the first available source in this order:2761 - ### 17.4 Coverage Goals 1781 + 1. content embedded in the binary;1782 + 2. `<prefix>/share/smith/docs/`;1783 + 3. `SMITH_DOCS_PATH`.2766 - | `smith-core` | ≥95% |2767 - | `smith-ai` | ≥90% |2768 - | `smith-tui` | ≥85% |2769 - | `smith-harness` | ≥90% |2770 - | `smith-cli` | ≥80% |1785 + The system prompt MUST direct capability discovery to `smith help --search`, `smith help --guide`, and `smith help --example` rather than embedding the complete SDK.2772 - Overall workspace coverage target is 85%; merges are blocked below 80%.1787 + Every public Lua function's runtime schema and documentation MUST derive from its LuaLS annotations. Interface descriptors MUST generate matching LuaLS `---@class`, `---@field`, and `---@param` stubs. Documentation examples declared by `---@usage` MUST be runnable as written.1789 + Documentation completeness MUST guarantee that every Rust SDK function has corresponding Lua binding documentation, every public Lua binding exists in code and is documented, and every event appears in at least one example.2776 - `.config/nextest.toml`:1791 + Diagnostics documented as path-qualified—configuration, themes, interface conformance, tool arguments, plugins, and reload—MUST preserve those exact paths in user-visible output.2781 - slow-timeout = "30s"1793 + ## Product Acceptance 1795 + A Smith release conforms only if every applicable **MUST** and **MUST NOT** in this specification holds. At minimum, end-to-end acceptance MUST demonstrate:2790 - [profile.integration]2791 - filter = 'test(integration::) or test(cli::) or test(tui::)'2793 - slow-timeout = "30s"2797 - slow-timeout = "120s"2802 - slow-timeout = "60s"2803 - # supports --partition for sharded CI runs2806 - ### 17.6 Property Tests 2808 - Required property areas:2810 - - CBOR session codec roundtrip,2811 - - model resolver determinism and cycle detection,2812 - - valid Lua config parsing,2813 - - token estimator monotonicity,2814 - - event-to-session-entry conversion,2815 - - trace filtering preserves order,2816 - - layout resolution (§8.7): every child Rect within its parent's bounds; flow2817 - siblings tile their axis without overlap; `expanded` is the exact remainder;2818 - `split` honors `split_ratio` (± one cell) and tiles exactly; resolution is2819 - deterministic for equal `(tree, size)`.2821 - Commit `proptest-regressions/`.2823 - ### 17.7 Snapshot Tests 2825 - Use `insta` + ratatui `TestBackend` for:2828 - - layout composition,2832 - - config parse output,2833 - - provider normalization.2835 - CI runs with `INSTA_UPDATE=no`.2837 - Snapshot contract (prototype-proven, p08): widget and theme snapshots serialize2838 - styled cells — symbol plus fg/bg/modifier per cell — not buffer text alone.2839 - Text-only snapshots cannot catch theme regressions: a theme swap changes styles2840 - while leaving text byte-identical. Text-only snapshots are permitted only for2841 - layout-only assertions.2843 - ### 17.8 Integration Tests 2845 - Required integration coverage:2847 - - CLI commands and flags,2848 - - session create/resume/fork/dump/replay,2849 - - plugin load/order/override/event dispatch,2850 - - provider registry/custom provider/auth/mock streaming/MuxProvider failover,2851 - - TUI startup/shutdown/capabilities/mouse/layout/theme/scroll,2852 - - interactive PTY smoke tests via `expectrl` (real terminal I/O paths),2853 - - docs/help/search/examples.2855 - Fixtures live under `tests/fixtures/` with plugins, sessions, configs, providers,2860 - Criterion benchmarks:2862 - - `session_encode_1000`,2863 - - `session_decode_1000`,2864 - - `widget_render_100`,2865 - - `agent_loop_turn`,2866 - - `config_resolve_3level`,2867 - - `trace_filter_10000`,2870 - Regression thresholds per benchmark: >5% warns, >10% fails the nightly gate2873 - ### 17.10 Continuous Integration 2875 - Test hermeticity — CI tests never touch real external state:2877 - - providers are mocked (`StreamFn` fakes; no network),2878 - - TUI renders through `TestBackend` (no TTY),2879 - - filesystem via temp dirs,2880 - - clock and randomness injected (mock clock, fixed seeds),2881 - - tests requiring real network live behind a `network-tests` feature and never2882 - run in the default CI lane.2884 - Gate tiers by context:2888 - | every agent iteration | fast tier (§17.1) |2889 - | before merge | fast + medium tiers (coverage gate included, §17.4) |2890 - | CI only | slow tier, mutation, benchmarks |2892 - Agent conduct while building Smith lives outside this spec in2893 - PROJECT-INVARIANTS §5. This section defines Smith's test artifacts.2895 - Android/Termux (`aarch64-linux-android`) is both the environment smith is2896 - developed in and a **required release target** (§14): CI keeps a validation lane2897 - that smoke-builds vendored LuaJIT and syntastica for it, and because the artifact2898 - ships, breakage there blocks publishing like any other required target — not only2899 - source-compatibility fixes.2901 - ## 18. Prototype Policy 2903 - Prototypes are disposable evidence for or against this spec. They live under2904 - `prototypes/`, never in production crates. A prototype tests one claim or risk,2905 - runs minimal commands, and reports whether the spec should change.2907 - Prototype output must include:2912 - - spec issues with evidence,2913 - - artifacts created,2915 - - next spec/design actions.2917 - Production code must not depend on prototype artifacts.2919 - Three validation campaigns (p02–p11 on 2026-07-14; p12–p14 and p15–p23 on2920 - 2026-07-15/16; x86_64-linux, rustc 1.94.1) ran twenty-two prototypes to2921 - completion; result blocks live in `prototypes/PLAN.md`. Sections marked2922 - "prototype-proven" in this spec cite that evidence.1797 + - first run reaches an unbordered default layout without onboarding and accepts input within the startup limit;1798 + - missing auth fails before streaming, preserves input, and gives credential, environment, and OAuth guidance when available;1799 + - streaming, tools, live usage, direct bash, VCS recording, steering, follow-ups, cancellation, and abort repair produce the specified ordered transcript;1800 + - conversation leaf switching never changes files, VCS restoration never implicitly changes conversation leaf, and replay never mutates the live session;1801 + - continuation restores leaf/history/cost but no ephemeral queue;1802 + - truncated/corrupt/unknown session records recover at the specified framing boundaries;1803 + - registered secrets remain placeholders at provider, trace, event, display, and RPC boundaries and rehydrate only for tools;1804 + - resolver validation, deterministic rotation, deduplication, retries, failover, and signed-thinking replay behave exactly as specified;1805 + - built-in and user facilities use the same restricted Lua SDK, plugin precedence, domain teardown, error isolation, bus ordering, and atomic reload rules;1806 + - TUI and RPC consume the same engine behavior while exposing only their permitted frontend-specific surfaces;1807 + - configuration reload is all-or-nothing and preserves in-flight continuity;1808 + - layout resolution keeps every child within its parent, tiles flow siblings without overlap, gives `expanded` the exact remainder, and makes `split` tile exactly while honoring its ratio within one cell;1809 + - widget and theme acceptance records each styled cell's symbol, foreground, background, and modifiers; text-only records validate layout only;1810 + - all mandatory performance and memory limits hold; and1811 + - every release artifact satisfies its target, naming, checksum, ABI, libc, size, and failure-policy requirements.docs/plans/PLUGIN-DOC-PLAN.md Deleted deleted file mode 100644+0 / −300 text lines
1 - # Smith Plugin SDK Documentation Plan 3 - > Non-normative execution plan. `docs/SPEC.md` is canonical; where this file and4 - > the spec disagree, the spec wins. The normative pieces already live in SPEC —5 - > doc resolution order + `SMITH_DOCS_PATH` (§16), dotted `topic.function`6 - > addressing (§10.2), the system-prompt self-learn bootstrap (§6.8). This file7 - > is the execution plan for file inventories and tooling only.11 - Smith must be able to extend itself when prompted by humans.12 - Documentation serves both humans and LLMs equally.13 - One source of truth. No drift.18 - Source of Truth: SDK Lua annotations (---@ + @usage + prose)20 - ├─→ Embed in binary (include_str!)22 - │ ├─→ smith help <topic> (primary interface)23 - │ ├─→ smith help --search X (fuzzy search)24 - │ ├─→ smith help --list (all topics)25 - │ └─→ system prompt bootstrap (teaches smith to self-learn)27 - ├─→ Generate man pages (CI, shipped in release)29 - ├─→ Generate compressed docs bundle (CI, shipped in install dir)30 - │ └─→ fallback: readable files on disk32 - └─→ Doc tests (CI, extracts @usage + guide code blocks → run in Lua)35 - ## One Source of Truth: SDK Annotations 37 - Every SDK function has `---@` annotations in the Lua source files.40 - smith-harness/src/lua/sdk/42 - ├── smith_provider.lua44 - ├── smith_shortcut.lua48 - ├── smith_credentials.lua52 - Guides live alongside the SDK code too:55 - smith-harness/src/lua/sdk/57 - ├── getting-started.lua -- guide as Lua comments + tested code blocks65 - Guides are Lua files where:66 - - Comments (`--`) contain prose67 - - Fenced blocks (`---[[` ... `--]]`) contain tested examples68 - - The doc test runner extracts and executes the fenced blocks70 - This keeps everything in one place — the `sdk/` directory is the entire documentation source.72 - ## `smith help` — The Primary Interface 74 - `smith help` is not just a man page reader. It's a full documentation browser.79 - smith help # topic list + fuzzy search prompt80 - smith help <topic> # show topic (tool, provider, event, etc.)81 - smith help <topic>.<function> # show specific function82 - smith help --search <query> # fuzzy search across all docs83 - smith help --list # list all topics84 - smith help --examples # list all examples85 - smith help --example <name> # show full example source86 - smith help --guide <name> # show full guide91 - Topics map 1:1 to SDK files:94 - smith help tools → smith_tool.lua annotations95 - smith help provider → smith_provider.lua annotations96 - smith help events → smith_events.lua annotations97 - smith help tui → smith_tui.lua annotations98 - smith help tools.register → specific function within topic104 - smith help --search "block tool call"105 - → Found: smith.on("tool_call") — subscribe to tool call events (can block)106 - → Found: smith.on("tool_result") — subscribe to tool result events (can modify)118 - Interactive mode (when run in TUI):122 - ┌──────────────────────────────────────────┐124 - │ Type to search, Enter to view, Esc to quit│125 - ├──────────────────────────────────────────┤129 - │ smith.tool.register Register custom tool│130 - │ smith.on("tool_call") Intercept tool calls│131 - │ smith.on("tool_result") Modify tool results│134 - │ tools.md Custom tools guide │137 - │ 02-custom-tool.lua Basic tool example │138 - │ 04-permission-gate.lua Block dangerous cmd│139 - └──────────────────────────────────────────┘142 - Uses the same `SelectList` widget from smith-tui. Reuses the fuzzy matcher.146 - Docs are resolved in this order:148 - 1. **Embedded in binary** (always available) — primary source for `smith help`149 - 2. **Install directory** (`<prefix>/share/smith/docs/`) — compressed fallback150 - 3. **`SMITH_DOCS_PATH` env var** — override for development152 - The embedded docs are compiled from annotations via `include_str!` at build time.153 - No files needed on disk for `smith help` to work.155 - Install directory contains the generated bundle for:156 - - Direct file reading by LLMs via `read` tool160 - ## System Prompt Bootstrap 163 - Smith is a coding agent that can extend itself via Lua plugins.165 - To learn the plugin SDK, use these commands:166 - - smith help <topic> — API reference (tools, events, provider, tui, etc.)167 - - smith help --search X — fuzzy search across all docs168 - - smith help --example N — read a tested example plugin169 - - smith help --guide N — read a guide171 - Key topics: tools, events, provider, command, shortcut, tui, fs, sandbox173 - When asked to create or modify a plugin, read the relevant help first.176 - This teaches smith to self-learn. When asked "write a plugin that blocks dangerous177 - commands", smith runs `smith help --search "block tool"` → reads `smith help events`178 - → reads `smith help --example 04-permission-gate` → generates correct code.182 - Tested examples live in the SDK source:185 - smith-harness/src/lua/sdk/examples/186 - ├── 01-hello-world.lua187 - ├── 02-custom-tool.lua188 - ├── 03-event-subscription.lua189 - ├── 04-permission-gate.lua190 - ├── 05-custom-provider.lua191 - ├── 06-custom-command.lua192 - ├── 07-custom-layout.lua193 - ├── 08-file-tree-panel.lua194 - ├── 09-auto-compact.lua195 - ├── 10-git-checkpoint.lua196 - ├── 11-session-state.lua197 - └── 12-streaming-updates.lua200 - Each example has a header comment with description (indexed by `smith help --examples`).204 - ### Doc Tests (automated) 213 - 1. `@usage` blocks from SDK annotation files214 - 2. Fenced code blocks from guide files (`---[[` ... `--]]`)215 - 3. Full example files217 - All run in sandboxed Lua VM. Any failure = CI failure.219 - ### Completeness Verification (automated) 228 - 1. Every Rust SDK function has a Lua binding with annotations229 - 2. Every annotated function has `@usage`230 - 3. Every event appears in at least one example231 - 4. No documented function that doesn't exist in code232 - 5. No public SDK function without documentation234 - ### Guide Correctness (automated) 236 - Guides are Lua files with prose in comments and code in fenced blocks.237 - The doc test runner treats them identically to SDK files — extracts code, runs it.240 - - Guide code is always tested241 - - If an API changes and breaks a guide, CI catches it242 - - No separate "guide test" vs "SDK test" — same runner247 - cargo run -p xtask -- test # unit + integration tests248 - cargo run -p xtask -- doc-test # run all code blocks249 - cargo run -p xtask -- verify-docs # completeness checks250 - cargo run -p xtask -- doc-gen # regenerate man pages + bundle (fail if changed)251 - cargo run -p xtask -- lint # clippy + luacheck261 - │ ├── smith_tool.lua -- annotations + @usage262 - │ ├── smith_provider.lua263 - │ ├── smith_command.lua264 - │ ├── smith_shortcut.lua268 - │ ├── smith_credentials.lua269 - │ ├── smith_events.lua271 - │ │ ├── getting-started.lua -- prose in comments, tested code274 - │ │ ├── providers.lua278 - │ ├── 01-hello-world.lua279 - │ ├── 02-custom-tool.lua281 - │ └── 12-streaming-updates.lua285 - ├── doc_test.rs -- run code blocks in Lua VM286 - ├── verify_docs.rs -- completeness checks287 - └── doc_gen.rs -- generate man pages + docs bundle292 - - [ ] Create SDK annotation files in `smith-harness/src/lua/sdk/`293 - - [ ] Create guide files (Lua files with prose comments + tested code)294 - - [ ] Create tested examples (01-12)295 - - [ ] Implement `smith help` command with fuzzy search + interactive browse296 - - [ ] Implement `xtask doc-test` (extract + run code blocks)297 - - [ ] Implement `xtask verify-docs` (completeness checker)298 - - [ ] Implement `xtask doc-gen` (generate man pages + docs bundle)299 - - [ ] Write system prompt bootstrap300 - - [ ] Set up CI pipeline
docs/plans/README.md Deleted deleted file mode 100644+0 / −23 text lines
3 - Non-normative execution plans — the bridge from `docs/SPEC.md` (what to build)4 - to code (in what order). The spec is canonical; a plan never overrides it.6 - | Plan | Covers | Status |7 - |------|--------|--------|8 - | `WALKING-SKELETON.md` | first vertical slice — one turn end-to-end, proving the four seams | ready to start |9 - | `TASK-BREAKDOWN.md` | crate build order (SM-003→012) plus the §14 release wave (SM-013), wave sequencing | pre-implementation |10 - | `PLUGIN-DOC-PLAN.md` | plugin-SDK doc source, `smith help`, doc tooling/tests | pre-implementation |12 - ## Is this the whole set? 14 - `WALKING-SKELETON` is the entry point for implementation — a thin slice through15 - every layer that proves the StreamFn, EngineEvent, session-codec, and TUI seams16 - connect before any of them is built out. `TASK-BREAKDOWN` is the full crate17 - sequencing that follows once the skeleton is green. One thing is still18 - intentionally *not* written, to avoid speculative planning:20 - - **Per-crate breakdowns.** Each SM-0xx task is crate-sized; it gets decomposed21 - into tested units at the start of its own wave, not now.23 - Prototype evidence that de-risks all of this lives in `../../prototypes/PLAN.md`.
docs/plans/TASK-BREAKDOWN.md Deleted deleted file mode 100644+0 / −67 text lines
3 - > Non-normative execution plan. `docs/SPEC.md` is canonical; where this file and4 - > the spec disagree, the spec wins. Architecture and crate responsibilities are5 - > defined once in SPEC §2 and CLAUDE.md — this file only sequences the build.7 - Top-level build order for the first implementation pass, at crate granularity.8 - Each task is a whole crate; decomposition into buildable, tested units is9 - deferred to that crate's own wave (see **Granularity**).11 - ## Task dependency graph 14 - SM-003 (scaffolding) ── SM-005 (smith/) ──┬── SM-006 (smith-core/) ──┐15 - ├── SM-007 (smith-ai/) ──┼── SM-009 (smith-harness/) ── SM-010 (smith-cli/)16 - └── SM-008 (smith-tui/) ──┘ │24 - The edges are the §2.2 boundary rules: `smith/` is the sole foundation;25 - `smith-core` / `smith-ai` / `smith-tui` build in parallel and never depend on26 - each other; `smith-harness` wires them; `smith-cli` sits on top.31 - Wave 0: SM-003 scaffolding — jj repo, Cargo workspace, crate skeletons, xtask32 - Wave 1: SM-005 smith/ — foundation types (sequential; everything blocks on it)33 - Wave 2: SM-006 + SM-007 + SM-008 core / ai / tui (parallel)34 - Wave 3: SM-009 smith-harness — wiring (after wave 2)35 - Wave 4: SM-010 + SM-011 cli + workspace (parallel)36 - Wave 5: SM-012 integration tests37 - Wave 6: SM-013 release — §14 artifact matrix via `xtask release`; the required38 - targets whose cross-build is unproven (Windows MSVC, Android)39 - need their §18 proofs before the matrix claims them44 - | Task | Crate | Blocked by | Blocks |45 - |------|-------|------------|--------|46 - | SM-003 | workspace | — | SM-005 |47 - | SM-005 | smith/ | SM-003 | SM-006/007/008 |48 - | SM-006 | smith-core/ | SM-005 | SM-009 |49 - | SM-007 | smith-ai/ | SM-005 | SM-009 |50 - | SM-008 | smith-tui/ | SM-005 | SM-009 |51 - | SM-009 | smith-harness/ | SM-006/007/008 | SM-010 |52 - | SM-010 | smith-cli/ | SM-009 | SM-012 |53 - | SM-011 | workspace | SM-009 | SM-012 |54 - | SM-012 | testing | SM-010, SM-011 | SM-013 |55 - | SM-013 | release | SM-012, §18 proofs (Windows MSVC, Android) | — |57 - What each crate owns and must not own is defined once in SPEC §2.2 — not58 - repeated here, to avoid drift.62 - These tasks are crate-sized, not buildable units: "SM-006 smith-core" is an63 - entire agent loop plus session, tools, hooks, and events. Before a crate's wave64 - starts it needs its own breakdown into vertical, tested slices. This file is65 - top-level sequencing only; a pure bottom-up walk of it produces nothing runnable66 - until SM-010, so the first implementation move should be a thin end-to-end slice67 - (walking skeleton) rather than a full horizontal wave — see the plans index.
docs/plans/WALKING-SKELETON.md Deleted deleted file mode 100644+0 / −107 text lines
1 - # Walking Skeleton — First Vertical Slice 3 - > Non-normative execution plan. `docs/SPEC.md` is canonical; where this file and4 - > the spec disagree, the spec wins. This plan sequences the *first* code, not5 - > the whole product — `TASK-BREAKDOWN.md` holds the full crate build order.7 - > **This build sequence is the first implementation wave.** Later waves come8 - > from `TASK-BREAKDOWN`.12 - `TASK-BREAKDOWN` is bottom-up: `smith/` → core/ai/tui → harness → cli. Built13 - literally, nothing runs end-to-end until the last wave, so the first integration14 - problem surfaces last — the most expensive place to find it. The walking15 - skeleton inverts that: build the **thinnest possible slice through every layer**16 - first, prove the seams connect, then widen. Each layer ships the minimum that17 - lets the next one exist — no more.19 - The slice is one agent turn, end to end, rendered and persisted:22 - input → agent loop → StreamFn → (scripted) ProviderEvents → one tool call23 - → assistant Message → EngineEvents → TUI render → session CBOR → reload26 - ## The seams it proves (the entire point) 28 - The skeleton exists to exercise the four load-bearing boundaries once, together,29 - before any of them is built out:31 - 1. **StreamFn seam** (§5.4) — the agent loop consumes a `StreamFn`, never a32 - concrete provider. Proven in isolation by p07; proven *wired* here.33 - 2. **EngineEvent seam** (§6.3) — the engine emits a UI-agnostic event stream;34 - the TUI is one consumer of it, not coupled to the loop.35 - 3. **Session codec** (§6.6) — a turn round-trips through CBOR and reloads36 - identically. Proven in isolation by p06.37 - 4. **TUI render loop** (§8) — EngineEvents render through `TestBackend` with no38 - TTY and no network. Proven in isolation by p08.40 - If these four connect, the architecture holds. Everything else is widening.42 - ## In scope (the minimum per layer) 44 - | Crate | Ships only | Leans on |45 - |-------|-----------|----------|46 - | workspace (SM-003) | jj repo, Cargo workspace, crate skeletons, `xtask check` | — |47 - | `smith/` (SM-005) | `Message`/`Id` (§5.1), `ProviderEvent`/`ProviderRequest` (§5.2), `AgentTool` (§5.3), `StreamFn` alias (§5.4), a minimal `Config` (§5.6) — and nothing else | — |48 - | `smith-ai/` (SM-007) | one **scripted** `StreamFn` that replays a fixture `ProviderEvent` sequence (deterministic, hermetic) | p05, p29 |49 - | `smith-core/` (SM-006) | one-turn agent loop (§6.1), `EngineEvent` emit (§6.3), one read-only tool via `ToolRegistry` (§6.10), session append + CBOR persist/reload (§6.5/§6.6) | p07, p06, p31 |50 - | `smith-tui/` (SM-008) | message list + input area + status bar (subset of §8.6), driven by EngineEvents through `TestBackend` | p08, p22 |51 - | `smith-harness/` (SM-009) | wire scripted StreamFn → loop → EngineEvent → TUI; register the one tool | p23 |52 - | `smith-cli/` (SM-010) | `smith new` (run one turn, render, persist) and `smith attach` (reload + re-render the persisted session) | — |54 - ## Explicitly deferred (widening, not skeleton) 56 - Lua runtime and plugins (§5.5/§9); real providers, auth, OAuth (§7); compaction57 - and cost (§6.9); session branching (§6.5 tree); the secret proxy (§6.7); the RPC58 - frontend (§10.4); the remaining §8.6 widgets and layout; every CLI subcommand59 - beyond `new`/`attach`. None of these block proving the seams.63 - **One hermetic end-to-end test is the definition of done** (fast tier, §17.1;64 - hermeticity rules, §17.10):66 - > Given a scripted `StreamFn` whose fixture emits text then one tool call, when67 - > `smith new` runs one turn, then the tool executes once, the assistant68 - > `Message` is assembled from the `ProviderEvent` stream, the expected69 - > `EngineEvent` sequence is observed, `TestBackend` renders the exchange, the70 - > session is written as CBOR, and `smith attach` reloads it to a byte-identical73 - One additional **gated** smoke test (`network-tests` feature, off by default per74 - §17.10) swaps the scripted StreamFn for a real Anthropic call, proving the same75 - loop drives a live provider. It never runs in the default lane.79 - Vertical, not the horizontal waves of `TASK-BREAKDOWN`:82 - 1. workspace skeleton + xtask green83 - 2. smith/ minimal types (only what steps 3–7 consume)84 - 3. scripted StreamFn (fixture in, ProviderEvents out)85 - 4. agent loop: one turn over the StreamFn, EngineEvents out, one tool86 - 5. session: append + CBOR persist/reload87 - 6. TUI: render EngineEvents via TestBackend88 - 7. harness wires 3–6; cli exposes `new` + `attach`89 - 8. the acceptance test goes green → skeleton done92 - Each step is mergeable on its own and leaves the tree building.96 - - The acceptance test passes in the fast tier; the gated real-provider smoke97 - passes when explicitly run.98 - - `cargo run -p xtask -- check` (fmt + clippy + arch + pup + test + doc) is100 - - No deferred subsystem was pulled in to make it work.102 - ## First widening steps after green 104 - Add a real provider normalizer behind the StreamFn (§7.2, p29); introduce the105 - Lua runtime and the first built-in plugin (§5.5/§9); grow the widget set (§8.6);106 - add `continue`/`resume` and the session tree (§6.5). Each rides the seams the107 - skeleton already proved.
docs/research/TESTING-STRATEGY-RESEARCH.md Modified +13 / −13 text lines
119 119 - **>80% mutants caught** — strong signal that tests verify behavior, not just reach code- **>80% mutants caught** — strong signal that tests verify behavior, not just reach code120 120 - **100% on pure functions** — config resolution, CBOR codec, model resolver, event mapping- **100% on pure functions** — config resolution, CBOR codec, model resolver, event mapping121 - - **Incremental on PRs ** — only mutants in changed files (fast: ~5 min)121 + - **Incremental before integration ** — only mutants in changed files (fast: ~5 min)122 122 - **Full on main** — all mutants (slow: ~30-60 min, nightly)- **Full on main** — all mutants (slow: ~30-60 min, nightly)124 124 ### Configuration ### Configuration 147 147 | Trigger | Scope | Duration | Gating || Trigger | Scope | Duration | Gating |148 148 |---------|-------|----------|--------||---------|-------|----------|--------|149 - | PR | Changed files only | ~5 min | Advisory (comment, not block) |150 - | Main branch | All mutants | ~30-60 min | Post-merge report |149 + | Integration candidate | Changed files only | ~5 min | Advisory |150 + | Trunk | All mutants | ~30-60 min | Post-integration report |151 151 | Release | All mutants | ~30-60 min | Block release if <80% || Release | All mutants | ~30-60 min | Block release if <80% |295 295 - **Slower** than TestBackend snapshots (~100ms-1s per test vs ~1ms)- **Slower** than TestBackend snapshots (~100ms-1s per test vs ~1ms)296 296 - **Flaky** — timing-dependent, requires retries- **Flaky** — timing-dependent, requires retries297 297 - **Platform-specific** — terminal emulation differences- **Platform-specific** — terminal emulation differences298 - - **Not for CI fast tier** — use for medium tier (every PR)298 + - **Not for the fast tier** — use for the medium pre-integration tier300 300 ### When to use ### When to use 394 - cargo bench -- --save-baseline main394 + cargo bench -- --save-baseline trunk397 - cargo bench -- --baseline main397 + cargo bench -- --baseline trunk424 424 - TUI integration tests (expectrl)- TUI integration tests (expectrl)425 425 - Session integration tests- Session integration tests426 426 - Plugin loading tests- Plugin loading tests427 - - **Run:** Every PR, post-merge on main427 + - **Run:** Before integration and after integration on trunk429 429 ### Slow tests (1s - 60min) ### Slow tests (1s - 60min) 606 606 | Concern | Tool | Crate | Scope | Speed | CI Tier || Concern | Tool | Crate | Scope | Speed | CI Tier |607 607 |---------|------|-------|-------|-------|---------||---------|------|-------|-------|-------|---------|608 608 | Runner | nextest | cargo-nextest | All | — | Every commit || Runner | nextest | cargo-nextest | All | — | Every commit |609 - | Coverage | tarpaulin | cargo-tarpaulin | All | minutes | Every PR |610 - | Mutation | mutants | cargo-mutants | All | minutes-hours | Nightly/PR-advisory |609 + | Coverage | tarpaulin | cargo-tarpaulin | All | minutes | Before integration |610 + | Mutation | mutants | cargo-mutants | All | minutes-hours | Scheduled/integration advisory |611 611 | Property | proptest | proptest | Core/Types | ms | Every commit || Property | proptest | proptest | Core/Types | ms | Every commit |612 612 | Snapshot | insta | insta | TUI/Types | ms | Every commit || Snapshot | insta | insta | TUI/Types | ms | Every commit |613 613 | Widget | TestBackend | ratatui | TUI | ms | Every commit || Widget | TestBackend | ratatui | TUI | ms | Every commit |614 - | CLI integ | assert_cmd | assert_cmd | CLI | 100ms | Every PR |615 - | TUI integ | expectrl | expectrl | CLI/TUI | 100ms-1s | Every PR |614 + | CLI integ | assert_cmd | assert_cmd | CLI | 100ms | Before integration |615 + | TUI integ | expectrl | expectrl | CLI/TUI | 100ms-1s | Before integration |616 616 | Benchmark | criterion | criterion | Hot paths | seconds | Nightly || Benchmark | criterion | criterion | Hot paths | seconds | Nightly |617 - | Fixture | assert_fs | assert_fs | All | — | Every PR |617 + | Fixture | assert_fs | assert_fs | All | — | Before integration |