repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

Make the product spec the sole documentation authority

84e9bff609f8ab42e07e22591a7f2bd7f60ec2ad

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare 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)

+1407 / −3529 text lines

Diff layout

.claude/skills/capture/references/tape.md

Modified

+2 / −2 text lines

2424- `FontSize` ≥ 16; **20 is the default here**.
2525- Columns ≈ `(Width − 2·Padding) / (FontSize × 0.6)`. The defaults
2626 (`Width 1200`, `Padding 12`, `FontSize 20`) yield a ~98×27 grid — about
27 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.
2828- Wider app? Prefer 1600×800 @ FontSize 18 (~145 cols) over shrinking the
29 font further. Below 14 pt, text in a PR is decoration, not evidence.
29 font further. Below 14 pt, text is decoration, not evidence.
3030- `Set Theme "Catppuccin Mocha"` (or any high-contrast dark theme) and
3131 `Set Padding 12` keep edges and colors readable.

.pi/prompts/capture.md

Modified

+1 / −1 text lines

11---
22name: capture
3description: Capture TUI screenshots and recordings for PRs, QA, debugging.
3description: Capture TUI screenshots and recordings for QA and debugging.
44argument-hint: "[target]"
55---

CLAUDE.md

Modified

+37 / −90 text lines

11# smith
3Rust coding agent TUI. Phase: spec/planning. No production code until specs
4are final; disposable spec-validation prototypes live under `prototypes/`
5(SPEC §18).
3Rust coding-agent TUI. Product behavior is specified; production crates remain skeletal.
75## Architecture
9```
10smith/ (types, StreamFn, AgentTool, Lua, config)
11 → smith-ai/ | smith-core/ | smith-tui/ (parallel)
12 → smith-harness/ (wiring, plugins, SDK)
13 → smith-cli/ (binary)
7```text
8smith
9 → smith-core | smith-ai | smith-tui
10 → smith-harness
11 → smith-cli
1412```
16## Locked Decisions
14Rust 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 |
16## Authority
31## Source of Truth
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.
33CLAUDE.md is a navigation index. Do not mirror individual source-of-truth file
34lists here; use the canonical directories and docs tree instead.
36One specification sits at the top:
38- **What to build — `docs/SPEC.md`.** The canonical specification for every
39 smith artifact: the app, the site, the book, and the documentation.
41Bound by the invariants, and supported by the rest:
43- **Invariants — `docs/PROJECT-INVARIANTS.md`.** Non-negotiable rules every
44 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 analysis
47 (evidence, non-normative).
48- Plans: `docs/plans/` — execution plans (non-normative); `README.md` indexes them.
49- Prototypes: `prototypes/` — spec-validation prototypes and their plan.
51Former `docs/design/` subsystem docs and the P1–P20 prototype report are fully
52absorbed into `docs/SPEC.md` and deleted (see git history).
23Do not create parallel specifications or duplicate source-of-truth lists.
5425## Rules
561. Spec before code. No production `.rs` until `docs/SPEC.md` covers the
57 work; prototype `.rs` under `prototypes/` is sanctioned by SPEC §18.
582. CLAUDE.md is the navigation index. `docs/SPEC.md` is the canonical project spec.
593. Every spec section answers: interfaces, data, errors, tests — as named
60 shapes and behavior, not code. Exact only at boundaries others program
61 against (files, wire formats, CLI, config, Lua SDK); code blocks are
62 illustrative unless the section says otherwise.
634. Open questions: stop and ask. No guessing.
645. 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 thin
67 pi adapters that defer to them. `.agents/skills` symlinks to
68 `.claude/skills` so harnesses that discover skills there read the same
69 definitions.
706. Cargo is the sole build system. See `docs/PROJECT-INVARIANTS.md` §1.
717. Agents must not modify `docs/SPEC.md` or `docs/PROJECT-INVARIANTS.md` without approval.
271. Specify product behavior before production implementation.
282. Product requirements belong only in `docs/SPEC.md`.
293. Exact boundaries include files, wire formats, CLI, configuration, RPC, and Lua SDK.
304. Stop on open design questions; never guess.
315. Cargo is the sole build interface.
326. Modifying the specification, invariants, dependency membership, toolchain, Cargo config, or CI requires explicit owner approval.
337. Keep research citations and evidence, but do not promote research prose into requirements.
348. Keep generated output, scratch state, credentials, and captures out of git.
73## Writing commits
36## Skills
75Commits argue the **why**, not the **what**. The diff already lists what
76changed — never retype it. A message earns its place by recording the
77motivation, the reasoning, and what was deliberately *not* done and why.
38Canonical 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", no
80 session links, no tool bylines. These commits are the author's.
81- **Subject:** one imperative line naming the decision or its effect, not the
82 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 alternative
85 dropped and the single cost that killed it, and the one number or fact that
86 settled it. If it wants more than that, the overflow belongs elsewhere.
87- **One grep-able anchor.** Exactly one sentence naming the concrete surface
88 touched — `SPEC §N`, a file, a config key, a `prototypes/pNN` dir — as a
89 range or count, never a per-item roster. This is what keeps `git bisect` and
90 `blame` meaningful. "Don't enumerate" is not "don't be specific."
91- **Where detail lives instead:** per-file change lists → the diff; benchmark
92 tables and raw measurements → the prototype dir and its `PLAN.md` result
93 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-lock
96 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
46## Commits
100Every 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, no
103 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. Say
105 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 verdict
107 and the findings that change it; drop everything else.
55## Output
109Thoroughness is in the *reasoning*, not the word count. A wall of text is a
110defect, not diligence.
57Report only findings and actions that affect the decision. Use one-line bullets, most severe first. A clean result is `No blocking findings.`

README.md

Modified

+38 / −88 text lines

11# Smith
3A coding-agent TUI written in Rust, extended in Lua.
3A fast, extensible coding-agent TUI written in Rust and extended in Lua.
5> **Status: specification.** Smith is being specified before it is built. The
6> 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 will
8> be, and it is considerably further along than the code.
5> **Status: specification.** Product behavior is specified; production crates are still skeletal.
10## Why Smith
7## Product
12[pi](https://github.com/earendil-works/pi) is Smith's starting point and its
13philosophical ancestor. It is well designed, and it hits a sweet spot: handle
14the annoying LLM details, stay minimal, stay extensible. Smith exists because
15two of its costs are structural rather than incidental — they follow from
16implementation choices that cannot be patched out from the outside.
9Smith combines:
18**The runtime.** Node and npm carry a dependency-security surface that has to
19be re-audited continuously, and a performance floor a terminal UI keeps
20bumping into. Smith is a single Rust binary. The targets it is specified
21against are a stripped release under 20MB and `--help` under 100ms
22(§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 has
25good hooks and a broadly stable API, but its audience is a single developer or
26a small team. Extensions are hard to share across a community, because a
27principled interface and an IPC channel are missing. The symptom is visible in
28the ecosystem: dozens of separate subagent extensions, some of them
29dependencies of other extensions that needed subagent functionality, with no
30common contract to depend on. For a consumer of community extensions that is a
31mess, and the rational response is to give up and maintain your own — which is
32the outcome an extension system is supposed to prevent.
19Smith is not a Pi fork and does not preserve Pi APIs or data formats.
34Smith's answer is to make the plugin API the *only* extension API. Everything
35user-visible — tools, slash commands, themes, keybindings, prompts, layouts,
36feature UI — is a Lua plugin, and the built-in tools are written against the
37same interface third-party plugins get (§9). An interface its own author must
38use is one that stays honest. Plugins declare identity and dependencies in a
39manifest, run sandboxed, and talk over a typed, versioned SDK rather than
40reaching into internals.
21## Architecture
42Two more things fall out of the design rather than being features bolted on:
44- **Provider independence.** The agent loop depends on `StreamFn` — a request
45 in, a stream of provider events out — and on nothing else (§5.4). Providers
46 are adapted to that shape, so the loop has no idea which one it is talking
47 to.
48- **Sessions you can replay.** Conversation state is a tree, stored as CBOR,
49 and a recorded trace can be re-executed deterministically without touching a
50 live provider (§6.5, §6.6, §6.11).
52**Who it is for.** People who live in a terminal, want their coding agent to
53start instantly and stay out of the way, and expect to reshape it — and to be
54able 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, no
57shared formats, no code lineage. Not a GUI, not an IDE plugin, and not an
58onboarding wizard — the first run has no setup flow, and a missing credential
59is reported as an error that names the env var to set.
61## The shape of it
63Interactive TUI, a non-interactive eval mode, and a JSON-RPC stdio mode, over
64one agent loop (§1). Conversation history is a tree you can navigate, separate
65from a VCS-backed timeline of what your files looked like — moving through the
66conversation does not move your working copy, and vice versa. Mid-run
67corrections queue as steers rather than forcing a cancel.
69## Layout
71```
72smith/ shared types, StreamFn, AgentTool, config, Lua runtime
73smith-ai/ providers, auth, model registry, provider streams
74smith-core/ agent loop, sessions, tools
75smith-tui/ terminal UI
76smith-harness/ wiring, plugin management, the Lua SDK
77smith-cli/ the binary
78xtask/ custom build tasks
23```text
24smith/ shared contracts
25smith-core/ agent runtime and sessions
26smith-ai/ providers and authentication
27smith-tui/ terminal frontend
28smith-harness/ orchestration and Lua SDK
29smith-cli/ executable
30xtask/ Cargo orchestration
7931```
81`docs/` holds project management rather than code: the specification, the
82invariants every contributor and agent follows, research notes, and execution
83plans. `prototypes/` holds disposable programs written to prove or disprove a
84specific spec claim (§18).
33The agent runtime depends on `StreamFn`, not concrete providers. Rust owns typed contracts and high-frequency primitives; Lua owns user-facing extensibility.
86## Building
35## Build
88Cargo is the only build system for the Rust workspace — there is no Makefile,
89justfile, or script to learn, and anything cargo does not do natively lives in
90`xtask`:
37Cargo is the only build interface.
9239```sh
9340cargo check
94cargo test
95cargo run -p xtask -- check # the full gate: fmt, clippy, tests, architecture
41cargo test --workspace
42cargo fmt --all --check
43cargo run -p xtask -- check
9644```
98Smith tracks latest stable Rust on edition 2024. A pinned nightly is used for
99exactly one thing — the `cargo-pup` architecture gate — and never for product
100code.
46Smith follows latest stable Rust on edition 2024.
102## Reading further
48## Documentation
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.
109Section marks above (§N) refer to `docs/SPEC.md`.
56## Services
58- Source: <https://vcs.bugabinga.net/smith>
59- CI: <https://ci.bugabinga.net>

docs/PROJECT-INVARIANTS.md

Modified

+87 / −498 text lines

