1 # CLAUDE.md
2
3 This file provides guidance to AI coding agents when working with code in this repository.
4
5 ## What this is
6
7 `sigit` ("siGit Code") is a single Rust binary: a local-first AI coding agent that runs LLM
8 inference on-device (via the `onde` crate / GGUF models) or against a hosted/OpenAI-compatible
9 endpoint. It exposes itself two ways from the *same* binary, chosen at startup by whether stdin
10 is a TTY:
11
12 - **ACP mode** (stdin not a TTY): speaks the Agent Client Protocol over stdio for editor
13 integration (Zed, VS Code ACP Client). Cross-platform.
14 - **Interactive terminal mode** (stdin is a TTY): a full-screen ratatui chat UI. **Unix-only**
15 it relies on fd redirection to keep logs out of the TUI, so Windows gets ACP mode only.
16
17 Before the TTY/ACP split, `main` also dispatches the account subcommands `sigit login`,
18 `sigit logout`, `sigit whoami` (see `src/main.rs` `main()`).
19
20 ## Working in this repo
21
22 **IMPORTANT — branch naming:** Name every working branch after the *changes it contains*, not
23 after a task, ticket, or session id. Use a short, descriptive, kebab-case slug so the branch is
24 self-explanatory from its name alone (e.g. `claude/agent-tools-multiedit-glob-todos-remember`,
25 not `claude/task-q003hm`).
26
27 **IMPORTANT — pull request target:** Always open pull requests against the `development` branch,
28 never `main`. `main` is release-only; `development` is where day-to-day work integrates.
29
30 **IMPORTANT — run CI before pushing:** Run the full CI gate locally and confirm it is green
31 *before* pushing a branch or opening a pull request — never push work that fails these:
32
33 ```sh
34 cargo fmt -- --check # formatting
35 cargo clippy --tests -- -D warnings # lint (warnings are errors)
36 cargo test --locked # tests
37 ```
38
39 ## Build / test / lint
40
41 ```sh
42 cargo build # debug build
43 cargo build --release # release binary at target/release/sigit
44 cargo run # launches interactive TUI (stdin is a TTY)
45 cargo test # CI runs: cargo test --locked --target <target>
46 cargo clippy --tests -- -D warnings # CI gate: clippy is -D warnings on all 4 targets
47 cargo fmt -- --check # CI gate (edition 2024)
48 ```
49
50 CI (`.github/workflows/ci.yml`) runs fmt + clippy + test across four targets:
51 `aarch64-apple-darwin`, `x86_64-apple-darwin`, `x86_64-unknown-linux-gnu`,
52 `x86_64-pc-windows-msvc`. Clippy is `-D warnings`, so warnings fail the build.
53
54 Run a single test: `cargo test <test_name>`.
55
56 ## Critical platform constraint: `#[cfg(unix)]` dead code
57
58 The interactive client, the `InferenceBackend` seam (`backend.rs`), and provider resolution
59 (`provider.rs`) are wired up **only** through `#[cfg(unix)]` code paths. On Windows the binary
60 runs ACP-only and drives `onde` directly, so much of `backend.rs` and `provider.rs` is
61 legitimately unused there and the dead-code lint is suppressed *on non-Unix targets only*.
62
63 Consequence: code can pass clippy on macOS/Linux but fail on the Windows target (or vice versa).
64 When touching `backend.rs`, `provider.rs`, or the interactive path, keep the `cfg` gates intact —
65 don't "fix" an unused-warning by deleting code that's live on Unix.
66
67 ## Architecture
68
69 The agent loop is backend-agnostic. The flow: a turn (messages + tool specs) goes to an
70 `InferenceBackend`, which returns assistant text and/or tool calls; the loop executes tools and
71 feeds results back. Neither the loop nor ACP/TUI surfaces depend on a concrete backend.
72
73 - **`src/main.rs`** — entry point, mode dispatch, the full ACP `Agent` impl (session lifecycle:
74 new/load/fork/prompt/cancel, config options, slash-command advertisement), and the `SYSTEM_PROMPT`
75 (note: it bakes in smbCloud-specific context the agent should use when the repo is clearly
76 smbCloud, and stay general otherwise).
77 - **`src/backend.rs`** — the `InferenceBackend` trait and neutral types (`ToolSpec`, `ToolCall`,
78 `ToolResult`, `TurnResult`). Two impls: `LocalBackend` (on-device via `onde::ChatEngine`) and
79 `OpenAiBackend` (any OpenAI-compatible HTTP endpoint).
80 - **`src/provider.rs`** — decides *which* backend serves inference. Resolution order, first match
81 wins: (1) override via `OPENAI_BASE_URL`+`OPENAI_API_KEY` or active profile in
82 `~/.config/sigit/providers.toml`; (2) siGit Code Cloud when logged in; (3) on-device.
83 - **`src/tools.rs`** — agent tool schemas + execution: `read_file`, `create_directory`,
84 `list_directory`, `search_files`, `glob`, `read_website`, `create_file`, `edit_file`,
85 `multi_edit`, `delete_file`, `run_command`, `write_todos`, `remember`. Add a tool in both the
86 spec list (`all_tools`) and the execute `match` (`execute_tool`).
87 - **`src/skills.rs`**[Agent Skills](https://agentskills.io) support. Discovers skill
88 folders (each with a `SKILL.md`: YAML frontmatter `name` + `description`, then Markdown
89 instructions) from `.sigit/skills/` and `.claude/skills/` in the cwd, `$SIGIT_CONFIG_DIR/skills/`,
90 and `~/.claude/skills/`. Progressive disclosure: the discovery list (name + description) is
91 baked into the dynamically-built `skill` tool's description, and activating a skill (the model
92 calls `skill` with a name) loads the full `SKILL.md` body. The `skill` tool is appended in the
93 `*_as_specs`/`build_tool_specs` layer (not in `all_tools()`) so its description can be dynamic,
94 and only when at least one skill exists.
95 - **`src/mcp.rs`**[Model Context Protocol](https://modelcontextprotocol.io) *client*. Connects to
96 MCP servers over the **Streamable HTTP** transport (one JSON-RPC POST endpoint; replies are
97 `application/json` or SSE), runs the `initialize`/`tools/list` handshake, and forwards `tools/call`.
98 Discovery is best-effort at startup (`mcp::init`, called from both branches of `main()`) and cached
99 in a process-global so the synchronous spec builders (`mcp::tool_specs`) and the async dispatch
100 (`mcp::call_tool`) can both read it. Tools are namespaced `mcp__<server>__<tool>`, appended in the
101 `*_as_specs`/`build_tool_specs` layer and routed in `tools::execute_tool` via `mcp::is_mcp_tool`. The
102 official server (`<cloud>/mcp`, default `https://sigit.si/api/v1/mcp`) is baked in and authed with the
103 cloud session token; extra servers live in `mcp.toml` (global `$SIGIT_CONFIG_DIR/mcp.toml` and
104 project-local `.sigit/mcp.toml`). stdio transport is not supported.
105 - **`src/permissions.rs`** — tool permission policy. Every tool call passes through
106 `decision_for` before executing: read-only tools always run; mutating tools (and all
107 `mcp__*`/unknown tools) are governed by, in order: per-session plan mode (`/plan` — deny all
108 mutating tools with a present-a-plan message), session "always allow" grants, per-tool
109 overrides and the default mode from `[permissions]` in `settings.toml` (`allow`/`ask`/`deny`,
110 default `ask`; `SIGIT_PERMISSIONS` env overrides the default). On `ask`, the ACP path sends
111 `session/request_permission` (allow once / allow for session / deny) and the TUI pauses the
112 inference task on a y/a/n prompt. Note: ACP turn-affecting handlers run in `cx.spawn`ed tasks
113 serialized by `SiGitAgent::turn_lock` so the dispatch loop can route the client's permission
114 answer mid-turn — don't move them back inline, and don't await client requests from inline
115 handlers (deadlock).
116 - **`src/instructions.rs`** — project instruction files, the always-on counterpart to skills.
117 Reads `AGENTS.md` (the cross-tool [agents.md](https://agents.md) standard) and `CLAUDE.md`,
118 walking from the session cwd up to the repo root (nearest ancestor with `.git`, never above it),
119 plus a global file under `$SIGIT_CONFIG_DIR`. Files are ordered outermost-first so the deepest
120 (most specific) wins. The combined block is injected via `session_context_message` in `main.rs`
121 — pushed as a system message at every ACP session entry point (new/load/fork + model switch)
122 and appended to the system prompt on the cloud and TUI-startup paths.
123 - **`src/chat.rs`** — the Unix-only ratatui TUI. Loading-spinner phase then chat; uses
124 `tokio::select!` to multiplex terminal events with streaming tokens.
125 - **`src/setup.rs`** — model cache location, local model discovery, selected-model persistence.
126 Must run (`setup_shared_model_cache`) *before* anything touches `ChatEngine`/`hf-hub`, since
127 those read env vars once at init.
128 - **`src/account.rs`** — siGit Code Cloud auth (`/login`, `/logout`, `/whoami`); authenticates
129 against the account API and stores a session token. Performs no console I/O.
130 - **`src/credentials.rs`** — local session-token store (TOML, `0600` on Unix).
131 - **`src/models.rs`** — model-picker types shared across platforms.
132
133 Slash commands (`/help`, `/models`, `/skills`, `/mcp`, `/login`, `/logout`, `/whoami`, `/reload`,
134 `/plan`, `/permissions`, `/clear`, `/status`) are advertised via `advertise_commands` in `main.rs`
135 and handled in both the TUI and ACP sessions.
136
137 ## Model cache (macOS)
138
139 On macOS the HF model cache lives in an App Group container shared with the siGit desktop app:
140 `~/Library/Group Containers/group.com.ondeinference.apps/models/`. Other platforms fall back to
141 `~/.cache/huggingface/`. The CLI reuses a model the desktop app already downloaded. First run
142 downloads a GGUF model (~1–2 GB) from Hugging Face.
143
144 ## Logging
145
146 In TTY (interactive) mode, *all* output — `log`, `tracing`, stray `println!` — is redirected to
147 `$TMPDIR/sigit.log` so the ratatui surface stays clean; the TUI holds a separate fd to the real
148 terminal. In ACP mode, stdout is reserved for protocol JSON and logs go to stderr. Control
149 verbosity with `RUST_LOG`.
150
151 ## Relevant env vars
152
153 `OPENAI_BASE_URL` / `OPENAI_API_KEY` (provider override), `SIGIT_API_URL` (account API base,
154 default `https://sigit.si`), `SIGIT_CLOUD_URL`, `SIGIT_CONFIG_DIR` (default `~/.config/sigit`),
155 `SIGIT_MODEL`, `SIGIT_MCP` (`off` disables MCP), `SIGIT_MCP_OFFICIAL` (`off` drops the baked-in
156 server), `SIGIT_PERMISSIONS` (`allow`/`ask`/`deny` — overrides the default permission mode for
157 mutating tools; the escape hatch for clients without permission-request support),
158 `HF_HOME` / `HF_HUB_CACHE`, `RUST_LOG`.
159
160 ## Releasing
161
162 Version lives in `Cargo.toml`. The binary is published to five registries via separate workflows
163 (`release-crates`, `release-github`, `release-homebrew`, `release-npm`, `release-pypi`); the
164 `npm/` and `pypi/` dirs hold the wrapper-package templates. Update `CHANGELOG.md` for releases.