Metadata-Version: 2.5
Name: siwah
Version: 1.0.4
Summary: Self-improving coding agent harness CLI
Project-URL: Homepage, https://github.com/zidanmubarak/siwah
Project-URL: Repository, https://github.com/zidanmubarak/siwah
Project-URL: Issues, https://github.com/zidanmubarak/siwah/issues
Project-URL: Changelog, https://github.com/zidanmubarak/siwah/blob/main/CHANGELOG.md
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: fastapi>=0.115.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.9.0
Requires-Dist: rich>=13.9.0
Requires-Dist: tomli-w>=1.0.0
Requires-Dist: tree-sitter-javascript>=0.23.0
Requires-Dist: tree-sitter-python>=0.23.0
Requires-Dist: tree-sitter-typescript>=0.23.0
Requires-Dist: tree-sitter>=0.25.0
Requires-Dist: typer>=0.15.0
Requires-Dist: uvicorn>=0.32.0
Provides-Extra: dev
Requires-Dist: pyright>=1.1.390; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Provides-Extra: lsp
Requires-Dist: nodejs-wheel>=24.0.0; extra == 'lsp'
Description-Content-Type: text/markdown

# siwah

Self-improving coding agent harness CLI. Built from scratch in Python for the
core/daemon/evolution/eval and TypeScript (OpenTUI + Solid) for the TUI.

**Status: Phase 10 implementation, with open conformance gaps.** The
[2026-11-17 audit](docs/AUDIT-2026-11-17.md) records verified reliability fixes
and incomplete evolution, trust-boundary, and UI acceptance criteria; passing
mock tests is not proof that every phase requirement is met.
The [2026-11-18 enforcement migration](docs/KERNEL-ENFORCEMENT-2026-11-18.md)
protects evaluator/promotion/rollback ownership and separates candidate execution
from grading; delayed boot recovery and production canary/idle admission remain open.
Phase 10 adds an opt-in command sandbox, parallel best-of-N worktrees, an ACP
stdio bridge, release artifacts, and a TestPyPI-first release runbook. The wheel
is published on TestPyPI; production PyPI remains pending approval. The Phase 2
terminal matrix is recorded in `docs/TUI_MATRIX.md`;
Windows Terminal, tmux and SSH are verified. Phase 2 is closed with a
user-approved exception for macOS Terminal and iTerm2 (not tested).

## Requirements

