repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs: spec cleanup — coherence audit fixes and altitude rule (#2)

10c3b95879a710b52733ebaf2061fc68bc66d22e

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

* docs: spec cleanup — resolve coherence audit findings

Three-lens audit (cross-references, contradictions, simplification) over
the post-merge spec; all verified findings applied.

Contradictions resolved:
- auth.json moved to config_dir/smith/auth.json, added to §4 layout
  (was non-XDG ~/.smith/, contradicting §4),
- §9.8 Lua return contracts now express every §6.4 hook capability:
  { cancel } on tool_call, { retry }/{ cancel } on tool_result,
  { stop } on turn_end (were claimed but unreachable),
- heap_limit precedence defined: config override wins over manifest,
- interface bindings re-resolve + re-check conformance on domain reload;
  conformance failure = reload failure with rollback (§9.16),
- coverage gate placed in the before-merge tier, removed from the
  CI-only row (§17.10 vs §17.2/§17.4),
- §8.3 image-protocol probe marked as having no v1 consumer (§8.11),
- blocked-call wording fixed in the §9.8 event table.

Naming/reference repairs:
- §5.7 "pricing" -> cost; explicit models.dev -> ModelMetadata mapping
  table added to §7.3 (limit.context/output, reasoning->thinking, etc.),
- "generation" disambiguated: interface generation (§9.6) vs API
  generation (§9.3) vs domain generation (§9.16),
- §9.14 normalized to "heap limit" terminology,
- jj integration boundary stated in §9.13 (jj-lib or shell-out, hidden
  behind smith.vcs.*, mirroring the §9.5 git boundary),
- orphan deps grounded: smith completions <shell> (§10.2,
  clap_complete), PTY smoke tests via expectrl (§17.8),
- §9.8 errors/shutdown rows split to correct targets.

Simplification (net -12 lines while adding the above):
- measured prototype numbers compressed to PLAN.md citations
  (§6.11, §9.16, §13.1) per §18's own policy,
- §7.3 models.dev narrative merged (was stated 4x); pi principle moved
  to §1 design principles; PR-agent hedge cut,
- §9.5 git-boundary hedge tightened to a decision,
- §6.6 properties/recovery-boundaries merged; §11 credential dupes ->
  §7.4 cross-ref; §9.19 cascade re-list -> §5.6 cite; §17.2 re-list ->
  §17.1 cite; bench thresholds owned by §17.9; §9.12 edit steps 10->6
  with error codes inlined.

All §-references machine-checked to resolve.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: fix PROJECT-INVARIANTS contradictions found by coherence audit

User-approved edits to the protected file:
- §8a "No CI" scoped to release automation (distribution/signing);
  test/lint/coverage CI gates (SPEC §17.10) exist and are required —
  resolves self-contradiction with §3.3/§3.7/§8,
- §4 fetch-providers row: pi.dev -> models.dev (stale vs SPEC §7.3),
- §1 cargo-only exception list now names zig/cargo-zigbuild for release
  cross-builds — §8a mandated a tool §1 prohibited.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: adopt altitude rule — exact at boundaries, shapes inside

AGENTS.md rule 3 now states the spec answers interfaces/data/errors/
tests as named shapes and behavior, not code: exact only at boundaries
others program against (files, wire formats, CLI, config, Lua SDK);
code blocks illustrative unless a section says otherwise. SPEC §1 gets
the matching design principle.

Spec revised to comply — internal-Rust exactness lifted to shapes:
- §5/§6 module-layout code blocks replaced with named exposed-surface/
  responsibility lists,
- §7.1 Provider trait signature replaced with its load-bearing
  properties (thread-safe, object-safe without async-trait, stream is
  a plain method returning a boxed event stream),
- §6.10 Arc<dyn AgentTool> -> shared thread-safe handles.

Kept exact (boundaries): §3.2 crate lint attributes, wire formats,
manifest/config/CLI/Lua SDK shapes, workspace manifest, nextest/release
profiles. Remaining rust block count: 1 (§3.2, enforceable policy).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

---------

Co-authored-by: Claude <noreply@anthropic.com>

Changed files (3)

+162 / −185 text lines

Diff layout

AGENTS.md

Modified

+4 / −1 text lines

45451. Spec before code. No `.rs` files until `docs/SPEC.md` covers the work.
46462. AGENTS.md is the navigation index. `docs/SPEC.md` is the canonical project spec.
473. Every spec section answers: interfaces, types, errors, tests.
473. Every spec section answers: interfaces, data, errors, tests — as named
48 shapes and behavior, not code. Exact only at boundaries others program
49 against (files, wire formats, CLI, config, Lua SDK); code blocks are
50 illustrative unless the section says otherwise.
48514. Open questions: stop and ask. No guessing.
49525. Invoke spec work: `/spec <topic>`.
50536. Cargo is the sole build system. See `docs/PROJECT-INVARIANTS.md` §1.

docs/PROJECT-INVARIANTS.md

Modified

+6 / −3 text lines

1818**Prohibited:**
1919- Makefile, justfile, package.json, build.sh
2020- Shell scripts in repo root or scripts/
21- Any build step that requires tools not installable via `cargo install`, except pinned nightly rustup components required by the `cargo-pup` architecture gate
21- Any build step that requires tools not installable via `cargo install`, with two named exceptions: pinned nightly rustup components required by the `cargo-pup` architecture gate, and the `zig` toolchain required by `cargo-zigbuild` for release cross-builds (§8a)
2323## 2. Directory Separation: Code vs. Project Management
233233| `cargo run -p xtask -- test` | Run all tests (delegates to `cargo nextest run`) | Every commit |
234234| `cargo run -p xtask -- lint` | Clippy + rustfmt check | Every commit |
235235| `cargo run -p xtask -- fmt` | Auto-format (delegates to `cargo fmt`) | On demand |
236| `cargo run -p xtask -- fetch-providers` | Fetch pi.dev + catwalk → `providers.json` | On demand |
236| `cargo run -p xtask -- fetch-providers` | Fetch models.dev + catwalk → `providers.json` | On demand |
237237| `cargo run -p xtask -- doc-test` | Extract + run Lua code blocks from docs | CI |
238238| `cargo run -p xtask -- verify-docs` | Completeness checks (every API documented) | CI |
239239| `cargo run -p xtask -- doc-gen` | Generate man pages + docs bundle | Release |
3363361. `cargo run -p xtask -- release` — builds all targets via cargo-zigbuild, creates archives, generates checksums.
3373372. OpenBSD (Tier 3) is best-effort — build natively if possible, skip otherwise.
339No CI, no automated distribution, no code signing yet. These are deferred.
339No CI-driven *release* automation yet: no automated distribution, no code
340signing — these are deferred. The test/lint/coverage CI gates themselves
341(SPEC §17.10) exist and are required.
341343See `docs/research/RELEASE-BUILD-RESEARCH.md` for cross-platform build tooling analysis.
428430| Date | Change | Author |
429431|------|--------|--------|
432| 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 |
430433| 2026-07-15 | §2 tree: design/ absorbed into SPEC.md and deleted; prototypes/ added (user-approved) | smith-spec |
431434| 2026-05-23 | Add architecture gates and pinned-nightly pup exception | smith-spec |
432435| 2026-05-22 | Initial invariants | smith-spec |

docs/SPEC.md

Modified

+152 / −181 text lines

2929 keybindings, prompts, layouts, and feature UI are Lua plugins.
3030- **LLM is the only untrusted actor.** Local user, local plugins, local files,
3131 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.
3339## 2. Workspace
325331config_dir/smith/
326332 config.lua
333 auth.json
327334```
329336Session files are plaintext length-prefixed CBOR sequences. Trace files are
330337compressed deterministic replay logs. Secrets in sessions are plaintext after
331local registration; the security boundary is the LLM, not the local user.
338local registration (§6.7, §11).
333340## 5. Shared Crate: `smith`
335342`smith` owns shared types and utilities. It has no business logic and no
336343downstream dependencies.
338Exports:
345Exposed surface (names, not module layout):
340```rust
341pub mod types;
342pub mod stream;
343pub mod tool;
344pub mod lua;
345pub mod config;
346pub mod error;
347pub mod mux;
349pub use types::*;
350pub use stream::StreamFn;
351pub use tool::{AgentTool, AgentToolResult, AgentToolUpdate, ToolExecutionMode};
352pub use lua::LuaRuntime;
353pub use config::Config;
354pub use error::SmithError;
355pub use mux::{ModelAlias, ModelGroup, ProviderBucket, ModelResolver, ResolvedModel, ResolveError};
356```
347- the shared types of §5.1–§5.3 (IDs, messages, provider types, tool types:
348 `AgentTool`, `AgentToolResult`, `AgentToolUpdate`, `ToolExecutionMode`),
349- `StreamFn` (§5.4),
350- `LuaRuntime` (§5.5),
351- `Config` (§5.6),
352- the model-resolution types (§5.7): `ModelAlias`, `ModelGroup`,
353 `ProviderBucket`, `ModelResolver`, `ResolvedModel`, `ResolveError`,
354- `SmithError` (§5.8).
358356`smith` must not re-export `smith-core` types. Domain types are imported from
359357their owning crates.
453451Invalid values are rejected with clear errors. Unknown keys warn or fail
454452according to the schema context.
456The cascade is re-evaluated at runtime by host configuration reload (§9.19);
457CLI flags stay fixed for the process lifetime.
454The cascade is re-evaluated at runtime by host configuration reload (§9.19).
459456Example:
477474- provider/model IDs,
478475- context window,
479476- max output tokens,
480- pricing,
477- cost,
481478- capabilities: thinking, vision, tool use, streaming.
483480`ModelResolver` is pure. It resolves:
513510`smith-core` owns pure business logic: agent loop, sessions, tools, hooks,
514511secret proxy, compaction, cost, trace, and replay. It depends only on `smith`.
516Exports:
518```rust
519pub mod agent;
520pub mod session;
521pub mod session_format;
522pub mod tools;
523pub mod events;
524pub mod secret_proxy;
525pub mod system_prompt;
526pub mod compaction;
527pub mod cost;
528pub mod trace;
529pub mod replay;
530```
513Responsibilities (names, not module layout): the agent loop (§6.1), agent and
514engine events (§6.2–§6.3), hooks (§6.4), session model and format (§6.5–§6.6),
515secret proxy (§6.7), system prompt (§6.8), compaction and cost (§6.9), tool
516registry (§6.10), trace and replay (§6.11).
532518### 6.1 Agent Loop
545531- outer loop: turns and follow-up messages,
546532- inner loop: provider streaming, tool calls, steering.
548It never imports provider implementations. Providers are `StreamFn` only.
550534Important config:
552536- `max_tool_calls_per_turn` default `100`,
641625u32 BE len | CBOR entry bytes | u32 BE len | CBOR entry bytes | ...
642626```
644Properties:
628Properties (recovery boundaries prototype-proven, p06):
646- crash recovery: truncated tail stops parsing,
647- corrupt entry: skip + warn if possible,
648- unknown future entry: preserve when round-tripping,
630- truncated tail stops parsing; prior entries survive,
631- a corrupt entry BODY is precisely skippable with a warning — the intact
632 length prefix bounds the damage,
633- a corrupt LENGTH PREFIX desynchronizes framing: entries before it survive,
634 everything after is unrecoverable and indistinguishable from truncation,
635- unknown-vs-corrupt is decided by two-stage decode (raw CBOR, then typed):
636 well-formed CBOR with an unknown variant tag is preserved raw and survives
637 rewrite roundtrips; invalid CBOR is corrupt and skipped,
649638- `smith session dump` outputs JSONL,
650639- session discovery is keyed by canonical `{session-id}.session` filenames.
652Recovery boundaries (prototype-proven, p06):
654- A corrupt entry BODY is precisely skippable — the intact length prefix
655 bounds the damage; prior and subsequent entries survive.
656- A corrupt LENGTH PREFIX desynchronizes framing: entries before it survive,
657 everything after is unrecoverable and indistinguishable from truncation.
658 "Skip + warn if possible" promises no more than this.
659- Unknown-vs-corrupt is decided by two-stage decode: first as raw CBOR, then
660 as a typed entry. Well-formed CBOR with an unknown variant tag is preserved
661 raw and survives rewrite roundtrips; invalid CBOR is corrupt and skipped.
663641### 6.7 Secret Proxy
665643The secret proxy prevents LLM exposure of secrets:
670648- rehydrates tool arguments before local execution,
671649- rebuilds table on resume by scanning session entries backward.
673Secrets are local plaintext. The protection target is the remote LLM.
651Secrets are stored as local plaintext; the trust model is §11's.
675653### 6.8 System Prompt
713691### 6.10 Tool Registry
715`ToolRegistry` stores `Arc<dyn AgentTool>` by name.
693`ToolRegistry` stores shared, thread-safe `AgentTool` handles by name.
717695Rules:
728706- file header with magic/version/session ID,
729707- compressed entries via zstd — per-entry compression inflates small traces
730 (measured ~115% of raw CBOR under ~50 entries from per-entry header
731 overhead); the codec uses block-level compression or a minimum entry-size
732 threshold so small traces never exceed their uncompressed size,
708 (p11 evidence, `prototypes/PLAN.md`), so the codec uses block-level
709 compression or a minimum entry-size threshold; small traces never exceed
710 their uncompressed size,
733711- provider requests/events,
734712- tool calls/results,
735713- TUI events as opaque JSON,
758736### 7.1 Provider Trait
760```rust
761pub trait Provider: Send + Sync {
762 fn id(&self) -> &str;
763 fn name(&self) -> &str;
764 fn validate_auth(&self) -> Result<(), ProviderError>;
765 fn stream(&self, request: ProviderRequest) -> Pin<Box<dyn Stream<Item = ProviderEvent> + Send>>;
766}
767```
738`Provider` is thread-safe and object-safe (usable as a trait object without
739async-trait machinery — a prototype-verified property). It exposes:
769`provider_to_stream_fn(Arc<dyn Provider>)` returns the `StreamFn` consumed by
770`smith-core`.
741- identity: id and display name,
742- auth validation, failing fast before the first stream (§7.4),
743- `stream`: takes a `ProviderRequest`, returns a boxed async stream of
744 `ProviderEvent` — a plain method returning a stream, not an async method.
746`provider_to_stream_fn` adapts a shared `Provider` handle into the `StreamFn`
747consumed by `smith-core`.
772749### 7.2 Provider Implementations
8157922. catwalk provider configs,
8167933. later shared provider repositories after review.
818Pi served as inspiration for Smith and continues to evolve independently; it is
819a philosophical guide, not a dependency. Smith has no data or format coupling
820to pi.
822795Merge rule (prototype-proven, p05):
824797- merge by provider/model ID at LEAF-FIELD granularity — a recursive
847820`replace_models` is a plugin provider-override flag (`smith.provider.*`,
848821§9.10), not a `fetch-providers` merge input.
850**Canonical schema.** Smith does not invent a provider/model schema — the shape
851is already pinned upstream by models.dev (TOML sources CI-validated against its
852published schema). Smith adopts that shape and keeps a pinned local snapshot:
853a JSON Schema at `smith-ai/src/providers.schema.json`, translated from the
854models.dev schema at a recorded upstream version. Local pinning keeps
855validation deterministic and offline; upstream schema evolution is reviewed and
856adopted like any dependency bump.
823**Canonical schema.** Smith does not invent a provider/model schema — it adopts
824the models.dev shape and keeps a pinned local snapshot: a JSON Schema at
825`smith-ai/src/providers.schema.json`, translated from the models.dev schema at
826a recorded upstream version. Local pinning keeps validation deterministic and
827offline; upstream schema evolution is reviewed like any dependency bump.
858829The snapshot is validated with the `jsonschema` workspace crate at three
859830boundaries:
8648352. the checked-in `providers.json` (CI gate),
8658363. provider tables passed to `smith.provider.register` at runtime (§9.10).
867Schema rules:
838Registry shapes follow models.dev naming: `cost` (USD per million tokens:
839`input`, `output`, `cache_read`, `cache_write`, optionally `reasoning` and
840audio variants), `limit` (`context`, `input`, `output`), modalities
841(`input`/`output` type lists), and capability flags (`attachment`,
842`reasoning`, `tool_call`, `structured_output`, `temperature`). `cost` is
843always an object — never a scalar (the p05 type-mismatch class). Unknown
844fields remain schema-legal (`additionalProperties` allowed) per the
845preservation rule above.
869- Registry shapes follow models.dev naming: `cost` (USD per million tokens:
870 `input`, `output`, `cache_read`, `cache_write`, optionally `reasoning` and
871 audio variants), `limit` (`context`, `input`, `output`), modalities
872 (`input`/`output` type lists), and capability flags (`attachment`,
873 `reasoning`, `tool_call`, `structured_output`, `temperature`). Smith maps
874 these into the §5.7 `ModelMetadata` type internally.
875- `cost` is always an object — never a scalar. This resolves the
876 scalar-vs-object ambiguity that produced p05's type-mismatch conflict class.
877- Unknown fields are permitted everywhere (`additionalProperties` allowed) so
878 the preservation rule above stays schema-legal; the snapshot constrains known
879 fields only.
847Mapping into `ModelMetadata` (§5.7):
881Provider config correctness cannot be fully automated because Smith does not have
882all provider accounts, subscriptions, API keys, or regional access. Generated
883changes require review before commit. After the provider format stabilizes,
884Smith may use a coding agent to open provider-data PRs from `fetch-providers`
885diffs.
849| §5.7 field | models.dev source |
850|------------|-------------------|
851| context window | `limit.context` |
852| max output tokens | `limit.output` |
853| cost | `cost` |
854| thinking | `reasoning` |
855| vision | `"image"` in `modalities.input` |
856| tool use | `tool_call` |
857| streaming | assumed true; provider config may disable |
859`structured_output`, `temperature`, and `attachment` are not represented in v1
860`ModelMetadata` and are preserved, not consumed.
862Provider config correctness cannot be fully automated because Smith does not
863have all provider accounts, subscriptions, API keys, or regional access.
864Generated changes require review before commit.
887866### 7.4 Auth
889868Auth resolver sources:
891870- environment variables,
892- `~/.smith/auth.json`,
871- `config_dir/smith/auth.json` (§4),
893872- plaintext Lua config values when explicitly supplied.
895874No OS keychain. No encryption.
900879`api_key` (with its `env_var` name), `oauth`, and `organization` (org-scoped
901880key, e.g. OpenAI: api key + org ID). `AuthMethod` mirrors these three.
903`~/.smith/auth.json` is a per-provider object map:
882`auth.json` is a per-provider object map:
905884```json
978957- capabilities are probed once per session at startup, with a 100ms timeout
979958 per probe; on timeout the capability is treated as absent (fail
980959 conservative),
981- image protocol is `ImageProtocol::{Kitty, Sixel}` — no other variants in v1,
960- image protocol is `ImageProtocol::{Kitty, Sixel}`; the capability is
961 detected but has no v1 consumer — inline image rendering is deferred
962 (§8.11),
982963- Kitty keyboard protocol flags are pushed on TUI startup and popped on
983964 shutdown (including error/signal paths, §10),
984965- synchronized output (`CSI ?2026 h/l`) wraps render passes when the terminal
12491230- Git installs strip the `.git` directory: an installed plugin is a pure file
12501231 snapshot, not a working clone. Updates go through reinstall.
1252Git URL installs use Smith's internal git implementation boundary. The preferred
1253implementation is `gix` if its required clone/fetch feature set stays bounded;
1254otherwise the behavior remains the same behind the install boundary. Prototype
1255evidence (p04): shell-out to a system git binary satisfies the boundary with
1256zero added crates but adds a runtime dependency on git being installed — the
1257boundary hides whichever choice release engineering makes.
1233Git URL installs go through Smith's internal git boundary; the concrete
1234implementation (`gix` or system-git shell-out) is release engineering's choice,
1235hidden behind the boundary (p04 evidence, `prototypes/PLAN.md`).
12591237`smith uninstall <org>/<name>`:
12861264enforcement points.
12881266**Descriptor.** An interface package exports a descriptor: a pure data table
1289with `name` (`<org>/<name>`), `generation` (integer), `functions` (map of
1290function name → `{ params, returns }` with typed, optionally-optional named
1291parameters), and `events` (list of bus topics, §9.18).
1267with `name` (`<org>/<name>`), `generation` (integer — the interface's own
1268version, distinct from the plugin API generation of §9.3 and the reload domain
1269generation of §9.16), `functions` (map of function name → `{ params, returns }`
1270with typed, optionally-optional named parameters), and `events` (list of bus
1271topics, §9.18).
12931273**Ecosystem shapes.** Interface-only packages, implementation-only packages,
12941274implementations referencing external interfaces, and combined packages are all
13491329| `model_select` | No | model changed |
13501330| `message_start`, `message_update`, `message_end` | No | streaming lifecycle |
13511331| `thinking_delta`, `text_delta` | No | token deltas |
1352| `tool_execution_start` | No | execution began |
1332| `tool_execution_start` | No | execution began or call was blocked (§6.4) |
13531333| `tool_call` | **Yes** | before tool executes (§6.4 blocked-call contract) |
13541334| `tool_execution_update`, `tool_result`, `tool_execution_end` | No | `tool_result` may modify the result |
13551335| `input` | No | may intercept/transform/mark handled |
13611341| `panel_toggle`, `resize` | No | TUI |
13621342| `provider_registered` | No | after provider add/override |
13631343| VCS events | No | §9.13 operations |
1364| errors, shutdown | No | §9.17 |
1344| errors | No | §9.17 |
1345| shutdown | No | host shutdown (§10, §12) |
1366Handler return-table contracts (Lua-facing):
1347Handler return-table contracts (Lua-facing, one per §6.4 hook capability):
13681349- `tool_call` → `{ block = true, reason = "..." }` or
1369 `{ args = <replacement> }` or nil/`{}` (allow),
1370- `tool_result` → `{ content = <replacement> }` or nil (keep),
1350 `{ args = <replacement> }` or `{ cancel = true }` or nil/`{}` (allow),
1351- `tool_result` → `{ content = <replacement> }` or `{ retry = true }` or
1352 `{ cancel = true }` or nil (keep),
1353- `turn_end` → `{ stop = true }` to end the agent loop after this turn
1354 (ShouldStopAfterTurn), or nil (continue),
13711355- `input` → `{ action = "handled" | "continue", text = <transformed>? }`,
13721356- `context` → `{ messages = <modified> }` or nil,
13731357- `session_before_*` → `{ block = true, reason = "..." }` or nil,
13741358- all other events: return value ignored.
1376The bridge maps these into `AgentLoopConfig` hooks (§6.4): block/transform
1377tool calls, replace results, retry/cancel, transform input, override system
1378prompt/context, request continue/stop, emit UI actions.
1360The bridge maps these into `AgentLoopConfig` hooks (§6.4).
13801362### 9.9 Extension Contexts
15361518- `new_text`,
15371519- `allow_multiple?: bool`.
1539Behavior:
1521Behavior (ordering is the contract):
15411. read file,
15422. reject empty `old_text`,
15433. reject binary,
15444. count exact matches,
15455. fail if zero matches,
15466. fail if multiple and `allow_multiple` false,
15477. re-read/hash before write,
15488. fail stale if file changed,
15499. write atomically,
155010. return change count and before/after hashes.
1552Errors include `ENOENT`, `EEMPTY`, `EBINARY`, `ENOMATCH`, `EMULTI`, `ESTALE`,
1553`ELOCK`.
15231. read the file (`ENOENT`),
15242. validate: non-empty `old_text`, non-binary content (`EEMPTY`, `EBINARY`),
15253. count exact matches: zero fails; multiple fails unless `allow_multiple`
1526 (`ENOMATCH`, `EMULTI`),
15274. re-read and hash immediately before write; fail if the file changed
1528 (`ESTALE`),
15295. write atomically via temp file + rename (`ELOCK`),
15306. return change count and before/after hashes.
15551532#### `bash`
15861563### 9.13 VCS SDK
1588Smith uses jj internally for operation-level undo/redo/time travel.
1565Smith uses jj internally for operation-level undo/redo/time travel. jj is
1566driven through the same kind of internal boundary as §9.5's git installs: the
1567concrete integration (`jj-lib` crate or jj binary shell-out) is release
1568engineering's choice, hidden behind `smith.vcs.*`.
15901570State:
16391619- no path capability system in v1,
16401620- built-in and user plugins use same API.
1642**Heap quota.** A plugin may be given a Lua heap limit via the optional
1643`heap_limit` manifest field (§9.2) or config override. Prototype-proven (p10,
1644p11) semantics:
1622**Heap limit.** A plugin may be given a Lua heap limit via the optional
1623`heap_limit` manifest field (§9.2) or config override; when both are set, the
1624config override wins (§5.6 cascade: user config over plugin contributions).
1625Prototype-proven (p10, p11) semantics:
1646- The quota domain is the plugin's own Lua state — one `mlua::Lua` per plugin
1647 (matching the §9.16 domain model). Per-plugin quotas in a shared Lua state are
1648 not attributable and are not offered.
1627- The limit's domain is the plugin's own Lua state — one `mlua::Lua` per
1628 plugin (matching the §9.16 domain model). Per-plugin limits in a shared Lua
1629 state are not attributable and are not offered.
16491630- Enforcement is `Lua::set_memory_limit()`; under the locked vendored-LuaJIT
16501631 feature set this enforces exactly, and breach surfaces as a recoverable
16511632 memory error handled by the §9.17 error model. Targets where mlua reports
1652 memory control as unavailable must fail plugin-quota configuration loudly,
1633 memory control as unavailable must fail heap-limit configuration loudly,
16531634 never enforce silently at zero; per-target enforcement is CI-verified.
1654- The quota covers the plugin's Lua heap only, including host-created Lua
1655 values. Host-side Rust allocations held for a plugin are invisible to the
1656 quota and are bounded by domain teardown (§9.16) instead.
1635- The limit covers the plugin's Lua heap only, including host-created Lua
1636 values. Host-side Rust allocations held for a plugin are invisible to it
1637 and are bounded by domain teardown (§9.16) instead.
16571638- After a plugin OOM, the preferred recovery is whole-domain replacement
16581639 (§9.16) rather than in-place retry.
17381719 warmup; no stale callback from `D` may run after the swap. The plateau is
17391720 the enforceable observable — an instantaneous RSS decrease per teardown is
17401721 not required, since small freed heaps are legitimately retained by the
1741 allocator for reuse (p11: ≤77KB growth over 80 cycles; a 31MB teardown
1742 returned fully to the OS).
1722 allocator for reuse (p11 evidence, `prototypes/PLAN.md`).
17441724**Rollback.** Reload is all-or-nothing. Either `D'` fully replaces `D`, or `D`
17451725remains and no partial state from `D'` survives. A failed reload never leaves the
17501730old domain run to completion under `D`; their results are still delivered. New
17511731invocations after the swap use `D'`.
1733**Interface bindings.** If the reloaded plugin backs an interface binding
1734(§9.6), the swap re-resolves the binding to `D'` and re-runs bind-time
1735conformance against it. Consumers' interface views rebind transparently — the
1736next call through a view dispatches into `D'`. A conformance failure is a
1737reload failure: rollback keeps `D` and its binding active.
17531739**Dependents.** Reloading `P` does not reload its dependents (§9.15). Dependents
17541740keep their handles to `P`'s registrations by stable name; the swap rebinds those
17551741names to `D'`. A reload that removes a registration a dependent relies on surfaces
18311817losing the active session. Host reload follows the same contract shape as plugin
18321818reload (§9.16): validate fully, swap atomically, roll back on failure.
1834**Scope.** A host reload re-evaluates the config cascade (§5.6) layers 1–4:
18361. Rust type defaults/schema,
18372. built-in Lua defaults,
18383. plugin contributions,
18394. user config at `config_dir/smith/config.lua`.
1841CLI flags (layer 5) are per-invocation. They were resolved at process start and
1842continue to override the reloaded layers unchanged.
1820**Scope.** A host reload re-evaluates config cascade layers 1–4 (§5.6). CLI
1821flags (layer 5) are per-invocation: resolved at process start, they continue to
1822override the reloaded layers unchanged.
18441824**Triggers.** Reload is requested by:
19221902- `smith uninstall <plugin>` — uninstall plugin.
19231903- `smith eval <prompt> [--json] [--session id]` — non-interactive eval.
19241904- `smith rpc` — JSON-RPC via stdio; methods include `config/reload` (§9.19).
1905- `smith completions <shell>` — generate shell completions (`clap_complete`).
19251906 The full method catalog is deferred: it is expected to mirror the Lua SDK
19261907 surface (§9.10), with mode-specific additions and omissions, rather than
19271908 define an independent API.
19581939Security mechanisms:
19601. Tool registry controls which tools the LLM can invoke.
19612. Secret proxy prevents real secrets from reaching LLM context.
19623. Restricted Lua runtime removes raw OS/file APIs.
19411. Tool registry (§6.10) controls which tools the LLM can invoke.
19422. Secret proxy (§6.7) prevents real secrets from reaching LLM context.
19433. Restricted Lua runtime (§5.5) removes raw OS/file APIs.
196319444. Users configure active tools; no confirmation-dialog security theater.
1965Credentials:
1967- environment vars preferred,
1968- plaintext config/auth file allowed,
1969- no keychain,
1970- no encryption.
1946Credential storage follows §7.4: plaintext, no keychain, no encryption.
19721948## 12. Concurrency and Async
19971973- TUI frame draw < 2ms within 16ms frame budget.
19981974- Session encode 1000 entries < 5ms.
19991975- Agent loop turn target < 30s excluding provider/network stalls beyond timeout.
2000- Bench regressions >10% fail nightly/release gates.
1976- Bench regressions fail nightly/release gates (thresholds in §17.9).
20021978### 13.1 Memory Policy
20051981`docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):
20071983- **Session discovery is lazy and metadata-only.** Discovery reads session
2008 headers, never full bodies: O(session count), not O(corpus bytes). Fully
2009 loading a realistic corpus would cost ~0.7–1.2GiB resident.
1984 headers, never full bodies: O(session count), not O(corpus bytes).
20101985- **Virtual scroll materializes at most viewport rows per frame.** Row
20111986 formatting stops at the visible window (lazy wrap); a single multi-MiB
20121987 message must not be fully formatted to render its visible slice.
20161991 arena code. Arena references never cross async, thread, or persistence
20171992 boundaries.
20181993- **Keep/drop gates for arena use** weigh allocator-call pressure, elapsed
2019 time, and peak/plateau stability — not allocation count alone. Measured:
2020 render-frame scratch is a clear win (−100% allocator calls, ~5× faster);
2021 request-build scratch is marginal (−99% calls, ×1.00 elapsed, +22% peak) —
2022 arenas are not a latency win where serialization dominates.
2023- **Provider request assembly** at compaction-scale contexts (~250k tokens) has
2024 a transient peak ~2.5× the serialized request size and must release it fully
2025 after send; peak memory (not just CPU) is a test gate.
1994 time, and peak/plateau stability — not allocation count alone. Render-frame
1995 scratch is a clear win; request-build scratch is marginal — arenas are not a
1996 latency win where serialization dominates (p09 measurements,
1997 `prototypes/PLAN.md`).
1998- **Provider request assembly** at compaction-scale contexts has a transient
1999 peak of a small multiple of the serialized request size and must release it
2000 fully after send; peak memory (not just CPU) is a test gate.
20272002## 14. Release Artifacts
21232098### 17.2 Medium Tier
2125Every PR:
2100Every PR: the fast tier (§17.1, with `--profile default` instead of `fast`),
2101plus:
21272103```bash
2128cargo fmt --check
2129cargo clippy --workspace --all-targets --all-features -- -D warnings
2130cargo run -p xtask -- arch
2131cargo +nightly-2026-01-22 pup
2132cargo nextest run --profile default
2133cargo test --doc
21342104cargo tarpaulin --out Lcov
21352105cargo nextest run --profile integration
21362106cargo doc --workspace --no-deps
22372207- plugin load/order/override/event dispatch,
22382208- provider registry/custom provider/auth/mock streaming/MuxProvider failover,
22392209- TUI startup/shutdown/capabilities/mouse/layout/theme/scroll,
2210- interactive PTY smoke tests via `expectrl` (real terminal I/O paths),
22402211- docs/help/search/examples.
22422213Fixtures live under `tests/fixtures/` with plugins, sessions, configs, providers,
22732244| Context | Gate |
22742245|---------|------|
22752246| every agent iteration | fast tier (§17.1) |
2276| before merge | fast + medium tiers |
2277| CI only | slow tier, coverage, mutation, benchmarks |
2247| before merge | fast + medium tiers (coverage gate included, §17.4) |
2248| CI only | slow tier, mutation, benchmarks |
22792250Agent CI-safety rules (binding for any coding agent working on Smith):