11# Project Invariants
3These invariants govern the smith codebase. They are non-negotiable rules that every contributor, tool, and agent must follow. Violations require explicit approval to override.
3These 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`
13- Docs: `cargo doc`
14- Custom tasks: `cargo run -p xtask -- <cmd>`
13## 2. Build Boundary
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.
15Cargo is the sole build interface.
18**Automation is orchestration, not a second build system.** Any automation
19delegates product work to `cargo` / `cargo run -p xtask -- <cmd>` and carries no
20business logic of its own.
22**Prohibited:**
23- Makefile, justfile, package.json, build.sh
24- Custom scripts outside Cargo
25- 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 else
28**Scope:** this invariant governs the **Rust workspace** — the app, its crates,
29and their build. The published **web site** is a separate artifact and is exempt,
30narrowly: the Astro site may carry its own `package.json` and Node build **confined
31to `site/`** (never the workspace root). The **book** stays inside the rule — it
32is mdBook, which is `cargo install`-able — so the site exemption remains confined
33there. No lockfile or `package.json` may appear at the repo root or inside any
34crate.
36## 2. Directory Separation: Code vs. Project Management
38```
39smith/ # ← code (crates, Cargo, .rs)
40├── Cargo.toml # workspace root
41├── smith/
42├── smith-core/
43├── smith-ai/
44├── smith-tui/
45├── smith-harness/
46├── smith-cli/
47├── xtask/
48├── .gitignore
49├── rust-toolchain.toml
50└── ...
52docs/ # ← 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,
56│ │ # non-normative)
57│ ├── RESEARCH-NOTES.md
58│ ├── TERMINAL-CAPABILITIES-RESEARCH.md
59│ ├── TESTING-STRATEGY-RESEARCH.md
60│ ├── CI-PATTERNS-RESEARCH.md
61│ └── CRATE-ECOSYSTEM-RESEARCH.md
62├── plans/ # execution plans (non-normative)
63│ ├── README.md # plans index + coverage
64│ ├── WALKING-SKELETON.md # first vertical slice — implementation entry
65│ ├── TASK-BREAKDOWN.md # crate build order
66│ └── PLUGIN-DOC-PLAN.md # doc-SDK tooling
67└── PROJECT-INVARIANTS.md # this file
69prototypes/ # ← disposable spec-validation prototypes
70├── CLAUDE.md # prototype rules
71└── PLAN.md # prototype plan + result blocks
17```text
18cargo build
19cargo test
20cargo fmt
21cargo clippy
22cargo run -p xtask -- <command>
7223```
74Former `docs/design/` subsystem docs were fully absorbed into `docs/SPEC.md`
75and deleted (2026-07-15; see git history).
25Forbidden 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/`.
27- Makefiles;
28- justfiles;
29- root scripts;
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
35Workspace 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.
87```toml
88# rust-toolchain.toml
89[toolchain]
90channel = "stable"
91components = ["rustfmt", "clippy"]
39```text
40smith/ shared contracts
41smith-core/ agent runtime
42smith-ai/ provider integrations
43smith-tui/ terminal frontend
44smith-harness/ orchestration and Lua plugins
45smith-cli/ executable
46xtask/ Cargo orchestration
47docs/SPEC.md product contract
48docs/research/ retained evidence
49prototypes/ isolated disposable proofs
9250```
94### 3.2 Clippy — Zero Warning Policy
52Product 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.
54## 4. Rust
98#### Where lints live
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 via
101`[lints] workspace = true` — never `rustflags`.** A `[target.<triple>].rustflags`
102key *replaces* `[build].rustflags` instead of merging, so a target carrying any
103flag of its own would build with the whole wall switched off; Android needs
104exactly such a flag (§8a). Lint tables are per-crate and target-independent, and
105apply only to workspace crates rather than leaking denials into dependencies.
64## 5. Dependencies
107Denied: the clippy **all / pedantic / suspicious / complexity / perf / style /
108correctness** 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 flag
114and the sparse registry protocol.
75## 6. Verification
116```toml
117# .clippy.toml — configuration VALUES only; enablement lives in [workspace.lints]
118cognitive-complexity-threshold = 25
119# No msrv key: lint policy follows latest stable Rust.
77Before integration, run the smallest complete applicable gate. At minimum:
79```text
80cargo fmt --all --check
81cargo test --workspace
12082```
122#### Command
84Rust 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.
124```bash
125cargo clippy --workspace --all-targets --all-features
126```
86Release 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:
90Agents MUST obtain explicit owner approval before modifying:
132```rust
133// BAD — no reason, will rot
134#[allow(clippy::unwrap_used)]
92- `docs/SPEC.md`;
93- `docs/PROJECT-INVARIANTS.md`;
94- root `Cargo.toml` dependency membership;
95- `.cargo/config.toml`;
96- `rust-toolchain.toml`;
97- CI definitions under `.ci/`.
136// GOOD — reason documented, #[expect] preferred (Rust 1.81+)
137#[expect(clippy::unwrap_used, reason = "mutex never poisoned — sole accessor")]
138let guard = mutex.lock().unwrap();
139```
99Agents 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.
103- Git is canonical.
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.
112## 9. Services
147### 3.3 Format — Enforced
148```bash
149cargo fmt --check
150```
151CI 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
155```rust
156// Every lib.rs in workspace crates:
157#![forbid(unsafe_code)]
158```
160**Exception:** `smith-cli` binary crate may use `unsafe` for OS-specific terminal manipulation **only** when:
1611. No safe alternative exists in the ecosystem
1622. Wrapped in a safe abstraction with `// SAFETY:` comment
1633. The safe wrapper is unit-tested independently
1644. Approved in PROJECT-INVARIANTS with documented rationale
166**Clippy enforcement:**
167```rust
168-D clippy::undocumented_unsafe_blocks
169```
171Every `unsafe` block must have a `// SAFETY:` comment explaining:
172- What invariant makes this safe
173- Why no safe alternative exists
174- What could go wrong if the invariant is violated
176### 3.5 unwrap, expect, panic — Prohibited in Libraries
178Enforced by clippy:
179```rust
180-D clippy::unwrap_used
181-D clippy::expect_used
182-D clippy::panic
183```
185| 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
195```bash
196cargo doc --workspace --no-deps
197```
199**Doc lints (in `[workspace.lints]`, §3.2):**
200```rust
201-D missing_docs
202-D rustdoc::missing_crate_level_docs
203-D rustdoc::broken_intra_doc_links
204-W rustdoc::invalid_html_tags
205-W rustdoc::bare_urls
206```
208**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
217```bash
218cargo deny check
219```
220Run via CI. Forbids:
221- Duplicate versions of the same crate (without explicit exception)
222- Unmaintained crates (`cargo-deny` advisory-db)
223- Crates with incompatible licenses
225## 4. xtask Responsibilities
227xtask 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
252SPEC §14 states what a release must guarantee — one host, MSVC-ABI on Windows, a
253glibc floor below the build host, no target silently dropped. This is the encoding
254that currently satisfies it:
256This table is the **single** encoding of how each target is built; §8a points
257here rather than restating it.
259| Target family | Cross-compiler | Proven by |
260|---|---|---|
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 the
268second tool rather than a GNU-ABI substitute — SPEC §14 forbids that substitution
269outright, so "cheaper to produce" is not an argument available here.
271Both cross-compilers need something the host must already have: `zig` for one,
272an LLVM/clang installation for the other (`cargo-xwin` fetches Microsoft's SDK
273but not the compiler that consumes it). §1 names both as exceptions.
275The **Proven by** column is load-bearing, not commentary: SPEC §14 forbids the
276matrix claiming a target whose cross-build no prototype has exercised. Windows
277MSVC is listed here as the intended encoding and marked unproven — the release
278matrix may not depend on `cargo-xwin` until a §18 prototype builds with it.
279This table is an implementation choice and may change with the ecosystem; the
280guarantees in SPEC §14 may not.
282### xtask Implementation Rule
283xtask 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
287Files 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 root
292- adding or removing a crate in any `Cargo.toml` `[dependencies]` (version
293 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 new
298third-party crate — or removing one — changes the architecture, crate set,
299compile budget, and siloing, so a worker agent escalates to the spec owner and
300never introduces a crate on its own initiative. The canonical set is SPEC §2.3
301and the change follows the spec-approval path. A **version bump** of an
302already-approved crate is routine upkeep, not a spec decision: it may be done
303by a dedicated dependency-maintenance agent or automation, provided it passes
304every gate — build, tests, clippy, `cargo deny`, and the §13.1 compile-budget
305regression gate. A bump that is semver-incompatible, raises the toolchain MSRV,
306or trips the compile-budget gate escalates like a new dependency, because it
307can change behavior or cost. Prototypes under `prototypes/` are exempt from all
308of this (SPEC §18): adding a crate to validate it before production is their
309job, and that evidence is what gets escalated.
311Files that coding agents MAY modify freely:
312- `*/src/*.rs` (implementation)
313- `*/tests/*.rs` (tests)
314- `xtask/src/*.rs` (xtask commands)
315- `benches/*.rs` (benchmarks)
317Files that coding agents SHOULD read before modifying:
318- `docs/SPEC.md` (the canonical spec)
319- `CLAUDE.md` (project overview)
321### Integrity rules (absolute)
323Binding on every agent, tool, and automation, with no gated exception — these
324protect 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
3311. **Spec before code.** No `.rs` changes without corresponding `docs/SPEC.md` coverage (or documented exception).
3322. **The spec lives at `docs/SPEC.md`.** Code lives in crate directories.
3333. **Cross-references are unidirectional:** the spec may reference code paths; code does NOT reference the spec.
3344. **Spec changes require `cargo run -p xtask -- spec-verify` once xtask exists.**
336## 7. Version Control
338- **VCS:** the repository is **git**, hosted at
339 `git@vcs.bugabinga.net:smith.git`. `jj` (Jujutsu) is git-compatible and may be
340 used locally, but git is canonical and load-bearing.
341- **History is linear.** Integrate by signed fast-forward; never create merge
342 commits or force-push.
343- **Commits on `trunk` are signed.** Every commit that lands on `trunk` carries a
344 valid owner or agent signature.
345- **Commit messages:** plain imperative subject naming the decision or its
346 effect; no required type prefix; argue *why*, not *what*; no AI attribution.
347- **Branch naming:** `feature/description` or `fix/description`; delete topic
348 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).
358Benchmarks tracked with criterion. Baselines stored in `target/criterion/`. Regressions > 10% fail CI.
360## 8a. Release Artifact Invariants
362### Target Platforms
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,
3812026-07-25). Android/Termux on `aarch64-linux-android` is both the environment smith
382is developed in *and* a required release artifact: a terminal-first coding agent is
383used on a phone, not merely built for one. It is a third libc — **Bionic**, beside
384glibc and musl — which is why it gets its own row rather than a Linux variant.
385Bionic does not carry the compiler-rt builtins Rust expects, so vendored LuaJIT
386fails to link `__clear_cache` unless they are linked explicitly; that flag lives in
387`.cargo/config.toml` and is normative for this target, not a local workaround. This
388table and `docs/SPEC.md` §14 must agree — a target listed in one and absent from the
389other is drift.
391### Artifact Format
393Each 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 archives
397Nothing else. No install scripts, no package manifests, no distribution metadata.
399### Release Profile
401```toml
402[profile.release]
403opt-level = 3
404lto = "thin"
405codegen-units = 1
406strip = "symbols"
407panic = "abort"
408```
410No debug info in release builds. Debug symbols are produced only by the default (dev) profile.
412### Release Pipeline
4141. `cargo run -p xtask -- release` — builds every target, creates archives,
415 generates checksums. Which cross-compiler each target family uses is the §4
416 *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` for
418 Windows, which it does not support.
4192. Best-effort targets — riscv64, FreeBSD, OpenBSD — build natively where
420 possible and are skipped otherwise. A skip is reported, never silent
421 (SPEC §14); a *required* target that fails stops the release.
423No automated distribution or code signing exists yet; these remain deferred.
425See `docs/research/RELEASE-BUILD-RESEARCH.md` for cross-platform build tooling analysis.
427## 9. Testing Invariants
429See `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
443```toml
444[workspace]
445members = [
446 "smith",
447 "smith-core",
448 "smith-ai",
449 "smith-tui",
450 "smith-harness",
451 "smith-cli",
452 "xtask",
453]
454resolver = "3"
456[workspace.package]
457version = "0.1.0"
458edition = "2024"
459license = "Apache-2.0"
460```
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
473Allowed internal crate dependencies are fixed:
475| Crate | May depend on |
476|-------|---------------|
477| `smith` | none |
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` |
483| `xtask` | none |
485Forbidden:
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-moving
493third-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 up
496into `smith`. The foundation crate is depended on by every other crate, so any
497churn or heavy dependency there invalidates the whole workspace's incremental
498cache; keeping it minimal is what lets an edit to one leaf crate rebuild
499without touching the others' compiled artifacts. `smith` carries only small,
500stable, universally-shared code (its one heavy dependency, `mlua`, is a locked
501exception because the SDK type surface needs it).
503Architecture gates:
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
510Smith production code uses stable Rust.
512Exception: `cargo-pup` architecture linting runs on pinned nightly
513`nightly-2026-01-22` because it uses rustc internals.
515Rules:
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.
521## Change Log
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 |
122Generated 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.

docs/SPEC.md

Modified

+1229 / −2340 text lines

1# Smith Specification
1# Smith Product Specification
3Smith is a Rust coding-agent TUI. This document describes the desired project
4state. It is the canonical specification for architecture, crates, interfaces,
5configuration, plugins, CLI behavior, build gates, and testing.
3This 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.
7## 1. Product Shape
5## Product
9Smith is a fast, extensible AI coding agent with:
7### Product boundary
11- interactive terminal UI,
12- non-interactive eval mode,
13- JSON-RPC stdio mode,
14- Lua plugin system,
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.
9Smith MUST be a fast, extensible AI coding agent with:
19Core 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; and
17- 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 the
24 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 typed
27 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 improves
33 on pi's ideas with no data or format coupling to it.
34- **Exact at boundaries, shapes inside.** This spec is exact where others
35 program against it — files, wire formats, CLI, config, Lua SDK — and
36 shape-level (named types, behavior, properties) for internal Rust. Code
37 blocks are illustrative unless a section says otherwise.
19Cross-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.
39### 1.1 Walkthrough
21Every 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.
41The product, as a user meets it. Each scene pins observable behavior; the
42cited sections own the contracts. Three features that must never blur:
43**tree navigation** moves through the conversation tree (§6.5, files
44untouched), **time travel** moves workspace file state through the VCS
45operation timeline (§9.13), and **replay** re-executes a recorded trace
46(§6.11, never the live session).
23Smith MUST NOT depend on Pi or couple to Pi APIs, data, or formats.
48**First run.** `smith` in a project directory. No config exists; defaults
49apply (§5.6). Capabilities probe once, fail-conservative (§8.3). The default
50layout plugin renders status bar (model, context %, cost), message history,
51input, hint bar — all border panels closed; panels are strictly opt-in
52(§8.7). The empty history shows a few dim hint lines (active model, how to
53begin, `smith help`) that vanish at the first entry. No wizard, no
54onboarding. Startup under 100ms (§13).
25Files, 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 fast
57before the first stream (§7.4). The error is the guidance: a recoverable
58error (§5.8) renders in history naming the missing credential, the env var
59to set, and `/auth login <provider>` for OAuth (§9.11); the message stays in
60the input for immediate resend. The failure teaches; no setup flow exists.
27### First run
62**First task.** Text streams as it arrives. Tool calls render as collapsed
63one-liners that expand on selection (§8.10); cost and context tick live in
64the status bar. `!cargo test` runs directly and lands as a bash-execution
65entry (§6.5). Every mutating tool records a VCS operation invisibly (§9.13)
66— no commit prompts, no jj exposed.
29Running `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 as
69a steer; a modifier queues a follow-up instead (§6.1). The queue renders
70between history and input (§8.11). In-flight tools finish, never-started
71calls skip, the steer lands, the model re-plans. Cancel keys pop the queue
72newest-first; only an empty queue aborts.
31The default Lua layout plugin MUST render:
74**Tree navigation.** A refactor went sideways. `/tree` shows the session
75tree; the user switches the leaf to the pre-refactor entry. The conversation
76rewinds; files do not (§6.5). A new message from here is a new branch,
77silently.
33- a status bar showing the active model, context percentage, and accumulated cost;
34- message history;
35- input; and
36- a hint bar.
79**Time travel.** The files are still wrong. The time-travel timeline shows
80the VCS operations recorded around each entry; the user inspects op diffs
81and restores the workspace to the pre-refactor op (`/undo`, or restore from
82the timeline). Tree navigation answers "where were we in the conversation";
83time travel answers "what did the files look like." The timeline bridges
84them by offering the restore for the op recorded at the current entry — but
85they are separate axes.
38All 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` opens
88a fuzzy picker. Both operate on resolver names (§5.7) — aliases, groups,
89buckets — as first-class vocabulary, with the picker showing what each name
90resolves to. Raw provider/model IDs are the fallback, not the interface.
40### Missing authentication
92**Leaving and returning.** Quit restores the terminal (§10). `smith
93continue` resumes the last session in cwd — same leaf (§6.5 replay rule),
94queues empty (§6.1, process-ephemeral), accumulated cost in the status bar.
95`smith attach` fuzzy-picks among sessions.
42Authentication 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 diffs
99current outputs against recorded ones (§6.11). Replay reads the trace and
100never touches the live session.
44- the missing credential;
45- the environment variable to set; and
46- `/auth login <provider>` when that provider offers OAuth.
102## 2. Workspace
48The unsent message MUST remain in the input for immediate resend. Smith MUST NOT start a setup flow.
104### 2.1 Crates
50### Active work
106```text
107smith/ foundation crate: shared types, StreamFn, AgentTool, config, Lua runtime, errors
108smith-core/ agent loop, sessions, tools, hooks, compaction, cost, trace, replay
109smith-ai/ LLM providers, auth, model registry, provider streams, MuxProvider
110smith-tui/ terminal events, widgets, layout primitives, render loop, themes
111smith-harness/ orchestration, plugin system, SDK, event bridge, built-ins, help
112smith-cli/ binary entry point, clap CLI, session commands, eval/rpc/replay
113xtask/ Cargo-only automation
114```
52Assistant 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
54Input 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|-------|---------------|
120| `smith` | none |
56Every 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
60Submitting 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.
62A 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
66Conversation navigation, workspace restoration, and replay MUST remain distinct:
681. `/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.
692. 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.
703. 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.
72A 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.
74### Model selection
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
80Quitting 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.
86## Architecture
88### Crates
90| Crate | Required responsibility |
91|---|---|
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 |
102|---|---|
103| `smith` | no internal crate |
121104| `smith-core` | `smith` |
122105| `smith-ai` | `smith` |
123106| `smith-tui` | `smith` |
124107| `smith-harness` | `smith`, `smith-core`, `smith-ai`, `smith-tui` |
125108| `smith-cli` | `smith`, `smith-harness` |
126| `xtask` | none |
128Forbidden:
110Consequently:
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.
137Implementation-module public API exceptions are declared only in this table. An
138exception names the crate, the implementation-module path, the exact public
139symbols allowed there, and the reason the symbol cannot live at the crate root or
140in a dedicated public API module. An empty table means no exceptions.
120## Runtime Files
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` |
143127|---|---|---|---|
144| _none_ | _none_ | _none_ | _none_ |
146Crate roots and dedicated public API modules may declare public API normally.
147Every other public item under an implementation module must either be private to
148its crate or appear in the exception table above.
150Architecture gates:
152- `cargo run -p xtask -- arch` checks stable Cargo metadata and source
153 invariants not covered by pup, including the implementation-module exception
154 table above: any public item in an implementation module that is absent from
155 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 metadata
158 plus cargo-pup submodule output.
159- `cargo run -p xtask -- check` includes `arch` and `pup`.
161### 2.3 Workspace Manifest
163Workspace root:
165```toml
166[workspace]
167members = [
168 "smith",
169 "smith-core",
170 "smith-ai",
171 "smith-tui",
172 "smith-harness",
173 "smith-cli",
174 "xtask",
175]
176resolver = "3"
178[workspace.package]
179edition = "2024"
180version = "0.1.0"
181license = "Apache-2.0"
182```
184Required shared dependencies:
186```toml
187mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }
188mlua-pkg = "0.2"
189serde = { version = "1", features = ["derive"] }
190serde_json = "1"
191tokio = { version = "1", features = ["full"] }
192clap = { version = "4", features = ["derive"] }
193clap_complete = "4"
194crossterm = "0.28"
195ratatui = "0.29"
196ciborium = "0.2"
197bumpalo = "3"
198thiserror = "2"
199anyhow = "1"
200toml = "0.8"
201regex = "1"
202tokio-stream = "0.1"
203tracing = "0.1"
204tracing-subscriber = { version = "0.3", features = ["env-filter"] }
205reqwest = { version = "0.12", features = ["json", "stream"] }
206futures = "0.3"
207unicode-width = "0.2"
208unicode-segmentation = "1"
209syntastica = { version = "0.6", default-features = false, features = ["runtime-c2rust"] }
210syntastica-parsers = "0.6"
211fuzzy-matcher = "0.3"
212similar = "2"
213ignore = "0.4"
214grep = "0.4"
215grep-regex = "0.1"
216grep-searcher = "0.1"
217gix = { version = "0.85", default-features = false, features = ["blame", "blob-diff", "revision", "sha1", "blocking-network-client", "worktree-mutation"] }
218jj-lib = "=0.43.0"
219url = "2"
220oauth2 = "4"
221insta = "1"
222dirs = "5"
223jsonschema = "0.28"
224uuid = { version = "1", features = ["v7"] }
225assert_cmd = "2"
226assert_fs = "1"
227proptest = "1"
228expectrl = "0.9"
229criterion = { version = "0.5", features = ["async_tokio"] }
230zstd = "0.13"
231sha2 = "0.10"
232zip = { version = "2", default-features = false, features = ["deflate"] }
233tar = "0.4"
234flate2 = "1"
235```
237This list is the canonical dependency registry. Adding or removing a crate here
238is a spec decision (PROJECT-INVARIANTS §5): worker agents escalate to the spec
239owner and never introduce a dependency on their own; a prototype under
240`prototypes/` validates a candidate first, and its evidence is what the
241decision rests on. Version bumps of an already-listed crate are maintenance,
242not 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,
244or budget-tripping bump escalates like a new dependency. Heavy dependencies
245attach at the crate that owns the concern and never propagate up into `smith`
246(PROJECT-INVARIANTS §11 dependency-siloing invariant), so a leaf-crate edit
247never rebuilds an unrelated crate's dependency tree.
249Two version constraints are load-bearing (prototype-decided, p25/p26): `gix`
250is pinned to the version `jj-lib` pulls (0.85) so the two never compile a
251duplicate gix tree, and `jj-lib` is pinned exact because it is pre-1.0 with a
252roughly monthly, unstable API — the `smith.vcs.*` façade (§9.13) absorbs the
253upgrade churn. `jj-lib`'s transitive `kstring` resolves to a version needing
254rustc 1.96; until stable Rust reaches it, `Cargo.lock` pins `kstring = 2.0.2`.
255This is a lockfile pin of a dependency, not a declaration of Smith's own MSRV,
256so PROJECT-INVARIANTS §3.1 stands; it self-heals once stable ≥ 1.96.
258Release profile:
260```toml
261[profile.release]
262opt-level = 3
263lto = "thin"
264codegen-units = 1
265strip = "symbols"
266panic = "abort"
268[profile.release.package."*"]
269opt-level = 3
270```
272## 3. Toolchain, Lints, and Build Gates
274### 3.1 Rust Toolchain
276`rust-toolchain.toml`:
278```toml
279[toolchain]
280channel = "stable"
281components = ["rustfmt", "clippy"]
282```
284Smith follows latest stable Rust. Do not pin a numeric MSRV unless release
285engineering creates a formal support window.
287Nightly exception:
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 moving
293 product code to nightly.
294- Pup failure blocks commit, PR, and release.
296### 3.2 Lints
298**Zero warnings.** A warning is an error; nothing merges or releases with one
299(PROJECT-INVARIANTS §3).
301Denied for every workspace crate: the `clippy` **all / pedantic / suspicious /
302complexity / perf / style / correctness** groups; the restriction lints
303**`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`**.
306Warned, 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 every
310target in the §14 matrix; no per-target build configuration may weaken it. This is
311a requirement, not a preference — the obvious encoding (global compiler flags) has
312the property that a target needing any flag of its own silently loses every lint,
313and a required release target needs exactly that. Whatever mechanism carries the
314wall must therefore be immune to per-target override, and must not impose smith's
315denials on third-party dependencies. `PROJECT-INVARIANTS` §3.2 records the
316encoding that satisfies this.
318Every library crate has:
320```rust
321#![forbid(unsafe_code)]
322#![warn(missing_docs)]
323```
325`smith-cli` may use unsafe only for OS terminal manipulation when no safe
326alternative exists, wrapped in a tested safe abstraction with `// SAFETY:`.
328### 3.3 Clippy Policy
330- Zero warnings.
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]`.
336`.clippy.toml`:
338```toml
339cognitive-complexity-threshold = 25
340```
342### 3.4 Audit
344`cargo run -p xtask -- audit` runs:
346```bash
347cargo deny check
348cargo audit --deny warnings
349```
351`deny.toml` allows Apache-2.0, MIT, and Unicode-DFS-2016. Duplicate versions are
352warned unless explicitly accepted.
354### 3.5 cargo-pup
356Root `pup.ron` exists and is required. Cargo-pup is the pinned-nightly source
357architecture lint gate. `xtask arch` remains the stable Cargo metadata gate.
359Initial pup rules enforce:
361- hygienic `mod.rs`,
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`.
367Crate-boundary module match patterns must include the crate root. Use
368`^crate($|::.*)`, not only `^crate::.*`. Cargo-pup sees root-owned items in
369`lib.rs`/`main.rs` under the crate name itself.
371Required boundary patterns:
373```ron
374matches: Module("^smith_core($|::.*)")
375matches: Module("^smith_ai($|::.*)")
376matches: Module("^smith_tui($|::.*)")
377```
379`cargo pup print-modules` is not a complete module inventory. It can omit crate
380roots and can emit synthetic `unknown_crate` for crates with no child `mod`
381items. Developer-facing module inventory uses `cargo run -p xtask -- print-modules`,
382which prefixes crate roots from stable Cargo metadata and then prints
383cargo-pup-discovered submodules.
385Required setup:
387```bash
388rustup component add --toolchain nightly-2026-01-22 rust-src rustc-dev llvm-tools-preview
389cargo +nightly-2026-01-22 install cargo_pup
390```
392Gate:
394```bash
395cargo +nightly-2026-01-22 pup
396```
398## 4. Runtime Directories and Files
400Smith uses XDG-style directories via `dirs`.
402| Platform | Config | Data | Cache |
403|----------|--------|------|-------|
404128| 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/` |
406130| Windows | `%APPDATA%\smith\` | `%LOCALAPPDATA%\smith\` | `%LOCALAPPDATA%\smith\cache\` |
408Data layout:
132When platform paths coincide, their children MUST coexist in that directory. The required layout is:
410134```text
411data_dir/smith/
135<data_dir>/
412136 sessions/
413137 {session-id}.session
414138 {session-id}.trace
415139 plugins/
140 <org>/<name>/
416141 data/
142 <org>/<name>/
417143 vcs/
418144 {project-hash}/
419145 jj-state/
421cache_dir/smith/
147<cache_dir>/
423config_dir/smith/
149<config_dir>/
424150 config.lua
425151 auth.json
426152```
428Session files are plaintext length-prefixed CBOR sequences. Trace files are
429compressed deterministic replay logs. Secrets in sessions are plaintext after
430local registration (§6.7, §11).
154Workspace-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 no
435downstream 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.
437Exposed 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`),
441- `StreamFn` (§5.4),
442- `LuaRuntime` (§5.5),
443- `Config` (§5.6),
444- the model-resolution types (§5.7): `ModelAlias`, `ModelGroup`,
445 `ProviderBucket`, `ModelResolver`, `ResolvedModel`, `ResolveError`,
446- `SmithError` (§5.8).
162Plaintext 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 from
449their owning crates.
164### VCS state
451### 5.1 IDs and Messages
166VCS 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.
453Required shared types:
168## Shared Contracts
455- `EntryId(String)` — UUID v7, time-sortable.
456- `SessionId(String)`.
457- `SecretId(String)`.
170### Required `smith` exports
172The `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`;
177- `StreamFn`;
178- `LuaRuntime`;
179- `Config`;
180- `ModelAlias`, `ModelGroup`, `ProviderBucket`, `ModelResolver`, `ResolvedModel`, and `ResolveError`; and
181- `SmithError`.
183### IDs, roles, content, and messages
185The required ID types are:
187- `EntryId(String)`, containing a time-sortable UUID v7;
188- `SessionId(String)`;
189- `SecretId(String)`; and
458190- `VcsOpId(String)`.
459- `Role`: `System`, `User`, `Assistant`, `Tool`.
460- `ContentBlock` — the authoritative content representation:
461 - `Text(String)`,
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 opaque
466 and preserved, never consumed by Smith; provider adapters attach it (e.g.
467 thinking signatures) and replay it on later requests (§7.2), so signed
468 thinking round-trips across turns.
469- `Message { role, content: list of ContentBlock }`.
471Roles say who speaks; entry kinds say what happened. Tool results are
472`Tool`-role messages carrying `ToolResult` blocks — there is no tool-result
473role. Events like user bash executions are `SessionEntry` kinds (§6.5), not
474roles.
192`Role` MUST have exactly these variants:
476### 5.2 Provider Types
194```text
195System | User | Assistant | Tool
196```
478- `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`.
481- `ProviderEvent`:
482 - `TextDelta { text }`,
483 - `ThinkingDelta { text, provider_metadata? }` — `provider_metadata` is
484 opaque, optional, and attached by the provider adapter to the delta whose
485 thinking text it authenticates,
486 - `ToolCall { id, name, arguments }` — assembled and complete; partial
487 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 by
491 `MuxProvider` (§7.5), each carrying a message: `RateLimit`, `AuthFailed`,
492 `Network`, `ServerError`, `InvalidRequest`, `ModelNotFound`, `Timeout`.
493- `ProviderRequest` contains messages, system prompt, model/provider IDs, tool
494 definitions, thinking level, token limit, and stop sequences.
198`ContentBlock` is the authoritative message-content representation and MUST support exactly these shapes:
496### 5.3 Tool Types
200```text
201Text(String)
202Image { data, media_type }
203ToolCall { id, name, arguments }
204ToolResult { id, result, is_error }
205Thinking { content, provider_metadata? }
206```
498- `ToolDefinitionSpec` is serializable metadata for LLM function calling and
499 plugin metadata.
500- `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 surfaced
505 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.
508### 5.4 StreamFn
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.
212### Provider types
214`ProviderUsage` MUST track:
216```text
217input_tokens
218output_tokens
219cache_read_tokens
220cache_write_tokens
221total_tokens
222```
224`StopReason` MUST have exactly:
226```text
227EndTurn | ToolUse | OverMaxTokens | Aborted | StopSequence | Error
228```
230`ThinkingLevel` MUST have exactly:
232```text
233Off | Minimal | Low | Medium | High | XHigh
234```
236`ProviderEvent` MUST support:
238```text
239TextDelta { text }
240ThinkingDelta { text, provider_metadata? }
241ToolCall { id, name, arguments }
242Done { usage, stop_reason }
243Error(ProviderError)
244```
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:
250```text
251RateLimit
252AuthFailed
253Network
254ServerError
255InvalidRequest
256ModelNotFound
257Timeout
258```
260`ProviderRequest` MUST contain:
262```text
263messages
264system_prompt
265model_id
266provider_id
267tool_definitions
268thinking_level
269token_limit
270stop_sequences
271```
273### Tool types
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.
281Tool arguments MUST be JSON and MUST be validated against the tool's JSON Schema before execution.
283### `StreamFn`
510285`StreamFn` is the provider abstraction consumed by `smith-core`:
512- input: `ProviderRequest`,
513- output: async stream of `ProviderEvent`,
514- no dependency on `smith-ai`.
287```text
288ProviderRequest -> asynchronous stream of ProviderEvent
289```
516This permits `smith-core` and `smith-ai` to build independently.
291It MUST have no dependency on `smith-ai`.
518The agent loop assembles consecutive `ThinkingDelta` events into a
519`ContentBlock::Thinking`. It concatenates `text` in arrival order and carries
520forward every non-empty `provider_metadata` value into the assembled block. If a
521provider emits more than one metadata value for one assembled thinking block,
522the block stores them in arrival order inside the opaque metadata payload;
523Smith still never interprets them. This is the only route by which signed
524thinking metadata crosses the `StreamFn` boundary and becomes available for
525provider replay (§7.2).
293The 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.
527### 5.5 Lua Runtime
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:
531Allowed standard libraries:
299```text
300string, table, math, coroutine, utf8, package
301```
533- `string`,
534- `table`,
535- `math`,
536- `coroutine`,
537- `utf8`,
538- `package` with custom searchers.
303`package` MUST use only the host's custom searchers. The following globals MUST be removed:
540Removed globals:
305```text
306io, os, debug, getfenv, setfenv
307```
542- `io`,
543- `os`,
544- `debug`,
545- `getfenv`,
546- `setfenv`.
309Host APIs MUST be obtained with:
548Smith host APIs are exposed through `require("smith")`.
311```lua
312local smith = require("smith")
313```
550No bytecode cache. The cache's premise is disproved (p17): loading cached
551bytecode saves ~285µs per 2000-line module over compiling source (LuaJIT
552compiles fast; stripped bytecode is even larger than source), while cached
553bytecode is the most dangerous input path possible — LuaJIT has no bytecode
554verifier, and corrupted images segfault the VM (~20% of trials) or silently
555execute wrong code (~12%).
315Lua 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.
557Binary chunks are therefore forbidden entirely: **every Lua source load
558specifies text-only chunk mode explicitly**. mlua's default mode accepts
559binary chunks auto-detected inside `.lua` files (p17) — relying on the
560default would let a plugin ship raw bytecode past the loader.
317### Configuration
562### 5.6 Config
319Lua 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:
564Lua is the configuration language. Rust defines schemas; Lua supplies values.
566Cascade order, later overrides earlier:
5681. Rust type defaults/schema,
5692. built-in Lua defaults,
5703. plugin contributions,
5714. user config at `config_dir/smith/config.lua`,
3211. Rust type defaults and schema;
3222. built-in Lua defaults;
3233. plugin contributions;
3244. `config_dir/config.lua`;
5723255. CLI flags.
574Invalid values are rejected with clear errors. Unknown keys warn in the
575top-level schema context and fail in strict contexts (`models.*`,
576`compaction.*` — anywhere a typo silently changes behavior).
327Later 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.
578Cross-layer merge is leaf-field recursive for table-valued keys; scalars
579AND lists are leaves that replace wholesale (prototype-proven, p16: under
580layer-replace, a user overriding one keybinding wipes the builtin
581`ctrl+c = abort` binding, and a plugin contributing one alias clobbers the
582builtin alias map). Same rule family as §7.3's registry merge.
329Invalid 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.
584The cascade is re-evaluated at runtime by host configuration reload (§9.19).
586Example:
331The full applicable cascade MUST be re-evaluated on runtime host-configuration reload. A valid configuration includes this shape:
588333```lua
589334return {
598343```
600### 5.7 Models, Aliases, Groups, Buckets
345### Models, aliases, groups, and buckets
602`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,
605- context window,
606- max output tokens,
607- cost,
608- capabilities: thinking, vision, tool use, streaming.
610`ModelResolver` is pure. It resolves:
349`ModelResolver` MUST resolve through this chain:
612351```text
613requested name → alias → group → bucket/account → provider/model metadata
352requested name -> alias -> group -> bucket/account -> provider/model metadata
614353```
616Rules (prototype-proven, p18):
355Resolution 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 exporting
619 rotation state: `resolve` is a pure function of (validated config,
620 requested name, rotation cursors); the cursors are owned and advanced by
621 `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 path
624 (`cycle detected at config load: a → b → a`); DAG diamonds do not
625 false-positive,
626- load-time rejections: a name defined as more than one kind (alias AND
627 group, all kinds named in the error), empty groups, empty bucket account
628 lists, dangling references (referrer named), duplicate members within one
629 group list, and buckets whose target is not a concrete model. Unknown
630 requested name is the only resolve-time error,
631- DAG-induced duplicate candidates (two paths reaching the same
632 provider/model/account) survive flattening; Mux deduplicates identical
633 candidates before attempting them,
634- `ResolvedModel` carries metadata needed by `smith-core`.
357Configuration loading and reload MUST validate the whole graph and MUST:
636Failover:
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; and
366- reject a bucket target that is not a concrete model.
638- `FailoverStrategy`: ordered or round-robin.
639- `BucketStrategy`: account rotation policy; bucket accounts are individual
640 failover candidates under §7.5.
641- Rate limits fail over immediately.
642- Non-rate-limit transient errors retry before failover; the retry count is
643 the `providers.retry_count` config key, default `2`.
368After successful validation, an unknown requested name MUST be the only resolution-time error.
645### 5.8 Errors
370Duplicate 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 at
648their subsystems: `ProviderError` (§5.2), auth (§7.4), tool errors including
649the §9.12 codes, config validation (§5.6), Lua (§5.5), I/O, session/trace
650codec (§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`.
652Recoverability is the load-bearing property of every error path:
374### Shared errors
654- **Recoverable** (the default): the failure surfaces to the user and/or the
655 LLM as content — error tool results (§6.4), UI notifications, plugin
656 diagnostics (§9.17) — and the loop continues. Provider failures (§7.5),
657 tool errors, plugin faults and OOM (§9.14, §9.17), and rejected config
658 reloads (§9.19) are all recoverable.
659- **Fatal**: the process cannot continue safely — unrecoverable terminal
660 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:
663Shipped library code never panics for external failures; internal impossible
664states use debug assertions.
378- `ProviderError`;
379- authentication;
380- tools, including defined tool error codes;
381- configuration validation;
382- Lua execution;
383- I/O;
384- session and trace codecs; and
385- model resolution.
666## 6. Core Crate: `smith-core`
387Recoverability 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,
669secret proxy, compaction, cost, trace, and replay. It depends only on `smith`.
389Provider 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.
671Responsibilities (names, not module layout): the agent loop (§6.1), agent and
672engine events (§6.2–§6.3), hooks (§6.4), session model and format (§6.5–§6.6),
673secret proxy (§6.7), system prompt (§6.8), compaction and cost (§6.9), tool
674registry (§6.10), trace and replay (§6.11).
391Shipped library code MUST NOT panic on external failures or plugin input. Impossible internal states MAY use debug assertions.
676### 6.1 Agent Loop
393## Core
678The agent loop:
395### Agent runtime
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.
397The 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.
687Steering and follow-up semantics:
399The loop MUST use:
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 fresh
691 user message and starts a new turn cycle.
692- **Steering**: delivers at the next safe boundary — after the current
693 provider stream completes, or after in-flight tool execution finishes.
694 Never-started tool calls from the current assistant message resolve as
695 error-flagged synthetic results (`skipped: user steered`) so every call
696 has a result on the wire; the model re-plans with the steer visible. All
697 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 is
700 queued, no new call starts; every already-started call runs to
701 completion; only never-started calls skip,
702 - steer arriving mid-stream: no call of that assistant message has
703 started, so ALL of them skip — none executes,
704 - transcript ordering: real results first (completion order in parallel
705 mode), then synthetics in original call order, then the drained steers,
706 - skipped calls emit `ToolExecutionStart`/`ToolExecutionEnd` with error
707 flag and reason, per the §6.4 blocked-call contract.
708- Interactive input during an active run is a steer by default; a modifier
709 submits it as a follow-up (§8.11). Plugins override default user-message
710 behavior through the `input` hook (§9.8) and send programmatically via
711 `smith.send_message` (§9.10).
712- Queues are ephemeral process state: queued messages become session entries
713 when delivered, never when queued — the session records only what the model
714 saw. Compaction (§6.9) neither consumes nor drops the queues.
715- Cancel keys pop the queue before they abort: see §8.11. A delivered abort
716 (§12) ends the run; whatever remains queued stays queued and is surfaced by
717 the TUI for the user to send, edit, or discard. An abort can leave the
718 session tail with an assistant message whose tool calls have no results
719 (no next request exists to carry synthetics); request assembly after
720 resume must repair such a dangling tail by synthesizing aborted-results
721 for the unanswered calls (p14).
401- an outer loop for turns and follow-up user messages; and
402- an inner loop for provider streaming, tool calls, and steering.
723The 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; and
410- typed hook callbacks.
728Important config:
412Every 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,
734- hook callbacks.
414### Follow-up and steering semantics
736Abort:
416Follow-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.
418A 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.
742### 6.2 Agent Events
420Once 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:
422A 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`,
751- `Error`.
4241. real results in completion order;
4252. synthetic results in original tool-call order; then
4263. drained steering messages in FIFO order.
753`AgentEvent::to_session_entry(timestamp)` returns a `SessionEntry` only for
754conversation-relevant completed events.
428Every 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
430Interactive 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:
432Both 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.
760- session lifecycle,
761- steering/follow-up,
762- UI state changes,
763- provider/model changes,
764- errors and shutdown.
434A 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 the
767frontend stream: every frontend (the built-in TUI in-process, §8; any RPC
768client out-of-process, §10.4) consumes `EngineEvent` and submits intents back.
769Some variants — TUI-internal UI state changes — are in-process-frontend-private
770and are not exposed out-of-process.
436### Agent and engine events
772### 6.4 Hooks
438`AgentEvent` MUST be the source of truth for agent behavior and MUST include:
774Core hook result types:
440```text
441AgentStart, AgentEnd
442TurnStart, TurnEnd
443MessageStart, MessageUpdate, MessageEnd
444ToolExecutionStart, ToolExecutionUpdate, ToolExecutionEnd
445TextDelta, ThinkingDelta
446Error
447```
776- `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.
782Blocked-call contract (prototype-proven, p07): a blocked tool call never
783executes the tool, still emits `ToolExecutionStart` and `ToolExecutionEnd`
784(with error flag and the block reason) so the UI can show it, and feeds the
785block 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.
453### Core hooks
789### 6.5 Session Model
455The hook API MUST provide these exact result types and choices:
791`Session` contains:
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; and
461- `TransformContext`: mutate LLM context before a provider request.
793- `SessionId`,
794- optional name,
795- cwd,
796- entries,
797- current leaf,
798- created/updated timestamps.
463A 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.
800Sessions are branching trees. A branch is emergent, not stored: the path from
801root to a leaf. `ctx.session.branch()` (§9.9) returns the current path.
802"Immutable once created" means entries are append-only and never rewritten —
803working from an older point creates a new child, never edits history. `/tree`
804and history/time-travel features are Lua plugins over this core state.
465### Session model
806Tree operations:
467`Session` MUST contain:
808- **append**: adds an entry as a child of the current leaf; the leaf advances
809 to it. Appending while the leaf sits on a non-leaf entry creates a fork
810 point implicitly — there is no explicit branch operation.
811- **switch leaf**: moves the current leaf to any entry, recorded by appending
812 a leaf-switch metadata entry. On load, the leaf is resolved by replaying
813 surviving entries in file order: an append moves the leaf to itself, a
814 leaf-switch moves it to its target — the last surviving entry decides
815 (prototype-proven, p12; the naive "last switch target" rule yields a stale
816 leaf once appends follow a switch). A leaf-switch whose target was lost to
817 §6.6 recovery is ignored on replay. Leaf state rides the append-only
818 recovery guarantees, and leaf history is replayable for free.
819- **read path**: returns the root→leaf path. The LLM context is built from
820 the current path only (through compaction, §6.9); sibling branches are
821 invisible to the model.
822- **fork**: clones entries up to a given entry into a new `SessionId` and
823 session file (the `session_before_fork` event, §9.8). Distinct from in-tree
824 branching, which stays in one file.
469```text
470SessionId
471optional name
472cwd
473entries
474current leaf
475created timestamp
476updated timestamp
477```
826No branch deletion or pruning exists in v1. A session has a single writer:
827one agent loop appends to it at a time.
479A 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.
829Recovery meets the tree (p12): a §6.6-skipped entry can be a parent or a
830switch target. Orphaned subtrees (parent missing) are detached and reported —
831unreachable from the root, never silently grafted; dangling leaf-switches are
832ignored during leaf replay.
481Append behavior:
834Leaf switches never touch the working tree. Filesystem time travel is plugin
835policy, not core behavior: the time-travel plugin (§9.11) pairs leaf switches
836with `smith.vcs.op_restore` using the `VcsOpId` stored in entries.
837Conversation 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:
486Leaf-switch behavior:
841- user message,
842- assistant message,
843- tool call,
844- tool result,
845- system prompt snapshot,
846- compaction summary,
847- secret registration,
848- model/provider change,
849- VCS operation,
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.
854Every entry has a stable `EntryId`, optional parent, and timestamp. New entry
855kinds are forward-compatible by construction: readers preserve unknown
856variants (§6.6), so adding a kind never breaks older sessions or readers.
495Path 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
497Session 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.
860Session files are length-prefixed CBOR sequences:
499If 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
503Every `SessionEntry` MUST have a stable `EntryId`, optional parent, and timestamp. Supported variants MUST include:
505- user message;
506- assistant message;
507- tool call;
508- tool result;
509- system-prompt snapshot;
510- compaction summary;
511- secret registration;
512- model/provider change;
513- VCS operation;
514- user bash execution, including `!` and `!!` command and output;
515- leaf switch; and
516- metadata required for migration and replay.
518Readers MUST preserve a well-formed unknown entry variant as raw data so future variants survive rewrite or migration round trips.
520The file framing is exact:
862522```text
863523u32 BE len | CBOR entry bytes | u32 BE len | CBOR entry bytes | ...
864524```
866Properties (recovery boundaries prototype-proven, p06):
526Recovery MUST obey these boundaries:
868- truncated tail stops parsing; prior entries survive,
869- a corrupt entry BODY is precisely skippable with a warning — the intact
870 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 survives
875 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.
879### 6.7 Secret Proxy
535`smith session dump` MUST emit JSONL. Session discovery MUST recognize only canonical `{session-id}.session` names.
881The secret proxy prevents LLM exposure of registered secrets. Smith provides
882the masking mechanics only; secret *detection* mechanisms are out of scope
883for core and belong to plugins.
537### Secret proxy
885**Registry.** The proxy holds a table of `SecretId → plaintext + label`.
886Registration paths:
539#### Registry and registration
888- automatic: every credential the auth resolver loads (§7.4) — provider keys
889 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 through
891 the SDK,
892- explicit: the built-in `/secret` command (§9.11),
893- plugins: `smith.secret.register(value, label)` (§9.10). Detection plugins
894 (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.
541The 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 against
899registered values — no heuristics in core. Content is masked to `smith:sec:N`
900placeholders *before* it becomes a session entry. Plaintext exists in exactly
901one entry kind: the secret-registration entry (preserved structurally by
902compaction but masked in provider rendering, §6.9). The ingestion scan runs
903after plugin `input`/`tool_result` hooks, so a value registered during those
904hooks is masked in the very content that surfaced it. On resume, the table
905rebuilds by scanning session entries backward for registration entries, and
906the `SecretId` allocator resumes past the highest id seen — a reused id would
907silently alias older placeholders (p13).
543Registration paths are:
909Masking 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`; and
548- programmatically through `smith.secret.register(value, label)`.
911- masking is **longest-match-first** in a single left-to-right pass that
912 never rescans emitted placeholder text — any other order provably leaks
913 residue of an overlapping secret,
914- rehydration is likewise single-pass; produced plaintext is never rescanned,
915- registration rejects values matching the placeholder grammar
916 (`smith:sec:<digits>`) with a diagnostic — accepting them aliases
917 legitimate placeholders,
918- re-registering identical plaintext is idempotent and returns the existing
919 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`).
550Detection 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:
924immediately before tool execution (subprocess and tool `execute`, Rust and
925Lua alike). Session content, provider requests, traces, and events carry
926placeholders only. Replay with compare (§6.11) re-executes tools and
927therefore rehydrates from the session's registration entries; trace files
928themselves stay masked. A placeholder whose ID is not registered passes
929through 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`; and
554- after resume, allocate above the greatest ID found in the session.
931**Display.** The TUI renders placeholders masked with their label
932(`‹secret: github-token›`); display matches context content. The local user
933can recover plaintext from registration entries via `smith session dump`.
556Placeholder 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 scan
936applies to post-transform content only, with exact case- and
937encoding-sensitive matching: a hook that re-encodes a secret while
938transforming (§9.8) launders the derived form past the scan (p13) —
939pre-transform text is never persisted, so this is a stated boundary, not a
940bug. The protection target is the remote LLM; the trust model is §11's, and
941core does no best-effort guessing.
558#### Ingestion masking
943### 6.8 System Prompt
560Masking 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:
562Matching 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.
947- base identity,
948- active model/tool capabilities,
949- plugin prompt contributions,
950- project/context facts,
951- safety and tool-use instructions,
564Pre-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.
566#### Rehydration
568A 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.
570Compare 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
574The 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.
576An 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.
578### System prompt
580`SystemPromptBuilder` MUST compose:
582- base identity;
583- active model and tool capabilities;
584- plugin prompt contributions;
585- workspace and context facts;
586- safety and tool-use instructions; and
952587- user overrides.
954Plugins may transform prompts through typed hooks. No hidden global prompt mutation.
589Plugins 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.
956The system prompt bootstraps SDK self-learning: it teaches the agent to
957discover plugin/SDK capabilities through `smith help --search`, `--guide`, and
958`--example` (§10.2) instead of embedding the full SDK reference inline.
591### Append-only compaction
960### 6.9 Compaction and Cost
593Compaction MUST neither rewrite nor delete history. Storage MUST retain every entry verbatim and remain memory-bounded through lazy loading.
962Compaction never rewrites history. Entries are append-only (§6.5), so
963compaction is a mask applied at context-assembly time, not a storage
964mutation:
595A 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, and
970 before/after token estimates.
971- **Context assembly folds the path** (§6.5 read path): spans covered by a
972 summary entry collapse into the summary; trim-masked content collapses
973 into stubs. What the model sees is the folded path; the file is untouched.
597```text
598from: EntryId
599to: EntryId
600summary text
601before token estimate
602after token estimate
603```
975Because the summary rides the path like any entry, branching needs no
976special case: switching the leaf to a pre-compaction entry yields a path
977without the summary — full history visible again, eligible to re-compact
978(producing a sibling summary on that branch) — and branches created after
979the compaction point inherit the mask.
605Context 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.
981Fold rules (prototype-proven, p12):
607Switching 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 segment
984 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 a
986 span crossing a fork point; a violating span is file damage — the fold
987 ignores that summary, shows the span raw, and diagnoses. Never a partial
988 collapse.
989- **Summaries nest**: re-compaction on an already-compacted path always
990 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 — leaf
993 resolution and replay read raw storage (§6.5), never the folded path, so
994 nothing is lost.
609A 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.
996Trigger (prototype-proven at ±1 token, p21): before each agent provider
997request — summarization requests are exempt from the trigger check, or the
998rule would be self-referential — when the estimated folded-path tokens
999STRICTLY exceed the threshold:
611Re-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
615Before every agent provider request except a summarization request, compaction MUST trigger only when estimated folded-path tokens strictly exceed:
1001617```text
1002618threshold = floor(threshold_fraction × context_window) − output_reserve_tokens
1003619```
1005All three values are named config keys (§5.6; reloadable per §9.19), with
1006the strict validity rule `recency_fraction + reserve_fraction <
1007threshold_fraction`, rejected at config load — otherwise the recency window
1008can dominate the budget and a triggered round can NEVER fit (the ladder
1009cannot touch the window), re-running the full ladder on every request
1010forever. Runtime guards back the static rule: a round whose protected
1011window alone exceeds the threshold reports and stops rather than spinning,
1012and a ladder pass that makes no progress aborts the round.
621The strict `compaction.*` schema MUST expose reloadable `threshold_fraction`, `output_reserve_tokens`, `recency_fraction`, `reserve_fraction`, `iteration_limit`, and `compaction_model` values. It MUST reject:
1014Trim ladder, cheapest first, repeated until the context fits or the
1015configured iteration limit is reached:
10171. mask old tool-result bodies to stubs (dominant bytes per the memory
1018 profile),
10192. mask old thinking blocks,
10203. LLM-summarize the oldest span. Summarization uses the active model unless
1021 the `compaction_model` config key selects another (resolved via §5.7, so
1022 aliases/groups work); its usage is tracked as normal cost.
1024Survives the trim ladder (never stubbed or discarded by a compaction round —
1025distinct from escaping a later covering span at fold time, which nothing
1026does):
1028- secret registrations (§6.7) — these survive *structurally*: hoisted out of
1029 collapsed spans so resume and rehydration keep working, but they hold
1030 plaintext, so the provider rendering masks/excludes them (§6.7 — a
1031 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 of
1035 the context window (token-budget based, so it adapts to model size).
1037A round cannot re-enter itself: it runs synchronously at the only trigger
1038site, before the agent's provider request. Reaching the iteration limit
1039terminates the round and reports — the request proceeds over budget, and
1040`session_compact` carries the outcome (fit, iteration-limit, no-progress,
1041recency-dominates).
1043`session_before_compact` (§9.8, blockable) may veto the round, adjust the
1044span, or replace the summarization prompt; `session_compact` reports the
1045result.
1047Token estimator:
1049- v1 heuristic: chars/4,
1050- exact tokenizer is not required in core.
1052Cost tracking:
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.
1062Rules:
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
1071Trace files capture deterministic replay data:
1073- file header with magic/version/session ID,
1074- compressed via block-level zstd (p20 measurements): ~4KiB blocks, entries
1075 under 64B never compressed individually, per-block raw-fallback flag —
1076 a trace never exceeds its uncompressed framed size by more than the fixed
1077 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 (leaf
1081 switches, compaction summaries, steer/follow-up deliveries, secret
1082 registrations with plaintext redacted idempotently; compare-mode
1083 rehydration reads the session file's registration entries, never the
1084 trace). Without this kind the reconstruction guarantee is unmeetable
1085 (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 the
1090 current leaf, both message queues, and the abort flag (p20: abort-time
1091 queue state is otherwise lost).
1093Trace guarantees:
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.
1100Replay modes:
1102- visual replay,
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 without
1114async-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 of
1119 `ProviderEvent` — a plain method returning a stream, not an async method.
1121`provider_to_stream_fn` adapts a shared `Provider` handle into the `StreamFn`
1122consumed by `smith-core`.
1124### 7.2 Provider Implementations
1126Required providers:
1128- Anthropic,
1129- OpenAI,
1130- Google,
1131- OpenAI-compatible local/remote endpoints.
1133Provider implementations normalize vendor wire formats into `ProviderEvent`.
1135Quirks 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` before
1140 the final answer on some OpenAI-compatible endpoints),
1141- provider-specific stop reasons,
1142- cache usage fields,
1143- model capability flags.
1145Error detection: some providers return errors as plain JSON bodies with
1146HTTP 200 instead of SSE (prototype-proven against a live OpenAI-compatible
1147endpoint). A provider implementation must detect a non-streaming JSON error
1148body on a streaming request and convert it to `ProviderEvent::Error` — never
1149hang 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-in
1154file is authoritative at runtime.
1156`fetch-providers` is a bootstrap and maintenance aid, not an automatic truth
1157source:
1159```bash
1160cargo run -p xtask -- fetch-providers
623```text
624recency_fraction + reserve_fraction >= threshold_fraction
1161625```
1163Data source priority for generated suggestions:
627A 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.
11651. models.dev (`https://models.dev/api.json` — the open, community-maintained
1166 model database with a CI-validated schema),
11672. catwalk provider configs,
11683. later shared provider repositories after review.
629The ladder MUST run in this order and repeat until context fits or `iteration_limit` is reached:
1170Merge rule (prototype-proven, p05):
6311. mask old tool-result bodies to stubs;
6322. mask old thinking blocks; then
6333. summarize the oldest eligible span with an LLM.
1172- merge by provider/model ID at LEAF-FIELD granularity — a recursive
1173 field-level merge; subtree or whole-model replacement would clobber curated
1174 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 ignored
1178 by v1. Preservation is semantic (value-equal), not byte-for-byte — default
1179 JSON tooling reorders keys. Unknown fields must never appear in generated
1180 diffs.
635Summarization MUST use the active model unless `compaction_model` chooses another. Aliases and groups MUST resolve normally. Summarization usage MUST enter normal cost accounting.
1182Conflict policy: some conflicts cannot be auto-merged and are excluded from the
1183suggestion and reported explicitly:
637Every round MUST protect from ladder trimming:
1185- type-mismatch-vs-curated: a source proposes a value whose structure differs
1186 from the hand-curated registry value (curated value kept). With schema
1187 validation at boundary 1, this class remains reachable only on
1188 schema-unconstrained (unknown) fields — real data contains live precedent
1189 (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 IDs
1192collapse at JSON parse time and are undetectable post-parse — p19. Detecting
1193them would require raw duplicate-key lexing, deferred until evidence demands
1194it.)
644Protection 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 PR
1197automation can never auto-merge a corrupting suggestion. Its outputs are the
1198suggested file, a reviewable source-attributed patch, and a machine-readable
1199conflict report.
646At 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.
648```text
649fit | iteration-limit | no-progress | recency-dominates
650```
1204**Canonical schema.** Smith does not invent a provider/model schema — it adopts
1205the models.dev shape and keeps a pinned local snapshot: a JSON Schema at
1206`smith-ai/src/providers.schema.json`. The pin procedure (p19: `api.json`
1207carries no in-band version and models.dev publishes no standalone schema
1208artifact) is: retrieval date + content sha256 of the reviewed snapshot,
1209recorded beside the schema; upstream evolution is reviewed like a dependency
1210bump.
652The blockable `session_before_compact` hook MAY veto the round, adjust its span, or replace its summarization prompt. `session_compact` MUST report the resulting outcome.
1212The schema is validated with the `jsonschema` workspace crate at three
1213boundaries (p19, executed against the full real registry — 166 providers,
12145666 models):
654### Token and cost accounting
12161. `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 a
1219 merge conflict,
12202. the merged result and the checked-in `providers.json` (full schema,
1221 CI gate),
12223. provider tables passed to `smith.provider.register` at runtime (§9.10).
656Version 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.
1224Registry 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`; tiered
1227fields `tiers`/`context_over_200k` are preserved, not consumed) — `cost` is
1228always an object when present, never a scalar, and is OPTIONAL (absent on
1229398/5666 real models: such models are priced-unknown and excluded from cost
1230tracking, never defaulted to zero); `limit` (`context`, `output` required
1231for chat models, `input` optional); modalities; capability flags
1232(`attachment`, `reasoning`, `tool_call`, `structured_output`, `temperature`)
1233are tri-state — absent means unknown, treated as false for gating and
1234preserved as absent. Unknown fields remain schema-legal
1235(`additionalProperties` allowed) per the preservation rule above.
658### Tool registry
1237Mapping 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|------------|-------------------|
662### Trace and replay
664A 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.
670Traces 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; and
678- an agent-state snapshot at every run end and abort.
680A 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.
682Trace 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.
684Replay 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.
686## AI
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; and
694- `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
700Smith MUST integrate:
702- Anthropic;
703- OpenAI;
704- Google; and
705- OpenAI-compatible local and remote endpoints.
707Each 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; and
714- model-capability flags.
716If 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.
722The 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.
724A 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`; and
731- `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.
735Eligible records MUST map to `ModelMetadata` as follows:
737| `ModelMetadata` field | Registry source |
738|---|---|
1241739| context window | `limit.context` |
1242| max output tokens | `limit.output` |
740| maximum output tokens | `limit.output` |
1243741| cost | `cost` |
1244742| thinking | `reasoning` |
1245| vision | `"image"` in `modalities.input` |
743| vision | presence of `"image"` in `modalities.input` |
1246744| 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 v1
1250`ModelMetadata` and are preserved, not consumed. (`reasoning_options` —
1251thinking-effort levels on 3578 real models — is a candidate for §5.2
1252ThinkingLevel configuration; preserved, consumption deferred.)
747`structured_output`, `temperature`, and `attachment` MUST be preserved in the registry but MUST NOT appear in version-1 `ModelMetadata`.
1254Mapping eligibility (p19): only chat-capable models map into
1255`ModelMetadata` — `"text"` in `modalities.output` and `limit.context > 0`.
1256Image/video generator models (limit 0) stay in the registry but are not
1257resolvable as chat models.
749Only 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.
1259Provider config correctness cannot be fully automated because Smith does not
1260have all provider accounts, subscriptions, API keys, or regional access.
1261Generated changes require review before commit.
751### Authentication
1263### 7.4 Auth
753The auth resolver MUST support credentials from:
1265Auth resolver sources:
755- environment variables;
756- `config_dir/auth.json`; and
757- plaintext Lua configuration when explicitly supplied.
1267- environment variables,
1268- `config_dir/smith/auth.json` (§4),
1269- plaintext Lua config values when explicitly supplied.
759Smith 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.
1271No OS keychain. No encryption.
761Each provider's registry `auth_types` map MUST declare supported methods:
1273Auth errors fail fast before first provider stream.
763- `api_key`, including its `env_var`;
764- `oauth`; and
765- `organization`, representing an organization-scoped credential such as an API key plus organization ID.
1275Auth methods per provider are declared in the registry's `auth_types` map:
1276`api_key` (with its `env_var` name), `oauth`, and `organization` (org-scoped
1277key, 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:
1281771```json
1289779```
1291OAuth module supports mocked OAuth flow in tests and provider-specific OAuth
1292where configured. OAuth per provider is configured with `id`, `name`,
1293`auth_url`, `token_url`, `scope`, and `client_id`; credentials are
1294`access_token`, `refresh_token`, `expires_at` (Unix seconds), auto-refreshed on
1295expiry. The login flow surfaces the auth URL to the user, receives the code via
1296a local callback HTTP server on a random port (or manual paste), exchanges it
1297for credentials, and persists them to `auth.json`.
1299### 7.5 MuxProvider
1301`MuxProvider` wraps multiple providers/accounts for resolved groups and buckets.
1303Behavior, 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, and
1314render loop. It depends only on `smith`.
1316**Frontend boundary.** `smith-tui` is the built-in *in-process frontend* — one
1317consumer of the `EngineEvent` stream (§6.3) that renders it and feeds intents
1318(prompt submit, steer, command, abort) back. It is not privileged as *the* UI:
1319the 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,
1321mobile). Those are RPC clients and link no smith Rust code. The render model
1322below — cells, borders, ratatui `Rect`s — is deliberately terminal-specific and
1323is **not** a cross-UI abstraction: a browser or GPU frontend brings its own
1324rendering and consumes only the event/intent surface, never smith's widgets.
1326### 8.1 Backend
1328Rendering uses:
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.
1334### 8.2 Events
1336`TuiEvent` normalizes crossterm events:
1338- keyboard,
1339- mouse,
1340- resize,
1341- focus gained/lost,
1342- paste.
1344Keyboard events include normalized key code, modifiers, and press/repeat/release
1345kind. Mouse events include button, scroll, position, and modifiers.
1347### 8.3 Terminal Capabilities
1349`TerminalCapabilities` records:
1351- truecolor,
1352- undercurl,
1353- Kitty keyboard protocol,
1354- bracketed paste,
1355- focus events,
1356- mouse support,
1357- Kitty graphics / sixel availability.
1359No terminfo database. Probe directly. Unsupported optional features degrade to
1360plain text without user-facing error.
1362Probe contract:
1364- capabilities are probed once per session at startup, with a 100ms timeout
1365 per probe; on timeout the capability is treated as absent (fail
1366 conservative),
1367- image protocol is `ImageProtocol::{Kitty, Sixel}`; the capability is
1368 detected but has no v1 consumer — inline image rendering is deferred
1369 (§8.12),
1370- Kitty keyboard protocol flags are pushed on TUI startup and popped on
1371 shutdown (including error/signal paths, §10),
1372- synchronized output (`CSI ?2026 h/l`) wraps render passes when the terminal
1373 supports it.
1375### 8.4 Component Trait
1377Components render into ratatui buffers and handle normalized `TuiEvent`.
1379Rules:
1381- rendering is deterministic,
1382- focus handling is explicit,
1383- event handlers return consumed/not-consumed,
1384- cached state has explicit invalidation.
1386### 8.5 TuiApp
1388`TuiApp` lifecycle:
781Provider OAuth configuration MUST support:
1390783```text
1391new → enter terminal → run event/render loop → shutdown → restore terminal
784id
785name
786auth_url
787token_url
788scope
789client_id
1392790```
1394The render loop ticks at 16ms. Event polling runs on a blocking thread and sends
1395normalized events over channels. `TuiApp` is created/driven by `smith-harness`.
792Stored OAuth credentials MUST contain `access_token`, `refresh_token`, and `expires_at` as Unix seconds. Expired credentials MUST refresh automatically.
1397States:
794`/auth login <provider>` MUST:
1399- `Idle`,
1400- `Thinking`,
1401- `ToolRunning`,
1402- `ToolResult`,
1403- `Error`,
1404- `Exiting`.
7961. surface the authorization URL;
7972. receive the authorization code from a local callback HTTP server on a random port or manual paste;
7983. exchange the code for credentials; and
7994. persist them to `config_dir/auth.json`.
1406Every state is interruptible.
801OAuth MUST permit mocked flows and provider-specific configuration.
1408### 8.6 Widgets
803### `MuxProvider`
1410Required 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:
1412- text,
1413- truncated text,
1414- spacer,
1415- markdown,
1416- message list,
1417- input area,
1418- status bar,
1419- hint bar,
1420- spinner,
1421- progress/cost/context indicators,
1422- tool call/result views,
1423- diff view,
1424- syntax-highlighted code,
1425- fuzzy list,
1426- tabs,
1427- scrollable,
1428- overlay,
1429- border layout panels.
807| `ProviderError` | Required behavior |
808|---|---|
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. |
1431Syntax highlighting uses `syntastica` with the `runtime-c2rust` runtime (no C
1432runtime dependencies; prototype-proven). Diffs use `similar` and support
1433unified and side-by-side modes. Fuzzy matching uses `fuzzy-matcher`.
817Authentication 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.
1435Overlays (modals, fuzzy search, autocomplete) are positioned by an anchor
1436model: nine anchors (`Center`, four corners, four edge-centers) plus
1437`offset_x`/`offset_y` and optional margin; overlay `width`/`max_height` are
1438`Size::Absolute(cells)` or `Size::Percent`.
819## TUI
1440### 8.7 Layout
821### Frontend boundary
1442Rust 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.
1444Primitives and their shapes:
825An 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 border
1448 (`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
1456One predefined border layout exists: center + north/east/south/west panels,
1457each panel carrying `visible`, `size`, and its own layout. Panels are invisible
1458when empty. Default layout is a Lua plugin.
829`TuiEvent` MUST normalize:
1460Composition rules (prototype-proven, p27):
831- keyboard;
832- mouse;
833- terminal resize;
834- focus gained/lost; and
835- paste.
1462- `overlay` floats over its container area and is excluded from the flow
1463 tiling set — flow siblings still tile as if it were absent, and the overlay
1464 is positioned by the §8.6 anchor model. Overlays may cover flow content by
1465 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 axis
1468 partition.
1469- `Size::Percent` rounds to the nearest cell.
837Keyboard 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 Lua
1472on 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 Rust
1474`LayoutTree` that retains no Lua handle (`Send + 'static`, so it can be built
1475off the render thread) and drops the Lua value. Every frame, a pure resolver
1476maps `(LayoutTree, terminal size) → Rect per widget slot` — deterministic for
1477equal inputs, zero Lua calls in the loop. This is what keeps §12's plugin-
1478thread round-trips (~81µs, serialized) off the §13 2ms frame budget; measured
1479per-frame resolution is ~0.4µs (release p99 &lt; 0.8µs) across 80×24 to 400×100.
839### Terminal capabilities
1481### 8.8 Theme
841`TerminalCapabilities` MUST record:
1483Themes are Lua tables validated by Rust schemas (prototype-proven, p08).
843```text
844truecolor
845undercurl
846Kitty keyboard protocol
847bracketed paste
848focus events
849mouse support
850Kitty graphics
851sixel
852```
1485Theme values cover status bar, messages, assistant content, tool call/result,
1486errors, input, borders, selections, diffs, syntax groups, and accents.
854Capabilities 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.
1488Schema contract:
856Image 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 above
1491 is a named table of color/style values.
1492- Colors are `#rrggbb` strings. Named/ANSI-indexed colors are not part of the
1493 v1 schema.
1494- A missing required key or malformed value is a validation error carrying the
1495 exact key path (e.g. `theme.status_bar.fg: expected "#rrggbb"`). Unknown keys
1496 warn.
1497- A user theme that fails validation at runtime does not abort Smith: it falls
1498 back to the built-in default theme with a visible warning naming the path
1499 error.
858Kitty 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
1503Message history uses virtual scrolling. `sticky_bottom` defaults true and turns
1504false when user scrolls up. New content does not move viewport until user returns
1505to bottom or submits input.
862Components 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:
1509Tools may register `renderCall` and `renderResult` Lua renderers. TUI receives
1510structured render instructions from harness, not arbitrary terminal writes.
866```text
867new -> enter terminal -> event/render loop -> shutdown -> restore terminal
868```
1512### 8.11 Input Queue
870The 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`.
1514Queued steering and follow-up messages (§6.1) appear in one visually combined
1515queue between message history and input:
872Application states MUST be exactly:
1517- follow-ups render above steers; within each kind, oldest to newest — steers
1518 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 and
1521 follow-up; the item lands at the NEWEST position of its new kind (its
1522 ordering within the other kind is meaningless — consequence, p22: a
1523 promote→demote round trip of a non-newest item does not restore the
1524 original order). The item keeps its original enqueue time,
1525- Up-arrow cycles newest-to-oldest through the queued messages; selecting
1526 one edits it. While edited, the message is OUT of the queue. Re-sending
1527 returns it to its remembered `(kind, index-within-kind)` position, clamped
1528 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, newest
1533 first, across both kinds — undo semantics: the most recently submitted
1534 message un-queues first, which provably diverges from visual-bottom-first
1535 (p22) — *instead of* their default action; only with an empty queue do
1536 they abort the run (§12). While a message is being edited it is not in
1537 the queue: cancel pops the remaining items first, and with the rest
1538 empty, cancel discards the edit (restoring the item) before it can abort.
874```text
875Idle | Thinking | ToolRunning | ToolResult | Error | Exiting
876```
1540### 8.12 Deferred Scope (v1)
878Every state MUST be interruptible.
1542Explicitly out of v1 TUI scope:
880### Widgets
1544- vim-style normal-mode editing,
1545- inline image rendering (Kitty graphics protocol),
1546- split-pane resizing (the `split` primitive exists; interactive resize does
1547 not),
1548- multiple simultaneous sessions.
882The TUI MUST provide:
1550## 9. Harness Crate: `smith-harness`
884- text and truncated text;
885- spacer;
886- Markdown;
887- message list;
888- input area;
889- status bar and hint bar;
890- spinner;
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;
895- fuzzy list;
896- tabs;
897- scrollable viewport;
898- overlay; and
899- border-layout panels.
1552`smith-harness` wires all subsystems and owns plugin management.
901### Overlay and layout contracts
1554Responsibilities:
903Overlays, 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`.
1556- load config,
1557- load model registry and auth,
1558- resolve active model,
1559- create provider and `StreamFn`,
1560- create agent,
1561- load plugins,
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.
905Rust 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; and
915- `split`: two children, horizontal or vertical orientation, and `split_ratio: f32`.
1569`Harness` contains:
917One 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.
1571- `Agent`,
1572- provider map,
1573- `ModelRegistry`,
1574- `ModelResolver`,
1575- auth resolver,
1576- `PluginManager`,
1577- optional `TuiApp`,
1578- active provider,
1579- active model.
919Composition 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.
1583Plugin names are mandatory and namespaced:
926### Layout ownership and resolution
928Layout 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:
932```text
933(LayoutTree, terminal size) -> Rect for each widget slot
934```
936Equal 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.
938### Themes
940A 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.
942Colors 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:
944```text
945theme.status_bar.fg: expected "#rrggbb"
946```
948Unknown 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
952History 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.
954Tools 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
958Steers 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
976Version 1 MUST NOT provide:
978- Vim-style normal-mode editing;
979- inline Kitty image rendering;
980- interactive split-pane resizing, although `split` exists; or
981- 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:
991```text
992Agent
993provider map
994ModelRegistry
995ModelResolver
996authentication resolver
997PluginManager
998optional TuiApp
999active provider
1000active model
1001```
1003### Plugin identity and locations
1005Every plugin name is mandatory and MUST be:
15851007```text
15861008<org>/<name>
15871009```
1589Rules:
1011Both 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>/`.
1013### Manifest
1596Every plugin has a mandatory Lua manifest file named `smith-plugin.lua` in the
1597plugin root. Plugin authors create it. Manifest loading uses a restricted
1598manifest environment — an empty Lua environment with no globals, no Smith SDK,
1599and no host I/O — so the chunk can only build and return a pure data table.
1600A manifest that reaches for `os`/`require`/any global, or that contains
1601function values, is rejected (prototype-proven, p04).
1015Every 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.
1603Required manifest fields:
1017Required fields are:
16051019```lua
16061020return {
16111025```
1613Optional manifest fields:
1027Optional fields are:
1615- `smith_api`,
1616- description,
1617- license,
1618- authors,
1619- repository,
1620- dependencies,
1621- declared secrets,
1622- `heap_limit` (bytes, §9.14),
1623- `interfaces` — list of interface names this package exports descriptors for
1624 (§9.6),
1625- `implements` — list of interface names this package implements (§9.6).
1029```text
1030smith_api
1031description
1032license
1033authors
1034repository
1035dependencies
1036secrets
1037heap_limit
1038interfaces
1039implements
1040```
1627If `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.
1629Smith validates manifests before loading plugin code.
1044### Plugin API compatibility
1631### 9.3 Plugin API Compatibility
1046Plugin 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.
1633Smith plugin API uses integer generations, not semver ranges.
1048A 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
1643Smith must keep API generation `1` working. Silent best-effort loading across
1644unknown generations is forbidden.
1052A plugin entry MUST return a registration table or factory. Loading MUST occur in this order:
1646### 9.4 Plugin Loading
1648Lua plugins return registration tables/factories from their entry file. Plugin
1649bridge phases:
16511. Load manifest in manifest environment.
16522. Validate name, version, source, API range, dependencies, and declared secrets.
16533. Load entry Lua source in restricted runtime.
10541. Load the manifest in its isolated environment.
10552. Validate name, version, source, API generation, dependencies, and declared secrets.
10563. Load entry Lua source in the restricted runtime.
165410574. Collect registrations.
16555. Materialize Rust-side handles.
16566. Register into tool/event/command/provider/TUI registries.
10585. Materialize host-side handles.
10596. Register tools, events, commands, providers, interfaces, and TUI contributions.
1658No Rust trait-object plugin API exists. Canonical plugin loading is the Lua
1659registration pipeline above.
1061Lua registration is canonical. Smith MUST NOT expose a Rust trait-object plugin API.
1661### 9.5 Plugin Install and Uninstall
1063Plugins MUST load by precedence:
1663Supported install sources for v1:
10651. built-ins;
10662. global user plugins;
10673. workspace-local plugins;
10684. explicit CLI/configuration overrides.
1665- local directory path,
1666- git URL.
1070Later registrations MUST override earlier registrations unless a registration explicitly defines duplication as an error.
1668No central registry exists in v1.
1072### Installation and uninstallation
1670`smith install <path-or-git-url>`:
1074Version 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 in
1674 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).
1076```text
1077smith install <path-or-git-url> [--force]
1078```
1679Install semantics:
1080Installation MUST:
1681- A duplicate is defined as: the destination directory
1682 `data_dir/smith/plugins/<org>/<name>/` already exists, regardless of version.
1683- `--force` is full replacement: remove the old plugin directory, then place the
1684 new one. Plugin data under `data_dir/smith/data/<org>/<name>/` survives a
1685 forced reinstall.
1686- Git installs strip the `.git` directory: an installed plugin is a pure file
1687 snapshot, not a working clone. Updates go through reinstall.
10821. resolve the source into temporary staging;
10832. read and validate manifest, namespace, and API compatibility in staging outside the global plugin root;
10843. leave the entire global plugin root untouched on failure;
10854. copy validated code to `data_dir/plugins/<org>/<name>/`;
10865. refuse an existing destination unless `--force` is present; and
10876. never execute entry code during installation.
1689Git URL installs go through Smith's internal git boundary, implemented with
1690`gix` — no runtime dependency on a `git` binary (prototype-decided, p25: gix
1691clones a repo at a ref byte-for-byte identical to shell-out). Local clone adds
1692five first-party gix crates over the §2.3 VCS-query baseline; the https
1693transport's TLS/async stack is mostly already paid for by the §2.3 `reqwest`
1694and `tokio` requirements, and gix's http transport is configured to share
1695reqwest's TLS backend rather than ship a second one. Shell-out was rejected:
1696zero build cost, but it forces a compatible `git` on every user's PATH for a
1697core feature.
1089Any 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>`:
1091```text
1092smith uninstall <org>/<name> [--purge-data]
1093```
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.
1095Uninstall 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 Modules
1097### Plugin interfaces
1708Interfaces are plain Lua descriptor tables validated at runtime. This design is
1709prototype-proven (p02, p03); the typed-Lua (Teal) and annotation-schema
1710candidates are rejected.
1099An interface package MUST export a pure-data descriptor with:
1712**Why Teal is rejected.** Teal's compile-time guarantees evaporate at the
1713runtime boundary: Smith embeds LuaJIT, so Teal ships as compiled Lua and the
1714host must re-validate conformance regardless — Teal would be additive toolchain
1715cost, not a replacement for runtime descriptors. Making official interfaces
1716Teal-authored would also split the ecosystem into typed and plain-Lua authors,
1717the exact fragmentation §9.6 exists to prevent. The authoring-time typing Teal
1718would provide is delivered instead by LuaLS annotations (below and §9.10)
1719without 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; and
1104- `events`: bus topic names.
1721**Generated typing.** Interface descriptors mechanically generate LuaLS stub
1722files (`---@class`/`---@field`/`---@param` annotations derived from the
1723descriptor's `functions` table) as part of `cargo run -p xtask -- doc-gen`.
1724Plugin authors targeting an interface get editor-time type checking against
1725the same descriptor the runtime validates — one source of truth, two
1726enforcement points.
1106The 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 table
1729with `name` (`<org>/<name>`), `generation` (integer — the interface's own
1730version, distinct from the plugin API generation of §9.3 and the reload domain
1731generation of §9.16), `functions` (map of function name → `{ params, returns }`
1732with typed, optionally-optional named parameters), and `events` (list of bus
1733topics, §9.18).
1108An adapter entry MUST export:
1735**Ecosystem shapes.** Interface-only packages, implementation-only packages,
1736implementations referencing external interfaces, and combined packages are all
1737supported through two manifest fields (§9.2): `interfaces` (list of interface
1738names this package exports descriptors for) and `implements` (list of interface
1739names this package implements).
1110```lua
1111adapts = "<org>/<name>"
1112```
1741**Adapters.** An adapter is an implementation package whose entry exports
1742`adapts = "<org>/<name>"` (the wrapped plugin) plus a `make(wrapped)` factory
1743returning a conforming implementation. The plugin manager injects the wrapped
1744plugin's exports into `make`.
1114and 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:
1116Configuration MUST select an implementation with:
17481118```lua
17491119interfaces = { ["community/subagent"] = "org/name" }
17501120```
1752Binding precedence: explicit config binding, else the last-loaded plugin
1753declaring `implements` for that interface (§9.7 order). Conformance is checked
1754at bind time. A conformance failure names the plugin, interface and generation,
1755every missing/mis-shaped export with its exact path, the exports the plugin
1756actually provides, and any installed adapter for it.
1122Binding precedence is:
1758**Views.** Consumers receive an interface view: only declared functions are
1759visible (implementation-private fields are hidden), and arguments are validated
1760against the descriptor at call time with errors naming function and parameter.
1761A resolved binding is a singleton: all consumers of an interface share the one
1762bound implementation instance.
11241. explicit configuration;
11252. otherwise, the last-loaded plugin declaring `implements` for that interface.
1764### 9.7 Plugin Precedence
1127Conformance 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.
1766Load order:
1129Consumers 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.
17681. built-in plugins,
17692. global user plugins,
17703. project plugins,
17714. explicit CLI/config overrides.
1131### Plugin event bridge
1773Later registrations override earlier ones unless registration marks duplicate as
1774an error.
1133Every Lua event table MUST contain `type`. The catalog and blocking behavior are:
1776### 9.8 Event Bridge
1135| Event | May block | Required behavior |
1136|---|---:|---|
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. |
1778Lua receives event tables with a `type` field. The canonical event catalog and
1779per-event blocking capability:
1163Handler 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) |
1165```lua
1166-- tool_call
1167{ block = true, reason = "..." }
1168{ args = replacement }
1169{ cancel = true }
1170nil -- or {}, allow
1809Handler return-table contracts (Lua-facing, one per §6.4 hook capability):
1172-- tool_result
1173{ content = replacement }
1174{ retry = true }
1175{ cancel = true }
1176nil -- keep original
1811- `tool_call` → `{ block = true, reason = "..." }` or
1812 `{ args = <replacement> }` or `{ cancel = true }` or nil/`{}` (allow),
1813- `tool_result` → `{ content = <replacement> }` or `{ retry = true }` or
1814 `{ cancel = true }` or nil (keep),
1815- `turn_end` → `{ stop = true }` to end the agent loop after this turn
1816 (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.
1178-- turn_end
1179{ stop = true } -- ShouldStopAfterTurn
1180nil -- continue
1822The bridge maps these into `AgentLoopConfig` hooks (§6.4).
1182-- input
1183{ action = "handled" | "continue", text = transformed_or_nil }
1824### 9.9 Extension Contexts
1185-- context
1186{ messages = modified }
1187nil
1826SDK contexts:
1189-- session_before_*
1190{ block = true, reason = "..." }
1191nil
1192```
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.
1194All other return values MUST be ignored. The bridge MUST translate accepted returns into `AgentLoopConfig` hooks.
1832The `ctx` table passed to event handlers, tool `execute`, and command handlers
1833has this shape:
1196### Extension contexts
1198The SDK MUST expose:
1200- `ExtensionContext` for agent lifecycle, model, context, tools, config, and logging;
1201- `ExtensionCommandContext` for slash-command arguments, selection, output, and session; and
1202- `ExtensionUIContext` for selection, confirmation, prompt, status, layout, and widgets.
1204Event handlers, tool `execute`, and command handlers MUST receive this context shape:
18351206```lua
18361207ctx = {
18371208 ui = {
18381209 notify = function(message, level) end, -- "info"|"success"|"error"|"warning"
1839 confirm = function(title, message) end, -- -> bool
1840 select = function(title, items) end, -- -> chosen item
1841 input = function(title, placeholder) end, -- -> string
1210 confirm = function(title, message) end, -- -> bool
1211 select = function(title, items) end, -- -> chosen item
1212 input = function(title, placeholder) end, -- -> string
18421213 set_status = function(key, text) end,
18431214 set_widget = function(key, lines) end,
18441215 },
1845 session = { -- read-only
1216 session = { -- read-only
18461217 id = "...", name = "...",
1847 entries = function() end, -- -> table
1848 entry_count = function() end, -- -> number
1849 branch = function() end, -- -> table
1218 entries = function() end, -- -> table
1219 entry_count = function() end, -- -> number
1220 branch = function() end, -- -> table
18501221 },
18511222 model = { id = "...", provider = "..." },
1852 cwd = "/path/to/project",
1223 cwd = "/path/to/workspace",
18531224 signal = AbortSignal,
18541225 shutdown = function() end,
18561227```
1858### 9.10 Lua SDK
1229### Lua SDK surface
1860SDK namespaces include:
1231`require("smith")` MUST expose:
1862- `smith.fs.*`,
1863- `smith.search.*`,
1864- `smith.env.*`,
1865- `smith.time.*`,
1866- `smith.log.*`,
1867- `smith.tool.*`,
1868- `smith.command.*`,
1869- `smith.provider.*`,
1870- `smith.alias.*`,
1871- `smith.group.*`,
1872- `smith.bucket.*`,
1873- `smith.tui.*`,
1874- `smith.vcs.*`,
1875- `smith.bus.*`,
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.4
1881 auth store),
1882- `smith.active_tools.*` (`get()`/`all()`/`set(names)`),
1883- `smith.send_message(text, { deliver_as = "steer" | "followUp" })` and
1884 `smith.send_user_message(text)`,
1885- `smith.abort()`,
1886- `smith.shutdown()`,
1233- `smith.fs.*`;
1234- `smith.search.*`;
1235- `smith.env.*`;
1236- `smith.time.*`;
1237- `smith.log.*`;
1238- `smith.tool.*`;
1239- `smith.command.*`;
1240- `smith.provider.*`;
1241- `smith.alias.*`;
1242- `smith.group.*`;
1243- `smith.bucket.*`;
1244- `smith.tui.*`;
1245- `smith.vcs.*`;
1246- `smith.bus.*`;
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)`;
1254- `smith.abort()`;
1255- `smith.shutdown()`; and
18871256- `smith.getContextUsage()`.
1889Core registration shapes:
1258Registration signatures MUST support:
18911260```lua
18921261smith.tool.register({
18931262 name = "my_tool",
18941263 description = "shown to the LLM",
1895 parameters = { --[[ JSON-schema table, validated per §5.3 ]] },
1264 parameters = { -- JSON Schema table
1265 },
18961266 execute = function(input, ctx)
18971267 return { content = { { type = "text", text = "..." } } }
18981268 end,
19111281```
1913`smith.provider.register(name, table)` merges into an existing provider or adds
1914a new one. Merge rules: `base_url`/`api_key`/`api` override; `headers` merge
1915per-key; `oauth` replaces whole; `models` merge by ID field-by-field (same
1916rules recursively); omitted fields keep existing values; `replace_models =
1917true` drops all existing models first. `smith.provider.unregister(name)` and
1918`smith.provider.unregister_model(provider, model_id)` remove entries. All
1919tables are validated against the §7.3 schema.
1283Every tool parameter table MUST validate as JSON Schema.
1921All public Lua SDK functions carry LuaLS/EmmyLua `---@` annotations. LuaLS is the
1922canonical annotation dialect; no other dialect is supported. Every public binding
1923declares, at minimum:
1285### Provider registration
1925- `---@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; and
1294- `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 annotations
1300Every 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; and
19271304- a `---@usage` block with a runnable example.
1929Runtime argument schemas (used for validation) and generated docs both derive
1930from these annotations, so annotations and runtime behavior stay in sync. The
1931`xtask verify-docs` gate fails if any public binding lacks required annotations.
1306Runtime argument schemas and generated documentation MUST derive from these annotations so runtime validation and documentation remain synchronized.
1933### 9.11 Built-in Plugins
1308### Built-in plugins and commands
1935Built-ins are Lua plugins, not Rust special cases:
1310Built-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,
1941- VCS tools,
1942- default layout,
1943- default keybindings,
1944- default theme,
1945- default prompts.
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;
1314- VCS tools;
1315- default layout, keybindings, theme, and prompts.
1947### 9.12 Built-in Tool Specs
1317`/model` MUST be a fuzzy picker over resolver names.
1319### Built-in tool contracts
19491321#### `read`
1951Inputs:
1323```text
1324path: string
1325offset?: number
1326limit?: number
1327```
1953- `path: string`,
1954- `offset?: number`,
1955- `limit?: number`.
1957Behavior:
1959- reads text files,
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.
19641331#### `write`
1966Inputs:
1333```text
1334path: string
1335content: string
1336```
1968- `path: string`,
1969- `content: string`.
1971Behavior:
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.
19771340#### `edit`
1979Inputs:
1342```text
1343path: string
1344old_text: exact string
1345new_text: string
1346allow_multiple?: bool
1347```
1981- `path: string`,
1982- exact `old_text`,
1983- `new_text`,
1984- `allow_multiple?: bool`.
1349Execution order and error codes are exact:
1986Behavior (ordering is the contract):
19881. read the file (`ENOENT`),
19892. validate: non-empty `old_text`, non-binary content (`EEMPTY`, `EBINARY`),
19903. count exact matches: zero fails; multiple fails unless `allow_multiple`
1991 (`ENOMATCH`, `EMULTI`),
19924. re-read and hash immediately before write; fail if the file changed
1993 (`ESTALE`),
19945. write atomically via temp file + rename (`ELOCK`),
19956. return change count and before/after hashes.
13511. Read the file; missing file returns `ENOENT`.
13522. Reject empty `old_text` with `EEMPTY` and binary content with `EBINARY`.
13533. Count exact matches; zero returns `ENOMATCH`; multiple returns `EMULTI` unless `allow_multiple` is true.
13544. Immediately before writing, re-read and hash; any change returns `ESTALE`.
13555. Atomically write using temporary-file-plus-rename; locking/write conflict returns `ELOCK`.
13566. Return replacement count and before/after hashes, then record the VCS operation.
19971358#### `bash`
1999Inputs:
1360```text
1361command: string
1362timeout?: number
1363cwd?: string
1364```
2001- `command: string`,
2002- `timeout?: number`,
2003- `cwd?: string`.
1366`bash` MUST execute off the UI thread, capture stdout, stderr, and exit status, enforce timeout, include output-truncation metadata, and observe abort.
2005Behavior:
1368#### `find`, `grep`, and `ls`
2007- executes subprocess on tool thread,
2008- captures stdout/stderr/status,
2009- enforces timeout,
2010- records output truncation metadata,
2011- supports abort.
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.
2013#### `find`
1374### VCS SDK
2015Uses `ignore` crate. Respects gitignore-style files. Returns sorted paths with
2016limits.
2018#### `grep`
2020Uses `grep`, `grep-regex`, and `grep-searcher`. Supports context lines, glob,
2021case-insensitive search, literal/regex modes, match limits.
2023#### `ls`
2025Lists directory entries sorted alphabetically, with directory suffix, bounded
2026output, and explicit errors.
2028### 9.13 VCS SDK
2030Smith uses jj internally for operation-level undo/redo/time travel, hidden
2031behind `smith.vcs.*`, integrated with the `jj-lib` crate — no runtime
2032dependency on a `jj` binary (prototype-decided, p26). Shell-out was rejected on
2033the hot path: jj runs on every mutating tool, and a real `jj` invocation costs
2034~12.5 ms against ~0.003 ms for the same read in-process, so per-turn spawn
2035overhead would accumulate for nothing. Embedding costs +186 crates over an
2036empty baseline, but much of that tree — gix, regex, futures, serde — is already
2037required by §2.3, and jj-lib builds on stable Rust (§2.3 records the pins that
2038keep it there). The pre-1.0, monthly-moving jj-lib API is the price; the
2039`smith.vcs.*` façade is what contains its churn, so an upgrade never reaches
2040plugins.
2042State:
2044- 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.
2048Plugins interact only through `smith.vcs.*`.
2050`smith.vcs.*` exposes:
2052Read-only queries:
1376The read-only API is exact:
20541378```lua
20551379smith.vcs.status() -- { modified={}, added={}, deleted={}, renamed={} }
20621386smith.vcs.evolog(rev) -- logical change evolution
20631387```
2065Mutations (explicit, validated inputs):
1389The mutation API MUST accept explicit validated inputs:
20671391```lua
20681392smith.vcs.commit(message)
20771401smith.vcs.workspace_add(name, opts)
20781402```
2080Lua receives stable smith-shaped tables; jj/gix implementation details never
2081leak through this surface.
1404Implementation-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 limits
2085### 9.14 Sandbox
1408Local 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.
2087Plugins are trusted but constrained to Smith SDK APIs:
1410A 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.
1412The 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 optional
2095`heap_limit` manifest field (§9.2) or config override; when both are set, the
2096config override wins (§5.6 cascade: user config over plugin contributions).
2097Prototype-proven (p10, p11) semantics:
1414The 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` per
2100 plugin (matching the §9.16 domain model). Per-plugin limits in a shared Lua
2101 state are not attributable and are not offered.
2102- Enforcement is `Lua::set_memory_limit()`; under the locked vendored-LuaJIT
2103 feature set this enforces exactly, and breach surfaces as a recoverable
2104 memory error handled by the §9.17 error model. Targets where mlua reports
2105 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 Lua
2108 values. Host-side Rust allocations held for a plugin are invisible to it
2109 and are bounded by domain teardown (§9.16) instead.
2110- After a plugin OOM, the preferred recovery is whole-domain replacement
2111 (§9.16) rather than in-place retry.
1416### Dependency resolution
2113### 9.15 Dependency Resolution
2115Plugins may declare dependencies on other plugins in their manifest
2116(`dependencies`, §9.2). v1 resolves dependencies from already-available plugins
2117only; there is no central registry and no network resolution.
2119Each dependency entry names a plugin and a minimum API generation:
1418A dependency MUST name a plugin and minimum Smith API generation:
21211420```lua
21221421dependencies = {
21251424```
2127Resolution runs once per plugin set (built-in, global, project) after manifests
2128load and before entry code runs:
1426Version 1 MUST resolve only already-available plugins and MUST NOT perform network dependency resolution or semantic-version range solving.
21301. Build the dependency graph from validated manifests.
21312. Fail loading a plugin whose declared dependency is absent from the resolved
2132 set. The plugin is disabled with a diagnostic naming the missing dependency.
21333. Fail loading a plugin whose dependency is present but supports a lower API
2134 generation than requested.
21354. Detect cycles. A dependency cycle disables every plugin in the cycle with a
2136 diagnostic listing the cycle path. Smith never partially loads a cycle.
21375. Load plugins in topological order so a dependency's registrations exist before
2138 its dependents run.
1428After manifests load and before entry execution, each built-in, global, and workspace plugin set MUST be resolved by:
2140v1 does not solve version ranges. `dependencies` express presence and API
2141generation only. Semver range solving is deferred until a registry exists.
2142Precedence (§9.7) still applies: a later plugin may override an earlier
2143registration even across a dependency edge.
14301. building a graph from validated manifests;
14312. disabling a plugin with an absent dependency and reporting that dependency;
14323. disabling a plugin whose dependency supports a lower API generation than requested;
14334. detecting cycles, disabling every plugin in each cycle, reporting the complete path, and never partially loading it; and
14345. loading topologically so dependency registrations exist before dependent entry code.
2145### 9.16 Plugin Hot-Reload
1436Dependencies express only presence and API generation. Normal registration precedence MUST still apply, including overrides across dependency edges.
2147Smith reloads a single plugin without restarting the process or losing the active
2148session. Reload is whole-domain replacement, not in-place mutation.
1438### Plugin domains and hot reload
2150**Plugin domain.** Each loaded plugin instance owns one reload domain. The domain
2151owns all reloadable plugin state:
1440A 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; and
1447- cancellation tokens for plugin tasks.
2159Nothing plugin-owned may outlive its domain. Registrations are keyed by domain
2160generation so teardown removes them deterministically. A callback, task, or
2161subscription that escapes its domain is a reload defect; the loader rejects
2162registrations that cannot be tied to the domain.
1449Nothing 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 reachable
2165exclusively through the generation-keyed registry. The host never clones or
2166stashes a raw callback handle outside it — invoking a raw `mlua` function after
2167its domain dropped is an unrecoverable panic, not a catchable error. Every
2168dispatch path (hook, tool, command, bus) checks the callback's domain generation
2169against the active set before touching any Lua value; stale generations are
2170rejected with a diagnostic and the callback does not run. An audit sweep over
2171the registries (anything registered under a non-active generation) is the
2172loader's escape-detection mechanism.
1451Reload 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; and
1455- 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.
1457Built-in `smith/*` plugins MUST use the same mechanism.
2180Built-in `smith/*` plugins reload by the same mechanism.
1459For plugin `P` with active domain `D` and candidate `D'`, reload MUST:
2182**Sequence.** For a reload of plugin `P`:
14611. construct `D'` and validate/load its manifest, entry, and registrations in isolation;
14622. on failure, drop `D'`, retain `D`, and report the error;
14633. on success, atomically replace registrations and subscriptions with `D'`, mark `D` retired, and activate `D'`; and
14644. drop `D` after its allowed in-flight work and deferred bus dispatch complete, tearing down its Lua state, registrations, subscriptions, caches, and scratch memory.
21841. Construct a new domain `D'` and load `P`'s manifest and entry code into it.
21852. 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.
21873. On success, atomically swap `D'` in for `D`: new registrations replace old,
2188 subscriptions transfer to `D'`, then drop `D`.
21894. Dropping `D` tears down its Lua state, registrations, subscriptions, caches,
2190 and scratch memory. Repeated reloads must plateau in live memory after
2191 warmup; no stale callback from `D` may run after the swap. The plateau is
2192 the enforceable observable — an instantaneous RSS decrease per teardown is
2193 not required, since small freed heaps are legitimately retained by the
2194 allocator for reuse (p11 evidence, `prototypes/PLAN.md`).
1466Reload 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`
2197remains and no partial state from `D'` survives. A failed reload never leaves the
2198plugin unregistered.
1468Domain 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` waits
2201for `D`'s currently executing hook to finish; a hook in flight during a bus
2202dispatch follows the §9.18 condemned/deferred rule (p15, p23).
1470Reload 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, agent
2205state, and other plugins' state are untouched. In-flight tool executions from the
2206old domain run to completion under `D`; their results are still delivered. New
2207invocations after the swap use `D'`.
1472### Plugin errors
2209**Interface bindings.** If the reloaded plugin backs an interface binding
2210(§9.6), the swap re-resolves the binding to `D'` and re-runs bind-time
2211conformance against it. Consumers' interface views rebind transparently — the
2212next call through a view dispatches into `D'`. A conformance failure is a
2213reload failure: rollback keeps `D` and its binding active.
1474Every 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). Dependents
2216keep their handles to `P`'s registrations by stable name; the swap rebinds those
2217names to `D'`. A reload that removes a registration a dependent relies on surfaces
2218as 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 Model
1483Host library code MUST NOT panic on plugin input.
2222Plugin faults are isolated. A plugin error never corrupts the host, the terminal,
2223or another plugin. Errors are classified by phase:
1485### Inter-plugin bus
2225- **Manifest/validation error** (bad name, bad version, unsupported `smith_api`,
2226 missing/cyclic dependency): the plugin does not load. It is disabled and listed
2227 by `smith plugins` with the reason. Other plugins load normally.
2228- **Entry-load error** (Lua error while running entry code or collecting
2229 registrations): the plugin's partial registrations are discarded, the plugin is
2230 disabled with the error, and loading continues for the rest of the set. On
2231 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 is
2233 caught, logged through `smith.log`, and the handler's result is treated as
2234 absent. A non-blocking event proceeds; a blocking event (e.g. `tool_call`) is
2235 treated as no decision — it does not block. One handler's failure never
2236 prevents other handlers for the same event from running.
2237- **Tool-execute error** (Lua error or returned error inside a plugin tool): it
2238 surfaces to the agent as a normal tool error result, not a host crash. The
2239 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.
2243Host library code never panics on plugin input (PROJECT-INVARIANTS §3.5). Plugin
2244errors carry the plugin name and phase so `smith plugins` and logs attribute them
2245unambiguously.
2247### 9.18 Inter-Plugin Messaging Bus
2249`smith.bus.*` is a namespaced publish/subscribe channel for plugin-defined
2250messages. It is separate from core lifecycle events (§9.8): the bus carries custom
2251plugin topics, not engine events, and plugins cannot emit core event types on it.
2253API:
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.
22551489```lua
2256-- Subscribe to a topic. Returns a handle usable to unsubscribe.
22571490local handle = smith.bus.on("acme/index-ready", function(payload, ctx)
22581491 ctx.ui.notify("index has " .. payload.count .. " files", "info")
22591492end)
2261-- Publish to a topic. Delivers to all current subscribers.
22621494smith.bus.emit("acme/index-ready", { count = 128 })
2264-- Stop receiving.
22651495smith.bus.off(handle)
22661496```
22681498Rules:
2270- **Topic names are namespaced** `<org>/<topic>`, using the same character set as
2271 plugin names (§9.2). A plugin may emit any topic; convention is to emit under
2272 its own `org`. `smith/*` topics are reserved for built-in plugins.
2273- **Payloads are plain Lua data tables** — the same value shape passed across the
2274 SDK boundary. No functions, userdata, or host handles cross the bus.
2275- **Delivery is synchronous, in registration order,** on the plugin thread
2276 (§12) within the current tick. Emitting during delivery enqueues to ONE
2277 global FIFO — regardless of topic — delivered strictly after the current
2278 dispatch completes in emit order; the bus never re-enters
2279 (prototype-proven, p23: max dispatch depth 1).
2280- **Teardown during dispatch** (§9.16 interaction, p23): a domain torn down
2281 mid-dispatch is condemned immediately — its remaining deliveries in the
2282 current dispatch are skipped with a diagnostic — and the actual drop is
2283 deferred until the dispatch queue drains. A handler may therefore safely
2284 request its own domain's teardown and complete normally.
2285- **Subscriptions are domain-owned** (§9.16). A subscription is dropped when its
2286 plugin's domain is torn down on reload or unload, so no stale subscriber
2287 survives.
2288- **A subscriber error is isolated** (§9.17): caught, logged, remaining
2289 subscribers still receive the message.
2290- **No delivery guarantee across load order:** a message emitted before a
2291 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.
2293The bus is the only sanctioned direct plugin-to-plugin channel. Plugins otherwise
2294compose through shared tool/command/provider registries and the core event
2295bridge.
1511Plugins MAY also compose through stable registries and the core event bridge.
2297### 9.19 Host Configuration Reload
1513### Runtime configuration reload
2299Smith reloads its own configuration at runtime without restarting the process or
2300losing the active session. Host reload follows the same contract shape as plugin
2301reload (§9.16): validate fully, swap atomically, roll back on failure.
1515Reload 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). CLI
2304flags (layer 5) are per-invocation: resolved at process start, they continue to
2305override the reloaded layers unchanged.
1517Reload triggers are:
2307**Triggers.** Reload is requested by:
1519- `/reload-config`;
1520- `smith.config.reload()`;
1521- `config_dir/config.lua` change when config watch reload is enabled;
1522- RPC `config/reload`; and
1523- 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 the
2310 `smith.config.reload()` primitive (§9.10),
2311- a change to `config_dir/smith/config.lua` when watch-reload is enabled in
2312 config (same setting family as plugin watch-reload, §9.16),
2313- a plugin reload (§9.16), which may change layer-3 contributions; after the
2314 domain swap the cascade is re-evaluated automatically,
2315- in RPC mode (§10.2), the `config/reload` JSON-RPC method. The response reports
2316 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.
2318Eval mode reads config at startup and has no runtime reload trigger.
1527Reload order is exact:
2320**Sequence.** For a host reload:
15291. Evaluate the cascade into a candidate.
15302. Validate every value against host schemas.
15313. Validate the complete alias/group/bucket graph, not only the active chain.
15324. If any step fails, report all failures together with exact key paths, discard the candidate, retain active configuration, and permit a later retry.
15335. Atomically activate a valid candidate.
15346. Apply theme, keybindings, active tool set, then resolved model/provider, in that order.
15357. Re-render the TUI with the new theme on the next frame.
15368. Emit `config_changed` with changed paths and no secrets.
23221. Re-evaluate the cascade into a candidate config. Validate every value against
2323 the Rust schemas, and re-run model resolution (§5.7) as whole-graph
2324 validation — every alias/group/bucket, not just the active model's chain
2325 (p16: a concrete CLI model otherwise masks a latent alias cycle into the
2326 accepted config).
23272. If evaluation, validation, or resolution fails, discard the candidate and
2328 keep the active config. ALL failures are reported together, each with its
2329 exact key path; nothing partially applies, and a later valid reload is
2330 unaffected.
23313. On success, atomically swap the candidate in as the active config.
23324. Apply effects in order: theme, keybindings, active tool set, resolved
2333 model/provider. TUI re-renders with the new theme on the next frame.
23345. Emit the `config_changed` plugin event (§9.8) carrying the changed key
2335 paths. Plugins read the new values through their contexts (§9.9); the
2336 event does not carry secrets. Diff rules (prototype-proven, p16): the
2337 diff is computed over the post-CLI *effective* config (a CLI-masked
2338 change is not reported); list-valued keys diff as one path; added and
2339 removed keys count as changed paths; an idempotent reload emits the
2340 event with an empty path list.
1538Changed-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:
1540An 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 it
2345 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 reload
2348 never loads, unloads, or reloads plugin code.
1542The following are fixed for process lifetime and MUST NOT hot-reload:
2350**Restart-only.** The following are fixed for the process lifetime and never
2351hot-reload:
1544- CLI flags;
1545- config, data, and cache directory locations;
1546- active session identity and storage paths;
1547- run mode: interactive, eval, or RPC; and
1548- 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 through
2358 `smith.provider.*` plugin overrides, not registry reload.
1550Runtime 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.
2360Credential resolution (§7.4) is not cached across reloads: the next provider
2361stream after a reload resolves auth against the new config values.
1552## CLI and RPC
2363## 10. CLI Crate: `smith-cli`
1554### CLI
2365Binary name: `smith`.
1556The executable MUST be `smith`. Global options are exact:
2367### 10.1 Global Flags
1558```text
1559--model <model>
1560--provider <provider>
1561--session <id-or-name>
1562--config <path>
1563--no-config
1564```
2369- `--model <model>`
2370- `--provider <provider>`
2371- `--session <id-or-name>`
2372- `--config <path>`
2373- `--no-config`
1566Commands and behavior are:
2375### 10.2 Commands
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.
2377Default:
1585Interactive slash commands MUST be registered by Lua plugins and MUST NOT be binary subcommands.
2379- `smith` starts interactive TUI with new auto-named session.
1587The 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.
2381Subcommands:
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).
2403Interactive slash commands are registered by Lua plugins, not clap subcommands.
1593These data/configuration surfaces MUST project as client request to server response methods:
2405### 10.3 Main
1595```text
1596fs
1597search
1598env
1599time
1600log
1601provider
1602alias
1603group
1604bucket
1605vcs
1606config
1607secret
1608active_tools
1609credentials
1610send_message
1611abort
1612shutdown
1613getContextUsage
1614```
2407`main` uses tokio, parses clap, resolves config, creates `Harness`, dispatches to
2408interactive/eval/rpc/replay/session/plugin/help command handlers.
1616Callback-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; and
1620- `bus.on` callbacks.
2412### 10.4 RPC Method Projection
1622Registration 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.
2414The `smith rpc` catalog is not a mirror of the Lua SDK (§9.10) — projecting
2415the SDK onto JSON-RPC is a structural transform, prototype-proven (p24), and
2416the method list is derived from it rather than enumerated here. Two
2417independent axes classify each surface: *origin* (mirrored from §9.10 vs an
2418RPC-only addition) and *shape* (data request/response, callback, or
2419notification).
1624Headless 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` (its
2426 `execute`), `command` handlers/autocomplete, and `bus.on` cannot travel as
2427 data; registering one means the engine issues a server→client REQUEST to
2428 run the client's handler and awaits the reply. RPC that registers behavior
2429 is therefore bidirectional, not a one-way call.
2430- **Events (§9.8) are server→client notifications** — except blocking events
2431 (`tool_call`, `session_before_*`), which are server→client REQUESTS so the
2432 client can answer block/allow/replace. A pure observer client that
2433 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`. Lua
2437 never needs these because a plugin already runs inside a live session; an RPC
2438 client must drive one from outside. `session/dump` returns persisted state
2439 (transcript, tree, leaf, folds); `session/snapshot` returns the *ephemeral*
2440 process state a live tail cannot replay — the steering/follow-up queue
2441 (§6.1) and in-flight run status — which a mid-session attach needs and which
2442 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
2446Framing (line-delimited JSON vs `Content-Length`) is an implementation choice
2447settled when `smith rpc` is built.
1628External clients MUST receive these RPC-only methods:
2449**RPC is the multi-frontend boundary.** An RPC client is a frontend peer of the
2450built-in TUI (§8), so its event surface is an adapter over the `EngineEvent`
2451stream (§6.3) — the same source the TUI consumes — not the plugin bridge
2452(§9.8). It is an adapter, not a mirror, by three rules: non-blocking events
2453project to notifications; blocking events (`tool_call`, `session_before_*`)
2454project to server→client requests the client answers; and frontend-private
2455`EngineEvent` variants (panel toggle, resize, selection/focus/scroll) are
2456omitted. Prototype-proven sufficient for a full alternative UI (p28: a headless
2457client reconstructed transcript, tools, steering queue, tree/leaf, model, cost,
2458fold, and secret placeholders from the wire alone), subject to:
1630```text
1631session/open
1632session/attach
1633session/list
1634session/dump
1635session/snapshot
1636session/fork
1637session/subscribe
1638prompt/submit
1639command/run
1640```
2460- two notification payload guarantees the reconstruction depends on —
2461 `session_compact` carries the covered span `{summary_id, start, end}` (the
2462 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 tail
2465 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); a
2467 `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.
2469Secret plaintext never crosses the wire — only `smith:sec:N` placeholders and
2470their labels (§6.7), tap-verified in p28.
1644### RPC frontend event boundary
2472## 11. Security Model
1646RPC 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.
2474Trusted:
1648Nonblocking 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.
2476- user,
2477- OS/filesystem,
2478- local plugins,
2479- Smith code,
2480- session/config/cache files.
1650Frontend-private events for panel toggling, resizing, selection, focus, and scrolling MUST be omitted.
2482Untrusted:
1652The 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:
2484- remote LLM,
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.
2487Security mechanisms:
1659Secret plaintext MUST never cross RPC. Only `smith:sec:N` placeholders and labels/IDs MAY cross.
24891. Tool registry (§6.10) controls which tools the LLM can invoke.
24902. Secret proxy (§6.7) prevents real secrets from reaching LLM context.
24913. Restricted Lua runtime (§5.5) removes raw OS/file APIs.
24924. Users configure active tools; no confirmation-dialog security theater.
1661RPC transport framing is intentionally selectable: line-delimited JSON and `Content-Length` framing are both permitted.
2494Credential storage follows §7.4: plaintext, no keychain, no encryption.
1663## Security
2496## 12. Concurrency and Async
1665### Trust boundary
2498Threads/tasks:
1667Smith 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 this
2507 thread and dropped on it (prototype-proven, p15).
1669### Required controls
2509Plugin dispatch (prototype-proven, p15 — hook round-trip median 81µs):
2510hook, bus, and plugin-callback dispatch is a channel actor. The engine
2511sends a plain-data request and awaits a reply; requests execute serially
2512in arrival order across ALL plugins; only plain data crosses the boundary.
2513This is the thread §9.18's delivery rules run on.
16711. `ToolRegistry` MUST determine which tools the LLM may invoke.
16722. The secret proxy MUST prevent registered plaintext secrets from entering LLM context, traces, public events, or RPC.
16733. Restricted Lua MUST expose no raw operating-system or filesystem APIs.
16744. Users MUST configure active tools. Confirmation dialogs MUST NOT be treated as a security boundary.
16755. Credentials MUST remain plaintext in permitted local storage, with no keychain integration or encryption.
2515Async boundary:
1677The 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.
1679## Concurrency
2521Responsiveness:
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 usable
2528 interrupt; debug hooks do not fire inside compiled traces). Abort
2529 abandons the pending hook *dispatch* — the engine drops the reply and
2530 continues; the hook runs to completion and its late reply is discarded.
2531 Hard cancellation of runaway Lua is domain teardown (§9.16), never
2532 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.
2534Hook budget (soft, since preemption is impossible): a hook blocks only its
2535dispatching turn plus queued plugin dispatches (head-of-line — all plugins
2536share the one plugin thread); it never blocks the engine runtime, UI, or
2537tool pool. A hook exceeding the configured soft deadline is reported as a
2538plugin diagnostic (§9.17), not killed.
1689### Plugin actor
2540## 13. Performance Requirements
1691Hooks, 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
2551Compile time is budgeted on two distinct axes, because they answer different
2552questions:
1700A 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-crate
2555 edit, the rebuild recompiles that crate and its reverse-dependency closure
2556 only — never an unrelated leaf crate or its heavy dependency tree. This is a
2557 structural guarantee of the workspace split + dependency siloing
2558 (PROJECT-INVARIANTS §11), not just a time target; the edit→check loop that
2559 dominates agent and dev work depends on it.
2560- **Cold build and crate count are a CI-cost sub-budget.** The full transitive
2561 tree (mlua/LuaJIT, jj-lib, gix, reqwest+tokio, aws-lc/TLS, syntastica) is
2562 paid once and cached; the gate is on *regression* — a dependency change that
2563 materially grows cold build or crate count fails CI the same way a
2564 binary-size or bench regression does. Exact thresholds are set from the
2565 first real full-workspace build.
1702Every 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.
2567A single TLS backend is shared across `reqwest` and `gix` rather than shipping
2568two stacks (p25).
1704Hook 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
1706## Performance
2572Prototype-proven against the measured session corpus (p09; see
2573`docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):
1708The product MUST satisfy:
2575- **Session discovery is lazy and metadata-only.** Discovery reads session
2576 headers, never full bodies: O(session count), not O(corpus bytes).
2577- **Virtual scroll materializes at most viewport rows per frame.** Row
2578 formatting stops at the visible window (lazy wrap); a single multi-MiB
2579 message must not be fully formatted to render its visible slice.
2580- **Arenas are scratch-only.** `bumpalo` is permitted solely for phase-local
2581 render/request scratch in measured hot paths. Persisted and session data use
2582 stable IDs and owned strings — never arena references. No custom or unsafe
2583 arena code. Arena references never cross async, thread, or persistence
2584 boundaries.
2585- **Keep/drop gates for arena use** weigh allocator-call pressure, elapsed
2586 time, and peak/plateau stability — not allocation count alone. Render-frame
2587 scratch is a clear win; request-build scratch is marginal — arenas are not a
2588 latency win where serialization dominates (p09 measurements,
2589 `prototypes/PLAN.md`).
2590- **Provider request assembly** at compaction-scale contexts has a transient
2591 peak of a small multiple of the serialized request size and must release it
2592 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; and
1717- an agent-loop turn SHOULD complete in less than 30 seconds, excluding provider/network stalls beyond configured timeout.
2594## 14. Release Artifacts
1719A release MUST NOT exceed a mandatory threshold because of a performance regression.
2596Required targets:
1721### Memory behavior
2598| Platform | Triple | Status |
2599|----------|--------|--------|
1723Session 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.
1725Virtual 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.
1727Arenas 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.
1729Arena 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.
1731Provider 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
1735### Target matrix
1737| Platform | Target triple | Obligation |
1738|---|---|---|
26001739| Windows x86_64 | `x86_64-pc-windows-msvc` | required |
26011740| Windows ARM64 | `aarch64-pc-windows-msvc` | required |
26021741| macOS Intel | `x86_64-apple-darwin` | required |
26111750| FreeBSD x86_64 | `x86_64-unknown-freebsd` | best-effort |
26121751| OpenBSD x86_64 | `x86_64-unknown-openbsd` | best-effort |
2614**Three libcs, not two.** glibc and musl cover the Linux rows; **Android is
2615Bionic**, which is why it is its own row rather than a Linux variant. Bionic does
2616not carry the compiler-rt builtins Rust expects to find, so the Android target
2617links against them explicitly — the flag lives in `.cargo/config.toml` (§3.2) and
2618is normative for this target, not a local workaround. A toolchain that cannot
2619supply them cannot produce this artifact.
1753Linux 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 stops
2622the release; a best-effort target that fails is reported in the release notes and
2623skipped, and its absence is never a reason to hold the other artifacts. Android is
2624required because a terminal-first coding agent is used on a phone, not only built
2625for one — it is a shipping platform, not a development convenience.
1755Failure 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.
2627Artifacts:
1757### Names and guarantees
2629- `smith-{triple}-v{version}.{zip|tar.gz}`,
2630- `checksums-sha256.txt`.
1759Every built target MUST produce:
2632**One host builds the matrix.** Producing thirteen targets must not require
2633thirteen build environments. The release is cross-compiled from a single host
2634wherever a target allows it; CI installs toolchains and invokes `xtask release`,
2635holding no build logic of its own (PROJECT-INVARIANTS §1). Which cross-compilers
2636achieve this is an implementation choice, not a spec commitment — it changes as
2637the ecosystem does.
2639Three 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 a
2643 substitute for a target the matrix lists as MSVC, however much easier it is to
2644 produce.
2645- **glibc artifacts run on glibc 2.28 or newer** — Debian 10, RHEL 8, Ubuntu
2646 18.10. The floor is a property of the release, not of whatever the build machine
2647 happens to ship: linking against the builder's glibc silently narrows who can run
2648 smith, and by an amount nobody stated. Raising the floor drops users, so it is a
2649 spec change, not a build detail.
2650- **No target is silently dropped.** Each release accounts for every target as
2651 built, or skipped with a reason. A required target that fails to build stops the
2652 release (above); quietly shipping a short matrix is a defect, not a degraded
2653 release.
2655Where a target's cross-build is unproven, a prototype (§18) establishes it before
2656the matrix claims it — an unverified target is a promise, not a platform.
2658No install scripts, package manifests, distribution metadata, or code signing in v1.
2660## 15. xtask
2662Required commands:
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 |
2684xtask 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. Any
2691 future exploratory design doc is non-canonical and cannot contradict
2692 `SPEC.md`.
2693- SDK docs are generated from Lua `---@` annotations and `@usage` blocks.
2694- `smith help` resolves docs in order: (1) embedded in the binary via
2695 `include_str!`, (2) install directory `<prefix>/share/smith/docs/`,
2696 (3) `SMITH_DOCS_PATH` environment override (development). First hit wins.
2698Documentation 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.
2707## 17. Testing
2709### 17.1 Fast Tier
2711Every commit, scoped to the touched crates and their reverse-dependency
2712closure (`-p <crate>`), so the §13.1 incremental guarantee is realized rather
2713than erased by a full-workspace `--all-features` sweep:
2715```bash
2716cargo fmt --check
2717cargo clippy -p <touched...> --all-targets -- -D warnings
2718cargo run -p xtask -- arch
2719cargo +nightly-2026-01-22 pup -p <touched...>
2720cargo nextest run --profile fast -p <touched...>
2721cargo test --doc -p <touched...>
1761```text
1762smith-{triple}-v{version}.{zip|tar.gz}
27221763```
2724The full `--workspace --all-features` clippy/build/test sweep runs in the
2725medium tier (§17.2), not per-commit. Blocks push.
1765and an entry in:
2727Scope:
2729- unit tests,
2730- property tests,
2731- TUI snapshots,
2732- serialization snapshots,
2733- doc tests,
2734- architecture gates.
2736### 17.2 Medium Tier
2738Every PR: the fast tier (§17.1, with `--profile default` instead of `fast`),
2739plus:
2741```bash
2742cargo tarpaulin --out Lcov
2743cargo nextest run --profile integration
2744cargo doc --workspace --no-deps
1767```text
1768checksums-sha256.txt
27451769```
2747Blocks merge.
1771Windows 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.
2749### 17.3 Slow Tier
1773Version 1 MUST NOT ship install scripts, package manifests, distribution metadata, or code signing.
2751Nightly + release:
1775## Documentation
2753```bash
2754cargo nextest run --profile thorough
2755cargo mutants --test-tool=nextest
2756cargo bench -- --baseline main
2757```
1777`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.
2759Blocks release if mutation score <80% or benchmark regression exceeds threshold.
1779Documentation lookup MUST use the first available source in this order:
2761### 17.4 Coverage Goals
17811. content embedded in the binary;
17822. `<prefix>/share/smith/docs/`;
17833. `SMITH_DOCS_PATH`.
2763| Crate | Target |
2764|-------|--------|
2765| `smith` | 100% |
2766| `smith-core` | ≥95% |
2767| `smith-ai` | ≥90% |
2768| `smith-tui` | ≥85% |
2769| `smith-harness` | ≥90% |
2770| `smith-cli` | ≥80% |
1785The system prompt MUST direct capability discovery to `smith help --search`, `smith help --guide`, and `smith help --example` rather than embedding the complete SDK.
2772Overall workspace coverage target is 85%; merges are blocked below 80%.
1787Every 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.
2774### 17.5 nextest
1789Documentation 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`:
1791Diagnostics documented as path-qualified—configuration, themes, interface conformance, tool arguments, plugins, and reload—MUST preserve those exact paths in user-visible output.
2778```toml
2779[profile.default]
2780retries = 3
2781slow-timeout = "30s"
2782fail-fast = false
1793## Product Acceptance
2784[profile.fast]
2785test-group = "fast"
2786retries = 0
2787fail-fast = true
2788slow-timeout = "5s"
1795A 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]
2791filter = 'test(integration::) or test(cli::) or test(tui::)'
2792retries = 2
2793slow-timeout = "30s"
2795[profile.thorough]
2796retries = 1
2797slow-timeout = "120s"
2799[profile.ci]
2800fail-fast = false
2801retries = 2
2802slow-timeout = "60s"
2803# supports --partition for sharded CI runs
2804```
2806### 17.6 Property Tests
2808Required 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; flow
2817 siblings tile their axis without overlap; `expanded` is the exact remainder;
2818 `split` honors `split_ratio` (± one cell) and tiles exactly; resolution is
2819 deterministic for equal `(tree, size)`.
2821Commit `proptest-regressions/`.
2823### 17.7 Snapshot Tests
2825Use `insta` + ratatui `TestBackend` for:
2827- widgets,
2828- layout composition,
2829- themes,
2830- CLI help,
2831- error formatting,
2832- config parse output,
2833- provider normalization.
2835CI runs with `INSTA_UPDATE=no`.
2837Snapshot contract (prototype-proven, p08): widget and theme snapshots serialize
2838styled cells — symbol plus fg/bg/modifier per cell — not buffer text alone.
2839Text-only snapshots cannot catch theme regressions: a theme swap changes styles
2840while leaving text byte-identical. Text-only snapshots are permitted only for
2841layout-only assertions.
2843### 17.8 Integration Tests
2845Required 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.
2855Fixtures live under `tests/fixtures/` with plugins, sessions, configs, providers,
2856and traces.
2858### 17.9 Benchmarks
2860Criterion 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`,
2868- `plugin_load_10`.
2870Regression thresholds per benchmark: >5% warns, >10% fails the nightly gate
2871(§13).
2873### 17.10 Continuous Integration
2875Test 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 never
2882 run in the default CI lane.
2884Gate tiers by context:
2886| Context | Gate |
2887|---------|------|
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 |
2892Agent conduct while building Smith lives outside this spec in
2893PROJECT-INVARIANTS §5. This section defines Smith's test artifacts.
2895Android/Termux (`aarch64-linux-android`) is both the environment smith is
2896developed in and a **required release target** (§14): CI keeps a validation lane
2897that smoke-builds vendored LuaJIT and syntastica for it, and because the artifact
2898ships, breakage there blocks publishing like any other required target — not only
2899source-compatibility fixes.
2901## 18. Prototype Policy
2903Prototypes are disposable evidence for or against this spec. They live under
2904`prototypes/`, never in production crates. A prototype tests one claim or risk,
2905runs minimal commands, and reports whether the spec should change.
2907Prototype output must include:
2909- status,
2910- proved claims,
2911- disproved claims,
2912- spec issues with evidence,
2913- artifacts created,
2914- commands run,
2915- next spec/design actions.
2917Production code must not depend on prototype artifacts.
2919Three validation campaigns (p02–p11 on 2026-07-14; p12–p14 and p15–p23 on
29202026-07-15/16; x86_64-linux, rustc 1.94.1) ran twenty-two prototypes to
2921completion; result blocks live in `prototypes/PLAN.md`. Sections marked
2922"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; and
1811- 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
2
3> Non-normative execution plan. `docs/SPEC.md` is canonical; where this file and
4> 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 file
7> is the execution plan for file inventories and tooling only.
8
9## Goal
11Smith must be able to extend itself when prompted by humans.
12Documentation serves both humans and LLMs equally.
13One source of truth. No drift.
15## Architecture
17```
18Source of Truth: SDK Lua annotations (---@ + @usage + prose)
19 │
20 ├─→ Embed in binary (include_str!)
21 │ │
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)
26 │
27 ├─→ Generate man pages (CI, shipped in release)
28 │
29 ├─→ Generate compressed docs bundle (CI, shipped in install dir)
30 │ └─→ fallback: readable files on disk
31 │
32 └─→ Doc tests (CI, extracts @usage + guide code blocks → run in Lua)
33```
35## One Source of Truth: SDK Annotations
37Every SDK function has `---@` annotations in the Lua source files.
39```
40smith-harness/src/lua/sdk/
41├── smith_tool.lua
42├── smith_provider.lua
43├── smith_command.lua
44├── smith_shortcut.lua
45├── smith_tui.lua
46├── smith_fs.lua
47├── smith_env.lua
48├── smith_credentials.lua
49└── smith_events.lua
50```
52Guides live alongside the SDK code too:
54```
55smith-harness/src/lua/sdk/
56└── guides/
57 ├── getting-started.lua -- guide as Lua comments + tested code blocks
58 ├── tools.lua
59 ├── events.lua
60 ├── providers.lua
61 ├── tui.lua
62 └── sandbox.lua
63```
65Guides are Lua files where:
66- Comments (`--`) contain prose
67- Fenced blocks (`---[[` ... `--]]`) contain tested examples
68- The doc test runner extracts and executes the fenced blocks
70This 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.
76### Subcommands
78```
79smith help # topic list + fuzzy search prompt
80smith help <topic> # show topic (tool, provider, event, etc.)
81smith help <topic>.<function> # show specific function
82smith help --search <query> # fuzzy search across all docs
83smith help --list # list all topics
84smith help --examples # list all examples
85smith help --example <name> # show full example source
86smith help --guide <name> # show full guide
87```
89### Topic Resolution
91Topics map 1:1 to SDK files:
93```
94smith help tools → smith_tool.lua annotations
95smith help provider → smith_provider.lua annotations
96smith help events → smith_events.lua annotations
97smith help tui → smith_tui.lua annotations
98smith help tools.register → specific function within topic
99```
101### Fuzzy Search
103```
104smith 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)
107```
109Fuzzy search across:
110- Function names
111- Descriptions
112- Parameter names
113- Example code
114- Guide prose
116### Navigation
118Interactive mode (when run in TUI):
120```
121smith help
122┌──────────────────────────────────────────┐
123│ Smith SDK Help │
124│ Type to search, Enter to view, Esc to quit│
125├──────────────────────────────────────────┤
126│ > tool │
127│ │
128│ Topics: │
129│ smith.tool.register Register custom tool│
130│ smith.on("tool_call") Intercept tool calls│
131│ smith.on("tool_result") Modify tool results│
132│ │
133│ Guides: │
134│ tools.md Custom tools guide │
135│ │
136│ Examples: │
137│ 02-custom-tool.lua Basic tool example │
138│ 04-permission-gate.lua Block dangerous cmd│
139└──────────────────────────────────────────┘
140```
142Uses the same `SelectList` widget from smith-tui. Reuses the fuzzy matcher.
144## Doc Location
146Docs are resolved in this order:
1481. **Embedded in binary** (always available) — primary source for `smith help`
1492. **Install directory** (`<prefix>/share/smith/docs/`) — compressed fallback
1503. **`SMITH_DOCS_PATH` env var** — override for development
152The embedded docs are compiled from annotations via `include_str!` at build time.
153No files needed on disk for `smith help` to work.
155Install directory contains the generated bundle for:
156- Direct file reading by LLMs via `read` tool
157- Offline access
158- Man pages
160## System Prompt Bootstrap
162```
163Smith is a coding agent that can extend itself via Lua plugins.
165To 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 docs
168- smith help --example N — read a tested example plugin
169- smith help --guide N — read a guide
171Key topics: tools, events, provider, command, shortcut, tui, fs, sandbox
173When asked to create or modify a plugin, read the relevant help first.
174```
176This teaches smith to self-learn. When asked "write a plugin that blocks dangerous
177commands", smith runs `smith help --search "block tool"` → reads `smith help events`
178→ reads `smith help --example 04-permission-gate` → generates correct code.
180## Examples
182Tested examples live in the SDK source:
184```
185smith-harness/src/lua/sdk/examples/
186├── 01-hello-world.lua
187├── 02-custom-tool.lua
188├── 03-event-subscription.lua
189├── 04-permission-gate.lua
190├── 05-custom-provider.lua
191├── 06-custom-command.lua
192├── 07-custom-layout.lua
193├── 08-file-tree-panel.lua
194├── 09-auto-compact.lua
195├── 10-git-checkpoint.lua
196├── 11-session-state.lua
197└── 12-streaming-updates.lua
198```
200Each example has a header comment with description (indexed by `smith help --examples`).
202## Testing Strategy
204### Doc Tests (automated)
206```
207xtask/
208 src/
209 doc_test.rs
210```
212Extracts and runs:
2131. `@usage` blocks from SDK annotation files
2142. Fenced code blocks from guide files (`---[[` ... `--]]`)
2153. Full example files
217All run in sandboxed Lua VM. Any failure = CI failure.
219### Completeness Verification (automated)
221```
222xtask/
223 src/
224 verify_docs.rs
225```
227CI checks:
2281. Every Rust SDK function has a Lua binding with annotations
2292. Every annotated function has `@usage`
2303. Every event appears in at least one example
2314. No documented function that doesn't exist in code
2325. No public SDK function without documentation
234### Guide Correctness (automated)
236Guides are Lua files with prose in comments and code in fenced blocks.
237The doc test runner treats them identically to SDK files — extracts code, runs it.
239This means:
240- Guide code is always tested
241- If an API changes and breaks a guide, CI catches it
242- No separate "guide test" vs "SDK test" — same runner
244## CI Pipeline
246```
247cargo run -p xtask -- test # unit + integration tests
248cargo run -p xtask -- doc-test # run all code blocks
249cargo run -p xtask -- verify-docs # completeness checks
250cargo run -p xtask -- doc-gen # regenerate man pages + bundle (fail if changed)
251cargo run -p xtask -- lint # clippy + luacheck
252```
254## File Structure
256```
257smith-harness/
258├── src/
259│ └── lua/
260│ └── sdk/
261│ ├── smith_tool.lua -- annotations + @usage
262│ ├── smith_provider.lua
263│ ├── smith_command.lua
264│ ├── smith_shortcut.lua
265│ ├── smith_tui.lua
266│ ├── smith_fs.lua
267│ ├── smith_env.lua
268│ ├── smith_credentials.lua
269│ ├── smith_events.lua
270│ ├── guides/
271│ │ ├── getting-started.lua -- prose in comments, tested code
272│ │ ├── tools.lua
273│ │ ├── events.lua
274│ │ ├── providers.lua
275│ │ ├── tui.lua
276│ │ └── sandbox.lua
277│ └── examples/
278│ ├── 01-hello-world.lua
279│ ├── 02-custom-tool.lua
280│ ├── ...
281│ └── 12-streaming-updates.lua
283xtask/
284└── src/
285 ├── doc_test.rs -- run code blocks in Lua VM
286 ├── verify_docs.rs -- completeness checks
287 └── doc_gen.rs -- generate man pages + docs bundle
288```
290## TODO
292- [ ] 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 browse
296- [ ] 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 bootstrap
300- [ ] Set up CI pipeline

docs/plans/README.md

Deleted
deleted file mode 100644

+0 / −23 text lines

1# Plans
2
3Non-normative execution plans — the bridge from `docs/SPEC.md` (what to build)
4to code (in what order). The spec is canonical; a plan never overrides it.
5
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 through
15every layer that proves the StreamFn, EngineEvent, session-codec, and TUI seams
16connect before any of them is built out. `TASK-BREAKDOWN` is the full crate
17sequencing that follows once the skeleton is green. One thing is still
18intentionally *not* written, to avoid speculative planning:
20- **Per-crate breakdowns.** Each SM-0xx task is crate-sized; it gets decomposed
21 into tested units at the start of its own wave, not now.
23Prototype 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

1# Smith Task Breakdown
2
3> Non-normative execution plan. `docs/SPEC.md` is canonical; where this file and
4> the spec disagree, the spec wins. Architecture and crate responsibilities are
5> defined once in SPEC §2 and CLAUDE.md — this file only sequences the build.
6
7Top-level build order for the first implementation pass, at crate granularity.
8Each task is a whole crate; decomposition into buildable, tested units is
9deferred to that crate's own wave (see **Granularity**).
11## Task dependency graph
13```
14SM-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/) ──┘ │
17 SM-011 (workspace)
18 │
19 SM-012 (testing)
20 │
21 SM-013 (release)
22```
24The 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 on
26each other; `smith-harness` wires them; `smith-cli` sits on top.
28## Execution order
30```
31Wave 0: SM-003 scaffolding — jj repo, Cargo workspace, crate skeletons, xtask
32Wave 1: SM-005 smith/ — foundation types (sequential; everything blocks on it)
33Wave 2: SM-006 + SM-007 + SM-008 core / ai / tui (parallel)
34Wave 3: SM-009 smith-harness — wiring (after wave 2)
35Wave 4: SM-010 + SM-011 cli + workspace (parallel)
36Wave 5: SM-012 integration tests
37Wave 6: SM-013 release — §14 artifact matrix via `xtask release`; the required
38 targets whose cross-build is unproven (Windows MSVC, Android)
39 need their §18 proofs before the matrix claims them
40```
42## Tasks
44| 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) | — |
57What each crate owns and must not own is defined once in SPEC §2.2 — not
58repeated here, to avoid drift.
60## Granularity
62These tasks are crate-sized, not buildable units: "SM-006 smith-core" is an
63entire agent loop plus session, tools, hooks, and events. Before a crate's wave
64starts it needs its own breakdown into vertical, tested slices. This file is
65top-level sequencing only; a pure bottom-up walk of it produces nothing runnable
66until SM-010, so the first implementation move should be a thin end-to-end slice
67(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
2
3> Non-normative execution plan. `docs/SPEC.md` is canonical; where this file and
4> the spec disagree, the spec wins. This plan sequences the *first* code, not
5> the whole product — `TASK-BREAKDOWN.md` holds the full crate build order.
6>
7> **This build sequence is the first implementation wave.** Later waves come
8> from `TASK-BREAKDOWN`.
9
10## Why this exists
12`TASK-BREAKDOWN` is bottom-up: `smith/` → core/ai/tui → harness → cli. Built
13literally, nothing runs end-to-end until the last wave, so the first integration
14problem surfaces last — the most expensive place to find it. The walking
15skeleton inverts that: build the **thinnest possible slice through every layer**
16first, prove the seams connect, then widen. Each layer ships the minimum that
17lets the next one exist — no more.
19The slice is one agent turn, end to end, rendered and persisted:
21```
22input → agent loop → StreamFn → (scripted) ProviderEvents → one tool call
23 → assistant Message → EngineEvents → TUI render → session CBOR → reload
24```
26## The seams it proves (the entire point)
28The skeleton exists to exercise the four load-bearing boundaries once, together,
29before any of them is built out:
311. **StreamFn seam** (§5.4) — the agent loop consumes a `StreamFn`, never a
32 concrete provider. Proven in isolation by p07; proven *wired* here.
332. **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.
353. **Session codec** (§6.6) — a turn round-trips through CBOR and reloads
36 identically. Proven in isolation by p06.
374. **TUI render loop** (§8) — EngineEvents render through `TestBackend` with no
38 TTY and no network. Proven in isolation by p08.
40If 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)
56Lua runtime and plugins (§5.5/§9); real providers, auth, OAuth (§7); compaction
57and cost (§6.9); session branching (§6.5 tree); the secret proxy (§6.7); the RPC
58frontend (§10.4); the remaining §8.6 widgets and layout; every CLI subcommand
59beyond `new`/`attach`. None of these block proving the seams.
61## Acceptance
63**One hermetic end-to-end test is the definition of done** (fast tier, §17.1;
64hermeticity rules, §17.10):
66> Given a scripted `StreamFn` whose fixture emits text then one tool call, when
67> `smith new` runs one turn, then the tool executes once, the assistant
68> `Message` is assembled from the `ProviderEvent` stream, the expected
69> `EngineEvent` sequence is observed, `TestBackend` renders the exchange, the
70> session is written as CBOR, and `smith attach` reloads it to a byte-identical
71> in-memory state.
73One additional **gated** smoke test (`network-tests` feature, off by default per
74§17.10) swaps the scripted StreamFn for a real Anthropic call, proving the same
75loop drives a live provider. It never runs in the default lane.
77## Build sequence
79Vertical, not the horizontal waves of `TASK-BREAKDOWN`:
81```
821. workspace skeleton + xtask green
832. smith/ minimal types (only what steps 3–7 consume)
843. scripted StreamFn (fixture in, ProviderEvents out)
854. agent loop: one turn over the StreamFn, EngineEvents out, one tool
865. session: append + CBOR persist/reload
876. TUI: render EngineEvents via TestBackend
887. harness wires 3–6; cli exposes `new` + `attach`
898. the acceptance test goes green → skeleton done
90```
92Each step is mergeable on its own and leaves the tree building.
94## Exit criteria
96- The acceptance test passes in the fast tier; the gated real-provider smoke
97 passes when explicitly run.
98- `cargo run -p xtask -- check` (fmt + clippy + arch + pup + test + doc) is
99 green on the slice.
100- No deferred subsystem was pulled in to make it work.
102## First widening steps after green
104Add a real provider normalizer behind the StreamFn (§7.2, p29); introduce the
105Lua runtime and the first built-in plugin (§5.5/§9); grow the widget set (§8.6);
106add `continue`/`resume` and the session tree (§6.5). Each rides the seams the
107skeleton already proved.

docs/research/TESTING-STRATEGY-RESEARCH.md

Modified

+13 / −13 text lines

119119- **>80% mutants caught** — strong signal that tests verify behavior, not just reach code
120120- **100% on pure functions** — config resolution, CBOR codec, model resolver, event mapping
121- **Incremental on PRs** — only mutants in changed files (fast: ~5 min)
121- **Incremental before integration** — only mutants in changed files (fast: ~5 min)
122122- **Full on main** — all mutants (slow: ~30-60 min, nightly)
124124### Configuration
147147| Trigger | Scope | Duration | Gating |
148148|---------|-------|----------|--------|
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 |
151151| Release | All mutants | ~30-60 min | Block release if <80% |
153153---
295295- **Slower** than TestBackend snapshots (~100ms-1s per test vs ~1ms)
296296- **Flaky** — timing-dependent, requires retries
297297- **Platform-specific** — terminal emulation differences
298- **Not for CI fast tier** — use for medium tier (every PR)
298- **Not for the fast tier** — use for the medium pre-integration tier
300300### When to use
392392```bash
393393# On trunk branch: save baseline
394cargo bench -- --save-baseline main
394cargo bench -- --save-baseline trunk
396# On PR: compare against baseline
397cargo bench -- --baseline main
396# Before integration: compare against baseline
397cargo bench -- --baseline trunk
398398# If any benchmark regresses > threshold, exit non-zero
399399```
424424- TUI integration tests (expectrl)
425425- Session integration tests
426426- Plugin loading tests
427- **Run:** Every PR, post-merge on main
427- **Run:** Before integration and after integration on trunk
429429### Slow tests (1s - 60min)
606606| Concern | Tool | Crate | Scope | Speed | CI Tier |
607607|---------|------|-------|-------|-------|---------|
608608| 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 |
611611| Property | proptest | proptest | Core/Types | ms | Every commit |
612612| Snapshot | insta | insta | TUI/Types | ms | Every commit |
613613| 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 |
616616| 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 |