sheperd 0.1.0-beta.3 → 0.1.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +1172 -108
  2. package/assets/index/grammars/SHA256SUMS +8 -0
  3. package/assets/index/grammars/SOURCES.json +61 -0
  4. package/assets/index/grammars/licenses/tree-sitter-go.LICENSE +21 -0
  5. package/assets/index/grammars/licenses/tree-sitter-java.LICENSE +21 -0
  6. package/assets/index/grammars/licenses/tree-sitter-javascript.LICENSE +21 -0
  7. package/assets/index/grammars/licenses/tree-sitter-python.LICENSE +21 -0
  8. package/assets/index/grammars/licenses/tree-sitter-rust.LICENSE +21 -0
  9. package/assets/index/grammars/licenses/tree-sitter-typescript.LICENSE +21 -0
  10. package/assets/index/grammars/licenses/web-tree-sitter.LICENSE +21 -0
  11. package/assets/index/grammars/tree-sitter-go.wasm +0 -0
  12. package/assets/index/grammars/tree-sitter-java.wasm +0 -0
  13. package/assets/index/grammars/tree-sitter-javascript.wasm +0 -0
  14. package/assets/index/grammars/tree-sitter-python.wasm +0 -0
  15. package/assets/index/grammars/tree-sitter-rust.wasm +0 -0
  16. package/assets/index/grammars/tree-sitter-tsx.wasm +0 -0
  17. package/assets/index/grammars/tree-sitter-typescript.wasm +0 -0
  18. package/assets/index/grammars/web-tree-sitter.wasm +0 -0
  19. package/assets/index/queries/go.scm +21 -0
  20. package/assets/index/queries/java.scm +16 -0
  21. package/assets/index/queries/javascript.scm +34 -0
  22. package/assets/index/queries/python.scm +16 -0
  23. package/assets/index/queries/rust.scm +32 -0
  24. package/assets/index/queries/typescript.scm +41 -0
  25. package/assets/reviewers/prompts/verifier.md +1 -1
  26. package/assets/session/prompts/chat.md +19 -0
  27. package/assets/session/prompts/compact.md +39 -0
  28. package/assets/session/prompts/verify-ops.md +19 -0
  29. package/assets/skills/prompts/skills-index.md +13 -0
  30. package/dist/THIRD_PARTY_LICENSES.md +13901 -107
  31. package/dist/main.js +237645 -81189
  32. package/package.json +5 -5
package/README.md CHANGED
@@ -1,20 +1,774 @@
1
- # rewire
2
-
3
- An anti-slop coding harness. You give it a task; it writes a contract and a set of tests first,
4
- freezes them, lets a model implement against them inside a sandbox, then blocks the result on
5
- hard gates and an independent multi-model review before it commits anything to a branch. It never
6
- reports "verified" on the strength of a model's say-so.
1
+ <p align="center">
2
+ <img src="docs/assets/rewire-banner.svg" alt="rewire: the anti-slop coding harness. Tests first, frozen, sandboxed, independently reviewed." width="100%">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/sheperd"><img alt="npm" src="https://img.shields.io/npm/v/sheperd?label=npm%20%C2%B7%20sheperd&color=3ee6b0&labelColor=0b1020"></a>
7
+ <a href="https://github.com/Abubakarjutt/sheperd/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/Abubakarjutt/sheperd/actions/workflows/ci.yml/badge.svg"></a>
8
+ <img alt="Platforms: macOS and Linux" src="https://img.shields.io/badge/platforms-macOS%20%C2%B7%20Linux-7cb4ff?labelColor=0b1020">
9
+ <img alt="Models: Claude, OpenAI, Ollama" src="https://img.shields.io/badge/models-Claude%20%C2%B7%20OpenAI%20%C2%B7%20Ollama-f6b94c?labelColor=0b1020">
10
+ <a href="LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-9aa6bd?labelColor=0b1020"></a>
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="#quick-start"><b>Quick start</b></a> ·
15
+ <a href="#how-a-run-works"><b>How it works</b></a> ·
16
+ <a href="#choosing-models"><b>Models</b></a> ·
17
+ <a href="#usage"><b>Usage</b></a> ·
18
+ <a href="#known-v01-limitations"><b>Limitations</b></a>
19
+ </p>
20
+
21
+ ---
22
+
23
+ You give rewire a task. It writes a contract and a set of tests **first**, freezes them, lets a
24
+ model implement against them **inside a sandbox**, then blocks the result on **hard gates** and
25
+ an **independent multi-model review** before it commits anything to a branch. It never reports
26
+ "verified" on the strength of a model's say-so.
7
27
 
