README Source History Refs Reviews Compare Notes Search Review guide chore(system): align lifecycle artifacts and foundation gates b024614c43bd405fd2bb2f906b0675f99d9926f3
Oliver Jan Krylow <oliver@bugabinga.net > · 10 Sep 2026
unsigned
Browse files Compare 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) Diff layout Auto Unified Split
.cargo/config.toml Modified +9 / −4 text lines
2 2 x = "run -p xtask --" x = "run -p xtask --" 5 7 rustflags = [rustflags = [7 9 "-D" , "warnings" , "-D" , "warnings" ,36 38 [registries .crates-io ][registries .crates-io ]37 39 protocol = "sparse" protocol = "sparse" 41 43 [target .aarch64-linux-android ][target .aarch64-linux-android ]42 - rustflags = [ "-C" , "link-args =-lclang_rt.builtins-aarch64-android" ] 45 + "-L" , "native=/data/data/com.termux/files/usr/lib/clang/latest/lib/linux" ,46 + "-C" , "link-arg =-lclang_rt.builtins-aarch64-android" , new file mode 100644+6 / −0 text lines
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" new file mode 100644+4 / −0 text lines
.system/config.json Modified +3 / −2 text lines
2 2 "prefix" : "SMH" , "prefix" : "SMH" ,5 + "currentPhase" : "SMH-PHASE-CORE0001" .system/issues/SMH-ISSUE-R4SEXWVT-running-cargo-run-p-xtask-command-is-cumbersome/index.md Modified +0 / −1 text lines
4 4 title: "xtask command invocation is cumbersome"title: "xtask command invocation is cumbersome"5 5 specs: [SMH-SPEC-SPEC0001]specs: [SMH-SPEC-SPEC0001]9 8 # xtask Command Invocation Is Cumbersome # xtask Command Invocation Is Cumbersome .system/phases/SMH-PHASE-AIAG0001-agent-capability/index.md Added new file mode 100644+17 / −0 text lines
4 + title: "Agent Capability"12 + Make Smith useful across all supported operating modes through a provider-independent agent loop.13 + Prioritize normalized provider behavior, deterministic turns, and complete event capture.17 + Eval 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
4 - title: "Provider and Agent Loop"5 - spec: SMH-SPEC-SPEC00017 - depends_on: [SMH-PHASE-CORE0001]10 - # Provider and Agent Loop 14 - Make Smith useful in eval mode with one provider path and the core loop.18 - 1. Implement provider trait and normalized stream events.19 - 2. Implement auth resolver.20 - 3. Implement OpenAI-compatible SSE provider.21 - 4. Implement minimal model registry.22 - 5. Implement agent loop over StreamFn and tools.23 - 6. Expose eval and JSON-RPC commands.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.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
4 + title: "Core Capability"12 + Establish Smith's provider-free runtime foundation across the project.13 + Prioritize stable shared types, deterministic sessions, explicit errors, and safe tool effects.17 + The 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
4 - title: "Core Session and Tools"5 - spec: SMH-SPEC-SPEC00017 - depends_on: [SMH-PHASE-XCICUUJD]10 - # Core Session and Tools 14 - Build the provider-free spine: shared types, deterministic storage, tool registry, and built-in tools.18 - 1. Implement `smith` shared types and errors.19 - 2. Implement config and Lua runtime shell without plugin loading.20 - 3. Implement CBOR session and trace format.21 - 4. Implement tool registry.22 - 5. Implement read, write, edit, ls, find, grep, bash.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.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
4 + title: "Extensible Product"12 + Make Lua extension the normal product path across Smith.13 + Prioritize one sandboxed loading model for built-in and user behavior, with Rust limited to safe primitives.17 + Smith 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
4 - title: "Lua Harness and Plugins"5 - spec: SMH-SPEC-SPEC00017 - depends_on: [SMH-PHASE-AIAG0001]10 - # Lua Harness and Plugins 14 - Connect Rust subsystems to Lua plugin loading and built-in extension points.18 - 1. Implement sandboxed Lua runtime and Teal loading.19 - 2. Implement convention plugin discovery.20 - 3. Implement event bridge and SDK namespaces.21 - 4. Move built-in commands and tool renderers into Lua plugins.22 - 5. Wire harness for config, provider, agent, plugins, and modes.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.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
4 - title: "Docs Release and Hardening"5 - spec: SMH-SPEC-SPEC00017 - depends_on: [SMH-PHASE-TUIR0001]10 - # Docs Release and Hardening 14 - Finish provider coverage, help docs, release artifacts, and required gates.18 - 1. Complete bundled provider registry and fetch review flow.19 - 2. Generate SDK help from Teal declarations and usage blocks.20 - 3. Add doc tests and completeness checks.21 - 4. Add cargo-pup, audit, coverage, and release gates.22 - 5. Build release archives and checksums.23 - 6. Add regression coverage for replay, plugins, providers, and tools.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.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
4 + title: "Release Readiness"12 + Prepare the whole product for dependable public distribution.13 + Prioritize complete documentation, reproducible artifacts, reviewed provider data, and enforced quality gates.17 + A 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
4 + title: "Interactive Product"12 + Make terminal interaction and historical state first-class across Smith.13 + Prioritize consistent live and replayed views, Lua-owned layout, and controlled VCS operations.17 + Users 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
4 - title: "TUI and Replay"5 - spec: SMH-SPEC-SPEC00017 - depends_on: [SMH-PHASE-LUAH0001]14 - Add interactive terminal UI, session replay, and VCS-backed undo/time travel.18 - 1. Implement terminal backend and event normalization.19 - 2. Implement widget primitives and theme schema.20 - 3. Implement Lua-driven layout integration.21 - 4. Implement replay engine over sessions and traces.22 - 5. Implement jj-lib VCS SDK primitives.23 - 6. Add undo, redo, history, and time-travel plugins.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.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
4 + title: "Project Foundation"12 + Establish the project-wide conditions for safe Smith development.13 + Prioritize repository law, crate boundaries, Cargo-only automation, and executable quality gates.17 + All 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
4 - title: "Foundation and Gates"5 - spec: SMH-SPEC-SPEC000113 - Create the empty product skeleton and make repository rules executable.17 - 1. Create Cargo workspace and crate shells.18 - 2. Add shared lint, fmt, docs, and audit config.19 - 3. Add xtask command shell.20 - 4. Add architecture checks for crate dependency direction.21 - 5. Add minimal CI command path.29 - - Root manifest edits need explicit approval.30 - - Lint policy may block before code exists.31 - - Architecture checks can drift from spec names.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
2 2 id: SMH-PLAN-AIAG0001id: SMH-PLAN-AIAG00014 - title: "Provider and Agent Loop Plan "4 + title: "Provider Runtime and Agent Loop"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00016 - phase: SMH-PHASE-AIAG0001
7 6 status: draftstatus: draft8 7 depends_on: [SMH-PLAN-CORE0001]depends_on: [SMH-PLAN-CORE0001]11 - # Provider and Agent Loop Plan 10 + # Provider Runtime and Agent Loop 15 - 1. Add provider trait and normalized events.16 - 2. Add auth resolver and auth errors.17 - 3. Add mocked OpenAI-compatible SSE parser.18 - 4. Add OpenAI-compatible provider shell.19 - 5. Add minimal model registry.20 - 6. Add agent loop over StreamFn.22 - 8. Add JSON-RPC command.14 + - Shared stream, tool, error, session, and trace contracts are stable.15 + - Provider-free tool events persist correctly.19 + 1. Add `smith-ai` provider adapters that normalize deltas, tool calls, usage, stop reasons, errors, and cancellation.20 + 2. Add explicit model capability metadata and request validation.21 + 3. Add the reviewed offline catalog and deterministic alias, group, and account resolution.22 + 4. Add credential resolution, readiness checks, renewable credentials, and concurrent update safety.23 + 5. Add cancellable catalog refresh with cached fallback and generation-checked publication.24 + 6. Prove one OpenAI-compatible stream against fragmented, malformed, incomplete, and non-stream error fixtures.25 + 7. Add required Anthropic, OpenAI, and Google adapter coverage through the same normalized boundary.26 + 8. Add the `smith-core` agent loop with ordered turn, message, tool, retry, and settled events.27 + 9. Add steering, follow-up, compaction, cost, secret substitution, bounded retry, and failover behavior.28 + 10. Expose eval and LF-delimited JSON-RPC through `smith-cli` and `smith-harness`.24 30 ## Interfaces ## Interfaces 26 - | Module | Interface |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.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.40 - - Provider-specific fields leak into core.41 - - JSON-RPC framing conflicts with session format.52 + Eval and RPC run complete provider-backed agent turns through one runtime without vendor details crossing the provider boundary.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
2 2 id: SMH-PLAN-CORE0001id: SMH-PLAN-CORE00014 - title: "Core Session and Tools Plan "4 + title: "Core Session and Tool Effects "5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00016 - phase: SMH-PHASE-CORE0001
7 6 status: draftstatus: draft8 7 depends_on: [SMH-PLAN-WSPC0001]depends_on: [SMH-PLAN-WSPC0001]11 - # Core Session and Tools Plan 10 + # Core Session and Tool Effects 15 - 1. Add shared IDs, request, response, error, and stream types.16 - 2. Add config data and validation.17 - 3. Add deterministic session entries and CBOR codec.20 - 6. Add read, write, edit.21 - 7. Add ls, find, grep.14 + - Workspace shells and architecture gates exist.15 + - No provider or interface is required.19 + 1. Define shared IDs, messages, normalized stream events, tool metadata, cancellation, and recoverable errors in `smith`.20 + 2. Add validated runtime configuration types without loading plugins.21 + 3. Add the `smith-core` session model, selected branch, and in-memory restoration.22 + 4. Add deterministic length-prefixed CBOR framing with bounded decode and opaque unknown-frame retention.23 + 5. Add append, load, fork, repair, and writer serialization around the session store.24 + 6. Add replay-relevant trace records without implementing presentation.25 + 7. Add the tool registry and lifecycle event boundary.26 + 8. Add read, write, exact edit, list, find, and grep effects.27 + 9. Add bounded cancellable bash execution after file effects are stable.24 29 ## Interfaces ## Interfaces 26 - | Module | Interface |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.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.40 - - Session format ambiguity.41 - - Tool side effect cannot be recorded with event.49 + Provider-free tool activity can be persisted, recovered, and reconstructed deterministically.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
2 2 id: SMH-PLAN-LUAH0001id: SMH-PLAN-LUAH00014 - title: "Lua Harness and Plugins Plan"4 + title: "Sandboxed Plugin Harness"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00016 - phase: SMH-PHASE-LUAH0001
7 6 status: draftstatus: draft8 7 depends_on: [SMH-PLAN-AIAG0001]depends_on: [SMH-PLAN-AIAG0001]11 - # Lua Harness and Plugins Plan 10 + # Sandboxed Plugin Harness 15 - 1. Add Lua runtime sandbox.16 - 2. Add Teal source checking and loading path.17 - 3. Add plugin discovery by convention.18 - 4. Add SDK namespace table.20 - 6. Add harness wiring.21 - 7. Convert built-in commands to Lua plugins.22 - 8. 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.19 + 1. Add project trust resolution before project executable configuration or package discovery.20 + 2. Add the restricted Lua runtime and trusted source validation boundary.21 + 3. Add convention-based package, module contract, and implementation discovery.22 + 4. Add deterministic module binding, ambiguity diagnostics, and plugin precedence.23 + 5. Add typed SDK namespaces for filesystem, search, tools, commands, providers, UI, VCS, logging, and lifecycle control.24 + 6. Bridge runtime events and plugin results without exposing internal ownership.25 + 7. Load each plugin into a transactional registration set so failure leaves no active residue.26 + 8. Route built-in commands, presentation, themes, keybindings, prompts, and workflows through the same loader.27 + 9. Add atomic reload with rollback and preserved session continuity.28 + 10. Wire trusted global, project, and explicit plugin sources into the harness.24 30 ## Interfaces ## Interfaces 26 - | Module | Interface |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.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.40 - - SDK primitive missing for a built-in plugin.41 - - Plugin discovery needs manifests.49 + The harness operates through the public sandboxed plugin surface with explicit project trust and no privileged built-in path.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
2 2 id: SMH-PLAN-RELS0001id: SMH-PLAN-RELS00014 - title: "Docs Release and Hardening Plan"4 + title: "Release Readiness"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00016 - phase: SMH-PHASE-RELS0001
7 6 status: draftstatus: draft8 7 depends_on: [SMH-PLAN-TUIR0001]depends_on: [SMH-PLAN-TUIR0001]11 - # Docs Release and Hardening Plan 15 - 1. Complete providers.json review flow.16 - 2. Add provider conflict reports.17 - 3. Generate help from Teal SDK docs.19 - 5. Add coverage, audit, arch, pup gates.20 - 6. Add release archive generation.21 - 7. 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.19 + 1. Complete provider catalog ingestion, provenance, conflict reporting, cached fallback, and human review flow.20 + 2. Generate Lua SDK help from the authoritative typed declarations and usage descriptions.21 + 3. Verify public Rust, Lua, event, command, and configuration documentation for completeness and drift.22 + 4. Complete architecture, lint, format, test, documentation, audit, coverage, mutation, and benchmark gates through Cargo automation.23 + 5. Harden provider streams, compaction, session recovery, plugin rollback, project trust, terminal restoration, RPC framing, and tool cancellation against recorded edge cases.24 + 6. Build versioned release archives and SHA-256 checksums for required targets.25 + 7. Verify supported target startup, fullscreen restoration, eval, RPC, and replay behavior from release artifacts.23 27 ## Interfaces ## Interfaces 25 - | Module | Interface |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.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.39 - - Gate needs secret or live network.40 - - Docs introduce source of truth outside SDK declarations.46 + A documented, reproducible Smith release passes all required gates and operates without maintainer-only knowledge.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
2 2 id: SMH-PLAN-TUIR0001id: SMH-PLAN-TUIR00014 - title: "TUI and Replay Plan "4 + title: "Fullscreen TUI and Replay"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00016 - phase: SMH-PHASE-TUIR0001
7 6 status: draftstatus: draft8 7 depends_on: [SMH-PLAN-LUAH0001]depends_on: [SMH-PLAN-LUAH0001]10 + # Fullscreen TUI and Replay15 - 1. Add terminal backend abstraction.16 - 2. Add normalized input events.17 - 3. Add widget primitives.18 - 4. Add theme validation.19 - 5. Add Lua layout bridge.21 - 7. Add jj-lib VCS primitives.22 - 8. 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.19 + 1. Add fullscreen terminal entry, restoration, panic-safe shutdown, and signal handling in `smith-cli` and `smith-tui`.20 + 2. Add conservative capability detection, bounded probes, explicit overrides, and plain-terminal fallback.21 + 3. Add normalized keyboard, paste, mouse, resize, and focus events.22 + 4. Add deterministic widget, overlay, theme, and layout primitives in `smith-tui`.23 + 5. Add structured Lua render descriptions and the default fullscreen layout.24 + 6. Add an independently scrollable transcript with sticky-bottom control and explicit jump to latest.25 + 7. Add stable search, selection, link activation, viewport navigation, and focus routing.26 + 8. Add replay reconstruction, seek, speed, range, and comparison over session and trace inputs.27 + 9. Add structured VCS snapshot, diff, restore, undo, redo, and time-travel primitives.28 + 10. Expose replay and VCS workflows through built-in Lua plugins.24 30 ## Interfaces ## Interfaces 26 - | Module | Interface |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.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.40 - - Rust widgets start owning product layout.41 - - Replay requires data absent from session entries.53 + Users can operate, inspect, replay, and revisit a session through one fullscreen terminal interface.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
4 4 title: "Foundation and Gates Plan"title: "Foundation and Gates Plan"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00016 - phase: SMH-PHASE-XCICUUJD10 9 # Foundation and Gates Plan # 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
2 + id: SMH-RESEARCH-FNY87IGJ4 + title: "Pi 0.75.5 to 0.85.1 Delta"7 + # Pi 0.75.5 to 0.85.1 Delta 11 + Baseline: Pi coding-agent 0.75.5, previously inspected at repository revision `3eb0027`.12 + Current release: 0.85.1, published 2026-09-05 and installed locally.14 + The npm releases span 36 published versions after the baseline.16 + This is a release-level architectural delta, not an exhaustive source diff.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.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?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
7 7 # Smith Memory Allocation Profile Estimate # Smith Memory Allocation Profile Estimate 9 9 **Date:** 2026-05-23 **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..system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md Modified +274 / −1851 text lines
2 2 id: SMH-SPEC-SPEC0001id: SMH-SPEC-SPEC00014 4 title: "Smith Specification"title: "Smith Specification"
5 + research: [SMH-RESEARCH-FNY87IGJ]7 8 # Smith Specification # Smith Specification 9 - Smith is a Rust coding-agent TUI. This document describes the desired project10 - state. It is the canonical specification for architecture, crates, interfaces,11 - configuration, plugins, CLI behavior, build gates, and testing.15 - Smith is a fast, extensible AI coding agent with:17 - - interactive terminal UI,18 - - non-interactive eval mode,19 - - JSON-RPC stdio mode,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.25 - Core 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 the30 - 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 typed33 - 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.44 - smith/ foundation crate: shared types, StreamFn, AgentTool, config, Lua runtime, errors45 - smith-core/ agent loop, sessions, tools, hooks, compaction, cost, trace, replay46 - smith-ai/ LLM providers, auth, model registry, provider streams, MuxProvider47 - smith-tui/ terminal events, widgets, layout primitives, render loop, themes48 - smith-harness/ orchestration, plugin system, SDK, event bridge, built-ins, help49 - smith-cli/ binary entry point, clap CLI, session commands, eval/rpc/replay50 - xtask/ Cargo-only automation53 - ### 2.2 Allowed Internal Dependencies 55 - | Crate | May depend on |56 - |-------|---------------|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` |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.76 - - `cargo run -p xtask -- arch` checks stable Cargo metadata and source77 - 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`.81 - Diagnostics (informational, not gates):83 - - `cargo run -p xtask -- print-modules` prints crate roots from Cargo metadata84 - plus cargo-pup submodule output.86 - ### 2.3 Workspace Manifest 106 - license = "Apache-2.0"109 - Required shared dependencies:112 - mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }114 - serde = { version = "1", features = ["derive"] }116 - tokio = { version = "1", features = ["full"] }117 - clap = { version = "4", features = ["derive"] }124 - tracing-subscriber = { version = "0.3", features = ["env-filter"] }125 - reqwest = { version = "0.12", features = ["json", "stream"] }127 - unicode-width = "0.2"128 - unicode-segmentation = "1"129 - syntastica = { version = "0.6", default-features = false, features = ["runtime-c2rust"] }130 - syntastica-parsers = "0.6"131 - fuzzy-matcher = "0.3"136 - grep-searcher = "0.1"137 - gix = { version = "0.83", default-features = false, features = ["blame", "blob-diff", "revision"] }143 - uuid = { version = "1", features = ["v7"] }148 - criterion = { version = "0.5", features = ["async_tokio"] }151 - zip = { version = "2", default-features = false, features = ["deflate"] }156 - Vendored language asset:162 - Smith vendors Teal as source, not as an external executable. Plugin checks,163 - plugin compilation, and runtime source generation do not shell out to `tl`.175 - [profile.release.package."*"]179 - ## 3. Toolchain, Lints, and Build Gates 181 - ### 3.1 Rust Toolchain 183 - `rust-toolchain.toml`:188 - components = ["rustfmt", "clippy"]191 - Smith follows latest stable Rust. Do not pin a numeric MSRV unless release192 - engineering creates a formal support window.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 moving200 - product code to nightly.201 - - The pinned nightly is updated only together with a cargo-pup upgrade, never202 - on a calendar basis. The pin date carries no staleness meaning.203 - - Pup failure blocks commit, PR, and release.207 - `.cargo/config.toml`:212 - # Zero warnings policy216 - "-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 patterns226 - "-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 lints235 - "-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",242 - [registries.crates-io]245 - # Target-scoped: only applies when building on/for Termux ARM64 (vendored246 - # LuaJIT needs the compiler-rt builtins). No effect on other platforms.247 - [target.aarch64-linux-android]248 - rustflags = ["-C", "link-args=-lclang_rt.builtins-aarch64-android"]251 - Every library crate has:254 - #![forbid(unsafe_code)]255 - #![warn(missing_docs)]258 - `smith-cli` may use unsafe only for OS terminal manipulation when no safe259 - alternative exists, wrapped in a tested safe abstraction with `// SAFETY:`.261 - ### 3.3 Clippy Policy 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]`.272 - cognitive-complexity-threshold = 25277 - `cargo run -p xtask -- audit` runs:281 - cargo audit --deny warnings284 - `deny.toml` allows Apache-2.0, MIT, and Unicode-DFS-2016. Duplicate versions are285 - warned unless explicitly accepted.289 - Root `pup.ron` exists and is required. Cargo-pup is the pinned-nightly source290 - architecture lint gate. `xtask arch` remains the stable Cargo metadata gate.292 - Initial pup rules enforce: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`.300 - Crate-boundary module match patterns must include the crate root. Use301 - `^crate($|::.*)`, not only `^crate::.*`. Cargo-pup sees root-owned items in302 - `lib.rs`/`main.rs` under the crate name itself.304 - Required boundary patterns:307 - matches: Module("^smith_core($|::.*)")308 - matches: Module("^smith_ai($|::.*)")309 - matches: Module("^smith_tui($|::.*)")312 - `cargo pup print-modules` is not a complete module inventory. It can omit crate313 - roots and can emit synthetic `unknown_crate` for crates with no child `mod`314 - items. Developer-facing module inventory uses `cargo run -p xtask -- print-modules`,315 - which prefixes crate roots from stable Cargo metadata and then prints316 - cargo-pup-discovered submodules.321 - rustup component add --toolchain nightly-2026-01-22 rust-src rustc-dev llvm-tools-preview322 - cargo +nightly-2026-01-22 install cargo_pup328 - cargo +nightly-2026-01-22 pup331 - ## 4. Runtime Directories and Files 333 - Smith 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\` |346 - {session-id}.session361 - Session files are plaintext length-prefixed CBOR sequences. Trace files are362 - compressed deterministic replay logs. Secrets in sessions are plaintext after363 - local 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 no368 - downstream dependencies.382 - pub use stream::StreamFn;383 - pub use tool::{AgentTool, AgentToolResult, AgentToolUpdate, ToolExecutionMode};384 - pub use lua::LuaRuntime;385 - pub use config::Config;386 - pub use error::SmithError;387 - pub use mux::{ModelAlias, ModelGroup, ProviderBucket, ModelResolver, ResolvedModel, ResolveError};390 - `smith` must not re-export `smith-core` types. Domain types are imported from393 - ### 5.1 IDs and Messages 395 - Required shared types:397 - - `EntryId(String)` — UUID v7, time-sortable.398 - - `SessionId(String)`.399 - - `SecretId(String)`.401 - - `Role`: `System`, `User`, `Assistant`, `Tool`, `ToolResult`, `Custom`, `BashExecution`.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`.421 - - `ProviderRequest` contains messages, system prompt, model/provider IDs, tool422 - definitions, thinking level, token limit, and stop sequences.426 - - `ToolDefinitionSpec` is serializable metadata for LLM function calling and428 - - `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`.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`.442 - This permits `smith-core` and `smith-ai` to build independently.446 - `LuaRuntime` wraps mlua + LuaJIT + `mlua-pkg` custom require. Plugin source is447 - fronted by vendored Teal (`tl.lua`): Smith compiles `.tl` and `.lua` plugin448 - source to Lua before loading it into the runtime.450 - Allowed standard libraries:457 - - `package` with custom searchers.467 - Smith host APIs are exposed through `require("smith")`.469 - Compiler 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.479 - Lua is the configuration language. Rust defines schemas; Lua supplies values.481 - Cascade order, later overrides earlier:483 - 1. Rust type defaults/schema,484 - 2. built-in Lua defaults,485 - 3. plugin contributions,486 - 4. user config at `config_dir/smith/config.lua`,489 - Invalid values are rejected with clear errors. Unknown keys warn or fail490 - according to the schema context.496 - theme = "catppuccin",498 - ["ctrl+l"] = "cycle_model",499 - ["ctrl+c"] = "abort",501 - tools = { "read", "write", "edit", "bash" },502 - model = "anthropic/claude-sonnet-4",504 - ["smith.subagents"] = "alice.subagents:smith.subagents",509 - ### 5.7 Models, Aliases, Groups, Buckets 511 - `ModelMetadata` includes:513 - - provider/model IDs,517 - - capabilities: thinking, vision, tool use, streaming.519 - `ModelResolver` is pure. It resolves:522 - requested name → alias → group → bucket/account → provider/model metadata527 - - no I/O during resolution,528 - - cycles detected at config load and reported with full path,530 - - `ResolvedModel` carries metadata needed by `smith-core`.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.541 - `SmithError` is the shared recoverable error enum. It wraps provider, auth, tool,542 - config, Lua, I/O, CBOR, and resolver errors.544 - Internal impossible states use assertions during development but shipped library545 - code must not panic for external failures.547 - ## 6. Core Crate: `smith-core` 549 - `smith-core` owns pure business logic: agent loop, sessions, tools, hooks,550 - secret proxy, compaction, cost, trace, and replay. It depends only on `smith`.557 - pub mod session_format ;560 - pub mod secret_proxy ;561 - pub mod system_prompt ;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.579 - The loop uses two nested loops:581 - - outer loop: turns and follow-up messages,582 - - inner loop: provider streaming, tool calls, steering.584 - It never imports provider implementations. Providers are `StreamFn` only.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,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.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`,611 - `AgentEvent::to_session_entry(timestamp)` returns a `SessionEntry` only for612 - conversation-relevant completed events.614 - ### 6.3 Engine Events 616 - `EngineEvent` wraps `AgentEvent` and adds harness-level events:619 - - steering/follow-up,621 - - provider/model changes,622 - - errors and shutdown.624 - `EngineEvent` is consumed by `smith-harness` and `smith-tui`.628 - Core 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 647 - - created/updated timestamps.649 - Sessions are branching trees. Branches are immutable once created. `/tree` and650 - history/time-travel features are Lua plugins over this core state.652 - `SessionEntry` variants include:658 - - system prompt snapshot,659 - - compaction summary,660 - - secret registration,661 - - model/provider change,663 - - metadata entries needed for migration and replay.665 - Every entry has a stable `EntryId`, optional parent, and timestamp.667 - ### 6.6 Session Format 669 - Session files are length-prefixed CBOR frame sequences:672 - u32 BE len | CBOR SessionFrame bytes | u32 BE len | CBOR SessionFrame bytes | ...675 - `len` is the byte length of the following CBOR frame payload, not including the676 - length prefix. v1 frame payloads are self-describing envelopes:685 - `kind` names the session-entry variant. `data` contains the variant payload.686 - Known kinds are decoded into typed `SessionEntry` values after envelope decode.687 - Unknown kinds are retained as opaque raw frame payload bytes.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.697 - - Complete known frame: decode envelope, decode typed payload, append entry.698 - - Complete unknown frame: decode envelope, store the exact raw frame payload bytes699 - and report unknown kind. Unknown frames are written back byte-for-byte when700 - 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 validation704 - fails, treat the frame as corrupt, skip it, warn, and continue at the next706 - - 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 no710 - byte resynchronization scan.714 - - crash recovery: truncated tail stops parsing without losing fully decoded prior716 - - 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.723 - The 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.731 - Secrets are local plaintext. The protection target is the remote LLM.733 - ### 6.8 System Prompt 735 - `SystemPromptBuilder` composes:738 - - active model/tool capabilities,739 - - plugin prompt contributions,740 - - project/context facts,741 - - safety and tool-use instructions,744 - Plugins may transform prompts through typed hooks. No hidden global prompt mutation.746 - ### 6.9 Compaction and Cost 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.758 - - v1 heuristic: chars/4,759 - - exact tokenizer is not required in core.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.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.778 - ### 6.11 Trace and Replay 780 - Trace 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,789 - - agent state snapshots.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.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 812 - pub 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 >>;820 - `provider_to_stream_fn(Arc<dyn Provider>)` returns the `StreamFn` consumed by823 - ### 7.2 Provider Implementations 830 - - OpenAI-compatible local/remote endpoints.832 - MiniMax 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`.12 + Smith is a fast Rust coding-agent TUI with Lua-owned customization.13 + It provides one provider-independent agent runtime across interactive, eval, JSON-RPC, and replay modes.834 - Provider implementations normalize vendor wire formats into `ProviderEvent`.836 - Quirks handled at provider boundary: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,845 - ### 7.3 Model Registry 29 + Smith 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-in848 - file is authoritative at runtime.850 - Runtime overrides come only from the Lua plugin API: plugins may add providers851 - and models or adjust fields through `smith.providers.*`. There is no user-level852 - `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 truth858 - cargo run -p xtask -- fetch-providers861 - Data 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.863 - 1. pi.dev model data,864 - 2. catwalk provider configs,865 - 3. later shared provider repositories after review.51 + A provider stream has explicit terminal success, tool-use, limit, abort, and error outcomes.52 + Malformed or incomplete provider streams fail explicitly.53 + A terminal event is emitted once.867 - `fetch-providers` emits a review bundle, not an in-place replacement:55 + Tool calls and results remain correctly paired and ordered.56 + Injected messages never split a tool call from its result.57 + Changes 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 61 + Smith supports Anthropic, OpenAI, Google, and OpenAI-compatible endpoints.62 + Additional providers can be supplied through the plugin API.875 - - merge identity is `(provider_id, model_id)`, with provider-only fields keyed by877 - - current `providers.json` wins every current-vs-suggestion conflict,878 - - current-vs-suggestion conflicts are written to `providers.review.json` and make879 - 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 conflicts883 - 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 for886 - forward compatibility but ignored by v1,887 - - unknown fields from source registries are ignored unless Smith maps them into888 - the normalized schema or an explicit `x_source_*` field during review,889 - - `replace_models` is allowed only in checked-in `providers.json` as a human890 - review annotation; generated sources must not apply full provider replacement64 + Every provider normalizes:893 - `providers.review.json` entries must include:66 + - text and thinking deltas,69 + - usage and cache accounting,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 900 - Provider config correctness cannot be fully automated because Smith does not have901 - all provider accounts, subscriptions, API keys, regional access, or provider902 - quirk coverage. Generated changes require review before commit. After the903 - provider format stabilizes, Smith may use a Pi agent to open provider-data PRs904 - from `fetch-providers` review bundles.75 + Model metadata states supported behavior explicitly, including:77 + - context and output limits,78 + - text and image input,81 + - strict or grammar-constrained tool input,908 - Auth resolver sources:85 + Provider requests use only advertised capabilities.86 + Unsupported optional behavior degrades predictably or fails before dispatch.87 + Family-name inference cannot override explicit provider evidence.910 - - environment variables,911 - - `~/.smith/auth.json`,912 - - plaintext Lua config values when explicitly supplied.914 - No OS keychain. No encryption.91 + Smith ships a reviewed offline model catalog.92 + Human configuration and checked-in data remain authoritative.916 - Auth errors fail fast before first provider stream.94 + Provider or plugin catalogs may refresh at runtime when enabled.95 + Refresh behavior must:918 - OAuth module supports mocked OAuth flow in tests and provider-specific OAuth where98 + - 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.104 + Catalog freshness cannot block normal offline startup.923 - `MuxProvider` wraps multiple providers/accounts for resolved groups and buckets.108 + Credentials may come from environment variables, Smith auth data, explicit configuration, or provider plugins.109 + Authentication is resolved before dispatch and can be checked independently of a model request.110 + Concurrent credential changes cannot lose unrelated provider state.111 + Expired renewable credentials refresh before use.112 + Credential 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`.933 - ## 8. TUI Crate: `smith-tui` 116 + Model aliases, groups, and account buckets resolve deterministically.117 + Resolution performs no network access.118 + Cycles and ambiguity fail with complete diagnostics.935 - `smith-tui` owns terminal primitives, normalized events, widgets, themes, and936 - render loop. It depends only on `smith`.120 + Rate limits may fail over immediately.121 + Transient transport failures follow bounded retry policy before failover.122 + Invalid requests and unavailable models do not retry indefinitely.126 + A session is an append-only branching history with stable IDs, parent links, timestamps, and a selected leaf.127 + Entries 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.129 + Session persistence uses length-prefixed CBOR frames.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:141 + Resuming, cloning, forking, and branch navigation preserve the selected history and compaction boundary.142 + Externally managed entries can initialize an in-memory session without changing their order or IDs.144 + Session dumps use JSONL for inspection and interchange.145 + JSONL is not the authoritative persistence format.956 - Keyboard events include normalized key code, modifiers, and press/repeat/release957 - kind. Mouse events include button, scroll, position, and modifiers.147 + ## Compaction, cost, and secrets 959 - ### 8.3 Terminal Capabilities 149 + Compaction reduces provider context without deleting durable history.150 + It preserves required lineage, recent context, tool ordering, secret registrations, and the active branch boundary.151 + It never persists a summary known to be truncated or incomplete.152 + Queued input resumes after compaction according to its original delivery mode.961 - `TerminalCapabilities` records:154 + Cost accounting includes provider responses, tool-reported usage, compaction, and branch summaries when usage is available.155 + Unknown usage remains unknown rather than becoming zero.965 - - Kitty keyboard protocol,969 - - Kitty graphics / sixel availability.157 + The secret proxy replaces registered secrets before remote dispatch and restores them only for authorized local effects.158 + Secrets remain local plaintext under the user's filesystem permissions.971 - No terminfo database. Probe directly. Unsupported optional features degrade to972 - plain text without user-facing error.974 - ### 8.4 Component Trait 976 - Components render into ratatui buffers and handle normalized `TuiEvent`.172 + All tools use provider-neutral definitions, bounded output, explicit errors, cancellation, and recorded lifecycle events.173 + Provider-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.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.990 - new → enter terminal → run event/render loop → shutdown → restore terminal185 + Bash executes in an explicit working directory with bounded output, timeout, exit status, and cancellation.186 + Process termination includes descendants started by the invocation where the platform permits it.187 + Shell output arriving immediately after process exit is not silently truncated.993 - The render loop ticks at 16ms. Event polling runs on a blocking thread and sends994 - normalized events over channels. `TuiApp` is created/driven by `smith-harness`.189 + Tool mutation is recorded only when the effect succeeds.190 + A failed recording step cannot leave a successful mutation presented as unrecorded success.192 + Compatibility adapters may translate external tool names only when semantics are equivalent.193 + Fuzzy edits, freeform patches, terminal sessions, plans, subagents, permissions, MCP, and semantic search remain plugin behavior.1005 - Every state is interruptible.197 + Replay reconstructs runtime state from recorded events without a provider.198 + It supports real-time playback, accelerated playback, turn ranges, and comparison of re-executed tool effects.199 + Replay preserves source event order and reports divergence explicitly.201 + Smith provides VCS-backed snapshots, diffs, undo, redo, restore, and time travel through one structured SDK boundary.202 + Normal operation does not require an external VCS executable.203 + Mutating VCS operations validate their target and remain attributable to session events.1009 - Required widget set includes:205 + ## Plugins and configuration 1020 - - progress/cost/context indicators,1021 - - tool call/result views,1023 - - syntax-highlighted code,1028 - - border layout panels.207 + Lua plugins run in a restricted runtime without direct operating-system, filesystem, environment, or debug libraries.208 + Host effects are available only through typed Smith SDK functions.209 + Built-in plugins have no privileged effect path.1030 - Syntax highlighting uses `syntastica`. Diffs use `similar`. Fuzzy matching uses211 + Plugins may contribute:1035 - Rust provides primitives; Lua defines layout.1049 - One predefined border layout exists: center + north/east/south/west panels.1050 - Panels are invisible when empty. Default layout is a Lua plugin.1052 - Overlays support modal and non-modal use with top, bottom, left, right, center, and cursor anchors.1056 - Themes are Lua tables validated by Rust schemas.1058 - Theme values cover status bar, messages, assistant content, tool call/result,1059 - errors, input, borders, selections, diffs, syntax groups, and accents.1061 - ### 8.9 Virtual Scroll 1063 - Message history uses virtual scrolling. `sticky_bottom` defaults true and turns1064 - false when user scrolls up. New content does not move viewport until user returns1065 - to bottom or submits input.1067 - ### 8.10 Tool Rendering 1069 - Tools may register `renderCall` and `renderResult` Lua renderers. TUI receives1070 - structured render instructions from harness, not arbitrary terminal writes.1072 - ## 9. Harness Crate: `smith-harness` 1074 - `smith-harness` wires all subsystems and owns plugin management.1079 - - load model registry and auth,1080 - - resolve active model,1081 - - create provider and `StreamFn`,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 1099 - - optional `TuiApp`,1103 - ### 9.2 Plugin Identity and Convention Discovery 1105 - Plugins do not have manifests in v1. Smith discovers plugin shape from paths and1106 - validates behavior from Teal types plus runtime registration tables.1108 - A plugin package is a directory under one of the plugin roots. Package path1109 - segments map to a dotted package ID using normal Lua module naming rules:1112 - data_dir/smith/plugins/<package-path>/1113 - .smith/plugins/<package-path>/1116 - `<package-id>` uses lowercase ASCII letters, numbers, `_`, `-`, and `.`. Exact1117 - `smith` and the `smith.` prefix are reserved for built-in packages. The package1118 - filesystem path is the package ID with `.` replaced by `/`.1123 - plugins/alice/subagents/ → alice.subagents1124 - git:bob/plugin → bob.plugin1125 - https://github.com/bob/plugin.git → bob.plugin1126 - plugins/smith/builtins/ → reserved built-in package1129 - Smith recognizes these files by convention:1132 - init.lua standalone plugin entry1133 - init.tl standalone plugin entry1134 - <module-path>/mod.tl module contract1135 - <module-path>/init.tl module implementation1138 - `<module-path>` maps to a module ID by replacing `/` with `.`:1141 - smith/subagents/mod.tl → smith.subagents1142 - smith/subagents/init.tl → implementation of smith.subagents1145 - Implementation IDs are derived from package ID plus module ID:1148 - plugins/alice/subagents/smith/subagents/init.tl1149 - → alice.subagents:smith.subagents1152 - No `smith-plugin.lua`, `package.json`, descriptor table, or metadata file is read1153 - for discovery. Package metadata is not part of v1.1155 - ### 9.3 Plugin API Compatibility 1157 - Smith plugin API generation is `1` for all v1 plugins. There is no per-plugin API1158 - selection in v1 because there are no manifests. Breaking plugin API generations1159 - are deferred until Smith introduces a versioned package metadata format.1161 - ### 9.4 Plugin Loading 1163 - Smith vendors Teal (`tl.lua`) and uses it as the single plugin source frontend.1164 - The Teal compiler runs in a trusted compiler Lua state. Plugin code runs in a1165 - separate restricted LuaJIT runtime state.1169 - - `.tl` files are checked and compiled with Teal. Syntax or type errors block1171 - - `.lua` files are checked and generated with Teal Lua mode. Syntax or generation1172 - errors block loading. Type and unknown-value diagnostics are emitted as1173 - non-blocking warnings.1174 - - Generated Lua is loaded into the restricted plugin runtime. Original source is1175 - never executed directly.1177 - Standalone plugin entries are `init.lua` or `init.tl` at the package root. They1178 - return registration tables/factories. Module implementation files return module1179 - implementation tables.1181 - Plugin bridge phases:1183 - 1. Discover package directories and convention paths.1184 - 2. Teal-check module contracts and implementation files.1185 - 3. Compile source to Lua in the compiler state.1186 - 4. Load generated Lua in the restricted runtime state.1187 - 5. Collect standalone registration tables/factories.1188 - 6. Register module contracts and implementation candidates.1189 - 7. Apply user module bindings and singleton auto-bindings.1190 - 8. Materialize Rust-side handles.1191 - 9. Register into tool/event/command/provider/TUI registries.1193 - No Rust trait-object plugin API exists. Canonical plugin loading is the Teal/Lua1194 - registration pipeline above.1196 - ### 9.5 Plugin Install and Uninstall 1198 - Supported install sources for v1:1200 - - local directory path,1203 - No 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.1216 - Git URL installs use Smith's internal git implementation boundary. The preferred1217 - implementation is `gix` if its required clone/fetch feature set stays bounded;1218 - otherwise 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 1229 - Smith plugin modules are Teal contracts. Implementations are Teal records checked1230 - against those contracts.1232 - A module contract is a `mod.tl` file:1235 - plugins/community-subagents/smith/subagents/mod.tl1239 - local record Subagents1257 - describe: function(): Description1258 - run: function(Request, Context): RunResult1264 - The module ID is derived from the path after the package root:1267 - smith/subagents/mod.tl → smith.subagents1270 - A module implementation is an `init.tl` file at the same module path:1273 - plugins/alice/subagents/smith/subagents/init.tl1277 - local Subagents = require("smith.subagents.mod")1279 - local AliceSubagents <total>: Subagents = {1280 - describe = function(): Subagents.Description1281 - return { label = "Alice Subagents" }1284 - run = function(request: Subagents.Request, ctx: Subagents.Context): Subagents.RunResult1285 - return { ok = true, output = request.prompt .. " in " .. ctx.cwd }1289 - return AliceSubagents1294 - - Module contracts use `record`, not `interface`, for exported module tables.1295 - - Module implementations bind the returned table as `<total>` to catch missing1297 - - 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 different1301 - `<module-path>/init.tl` files.1302 - - Multiple implementations of one module means multiple packages provide the1304 - - Authors who want to ship variants split them into separate packages, e.g.1305 - `alice.subagents-fast:smith.subagents` and1306 - `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 module1310 - and implement another module by convention. No adapter-specific registry or1311 - plugin-manager path exists.1312 - - A package may contain both `mod.tl` and `init.tl` for the same module path.1314 - Module binding lifecycle:1316 - 1. Discover all module contracts.1317 - 2. Discover and Teal-check all implementation candidates.1318 - 3. Apply user config bindings.1319 - 4. Auto-bind modules with exactly one implementation.1320 - 5. Emit a warning/status for modules with multiple implementations and no binding.1321 - 6. Do not fail discovery for modules with zero implementations.1322 - 7. Resolve module implementations only when a consumer requests that module.1326 - - `NoImplementation { module }` when a consumed module has no implementation,1327 - - `AmbiguousImplementation { module, candidates }` when multiple implementations1328 - exist and none is selected,1329 - - `ConfiguredImplementationMissing { module, implementation }` when config names1330 - an implementation that is not installed.1332 - User config binds modules to implementations:1337 - ["smith.subagents"] = "alice.subagents:smith.subagents",1342 - Binding validation rejects implementation IDs whose module suffix does not match1343 - requested module. For example, binding `smith.subagents` to1344 - `bob-agents:bob.agents` fails before module use because `bob.agents` is not an1345 - implementation of `smith.subagents`.1347 - Config bindings override singleton auto-bindings and earlier bindings.1349 - ### 9.7 Plugin Precedence 1353 - 1. built-in plugins,1354 - 2. global user plugins,1356 - 4. explicit CLI/config overrides.1358 - Later registrations override earlier ones unless registration marks duplicate as1361 - ### 9.8 Event Bridge 1363 - `PluginEvent` variants cover:1367 - - message deltas/end,1369 - - session lifecycle,1371 - - context/compaction,1373 214 - commands,- commands,1374 - - provider/auth events,1376 - - errors and shutdown.215 + - providers and models,216 + - prompts and context transforms,218 + - themes and keybindings,219 + - layout and render descriptions,1378 - Lua receives event tables with a `type` field.222 + Plugin events are ordered and typed.223 + A failed plugin load leaves no registrations or subscriptions active.224 + Reload either activates one coherent new plugin state or retains the previous state.225 + Session continuity survives reload.1380 - Plugin event results can:227 + ### Discovery and modules 1383 - - transform tool args,1384 - - replace tool result,1387 - - override system prompt/context,1388 - - request continue/stop,229 + Version 1 discovers plugin packages and module contracts by path convention without requiring manifests.230 + Package and module identities are deterministic and validated before execution.1391 - The bridge maps these into `AgentLoopConfig` hooks.232 + A module can have zero, one, or multiple implementations.233 + One implementation binds automatically.234 + Zero or ambiguous implementations fail only when consumed, with candidates reported.235 + Explicit user binding overrides automatic binding and must match the requested module contract.1393 - ### 9.9 Extension Contexts 237 + Precedence is built-in, global user, project, then explicit override.238 + Later registration replaces earlier registration only where the contract permits replacement.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.242 + Project-local executable configuration, plugins, and managed packages do not load before trust is resolved.243 + Interactive mode can ask and persist the decision.244 + Non-interactive modes require an explicit or previously persisted decision to load project-local executable behavior.245 + Ignoring untrusted project behavior produces a visible diagnostic.247 + Trust does not remove the Lua sandbox or tool boundaries.1403 - SDK namespaces include:1411 - - `smith.command.*`,1412 - - `smith.provider.*`,1419 - - `smith.shutdown()`,1420 - - `smith.getContextUsage()`.251 + Configuration has deterministic precedence:1422 - All public Lua SDK functions have Teal type declarations and `@usage` docs.1423 - Docs are generated from Smith's Teal SDK declarations and usage blocks.254 + 2. built-in plugin defaults,255 + 3. plugin contributions,256 + 4. user configuration,257 + 5. trusted project configuration,258 + 6. explicit command-line overrides.1425 - ### 9.11 Built-in Plugins 260 + Invalid values fail with their source and field path.261 + Unknown values follow the owning schema's explicit policy.1427 - Built-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,1433 - - default keybindings,265 + Smith uses a fullscreen TUI by default.266 + Version 1 has no regular terminal-scrollback mode.267 + The 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 269 + Required interaction behavior: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.279 + Rust supplies deterministic widgets and layout primitives.280 + Lua selects product layout and presentation.281 + Structured render descriptions cannot emit arbitrary terminal control sequences.1444 - - `offset?: number`,283 + Terminal capabilities are detected conservatively and can be overridden explicitly.284 + Unsupported hyperlinks, color, keyboard, mouse, or image features degrade to plain terminal behavior.285 + Capability probing cannot indefinitely delay startup.1450 - - supports line windowing,1451 - - rejects binary content or returns explicit binary metadata,1452 - - output is bounded for LLM context.291 + Interactive mode supports new, attach, continue, resume, branch, compact, replay, model selection, plugin management, help, and shutdown behavior.292 + User-visible commands are plugin-registered unless they are required to enter or recover the runtime.1459 - - `content: string`.296 + Eval accepts a prompt, runs the same agent behavior without the TUI, and can emit human-readable or structured output.297 + It can persist to a selected session.1463 - - creates parent dirs as needed,1464 - - writes atomically with temp file + rename,1465 - - records VCS op when mutation succeeds.301 + RPC uses standard input and output with strict LF-delimited messages.302 + Standard output contains protocol records only.303 + Requests and responses preserve request IDs.304 + Unknown commands return correlated errors.306 + Streaming message updates are ordered deltas between start and end events.307 + The end event is authoritative.308 + Clients can inspect sessions, observe tool and compaction lifecycle, manage queued input, abort active work, and wait for the runtime to settle.1474 - - `allow_multiple?: bool`.312 + Replay operates without provider credentials.313 + Structured replay output is deterministic for the same session and trace inputs.1479 - 2. reject empty `old_text`,1481 - 4. count exact matches,1482 - 5. fail if zero matches,1483 - 6. fail if multiple and `allow_multiple` false,1484 - 7. re-read/hash before write,1485 - 8. fail stale if file changed,1486 - 9. write atomically,1487 - 10. return change count and before/after hashes.1489 - Errors include `ENOENT`, `EEMPTY`, `EBINARY`, `ENOMATCH`, `EMULTI`, `ESTALE`,1496 - - `command: string`,1497 - - `timeout?: number`,1502 - - executes subprocess on tool thread,1503 - - captures stdout/stderr/status,1505 - - records output truncation metadata,1510 - Uses `ignore` crate. Respects gitignore-style files. Returns sorted paths with1515 - Uses `grep`, `grep-regex`, and `grep-searcher`. Supports context lines, glob,1516 - case-insensitive search, literal/regex modes, match limits.1520 - Lists directory entries sorted alphabetically, with directory suffix, bounded1521 - output, and explicit errors.1523 - ### 9.13 Tool Surface Compatibility 1525 - Smith's built-in coding tool names intentionally match the Pi-compatible minimal1526 - IR: `read`, `write`, `edit`, `bash`, `find`, `grep`, and `ls`.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.1536 - Bridge aliases for compatibility plugins:1541 - Claude Edit -> edit with one exact replacement1542 - Claude MultiEdit -> edit with multiple exact replacements (legacy alias)1543 - Claude Write -> write1548 - Cursor read_file -> read1549 - Cursor run_terminal_cmd -> bash1550 - Cursor list_dir -> ls1551 - Cursor grep_search -> grep1552 - Cursor file_search -> find adapter1553 - Cursor edit_file -> fuzzy/apply-model plugin, not edit1555 - Codex shell_command/exec_command -> bash adapter1556 - Codex apply_patch -> plugin parser to edit/write operations1557 - Codex update_plan -> plugin tool1558 - Codex view_image -> image-content/plugin adapter1563 - - Unsupported non-equivalent aliases fail explicitly with `UnsupportedToolAlias`.1564 - - Fuzzy edit adapters must not silently call exact `edit` unless they can produce1565 - unique exact replacements.1566 - - Freeform patch parsers return parse errors before file mutation.1567 - - Shell adapters that need TTY/session/yield semantics must declare those1568 - capabilities; plain `bash` does not emulate them implicitly.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 normal1576 - Smith tool events and session entries.1580 - Smith uses jj internally for operation-level undo/redo/time travel.1582 - jj is embedded as a library (`jj-lib`). Smith never shells out to, bundles, or1583 - requires 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`.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.1591 - Plugins interact only through `smith.vcs.*`.1593 - `smith.vcs.*` exposes:1595 - - init/status/snapshot,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.*`.1608 - Plugins 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` 1617 - Binary name: `smith`.1619 - ### 10.1 Global Flags 1622 - - `--provider <provider>`1623 - - `--session <id-or-name>`1631 - - `smith` starts interactive TUI with new auto-named session.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]`.1650 - Interactive slash commands are registered by Lua plugins, not clap subcommands.1654 - `main` uses tokio, parses clap, resolves config, creates `Harness`, dispatches to1655 - interactive/eval/rpc/replay/session/plugin/help command handlers.1657 - `smith-cli` restores terminal state on errors and signals.1659 - ## 11. Security Model 1667 - - session/config/cache files.1672 - - provider network response content.1674 - Security mechanisms:1676 - 1. Tool registry controls which tools the LLM can invoke.1677 - 2. Secret proxy prevents real secrets from reaching LLM context.1678 - 3. Restricted Lua runtime removes raw OS/file APIs.1679 - 4. Users configure active tools; no confirmation-dialog security theater.1683 - - environment vars preferred,1684 - - plaintext config/auth file allowed,1688 - ## 12. Concurrency and Async 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.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.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 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 |1736 - - `smith-{triple}-v{version}.{zip|tar.gz}`,1737 - - `checksums-sha256.txt`.1739 - No install scripts, package manifests, distribution metadata, or code signing in v1.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 |1765 - xtask 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.1775 - Documentation 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.1792 - cargo clippy --workspace --all-targets --all-features -- -D warnings1793 - cargo run -p xtask -- arch1794 - cargo +nightly-2026-01-22 pup1795 - cargo nextest run --profile fast1806 - - serialization snapshots,1808 - - architecture gates.1810 - ### 17.2 Medium Tier 1816 - cargo clippy --workspace --all-targets --all-features -- -D warnings1817 - cargo run -p xtask -- arch1818 - cargo +nightly-2026-01-22 pup1819 - cargo nextest run --profile default1821 - cargo tarpaulin --out Lcov1822 - cargo nextest run --profile integration1823 - cargo doc --workspace --no-deps1833 - cargo nextest run --profile thorough1834 - cargo mutants --test-tool= nextest1835 - cargo bench -- --baseline main1838 - Blocks release if mutation score <80% or benchmark regression exceeds threshold.1840 - ### 17.4 Coverage Goals 1845 - | `smith-core` | ≥95% |1846 - | `smith-ai` | ≥90% |1847 - | `smith-tui` | ≥85% |1848 - | `smith-harness` | ≥90% |1849 - | `smith-cli` | ≥80% |1853 - `.config/nextest.toml`:1858 - slow-timeout = "30s"1867 - [profile.integration]1868 - filter = 'test(integration::) or test(cli::) or test(tui::)'1870 - slow-timeout = "30s"1874 - slow-timeout = "120s"1877 - ### 17.6 Property Tests 1879 - Required 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.1888 - Commit `proptest-regressions/`.1890 - ### 17.7 Snapshot Tests 1892 - Use `insta` + ratatui `TestBackend` for:1895 - - layout composition,1899 - - config parse output,1900 - - provider normalization.1902 - CI runs with `INSTA_UPDATE=no`.1904 - ### 17.8 Integration Tests 1906 - Required 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.1915 - Fixtures live under `tests/fixtures/` with plugins, sessions, configs, providers,1920 - Criterion 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`,1930 - ## 18. Prototype Policy 1932 - Prototypes are disposable evidence for or against this spec. They live under1933 - `prototypes/`, never in production crates. A prototype tests one claim or risk,1934 - runs minimal commands, and reports whether the spec should change.1936 - Prototype output must include:1941 - - spec issues with evidence,1942 - - artifacts created,1944 - - next spec/design actions.1946 - Production code must not depend on prototype artifacts.315 + ## Documentation and help 317 + Public Rust and Lua APIs are documented.318 + Lua SDK declarations are the source for generated plugin help.319 + Every public event and function has one discoverable usage description.320 + Generated help is checked against the exposed SDK so neither can silently drift.324 + The remote model and provider response content are untrusted.325 + Project-local executable behavior is untrusted until approved.326 + Installed user plugins are user-approved but remain sandboxed.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.338 + Smith does not depend on confirmation dialogs as its primary security boundary.340 + ## Performance and portability 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.351 + Smith supports current Windows, macOS, and Linux on x86_64 and ARM64 where Rust and required native dependencies support the target.352 + OpenBSD x86_64 is best effort.353 + Release archives include versioned binaries and SHA-256 checksums.355 + ## Acceptance criteria 357 + Smith 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
xtask/src/main.rs Modified +1 / −1 text lines
142 142 denied: &'static [&'static str ], denied: &'static [&'static str ],145 - fn dependency_rules () -> &'static [DependencyRule] {145 + const fn dependency_rules () -> &'static [DependencyRule] {147 147 DependencyRule { DependencyRule {148 148 crate_name: "smith" , crate_name: "smith" ,