- Python 3.11+ with [uv](https://docs.astral.sh/uv/)
- Bun 1.3.14+ only for the Phase 2 TUI and TypeScript eval checks; not needed
  for `siwah run`, `siwah serve`, or Python-only evals
- An OpenAI-compatible provider, or an OpenCode Go subscription

## Install

### One-line bootstrap (recommended)

The repository is private, so the one-liner uses the GitHub CLI. Install
[`gh`](https://cli.github.com/) once and run `gh auth login`. The bootstrap
installs `uv` and Bun when missing, clones the repository to `~/.siwah/src`,
installs the editable `siwah` tool, and builds the TUI binary.

Windows PowerShell:

```powershell
gh api repos/zidanmubarak/siwah/contents/scripts/install/bootstrap.ps1 -H "Accept: application/vnd.github.raw" | Out-String | Invoke-Expression
```

macOS/Linux:

```bash
gh api repos/zidanmubarak/siwah/contents/scripts/install/bootstrap.sh -H "Accept: application/vnd.github.raw" | bash
```

Open a new terminal and run `siwah`. The checkout in `~/.siwah/src` is what
`/update` and `siwah update --apply` fast-forward.

### Manual checkout

```bash
git clone https://github.com/zidanmubarak/siwah.git
cd siwah
uv sync --extra dev
uv tool install --force --editable .
cd ui/tui
bun install --frozen-lockfile
bun run build
cd ../..
siwah --version
```

`--editable` is intentional: the TUI source stays discoverable, so `/update` can
fast-forward the checkout and rebuild the binary. The compiled TUI is written to
`ui/tui/dist/siwah-tui[.exe]` and is found automatically.

### From a wheel

For development inside this repository:

```bash
uv sync --extra dev
uv run siwah --version
```

To use a prebuilt wheel from any directory:

```bash
uv tool install --force ./dist/siwah-1.0.4-py3-none-any.whl
mkdir -p ~/.siwah/bin
cp ./dist/siwah-tui-windows-amd64.exe ~/.siwah/bin/siwah-tui.exe  # adjust per platform
siwah --version
```

`uv tool install` creates the `siwah` shim in the uv tool bin directory
(usually `~/.local/bin` on Unix and `%USERPROFILE%\.local\bin` on Windows).
Run `uv tool update-shell` if that directory is not on PATH. The wheel does not
contain the large TUI binary; `siwah` searches `SIWAH_TUI_BINARY`,
`~/.siwah/bin/siwah-tui[.exe]`, the executable directory, PATH, and finally the
repository's `ui/tui/dist` directory. Without a binary, use
`siwah run "..." --ui plain`.

## Connect a provider

On first run, siwah creates `~/.siwah/harness/config.toml` automatically with
`opencode-go` and `openai` provider templates (mode 600). Start the TUI and run
`/connect`; it lists those providers, and the key is stored in
`~/.siwah/auth.json` (mode 600). No manual config edit is required.

Model IDs, prices, and limits are read from the provider's live models endpoint;
they are never hardcoded. If you want a different OpenAI-compatible provider or
a permanent CLI role, edit `~/.siwah/harness/config.toml` and add a block such as:

```toml
[providers.my-provider]
api = "openai_chat"
base_url = "https://example.invalid/v1"
models_url = "https://example.invalid/v1/models"
auth = { scheme = "bearer", env = "MY_PROVIDER_API_KEY" }

[roles]
main = "my-provider/<model-id>"
```

Legacy `~/.siwah/config.toml` files are migrated into the harness directory on
first load. `siwah auth login` remains available for terminals where `/connect`
is not used. Credentials come from the configured environment variable first, then the
auth file.

## Use

```bash
siwah                                   # TUI; starts the daemon if needed
siwah run "Fix the failing test in this repo" --permission yolo
siwah run "Plan the refactor" --effort max --auto
siwah --allow-all                       # TUI with auto-approved tools
siwah run "Summarize the project" --json
siwah run "..." --ui plain
siwah serve
siwah models list --provider opencode-go
siwah models probe opencode-go/<model-id>
siwah skills list
siwah skills view <name>
siwah memory show
siwah trace <session-id> --json
siwah openapi > openapi.json
```

The TUI needs Bun 1.3.14+ or a compiled `siwah-tui` binary. `siwah` searches
`SIWAH_TUI_BINARY`, `~/.siwah/bin/siwah-tui[.exe]`, the executable directory,
PATH, and the repository's `ui/tui/dist` directory; it falls back to Bun source
only when the repository source is present.

The redesigned TUI has a Siwah/Rencong-inspired pixel welcome emblem, stable
streaming, compact tool cards, split/unified diffs, task progress, dismissible
notices and scrollable dialogs. Use PageUp/PageDown to browse without moving
prompt focus, Ctrl+End to follow the latest output, Ctrl+O or `/tools` for tool
details, and `/todos` for the plan. Permissions support a full preview (`v`) and
denial with a reason (`d`). Verification and local-build preview instructions:
[TUI redesign checkpoint](docs/phases/TUI-REDESIGN-2026-11-18.md).

`siwah run` uses the permission mode `ask` by default. In a non-interactive run,
use `--permission auto-edit` for file edits, `--permission yolo` for shell
commands too, or the `--auto`/`--bypass` alias. `--effort
minimal|low|medium|high|xhigh|max` sets `reasoning_effort` for models that
support it. In the TUI, `/effort` opens a picker with the values advertised by
the current model (`low`/`high`/`max`, etc.) and persists the choice in
`[agent].effort`; `/permissions` cycles `ask` → `auto-edit` → `yolo` (the
`AUTO` badge appears in `yolo`). Start the TUI directly in bypass mode with `siwah --allow-all`
(alias `--bypass`); the path guard and catastrophic-command denial remain
active. In `yolo` mode, destructive workspace commands such as `rm -rf build`
run without a prompt; commands that target the filesystem root, disks, or
shutdown are still denied.

Long interactive runs have **no step cap by default** (`[agent].interactive_max_steps = 0`).
They continue until the agent finishes, you cancel, the provider allowance is
exhausted, or the stall guard detects repeated unproductive steps. Setting
`[agent].interactive_max_steps` to a positive value opts into an initial budget
with progress-based extensions up to `[agent].max_steps_ceiling`. Explicit
`siwah run --max-steps`, eval, and subagent budgets remain hard limits. This
matches the usual interactive-agent behavior: a step counter is not a silent
deadline. The todo list is restored on the next message and reconciled before a
final answer, and the task panel reflects the persisted list when the run ends.

`siwah eval` keeps an explicit measurement budget (default 8 steps for
screening); raise `--max-steps` for a fuller benchmark. That is a deterministic
evaluation budget, not an interactive deadline.

You can submit another prompt while the current run is still working. The daemon
queues it (up to 16 per session), the activity line shows `N queued`, and the
next prompt starts automatically when the current run finishes. `Esc` cancels
the active run and clears that session's queue. The queue is in memory, so it is
not preserved across a daemon restart.

Sessions live in the global `~/.siwah/state.db`, but the TUI lists the current
project by default. The top bar shows the project's sessions as tabs: click a
tab to switch, click `×` to close it (running sessions must stop first), and a
spinner marks a running tab. The active model and effort are shown in the status
bar; update notices appear only on the welcome screen.

The prompt box reports context-window usage for the active model (for example
`ctx 42.1k/1M 4%`). The number follows `context` events and is not overwritten
by usage refreshes, so it does not flicker mid-run. The context manager
auto-compacts at 95% by default; the prompt box changes to a warning color and
adds `compact` at that threshold.
`/compact` remains available for a manual summary. Paste text normally, or
paste an image with `Ctrl+V` (or a binary image paste from the terminal) to
attach up to four images to the next message. Each image inserts an
`[Image N]` token and a `file <name>` chip; copying a screenshot file preserves
its filename, and pasting a local image path is converted to an attachment
instead of leaving the path as text. The task panel can be hidden with its `×` button and restored
from the `tasks n/m ▸` status-bar control; long plans scroll inside the panel
with a `↕` indicator. `jump latest ↓` sits above the prompt box on the right.
Assistant markdown tables use aligned columns and a single header rule rather
than a grid, so wrapped cells cannot break the border.

A new session tab takes its title from the first prompt immediately, without
waiting for the run to finish. Tool cards show at most four output lines and
diff cards at most two changed lines; click the card or the `click to expand`
hint to see the rest. Diff line numbers use separate old/new columns so one
hunk stays visually contiguous.

Prompt history is persisted per project in
`~/.siwah/prompt-history.json` (mode 600), so `Ctrl+R` survives restarts and
imports user prompts from the last opened project session.

## Update

The TUI checks the git upstream after startup and shows `↑ vX.Y.Z` in the top
bar when `pyproject.toml` on `origin/<branch>` has a newer version. `/update`
(or `siwah update --apply`) fast-forwards the checkout, reinstalls TUI
dependencies, rebuilds the binary, and asks you to restart siwah. The new binary
is staged as `siwah-tui[.exe].next` and activated by the next `siwah` launch,
because Windows cannot replace a running executable. The check is cached for six
hours and stays quiet when the network or private-repo credentials are
unavailable; `siwah update --refresh` forces a fresh check.

Updates use the normal git credential helper, never an embedded GitHub token. A
checkout with local changes is refused so user edits are not overwritten. A
wheel-only install can still see the notification, but applying it requires the
editable checkout above.

## Harness data, memory, and skills

On first use siwah seeds a git-backed harness under `~/.siwah/harness/`:

- `prompts/system.md` — editable base system prompt with `{{workspace}}`,
  `{{memory}}`, `{{skills}}`, `{{tool_guidance}}`, `{{agents_md}}` and
  `{{model_overlay}}` placeholders.
- `tool_guidance/*.md` — guidance appended to the prompt deterministically,
  including the harness-format guide and a turn-efficiency guide that asks the
  model to batch independent tool calls and keep reasoning concise.
- `skills/<name>/SKILL.md` — agentskills.io-style skills; only name and
  description enter the prompt, while `skill_view` loads the body on demand.
- `commands/<name>.md` — custom slash commands; the body may use `$ARGUMENTS`.
- `subagents/<name>.md` — custom subagents invoked through the `task` tool.
- `profiles/<provider>__<model>/` — capability profiles and optional
  `system_append.md` overlays.
- `config.toml` — provider/auth/role/permission configuration.

Project-local harness files live under `<repo>/.siwah/` and override the global
entries with the same name. This is siwah's equivalent of `.opencode/`:

```text
my-project/
├─ .siwah/
│  ├─ skills/<name>/SKILL.md      project-only skills
│  ├─ subagents/<name>.md         project-only subagents
│  ├─ commands/<name>.md          project-only slash commands
│  ├─ project.md                  project memory (created by /init)
│  └─ plan.md                     plan mode output
├─ AGENTS.md                      repo instructions (also read from parents)
└─ ...
```

Start siwah with the project root as the working directory; discovery uses the
session cwd. A project file wins over a global file with the same name. A
command or subagent file created during a run is usable immediately: the TUI
reloads the command list when an unknown command is entered, and the subagent
manager reloads specs before every `task` call. `siwah doctor` prints the
project-local skill/subagent/command counts when a `.siwah/` directory exists,
so you can verify what the agent sees.

Use project-local entries for repository-specific procedures and global entries
for reusable defaults. The benchmark-style request to write an exact path under
`~/.siwah/harness/` still wins; do not duplicate it into `.siwah/` unless the
task asks for project scope.

Memory is layered: `~/.siwah/memory/user.md` for durable user preferences,
`<repo>/.siwah/project.md` for project memory, and
`~/.siwah/memory/quick.md` for `#` notes. Memory is curated, not a transcript
dump: use `# note` for a quick inbox entry, ask the agent to remember a durable
preference, or run `/init`. `/init` creates `.siwah/project.md` and sends a
guided prompt that updates both `AGENTS.md` and project memory. When a prompt
contains an explicit memory cue (`ingat`, `remember`, `selalu`, `always`,
`never`, etc.), the agent gets one completion nudge to call `memory_write`
before finishing. The agent writes through `memory_write`, creates and patches
skills through `skill_manage`, and searches old sessions with `recall`;
`AGENTS.md` is read from the workspace and every parent directory.
Memory/skill writes are size-limited, reject credential-like content, and recall
snippets are redacted. `/memory` shows the three files and explains this.

Checkpoint and context commands are intentionally distinct: `/undo` restores the
checkpoint immediately before the latest step, `/rewind N` targets N steps back
and can fork the session, and `/compact` summarizes the model context without
changing the visible transcript (the toast reports before/after tokens).

## Verifier, checkpoints, and plan mode

Phase 4 adds a project verifier. Put a `verify.toml` at the workspace root to
override auto-detection:

```toml
[commands]
test = "pytest -q"
lint = "ruff check ."
typecheck = "pyright"
```

Without it, Python, JS/TS, Go, and Rust projects are detected. Verifier output is
fed back to the model after edits; a new failure triggers a bounded repair loop
and an unexplained final claim ends with `verification_failed`. Set
`[verify].auto = false` to disable it.

Each session gets a shadow git repository under
`~/.siwah/checkpoints/<session-id>/`. The user's `.git` is not modified. The TUI
`/checkpoints` panel lists snapshots; Enter restores one after confirmation, and
`f` forks the session from it. `/undo` and `/rewind [n]` restore prior states.

Large tool output is offloaded to
`~/.siwah/tool_outputs/<session>/<call>.txt`; the model sees a handle and can
reopen it with `tool_output`. `/compact` persists a structured context summary.
`/plan` enters read-only plan mode, writes `<repo>/.siwah/plan.md`, and
`/execute-plan` sends the edited file back in build mode. The `refs` tool uses a
detected LSP server (pyright, TypeScript, gopls, rust-analyzer, or clangd) when
available and falls back to git grep/ripgrep; `SIWAH_LSP=off` forces the
fallback. The optional `lsp` extra (`uv sync --extra dev --extra lsp`) installs
a bundled Node runtime for environments without system Node.

## Evaluation

`evals/` is protected evaluation data: 30 golden tasks, 10 heldout tasks, and
three traps covering reward hacking, prompt injection, and destructive
requests. Golden tasks cover bug fixes, features, refactors, tests, multi-file
changes, comprehension, and tool hygiene in Python and TypeScript. Heldout
reports expose aggregate metrics only.

```bash
siwah eval --suite golden                  # full deterministic mock suite
siwah eval --suite golden --baseline       # also run the fixed naive baseline
siwah eval --suite golden --tier t0        # structural validation only
siwah eval --suite heldout                 # aggregate-only heldout score
siwah eval --suite traps                   # guard and injection traps
siwah eval --suite golden --only golden-verifier-01 --baseline --no-cache
```

Each task runs in a fresh temporary workspace. Reports include pass rate, steps,
tokens, allowance, duration, tool-error rate, cache-read ratio, and guard/trap
results. JSON reports are written under `~/.siwah/eval/reports/`; the baseline
cache lives under `~/.siwah/eval/cache/`.

Mock runs are deterministic and cost no allowance. Live evaluation is opt-in:
set `SIWAH_LIVE=1`, pass `--live --max-allowance <amount>`, and use a real
`--model`. The default eval step limit is 8; use `--max-steps 16` or higher for
live models. `--write-budget` writes the calibrated allowance and wall-time
ceilings from a complete live run into `[budget]` in the config, preserving the
other sections. Mock measurements and runs stopped at the allowance cap cannot
calibrate the budget.

## Kernel and supervisor

`src/siwah/kernel/`, `evals/`, `tests/kernel/`, and `kernel.manifest.json` are
protected from agent writes. The kernel provides the path guard, manifest,
audit, snapshot, budget, and supervisor primitives.

```bash
siwah kernel manifest --write   # human-only: regenerate after kernel/eval edits
siwah kernel verify             # check the committed SHA-256 manifest (CRLF/LF stable)
siwah rollback [tag]            # restore protected paths from a healthy tag
siwah audit --limit 20          # newest hash-chained audit events
```

Healthy boots create annotated `kernel-healthy-<hash12>` git tags signed with
an HMAC key at `~/.siwah/supervisor.key` (override with
`SIWAH_SUPERVISOR_KEY`). Unsigned or forged tags are ignored. Rollback checks
out only the protected paths and leaves the rest of the workspace untouched. The
normal launcher starts `siwah supervise`, which verifies the manifest, starts
`siwah serve`, and rolls back after two consecutive failed boots. The supervisor
passes a one-boot token and challenge nonce to the daemon and verifies an HMAC
proof on `/v1/health`; `runtime.json` never contains the nonce. Failed boots are
logged to `~/.siwah/logs/daemon.log`, and both the launcher and the daemon PID
are stopped so a stale process cannot hold the port. `siwah serve` remains
available for direct debugging. The daemon picks an ephemeral free port by
default; if `[server].port` or `--port` is busy, it falls back to a free port,
writes the actual port to `runtime.json`, and retries a bind race up to three
times. An unrelated local server on a fixed port (for example a Python script
on 8765) therefore cannot block siwah startup.

Audit events live in `~/.siwah/audit.jsonl`; budget state lives in
`~/.siwah/budget-state.json`. The `[budget]` governor enforces cycle/day,
cooldown, per-cycle allowance, wall-time, and an optional weekly reserve; the
weekly limit is a provider fact supplied by the caller, not hardcoded.

## Subagents, MCP, hooks, and jobs

`task` launches isolated child sessions. `explore` and `review` are read-only;
`general` can implement; custom specs live in `~/.siwah/harness/subagents/*.md`.
Children cannot launch further children, and read-only task batches can run in
parallel.

MCP servers are configured in `~/.siwah/harness/mcp.json` and can be managed
without editing JSON:

```bash
siwah mcp add filesystem --command "npx -y @modelcontextprotocol/server-filesystem C:/work"
siwah mcp add remote --url https://example.com/mcp --header "Authorization=Bearer ..."
siwah mcp list --tools
siwah mcp status                 # connected / error, tool count, latency
siwah mcp test filesystem
siwah mcp show filesystem        # secret header/env values are redacted
siwah mcp remove filesystem
```

The TUI `/mcp` command lists configured servers with their connection status,
tool count, and latency. Select a server and press Enter to reconnect it; a
disconnected server is restarted in place.

The agent can add or remove servers through the same `mcp` tool
(`action=add`/`remove`), so a chat request such as "add the filesystem MCP
server with this command" can set it up without hand-editing JSON. In `ask` or
`auto-edit` mode the permission dialog shows the exact command/URL before
`mcp.json` is written; `yolo` auto-approves it. `action=status` checks whether
each configured server connects and reports its tool count and latency.

The `mcp` tool lists tool names/descriptions lazily, fetches a schema on demand,
and calls tools over stdio or streamable HTTP. Stdio servers can set `env` and
`cwd`; HTTP servers can set headers. The client sends the MCP session id,
`MCP-Protocol-Version`, the initialized notification, follows tool pagination,
and surfaces `isError` results as tool failures. Resources, prompts, sampling,
and server-initiated requests are out of scope. Treat every MCP description and
result as untrusted data.

`siwah doctor` reports checkpoint/trajectory counts, orphaned session artifacts,
the daemon log size, harness git changes, and configured MCP servers. Remove
artifacts for sessions that no longer exist in `state.db` with
`siwah clean --sessions --dry-run` first, then `siwah clean --sessions --yes`;
`siwah clean --logs` rotates a large `daemon.log`.

Hooks live in `~/.siwah/harness/hooks/*.json` and receive JSON on stdin. A
`PreToolUse` hook can deny a call; `PostToolUse` and session hooks can add
context. Custom slash commands live in `~/.siwah/harness/commands/*.md` or
`<project>/.siwah/commands/*.md` and are merged into the TUI palette.

`bash` accepts `background=true`; `jobs` lists, tails, and kills those
process-local jobs. On Windows the tool uses Git Bash when available, so POSIX
shell syntax works consistently; `cmd.exe` is only a fallback. Long-running
server/watch commands are rejected unless `background=true`. `siwah trace
<session>` shows per-step model, latency, token, allowance, and tool trace data.
Escalation is opt-in through `[escalation]` and emits a visible event when it
switches models.

## Evolution (Level 0–1)

Level 0–1 evolution changes harness data under `~/.siwah/harness/`, never the
kernel, evals, permissions, or tests. The loop observes recent sessions,
reflects through a `training=false` model, proposes a harness candidate, probes
it, gates the result, commits and tags `evo-N`, then watches a canary.
The canary monitor is persistent, but production session sampling is not yet
connected; automatic post-session rollback is not an end-to-end guarantee.

```bash
siwah evolve                 # refuses non-seed operation without --live
siwah evolve --seed          # deterministic cold-start synthetic cycle
siwah evolve --live --model provider/model --max-allowance 0.05
siwah evolve --live --seed --probe-limit 2   # cheap live smoke
siwah evolve --pause         # pause before the next cycle
siwah evolve --resume
siwah evolve log             # recent evolution audit events
```

`--live` requires `SIWAH_LIVE=1`, a real model, and a positive per-probe
`--max-allowance`; it copies the harness into a temporary home and runs the real
eval suite at T1/T2. Without `--live`, only explicit `--seed` may use the
deterministic rubric prober; it is a smoke fixture, not coding-quality evidence.
The TUI `/evolve` panel summarizes and groups audit events (candidate, gate
result, pause/resume, rollback), shows whether automatic evolution is paused,
and supports `r` rollback and `p` pause/resume. `/rollback` needs a previous
harness revision, so it reports a clear message until `/evolve` promotes a
candidate or the harness has an earlier commit.

Automatic evolution runs after a session when `[evolution].auto` is enabled,
there is an error/correction/tool-error signal, the minimum session count is
met, and the cooldown has elapsed. It spawns a separate `siwah evolve` process;
`SIWAH_EVOLVE=off`, `SIWAH_EVOLVE_AUTO=0`, and the pause file stop it.
The current automatic trigger does not opt into paid live evaluation and
therefore cannot silently promote through the synthetic gate. Cross-process
idle admission still needs a shared lease; keep automatic evolution disabled
while relying on the audit's safety constraints.

The weekly allowance is supplied explicitly because it is a provider fact:
`--weekly-allowance <amount>` or `SIWAH_WEEKLY_ALLOWANCE`. `SIWAH_EVOLVE=off` is
the kill switch. Promotion and rollback refuse dirty repositories rather than
discarding user edits. A blocked rollback needs human conflict resolution.
`siwah rollback evo-N` manually restores a harness tag. Model-specific overlays
with complex model names still have a gate/loader canonicalization gap; see
the audit before using them. Rendered system prompts are pinned when a
session first runs; this is not yet a snapshot of all harness/config state.

The TUI `/evolve` panel reads `/v1/evolution`, which combines persisted state
with hash-chained `evolve.*` audit events. The cold-start prober is a
deterministic rubric over a temporary harness copy; live model evaluation
remains opt-in and budget-limited. The gate scanner is conservative but
heuristic, not a formal policy verifier.

## Level 2 evolution (core code)

Level 2 patches target `src/siwah/` outside the kernel and are reviewed in an
isolated git worktree:

```bash
siwah evolve --patch-file fix-edit-file.diff
```

The gate rejects changes to `src/siwah/kernel/`, `evals/`, `ui/`,
`tests/kernel/`, or the kernel manifest; limits a candidate to 5 files and 200
changed lines; rejects removed lines under `tests/`; and scans added content for
credentials or guard relaxation. The default gate runs `pytest`, `ruff`,
`pyright`, a CLI smoke boot, and `siwah eval` T0–T3 in the worktree.
Evaluation/promotion/rollback authority is owned by the kernel. A common
protected inventory also covers necessary bootstrap/config/auth/profile loaders
and compatibility imports. Candidate agent code runs in a separate interpreter,
and promotion requires a one-use kernel approval bound to the checked candidate
and HEAD. These are application-level controls, not an OS sandbox.

A passing candidate is committed and tagged `evo-core-N` (the harness evolution
uses `evo-N`). A post-promotion boot check and supervisor restart follow; a
failure attempts a non-discarding reset to the previous commit, deletes the candidate tag,
and audits the rollback. The main repository must be clean before promotion.
Dirty/conflicting rollback is reported as blocked. Delayed daemon boot failures
still require a pending-core recovery journal; do not infer that guarantee from
the protected-tree snapshot mechanism. After human changes to protected code,
review/commit the protected baseline deliberately before production rollout;
matching the working-tree manifest alone does not authorize an uncommitted tree.

## Sandbox, best-of-N, and ACP

The command sandbox is opt-in through `[sandbox]`. Docker is used when an image
is configured, bubblewrap is used on Linux when available, and the local
fallback is explicitly labelled as non-isolated. Docker/bwrap disable network by
default. `bash` runs through the sandbox when enabled.
Direct `!` shell and verifier commands use the configured sandbox too. Verifier
commands require their own shell approval, even in `auto-edit` mode.
Background commands with a configured sandbox currently fail closed rather
than falling back to an unsandboxed host job.

```toml
[sandbox]
enabled = true
backend = "docker"      # auto, docker, bwrap, or local
image = "alpine:3.20"   # any image with the project's runtime
network = false
```

Docker and bubblewrap run commands with `sh -lc`, including when the host is
Windows; the host's `cmd` is only used by the local fallback. A timed-out Docker
command is killed and its container is removed. The image must contain the
project's toolchain, so use a project-specific image for real work.

`siwah run --ultra N` runs N attempts in separate git worktrees and applies the
first passing attempt to a clean main worktree. It is explicit, parallel, and
does not silently spend allowance.

`siwah acp` starts an Agent Client Protocol v1 stdio bridge for editors:
initialize, session/new, session/prompt, session/cancel, and session/update.
Requests requiring `ask` approval are denied because client permission dialogs
are not implemented; explicitly allowed policy operations can still run.
Filesystem/terminal methods are not advertised yet. `siwah run --json` and
the daemon OpenAPI remain the headless/SDK surface.

## Build a release

```bash
uv run python scripts/build-release.py
```

This creates a wheel, a platform-specific TUI binary, and `dist/SHA256SUMS`.
The current source is `1.0.4`; public releases are distributed from the
public GitHub repository. Tag releases as `vX.Y.Z`; the update
checker reads `pyproject.toml` on the upstream branch and falls back to semver
tags. See `docs/RELEASING.md` for the release steps.

To share a test build with someone, create a bundle:

```bash
uv run python scripts/package-bundle.py
```

This writes `dist/siwah-<version>-<platform>-<arch>.zip` with the wheel, TUI
binary, `SHA256SUMS`, and installers. The recipient extracts it and runs
`install.ps1` on Windows or `install.sh` on macOS/Linux. Bundle users update by
rerunning the installer; checkout users get the in-TUI `/update` flow.

## Architecture

- `src/siwah/harness/` — harness bootstrap, prompt composition, memory, skills.
- `src/siwah/providers/` — config-driven adapters, streaming, tool calls, usage
  and allowance accounting, record/replay fixtures, capability profiles.
- `src/siwah/core/` — agent loop, SQLite sessions, verifier, checkpoints,
  context pruning/compaction, message/trajectory storage.
- `src/siwah/repo/` — gitignore-aware file index, tree-sitter symbols, repo map.
- `src/siwah/eval/` — protected fixture loader, deterministic mock and naive
  harnesses, temp-workspace runner, cache, metrics, budget, and reports.
- `src/siwah/kernel/` — protected guard, manifest, audit, snapshot, budget,
  gate, and supervisor primitives.
- `src/siwah/adapt/` — observer, reflector, proposer, tiered prober, composer,
  promoter, canary, Level 2 worktree gate, best-of-N, and evolution engine.
- `src/siwah/sandbox.py` — Docker/bubblewrap command sandbox with local fallback.
- `src/siwah/acp.py` — Agent Client Protocol v1 stdio bridge.
- `src/siwah/tools/` — read/edit/search/bash/todo/web plus memory/skill/recall,
  repo-map, tool-output, task, jobs, MCP, and syntax validation tools.
- `src/siwah/mcp/` — stdio/HTTP JSON-RPC client and lazy MCP tool manager.
- `src/siwah/hooks.py` — JSON-contract local hook runner.
- `src/siwah/jobs.py` — process-local background job manager.
- `src/siwah/commands.py` — custom harness slash-command loader.
- `src/siwah/permissions/` — application-level path guard and permission rules.
- `src/siwah/server/` — local FastAPI HTTP + SSE protocol and OpenAPI.
- `ui/tui/` — OpenTUI + Solid terminal interface; generated API types and tests.
- `docs/DESIGN.md` and `docs/PROTOCOL.md` — design and contract.
- `docs/SDK.md` — headless, daemon API, and ACP integration surfaces.
- `docs/RELEASING.md` — artifact build and TestPyPI-first release steps.
- `docs/DECISIONS.md` — architecture decision log.
- `docs/TUI_MATRIX.md` — verified terminal matrix and open checks.
- `docs/TUI_MATRIX_RUNBOOK.md` — manual macOS/iTerm2 checklist and helper scripts.
- `docs/tui/matrix/` — committed terminal-matrix captures.

## Honest security limitation

The path guard is an **application-level guard**. A deliberately malicious
`bash` command can still write outside the workspace unless the opt-in sandbox
is configured with Docker or bubblewrap. The local sandbox fallback is not
isolation. Evolution runs in a separate process and Level 2 patches are gated in
worktrees, but this is not a claim of full sandboxing. Do not treat it as such.

## Development

```bash
uv run ruff check .
uv run pyright
uv run pytest
# Docker sandbox integration (pulls the image once; Linux shell + workspace mount)
SIWAH_TEST_DOCKER=1 uv run pytest tests/test_sandbox.py -k docker_sandbox
cd ui/tui && bun install && bun run typecheck && bun run test && bun run bench
uv run python scripts/build-release.py
```

Generated OpenAPI types are committed under `ui/tui/src/api/schema.d.ts`; CI
regenerates them and fails on drift.

## License

MIT.