8
28
  It works with Claude, OpenAI models and local models through [Ollama](https://ollama.com).
9
29
 
10
- **Status: v0.1, TypeScript only.** The 20-task anti-slop benchmark in [`bench/`](bench/README.md)
11
- exists and its scorer is unit-tested, but **it has not been run against real models yet**. There
12
- are no measured pass rates, and nothing here should be read as a claim about how often rewire
13
- catches slop. The release checklist ([`docs/v0.1-release-checklist.md`](docs/v0.1-release-checklist.md))
14
- lists what must hold on a live run before v0.1 is called released.
30
+ > [!NOTE]
31
+ > **Status: v0.1 beta, TypeScript repositories only.** The 20-task anti-slop benchmark in
32
+ > [`bench/`](bench/README.md) exists and its scorer is unit-tested, but **it has not been run
33
+ > against real models yet**. There are no measured pass rates, and nothing here should be read as
34
+ > a claim about how often rewire catches slop. The release checklist
35
+ > ([`docs/v0.1-release-checklist.md`](docs/v0.1-release-checklist.md)) lists what must hold on a
36
+ > live run before v0.1 is called released.
37
+
38
+ ## Why rewire
39
+
40
+ Coding agents are fast, and they are very good at producing work that _looks_ done: tests that
41
+ assert nothing, a fix that special-cases the one input in the bug report, an error swallowed so
42
+ the suite goes green, a test quietly edited until it passes. rewire is built so that none of
43
+ those can reach your branch on the model's word alone.
44
+
45
+ | The usual failure | What rewire does instead |
46
+ | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
47
+ | The agent edits the tests until they pass | Tests are written before the code, checked red, then **frozen and hashed**. Changing one fails a gate. |
48
+ | "All tests pass", but the tests assert nothing | Every test must make an assertion; the harness proves the runner enforces it with its own probe test. |
49
+ | The model grades its own homework | Reviewers and the verifier come from a **different model family** than the implementer whenever one is available. |
50
+ | The agent runs anything on your machine | Every write and command goes through **`rewire-sandbox`** (bubblewrap on Linux, `sandbox-exec` on macOS), with credential files denied. |
51
+ | "Done!" with nothing to show for it | A run is either `verified` (committed to `rewire/<runId>` with an evidence report) or escalated to you with the reason. |
52
+
53
+ ## Quick start
54
+
55
+ **1. Install** rewire (Node.js 22 or newer) and the tools its gates use:
56
+
57
+ ```sh
58
+ npm i -g sheperd # the package is "sheperd"; the command is "rewire"
59
+
60
+ # macOS
61
+ brew install ripgrep semgrep gitleaks
62
+
63
+ # Debian / Ubuntu (gitleaks: see "Installation in detail" below)
64
+ sudo apt-get install -y git ripgrep bubblewrap pipx && pipx install semgrep==1.186.0
65
+ ```
66
+
67
+ **2. Check your setup.** Every line should be a `✓`; each `✗` comes with the fix.
68
+
69
+ ```sh
70
+ rewire doctor
71
+ ```
72
+
73
+ **3. Give it a model.** With nothing configured, rewire uses what it finds:
74
+
75
+ ```sh
76
+ export ANTHROPIC_API_KEY=... # → anthropic:claude-sonnet-5-5
77
+ export OPENAI_API_KEY=... # → openai:gpt-5 (both set = cross-family review)
78
+ # or just have Ollama running with a model pulled: fully local, no key needed
79
+ ```
80
+
81
+ **4. Run a task** from the root of a clean git repository:
82
+
83
+ ```sh
84
+ cd my-typescript-project
85
+ rewire run "add a --json flag to the export command"
86
+ ```
87
+
88
+ Or open the interactive session and describe the task there (see "Interactive mode" below):
89
+
90
+ ```sh
91
+ rewire
92
+ ```
93
+
94
+ **5. Read the result.** A verified run (exit code `0`) is committed to the branch
95
+ `rewire/<runId>`; your current branch is never touched. The evidence report explains what was
96
+ checked and why it passed:
97
+
98
+ ```sh
99
+ git log --oneline rewire/<runId>
100
+ cat .rewire/runs/<runId>/report.md
101
+ ```
102
+
103
+ If the run escalates instead (exit code `2`), the same report says why and what it needs from
104
+ you. Add `.rewire/runs/`, `.rewire/worktrees/`, `.rewire/cache/` and `.rewire/sessions/` to your
105
+ `.gitignore`.
106
+
107
+ ## Interactive mode
108
+
109
+ Run `rewire` with no arguments in a terminal, from the root of a clean git repository:
110
+
111
+ ```sh
112
+ rewire # on a TTY: the interactive session
113
+ rewire chat # always the interactive session; exits 1 with tui_requires_tty without a TTY
114
+ ```
115
+
116
+ You chat with an agent that can read the repo, run sandboxed read-only commands and use skills.
117
+ It cannot write to your repo. When you want a code change, it proposes a task and you confirm it.
118
+ The change then goes through the same gated pipeline as `rewire run`, shown as a live stage board.
119
+ The chat model is the author model (`routing.spec`). Chats are saved to `.rewire/sessions/` and
120
+ can be resumed with `/resume`.
121
+
122
+ A sample session (colours left out):
123
+
124
+ ```
125
+ ╭──────────────────────────────────────────────────────────────╮
126
+ │ ✻ Welcome to rewire │
127
+ │ cwd: ~/src/shop │
128
+ │ chat: <author model> │
129
+ │ run: spec <author model> · impl <implementer> · review <rev> │
130
+ │ │
131
+ │ /help for commands · /run <task> for a gated change · @ to │
132
+ │ mention a file · esc to interrupt │
133
+ ╰──────────────────────────────────────────────────────────────╯
134
+ > why does export ignore the --limit flag? @src/export.ts
135
+ ● Read(src/export.ts)
136
+ ⎿ import { parseArgs } from "node:util";
137
+ … +118 lines
138
+ ✶ Pondering… (4s · ↓ ~310 tokens · esc to interrupt)
139
+ (the reply streams in as Markdown; code blocks are syntax-highlighted)
140
+ ╭──────────────────────────────────────────────────────────────╮
141
+ │ > add a --json flag to the export command │
142
+ ╰──────────────────────────────────────────────────────────────╯
143
+ <author model> · ctx 12.4k · checkpoints: contract,tests · chat ? for shortcuts
144
+ (Enter; the agent proposes the task)
145
+ ╭──────────────────────────────────────────╮
146
+ │ add a --json flag to the export command │
147
+ │ Run this as a gated task? [y/n] │
148
+ ╰──────────────────────────────────────────╯
149
+ (press y)
150
+ ╭──────────────────────────────────────────────────────────────╮
151
+ │ ✓ Spec contract ready │
152
+ │ ○ Tests │
153
+ │ ... │
154
+ ╰──────────────────────────────────────────────────────────────╯
155
+ ╭──────────────────────────────────────────────────────────────╮
156
+ │ Contract checkpoint: add a --json flag to the export command │
157
+ │ AC-1 [change] export --json prints the rows as JSON │
158
+ │ a approve · e revise · s stop │
159
+ ╰──────────────────────────────────────────────────────────────╯
160
+ (press a; the tests checkpoint shows a approve · v view · s stop)
161
+ ... tests, implement, gates, review ...
162
+ Run <runId> verified.
163
+ Branch: rewire/<runId>
164
+ ```
165
+
166
+ The header box shows the working directory and the models the chat and a run use. A tool call
167
+ shows as `● Name(args)` with the first lines of its result under `⎿`; a failed one is red with
168
+ `✗`. While a reply is in flight, the spinner line shows the elapsed time and the output tokens
169
+ so far (`~` while part of the count is estimated from streamed text). The status line under the
170
+ input shows the chat model, `ctx` (the size of the chat's context: the last chat model call's
171
+ input plus output tokens), the checkpoints, and what the session is doing (`chat`, `thinking`,
172
+ `run: <stage>` or `checkpoint: <kind>`). Only the chat streams; a gated run's stages do not.
173
+
174
+ By default a run pauses for your approval after the contract and after the tests. It does not
175
+ pause before the commit. Checkpoints and proposal cards take single keys, not typed lines. A
176
+ contract checkpoint takes `a` (approve), `e` (revise: type a note in the box that opens, Enter
177
+ sends it, Esc cancels it; at most 3 revisions, a 4th is treated as stop), `s` (stop) or `v`
178
+ (view every criterion, when there are more than fit on the card). The tests checkpoint takes
179
+ `a`, `v` (view the frozen tests) or `s`. The commit checkpoint, when on, takes `a`, `v` (view
180
+ the diff, coloured, with `+N −M` per file on the card) or `s`. In a view, ↑/↓ scroll a line,
181
+ PgUp/PgDn (or `b`/space) a page, `g`/`G` jump to the top or bottom, and `v` or Esc closes it.
182
+ Stopping ends the run with reason `stopped_by_user` (exit 2 semantics). Every decision is
183
+ recorded in `events.jsonl` and `report.md`. `rewire run` and `--headless` never pause.
184
+
185
+ ### Keys
186
+
187
+ | Key | What it does |
188
+ | -------------------------- | ------------------------------------------------------------------------ |
189
+ | Enter | Send the input. |
190
+ | Shift+Enter or `\` + Enter | Insert a newline. |
191
+ | ↑/↓ | Walk the input history. |
192
+ | Esc | Interrupt the chat reply in flight, or close the `/` menu or `@` picker. |
193
+ | Ctrl-C | Abort a run or a chat turn, or quit (see "Ctrl-C" below). |
194
+ | `?` (on an empty input) | Show or hide the shortcuts panel; any other key closes it. |
195
+ | `/` | Open the command menu. |
196
+ | `@` | Open the file picker. |
197
+
198
+ **Esc** stops the chat reply that is streaming. What already streamed stays on screen, followed
199
+ by `⎿ Interrupted by user`, and you can send again at once. The interrupted turn is not stored
200
+ in the session. Esc does not abort a gated run; Ctrl-C does that.
201
+
202
+ **The `/` menu** opens when the input starts with `/` (until the first space; `//` never
203
+ opens it). It lists the commands that match what
204
+ you typed (only the ones allowed during a run, while one is active). ↑/↓ move the selection.
205
+ Tab completes the selected name. Enter completes it too, or runs it when the name is already
206
+ complete and the command needs no arguments. Esc closes the menu and leaves the text as typed.
207
+
208
+ **The `@` picker** opens on an `@` at the start of the input or after a space. It lists the
209
+ repo's files (`git ls-files`, up to 5,000 paths) that match what follows the `@`. ↑/↓ move the
210
+ selection, Tab or Enter inserts the path (quoted when it holds a space, a quote or a
211
+ backslash), and Esc closes the picker. It only inserts the path text: the chat agent reads the
212
+ file with its own sandboxed tools. The `/` menu and the `@` picker stay closed while the input
213
+ takes a run's clarification answers, where `/` and `@` are typed literally (`/skip` still
214
+ works).
215
+
216
+ ### Slash commands
217
+
218
+ | Command | What it does | During a run |
219
+ | ------------------------------------------ | ---------------------------------------------------------------- | ------------ |
220
+ | `/run <task>` | Start a gated run directly, without proposing first. | no |
221
+ | `/skills` | Browse skills and their files; review pending repo skills. | browse only |
222
+ | `/checkpoints [contract] [tests] [commit]` | Show or set where runs pause. `/checkpoints off` pauses nowhere. | show only |
223
+ | `/model` (or `/models`) | Choose the model for each role (see "Choosing models"). | show only |
224
+ | `/resume [id]` | List stored sessions, or resume one. | no |
225
+ | `/compact [focus]` | Compact the chat context now (see "Context and compaction"). | no |
226
+ | `/context` | Show the compaction limit, window and session record. | yes |
227
+ | `/clear` | Start a fresh session. The old one stays resumable. | no |
228
+ | `/doctor` | Check prerequisites. | no |
229
+ | `/skip` | Decline a run's clarification questions. | yes |
230
+ | `/help` | List the commands. | yes |
231
+ | `/exit` | Quit. | no |
232
+ | `//text` | Send `/text` as chat text (a literal leading slash). | - |
233
+
234
+ While a run is active, the input box answers clarifications (one answer per line, `/skip` to
235
+ decline); checkpoints and proposals take single keys.
236
+
237
+ ### Ctrl-C
238
+
239
+ | When | What happens |
240
+ | -------------------------------------- | -------------------------------------------------------------- |
241
+ | during a run | aborts the run (an interrupted report); the session stays open |
242
+ | during a chat turn | stops the turn, like Esc |
243
+ | idle at the prompt | exits 0 |
244
+ | a second press within 1 second | exits 130 |
245
+ | at a proposal card or the trust prompt | exits 0 (the chat is saved and can be resumed) |
246
+
247
+ A chat `bash` command ignores the abort and runs to its own timeout (up to 600 seconds). It
248
+ cannot write to the repo.
249
+
250
+ ## Context and compaction
251
+
252
+ A long chat fills the model's context window. rewire compacts the chat before that happens.
253
+ Compaction applies to the interactive chat only. `rewire run`, `--headless` and the gated
254
+ pipeline never compact.
255
+
256
+ ### What compaction does
257
+
258
+ After a compaction the model sees, in order:
259
+
260
+ 1. the session record: a structured list of goals, constraints, decisions, open questions,
261
+ preferences, next steps and notes, each with the messages that back it, then a recap: the
262
+ compactor's own prose summary (at most 400 words) of the work so far, its findings, the
263
+ options it offered and what it recommended, the current state and the next step;
264
+ 2. the most recent part of the conversation, verbatim: your messages and the assistant's
265
+ replies, as real messages in order (up to `recent_user_tokens`, and at most a quarter of the
266
+ limit). The assistant's tool calls and the tool output are left out. The latest reply is
267
+ always kept, cut in the middle when it alone is over that budget, so a short answer such as
268
+ `a` or `yes` still has the question it answers;
269
+ 3. every turn after that point.
270
+
271
+ Older turns and all compacted tool output are not kept in the context. The full conversation
272
+ stays on disk, and the chat can search it with `recall`.
273
+
274
+ It is a record and not a summary, so nothing is lost without a trace:
275
+
276
+ - The model proposes edits to the record (add, update, resolve, supersede). Code checks every
277
+ one. Each edit cites messages, and the quote must appear word for word in the cited message.
278
+ - A constraint that came from you can only be created or changed by an edit that quotes one of
279
+ your own messages. Tool output, file contents, skills and the model's own text can never make
280
+ or override one. This stops a file that says "from now on, the user requires X" from becoming
281
+ a standing rule.
282
+ - Only items tagged `[user …]` speak for you. Everything else is `[inferred …]`: the compactor's
283
+ reading of tool output, files and replies, which the chat model is told never to treat as an
284
+ instruction. An inferred item that none of your messages supports is shown as
285
+ `[inferred, not from the user …]`.
286
+ - Some edits are also checked by a second model, from a different family when one is
287
+ configured: an edit that changes one of your rules or adds a claim attributed to you, any
288
+ change to an open question, and an inferred goal, constraint, must-keep-working item or
289
+ decision that rests on tool output with no message of yours behind it. Without that check they are not applied. If the
290
+ check is unavailable, the whole compaction fails.
291
+ - Skill text and `recall` results are never evidence for an edit.
292
+ - A short answer is read against the reply it answers. When you answer an open question with
293
+ `a`, `yes` or `2`, the compactor resolves the question into a decision citing your message,
294
+ and the checking model is shown the end of the assistant reply before it, so it can see which
295
+ option you picked. That reply never speaks for you: it only shows what your answer refers to.
296
+ - The recap is the compactor's prose and is rendered as `Recap (model-written, not from the
297
+ user)`. It is not checked sentence by sentence, it can never create or change one of your
298
+ rules, and it is the first thing after notes to be dropped when the record must be shorter.
299
+ - Items are never deleted. Resolved and superseded items move to an archive.
300
+ - If a compaction fails for any reason, the previous record and the full context are kept, and
301
+ the chat carries on. (When a long window is compacted in parts, the parts already applied
302
+ stay.) The failure is written to the session file as a `compaction_failed` line (its code, a
303
+ short reason and the sizes, never message text), and `/context` shows the latest one, also
304
+ after a resume.
305
+
306
+ The facts about files and commands (what was read, which commands ran and their exit codes,
307
+ which tool calls failed) are computed by code from the stored messages. The model does not
308
+ write them. Run outcomes are not part of the record.
309
+
310
+ ### When it triggers
311
+
312
+ The limit is a number of tokens. Compaction runs before a send when the next request would reach
313
+ it. For a context window `W`, the formula is:
314
+
315
+ ```
316
+ min(0.85·W, 32768·(W/32768)^0.6), rounded down to the thousand
317
+ ```
318
+
319
+ | window | trigger |
320
+ | ------ | ------- |
321
+ | 8K | 6000 |
322
+ | 32K | 27000 |
323
+ | 128K | 75000 |
324
+ | 200K | 97000 |
325
+ | 256K | 114000 |
326
+ | 1M | 262000 |
327
+
328
+ Large windows trigger well before they are full. Models read long prompts less reliably, and
329
+ every turn re-reads the whole context.
330
+
331
+ Other candidates:
332
+
333
+ - **Window share.** `0.85·W`, rounded down to the thousand.
334
+ - **Latency.** Once rewire has timed the model reading prompts (2 samples), that rate times
335
+ `latency_budget_s` (300 s by default), but never less than half the formula (or calibrated)
336
+ value. A slow local model compacts sooner, but not every few thousand tokens: with a prefix
337
+ cache a turn reads only what is new, so the full-context reading time is a pessimistic guide. A sample counts only the tokens the
338
+ server had to read: when a request starts with the whole previous one, a server with a prefix
339
+ cache (Ollama) reads only what was added, so rewire divides only that by the time to the first
340
+ streamed chunk (reasoning included). A read of under 1,000 new tokens is not a sample.
341
+ - **Calibrated.** `rewire calibrate` (below) measures how much context a model really uses.
342
+ The measured value replaces the formula, so it can be higher than the formula's value (a 200K
343
+ window that passes at 128K gives 131,072, not 97,000).
344
+
345
+ The smallest candidate wins. It is raised to at least 4,096 and then capped at `0.85·W`, so a
346
+ window under about 4.8K gets a limit below 4,096. A configured `limit` (below) replaces all of
347
+ this; it is at least 4,096 and is not capped. The window is asked of the provider (Ollama's
348
+ loaded context, or a built-in table for Anthropic and OpenAI).
349
+
350
+ Compaction aims to leave the context at no more than half the limit, with room for the message
351
+ being sent, keeping fewer recent messages (down to the latest reply alone) and then a shorter
352
+ record (down to 1,000 tokens, never to nothing) until it fits. Your own rules are never dropped
353
+ from the record, so when they alone are too big the compaction still applies.
354
+
355
+ When a compaction fails, or applies but cannot bring the context under its target, rewire falls
356
+ back to clearing the tool output of earlier turns from what the model sees, oldest first (the
357
+ same fixed stub as inside a turn, below). That needs no model call and changes neither the
358
+ record nor the stored messages. Only when even that cannot help is automatic compaction held
359
+ back (` · held`) or, past half-way from the limit to the window, turned off for the window
360
+ (` · stuck`). `/context` says which step is in effect.
361
+
362
+ ### Inside one turn
363
+
364
+ Compaction runs only between your messages, but one message can lead to many tool calls, and
365
+ a few large file reads can fill the context before the turn ends. So before each model call
366
+ inside a turn, when the context is over the limit, rewire clears this turn's older tool
367
+ results from what the model sees, oldest first, down to 60% of the limit, so the turn can add
368
+ several results before it has to clear again. The 2 most recent results are always kept whole,
369
+ and so is a result the model asked for again after it was cleared. A cleared result becomes a
370
+ fixed line:
371
+
372
+ ```
373
+ [tool output cleared to fit the context: read src/big.ts — 65536 chars. Run it again (with offset/limit for read) if you still need it, or use recall after this turn.]
374
+ ```
375
+
376
+ It names the call by the same safe summary the TUI shows (redacted, never the raw arguments).
377
+ A cleared result stays cleared for the rest of the turn, so the start of the prompt does not
378
+ change again and a prefix cache keeps working. The stored conversation keeps every result
379
+ whole, so `recall` finds it once the turn has ended, and the next turn starts from the full
380
+ history (which compaction then handles). So the status line's context size can drop during a
381
+ long turn and jump back after it, until compaction runs before your next message. The TUI shows
382
+ one dim line per clearing, for example
383
+ `⎿ cleared 3 earlier tool outputs to fit the context (75k limit)`.
384
+
385
+ **Prefill guard (Ollama).** A local model can read slowly: at 90 tokens a second a 107K-token
386
+ prompt takes about 20 minutes, which is past the reply timeout. Once rewire has measured the
387
+ chat model's reading speed, it checks each call: if the estimated prompt would take more than
388
+ 80% of the reply timeout to read, it clears more, down to only the most recent result. This and the
389
+ window check below may also clear earlier turns' tool output (never this turn's most recent
390
+ result). If even that is too large, the request is not sent and the turn ends at once with
391
+ `ollama_timeout`,
392
+ whose message starts `not sent:` and gives the estimated tokens, the measured speed and the
393
+ reading time against the reply timeout. Run `/compact`, ask for less at a time
394
+ (read with offset and limit), or raise the reply timeout. The guard counts the whole prompt,
395
+ even when part of it may be cached, because Ollama does not keep the cache of a very large
396
+ prompt reliably.
397
+
398
+ **Never past the loaded window.** A server cuts a prompt longer than the context it loaded the
399
+ model with from the front, which drops the system prompt and the record first. So before each
400
+ call rewire checks the estimate against 85% of the model's loaded window (re-read from Ollama
401
+ after the first turn and after a reload). Over it, it clears tool output from earlier turns as
402
+ well as this one, oldest first, down to 60% of the limit. If the request still does not fit
403
+ (one message alone can be too large), it is not sent: the turn ends with `context_overflow`.
404
+
405
+ ### `models.toml`
406
+
407
+ ```toml
408
+ [compaction]
409
+ latency_budget_s = 300 # 5 to 3600; seconds to read a full context
410
+ recent_user_tokens = 20000 # 1000 to 200000; your recent messages kept verbatim
411
+
412
+ [compaction.models."ollama:qwen3:32b"]
413
+ limit = 24000 # integer, at least 4096; replaces every computed candidate
414
+ ```
415
+
416
+ All keys are optional. Unknown keys are an error (`models_file_invalid`).
417
+
418
+ ### Commands and the status line
419
+
420
+ | Command | What it does |
421
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
422
+ | `/compact [focus]` | Compact now. The optional focus tells the compactor what to keep. Not available during a run. Esc cancels. |
423
+ | `/context` | Show the limit and how it was chosen, the window, the record counts, the tokens the code tools saved this session (once they saved some), the last compaction, the recovery step in effect and the latest failure, and the record itself. Scroll with the arrow keys, Esc closes. |
424
+
425
+ The status line shows `ctx 61k/74k (f)`: the context size, the limit, and why the limit is that
426
+ value: `f` formula, `l` latency, `c` calibrated, `w` window share, `o` override. The size is dim,
427
+ turns yellow at 70% of the limit and red at 90%. A dim ` · held` means automatic compaction is
428
+ waiting for the context to grow by a quarter of the limit before it tries again. ` · stuck` means
429
+ automatic compaction is off for this window, because a failed or over-budget compaction left the
430
+ context at or past halfway from the limit to `0.85·W`. `/compact` still works then, and a
431
+ changed window clears it.
432
+
433
+ Lines you may see:
434
+
435
+ - `⎿ compacted 41 messages → record (3 decisions · 2 constraints · 1 open) · ctx 72k → 9k`
436
+ - `⎿ 2 proposed changes rejected: <first reason>…` (the checks refused some edits; the rest applied)
437
+ - `⎿ compaction skipped: <code> — kept full context (/context for details)`
438
+ - `⎿ automatic compaction paused: <reason> — /compact to retry`
439
+ - `⎿ note: compaction checks use the same model family as chat (no independent verifier configured)`
440
+
441
+ ### `recall`
442
+
443
+ The chat has a read-only `recall` tool. It searches the whole stored conversation and the
444
+ archive for a word or phrase, so a detail that left the context can be found again. Results are
445
+ at most 10 snippets and 4 KB, are cleaned of secrets, and are fenced as untrusted data. Only the
446
+ chat has it, never a pipeline stage, and a compaction never cites its results as evidence.
447
+
448
+ ### `rewire calibrate`
449
+
450
+ ```sh
451
+ rewire calibrate <provider:model> [--max <tokens>] [--yes] [--models <file>] [--fresh]
452
+ ```
453
+
454
+ The formula is a guess. `calibrate` measures. It sends probes of growing length (8K, 16K, 32K
455
+ and so on, up to 0.95 of the window or `--max`, which takes `N` or `Nk`). Each probe is filled
456
+ with varied text with facts planted through it, and the model has to answer five questions about
457
+ them. A probe passes with 4 of 5 right. The effective context is the longest length that passes
458
+ along with every shorter one. The run stops after two failures in a row.
459
+
460
+ On a local model this is slow: each long probe can take minutes, and a full run can take an hour
461
+ or more. Calibration never runs by itself.
462
+
463
+ - **Resume.** Each length is saved as soon as it finishes, under the XDG cache directory. Ctrl-C
464
+ stops the run after the lengths already recorded (exit 130; a second Ctrl-C force-quits), and
465
+ the same command continues from the saved lengths. A failed run exits 1
466
+ (`calibration_failed`). `--fresh`
467
+ measures everything again.
468
+ - **Stale runs.** The result is tied to the model's digest and window. If the window changes by
469
+ more than 10%, the result is stale: `/context` warns, the trigger stops using it, and
470
+ `calibrate` measures again. An endpoint's result is kept by `<endpoint>:<model>`, not its
471
+ `base_url`: after pointing an endpoint at another server, run `calibrate --fresh`.
472
+ - **Truncation.** If the provider read far fewer tokens than were sent (under 60%), the probe is
473
+ not scored and the run fails with `calibration_failed`. For Ollama, the hint is to raise
474
+ `OLLAMA_CONTEXT_LENGTH` (for example 65536) on the server, or set `num_ctx` in a Modelfile.
475
+ - **Provider errors.** An error is not a score. The run is marked incomplete and the failed
476
+ length is tried again next time. An incomplete run is never used.
477
+ - **Paid providers.** For every provider except Ollama, the faux provider and an endpoint on a
478
+ loopback `base_url` (Anthropic, OpenAI, Bedrock, Vertex, Foundry, Azure, Gemini, any other
479
+ endpoint), `calibrate` prints the probe list and an input-token estimate (a token count, not a
480
+ price), then exits without spending. Add `--yes` to run. Ollama and loopback endpoints need no
481
+ flag.
482
+
483
+ ## Skills
484
+
485
+ Interactive mode can use Claude-style skills (`<name>/SKILL.md`).
486
+
487
+ - **User skills** load automatically from `~/.claude/skills` and `$XDG_CONFIG_HOME/rewire/skills`
488
+ (default `~/.config/rewire/skills`). A user skill wins over a repo skill with the same name.
489
+ - **Repo skills** (`<repo>/.claude/skills`) load only after you approve them. The approval is
490
+ stored once per repo, pinned to a sha256 over all the skills' files, in
491
+ `$XDG_CONFIG_HOME/rewire/trusted-skills.json`. If any file changes, rewire asks again. The
492
+ prompt also lists repo skills shadowed by a user skill, because they are part of the hash.
493
+ - Skills are read once per session. A skill you trust mid-session takes effect when the session
494
+ is rebuilt: after `/clear` or `/resume`, or a `/model` pick that changes the chat model or the
495
+ verifier.
496
+ - `/skills` lists every skill found, with its source (`user` or `repo`) and state (`active`,
497
+ `pending trust`, `trusted; takes effect in a new session (/clear)` or `shadowed`), active ones
498
+ first. Enter shows a skill's description, path and the files in its directory now. A
499
+ symlinked skill directory is followed once and shown as `linked → <real path>`; links inside
500
+ it are listed, never followed. Esc goes back, then closes. When repo skills
501
+ are pending, a first row, "Review pending repo skills", opens the trust prompt. During a run
502
+ the list is read-only, that row is absent, and a checkpoint or clarification closes the list.
503
+ - A skill that is rejected (malformed, over a limit, or a repo skill with a symlink) is skipped
504
+ and shown as a warning line when the session starts.
505
+ - Skills are given to the chat, the spec stage, the test writer and the implementer. The
506
+ reviewers and the verifier never get them. Skill text can still reach a reviewer indirectly if
507
+ an author stage copies it into the contract or the diff.
508
+
509
+ Limits: `SKILL.md` up to 256 KiB. A repo skill directory up to 2 MiB and 200 files, with no
510
+ symlinks. A user skill directory up to 64 MiB and 5000 files; its symlinks are followed only to
511
+ targets inside your home directory that are not credential files.
512
+
513
+ ## Web access
514
+
515
+ The chat agent, the spec stage and the implementer (in every fix round too) have two tools,
516
+ `web_search` and `web_fetch`. Nothing else goes online: the test writer, the reviewers, the
517
+ verifier, compaction and its verifier never get the tools, and the frozen tests and the gates run
518
+ in the sandbox as before, with no network (the dependency audit's registry exception is
519
+ unchanged). The tools run in the rewire process, outside the sandbox. The sandbox's network
520
+ allowlist stays empty, so `bash` in the chat or the implementer still cannot reach the network.
521
+
522
+ Web access is on by default in `rewire` (chat) and `rewire run`. `web_fetch` needs no key. Without
523
+ a search backend, `web_search` returns a tool error that says what to set, and chat and runs work
524
+ as before. `.rewire/policy.toml` can turn web off (see below), and `rewire run --no-web` turns it
525
+ off for one run as a run-layer policy that no repository policy can turn back on. Faux-provider
526
+ runs (`REWIRE_FAUX_SCRIPT`) never get web access. The benchmark passes `--no-web` on every run
527
+ (see `bench/README.md`).
528
+
529
+ ### Search backends
530
+
531
+ | Backend | Setup |
532
+ | ---------------- | --------------------------------------------------------------------- |
533
+ | Ollama (default) | `OLLAMA_API_KEY`, a free key from ollama.com (its hosted search API). |
534
+ | Tavily | `TAVILY_API_KEY`. |
535
+ | Brave Search | `BRAVE_API_KEY` (sent as the `X-Subscription-Token` header). |
536
+ | SearXNG | Your own instance: `search = "searxng"` and `searxng_url`, no key. |
537
+
538
+ A SearXNG server must allow JSON output: add `json` to `search.formats` in its `settings.yml`
539
+ (a 403 means it does not).
540
+
541
+ With `search` unset, rewire uses the first of `OLLAMA_API_KEY`, `TAVILY_API_KEY` and
542
+ `BRAVE_API_KEY` that is set (a blank value counts as unset). An explicit `search` uses that
543
+ backend or says its key is missing; it never falls back to another one. Search requests never
544
+ follow a redirect, so a key is never sent to another host. `rewire doctor` shows which backend
545
+ and which env var it found (see [`rewire doctor`](#rewire-doctor)).
546
+
547
+ `models.toml`:
548
+
549
+ ```toml
550
+ [web]
551
+ search = "tavily" # "ollama" | "tavily" | "brave" | "searxng"; optional
552
+ searxng_url = "https://search.example" # https, or http on a loopback host; no credentials, query or fragment
553
+ max_results = 5 # 1 to 10, default 5
554
+ ```
555
+
556
+ An unknown key or a bad value fails with `models_file_invalid`.
557
+
558
+ ### Policy
559
+
560
+ `.rewire/policy.toml`:
561
+
562
+ ```toml
563
+ [web]
564
+ enabled = false # default true
565
+ deny_domains = ["pastebin.com"] # these hosts and their subdomains are refused
566
+ allow_domains = ["nodejs.org", "developer.mozilla.org"] # when set, only these and their subdomains
567
+ ```
568
+
569
+ The rules apply to every fetch target, every redirect hop, the search service itself, and the
570
+ result URLs `web_search` shows (hidden results are counted, as `N hidden by policy`). A query is
571
+ sent to the backend's host (`ollama.com`, `api.tavily.com`, `api.search.brave.com`, or your
572
+ SearXNG host), so once any layer sets `allow_domains`, `web_search` is refused unless that host
573
+ is in it, and a `deny_domains` entry matching it refuses it too. A refused fetch or search is a
574
+ tool error that names the rule, and `rewire doctor` shows it. Domains are bare host names (no scheme, port, path or `*.`), matched case-
575
+ insensitively, and `deny_domains` wins over `allow_domains`. A bad entry fails with
576
+ `policy_invalid`.
577
+
578
+ Layers only tighten. A later layer can turn web off but never back on (`policy_loosening`).
579
+ `deny_domains` is the union of all layers. The first layer that sets `allow_domains` sets it, and
580
+ each later one intersects with it. An empty `allow_domains` (`[]`, or layers with no domain in
581
+ common) allows nothing, so the tools are removed, as with `enabled = false`.
582
+
583
+ ### What a fetch may do
584
+
585
+ - Only `http` and `https`, URLs up to 2048 characters, no `user:password@`.
586
+ - **No private addresses.** Each host is resolved and refused if any address is loopback, private
587
+ (10/8, 172.16/12, 192.168/16, fc00::/7), link-local (169.254/16 including cloud metadata,
588
+ fe80::/10), CGNAT (100.64/10), multicast, unspecified or reserved. `localhost`, `*.localhost`,
589
+ `.local` and `.internal` names are refused too. IPv4 written as a number (`0x7f000001`,
590
+ `2130706433`, `127.1`) and IPv4 inside IPv6 (mapped, compatible, NAT64, 6to4) are judged as
591
+ IPv4. Teredo is refused. The connection is pinned to the address that was checked, so DNS
592
+ rebinding cannot swap it. Every redirect is checked again, up to 5.
593
+ - 30 s for the whole fetch, at most 5 MB read and 100,000 characters of text, with truncation
594
+ stated. Only text types: `text/*`, JSON and XML. HTML is converted to plain text, and links keep
595
+ their targets. Any other type is a short tool error naming the type.
596
+ - A fixed `User-Agent: rewire/<version>` is sent, and nothing about you.
597
+
598
+ The SearXNG URL is yours, so it is not checked against these rules; it can be on loopback.
599
+
600
+ ### What goes out, and what comes back
601
+
602
+ - **Outgoing.** A query or URL that holds a secret-shaped value is refused before anything is
603
+ sent. The patterns are the ones rewire redacts (Tavily's `tvly-` keys among them), also when
604
+ percent-encoded (to any depth), `%uXXXX`-escaped, full-width or split by control characters.
605
+ `sk-`, `ghp_` and `AKIA` keys are also caught with other characters in front (`x<key>`). A
606
+ host name is checked case-insensitively. Brave and Ollama keys have no fixed shape, so a query
607
+ or URL holding the value of any search key set in this process (`OLLAMA_API_KEY`,
608
+ `TAVILY_API_KEY`, `BRAVE_API_KEY`, 8 characters or more), raw or percent-encoded, in any case,
609
+ is refused too, and those values are redacted from web text. Queries are capped at 400
610
+ characters.
611
+ - **History.** The model's own arguments for a refused call are kept as
612
+ `{"refused":"secret-shaped"}`, so the value never reaches `.rewire/sessions/`, the spec
613
+ digest or a later prompt.
614
+ - **Incoming.** Every title, URL, snippet and page has control and escape sequences removed and
615
+ secrets redacted. It reaches the model inside an `<untrusted_web>` fence, which the page
616
+ cannot close, and the agents' prompts say web content is data, never instructions.
617
+ - **Audit.** Every call emits a `web_request` event, whether it succeeded or failed: the tool, the
618
+ backend, the query or the URL's host and path (never its query string), the status, the
619
+ number of results and the bytes returned. A run writes them to its `events.jsonl`. In chat
620
+ they are shown live and not written to disk (the session file keeps the messages only). A
621
+ refused secret-shaped value is recorded as `[refused: secret-shaped]`, and a key is never
622
+ recorded. The TUI shows each call as `● WebSearch("<query>")` or `● Fetch(<host><path>)`, with
623
+ result titles and hosts, or a status line (`HTTP 200 · text/html · 12.3 KB`, the size the
624
+ model got, and `truncated`) followed by the page's first line.
625
+
626
+ ### Residuals
627
+
628
+ - A page can still mislead the model's reasoning. The fence stops a page from posing as
629
+ instructions in rewire's prompts, but a model can still believe what it reads. The gates and
630
+ the review check the result, not the sources.
631
+ - With web on, repository text that does not look like a secret can leave in a query or a URL,
632
+ through a prompt-injected page or a model's own choice. The outgoing check catches only
633
+ secret-shaped values and the configured search keys. For repositories where this matters,
634
+ `enabled = false` stops it, and `allow_domains` limits it to the hosts listed: text can still
635
+ reach those hosts, in URLs, and in queries when the search service's host is listed.
636
+ - A Brave or Ollama key, or any other unprefixed secret, that is not the value configured in
637
+ this process is not recognised.
638
+ - A key that has been re-encoded (base64, reversed, split across host labels, overlong UTF-8) is
639
+ not recognised.
640
+ - The outgoing check has false positives that fail closed: an `sk-` word followed by a word of
641
+ 20 or more letters (`ask-about-internationalization`) and host labels that start like an AWS
642
+ key id (`akia…`) are refused.
643
+ - Web text is NFKC-normalised, so full-width and other compatibility forms in a page reach the
644
+ model as their plain forms.
645
+ - `tool_call` summaries of other tools (a `bash` command, for one) are still logged with display
646
+ redaction only, so a key written with a prefix (`x<key>`) can appear there.
647
+ - A cancelled chat turn's web calls are still reported, because their requests went out.
648
+
649
+ ## Code navigation
650
+
651
+ Agents can find their way around a repository by its structure instead of reading whole files.
652
+ rewire has a built-in code index, with no model and no network involved. It is parsed with
653
+ Tree-sitter and refreshed before every query.
654
+
655
+ ### The tools
656
+
657
+ | tool | what it returns |
658
+ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
659
+ | `code_map` | A short map of the repository: directories with file counts and languages, entry points (package `bin`/`main`/`exports`, `index.*`), and the most-referenced files and symbols. It is about 1,500 tokens by default (`budget_tokens` from 200 to 6,000). |
660
+ | `outline` | Every definition in one file: kind, name, signature line, line range and first doc-comment line, nested. At most 400 entries, and it says when it cut some. |
661
+ | `symbol` | One definition's exact source (`name` or `Parent.name`). Other matches are listed best first: the asking file, then files it imports, then by references. A span over 200 lines comes back as its outline plus the `read` offset and limit to use. |
662
+ | `references` | Callers (the default) or callees of a function, grouped by the enclosing definition with `path:line`. At most 50 sites, with totals. Matching is **by name**, and the result says so. |
663
+ | `code_search` | A ranked search over symbol names (exact, then prefix, then fuzzy), file paths and doc comments. It falls back to a sandboxed ripgrep text search, grouped by enclosing definition, when no name matches. At most 30 results. |
664
+
665
+ **Who gets them:** the chat, the spec stage and the implementer get all five. The test-writer
666
+ gets only `code_map` and `outline`, which show declarations and never bodies, in keeping with its
667
+ rule not to read implementation bodies. Reviewers, the verifier and compaction never get any of
668
+ them. The tools are read-only. A failure (not a git repository, the sandbox binary missing or too
669
+ old) is a tool result that says to use `read`, `grep` and `find` instead, and those keep working.
670
+
671
+ **Outline-first `read`:** a `read` with no `offset` or `limit`, of a file over 300 lines in a
672
+ known language, returns:
673
+
674
+ 1. a one-line notice;
675
+ 2. the outline;
676
+ 3. lines 1 to 60;
677
+ 4. how to get the rest (`read` with an offset and limit, or `symbol`).
678
+
679
+ The outline is used only when the index record's sha256 matches the text the sandbox returned.
680
+ Otherwise the file is read as before. An explicit `offset` or `limit` always reads exactly
681
+ those lines. Files of 300 lines or fewer, and files in other languages, read as before.
682
+
683
+ **Tokens saved:** each answer estimates what a full `read` of the files it answered from would
684
+ have cost, minus its own size, and never goes below 0. `code_map` claims nothing, because a map
685
+ replaces no particular read. The estimate is the chat's token estimator, or characters / 4 in a
686
+ run.
687
+
688
+ - **In the chat:** the TUI shows a dim `⎿ ≈12.3k tokens saved by code navigation (2 calls)` line
689
+ after a turn that saved some, and `/context` lists the session's total.
690
+ - **In a run:** a run that used the tools logs one `tokens_saved` event per run in `events.jsonl`,
691
+ with a split by stage.
692
+
693
+ The tool calls show as `● Map`, `● Outline(src/x.ts)`, `● Symbol(name in src/x.ts)`,
694
+ `● References(name callers)` and `● Search("query")`, with the usual `⎿` preview.
695
+
696
+ ### What is indexed, and what never is
697
+
698
+ The file list is `git ls-files --cached --others --exclude-standard`, so `.gitignore` is respected.
699
+ git runs with the same hardening as the orchestrator: no hooks, no fsmonitor, no untracked cache,
700
+ and no system or global config. These are then dropped:
701
+
702
+ - **Sandbox-denied files.** Everything the `rewire-sandbox` binary would refuse to `read`. That
703
+ covers the policy's credential globs, `~/.ssh` and the like, and the repo's `.env` rules. The
704
+ binary decides, in one `check-paths` call per refresh. No glob is matched in TypeScript.
705
+ - **Symlinks.** Any path with a symlinked component, and symlinks themselves.
706
+ - **rewire's own state and git's.** `.rewire/` and `.git/`.
707
+ - **Big, binary or slow files.** Files over 1 MiB, binary files (a NUL in the first 8,000 bytes),
708
+ and files whose parse takes over 2 s.
709
+
710
+ A file the agent cannot `read` never appears in the map, an outline, a symbol, references or
711
+ search results. Names, signatures, doc comments and spans come from repository files. They are
712
+ stripped of terminal control sequences, redacted, capped at 48 KiB per result, and described to
713
+ the model as data, never instructions.
714
+
715
+ **Languages (v1):** TypeScript, TSX, JavaScript (including JSX), Python, Go, Rust and Java. A file
716
+ in another language is listed in the map and has no outline, and `read` reads it as before. The
717
+ grammars and the Tree-sitter runtime are pinned `.wasm` files shipped with rewire, with
718
+ `SHA256SUMS` and their MIT licences in `packages/index/grammars/`. They are checked by sha256
719
+ before they are loaded, and a mismatch is refused with `binary_missing`.
720
+
721
+ ### Freshness and storage
722
+
723
+ Before every query, the index re-checks the file list:
724
+
725
+ - **Changed files.** A file whose mtime or size changed is re-hashed. It is re-parsed only if its
726
+ content is new: records are keyed by content hash, so an unchanged or renamed file never
727
+ re-parses.
728
+ - **Deleted files** are dropped.
729
+ - **Same-session edits.** An edit, a new file or a deletion by the implementer is visible to its
730
+ very next query.
731
+ - **The first build** answers after at most 20 s with what it has indexed, says it is partial,
732
+ and goes on in the background. A repository the size of rewire itself (about 650 files) builds
733
+ in under a second.
734
+
735
+ **Where it lives:**
736
+
737
+ - **Chat sessions** keep the index in the repo's `.rewire/index/`. It is a run artifact like
738
+ `.rewire/runs/`, so it never makes a run's tree dirty.
739
+ - **A run** indexes its own worktree in a temporary store outside the worktree, removed when the
740
+ run ends.
741
+
742
+ ```sh
743
+ rewire index [--repo <path>] [--rebuild]
744
+ ```
745
+
746
+ `rewire index` builds or refreshes the repo's index now. It prints the number of files, a
747
+ count per language, the definitions, the time taken and how many files it parsed, and the store
748
+ size. It prints counts only, never a path or a line of any file. `--rebuild` clears
749
+ `.rewire/index` first, and refuses a `.rewire` or `.rewire/index` that is a symlink. Ctrl-C stops
750
+ the build with exit 130, and nothing is saved.
751
+
752
+ ### Limits
753
+
754
+ - `references` is name-based. `this.run()` and `obj.run()` match any `run`. Imports are used to
755
+ prefer one same-named definition over another, and aliased imports (`{ a as b }`) are not
756
+ followed. Each site says how it was tied to the definition (`via same file`, `import` or
757
+ `name`).
758
+ - Only the v1 languages above have outlines.
759
+ - A hard link inside the repository is judged by its own path, as `read` judges it.
760
+ - A very large repository is refused rather than half-indexed: a file listing that takes over
761
+ 30 s, or `check-paths` output over 16 MiB, makes the tools report the index unavailable. `read`,
762
+ `grep` and `find` still work.
763
+ - Plain `read` output is passed to the model raw, as before this feature. Only the code tools'
764
+ results and the outline part of an outline-first read are cleaned.
15
765
 
16
766
  ## How a run works
17
767
 
768
+ <p align="center">
769
+ <img src="docs/assets/rewire-pipeline.svg" alt="How a run works: spec, tests first (red check, then frozen), implement in a sandbox, gates, cross-family review, verified branch; findings loop back to the implementer, and a run that stops converging escalates to you." width="100%">
770
+ </p>
771
+
18
772
  1. **Spec.** The task becomes a contract (asking you clarifying questions if it is ambiguous):
19
773
  acceptance criteria, non-goals and affected areas. Each criterion has a kind: `change` (new or
20
774
  corrected behaviour) or `preserve` (behaviour that works today and the task says must keep
@@ -27,7 +781,10 @@ lists what must hold on a live run before v0.1 is called released.
27
781
  criterion id; these problems get one retry;
28
782
  - a test for a `preserve` criterion must pass. One that fails stops the run at once, never
29
783
  retried (`preserve_fails_now`), and asks you whether the criterion is mislabelled (really a
30
- `change`) or the test is wrong. A retry could only make it pass by weakening it;
784
+ `change`) or the test is wrong. A retry could only make it pass by weakening it. The
785
+ exception is a test that crashed in its own code rather than on an assertion (for example,
786
+ it called a function that does not exist): that is a test-writer mistake and gets the one
787
+ retry. An error thrown from the code under test still stops the run;
31
788
  - every test must make an assertion. The harness runs its own no-assertion probe test in the
32
789
  same run and stops (`assertion_rule_unenforced`) if the test runner does not fail it.
33
790
 
@@ -49,104 +806,21 @@ lists what must hold on a live run before v0.1 is called released.
49
806
  a re-plan, and escalation to you when it stops converging.
50
807
  7. **Result.** A verified run is committed to the branch `rewire/<runId>` with an evidence report.
51
808
 
52
- ## Install
53
-
54
- ### Install from npm
55
-
56
- rewire is published to npm as the package **`sheperd`** (pre-release, on the `next` tag). The
57
- command it installs is `rewire`:
58
-
59
- ```sh
60
- npm i -g sheperd@next
61
- rewire doctor
62
- ```
63
-
64
- The package carries the CLI as one bundled file plus a prebuilt `rewire-sandbox` for your
65
- platform, which npm installs automatically as an optional dependency
66
- (`sheperd-darwin-arm64`, `sheperd-darwin-x64`, `sheperd-linux-x64` or `sheperd-linux-arm64`).
67
- Supported platforms: macOS on Apple silicon or Intel, and Linux on x64 or arm64 with glibc 2.35
68
- or newer (Ubuntu 22.04, Debian 12 or later; musl distributions such as Alpine are not supported).
69
- Windows is not supported. If your npm install skips optional dependencies
70
- (`--omit=optional`, `--no-optional`), the sandbox binary is missing and `rewire doctor` says so.
71
-
72
- You still need these system tools on `PATH`: git,
73
- [ripgrep](https://github.com/BurntSushi/ripgrep), [semgrep](https://semgrep.dev),
74
- [gitleaks](https://github.com/gitleaks/gitleaks), and on Linux
75
- [bubblewrap](https://github.com/containers/bubblewrap) 0.8 or newer. macOS uses the built-in
76
- `sandbox-exec`. See the per-OS install commands below.
77
-
78
- ### Build from source
79
-
80
- Requirements: git, Node.js 22+, pnpm, a Rust toolchain (to build the sandbox helper),
81
- [ripgrep](https://github.com/BurntSushi/ripgrep), [semgrep](https://semgrep.dev),
82
- [gitleaks](https://github.com/gitleaks/gitleaks), and on Linux
83
- [bubblewrap](https://github.com/containers/bubblewrap) 0.8 or newer. macOS uses the built-in
84
- `sandbox-exec`. Windows is not supported. CI uses semgrep 1.186.0 and gitleaks 8.30.1, the
85
- versions the gates were developed against.
86
-
87
- ```sh
88
- # macOS
89
- brew install ripgrep semgrep gitleaks pnpm
90
-
91
- # Debian/Ubuntu
92
- sudo apt-get install -y git ripgrep bubblewrap pipx
93
- pipx install semgrep==1.186.0
94
- pipx ensurepath # then restart the shell so ~/.local/bin is on PATH
95
- # gitleaks: download the release for your platform from
96
- # https://github.com/gitleaks/gitleaks/releases/tag/v8.30.1
97
- # and put the `gitleaks` binary on PATH
98
- # pnpm: npm install -g pnpm (or corepack enable)
99
- ```
100
-
101
- Then build rewire from source:
102
-
103
- ```sh
104
- git clone <this repository> rewire && cd rewire
105
- cargo build --release -p rewire-sandbox
106
- pnpm install --frozen-lockfile
107
- pnpm -r build
108
-
109
- # put the CLI on PATH (or run `node "$PWD/packages/cli/dist/main.js"` directly)
110
- alias rewire='node '"$PWD"'/packages/cli/dist/main.js'
111
- ```
112
-
113
- The CLI looks for the sandbox binary in this order:
114
-
115
- 1. `REWIRE_SANDBOX_BIN` (a missing file is an error, never a fall-through);
116
- 2. the newer of `target/release/` and `target/debug/` in the checkout (source builds only; the npm
117
- package never looks for a checkout);
118
- 3. the `sheperd-<os>-<arch>` package installed next to the CLI (only there: never via `NODE_PATH`
119
- or other global folders). Its binary must match the sha256 recorded in the npm bundle at
120
- build time; a package whose binary is missing, not executable, modified, or of a different
121
- version than the CLI is an error, never a fall-through;
122
- 4. the first absolute `PATH` entry that has `rewire-sandbox`.
123
-
124
- `rewire doctor` reports exactly this lookup, including which step found the binary, and a run
125
- that cannot find the binary stops in preflight, before any model call.
126
-
127
- ## `rewire doctor`
128
-
129
- ```sh
130
- rewire doctor [--models <file>]
131
- ```
132
-
133
- Prints one line per check, `✓` or `✗` with a fix hint, and exits `0` when everything required is
134
- present or `1` otherwise. It checks: the sandbox binary, `git`, `rg`, `semgrep`, `gitleaks`,
135
- `bwrap` (Linux) or `sandbox-exec` (macOS), the model list, and, when any model is an Ollama model,
136
- that Ollama is reachable and at least version 0.6.4. Run it before your first `rewire run`.
137
-
138
809
  ## Usage
139
810
 
140
811
  ```sh
141
- rewire run "add a --json flag to the export command" [--repo <path>] [--models <file>] [--headless]
142
- rewire run --task-file task.md [--repo <path>] [--models <file>] [--headless]
812
+ rewire # interactive session (on a TTY)
813
+ rewire chat [--repo <path>] [--models <file>]
814
+ rewire run "add a --json flag to the export command" [--repo <path>] [--models <file>] [--headless] [--no-web]
815
+ rewire run --task-file task.md [--repo <path>] [--models <file>] [--headless] [--no-web]
816
+ rewire index [--repo <path>] [--rebuild] # build or refresh the code index (see "Code navigation")
143
817
  ```
144
818
 
145
819
  `--repo` defaults to the current directory, which must be the root of a clean git repository
146
820
  (a package subdirectory of a monorepo is refused with `not_repo_root` in v0.1).
147
821
  `--headless` never asks questions (an ambiguous task escalates with reason
148
822
  `clarification_required`) and writes machine-readable events to stdout and the human summary to
149
- stderr.
823
+ stderr. `--no-web` turns web access off for the run (see "Web access").
150
824
 
151
825
  ### Exit codes
152
826
 
@@ -157,7 +831,34 @@ stderr.
157
831
  | 2 | the run escalated to a human (see the evidence report for the reason) |
158
832
  | 130 | a second Ctrl-C: forced quit (the first Ctrl-C stops the run and writes an interrupted report) |
159
833
 
160
- Running `rewire` with no arguments prints the usage and exits 1; `rewire --help` prints it and exits 0.
834
+ Running `rewire` with no arguments and no TTY prints the usage and exits 1 (on a TTY it opens the
835
+ interactive session); `rewire --help` prints it and exits 0.
836
+
837
+ ### Error codes
838
+
839
+ Errors carry a stable code. The ones added with interactive mode and skills:
840
+
841
+ | code | meaning |
842
+ | --------------------------------- | --------------------------------------------------------------------------------------------------- |
843
+ | `tui_requires_tty` | `rewire chat` needs a terminal. Exit 1. |
844
+ | `tui_render_failed` | The terminal UI failed to render. |
845
+ | `skill_invalid` | A skill is malformed or over a limit (name, description, size, symlink). |
846
+ | `trust_store_unreadable` | `trusted-skills.json` is unreadable: repo skills are not loaded; the session opens. |
847
+ | `trust_store_locked` | Another rewire process holds the trust store lock. |
848
+ | `session_corrupt` | A stored session file is damaged. |
849
+ | `session_locked` | Another rewire process is writing this session; retry shortly. |
850
+ | `session_not_found` | `/resume` named a session that is not stored. |
851
+ | `session_disposed` | The session was closed and can't take more turns. |
852
+ | `session_store_unsafe` | `.rewire/sessions/` is not a plain directory owned by you (for example a symlink). |
853
+ | `run_in_progress` | A gated run is already active; only one runs at a time. |
854
+ | `stopped_by_user` | You chose stop at a checkpoint. The run escalates (exit 2). |
855
+ | `aborted` | You pressed Esc or Ctrl-C during a chat turn; the turn is not stored. |
856
+ | `provider_stream_callback_failed` | A streaming reply's display callback threw; the chat call fails. |
857
+ | `compaction_invalid` | A compaction's output or an edit to the record was invalid; the context is kept. |
858
+ | `compaction_rejected` | A compaction broke a rule or its independent check was unavailable; context kept. |
859
+ | `calibration_failed` | `rewire calibrate` could not finish (bad model, paid gate, truncation, errors). |
860
+ | `context_window_unknown` | The model ref has no known provider, so no context window can be found. |
861
+ | `context_overflow` | A chat request would not fit the model's loaded window even with old tool output cleared; not sent. |
161
862
 
162
863
  ### Run directory
163
864
 
@@ -171,10 +872,50 @@ Every run writes into the target repo:
171
872
  report.md the evidence report, including the known limitations below
172
873
  ```
173
874
 
174
- Add `.rewire/runs/`, `.rewire/worktrees/` and `.rewire/cache/` to the repo's ignore file (not
875
+ Add `.rewire/runs/`, `.rewire/worktrees/`, `.rewire/cache/`, `.rewire/sessions/` and `.rewire/index/` to the repo's
876
+ ignore file (not
175
877
  all of `.rewire/`: `.rewire/policy.toml` is the repo policy and belongs in version control). The
176
878
  result of a verified run lives on the branch `rewire/<runId>`.
177
879
 
880
+ ## `rewire doctor`
881
+
882
+ ```sh
883
+ rewire doctor [--models <file>] [--repo <path>]
884
+ ```
885
+
886
+ Prints one line per check, `✓` or `✗` with a fix hint, and exits `0` when everything required is
887
+ present or `1` otherwise. It checks: the sandbox binary, `git`, `rg`, `semgrep`, `gitleaks`,
888
+ `bwrap` (Linux) or `sandbox-exec` (macOS), the model list, and, when any model is an Ollama model,
889
+ that Ollama is reachable and at least version 0.6.4. Run it before your first `rewire run`.
890
+
891
+ For each cloud provider a model or a `[providers.*]` table uses, and each `[endpoints.<name>]`, it
892
+ prints one line with what rewire resolved (region, project, resource or host, API version) and
893
+ where each value came from (a toml key, or an env var **name**). Credentials appear only as env var
894
+ names, never as values. A region, project, resource or API version that does not look like a
895
+ normal one is shown as `(set, unusual format)` instead of its value. An endpoint `family` override
896
+ is shown, with the family rewire would derive when it differs. A provider that a model uses but
897
+ that is incomplete is `✗` and makes doctor exit 1; a table that no model uses is a `!` note and
898
+ does not. Doctor makes no network calls and reads no credential files.
899
+
900
+ A `web` line shows the search backend and the env var **name** its key came from, or `none` and
901
+ what to set, the SearXNG host when that is used, and the web policy from the repository's
902
+ `.rewire/policy.toml` (`--repo`, default the current directory): `on` with the `allow_domains`
903
+ and `deny_domains` counts, or `off` and why. It is a `✓`, or a `!` note when there is no search
904
+ backend, when the policy refuses the search service's host, or when web is off; none of these
905
+ makes doctor exit 1. An invalid policy file, or a `--repo` that is not a directory, is a
906
+ `✗ policy` line and exit 1, because a run would fail on it too.
907
+
908
+ An `index` line covers the code index (see "Code navigation"). It checks three things:
909
+
910
+ - **Grammars.** Every grammar and the Tree-sitter runtime match their pinned sha256 and load.
911
+ - **check-paths.** The sandbox binary doctor located has `check-paths`, which decides what the
912
+ index may read.
913
+ - **Store.** The size and age of the repository's `.rewire/index` store, or that there is none
914
+ yet.
915
+
916
+ It never prints file contents. A tampered grammar, or a sandbox binary older than this rewire
917
+ (one without `check-paths`), is `✗ index` with a hint to reinstall or rebuild, and doctor exits 1.
918
+
178
919
  ## Choosing models
179
920
 
180
921
  With no configuration, rewire uses whatever it finds: `ANTHROPIC_API_KEY` selects
@@ -184,8 +925,9 @@ Ollama selects its first pulled model. Override the first two with `REWIRE_ANTHR
184
925
 
185
926
  For control, write a `models.toml` and pass `--models <file>`, or save it as
186
927
  `~/.config/rewire/models.toml` (`$XDG_CONFIG_HOME/rewire/models.toml`), which is used
187
- automatically. Models are written `<provider>:<model>` where provider is `anthropic`, `openai` or
188
- `ollama`.
928
+ automatically. Models are written `<provider>:<model>` where provider is `anthropic`, `openai`,
929
+ `ollama`, a cloud provider (`bedrock`, `vertex`, `foundry`, `azure`, `gemini`) or an endpoint you
930
+ declare (see "Providers" below).
189
931
 
190
932
  - `available` (required): the models rewire may use. The first one is the author: it writes the
191
933
  spec and tests and implements.
@@ -224,9 +966,309 @@ review is weaker than a cross-family one. Rewire still runs, and marks the evide
224
966
  `independence: same-family` so you can discount it. Ollama models must support tool calling;
225
967
  rewire checks this.
226
968
 
227
- Each Ollama reply may take up to 300 seconds. A larger local model on modest hardware can need
228
- more: set `REWIRE_OLLAMA_TIMEOUT_S` (whole seconds, 1 to 86400), e.g.
229
- `REWIRE_OLLAMA_TIMEOUT_S=900 rewire run ...`. `rewire doctor` shows the value in use.
969
+ Each Ollama reply may take up to 900 seconds, the reply timeout. A larger local model on modest
970
+ hardware can need more. Set it in either of two places (whole seconds, 1 to 86400):
971
+
972
+ - `REWIRE_OLLAMA_TIMEOUT_S`, e.g. `REWIRE_OLLAMA_TIMEOUT_S=1800 rewire run ...`. It wins over the
973
+ file. A variable added to `~/.zshrc` reaches only terminals opened after the edit, so a
974
+ terminal opened before it runs rewire on the default.
975
+ - `timeout_s` in `models.toml`, which does not depend on the shell:
976
+
977
+ ```toml
978
+ [providers.ollama]
979
+ timeout_s = 1800
980
+ ```
981
+
982
+ `rewire doctor` shows the value in use and where it came from, as
983
+ `reply timeout 1800s (env|models.toml|default)`. The `ollama_timeout` error names both too.
984
+
985
+ A streamed reply (the TUI chat) works differently. The reply timeout covers only the wait for
986
+ its first chunk, which is mostly the time the model spends reading the prompt. Once chunks
987
+ flow there is no total limit. The request fails only when no chunk (text, thinking or a tool
988
+ call) arrives for 120 seconds. Esc still interrupts it. The pipeline's stages never stream, so
989
+ each of their replies has the reply timeout as its whole limit. In the chat, a prompt too large
990
+ to read within the reply timeout is trimmed or refused before it is sent (see "Inside one turn"
991
+ under "Context and compaction").
992
+
993
+ Ollama keeps a prompt cache per loaded model. When the chat model and another role's model (the
994
+ reviewer or verifier, say) take turns and only one fits in memory, each switch unloads the
995
+ other, and the next chat call reads its whole prompt again. If you have the memory, letting
996
+ Ollama keep both loaded (`OLLAMA_MAX_LOADED_MODELS=2` in the Ollama server's environment) avoids
997
+ those reloads. rewire does not set it.
998
+
999
+ ### Picking models in the TUI
1000
+
1001
+ In interactive mode, `/model` (or `/models`) picks the model for each role. The roles are
1002
+ `chat & spec` (the chat model is the spec author), `test-writer`, `implementer`, `reviewer` and
1003
+ `verifier`. Each role shows its `provider:model`, family and source: `session`, `models.toml` or
1004
+ `auto`. Enter on a role lists the `available` models, plus `default`, which drops the session
1005
+ pick and goes back to `[roles]` or automatic routing.
1006
+
1007
+ - **Session only.** Nothing writes `models.toml`; the next `rewire` starts from the file again.
1008
+ - **Family rule.** A pick that puts the reviewer or the verifier in the implementer's family is
1009
+ refused while `available` holds a model of another family, and the message names both
1010
+ families. A pairing already in effect, or set by the models file itself, is exempt, so a file
1011
+ that pins a same-family reviewer keeps working and `default` always gets back to it. With only
1012
+ one family available, the pick applies and its note says `independence: same-family`.
1013
+ - A pick whose provider cannot be created (for example `provider_auth_missing`) is refused. A
1014
+ refused pick changes nothing.
1015
+ - **The conversation carries over.** Changing `chat & spec` or the verifier (the chat's
1016
+ compaction check uses the verifier) rebuilds the chat session by resuming the same session id
1017
+ on the new routing, so the messages, the session record and the compaction state are kept. A
1018
+ session with no completed turn yet starts fresh, as there is nothing to keep. The status line
1019
+ then shows the new chat model and, with compaction on, its context limit. The rebuild also
1020
+ re-reads the skills, so a skill trusted earlier in the session loads then. Such a pick can
1021
+ make the chat's compaction check same-family (the verifier shares the chat model's family);
1022
+ it is not refused, and the same notice as at session start says so.
1023
+ - Picks are refused while a gated run, a chat turn, a compaction or a session change is in
1024
+ progress. A run keeps the routing it started with; the next run uses the new one.
1025
+
1026
+ ## Providers
1027
+
1028
+ Besides Anthropic, OpenAI and Ollama, rewire talks to Claude on Amazon Bedrock, Google Vertex AI
1029
+ and Microsoft Foundry, to Azure OpenAI, to Gemini, and to any OpenAI-compatible endpoint (Groq,
1030
+ OpenRouter, vLLM, LM Studio and so on). Only Gemini (`GEMINI_API_KEY`) is auto-detected. The clouds,
1031
+ Azure and endpoints need a `models.toml`, because their credentials are ambiguous.
1032
+
1033
+ Credentials come only from the environment or the platform's own credential chain. rewire never
1034
+ reads credential files itself, never stores a key, and redacts keys from every error. `models.toml`
1035
+ holds the **name** of an env var (`api_key_env`), never a key.
1036
+
1037
+ ### Claude on Bedrock, Vertex and Foundry
1038
+
1039
+ rewire uses each platform's own client (`AnthropicBedrockMantle`, `AnthropicVertex`,
1040
+ `AnthropicFoundry`), not the Anthropic client with a changed URL. Only Claude models are supported
1041
+ there: a model id without `claude` is `model_ref_invalid`.
1042
+
1043
+ ```toml
1044
+ available = [
1045
+ "bedrock:anthropic.claude-opus-5-5", # Bedrock ids carry the anthropic. prefix
1046
+ "vertex:claude-opus-5-5", # bare ids; dated snapshots use @
1047
+ "foundry:my-claude-deployment", # the Foundry deployment name
1048
+ ]
1049
+
1050
+ [providers.bedrock]
1051
+ region = "us-west-2"
1052
+
1053
+ [providers.vertex]
1054
+ project = "my-gcp-project"
1055
+ region = "us-east5" # optional, default "global"
1056
+
1057
+ [providers.foundry]
1058
+ resource = "my-foundry-resource" # or base_url = "https://..."
1059
+ ```
1060
+
1061
+ | Provider | Credentials | Region, project, resource (first set wins) |
1062
+ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1063
+ | `bedrock` | `AWS_BEARER_TOKEN_BEDROCK`, else `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (+ `AWS_SESSION_TOKEN`), else `AWS_PROFILE`, else the AWS default chain (SSO, instance roles) | `[providers.bedrock] region`, `AWS_REGION`, `AWS_DEFAULT_REGION` |
1064
+ | `vertex` | Google application default credentials (`gcloud auth application-default login` or `GOOGLE_APPLICATION_CREDENTIALS`) | project: `[providers.vertex] project`, `ANTHROPIC_VERTEX_PROJECT_ID`, `GOOGLE_CLOUD_PROJECT`. Region: `[providers.vertex] region`, `CLOUD_ML_REGION`, else `global` |
1065
+ | `foundry` | `ANTHROPIC_FOUNDRY_API_KEY` (required) | `[providers.foundry] resource` or `base_url`, else `ANTHROPIC_FOUNDRY_RESOURCE` or `ANTHROPIC_FOUNDRY_BASE_URL` |
1066
+
1067
+ `ANTHROPIC_CUSTOM_HEADERS` applies only to the plain `anthropic` provider. For Bedrock, Vertex and
1068
+ Foundry every header it names is removed, and each sends only its own credential (SigV4 or a Bedrock
1069
+ API key, a Google OAuth token, the Foundry key), so a gateway header meant for Anthropic never
1070
+ reaches AWS, Google or Azure.
1071
+
1072
+ A missing region, project or key is `provider_auth_missing`, and its hint names the env var or toml
1073
+ key to set. `rewire run` and `rewire chat` create the provider of every routed role (spec,
1074
+ test-writer, implementer, reviewer, verifier) before they start, so a misconfigured provider fails
1075
+ before any model is called, even one only the review stage would use. Creating a provider sends no
1076
+ request: the cloud SDK, and for Vertex the Google credentials, load on its first call. A region or Foundry
1077
+ resource must be a single DNS label, because it becomes part of a host name.
1078
+
1079
+ ### Azure OpenAI
1080
+
1081
+ ```toml
1082
+ available = ["azure:my-gpt-deployment"] # the deployment name
1083
+
1084
+ [providers.azure]
1085
+ endpoint = "https://myres.openai.azure.com"
1086
+ api_version = "2024-10-21"
1087
+ # family = "deepseek" # optional, see "Model families"
1088
+ ```
1089
+
1090
+ Needs `AZURE_OPENAI_API_KEY`. The endpoint comes from `[providers.azure] endpoint` or
1091
+ `AZURE_OPENAI_ENDPOINT`, and **must be the resource root** with no path (rewire adds
1092
+ `/openai/deployments/<deployment>/...`). **The API version is required**, from
1093
+ `[providers.azure] api_version` or `OPENAI_API_VERSION`: the OpenAI SDK has no default for Azure, so a
1094
+ missing version is `provider_auth_missing`.
1095
+
1096
+ ### Gemini
1097
+
1098
+ ```toml
1099
+ available = ["gemini:gemini-2.5-pro"]
1100
+ ```
1101
+
1102
+ Needs `GEMINI_API_KEY` (or `GOOGLE_API_KEY`). rewire uses Gemini's OpenAI-compatible API at
1103
+ `https://generativelanguage.googleapis.com/v1beta/openai/`. With `GEMINI_API_KEY` set and no
1104
+ `models.toml`, rewire auto-detects `gemini:gemini-2.5-pro` (override with `REWIRE_GEMINI_MODEL`).
1105
+ `GOOGLE_API_KEY` alone is not auto-detected.
1106
+
1107
+ ### OpenAI-compatible endpoints
1108
+
1109
+ ```toml
1110
+ available = ["groq:llama-3.3-70b-versatile", "local:qwen2.5-coder"]
1111
+
1112
+ [endpoints.groq]
1113
+ base_url = "https://api.groq.com/openai/v1"
1114
+ api_key_env = "GROQ_API_KEY" # the NAME of the env var
1115
+ # family = "llama" # optional override, see "Model families"
1116
+ # context_window = 131072 # optional, integer >= 4096
1117
+ # max_tokens_field = "max_tokens" # or "max_completion_tokens"; default max_tokens
1118
+
1119
+ [endpoints.local]
1120
+ base_url = "http://127.0.0.1:1234/v1" # loopback http needs no key
1121
+ ```
1122
+
1123
+ Endpoint names match `^[a-z][a-z0-9-]{0,31}$` and may not be a built-in provider name. Unknown keys
1124
+ in any of these tables are `models_file_invalid`. Requests go to `<base_url>/chat/completions`.
1125
+
1126
+ Rules for every base URL (endpoints, `[providers.foundry] base_url`, the Azure endpoint, and the
1127
+ three SDK env overrides `ANTHROPIC_BEDROCK_MANTLE_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL` and
1128
+ `ANTHROPIC_FOUNDRY_BASE_URL`):
1129
+
1130
+ - It must be `https`. Plain `http` is allowed only for `localhost`, `127.x.x.x` and `[::1]`.
1131
+ - It may not carry userinfo, a query or a fragment. Put the key in an env var.
1132
+ - A loopback endpoint without `api_key_env` sends **no** auth header at all. Any other endpoint
1133
+ needs `api_key_env`, and an unset var is `provider_auth_missing`.
1134
+
1135
+ `OPENAI_CUSTOM_HEADERS` applies only to the plain `openai` provider. For Azure, Gemini and endpoints
1136
+ it is ignored, so a header meant for OpenAI can never replace another vendor's credential. The
1137
+ OpenAI SDK's own `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` are
1138
+ not read for these providers either.
1139
+
1140
+ ### Model families
1141
+
1142
+ Cross-family review depends on knowing each model's family, so it is derived with fixed rules:
1143
+
1144
+ - `bedrock`, `vertex`, `foundry`: `claude`. `gemini`: `gemini`, or `gemma` for a Gemma id (the
1145
+ same weights as `ollama:gemma3`).
1146
+ - `azure`: `[providers.azure] family` when set (same rule as an endpoint `family`), else from the
1147
+ deployment name, which you choose: a word naming another vendor's model (`claude`, `gemini`,
1148
+ `gemma`, `llama`, `mistral`, `mixtral`, `deepseek`, `qwen`, `grok`, `phi`, at the start of a word)
1149
+ gives that family, so `azure:DeepSeek-R1` is `deepseek`; anything else is `gpt`. A deployment
1150
+ name that hides its model gets the wrong family: set `family`. `rewire doctor` shows the override,
1151
+ and the family rewire would have derived when that differs.
1152
+ - An **endpoint** uses its `family` key when set. Otherwise the family comes from the model id
1153
+ alone, **never from the endpoint name** (you choose that name, and it says nothing about the
1154
+ model):
1155
+ 1. A vendor path segment: `anthropic/` is `claude`, `openai/` is `gpt`, `google/` is `gemini`
1156
+ (`gemma` for gemma ids), `meta-llama/` is `llama`, `x-ai/` is `grok`, `mistralai/` is
1157
+ `mistral`, `deepseek/` is `deepseek`, `qwen/` is `qwen`. So `openrouter:anthropic/claude-opus-5-5`
1158
+ is `claude` and cannot be the independent reviewer of a Claude implementer.
1159
+ 2. Otherwise, in the last path segment: contains `claude` is `claude`; starts `gpt-`, `o1`, `o3`,
1160
+ `o4`, `chatgpt`, `codex` or `gpt-oss` is `gpt`; contains `gemini` or `gemma` is that family.
1161
+ 3. Otherwise the Ollama rules (leading word, with code and vision variants mapped to their base).
1162
+ - A router or default id (`auto`, `router`, `default`, an empty last segment, or anything under
1163
+ `openrouter/`) names no model, so its family cannot be known: set `family` or it is
1164
+ `model_ref_invalid`.
1165
+ - An endpoint `family` override is honoured, and `rewire doctor` prints it, and the family rewire
1166
+ would have derived when that differs.
1167
+
1168
+ An unrecognised leading word counts as its own family (so `llama-3.3` and `qwen2.5` work with no
1169
+ configuration). An exotic id that really shares training with another family can therefore pass
1170
+ as independent; set `family` when you know it does.
1171
+
1172
+ ### Not supported
1173
+
1174
+ - **Claude subscription login (Free, Pro, Max).** Anthropic's terms say it "does not permit
1175
+ third-party developers to offer Claude.ai login into their own applications, or to route requests
1176
+ through Free, Pro, Max, or Ultra plan credentials on behalf of their users"
1177
+ ([Legal and compliance](https://code.claude.com/docs/en/legal-and-compliance)). rewire is such an
1178
+ application, so it takes an API key (`ANTHROPIC_API_KEY`) or a supported cloud provider instead.
1179
+ - Non-Claude models on Bedrock, Vertex and Foundry (use `azure`, `gemini` or an endpoint).
1180
+ - Keys in `models.toml`, and credentials in URLs.
1181
+
1182
+ ## Configuration
1183
+
1184
+ | Variable | What it does |
1185
+ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
1186
+ | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY` | Enable the Anthropic, OpenAI and Gemini providers (auto-detected when no `models.toml` is given). |
1187
+ | `REWIRE_ANTHROPIC_MODEL`, `REWIRE_OPENAI_MODEL`, `REWIRE_GEMINI_MODEL` | Override the auto-detected models. |
1188
+ | Cloud and endpoint credentials | Named under "Providers" (AWS, Google, `ANTHROPIC_FOUNDRY_*`, `AZURE_OPENAI_*`, and each endpoint's `api_key_env`). |
1189
+ | `OLLAMA_API_KEY`, `TAVILY_API_KEY`, `BRAVE_API_KEY` | Web search backends, first set wins in this order (see "Web access"). `web_fetch` needs no key. |
1190
+ | `OLLAMA_HOST` | Where Ollama is found (default `http://127.0.0.1:11434`). |
1191
+ | `REWIRE_OLLAMA_TIMEOUT_S` | Ollama reply timeout, whole seconds 1 to 86400 (default 900). Wins over `[providers.ollama] timeout_s`. |
1192
+ | `REWIRE_SANDBOX_BIN` | Use this sandbox binary (a missing file is an error, never a fall-through). |
1193
+ | `XDG_CONFIG_HOME` | Where the default `rewire/models.toml` is looked up (default `~/.config`). |
1194
+
1195
+ The repository's own policy lives in `.rewire/policy.toml` and belongs in version control. Policy
1196
+ layers only ever tighten: built-in, then organisation, then repository, then run.
1197
+
1198
+ ## Installation in detail
1199
+
1200
+ ### From npm
1201
+
1202
+ rewire is published to npm as the package **`sheperd`** (a v0.1 beta). The command it installs
1203
+ is `rewire`:
1204
+
1205
+ ```sh
1206
+ npm i -g sheperd
1207
+ rewire doctor
1208
+ ```
1209
+
1210
+ The package carries the CLI as one bundled file plus a prebuilt `rewire-sandbox` for your
1211
+ platform, which npm installs automatically as an optional dependency
1212
+ (`sheperd-darwin-arm64`, `sheperd-darwin-x64`, `sheperd-linux-x64` or `sheperd-linux-arm64`).
1213
+ Supported platforms: macOS on Apple silicon or Intel, and Linux on x64 or arm64 with glibc 2.35
1214
+ or newer (Ubuntu 22.04, Debian 12 or later; musl distributions such as Alpine are not supported).
1215
+ Windows is not supported. If your npm install skips optional dependencies
1216
+ (`--omit=optional`, `--no-optional`), the sandbox binary is missing and `rewire doctor` says so.
1217
+
1218
+ You still need these system tools on `PATH`: git,
1219
+ [ripgrep](https://github.com/BurntSushi/ripgrep), [semgrep](https://semgrep.dev),
1220
+ [gitleaks](https://github.com/gitleaks/gitleaks), and on Linux
1221
+ [bubblewrap](https://github.com/containers/bubblewrap) 0.8 or newer. macOS uses the built-in
1222
+ `sandbox-exec`. See the per-OS install commands below.
1223
+
1224
+ ### From source
1225
+
1226
+ Requirements: git, Node.js 22+, pnpm, a Rust toolchain (to build the sandbox helper),
1227
+ [ripgrep](https://github.com/BurntSushi/ripgrep), [semgrep](https://semgrep.dev),
1228
+ [gitleaks](https://github.com/gitleaks/gitleaks), and on Linux
1229
+ [bubblewrap](https://github.com/containers/bubblewrap) 0.8 or newer. macOS uses the built-in
1230
+ `sandbox-exec`. Windows is not supported. CI uses semgrep 1.186.0 and gitleaks 8.30.1, the
1231
+ versions the gates were developed against.
1232
+
1233
+ ```sh
1234
+ # macOS
1235
+ brew install ripgrep semgrep gitleaks pnpm
1236
+
1237
+ # Debian/Ubuntu
1238
+ sudo apt-get install -y git ripgrep bubblewrap pipx
1239
+ pipx install semgrep==1.186.0
1240
+ pipx ensurepath # then restart the shell so ~/.local/bin is on PATH
1241
+ # gitleaks: download the release for your platform from
1242
+ # https://github.com/gitleaks/gitleaks/releases/tag/v8.30.1
1243
+ # and put the `gitleaks` binary on PATH
1244
+ # pnpm: npm install -g pnpm (or corepack enable)
1245
+ ```
1246
+
1247
+ Then build rewire from source:
1248
+
1249
+ ```sh
1250
+ git clone <this repository> rewire && cd rewire
1251
+ cargo build --release -p rewire-sandbox
1252
+ pnpm install --frozen-lockfile
1253
+ pnpm -r build
1254
+
1255
+ # put the CLI on PATH (or run `node "$PWD/packages/cli/dist/main.js"` directly)
1256
+ alias rewire='node '"$PWD"'/packages/cli/dist/main.js'
1257
+ ```
1258
+
1259
+ The CLI looks for the sandbox binary in this order:
1260
+
1261
+ 1. `REWIRE_SANDBOX_BIN` (a missing file is an error, never a fall-through);
1262
+ 2. the newer of `target/release/` and `target/debug/` in the checkout (source builds only; the npm
1263
+ package never looks for a checkout);
1264
+ 3. the `sheperd-<os>-<arch>` package installed next to the CLI (only there: never via `NODE_PATH`
1265
+ or other global folders). Its binary must match the sha256 recorded in the npm bundle at
1266
+ build time; a package whose binary is missing, not executable, modified, or of a different
1267
+ version than the CLI is an error, never a fall-through;
1268
+ 4. the first absolute `PATH` entry that has `rewire-sandbox`.
1269
+
1270
+ `rewire doctor` reports exactly this lookup, including which step found the binary, and a run
1271
+ that cannot find the binary stops in preflight, before any model call.
230
1272
 
231
1273
  ## Benchmark
232
1274
 
@@ -240,6 +1282,19 @@ defines what a first run must show.
240
1282
 
241
1283
  ## Behaviour changes in this release
242
1284
 
1285
+ - The chat agent, the spec stage and the implementer can use the internet through `web_search`
1286
+ and `web_fetch` (see "Web access"). It is on by default; `web_fetch` works without a key.
1287
+ Turn it off with `[web] enabled = false` in `.rewire/policy.toml`, or limit it with
1288
+ `allow_domains`.
1289
+ - The chat clears its own older tool results inside a long turn to stay under the compaction
1290
+ limit, and on Ollama refuses (`ollama_timeout`) a request whose prompt it could not read
1291
+ within the reply timeout, instead of waiting for the timeout (see "Inside one turn"). The
1292
+ latency-based compaction limit now ignores prefix-cache hits, so on a slow local model it
1293
+ is lower than before, and compaction runs sooner.
1294
+ - `/model` in the TUI opens a picker instead of printing the routing. During a run it still
1295
+ prints the routing and says why picks are refused.
1296
+ - `/skills` opens a list instead of printing the skill names and opening the trust prompt at
1297
+ once. The list's "Review pending repo skills" row opens the prompt.
243
1298
  - Leftover processes fail the command on Linux too: a command that leaves a child running more than
244
1299
  300 ms after it exits (a server a test suite never closes, slow workers) now fails as a sandbox
245
1300
  escape (`sandbox_escape`), matching macOS. Test suites that relied on this passing on Linux need
@@ -253,6 +1308,11 @@ defines what a first run must show.
253
1308
 
254
1309
  ## Known v0.1 limitations
255
1310
 
1311
+ rewire is honest about what it does not catch yet. The full list is long and specific.
1312
+
1313
+ <details>
1314
+ <summary><b>Show all known limitations</b></summary>
1315
+
256
1316
  These are rendered into every evidence report (the first list) or are known gaps in the harness.
257
1317
 
258
1318
  Stated in every report (this list is checked against the pipeline's `KNOWN_LIMITATIONS` by a test):
@@ -350,6 +1410,8 @@ Also known:
350
1410
  - The Ollama role-fitness cache is not safe for concurrent runs (single-user CLI), and each
351
1411
  fitness probe costs a few model calls the first time a model digest is seen.
352
1412
  - `events.jsonl` has no size cap.
1413
+ - Web access has its own residuals (a page can mislead the model; non-secret repository text can
1414
+ leave in a query or URL when web is on): see "Web access", "Residuals".
353
1415
  - An unexpected (non-`RewireError`) failure inside a stage exits 1 and keeps the worktree.
354
1416
  - A coverage failure in the test-writer stage (a criterion without a test) escalates without a
355
1417
  retry.
@@ -359,6 +1421,8 @@ Also known:
359
1421
  - The registry-client e2e test has flaked under load on a developer machine.
360
1422
  - No PR delivery, TUI, Python pack, plugin API or streaming in v0.1.
361
1423
 
1424
+ </details>
1425
+
362
1426
  ## Development
363
1427
 
364
1428
  ```sh