repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

chore(system): align lifecycle artifacts and foundation gates

b024614c43bd405fd2bb2f906b0675f99d9926f3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Migrate System bundles to schema 0 and project-wide phases. Restore the SMH-PLAN-WSPC0001 lint and Termux linker path so stable workspace gates run.

Changed files (28)

+695 / −2213 text lines

Diff layout

.cargo/config.toml

Modified

+9 / −4 text lines

11[alias]
22x = "run -p xtask --"
4[build]
4# Keep universal policy in a matching target table so platform-specific flags
5# compose with it instead of replacing it.
6[target.'cfg(all())']
57rustflags = [
68 # Zero warnings policy
79 "-D", "warnings",
3638[registries.crates-io]
3739protocol = "sparse"
39# Target-scoped: only applies when building on/for Termux ARM64 (vendored
40# LuaJIT needs the compiler-rt builtins). No effect on other platforms.
41# Native Termux ARM64: vendored LuaJIT needs compiler-rt for __clear_cache.
42# `latest` is Termux's stable symlink to the installed Clang resource version.
4143[target.aarch64-linux-android]
42rustflags = ["-C", "link-args=-lclang_rt.builtins-aarch64-android"]
44rustflags = [
45 "-L", "native=/data/data/com.termux/files/usr/lib/clang/latest/lib/linux",
46 "-C", "link-arg=-lclang_rt.builtins-aarch64-android",
47]

.pi/settings.json

Added
new file mode 100644

+6 / −0 text lines

1{
2 "skills": [
3 "/data/data/com.termux/files/home/.pi/agent/skills/luci-ci/SKILL.md",
4 "+/data/data/com.termux/files/home/.pi/agent/skills/luci-ci/SKILL.md"
5 ]
6}No final newline

.system/board.json

Added
new file mode 100644

+4 / −0 text lines

1{
2 "schemaVersion": 0,
3 "items": {}
4}

.system/config.json

Modified

+3 / −2 text lines

11{
22 "prefix": "SMH",
3 "schemaVersion": 3,
4 "title": "smith"
3 "schemaVersion": 0,
4 "title": "smith",
5 "currentPhase": "SMH-PHASE-CORE0001"
56}

.system/issues/SMH-ISSUE-R4SEXWVT-running-cargo-run-p-xtask-command-is-cumbersome/index.md

Modified

+0 / −1 text lines

33type: issue
44title: "xtask command invocation is cumbersome"
55specs: [SMH-SPEC-SPEC0001]
6status: done
76---
98# xtask Command Invocation Is Cumbersome

.system/phases/SMH-PHASE-AIAG0001-agent-capability/index.md

Added
new file mode 100644

+17 / −0 text lines

1---
2id: SMH-PHASE-AIAG0001
3type: phase
4title: "Agent Capability"
5label: agent
6---
7
8# Agent Capability
9
10## Operating posture
12Make Smith useful across all supported operating modes through a provider-independent agent loop.
13Prioritize normalized provider behavior, deterministic turns, and complete event capture.
15## Transition signal
17Eval and RPC exercise the same reliable agent behavior without provider details leaking across crate boundaries.

.system/phases/SMH-PHASE-AIAG0001-provider-and-agent-loop/index.md

Deleted
deleted file mode 100644

+0 / −39 text lines

1---
2id: SMH-PHASE-AIAG0001
3type: phase
4title: "Provider and Agent Loop"
5spec: SMH-SPEC-SPEC0001
6status: draft
7depends_on: [SMH-PHASE-CORE0001]
8---
9
10# Provider and Agent Loop
12## Scope
14Make Smith useful in eval mode with one provider path and the core loop.
16## Steps
181. Implement provider trait and normalized stream events.
192. Implement auth resolver.
203. Implement OpenAI-compatible SSE provider.
214. Implement minimal model registry.
225. Implement agent loop over StreamFn and tools.
236. Expose eval and JSON-RPC commands.
25## Dependencies
27- SMH-PHASE-CORE0001
29## Risks
31- Provider quirks can leak into core.
32- Tool-call chunk parsing can be wrong under streaming.
33- Eval mode can overfit CLI before harness exists.
35## Done
37- Mock provider drives one full tool-using turn.
38- OpenAI-compatible mocked SSE tests pass.
39- Eval emits deterministic session entries.

.system/phases/SMH-PHASE-CORE0001-core-capability/index.md

Added
new file mode 100644

+17 / −0 text lines

1---
2id: SMH-PHASE-CORE0001
3type: phase
4title: "Core Capability"
5label: core
6---
7
8# Core Capability
9
10## Operating posture
12Establish Smith's provider-free runtime foundation across the project.
13Prioritize stable shared types, deterministic sessions, explicit errors, and safe tool effects.
15## Transition signal
17The product can persist and replay tool-driven state without relying on a live provider or interface mode.

.system/phases/SMH-PHASE-CORE0001-core-session-and-tools/index.md

Deleted
deleted file mode 100644

+0 / −38 text lines

1---
2id: SMH-PHASE-CORE0001
3type: phase
4title: "Core Session and Tools"
5spec: SMH-SPEC-SPEC0001
6status: draft
7depends_on: [SMH-PHASE-XCICUUJD]
8---
9
10# Core Session and Tools
12## Scope
14Build the provider-free spine: shared types, deterministic storage, tool registry, and built-in tools.
16## Steps
181. Implement `smith` shared types and errors.
192. Implement config and Lua runtime shell without plugin loading.
203. Implement CBOR session and trace format.
214. Implement tool registry.
225. Implement read, write, edit, ls, find, grep, bash.
24## Dependencies
26- SMH-PHASE-XCICUUJD
28## Risks
30- Tool mutation semantics can corrupt sessions if not recorded atomically.
31- Shell tool needs timeout and bounded output from day one.
32- CBOR format must be stable before replay work starts.
34## Done
36- Session roundtrip tests pass.
37- Tool tests cover success and explicit errors.
38- Tool events are persisted deterministically.

.system/phases/SMH-PHASE-LUAH0001-extensible-product/index.md

Added
new file mode 100644

+17 / −0 text lines

1---
2id: SMH-PHASE-LUAH0001
3type: phase
4title: "Extensible Product"
5label: plugins
6---
7
8# Extensible Product
9
10## Operating posture
12Make Lua extension the normal product path across Smith.
13Prioritize one sandboxed loading model for built-in and user behavior, with Rust limited to safe primitives.
15## Transition signal
17Smith operates through its public plugin surface without separate privileged paths for built-ins.

.system/phases/SMH-PHASE-LUAH0001-lua-harness-and-plugins/index.md

Deleted
deleted file mode 100644

+0 / −38 text lines

1---
2id: SMH-PHASE-LUAH0001
3type: phase
4title: "Lua Harness and Plugins"
5spec: SMH-SPEC-SPEC0001
6status: draft
7depends_on: [SMH-PHASE-AIAG0001]
8---
9
10# Lua Harness and Plugins
12## Scope
14Connect Rust subsystems to Lua plugin loading and built-in extension points.
16## Steps
181. Implement sandboxed Lua runtime and Teal loading.
192. Implement convention plugin discovery.
203. Implement event bridge and SDK namespaces.
214. Move built-in commands and tool renderers into Lua plugins.
225. Wire harness for config, provider, agent, plugins, and modes.
24## Dependencies
26- SMH-PHASE-AIAG0001
28## Risks
30- Plugin API can become a second Rust API by accident.
31- Sandbox restrictions can block built-ins unless SDK primitives are complete.
32- Hot reload must not lose session continuity.
34## Done
36- Built-in plugins load through the same path as user plugins.
37- Lua SDK has typed declarations.
38- Harness can run eval with plugins enabled.

.system/phases/SMH-PHASE-RELS0001-docs-release-and-hardening/index.md

Deleted
deleted file mode 100644

+0 / −39 text lines

1---
2id: SMH-PHASE-RELS0001
3type: phase
4title: "Docs Release and Hardening"
5spec: SMH-SPEC-SPEC0001
6status: draft
7depends_on: [SMH-PHASE-TUIR0001]
8---
9
10# Docs Release and Hardening
12## Scope
14Finish provider coverage, help docs, release artifacts, and required gates.
16## Steps
181. Complete bundled provider registry and fetch review flow.
192. Generate SDK help from Teal declarations and usage blocks.
203. Add doc tests and completeness checks.
214. Add cargo-pup, audit, coverage, and release gates.
225. Build release archives and checksums.
236. Add regression coverage for replay, plugins, providers, and tools.
25## Dependencies
27- SMH-PHASE-TUIR0001
29## Risks
31- Provider data can drift without review provenance.
32- Documentation can become a second SDK source of truth.
33- Release gates can depend on unavailable external services.
35## Done
37- `smith help` covers the public Lua SDK.
38- CI runs all required gates.
39- Release artifacts match spec format.

.system/phases/SMH-PHASE-RELS0001-release-readiness/index.md

Added
new file mode 100644

+17 / −0 text lines

1---
2id: SMH-PHASE-RELS0001
3type: phase
4title: "Release Readiness"
5label: release
6---
7
8# Release Readiness
9
10## Operating posture
12Prepare the whole product for dependable public distribution.
13Prioritize complete documentation, reproducible artifacts, reviewed provider data, and enforced quality gates.
15## Transition signal
17A release can be built, verified, understood, and operated without undocumented maintainer knowledge.

.system/phases/SMH-PHASE-TUIR0001-interactive-product/index.md

Added
new file mode 100644

+17 / −0 text lines

1---
2id: SMH-PHASE-TUIR0001
3type: phase
4title: "Interactive Product"
5label: interactive
6---
7
8# Interactive Product
9
10## Operating posture
12Make terminal interaction and historical state first-class across Smith.
13Prioritize consistent live and replayed views, Lua-owned layout, and controlled VCS operations.
15## Transition signal
17Users can operate, inspect, and revisit an agent session through one coherent terminal experience.

.system/phases/SMH-PHASE-TUIR0001-tui-and-replay/index.md

Deleted
deleted file mode 100644

+0 / −39 text lines

1---
2id: SMH-PHASE-TUIR0001
3type: phase
4title: "TUI and Replay"
5spec: SMH-SPEC-SPEC0001
6status: draft
7depends_on: [SMH-PHASE-LUAH0001]
8---
9
10# TUI and Replay
12## Scope
14Add interactive terminal UI, session replay, and VCS-backed undo/time travel.
16## Steps
181. Implement terminal backend and event normalization.
192. Implement widget primitives and theme schema.
203. Implement Lua-driven layout integration.
214. Implement replay engine over sessions and traces.
225. Implement jj-lib VCS SDK primitives.
236. Add undo, redo, history, and time-travel plugins.
25## Dependencies
27- SMH-PHASE-LUAH0001
29## Risks
31- TUI layout can leak product behavior into Rust widgets.
32- Replay can drift from stored session semantics.
33- VCS SDK can expose unsafe mutation without confirmation.
35## Done
37- TUI renders a live agent session.
38- Replay can seek and compare turns.
39- VCS plugins operate only through `smith.vcs.*`.

.system/phases/SMH-PHASE-XCICUUJD-project-foundation/index.md

Added
new file mode 100644

+17 / −0 text lines

1---
2id: SMH-PHASE-XCICUUJD
3type: phase
4title: "Project Foundation"
5label: foundation
6---
7
8# Project Foundation
9
10## Operating posture
12Establish the project-wide conditions for safe Smith development.
13Prioritize repository law, crate boundaries, Cargo-only automation, and executable quality gates.
15## Transition signal
17All later product work starts from a buildable workspace with enforced architectural boundaries.

.system/phases/SMH-PHASE-XCICUUJD-the-current-plans-are-too-broad-reshape-into-man/index.md

Deleted
deleted file mode 100644

+0 / −38 text lines

1---
2id: SMH-PHASE-XCICUUJD
3type: phase
4title: "Foundation and Gates"
5spec: SMH-SPEC-SPEC0001
6status: done
7---
8
9# Foundation and Gates
11## Scope
13Create the empty product skeleton and make repository rules executable.
15## Steps
171. Create Cargo workspace and crate shells.
182. Add shared lint, fmt, docs, and audit config.
193. Add xtask command shell.
204. Add architecture checks for crate dependency direction.
215. Add minimal CI command path.
23## Dependencies
25None. First phase.
27## Risks
29- Root manifest edits need explicit approval.
30- Lint policy may block before code exists.
31- Architecture checks can drift from spec names.
33## Done
35- Workspace builds with empty crates.
36- Each crate has docs and unsafe policy.
37- xtask exposes check, lint, test, doc, arch stubs.
38- CI can run the cheap gates.

.system/plans/SMH-PLAN-AIAG0001-provider-and-agent-loop/index.md

Modified

+41 / −24 text lines

11---
22id: SMH-PLAN-AIAG0001
33type: plan
4title: "Provider and Agent Loop Plan"
4title: "Provider Runtime and Agent Loop"
55spec: SMH-SPEC-SPEC0001
6phase: SMH-PHASE-AIAG0001
76status: draft
87depends_on: [SMH-PLAN-CORE0001]
98---
11# Provider and Agent Loop Plan
10# Provider Runtime and Agent Loop
13## Build order
12## Entry
151. Add provider trait and normalized events.
162. Add auth resolver and auth errors.
173. Add mocked OpenAI-compatible SSE parser.
184. Add OpenAI-compatible provider shell.
195. Add minimal model registry.
206. Add agent loop over StreamFn.
217. Add eval command.
228. Add JSON-RPC command.
14- Shared stream, tool, error, session, and trace contracts are stable.
15- Provider-free tool events persist correctly.
17## Order
191. Add `smith-ai` provider adapters that normalize deltas, tool calls, usage, stop reasons, errors, and cancellation.
202. Add explicit model capability metadata and request validation.
213. Add the reviewed offline catalog and deterministic alias, group, and account resolution.
224. Add credential resolution, readiness checks, renewable credentials, and concurrent update safety.
235. Add cancellable catalog refresh with cached fallback and generation-checked publication.
246. Prove one OpenAI-compatible stream against fragmented, malformed, incomplete, and non-stream error fixtures.
257. Add required Anthropic, OpenAI, and Google adapter coverage through the same normalized boundary.
268. Add the `smith-core` agent loop with ordered turn, message, tool, retry, and settled events.
279. Add steering, follow-up, compaction, cost, secret substitution, bounded retry, and failover behavior.
2810. Expose eval and LF-delimited JSON-RPC through `smith-cli` and `smith-harness`.
2430## Interfaces
26| Module | Interface |
27|---|---|
28| smith-ai | provider, registry, auth |
29| smith-core agent | turn input, stream events, tool calls |
30| smith-cli | eval and rpc entrypoints |
32- `smith-ai::provider`: vendor transport to normalized stream.
33- `smith-ai::models`: coherent catalog snapshots and capabilities.
34- `smith-ai::auth`: credential state without context exposure.
35- `smith-core::agent`: provider-independent turns and ordered effects.
36- `smith-harness`: shared eval and RPC runtime assembly.
32## Checks
38## Verification
34- Mock stream drives complete assistant turn.
35- Tool call loop persists all entries.
36- Non-SSE JSON error becomes provider error.
40- A mock provider completes a tool-using turn with correctly paired durable events.
41- Every stream has one terminal outcome; malformed terminal sequences fail explicitly.
42- Requests cannot use unadvertised model capabilities.
43- Stale or cancelled catalog refreshes cannot replace newer state.
44- Offline startup retains a usable catalog.
45- Concurrent credential changes preserve unrelated providers.
46- Injected messages never split tool calls from results.
47- Compaction preserves queued-message mode and rejects incomplete summaries.
48- RPC deltas assemble to the authoritative final message and errors retain request IDs.
38## Stop points
50## Exit
40- Provider-specific fields leak into core.
41- JSON-RPC framing conflicts with session format.
52Eval and RPC run complete provider-backed agent turns through one runtime without vendor details crossing the provider boundary.
54## Stop conditions
56- Provider fields are required by core behavior.
57- Catalog authority or refresh conflict policy is unresolved.
58- Event ordering cannot represent a provider edge case without ambiguity.

.system/plans/SMH-PLAN-CORE0001-core-session-and-tools/index.md

Modified

+38 / −24 text lines

11---
22id: SMH-PLAN-CORE0001
33type: plan
4title: "Core Session and Tools Plan"
4title: "Core Session and Tool Effects"
55spec: SMH-SPEC-SPEC0001
6phase: SMH-PHASE-CORE0001
76status: draft
87depends_on: [SMH-PLAN-WSPC0001]
98---
11# Core Session and Tools Plan
10# Core Session and Tool Effects
13## Build order
12## Entry
151. Add shared IDs, request, response, error, and stream types.
162. Add config data and validation.
173. Add deterministic session entries and CBOR codec.
184. Add trace model.
195. Add tool registry.
206. Add read, write, edit.
217. Add ls, find, grep.
228. Add bash last.
14- Workspace shells and architecture gates exist.
15- No provider or interface is required.
17## Order
191. Define shared IDs, messages, normalized stream events, tool metadata, cancellation, and recoverable errors in `smith`.
202. Add validated runtime configuration types without loading plugins.
213. Add the `smith-core` session model, selected branch, and in-memory restoration.
224. Add deterministic length-prefixed CBOR framing with bounded decode and opaque unknown-frame retention.
235. Add append, load, fork, repair, and writer serialization around the session store.
246. Add replay-relevant trace records without implementing presentation.
257. Add the tool registry and lifecycle event boundary.
268. Add read, write, exact edit, list, find, and grep effects.
279. Add bounded cancellable bash execution after file effects are stable.
2429## Interfaces
26| Module | Interface |
27|---|---|
28| smith | shared types only |
29| smith-core session | append, load, list, validate |
30| smith-core tools | register, invoke, emit event |
31- `smith`: provider-neutral values, errors, cancellation, and tool contracts.
32- `smith-core::session`: branch state and durable frame operations.
33- `smith-core::trace`: ordered replay evidence.
34- `smith-core::tools`: registration, validation, invocation, and recorded outcomes.
32## Checks
36## Verification
34- CBOR roundtrip is byte-stable.
35- Tool errors are typed and persisted.
36- File mutation tools are atomic and stale-safe.
38- Equivalent sessions encode identically.
39- Complete frames survive truncated tails; unknown frames round-trip unchanged.
40- Corrupt or oversized frames cannot trigger unbounded allocation or scanning.
41- Concurrent writers cannot interleave frames or lose committed entries.
42- Fork and in-memory restoration preserve IDs, order, leaf, and compaction boundary.
43- File mutations are atomic and exact edit rejects stale or ambiguous input.
44- Tool effects and their durable outcomes cannot disagree silently.
45- Bash timeout and cancellation terminate the owned process tree where supported and retain late output.
38## Stop points
47## Exit
40- Session format ambiguity.
41- Tool side effect cannot be recorded with event.
49Provider-free tool activity can be persisted, recovered, and reconstructed deterministically.
51## Stop conditions
53- Frame recovery semantics remain ambiguous.
54- A successful mutation cannot be coupled to a durable outcome.
55- Cancellation ownership across a tool effect is unclear.

.system/plans/SMH-PLAN-LUAH0001-lua-harness-and-plugins/index.md

Modified

+38 / −24 text lines

11---
22id: SMH-PLAN-LUAH0001
33type: plan
4title: "Lua Harness and Plugins Plan"
4title: "Sandboxed Plugin Harness"
55spec: SMH-SPEC-SPEC0001
6phase: SMH-PHASE-LUAH0001
76status: draft
87depends_on: [SMH-PLAN-AIAG0001]
98---
11# Lua Harness and Plugins Plan
10# Sandboxed Plugin Harness
13## Build order
12## Entry
151. Add Lua runtime sandbox.
162. Add Teal source checking and loading path.
173. Add plugin discovery by convention.
184. Add SDK namespace table.
195. Add event bridge.
206. Add harness wiring.
217. Convert built-in commands to Lua plugins.
228. Add plugin reload and rollback.
14- Eval and RPC use the shared provider-independent runtime.
15- Agent, tool, provider, and session events are typed and ordered.
17## Order
191. Add project trust resolution before project executable configuration or package discovery.
202. Add the restricted Lua runtime and trusted source validation boundary.
213. Add convention-based package, module contract, and implementation discovery.
224. Add deterministic module binding, ambiguity diagnostics, and plugin precedence.
235. Add typed SDK namespaces for filesystem, search, tools, commands, providers, UI, VCS, logging, and lifecycle control.
246. Bridge runtime events and plugin results without exposing internal ownership.
257. Load each plugin into a transactional registration set so failure leaves no active residue.
268. Route built-in commands, presentation, themes, keybindings, prompts, and workflows through the same loader.
279. Add atomic reload with rollback and preserved session continuity.
2810. Wire trusted global, project, and explicit plugin sources into the harness.
2430## Interfaces
26| Module | Interface |
27|---|---|
28| smith Lua | sandbox, load, call |
29| smith-harness plugins | discover, load, register, reload |
30| Lua SDK | tools, commands, providers, tui, vcs namespaces |
32- `smith::lua`: source validation, sandbox, typed host calls, and cancellation.
33- `smith-harness::trust`: persisted and one-run project decisions.
34- `smith-harness::plugins`: discovery, binding, registration transactions, reload.
35- Lua SDK: the only plugin path to host effects.
32## Checks
37## Verification
34- User and built-in plugins share loader.
35- Sandbox denies raw io, os, debug.
36- Reload preserves session continuity.
39- Raw operating-system, filesystem, environment, and debug libraries are unavailable.
40- Project plugins and executable configuration cannot run before trust resolution.
41- Non-interactive untrusted project behavior is skipped with a visible diagnostic.
42- Built-in and user plugins use the same sandbox and registration path.
43- Zero, singleton, ambiguous, and explicit module bindings follow the specification.
44- Failed load or reload leaves no subscriptions, tools, providers, or UI registrations behind.
45- Successful reload preserves the active session and swaps one coherent plugin state.
38## Stop points
47## Exit
40- SDK primitive missing for a built-in plugin.
41- Plugin discovery needs manifests.
49The harness operates through the public sandboxed plugin surface with explicit project trust and no privileged built-in path.
51## Stop conditions
53- A built-in requires an effect absent from the public SDK.
54- Trust must execute project code to determine trust.
55- Reload cannot separate candidate registrations from active state.

.system/plans/SMH-PLAN-RELS0001-docs-release-and-hardening/index.md

Modified

+35 / −23 text lines

11---
22id: SMH-PLAN-RELS0001
33type: plan
4title: "Docs Release and Hardening Plan"
4title: "Release Readiness"
55spec: SMH-SPEC-SPEC0001
6phase: SMH-PHASE-RELS0001
76status: draft
87depends_on: [SMH-PLAN-TUIR0001]
98---
11# Docs Release and Hardening Plan
10# Release Readiness
13## Build order
12## Entry
151. Complete providers.json review flow.
162. Add provider conflict reports.
173. Generate help from Teal SDK docs.
184. Add doc tests.
195. Add coverage, audit, arch, pup gates.
206. Add release archive generation.
217. Add final regression matrix.
14- Fullscreen interactive, eval, RPC, replay, provider, tool, and plugin paths work end to end.
15- Public SDK boundaries are stable enough to document.
17## Order
191. Complete provider catalog ingestion, provenance, conflict reporting, cached fallback, and human review flow.
202. Generate Lua SDK help from the authoritative typed declarations and usage descriptions.
213. Verify public Rust, Lua, event, command, and configuration documentation for completeness and drift.
224. Complete architecture, lint, format, test, documentation, audit, coverage, mutation, and benchmark gates through Cargo automation.
235. Harden provider streams, compaction, session recovery, plugin rollback, project trust, terminal restoration, RPC framing, and tool cancellation against recorded edge cases.
246. Build versioned release archives and SHA-256 checksums for required targets.
257. Verify supported target startup, fullscreen restoration, eval, RPC, and replay behavior from release artifacts.
2327## Interfaces
25| Module | Interface |
26|---|---|
27| xtask providers | source fetch, review bundle, diagnostics |
28| xtask docs | extract, test, generate, verify |
29| xtask release | archive, checksum, manifest |
29- `xtask` provider workflow: suggestions, provenance, conflicts, and reviewed publication.
30- `xtask` documentation workflow: extraction, completeness, examples, and drift checks.
31- `xtask` quality workflow: required repository gates.
32- `xtask` release workflow: target artifacts and checksums.
31## Checks
34## Verification
33- Docs are generated from SDK source.
34- Provider suggestions never overwrite current data automatically.
35- Release output matches spec artifacts.
36- Generated provider suggestions never overwrite authoritative values automatically.
37- Runtime catalog refresh remains usable offline and cannot publish stale state.
38- Generated help and exposed SDK agree.
39- Required gates run without secrets or live provider access.
40- Release archives contain the expected binary and verify against published checksums.
41- Supported artifacts restore terminal state and execute provider-free replay.
42- Regression coverage includes every failure class recorded by earlier plans.
37## Stop points
44## Exit
39- Gate needs secret or live network.
40- Docs introduce source of truth outside SDK declarations.
46A documented, reproducible Smith release passes all required gates and operates without maintainer-only knowledge.
48## Stop conditions
50- A required gate depends on live credentials or uncontrolled network state.
51- Documentation creates a second SDK source of truth.
52- A release target cannot satisfy terminal restoration or session safety requirements.

.system/plans/SMH-PLAN-TUIR0001-tui-and-replay/index.md

Modified

+42 / −24 text lines

11---
22id: SMH-PLAN-TUIR0001
33type: plan
4title: "TUI and Replay Plan"
4title: "Fullscreen TUI and Replay"
55spec: SMH-SPEC-SPEC0001
6phase: SMH-PHASE-TUIR0001
76status: draft
87depends_on: [SMH-PLAN-LUAH0001]
98---
11# TUI and Replay Plan
10# Fullscreen TUI and Replay
13## Build order
12## Entry
151. Add terminal backend abstraction.
162. Add normalized input events.
173. Add widget primitives.
184. Add theme validation.
195. Add Lua layout bridge.
206. Add replay engine.
217. Add jj-lib VCS primitives.
228. Add time-travel and VCS plugins.
14- The harness exposes stable runtime events and sandboxed UI registration.
15- Sessions and traces reconstruct provider-free state.
17## Order
191. Add fullscreen terminal entry, restoration, panic-safe shutdown, and signal handling in `smith-cli` and `smith-tui`.
202. Add conservative capability detection, bounded probes, explicit overrides, and plain-terminal fallback.
213. Add normalized keyboard, paste, mouse, resize, and focus events.
224. Add deterministic widget, overlay, theme, and layout primitives in `smith-tui`.
235. Add structured Lua render descriptions and the default fullscreen layout.
246. Add an independently scrollable transcript with sticky-bottom control and explicit jump to latest.
257. Add stable search, selection, link activation, viewport navigation, and focus routing.
268. Add replay reconstruction, seek, speed, range, and comparison over session and trace inputs.
279. Add structured VCS snapshot, diff, restore, undo, redo, and time-travel primitives.
2810. Expose replay and VCS workflows through built-in Lua plugins.
2430## Interfaces
26| Module | Interface |
27|---|---|
28| smith-tui | backend, event, widget, layout, theme |
29| replay | load, seek, compare, render model |
30| smith.vcs | status, diff, op, restore, undo, redo |
32- `smith-tui::terminal`: fullscreen lifecycle and capabilities.
33- `smith-tui::event`: normalized input independent of terminal quirks.
34- `smith-tui::view`: deterministic widgets, viewport, overlays, and themes.
35- Lua UI SDK: product layout and structured presentation.
36- Replay: recorded state to deterministic render model.
37- VCS SDK: validated history queries and mutations.
32## Checks
39## Verification
34- TUI renders from structured state only.
35- Replay of saved session is deterministic.
36- VCS mutation APIs validate inputs.
41- Smith starts directly in fullscreen mode; no regular scrollback mode exists.
42- Terminal state is restored after normal exit, error, abort, and supported signals.
43- Capability failure or timeout degrades without blocking startup.
44- User overrides win over detection.
45- New output does not move a transcript whose user scrolled away from the bottom.
46- Search, selection, links, and pointer actions target stable visible content.
47- Rust widgets do not own product layout.
48- Replay reconstructs the same state without provider credentials.
49- VCS mutations validate targets and remain attributable to session events.
38## Stop points
51## Exit
40- Rust widgets start owning product layout.
41- Replay requires data absent from session entries.
53Users can operate, inspect, replay, and revisit a session through one fullscreen terminal interface.
55## Stop conditions
57- Correct replay needs data absent from durable session or trace contracts.
58- Lua render descriptions require arbitrary terminal writes.
59- Terminal restoration cannot be guaranteed for an owned exit path.

.system/plans/SMH-PLAN-WSPC0001-foundation-and-gates/index.md

Modified

+1 / −2 text lines

33type: plan
44title: "Foundation and Gates Plan"
55spec: SMH-SPEC-SPEC0001
6phase: SMH-PHASE-XCICUUJD
7status: done
6status: approved
87---
109# Foundation and Gates Plan

.system/research/SMH-RESEARCH-FNY87IGJ-pi-0-75-5-to-0-85-1-delta/index.md

Added
new file mode 100644

+99 / −0 text lines

1---
2id: SMH-RESEARCH-FNY87IGJ
3type: research
4title: "Pi 0.75.5 to 0.85.1 Delta"
5---
6
7# Pi 0.75.5 to 0.85.1 Delta
8
9## Scope
11Baseline: Pi coding-agent 0.75.5, previously inspected at repository revision `3eb0027`.
12Current release: 0.85.1, published 2026-09-05 and installed locally.
13Checked 2026-09-09.
14The npm releases span 36 published versions after the baseline.
16This is a release-level architectural delta, not an exhaustive source diff.
18## Facts
20### Providers and models
22- Static generated model data grew into a runtime model and authentication facade named `ModelRuntime`.
23- Provider catalogs can restore persisted data, refresh remotely, publish partial results, reject stale generations, and operate offline.
24- Extensions can register complete providers with authentication, model refresh, filtering, and custom streaming.
25- Model metadata now carries richer compatibility and capability information: verified thinking levels, strict tool support, grammar tools, deferred tools, cache behavior, session affinity, sampling parameters, and provider-specific reasoning controls.
26- Provider and model coverage expanded substantially, including llama.cpp management and additional subscription, gateway, and direct providers.
27- Credential handling gained provider-scoped environments, auth readiness checks, token export, proactive OAuth refresh, and stronger concurrent update behavior.
29### Agent loop and tools
31- Provider retries, timeouts, cancellation, terminal stop reasons, and malformed stream handling became explicit and more consistent.
32- Dynamic tool loading can preserve prompt-cache prefixes on supported providers.
33- Tools can request strict JSON Schema or grammar-constrained sampling when a model advertises support.
34- Tool, compaction, and branch-summary usage is persisted and included in totals.
35- Built-in tool selection is configurable; Windows gained an optional PowerShell tool.
36- Tool and session event surfaces expanded, including settled runs, failed compaction, UI prompt waits, correlated RPC bash output, and terminating blocked tool calls.
38### Sessions and replay
40- The coding-agent's user-facing session format remains append-only JSONL with a version 3 parent-linked tree.
41- Session loading, forking, compaction boundaries, torn-tail handling, atomic publication, large-file reads, concurrent sharing, and in-memory restoration received substantial fixes.
42- Lower-level agent-core introduced a separate version 4 lane-based session architecture with durable operations, global facts, shared sequence numbers, storage abstractions, and repository interfaces.
43- Experimental remote-session work added a transport-neutral client and CBOR protocol.
44- These lower-level additions do not replace the coding-agent's documented JSONL session files.
46### Extensions and security
48- Project trust now gates project-local settings, resources, instructions, and packages.
49- Extension APIs gained trust events, provider hooks, Markdown transformers, entry renderers, autocomplete triggers, more lifecycle events, and richer runtime context.
50- Pi packages and extensions still execute with full system access; isolation remains delegated to containers or custom extensions.
51- Resource installation and update paths gained path validation, private temporary directories, exact-version updates, checksums, staged activation, and deterministic source archives.
53### TUI and operating modes
55- Pi gained an experimental fullscreen TUI with an independently scrollable transcript, sticky editor, search, selection, scrollbars, and runtime mode switching.
56- Markdown rendering gained terminal Mermaid and LaTeX support.
57- Terminal behavior gained capability overrides and many fixes for tmux, Windows, WSL, Kitty graphics, hyperlinks, Unicode width, focus, and keyboard negotiation.
58- RPC gained session tree reads, queue clearing, streaming bash events, usage fixes, and stronger cancellation and framing behavior.
59- The supported product modes remain interactive, print, JSON, RPC, and SDK embedding.
61### Public API changes
63- Pi AI's old global API moved to a compatibility entry point.
64- SDK model configuration moved from separate auth storage and model registry inputs to asynchronous `ModelRuntime`.
65- JSON and RPC message updates changed from cumulative partial messages to deltas.
66- TypeBox was upgraded with deprecated APIs removed.
67- Provider refresh contracts became cancellation-aware and generation-checked.
68- Agent-core replaced legacy repository APIs with newer session storage and repository contracts.
69- The packaged CLI now uses a bundled entry point; supported SDK and stdio RPC entry points remain.
71## Conclusions
73- The old provider snapshot is stale as a design reference because current Pi treats catalogs, credentials, compatibility, and capability discovery as coordinated runtime state.
74- Pi remains useful evidence for provider normalization, but current behavior should be inspected before adopting field names or refresh semantics.
75- Provider churn strengthens the case for a narrow provider-independent stream boundary.
76- Pi's generation-checked catalog publication, cancellation, explicit capability flags, and event-sequence fixes are strong candidates for Smith prototypes.
77- Pi's dual session direction is evidence for separating durable storage from runtime views, not evidence for copying either JSONL or lane APIs.
78- Pi's remote CBOR protocol supports CBOR as an integration format, while its user session persistence still demonstrates the operational value of append-only records and repairable tails.
79- Pi's project trust model addresses untrusted local inputs. Its unrestricted extension model differs fundamentally from Smith's sandboxed Lua boundary.
80- Fullscreen rendering, terminal overrides, compaction timing, and RPC delta assembly identify failure cases Smith should test early rather than features Smith must copy.
82## Unresolved Questions
84- What is the exact field-level change in generated model data between revisions `3eb0027` and `d981de1`?
85- Which `ModelRuntime` catalog and credential contracts are stable public API rather than transitional compatibility layers?
86- Will agent-core's version 4 lane sessions replace coding-agent JSONL sessions or remain a separate harness architecture?
87- Which constrained-sampling capabilities are provider-verified versus inferred from model families?
88- Which fullscreen TUI mechanisms transfer to a Rust renderer without inheriting Pi's component architecture?
90## Sources
92- Pi 0.75.5 package at the previously inspected revision: <https://raw.githubusercontent.com/earendil-works/pi-mono/3eb0027/packages/coding-agent/package.json>
93- Pi 0.75.5 npm release metadata, release git head `83a227aed3f6f7d2f8a63bdd66df0bdb80cd21e2`: <https://www.npmjs.com/package/@earendil-works/pi-coding-agent/v/0.75.5>
94- Pi 0.85.1 npm release metadata, release git head `d981de1229ef899957bbe968bc8dcda02a21f477`: <https://www.npmjs.com/package/@earendil-works/pi-coding-agent/v/0.85.1>
95- Pi coding-agent changelog through 0.85.1: <https://github.com/earendil-works/pi/blob/d981de1229ef899957bbe968bc8dcda02a21f477/packages/coding-agent/CHANGELOG.md>
96- Pi coding-agent README at 0.85.1: <https://github.com/earendil-works/pi/blob/d981de1229ef899957bbe968bc8dcda02a21f477/packages/coding-agent/README.md>
97- Current model configuration: <https://github.com/earendil-works/pi/blob/d981de1229ef899957bbe968bc8dcda02a21f477/packages/coding-agent/docs/models.md>
98- Current SDK documentation: <https://github.com/earendil-works/pi/blob/d981de1229ef899957bbe968bc8dcda02a21f477/packages/coding-agent/docs/sdk.md>
99- Current session format: <https://github.com/earendil-works/pi/blob/d981de1229ef899957bbe968bc8dcda02a21f477/packages/coding-agent/docs/session-format.md>

.system/research/SMH-RESEARCH-RSCH0010-smith-memory-allocation-profile/index.md

Modified

+1 / −1 text lines

77# Smith Memory Allocation Profile Estimate
99**Date:** 2026-05-23
10**Status:** Estimate from `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md` + local Pi JSONL session metadata. No session content quoted.
10**Status:** Estimate from the project specification and local Pi JSONL session metadata. No session content quoted.
1212## Method

.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md

Modified

+274 / −1851 text lines

22id: SMH-SPEC-SPEC0001
33type: spec
44title: "Smith Specification"
5research: [SMH-RESEARCH-FNY87IGJ]
56---
78# Smith Specification
9Smith is a Rust coding-agent TUI. This document describes the desired project
10state. It is the canonical specification for architecture, crates, interfaces,
11configuration, plugins, CLI behavior, build gates, and testing.
13## 1. Product Shape
15Smith is a fast, extensible AI coding agent with:
17- interactive terminal UI,
18- non-interactive eval mode,
19- JSON-RPC stdio mode,
20- Lua plugin system,
21- provider-independent agent loop,
22- deterministic session storage and replay,
23- built-in coding tools implemented through the same plugin API as user tools.
25Core design principles:
27- **Spec before code.** No production Rust exists without a matching spec.
28- **Cargo only.** No Makefile, justfile, package scripts, or root shell scripts.
29- **Stable Rust for product code.** Pinned nightly is allowed only for the
30 required cargo-pup architecture gate.
31- **Deep modules.** Public interfaces are small, honest, and typed.
32- **Sinks, not pipes.** Cross-crate behavior flows through explicit typed
33 requests, streams, events, or hooks. No hidden downstream cascades.
34- **Everything user-visible is a plugin.** Tools, slash commands, themes,
35 keybindings, prompts, layouts, and feature UI are Lua plugins.
36- **LLM is the only untrusted actor.** Local user, local plugins, local files,
37 and Smith itself are trusted.
39## 2. Workspace
41### 2.1 Crates
43```text
44smith/ foundation crate: shared types, StreamFn, AgentTool, config, Lua runtime, errors
45smith-core/ agent loop, sessions, tools, hooks, compaction, cost, trace, replay
46smith-ai/ LLM providers, auth, model registry, provider streams, MuxProvider
47smith-tui/ terminal events, widgets, layout primitives, render loop, themes
48smith-harness/ orchestration, plugin system, SDK, event bridge, built-ins, help
49smith-cli/ binary entry point, clap CLI, session commands, eval/rpc/replay
50xtask/ Cargo-only automation
51```
53### 2.2 Allowed Internal Dependencies
55| Crate | May depend on |
56|-------|---------------|
57| `smith` | none |
58| `smith-core` | `smith` |
59| `smith-ai` | `smith` |
60| `smith-tui` | `smith` |
61| `smith-harness` | `smith`, `smith-core`, `smith-ai`, `smith-tui` |
62| `smith-cli` | `smith`, `smith-harness` |
63| `xtask` | none |
65Forbidden:
67- `smith` depending on any downstream crate.
68- `smith-core`, `smith-ai`, and `smith-tui` depending on each other.
69- `smith-cli` depending directly on `smith-core`, `smith-ai`, or `smith-tui`.
70- Wildcard imports outside tests.
71- `mod.rs` containing anything except module declarations and re-exports.
72- Public API leaking from implementation modules unless explicitly listed here.
74Architecture gates:
76- `cargo run -p xtask -- arch` checks stable Cargo metadata and source
77 invariants not covered by pup.
78- `cargo run -p xtask -- pup` runs `cargo +nightly-2026-01-22 pup`.
79- `cargo run -p xtask -- check` includes `arch` and `pup`.
81Diagnostics (informational, not gates):
83- `cargo run -p xtask -- print-modules` prints crate roots from Cargo metadata
84 plus cargo-pup submodule output.
86### 2.3 Workspace Manifest
88Workspace root:
90```toml
91[workspace]
92members = [
93 "smith",
94 "smith-core",
95 "smith-ai",
96 "smith-tui",
97 "smith-harness",
98 "smith-cli",
99 "xtask",
100]
101resolver = "3"
103[workspace.package]
104edition = "2024"
105version = "0.1.0"
106license = "Apache-2.0"
107```
109Required shared dependencies:
111```toml
112mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }
113mlua-pkg = "0.2"
114serde = { version = "1", features = ["derive"] }
115serde_json = "1"
116tokio = { version = "1", features = ["full"] }
117clap = { version = "4", features = ["derive"] }
118clap_complete = "4"
119crossterm = "0.28"
120ratatui = "0.29"
121ciborium = "0.2"
122thiserror = "2"
123tracing = "0.1"
124tracing-subscriber = { version = "0.3", features = ["env-filter"] }
125reqwest = { version = "0.12", features = ["json", "stream"] }
126futures = "0.3"
127unicode-width = "0.2"
128unicode-segmentation = "1"
129syntastica = { version = "0.6", default-features = false, features = ["runtime-c2rust"] }
130syntastica-parsers = "0.6"
131fuzzy-matcher = "0.3"
132similar = "2"
133ignore = "0.4"
134grep = "0.4"
135grep-regex = "0.1"
136grep-searcher = "0.1"
137gix = { version = "0.83", default-features = false, features = ["blame", "blob-diff", "revision"] }
138url = "2"
139oauth2 = "4"
140insta = "1"
141dirs = "5"
142jsonschema = "0.28"
143uuid = { version = "1", features = ["v7"] }
144assert_cmd = "2"
145assert_fs = "1"
146proptest = "1"
147expectrl = "0.9"
148criterion = { version = "0.5", features = ["async_tokio"] }
149zstd = "0.13"
150sha2 = "0.10"
151zip = { version = "2", default-features = false, features = ["deflate"] }
152tar = "0.4"
153flate2 = "1"
154```
156Vendored language asset:
158```text
159smith/src/lua/tl.lua
160```
162Smith vendors Teal as source, not as an external executable. Plugin checks,
163plugin compilation, and runtime source generation do not shell out to `tl`.
165Release profile:
167```toml
168[profile.release]
169opt-level = 3
170lto = "thin"
171codegen-units = 1
172strip = "symbols"
173panic = "abort"
175[profile.release.package."*"]
176opt-level = 3
177```
179## 3. Toolchain, Lints, and Build Gates
181### 3.1 Rust Toolchain
183`rust-toolchain.toml`:
185```toml
186[toolchain]
187channel = "stable"
188components = ["rustfmt", "clippy"]
189```
191Smith follows latest stable Rust. Do not pin a numeric MSRV unless release
192engineering creates a formal support window.
194Nightly exception:
196- `cargo-pup` uses pinned `nightly-2026-01-22` because it depends on rustc internals.
197- Nightly is used only by the pup gate.
198- Stable remains required for build, test, run, and release.
199- Nightly breakage is fixed by updating pup/toolchain config, not by moving
200 product code to nightly.
201- The pinned nightly is updated only together with a cargo-pup upgrade, never
202 on a calendar basis. The pin date carries no staleness meaning.
203- Pup failure blocks commit, PR, and release.
205### 3.2 Rust Flags
207`.cargo/config.toml`:
209```toml
210[build]
211rustflags = [
212 # Zero warnings policy
213 "-D", "warnings",
215 # Core lint groups
216 "-D", "clippy::all",
217 "-D", "clippy::pedantic",
218 "-W", "clippy::nursery",
219 "-D", "clippy::suspicious",
220 "-D", "clippy::complexity",
221 "-D", "clippy::perf",
222 "-D", "clippy::style",
223 "-D", "clippy::correctness",
225 # Restriction lints — prohibited patterns
226 "-D", "clippy::unwrap_used",
227 "-D", "clippy::expect_used",
228 "-D", "clippy::panic",
229 "-D", "clippy::todo",
230 "-D", "clippy::unimplemented",
231 "-D", "clippy::print_stdout",
232 "-D", "clippy::print_stderr",
234 # Documentation lints
235 "-D", "missing_docs",
236 "-D", "rustdoc::missing_crate_level_docs",
237 "-D", "rustdoc::broken_intra_doc_links",
238 "-W", "rustdoc::invalid_html_tags",
239 "-W", "rustdoc::bare_urls",
240]
242[registries.crates-io]
243protocol = "sparse"
245# Target-scoped: only applies when building on/for Termux ARM64 (vendored
246# LuaJIT needs the compiler-rt builtins). No effect on other platforms.
247[target.aarch64-linux-android]
248rustflags = ["-C", "link-args=-lclang_rt.builtins-aarch64-android"]
249```
251Every library crate has:
253```rust
254#![forbid(unsafe_code)]
255#![warn(missing_docs)]
256```
258`smith-cli` may use unsafe only for OS terminal manipulation when no safe
259alternative exists, wrapped in a tested safe abstraction with `// SAFETY:`.
261### 3.3 Clippy Policy
263- Zero warnings.
264- No `unwrap`, `expect`, `panic`, `todo`, `unimplemented` in shipped library code.
265- Tests may use `unwrap`, `expect`, and `panic`.
266- `smith-cli` and `xtask` may use them only with a justification comment.
267- Prefer `#[expect(lint, reason = "...")]` over `#[allow]`.
269`.clippy.toml`:
271```toml
272cognitive-complexity-threshold = 25
273```
275### 3.4 Audit
277`cargo run -p xtask -- audit` runs:
279```bash
280cargo deny check
281cargo audit --deny warnings
282```
284`deny.toml` allows Apache-2.0, MIT, and Unicode-DFS-2016. Duplicate versions are
285warned unless explicitly accepted.
287### 3.5 cargo-pup
289Root `pup.ron` exists and is required. Cargo-pup is the pinned-nightly source
290architecture lint gate. `xtask arch` remains the stable Cargo metadata gate.
292Initial pup rules enforce:
294- hygienic `mod.rs`,
295- no wildcard imports,
296- `smith-core` imports no `smith-ai`, `smith-tui`, `smith-harness`, `smith-cli`,
297- `smith-ai` imports no `smith-core`, `smith-tui`, `smith-harness`, `smith-cli`,
298- `smith-tui` imports no `smith-core`, `smith-ai`, `smith-harness`, `smith-cli`.
300Crate-boundary module match patterns must include the crate root. Use
301`^crate($|::.*)`, not only `^crate::.*`. Cargo-pup sees root-owned items in
302`lib.rs`/`main.rs` under the crate name itself.
304Required boundary patterns:
306```ron
307matches: Module("^smith_core($|::.*)")
308matches: Module("^smith_ai($|::.*)")
309matches: Module("^smith_tui($|::.*)")
310```
312`cargo pup print-modules` is not a complete module inventory. It can omit crate
313roots and can emit synthetic `unknown_crate` for crates with no child `mod`
314items. Developer-facing module inventory uses `cargo run -p xtask -- print-modules`,
315which prefixes crate roots from stable Cargo metadata and then prints
316cargo-pup-discovered submodules.
318Required setup:
320```bash
321rustup component add --toolchain nightly-2026-01-22 rust-src rustc-dev llvm-tools-preview
322cargo +nightly-2026-01-22 install cargo_pup
323```
325Gate:
327```bash
328cargo +nightly-2026-01-22 pup
329```
331## 4. Runtime Directories and Files
333Smith uses XDG-style directories via `dirs`.
335| Platform | Config | Data | Cache |
336|----------|--------|------|-------|
337| Linux | `~/.config/smith/` | `~/.local/share/smith/` | `~/.cache/smith/` |
338| macOS | `~/Library/Application Support/smith/` | same | `~/Library/Caches/smith/` |
339| Windows | `%APPDATA%\smith\` | `%LOCALAPPDATA%\smith\` | `%LOCALAPPDATA%\smith\cache\` |
341Data layout:
343```text
344data_dir/smith/
345 sessions/
346 {session-id}.session
347 {session-id}.trace
348 plugins/
349 data/
350 vcs/
351 {project-hash}/
352 jj-state/
354cache_dir/smith/
355 bytecode/
357config_dir/smith/
358 config.lua
359```
361Session files are plaintext length-prefixed CBOR sequences. Trace files are
362compressed deterministic replay logs. Secrets in sessions are plaintext after
363local registration; the security boundary is the LLM, not the local user.
365## 5. Shared Crate: `smith`
367`smith` owns shared types and utilities. It has no business logic and no
368downstream dependencies.
370Exports:
372```rust
373pub mod types;
374pub mod stream;
375pub mod tool;
376pub mod lua;
377pub mod config;
378pub mod error;
379pub mod mux;
381pub use types::*;
382pub use stream::StreamFn;
383pub use tool::{AgentTool, AgentToolResult, AgentToolUpdate, ToolExecutionMode};
384pub use lua::LuaRuntime;
385pub use config::Config;
386pub use error::SmithError;
387pub use mux::{ModelAlias, ModelGroup, ProviderBucket, ModelResolver, ResolvedModel, ResolveError};
388```
390`smith` must not re-export `smith-core` types. Domain types are imported from
391their owning crates.
393### 5.1 IDs and Messages
395Required shared types:
397- `EntryId(String)` — UUID v7, time-sortable.
398- `SessionId(String)`.
399- `SecretId(String)`.
400- `VcsOpId(String)`.
401- `Role`: `System`, `User`, `Assistant`, `Tool`, `ToolResult`, `Custom`, `BashExecution`.
402- `ContentBlock`:
403 - `Text(String)`,
404 - `Image { data, media_type }`,
405 - `ToolCall { id, name, arguments }`,
406 - `ToolResult { id, result, is_error }`,
407 - `Thinking { content }`.
408- `Message { role, content }`.
410### 5.2 Provider Types
412- `ProviderUsage` tracks input, output, cache read/write, and total tokens.
413- `StopReason`: `EndTurn`, `ToolUse`, `OverMaxTokens`, `Aborted`, `StopSequence`, `Error`.
414- `ThinkingLevel`: `Off`, `Minimal`, `Low`, `Medium`, `High`, `XHigh`.
415- `ProviderEvent`:
416 - `TextDelta`,
417 - `ToolCall`,
418 - `ThinkingDelta`,
419 - `Done`,
420 - `Error`.
421- `ProviderRequest` contains messages, system prompt, model/provider IDs, tool
422 definitions, thinking level, token limit, and stop sequences.
424### 5.3 Tool Types
426- `ToolDefinitionSpec` is serializable metadata for LLM function calling and
427 plugin metadata.
428- `ToolDefinition` is runtime definition used by providers and the agent loop.
429- `AgentTool` is async and `Send + Sync`.
430- `ToolExecutionMode`: sequential or parallel according to tool metadata.
431- `AgentToolResult` returns content blocks, error flag, and optional updates.
432- Tool arguments are JSON and validated with `jsonschema`.
434### 5.4 StreamFn
436`StreamFn` is the provider abstraction consumed by `smith-core`:
438- input: `ProviderRequest`,
439- output: async stream of `ProviderEvent`,
440- no dependency on `smith-ai`.
442This permits `smith-core` and `smith-ai` to build independently.
444### 5.5 Lua Runtime
446`LuaRuntime` wraps mlua + LuaJIT + `mlua-pkg` custom require. Plugin source is
447fronted by vendored Teal (`tl.lua`): Smith compiles `.tl` and `.lua` plugin
448source to Lua before loading it into the runtime.
450Allowed standard libraries:
452- `string`,
453- `table`,
454- `math`,
455- `coroutine`,
456- `utf8`,
457- `package` with custom searchers.
459Removed globals:
461- `io`,
462- `os`,
463- `debug`,
464- `getfenv`,
465- `setfenv`.
467Smith host APIs are exposed through `require("smith")`.
469Compiler and bytecode cache:
471- Teal runs in a separate trusted compiler Lua state.
472- Generated Lua runs in the restricted plugin runtime state.
473- Smith compiles generated Lua to bytecode on first load.
474- Cache key includes source hash, Teal version, compile mode, and generated Lua hash.
475- Smith never loads bytecode it did not compile.
477### 5.6 Config
479Lua is the configuration language. Rust defines schemas; Lua supplies values.
481Cascade order, later overrides earlier:
4831. Rust type defaults/schema,
4842. built-in Lua defaults,
4853. plugin contributions,
4864. user config at `config_dir/smith/config.lua`,
4875. CLI flags.
489Invalid values are rejected with clear errors. Unknown keys warn or fail
490according to the schema context.
492Example:
494```lua
495return {
496 theme = "catppuccin",
497 keybindings = {
498 ["ctrl+l"] = "cycle_model",
499 ["ctrl+c"] = "abort",
500 },
501 tools = { "read", "write", "edit", "bash" },
502 model = "anthropic/claude-sonnet-4",
503 modules = {
504 ["smith.subagents"] = "alice.subagents:smith.subagents",
505 },
506}
507```
509### 5.7 Models, Aliases, Groups, Buckets
511`ModelMetadata` includes:
513- provider/model IDs,
514- context window,
515- max output tokens,
516- pricing,
517- capabilities: thinking, vision, tool use, streaming.
519`ModelResolver` is pure. It resolves:
521```text
522requested name → alias → group → bucket/account → provider/model metadata
523```
525Rules:
527- no I/O during resolution,
528- cycles detected at config load and reported with full path,
529- DAGs allowed,
530- `ResolvedModel` carries metadata needed by `smith-core`.
532Failover:
534- `FailoverStrategy`: ordered or round-robin.
535- `BucketStrategy`: account rotation policy.
536- Rate limits fail over immediately.
537- Non-rate-limit transient errors retry before failover.
539### 5.8 Errors
541`SmithError` is the shared recoverable error enum. It wraps provider, auth, tool,
542config, Lua, I/O, CBOR, and resolver errors.
544Internal impossible states use assertions during development but shipped library
545code must not panic for external failures.
547## 6. Core Crate: `smith-core`
549`smith-core` owns pure business logic: agent loop, sessions, tools, hooks,
550secret proxy, compaction, cost, trace, and replay. It depends only on `smith`.
552Exports:
554```rust
555pub mod agent;
556pub mod session;
557pub mod session_format;
558pub mod tools;
559pub mod events;
560pub mod secret_proxy;
561pub mod system_prompt;
562pub mod compaction;
563pub mod cost;
564pub mod trace;
565pub mod replay;
566```
568### 6.1 Agent Loop
570The agent loop:
572- receives an `AgentContext`, `AgentLoopConfig`, `StreamFn`, tool registry, and event sender,
573- streams model responses,
574- emits `AgentEvent`,
575- executes tool calls,
576- handles steering/follow-up messages,
577- repeats until stop criteria.
579The loop uses two nested loops:
581- outer loop: turns and follow-up messages,
582- inner loop: provider streaming, tool calls, steering.
584It never imports provider implementations. Providers are `StreamFn` only.
586Important config:
588- `max_tool_calls_per_turn` default `100`,
589- `max_turns_per_user_message` default `50`,
590- tool execution mode: sequential or parallel,
591- `model_metadata` for context/cost,
592- hook callbacks.
594Abort:
596- Ctrl+C or programmatic abort sets an abort signal.
597- Streaming and tool execution check it and bail cleanly.
598- Every state is interruptible.
600### 6.2 Agent Events
602`AgentEvent` is source of truth for agent behavior:
604- `AgentStart`, `AgentEnd`,
605- `TurnStart`, `TurnEnd`,
606- `MessageStart`, `MessageUpdate`, `MessageEnd`,
607- `ToolExecutionStart`, `ToolExecutionUpdate`, `ToolExecutionEnd`,
608- `TextDelta`, `ThinkingDelta`,
609- `Error`.
611`AgentEvent::to_session_entry(timestamp)` returns a `SessionEntry` only for
612conversation-relevant completed events.
614### 6.3 Engine Events
616`EngineEvent` wraps `AgentEvent` and adds harness-level events:
618- session lifecycle,
619- steering/follow-up,
620- UI state changes,
621- provider/model changes,
622- errors and shutdown.
624`EngineEvent` is consumed by `smith-harness` and `smith-tui`.
626### 6.4 Hooks
628Core hook result types:
630- `BeforeToolCallResult`: allow, block, replace args, cancel.
631- `AfterToolCallResult`: keep, replace result, retry, cancel.
632- `ShouldStopAfterTurn`: stop or continue.
633- `PrepareNextTurn`: mutate queued prompts/messages.
634- `TransformContext`: mutate LLM context before provider request.
636`smith-harness` translates Lua plugin event returns into these core hook results.
638### 6.5 Session Model
640`Session` contains:
642- `SessionId`,
643- optional name,
644- cwd,
645- entries,
646- current leaf,
647- created/updated timestamps.
649Sessions are branching trees. Branches are immutable once created. `/tree` and
650history/time-travel features are Lua plugins over this core state.
652`SessionEntry` variants include:
654- user message,
655- assistant message,
656- tool call,
657- tool result,
658- system prompt snapshot,
659- compaction summary,
660- secret registration,
661- model/provider change,
662- VCS operation,
663- metadata entries needed for migration and replay.
665Every entry has a stable `EntryId`, optional parent, and timestamp.
667### 6.6 Session Format
669Session files are length-prefixed CBOR frame sequences:
671```text
672u32 BE len | CBOR SessionFrame bytes | u32 BE len | CBOR SessionFrame bytes | ...
673```
675`len` is the byte length of the following CBOR frame payload, not including the
676length prefix. v1 frame payloads are self-describing envelopes:
678```text
679SessionFrame {
680 kind: string,
681 data: CBOR value,
682}
683```
685`kind` names the session-entry variant. `data` contains the variant payload.
686Known kinds are decoded into typed `SessionEntry` values after envelope decode.
687Unknown kinds are retained as opaque raw frame payload bytes.
689Frame size:
691- default max frame payload length: 64 MiB,
692- readers check the length prefix before allocating or decoding,
693- frames larger than the configured limit are reported and stop parsing.
695Recovery classes:
697- Complete known frame: decode envelope, decode typed payload, append entry.
698- Complete unknown frame: decode envelope, store the exact raw frame payload bytes
699 and report unknown kind. Unknown frames are written back byte-for-byte when
700 round-tripping so newer entries are not destroyed by older Smith versions.
701- Corrupt payload: if `len` is intact and bounded but CBOR envelope decode fails,
702 skip exactly `len` bytes, warn, and continue at the next frame.
703- Malformed known entry: if envelope decode succeeds but typed payload validation
704 fails, treat the frame as corrupt, skip it, warn, and continue at the next
705 frame.
706- Truncated length prefix: stop parsing and keep prior entries.
707- Truncated frame payload: stop parsing and keep prior entries.
708- Oversized frame length: stop parsing and keep prior entries.
709- Plausible but wrong length prefixes cannot be reliably detected; readers do no
710 byte resynchronization scan.
712Properties:
714- crash recovery: truncated tail stops parsing without losing fully decoded prior
715 entries,
716- corrupt entry recovery is bounded to intact length prefixes,
717- unknown future entries are preserved when round-tripping via raw frame bytes,
718- `smith session dump` outputs JSONL,
719- session discovery is keyed by canonical `{session-id}.session` filenames.
721### 6.7 Secret Proxy
723The secret proxy prevents LLM exposure of secrets:
725- scans user messages and tool outputs for secrets,
726- replaces secrets with `smith:sec:N`,
727- stores plaintext translation entries locally,
728- rehydrates tool arguments before local execution,
729- rebuilds table on resume by scanning session entries backward.
731Secrets are local plaintext. The protection target is the remote LLM.
733### 6.8 System Prompt
735`SystemPromptBuilder` composes:
737- base identity,
738- active model/tool capabilities,
739- plugin prompt contributions,
740- project/context facts,
741- safety and tool-use instructions,
742- user overrides.
744Plugins may transform prompts through typed hooks. No hidden global prompt mutation.
746### 6.9 Compaction and Cost
748Compaction:
750- uses `AgentLoopConfig.model_metadata.context_window`,
751- starts with old non-essential/redundant entries,
752- runs summarization when trimming is insufficient,
753- repeats until context fits or configured iteration limit reached,
754- preserves secret registrations and necessary lineage.
756Token estimator:
758- v1 heuristic: chars/4,
759- exact tokenizer is not required in core.
761Cost tracking:
763- consumes `ProviderUsage`,
764- multiplies by `ModelMetadata.cost`,
765- tracks input/output/cache tokens and running total.
767### 6.10 Tool Registry
769`ToolRegistry` stores `Arc<dyn AgentTool>` by name.
771Rules:
773- duplicate registration follows harness plugin precedence,
774- arguments are JSON-schema validated,
775- final tool errors become tool-result content for the LLM,
776- transient failures may retry according to tool policy.
10## Intent
778### 6.11 Trace and Replay
780Trace files capture deterministic replay data:
782- file header with magic/version/session ID,
783- compressed entries via zstd,
784- provider requests/events,
785- tool calls/results,
786- TUI events as opaque JSON,
787- plugin events as opaque JSON,
788- VCS operation IDs,
789- agent state snapshots.
791Trace guarantees:
793- preserves event order,
794- enough data to reconstruct session state,
795- compare mode can re-execute tools and diff outputs,
796- replay can run real-time, speed multiplier, or max speed.
798Replay modes:
800- visual replay,
801- max-speed reconstruction,
802- compare old vs new tool outputs,
803- fast-forward to turn range.
805## 7. AI Crate: `smith-ai`
807`smith-ai` owns concrete provider integrations. It depends only on `smith`.
809### 7.1 Provider Trait
811```rust
812pub trait Provider: Send + Sync {
813 fn id(&self) -> &str;
814 fn name(&self) -> &str;
815 fn validate_auth(&self) -> Result<(), ProviderError>;
816 fn stream(&self, request: ProviderRequest) -> Pin<Box<dyn Stream<Item = ProviderEvent> + Send>>;
817}
818```
820`provider_to_stream_fn(Arc<dyn Provider>)` returns the `StreamFn` consumed by
821`smith-core`.
823### 7.2 Provider Implementations
825Required providers:
827- Anthropic,
828- OpenAI,
829- Google,
830- OpenAI-compatible local/remote endpoints.
832MiniMax Token Plan uses the OpenAI-compatible adapter with bearer keys using the `sk-cp-` prefix, endpoint `https://api.minimax.io/v1/chat/completions`, and models `MiniMax-M2.7` and `MiniMax-M2.7-highspeed`.
12Smith is a fast Rust coding-agent TUI with Lua-owned customization.
13It provides one provider-independent agent runtime across interactive, eval, JSON-RPC, and replay modes.
834Provider implementations normalize vendor wire formats into `ProviderEvent`.
15## Scope
836Quirks handled at provider boundary:
17Smith includes:
838- streaming vs non-streaming APIs,
839- partial tool-call argument chunks,
840- thinking/reasoning fields,
841- provider-specific stop reasons,
842- cache usage fields,
843- model capability flags.
19- terminal interaction,
20- non-interactive evaluation,
21- JSON-RPC over standard input and output,
22- deterministic CBOR sessions and replay,
23- provider and model selection,
24- built-in coding tools,
25- sandboxed Lua plugins,
26- VCS-backed history and recovery,
27- generated SDK help.
845### 7.3 Model Registry
29Smith does not require a live provider for session storage, replay, tool execution, or interface testing.
847`providers.json` is bundled in `smith-ai/src/providers.json`. That checked-in
848file is authoritative at runtime.
31## Product boundaries
850Runtime overrides come only from the Lua plugin API: plugins may add providers
851and models or adjust fields through `smith.providers.*`. There is no user-level
852`providers.json` override file.
33- Rust owns safety, persistence, concurrency, terminal primitives, provider adapters, and bounded tool effects.
34- Lua owns user extension, product layout, prompts, themes, keybindings, commands, and tool presentation.
35- Built-in and user-visible extension behavior use the same plugin contracts.
36- Provider details do not enter the agent, session, tool, plugin, or interface contracts.
37- Interface modes share one runtime behavior rather than reimplementing the agent loop.
854`fetch-providers` is a bootstrap and maintenance aid, not an automatic truth
855source:
39## Agent behavior
857```bash
858cargo run -p xtask -- fetch-providers
859```
41The agent:
861Data source priority for generated suggestions:
43- accepts user, steering, and follow-up input,
44- streams normalized assistant output,
45- validates and executes tool calls,
46- records completed conversation-relevant events,
47- continues until an explicit stop condition,
48- exposes ordered lifecycle events,
49- remains abortable during provider, tool, compaction, and plugin work.
8631. pi.dev model data,
8642. catwalk provider configs,
8653. later shared provider repositories after review.
51A provider stream has explicit terminal success, tool-use, limit, abort, and error outcomes.
52Malformed or incomplete provider streams fail explicitly.
53A terminal event is emitted once.
867`fetch-providers` emits a review bundle, not an in-place replacement:
55Tool calls and results remain correctly paired and ordered.
56Injected messages never split a tool call from its result.
57Changes to active tools apply only between provider requests.
869- `providers.generated.json`: proposed full provider file,
870- `providers.patch.json`: structured additions and field fills,
871- `providers.review.json`: conflicts and source provenance.
59## Providers, models, and authentication
873Merge rule:
61Smith supports Anthropic, OpenAI, Google, and OpenAI-compatible endpoints.
62Additional providers can be supplied through the plugin API.
875- merge identity is `(provider_id, model_id)`, with provider-only fields keyed by
876 `provider_id`,
877- current `providers.json` wins every current-vs-suggestion conflict,
878- current-vs-suggestion conflicts are written to `providers.review.json` and make
879 strict/CI fetch checks fail until reviewed,
880- pi.dev is the primary suggestion source,
881- catwalk fills only missing normalized fields after pi.dev,
882- pi.dev-vs-catwalk conflicts are written as source conflicts; source conflicts
883 do not overwrite pi.dev values,
884- new providers/models from either source may be suggested,
885- unknown fields already present in current `providers.json` are preserved for
886 forward compatibility but ignored by v1,
887- unknown fields from source registries are ignored unless Smith maps them into
888 the normalized schema or an explicit `x_source_*` field during review,
889- `replace_models` is allowed only in checked-in `providers.json` as a human
890 review annotation; generated sources must not apply full provider replacement
891 automatically.
64Every provider normalizes:
893`providers.review.json` entries must include:
66- text and thinking deltas,
67- tool calls,
68- stop reasons,
69- usage and cache accounting,
70- provider errors,
71- cancellation.
895- JSON pointer path,
896- kind: add provider, add model, fill field, current conflict, source conflict,
897- kept value and source when applicable,
898- suggested or discarded value and source when applicable.
73### Model capabilities
900Provider config correctness cannot be fully automated because Smith does not have
901all provider accounts, subscriptions, API keys, regional access, or provider
902quirk coverage. Generated changes require review before commit. After the
903provider format stabilizes, Smith may use a Pi agent to open provider-data PRs
904from `fetch-providers` review bundles.
75Model metadata states supported behavior explicitly, including:
906### 7.4 Auth
77- context and output limits,
78- text and image input,
79- tool use,
80- thinking levels,
81- strict or grammar-constrained tool input,
82- cache behavior,
83- pricing.
908Auth resolver sources:
85Provider requests use only advertised capabilities.
86Unsupported optional behavior degrades predictably or fails before dispatch.
87Family-name inference cannot override explicit provider evidence.
910- environment variables,
911- `~/.smith/auth.json`,
912- plaintext Lua config values when explicitly supplied.
89### Catalogs
914No OS keychain. No encryption.
91Smith ships a reviewed offline model catalog.
92Human configuration and checked-in data remain authoritative.
916Auth errors fail fast before first provider stream.
94Provider or plugin catalogs may refresh at runtime when enabled.
95Refresh behavior must:
918OAuth module supports mocked OAuth flow in tests and provider-specific OAuth where
919configured.
97- remain cancellable,
98- preserve a usable cached or bundled snapshot,
99- prevent stale work from replacing newer state,
100- publish coherent snapshots,
101- expose source provenance and conflicts,
102- never silently overwrite human configuration.
921### 7.5 MuxProvider
104Catalog freshness cannot block normal offline startup.
923`MuxProvider` wraps multiple providers/accounts for resolved groups and buckets.
106### Authentication
925Behavior:
108Credentials may come from environment variables, Smith auth data, explicit configuration, or provider plugins.
109Authentication is resolved before dispatch and can be checked independently of a model request.
110Concurrent credential changes cannot lose unrelated provider state.
111Expired renewable credentials refresh before use.
112Credential values never enter remote model context, logs, diagnostics, or replay output.
927- `RateLimit`: immediate failover,
928- `AuthFailed`, `Network`, `ServerError`: retry configured count then failover,
929- `InvalidRequest`, `ModelNotFound`: no retry, immediate failover,
930- `Timeout`: retry once then failover,
931- exhausted providers emit `ProviderEvent::Error`.
114### Failover
933## 8. TUI Crate: `smith-tui`
116Model aliases, groups, and account buckets resolve deterministically.
117Resolution performs no network access.
118Cycles and ambiguity fail with complete diagnostics.
935`smith-tui` owns terminal primitives, normalized events, widgets, themes, and
936render loop. It depends only on `smith`.
120Rate limits may fail over immediately.
121Transient transport failures follow bounded retry policy before failover.
122Invalid requests and unavailable models do not retry indefinitely.
938### 8.1 Backend
124## Sessions
940Rendering uses:
126A session is an append-only branching history with stable IDs, parent links, timestamps, and a selected leaf.
127Entries represent messages, tool activity, model changes, compaction, secret registration, VCS operations, and replay-relevant metadata.
942- `ratatui` for layout/widgets/TestBackend snapshots,
943- `crossterm` for terminal I/O, event polling, raw mode, alternate screen,
944 Kitty keyboard protocol flags, and terminal capability probes.
129Session persistence uses length-prefixed CBOR frames.
130It guarantees:
946### 8.2 Events
132- deterministic encoding,
133- bounded frame allocation,
134- recovery of all complete frames before a truncated tail,
135- bounded skipping of corrupt frames with intact lengths,
136- preservation of unknown future frames during round trips,
137- explicit failure for unrecoverable framing ambiguity,
138- atomic publication of newly created, forked, or repaired sessions,
139- serialization of concurrent writers.
948`TuiEvent` normalizes crossterm events:
141Resuming, cloning, forking, and branch navigation preserve the selected history and compaction boundary.
142Externally managed entries can initialize an in-memory session without changing their order or IDs.
950- keyboard,
951- mouse,
952- resize,
953- focus gained/lost,
954- paste.
144Session dumps use JSONL for inspection and interchange.
145JSONL is not the authoritative persistence format.
956Keyboard events include normalized key code, modifiers, and press/repeat/release
957kind. Mouse events include button, scroll, position, and modifiers.
147## Compaction, cost, and secrets
959### 8.3 Terminal Capabilities
149Compaction reduces provider context without deleting durable history.
150It preserves required lineage, recent context, tool ordering, secret registrations, and the active branch boundary.
151It never persists a summary known to be truncated or incomplete.
152Queued input resumes after compaction according to its original delivery mode.
961`TerminalCapabilities` records:
154Cost accounting includes provider responses, tool-reported usage, compaction, and branch summaries when usage is available.
155Unknown usage remains unknown rather than becoming zero.
963- truecolor,
964- undercurl,
965- Kitty keyboard protocol,
966- bracketed paste,
967- focus events,
968- mouse support,
969- Kitty graphics / sixel availability.
157The secret proxy replaces registered secrets before remote dispatch and restores them only for authorized local effects.
158Secrets remain local plaintext under the user's filesystem permissions.
971No terminfo database. Probe directly. Unsupported optional features degrade to
972plain text without user-facing error.
160## Tools
974### 8.4 Component Trait
162Built-in tools are:
976Components render into ratatui buffers and handle normalized `TuiEvent`.
164- `read`,
165- `write`,
166- `edit`,
167- `bash`,
168- `find`,
169- `grep`,
170- `ls`.
978Rules:
172All tools use provider-neutral definitions, bounded output, explicit errors, cancellation, and recorded lifecycle events.
173Provider-specific constrained sampling is an optional transport capability, not a separate tool contract.
980- rendering is deterministic,
981- focus handling is explicit,
982- event handlers return consumed/not-consumed,
983- cached state has explicit invalidation.
175### File effects
985### 8.5 TuiApp
177- Read supports bounded line windows and identifies unsupported binary content.
178- Write creates parent directories when permitted and replaces files atomically.
179- Edit applies exact replacements, rejects missing or ambiguous matches, detects stale input, and writes atomically.
180- Find, grep, and list return deterministic bounded results and respect configured ignore behavior.
181- File tools resolve paths against the invocation context, not process-global startup state.
987`TuiApp` lifecycle:
183### Process effects
989```text
990new → enter terminal → run event/render loop → shutdown → restore terminal
991```
185Bash executes in an explicit working directory with bounded output, timeout, exit status, and cancellation.
186Process termination includes descendants started by the invocation where the platform permits it.
187Shell output arriving immediately after process exit is not silently truncated.
993The render loop ticks at 16ms. Event polling runs on a blocking thread and sends
994normalized events over channels. `TuiApp` is created/driven by `smith-harness`.
189Tool mutation is recorded only when the effect succeeds.
190A failed recording step cannot leave a successful mutation presented as unrecorded success.
996States:
192Compatibility adapters may translate external tool names only when semantics are equivalent.
193Fuzzy edits, freeform patches, terminal sessions, plans, subagents, permissions, MCP, and semantic search remain plugin behavior.
998- `Idle`,
999- `Thinking`,
1000- `ToolRunning`,
1001- `ToolResult`,
1002- `Error`,
1003- `Exiting`.
195## Replay and VCS
1005Every state is interruptible.
197Replay reconstructs runtime state from recorded events without a provider.
198It supports real-time playback, accelerated playback, turn ranges, and comparison of re-executed tool effects.
199Replay preserves source event order and reports divergence explicitly.
1007### 8.6 Widgets
201Smith provides VCS-backed snapshots, diffs, undo, redo, restore, and time travel through one structured SDK boundary.
202Normal operation does not require an external VCS executable.
203Mutating VCS operations validate their target and remain attributable to session events.
1009Required widget set includes:
205## Plugins and configuration
1011- text,
1012- truncated text,
1013- spacer,
1014- markdown,
1015- message list,
1016- input area,
1017- status bar,
1018- hint bar,
1019- spinner,
1020- progress/cost/context indicators,
1021- tool call/result views,
1022- diff view,
1023- syntax-highlighted code,
1024- fuzzy list,
1025- tabs,
1026- scrollable,
1027- overlay,
1028- border layout panels.
207Lua plugins run in a restricted runtime without direct operating-system, filesystem, environment, or debug libraries.
208Host effects are available only through typed Smith SDK functions.
209Built-in plugins have no privileged effect path.
1030Syntax highlighting uses `syntastica`. Diffs use `similar`. Fuzzy matching uses
1031`fuzzy-matcher`.
211Plugins may contribute:
1033### 8.7 Layout
1035Rust provides primitives; Lua defines layout.
1037Primitives:
1039- column,
1040- row,
1041- box,
1042- expanded,
1043- scrollable,
1044- overlay,
1045- spacer,
1046- tabs,
1047- split.
1049One predefined border layout exists: center + north/east/south/west panels.
1050Panels are invisible when empty. Default layout is a Lua plugin.
1052Overlays support modal and non-modal use with top, bottom, left, right, center, and cursor anchors.
1054### 8.8 Theme
1056Themes are Lua tables validated by Rust schemas.
1058Theme values cover status bar, messages, assistant content, tool call/result,
1059errors, input, borders, selections, diffs, syntax groups, and accents.
1061### 8.9 Virtual Scroll
1063Message history uses virtual scrolling. `sticky_bottom` defaults true and turns
1064false when user scrolls up. New content does not move viewport until user returns
1065to bottom or submits input.
1067### 8.10 Tool Rendering
1069Tools may register `renderCall` and `renderResult` Lua renderers. TUI receives
1070structured render instructions from harness, not arbitrary terminal writes.
1072## 9. Harness Crate: `smith-harness`
1074`smith-harness` wires all subsystems and owns plugin management.
1076Responsibilities:
1078- load config,
1079- load model registry and auth,
1080- resolve active model,
1081- create provider and `StreamFn`,
1082- create agent,
1083- load plugins,
1084- expose SDK to Lua,
1085- bridge core events to plugin events,
1086- translate plugin returns into core hooks,
1087- coordinate TUI, eval, and RPC modes.
1089### 9.1 Harness Structure
1091`Harness` contains:
1093- `Agent`,
1094- provider map,
1095- `ModelRegistry`,
1096- `ModelResolver`,
1097- auth resolver,
1098- `PluginManager`,
1099- optional `TuiApp`,
1100- active provider,
1101- active model.
1103### 9.2 Plugin Identity and Convention Discovery
1105Plugins do not have manifests in v1. Smith discovers plugin shape from paths and
1106validates behavior from Teal types plus runtime registration tables.
1108A plugin package is a directory under one of the plugin roots. Package path
1109segments map to a dotted package ID using normal Lua module naming rules:
1111```text
1112data_dir/smith/plugins/<package-path>/
1113.smith/plugins/<package-path>/
1114```
1116`<package-id>` uses lowercase ASCII letters, numbers, `_`, `-`, and `.`. Exact
1117`smith` and the `smith.` prefix are reserved for built-in packages. The package
1118filesystem path is the package ID with `.` replaced by `/`.
1120Package examples:
1122```text
1123plugins/alice/subagents/ → alice.subagents
1124git:bob/plugin → bob.plugin
1125https://github.com/bob/plugin.git → bob.plugin
1126plugins/smith/builtins/ → reserved built-in package
1127```
1129Smith recognizes these files by convention:
1131```text
1132init.lua standalone plugin entry
1133init.tl standalone plugin entry
1134<module-path>/mod.tl module contract
1135<module-path>/init.tl module implementation
1136```
1138`<module-path>` maps to a module ID by replacing `/` with `.`:
1140```text
1141smith/subagents/mod.tl → smith.subagents
1142smith/subagents/init.tl → implementation of smith.subagents
1143```
1145Implementation IDs are derived from package ID plus module ID:
1147```text
1148plugins/alice/subagents/smith/subagents/init.tl
1149 → alice.subagents:smith.subagents
1150```
1152No `smith-plugin.lua`, `package.json`, descriptor table, or metadata file is read
1153for discovery. Package metadata is not part of v1.
1155### 9.3 Plugin API Compatibility
1157Smith plugin API generation is `1` for all v1 plugins. There is no per-plugin API
1158selection in v1 because there are no manifests. Breaking plugin API generations
1159are deferred until Smith introduces a versioned package metadata format.
1161### 9.4 Plugin Loading
1163Smith vendors Teal (`tl.lua`) and uses it as the single plugin source frontend.
1164The Teal compiler runs in a trusted compiler Lua state. Plugin code runs in a
1165separate restricted LuaJIT runtime state.
1167Source handling:
1169- `.tl` files are checked and compiled with Teal. Syntax or type errors block
1170 loading that file.
1171- `.lua` files are checked and generated with Teal Lua mode. Syntax or generation
1172 errors block loading. Type and unknown-value diagnostics are emitted as
1173 non-blocking warnings.
1174- Generated Lua is loaded into the restricted plugin runtime. Original source is
1175 never executed directly.
1177Standalone plugin entries are `init.lua` or `init.tl` at the package root. They
1178return registration tables/factories. Module implementation files return module
1179implementation tables.
1181Plugin bridge phases:
11831. Discover package directories and convention paths.
11842. Teal-check module contracts and implementation files.
11853. Compile source to Lua in the compiler state.
11864. Load generated Lua in the restricted runtime state.
11875. Collect standalone registration tables/factories.
11886. Register module contracts and implementation candidates.
11897. Apply user module bindings and singleton auto-bindings.
11908. Materialize Rust-side handles.
11919. Register into tool/event/command/provider/TUI registries.
1193No Rust trait-object plugin API exists. Canonical plugin loading is the Teal/Lua
1194registration pipeline above.
1196### 9.5 Plugin Install and Uninstall
1198Supported install sources for v1:
1200- local directory path,
1201- git URL.
1203No central registry exists in v1.
1205`smith install <path-or-git-url>`:
1207- resolves the source,
1208- derives package ID from the source path by converting path separators to `.`,
1209 or from `<owner>.<repo>` for git URLs,
1210- validates package ID syntax and reserved namespace,
1211- copies or clones into `data_dir/smith/plugins/<package-path>/`,
1212- refuses duplicates unless `--force`,
1213- Teal-checks discovered plugin files,
1214- does not execute generated plugin code during install.
1216Git URL installs use Smith's internal git implementation boundary. The preferred
1217implementation is `gix` if its required clone/fetch feature set stays bounded;
1218otherwise the behavior remains the same behind the install boundary.
1220`smith uninstall <package-id>`:
1222- removes installed plugin code,
1223- keeps plugin data by default,
1224- supports `--purge-data` to remove `data_dir/smith/data/<package-path>/`,
1225- never removes project plugins.
1227### 9.6 Teal Module and Implementation System
1229Smith plugin modules are Teal contracts. Implementations are Teal records checked
1230against those contracts.
1232A module contract is a `mod.tl` file:
1234```text
1235plugins/community-subagents/smith/subagents/mod.tl
1236```
1238```lua
1239local record Subagents
1240 record Request
1241 prompt: string
1242 end
1244 record Context
1245 cwd: string
1246 end
1248 record Description
1249 label: string
1250 end
1252 record RunResult
1253 ok: boolean
1254 output: string
1255 end
1257 describe: function(): Description
1258 run: function(Request, Context): RunResult
1259end
1261return Subagents
1262```
1264The module ID is derived from the path after the package root:
1266```text
1267smith/subagents/mod.tl → smith.subagents
1268```
1270A module implementation is an `init.tl` file at the same module path:
1272```text
1273plugins/alice/subagents/smith/subagents/init.tl
1274```
1276```lua
1277local Subagents = require("smith.subagents.mod")
1279local AliceSubagents <total>: Subagents = {
1280 describe = function(): Subagents.Description
1281 return { label = "Alice Subagents" }
1282 end,
1284 run = function(request: Subagents.Request, ctx: Subagents.Context): Subagents.RunResult
1285 return { ok = true, output = request.prompt .. " in " .. ctx.cwd }
1286 end,
1289return AliceSubagents
1290```
1292Rules:
1294- Module contracts use `record`, not `interface`, for exported module tables.
1295- Module implementations bind the returned table as `<total>` to catch missing
1296 required exports.
1297- Implementation private state lives outside the returned typed table.
1298- The implementation ID is `<package-id>:<module-id>`.
1299- A package provides at most one implementation for a given module ID.
1300- A package may implement many different module IDs by providing different
1301 `<module-path>/init.tl` files.
1302- Multiple implementations of one module means multiple packages provide the
1303 same module ID.
1304- Authors who want to ship variants split them into separate packages, e.g.
1305 `alice.subagents-fast:smith.subagents` and
1306 `alice.subagents-safe:smith.subagents`.
1307- Module packages may be contract-only.
1308- Implementation packages may implement contracts from other packages.
1309- Adapter packages are ordinary implementation packages: they consume one module
1310 and implement another module by convention. No adapter-specific registry or
1311 plugin-manager path exists.
1312- A package may contain both `mod.tl` and `init.tl` for the same module path.
1314Module binding lifecycle:
13161. Discover all module contracts.
13172. Discover and Teal-check all implementation candidates.
13183. Apply user config bindings.
13194. Auto-bind modules with exactly one implementation.
13205. Emit a warning/status for modules with multiple implementations and no binding.
13216. Do not fail discovery for modules with zero implementations.
13227. Resolve module implementations only when a consumer requests that module.
1324Resolution errors:
1326- `NoImplementation { module }` when a consumed module has no implementation,
1327- `AmbiguousImplementation { module, candidates }` when multiple implementations
1328 exist and none is selected,
1329- `ConfiguredImplementationMissing { module, implementation }` when config names
1330 an implementation that is not installed.
1332User config binds modules to implementations:
1334```lua
1335return {
1336 modules = {
1337 ["smith.subagents"] = "alice.subagents:smith.subagents",
1338 },
1340```
1342Binding validation rejects implementation IDs whose module suffix does not match
1343requested module. For example, binding `smith.subagents` to
1344`bob-agents:bob.agents` fails before module use because `bob.agents` is not an
1345implementation of `smith.subagents`.
1347Config bindings override singleton auto-bindings and earlier bindings.
1349### 9.7 Plugin Precedence
1351Load order:
13531. built-in plugins,
13542. global user plugins,
13553. project plugins,
13564. explicit CLI/config overrides.
1358Later registrations override earlier ones unless registration marks duplicate as
1359an error.
1361### 9.8 Event Bridge
1363`PluginEvent` variants cover:
1365- agent lifecycle,
1366- turns,
1367- message deltas/end,
1368- tool call/result,
1369- session lifecycle,
1370- model changes,
1371- context/compaction,
1372- TUI/input events,
213- tools,
1373214- commands,
1374- provider/auth events,
1375- VCS events,
1376- errors and shutdown.
215- providers and models,
216- prompts and context transforms,
217- event handlers,
218- themes and keybindings,
219- layout and render descriptions,
220- VCS workflows.
1378Lua receives event tables with a `type` field.
222Plugin events are ordered and typed.
223A failed plugin load leaves no registrations or subscriptions active.
224Reload either activates one coherent new plugin state or retains the previous state.
225Session continuity survives reload.
1380Plugin event results can:
227### Discovery and modules
1382- block tool call,
1383- transform tool args,
1384- replace tool result,
1385- retry/cancel,
1386- transform input,
1387- override system prompt/context,
1388- request continue/stop,
1389- emit UI actions.
229Version 1 discovers plugin packages and module contracts by path convention without requiring manifests.
230Package and module identities are deterministic and validated before execution.
1391The bridge maps these into `AgentLoopConfig` hooks.
232A module can have zero, one, or multiple implementations.
233One implementation binds automatically.
234Zero or ambiguous implementations fail only when consumed, with candidates reported.
235Explicit user binding overrides automatic binding and must match the requested module contract.
1393### 9.9 Extension Contexts
237Precedence is built-in, global user, project, then explicit override.
238Later registration replaces earlier registration only where the contract permits replacement.
1395SDK contexts:
240### Project trust
1397- `ExtensionContext`: agent lifecycle, model, context, tools, config, logging.
1398- `ExtensionCommandContext`: slash command args, selection, output, session.
1399- `ExtensionUIContext`: selection, confirm, prompt, status, layout, widget APIs.
242Project-local executable configuration, plugins, and managed packages do not load before trust is resolved.
243Interactive mode can ask and persist the decision.
244Non-interactive modes require an explicit or previously persisted decision to load project-local executable behavior.
245Ignoring untrusted project behavior produces a visible diagnostic.
1401### 9.10 Lua SDK
247Trust does not remove the Lua sandbox or tool boundaries.
1403SDK namespaces include:
249### Configuration
1405- `smith.fs.*`,
1406- `smith.search.*`,
1407- `smith.env.*`,
1408- `smith.time.*`,
1409- `smith.log.*`,
1410- `smith.tool.*`,
1411- `smith.command.*`,
1412- `smith.provider.*`,
1413- `smith.alias.*`,
1414- `smith.group.*`,
1415- `smith.bucket.*`,
1416- `smith.tui.*`,
1417- `smith.vcs.*`,
1418- `smith.abort()`,
1419- `smith.shutdown()`,
1420- `smith.getContextUsage()`.
251Configuration has deterministic precedence:
1422All public Lua SDK functions have Teal type declarations and `@usage` docs.
1423Docs are generated from Smith's Teal SDK declarations and usage blocks.
2531. product defaults,
2542. built-in plugin defaults,
2553. plugin contributions,
2564. user configuration,
2575. trusted project configuration,
2586. explicit command-line overrides.
1425### 9.11 Built-in Plugins
260Invalid values fail with their source and field path.
261Unknown values follow the owning schema's explicit policy.
1427Built-ins are Lua plugins, not Rust special cases:
263## Terminal interface
1429- tools: `read`, `write`, `edit`, `bash`, `find`, `grep`, `ls`,
1430- slash commands: `/undo`, `/redo`, `/history`, `/tree`, replay/time-travel,
1431- VCS tools,
1432- default layout,
1433- default keybindings,
1434- default theme,
1435- default prompts.
265Smith uses a fullscreen TUI by default.
266Version 1 has no regular terminal-scrollback mode.
267The TUI presents messages, thinking, tool activity, errors, input, status, model, cost, and context use through an independently scrollable transcript.
1437### 9.12 Built-in Tool Specs
269Required interaction behavior:
1439#### `read`
271- input remains responsive during provider and tool work,
272- scrolling away from the bottom does not jump on new output,
273- users can return to the latest message explicitly,
274- search and selection target stable visible content,
275- overlays own focus explicitly,
276- resize and focus changes preserve valid layout,
277- shutdown restores terminal state after normal exit, error, abort, or signal.
1441Inputs:
279Rust supplies deterministic widgets and layout primitives.
280Lua selects product layout and presentation.
281Structured render descriptions cannot emit arbitrary terminal control sequences.
1443- `path: string`,
1444- `offset?: number`,
1445- `limit?: number`.
283Terminal capabilities are detected conservatively and can be overridden explicitly.
284Unsupported hyperlinks, color, keyboard, mouse, or image features degrade to plain terminal behavior.
285Capability probing cannot indefinitely delay startup.
1447Behavior:
287## Interface modes
1449- reads text files,
1450- supports line windowing,
1451- rejects binary content or returns explicit binary metadata,
1452- output is bounded for LLM context.
289### Interactive
1454#### `write`
291Interactive mode supports new, attach, continue, resume, branch, compact, replay, model selection, plugin management, help, and shutdown behavior.
292User-visible commands are plugin-registered unless they are required to enter or recover the runtime.
1456Inputs:
294### Eval
1458- `path: string`,
1459- `content: string`.
296Eval accepts a prompt, runs the same agent behavior without the TUI, and can emit human-readable or structured output.
297It can persist to a selected session.
1461Behavior:
299### JSON-RPC
1463- creates parent dirs as needed,
1464- writes atomically with temp file + rename,
1465- records VCS op when mutation succeeds.
301RPC uses standard input and output with strict LF-delimited messages.
302Standard output contains protocol records only.
303Requests and responses preserve request IDs.
304Unknown commands return correlated errors.
1467#### `edit`
306Streaming message updates are ordered deltas between start and end events.
307The end event is authoritative.
308Clients can inspect sessions, observe tool and compaction lifecycle, manage queued input, abort active work, and wait for the runtime to settle.
1469Inputs:
310### Replay
1471- `path: string`,
1472- exact `old_text`,
1473- `new_text`,
1474- `allow_multiple?: bool`.
312Replay operates without provider credentials.
313Structured replay output is deterministic for the same session and trace inputs.
1476Behavior:
14781. read file,
14792. reject empty `old_text`,
14803. reject binary,
14814. count exact matches,
14825. fail if zero matches,
14836. fail if multiple and `allow_multiple` false,
14847. re-read/hash before write,
14858. fail stale if file changed,
14869. write atomically,
148710. return change count and before/after hashes.
1489Errors include `ENOENT`, `EEMPTY`, `EBINARY`, `ENOMATCH`, `EMULTI`, `ESTALE`,
1490`ELOCK`.
1492#### `bash`
1494Inputs:
1496- `command: string`,
1497- `timeout?: number`,
1498- `cwd?: string`.
1500Behavior:
1502- executes subprocess on tool thread,
1503- captures stdout/stderr/status,
1504- enforces timeout,
1505- records output truncation metadata,
1506- supports abort.
1508#### `find`
1510Uses `ignore` crate. Respects gitignore-style files. Returns sorted paths with
1511limits.
1513#### `grep`
1515Uses `grep`, `grep-regex`, and `grep-searcher`. Supports context lines, glob,
1516case-insensitive search, literal/regex modes, match limits.
1518#### `ls`
1520Lists directory entries sorted alphabetically, with directory suffix, bounded
1521output, and explicit errors.
1523### 9.13 Tool Surface Compatibility
1525Smith's built-in coding tool names intentionally match the Pi-compatible minimal
1526IR: `read`, `write`, `edit`, `bash`, `find`, `grep`, and `ls`.
1528Interface rules:
1530- Core tools use provider-neutral JSON schemas through `ToolDefinitionSpec`.
1531- Core tools do not use provider-specific freeform grammars.
1532- Exact file mutation is core; fuzzy or model-applied edits are plugin adapters.
1533- Product workflow tools are plugins, not core tools: plans, todos, subagents,
1534 permissions, MCP, semantic search, notifications, worktrees, and LSP.
1536Bridge aliases for compatibility plugins:
1538```text
1539Claude Read -> read
1540Claude Bash -> bash
1541Claude Edit -> edit with one exact replacement
1542Claude MultiEdit -> edit with multiple exact replacements (legacy alias)
1543Claude Write -> write
1544Claude Glob -> find
1545Claude Grep -> grep
1546Claude LS -> ls
1548Cursor read_file -> read
1549Cursor run_terminal_cmd -> bash
1550Cursor list_dir -> ls
1551Cursor grep_search -> grep
1552Cursor file_search -> find adapter
1553Cursor edit_file -> fuzzy/apply-model plugin, not edit
1555Codex shell_command/exec_command -> bash adapter
1556Codex apply_patch -> plugin parser to edit/write operations
1557Codex update_plan -> plugin tool
1558Codex view_image -> image-content/plugin adapter
1559```
1561Error rules:
1563- Unsupported non-equivalent aliases fail explicitly with `UnsupportedToolAlias`.
1564- Fuzzy edit adapters must not silently call exact `edit` unless they can produce
1565 unique exact replacements.
1566- Freeform patch parsers return parse errors before file mutation.
1567- Shell adapters that need TTY/session/yield semantics must declare those
1568 capabilities; plain `bash` does not emulate them implicitly.
1570Tests:
1572- Unit tests cover every alias mapping.
1573- Negative tests cover Cursor `edit_file`, Codex `apply_patch` parse failures,
1574 and unsupported product tools.
1575- Integration tests verify adapters lower successful operations into normal
1576 Smith tool events and session entries.
1578### 9.14 VCS SDK
1580Smith uses jj internally for operation-level undo/redo/time travel.
1582jj is embedded as a library (`jj-lib`). Smith never shells out to, bundles, or
1583requires an external `jj` binary; the user does not need jj installed. The development-workflow VCS choice for the Smith repo itself is separate and governed by `.system/RULES.md`.
1585State:
1587- actual `.jj` lives under `data_dir/smith/vcs/{project-hash}/jj-state`,
1588- project root contains only `.jj` symlink,
1589- colocated git repos rewrite jj `git_target` to absolute `.git` path.
1591Plugins interact only through `smith.vcs.*`.
1593`smith.vcs.*` exposes:
1595- init/status/snapshot,
1596- op ID capture,
1597- diff queries: working-copy diff, rev diff, op diff, interdiff, evolog, annotation,
1598- undo/redo/time-travel primitives,
1599- selective path restore,
1600- commit/split/squash helpers for built-in workflows,
1601- workspace and sparse materialization helpers,
1602- structured file statuses and hunks.
1604`gix` is used only for targeted structured queries behind `smith.vcs.*`.
1606### 9.15 Sandbox
1608Plugins are trusted but constrained to Smith SDK APIs:
1610- no raw `io`, `os`, or `debug`,
1611- filesystem/env access only through SDK,
1612- no path capability system in v1,
1613- built-in and user plugins use same API.
1615## 10. CLI Crate: `smith-cli`
1617Binary name: `smith`.
1619### 10.1 Global Flags
1621- `--model <model>`
1622- `--provider <provider>`
1623- `--session <id-or-name>`
1624- `--config <path>`
1625- `--no-config`
1627### 10.2 Commands
1629Default:
1631- `smith` starts interactive TUI with new auto-named session.
1633Subcommands:
1635- `smith new <name>` — new named interactive session.
1636- `smith attach [id-or-name]` — attach; fuzzy select if no arg.
1637- `smith continue` — continue last session in cwd.
1638- `smith resume` — fuzzy select session in cwd.
1639- `smith session list [--cwd]` — list sessions.
1640- `smith session dump [id] [--last N] [--output path]` — JSONL dump.
1641- `smith plugins` — list plugins.
1642- `smith install <plugin>` — install plugin.
1643- `smith uninstall <plugin>` — uninstall plugin.
1644- `smith eval <prompt> [--json] [--session id]` — non-interactive eval.
1645- `smith rpc` — JSON-RPC via stdio.
1646- `smith help [topic] [--search q] [--list] [--examples] [--example name] [--guide name]`.
1647- `smith replay <session> [--speed f64] [--compare] [--sandbox path]
1648 [--turns N] [--from-turn N] [--format text|json|summary] [--continue-on-diff bool]`.
1650Interactive slash commands are registered by Lua plugins, not clap subcommands.
1652### 10.3 Main
1654`main` uses tokio, parses clap, resolves config, creates `Harness`, dispatches to
1655interactive/eval/rpc/replay/session/plugin/help command handlers.
1657`smith-cli` restores terminal state on errors and signals.
1659## 11. Security Model
1661Trusted:
1663- user,
1664- OS/filesystem,
1665- local plugins,
1666- Smith code,
1667- session/config/cache files.
1669Untrusted:
1671- remote LLM,
1672- provider network response content.
1674Security mechanisms:
16761. Tool registry controls which tools the LLM can invoke.
16772. Secret proxy prevents real secrets from reaching LLM context.
16783. Restricted Lua runtime removes raw OS/file APIs.
16794. Users configure active tools; no confirmation-dialog security theater.
1681Credentials:
1683- environment vars preferred,
1684- plaintext config/auth file allowed,
1685- no keychain,
1686- no encryption.
1688## 12. Concurrency and Async
1690Threads/tasks:
1692- engine/main: owns harness event loop and agent state,
1693- UI thread: render/event polling, never blocks engine,
1694- tool thread pool: subprocess/file/plugin tool execution,
1695- provider async tasks: streaming HTTP.
1697Async boundary:
1699- `tokio` in `smith-ai`, `smith-core`, and harness orchestration,
1700- TUI rendering is sync on UI thread,
1701- tool execution runs off the UI thread.
1703Responsiveness:
1705- UI keypress acknowledged within 16ms,
1706- engine never blocks on UI,
1707- every long operation observes abort.
1709## 13. Performance Requirements
1711- Release binary < 20MB stripped.
1712- `smith --help` < 100ms.
1713- TUI frame draw < 2ms within 16ms frame budget.
1714- Session encode 1000 entries < 5ms.
1715- Agent loop turn target < 30s excluding provider/network stalls beyond timeout.
1716- Bench regressions >10% fail nightly/release gates.
1718## 14. Release Artifacts
1720Required targets:
1722| Platform | Triple | Status |
1723|----------|--------|--------|
1724| Windows x86_64 | `x86_64-pc-windows-msvc` | required |
1725| Windows ARM64 | `aarch64-pc-windows-msvc` | required |
1726| macOS Intel | `x86_64-apple-darwin` | required |
1727| macOS Apple Silicon | `aarch64-apple-darwin` | required |
1728| Linux x86_64 glibc | `x86_64-unknown-linux-gnu` | required |
1729| Linux ARM64 glibc | `aarch64-unknown-linux-gnu` | required |
1730| Linux x86_64 musl | `x86_64-unknown-linux-musl` | required |
1731| Linux ARM64 musl | `aarch64-unknown-linux-musl` | required |
1732| OpenBSD x86_64 | `x86_64-unknown-openbsd` | best-effort |
1734Artifacts:
1736- `smith-{triple}-v{version}.{zip|tar.gz}`,
1737- `checksums-sha256.txt`.
1739No install scripts, package manifests, distribution metadata, or code signing in v1.
1741## 15. xtask
1743Required commands:
1745| Command | Purpose |
1746|---------|---------|
1747| `check` | fmt + clippy + arch + pup + test + doc |
1748| `test` | all tests via nextest |
1749| `lint` | clippy + rustfmt check |
1750| `fmt` | auto-format |
1751| `fetch-providers` | emit provider review bundle for `smith-ai/src/providers.json` |
1752| `doc-test` | run Lua `@usage`, guide blocks, examples |
1753| `verify-docs` | verify SDK/API docs completeness |
1754| `doc-gen` | generate man pages and docs bundle |
1755| `spec-verify` | verify SPEC links and project invariants |
1756| `arch` | stable architecture checks |
1757| `pup` | pinned-nightly cargo-pup gate |
1758| `print-modules` | module inventory: Cargo metadata crate roots + cargo-pup submodules |
1759| `audit` | cargo-deny + cargo-audit |
1760| `bench` | criterion benchmarks |
1761| `coverage` | tarpaulin coverage |
1762| `mutants` | cargo-mutants mutation testing |
1763| `release` | build archives and checksums |
1765xtask commands are thin orchestrators. No business logic.
1767## 16. Documentation
1769- `.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md` is the canonical product spec.
1770- `.system/RULES.md` contains non-negotiable repository invariants.
1771- Design docs may expand implementation rationale but cannot contradict `SPEC.md`.
1772- SDK docs are generated from Teal SDK declarations and `@usage` blocks.
1773- `smith help` reads embedded generated docs.
1775Documentation gates:
1777- every Rust SDK function has Lua binding docs,
1778- every Lua binding has a Teal declaration,
1779- every declared function has usage,
1780- every event appears in at least one example,
1781- no documented function missing in code,
1782- no public SDK function undocumented.
1784## 17. Testing
1786### 17.1 Fast Tier
1788Every commit:
1790```bash
1791cargo fmt --check
1792cargo clippy --workspace --all-targets --all-features -- -D warnings
1793cargo run -p xtask -- arch
1794cargo +nightly-2026-01-22 pup
1795cargo nextest run --profile fast
1796cargo test --doc
1797```
1799Blocks push.
1801Scope:
1803- unit tests,
1804- property tests,
1805- TUI snapshots,
1806- serialization snapshots,
1807- doc tests,
1808- architecture gates.
1810### 17.2 Medium Tier
1812Every PR:
1814```bash
1815cargo fmt --check
1816cargo clippy --workspace --all-targets --all-features -- -D warnings
1817cargo run -p xtask -- arch
1818cargo +nightly-2026-01-22 pup
1819cargo nextest run --profile default
1820cargo test --doc
1821cargo tarpaulin --out Lcov
1822cargo nextest run --profile integration
1823cargo doc --workspace --no-deps
1824```
1826Blocks merge.
1828### 17.3 Slow Tier
1830Nightly + release:
1832```bash
1833cargo nextest run --profile thorough
1834cargo mutants --test-tool=nextest
1835cargo bench -- --baseline main
1836```
1838Blocks release if mutation score <80% or benchmark regression exceeds threshold.
1840### 17.4 Coverage Goals
1842| Crate | Target |
1843|-------|--------|
1844| `smith` | 100% |
1845| `smith-core` | ≥95% |
1846| `smith-ai` | ≥90% |
1847| `smith-tui` | ≥85% |
1848| `smith-harness` | ≥90% |
1849| `smith-cli` | ≥80% |
1851### 17.5 nextest
1853`.config/nextest.toml`:
1855```toml
1856[profile.default]
1857retries = 3
1858slow-timeout = "30s"
1859fail-fast = false
1861[profile.fast]
1862test-group = "fast"
1863retries = 0
1864fail-fast = true
1865slow-timeout = "5s"
1867[profile.integration]
1868filter = 'test(integration::) or test(cli::) or test(tui::)'
1869retries = 2
1870slow-timeout = "30s"
1872[profile.thorough]
1873retries = 1
1874slow-timeout = "120s"
1875```
1877### 17.6 Property Tests
1879Required property areas:
1881- CBOR session codec roundtrip,
1882- model resolver determinism and cycle detection,
1883- valid Lua config parsing,
1884- token estimator monotonicity,
1885- event-to-session-entry conversion,
1886- trace filtering preserves order.
1888Commit `proptest-regressions/`.
1890### 17.7 Snapshot Tests
1892Use `insta` + ratatui `TestBackend` for:
1894- widgets,
1895- layout composition,
1896- themes,
1897- CLI help,
1898- error formatting,
1899- config parse output,
1900- provider normalization.
1902CI runs with `INSTA_UPDATE=no`.
1904### 17.8 Integration Tests
1906Required integration coverage:
1908- CLI commands and flags,
1909- session create/resume/fork/dump/replay,
1910- plugin load/order/override/event dispatch,
1911- provider registry/custom provider/auth/mock streaming/MuxProvider failover,
1912- TUI startup/shutdown/capabilities/mouse/layout/theme/scroll,
1913- docs/help/search/examples.
1915Fixtures live under `tests/fixtures/` with plugins, sessions, configs, providers,
1916and traces.
1918### 17.9 Benchmarks
1920Criterion benchmarks:
1922- `session_encode_1000`,
1923- `session_decode_1000`,
1924- `widget_render_100`,
1925- `agent_loop_turn`,
1926- `config_resolve_3level`,
1927- `trace_filter_10000`,
1928- `plugin_load_10`.
1930## 18. Prototype Policy
1932Prototypes are disposable evidence for or against this spec. They live under
1933`prototypes/`, never in production crates. A prototype tests one claim or risk,
1934runs minimal commands, and reports whether the spec should change.
1936Prototype output must include:
1938- status,
1939- proved claims,
1940- disproved claims,
1941- spec issues with evidence,
1942- artifacts created,
1943- commands run,
1944- next spec/design actions.
1946Production code must not depend on prototype artifacts.
315## Documentation and help
317Public Rust and Lua APIs are documented.
318Lua SDK declarations are the source for generated plugin help.
319Every public event and function has one discoverable usage description.
320Generated help is checked against the exposed SDK so neither can silently drift.
322## Security
324The remote model and provider response content are untrusted.
325Project-local executable behavior is untrusted until approved.
326Installed user plugins are user-approved but remain sandboxed.
328Security guarantees:
330- only active tools can be invoked,
331- tool arguments are validated before effects,
332- secrets are removed before remote dispatch,
333- plugin effects pass through Smith SDK boundaries,
334- project trust gates local executable behavior,
335- path and package installation cannot escape owned roots,
336- diagnostics do not expose credentials.
338Smith does not depend on confirmation dialogs as its primary security boundary.
340## Performance and portability
342Target behavior:
344- help output starts within 100 ms on supported desktop systems,
345- normal TUI frames complete within a 16 ms budget,
346- encoding 1,000 representative session entries completes within 5 ms,
347- large sessions load incrementally without requiring one contiguous file-sized string,
348- transcript work scales with visible content rather than complete history where practical,
349- long-running network and filesystem work never blocks input rendering.
351Smith supports current Windows, macOS, and Linux on x86_64 and ARM64 where Rust and required native dependencies support the target.
352OpenBSD x86_64 is best effort.
353Release archives include versioned binaries and SHA-256 checksums.
355## Acceptance criteria
357Smith is acceptable when:
359- all modes use one provider-independent agent runtime,
360- a mock provider completes a tool-using turn with ordered durable events,
361- sessions survive truncation, preserve unknown frames, and replay deterministically,
362- concurrent or interrupted session operations do not silently corrupt history,
363- provider catalogs remain usable offline and reject stale refresh publication,
364- model requests never use unadvertised capabilities,
365- project plugins cannot execute before trust resolution,
366- built-in and user plugins use the same sandboxed effect APIs,
367- terminal shutdown restores host state across supported exit paths,
368- RPC consumers can assemble complete messages from ordered events,
369- required quality, architecture, documentation, and release gates pass without warnings.

smith-cli/src/main.rs

Modified

+1 / −1 text lines

44//! Smith command-line entry point.
6fn main() {}
6const fn main() {}

xtask/src/main.rs

Modified

+1 / −1 text lines

142142 denied: &'static [&'static str],
145fn dependency_rules() -> &'static [DependencyRule] {
145const fn dependency_rules() -> &'static [DependencyRule] {
146146 &[
147147 DependencyRule {
148148 crate_name: "smith",