# MCP Tools Reference

SageFs runs a Model Context Protocol server on port 37749. Any MCP client
(GitHub Copilot, Claude Code, Claude Desktop, Cursor, Windsurf, OpenCode)
can connect and drive an F# session: run code, type-check it, list and verify
tests, and read live status. This is the surface I actually use every day to
work on SageFs itself, so if it's clunky, I feel it first.

SageFs gates tools when you call them. A connection that presents no member
token sees the full catalog below in `tools/list`, whatever state its session
is in. Calling one is different: a call that doesn't apply to the current session
state gets rejected with a structured error (`enforceToolCallGate` in
`SageFs/Mcp.fs`), instead of a raw failure. Call `get_daemon_status`
for daemon health, then `get_session_status` to see which tools currently
apply. In a warming-up session, for example, it
reports `send_fsharp_code` as not yet available, even though the tool is
still listed. I went back and forth on filtering the list by session state.
For now the call-time gate is what's wired up for that.

There are two exceptions, and both depend on the credential a request presents,
and on nothing else. A caller that presents a [member token](#member-tokens-one-identity-per-agent-run)
sees only the tools its role allows. And a daemon started with
`SAGEFS_IDENTITY_POLICY=TokenRequired` shows a caller that presents no credential
the status tools and `join_cohort`, and shows the caller that presents the daemon's
operator credential everything. The list does not change when a connection joins
the cohort or takes the conductor seat. The MCP revision of 2026-07-28 says a tool
list must not vary per connection or as a side effect of another request, and may
vary by the authorization presented, so that is the only input, with one setting
of the daemon beside it (next section).

### The size of the list, and the starter list

`tools/list` is the largest cost an agent pays on every session, so it has a
weight budget. `ToolListBudgetTests` builds the registered tools in process, sums
the minified JSON of each tool's name, description and input schema, and holds
the total to `RatchetBudgets.toolList`, a number that only goes down (`--ratchets
--tighten`). The count is characters. Divide by four for tokens: that is a rule of
thumb, and nobody has run the API's token counter over these lists yet.

Three things keep it small.

- **One sentence per tool.** The list carries `ToolSummaries.sentenceOf`, at most
  160 characters. The rest of a tool, its rules and the shape of its answer, is
  its manual, and `discover_features` with `tool` returns it (the description the
  tool is registered with, then every parameter and its description).
- **Shared parameters are described once.** `working_directory` was described 18
  ways across fifty tools, `session_id` six ways across 19 and the agent name six ways
  across 17. `SharedParameters` holds a few named sentences per parameter, one for
  each role it plays, and a test fails for a tool that carries a private variant.
  A JSON Schema in `tools/list` cannot point at a shared definition, so each tool
  still carries its short sentence. The sentence is written once in the source.
- **A starter list, opt-in.** A daemon started with `SAGEFS_TOOL_LIST=Starter`
  shows a caller that presents nothing nine tools: `create_project_session`,
  `get_session_status`, `list_sessions`, `send_fsharp_code`, `check_fsharp_code`,
  `run_tests`, `cancel_eval`, `hard_reset_fsi_session` and `discover_features`,
  which names the rest (`get_available_projects` and `stop_session` among them). A member token keeps its role's list and the operator credential keeps
  the full list. Every tool outside the starter list is still callable by name.
  The setting is read once at start, so the list is the same for every connection
  and does not move when a session is created or a member joins. `Full` is the
  default until a measured pass rate on a fixed task set shows no loss with the
  starter list.

Every tool in the catalog also says what calling it does to your work.
Eighteen of them stop, reset, discard or land something you already have, and
each comes back with MCP's own `destructiveHint: true`, so a client that wants
to ask before letting one through reads the list from the server instead of
keeping a copy of its own. That copy is the trap: a renamed tool drops out of
every hand-typed list without a sound. The eighteen live in
`Affordances.destructiveTools`, and a test holds them to the tools that are
actually registered.

One of those eighteen goes further and stops to ask you: `manage_local_data`.
A client that advertises MCP elicitation gets a prompt naming the tool and what
it is about to take away, and a decline stops the call the same way a gate
rejection does. It asks because it clears the local stores SageFs keeps on your
machine, which belong to no session, and an agent has no reason to call it in
the middle of a task.

The other seventeen never ask. `stop_session`, `reset_fsi_session`,
`hard_reset_fsi_session`, `switch_workflow` and `stop_app` are normal steps of
everyday MCP use: an agent starts a session, works in it, resets it and stops
it. A prompt on those would fire nearly every time, because the stdio bridge
makes a new connection per call, and it would train people to click through. So
they run at once on any session, whoever made it and whoever has run code in it
(a dashboard tab, an editor over `/exec`, another agent). They keep their
`destructiveHint`, which is information on `tools/list` and not a prompt.
`tidy_workspace` already demands its plan id, `nudge_value` is scrubbed one step
at a time from the editor, the cohort verbs are the loop an unattended agent
runs in where nobody is sitting there to click, and `run_app` is listed as
destructive but not asked about, because running the app is what you asked for
and the REPL loss is written on the tool itself.

Asking is separate from refusing. `stop_session`, `reset_fsi_session`,
`hard_reset_fsi_session`, `switch_workflow` and `stop_app` (and the editor routes
`POST /api/sessions/stop`, `/api/sessions/{sid}/stop-app` and
`/api/sessions/{sid}/workflow`) refuse a session another member made. One rule,
`SessionAccess.decide`, decides all of them: the member that made the session, the
conductor of the cohort it sits in, and the operator may act, and a different bound
member is refused with a reason and a next action. Nobody is asked. A session
with no maker on record (made from the dashboard or the CLI, or one a restarted
daemon resumed) and a call on no bound identity (the dashboard, an editor, the CLI)
are open, as before. Like the roles, this keeps well-mannered agents out of each
other's sessions and does not contain a hostile one: `send_fsharp_code` can run
anything the daemon's user can.

The part worth knowing: a client that never advertised elicitation is neither
prompted nor refused. The prompt is skipped, and the four gates ahead of it
still decide everything they decided before. The stdio bridge lands in exactly
that case after it re-handshakes on a stale session id, because it announces
empty capabilities, so confirmations stay off until that client initializes
again. If you are not being asked, that is why. `SAGEFS_CONFIRM_ANSWER_SECONDS`
raises the wait if you read slowly; running out refuses the call rather than
letting it through.

A refusal says plainly that nothing was done and your local data is untouched.
A client that advertises elicitation but cannot answer (a headless agent, or a
UI whose prompt never takes an answer) waits the full 60 seconds on
`manage_local_data` and then gets "needs a person to confirm it, and no answer
came within 00:01:00", with the way out spelled out. There is no setting that
turns the prompt off, and no route skips it for an agent: the person who runs
the daemon clears the stores from a shell with
`sagefs data clear [--store friction|cohort|all]`, which reads the operator
credential (`operator.token`) and sends it as the Bearer header.
`POST /api/local-data/clear` takes that credential and nothing else, so no tool and
no member token reaches it. (`sagefs stop` stops the whole daemon, not one
session.)

The full advertised set is 76 tools, grouped below. This is separate
from the daemon's HTTP API (`/api/...`), which the editors and dashboard use
for completions, coverage bitmaps, run policies, and event history. Those
HTTP endpoints are not MCP tools.

## Connect

**stdio (recommended)**: your client spawns `sagefs mcp`, so there's no
ordering to get wrong, no port to be missing, no cached connection
failure, no race between your client starting and the daemon starting.
`sagefs mcp` checks whether the daemon is up, starts it if it isn't, waits
for it, then bridges your client's stdin/stdout to it.

```
claude mcp add sagefs -- sagefs mcp
```

### How long the daemon lives

If `sagefs mcp` has to start the daemon, it starts it with
`--owner-pid <the pid of that bridge>` (`startDaemonProcess` in
`SageFs/McpStdioBridge.fs`). The daemon polls that pid every 2 seconds
(`OwnerMonitor`, `SageFs.Core/OwnerMonitor.fs`) and shuts down when the owner
is gone. So a daemon that an agent started lives exactly as long as that agent
session: when the client exits, the daemon goes within about ten seconds, and
the dashboard and every session go with it. Two agents sharing that daemon
share its fate, too. The one that started it leaving takes it down for the
other.

Good for a throwaway session, bad if you want the REPL, the dashboard and the
warm sessions to still be there tomorrow. To get a daemon that outlives the
agent, start it yourself before the agent does: run `sagefs` in a terminal, or
run it as a service (see "Run it as a service (Linux)" or "Run it as a
service (macOS)" in the [README](../Readme.html)). `sagefs mcp` checks for a
running daemon first, so it just bridges to yours and never becomes its owner.

For clients that take raw JSON config:
```json
{ "mcpServers": { "sagefs": { "command": "sagefs", "args": [ "mcp" ] } } }
```

**Streamable HTTP** (for a client that only speaks HTTP, or that's already
started before you get to configure it, the daemon has to be running
first):
```json
{ "mcpServers": { "sagefs": { "type": "streamable-http", "url": "http://localhost:37749/" } } }
```

**SSE** (for clients that don't support Streamable HTTP yet):
```json
{ "mcpServers": { "sagefs": { "type": "sse", "url": "http://localhost:37749/sse" } } }
```

### No SageFs tools in your client

If your client shows no SageFs tools, or it shows them but every call
fails, you almost certainly configured HTTP and started your client before
the daemon. An HTTP-based MCP client that fails to connect on its first try
usually caches that failure and never retries, even once the daemon comes
up seconds later, restarting the client is the only fix, and nothing
tells you that's what you need to do. Switch to stdio (`claude mcp add
sagefs -- sagefs mcp`, above) and this stops happening: your client spawns
the bridge itself, and the bridge makes sure the daemon is there before
your client ever sees an empty tool list. If you want to stay on HTTP,
check `sagefs status`, if it says no daemon is running, start one with
`sagefs` and restart your client.

### Reaching the tools without a client: `sagefs call`

A script, a hook, CI, or an agent whose client has no SageFs tools can call
any tool from a shell. `sagefs call` talks to the daemon's HTTP endpoint
itself, with the same client code the stdio bridge uses, so it has no child
process and heals a session the daemon has forgotten.

```sh
sagefs call --list                                    # each tool and the first line of what it does
sagefs call run_tests --help                          # what one tool does and takes, one line a parameter
sagefs call get_session_status --session_id 1a2b3c4d
sagefs call run_tests --pattern Foo --timeout_seconds 60
sagefs call stop_session --json '{"session_id":"1a2b3c4d"}'
```

`sagefs call <tool> --help` prints the tool's own sentence, then each parameter on a
line with its type and whether it is required, read from the same input schema, and
says where the full manual is (`sagefs call discover_features --tool <tool>`, or this
page). A name the daemon does not list to the caller is said so, with the nearest
tool names and a pointer to `--list`. The tool's help comes from the daemon, so with
none running it prints the command's usage and how to start one, and exits 1.
`sagefs call --help` alone is the command's usage.

A flag is typed from the tool's own input schema (a string stays a string, a
number a number, a boolean flag alone is `true`; `--ids='[1,2]'` is an array).
A name the tool does not have is refused before anything is sent, with the names
it does have. The tool's answer is on stdout. A tool that answers with an error
goes to stderr with exit code 1, its full text kept: a refusal by a gate names the
next action. A usage mistake is exit code 2. A daemon that is not running gets the
words `sagefs status` uses and exit code 1. `--port` or `SAGEFS_MCP_PORT` picks the
daemon (`--mcp-port` works too). The command's own options (`--list`, `--json`,
`--token`, `--token-file`, `--port`, `--mcp-port`, `--help`) are never tool parameters,
and no tool has a parameter with one of those names.

**Who is calling.** Every `sagefs call` is a new process, so the daemon sees a new
connection each time, and what one call makes (a session, a claim) belongs to that
connection. With no token the next call cannot stop the session the last one made:
`stop_session` answers an error, "made by another member". A member
token outranks the connection (see "Member tokens" below), so pass one and every
call is the same member:

```sh
eval "$(sagefs member mint --role Implementer --dir "$PWD" --print-env SAGEFS_MEMBER_TOKEN)"
sagefs call create_bare_session --working_directory "$PWD"
sagefs call stop_session --session_id 1a2b3c4d      # the same member, so it is allowed
```

`--token-file <path>` reads the token from a file (`--token-file -` reads standard
input), and the environment variable works the same way: neither puts the token in
the process list or the shell history. `--token <token>` still works for one call
and prints a warning, because the token sits on the command line. A token lapses
after 30 minutes with no call (see "Expiry" below), and a session it made can then
only be stopped by the conductor, the operator or a token that is the same member,
which a new mint is not: stop such a session before you leave a token idle. `SAGEFS_OPERATOR_TOKEN` is sent too, so `--list` shows
the full tool list under `TokenRequired`. With neither, `--list` starts with
`identity: anonymous` and any refusal ends with what to do about it.

## "404 Session not found": the daemon was replaced under a live client

The single most confusing failure here, and it is not what it looks like. Read
this before you assume your client is broken.

**What happened.** The MCP session lives in the DAEMON'S MEMORY. The SDK mints an
`Mcp-Session-Id` when a client sends `initialize`, and the daemon holds that
session in its process. So a client that connected over **Streamable HTTP**
is holding an id the daemon only knows about. If the daemon is then
**restarted**, which SageFs does on purpose whenever a new build is installed,
so you get the new code, the new daemon has never heard of that id, and every
request the client makes is refused.

Measured, same id and same port either side of a restart:

```
held session id, before restart:  200
held session id, after  restart:   404
```

Nothing was wrong with your client, your code, or your configuration. The
connection was LIVE and pointed at a session that no longer existed.

**Why HTTP makes this permanent.** An HTTP client sends `initialize` once, at
connect, and keeps the id it got. When the daemon changes, nothing tells the
client to run `initialize` again, so it keeps presenting a dead id forever, and
the only fix is a manual client reload. The protocol has no way to recover an
id in place; `initialize` is the only thing that mints one.

**Why stdio does not have this problem.** With `sagefs mcp` the session id is
captured by the BRIDGE (`SageFs/McpStdioBridge.fs`, `forward`), not by your
client, the client never sees one. The bridge is a process that lives for the
length of your session, so it is the thing that would have to recover, and
that is what the bridge's own docs are about.

**If you are on HTTP and you hit it, do this.** One command re-establishes and
PROVES the session (it first checks a deliberately stale id is rejected, so a
pass cannot mean "the endpoint merely answers"):

```
dotnet fsi scripts/reconnect-mcp.fsx
```

If it prints `OK`, the session is live again, no client reload needed. That
repairs the connection; it cannot change what your client does on its own, which
is why the durable fix is stdio.

**Registering the bridge, for any client** (Claude Code, Open Code, Cursor,
Windsurf, or anything that spawns a command):

```
claude mcp add sagefs -- sagefs mcp
```

or in raw JSON:

```json
{ "mcpServers": { "sagefs": { "command": "sagefs", "args": [ "mcp" ] } } }
```

The daemon must be reachable on 37749 (the bridge's default). Point it
somewhere else with `SAGEFS_MCP_PORT`. If the daemon is not running, the
bridge starts one.

## Reading a tool reply

A tool's answer is the FIRST text content block of its result. When the daemon saw events since your
last call (a warmup finished, a test run landed), it adds one more text block after it, which starts with
`📡 SageFs events since last call:`. The echo is its own block, never part of the answer's text, so a tool
whose answer is JSON (`nudge_value` is one) is valid JSON on its own. A client that joins every text block into one string will see the echo glued on
the end: read the first block (or `structuredContent`, where a tool has it) and treat any later block as
the daemon talking. Agents still get the echo, because their client shows every block.

A call that failed says so with `isError: true`, on every tool. Its text is the reason and the next step
(`<what> → Next: <what to do>`), and `structuredContent` carries `case`, `fields`, `message` and
`suggestedAction`, so a client branches on `case` without reading the prose. A tool whose body has only text to
give is reported as `ToolFailed`
([`McpTools.classifyEcho`](https://github.com/WillEhrendreich/SageFs/blob/master/SageFs/McpTools.fs)). A session
that is restarting on purpose answers `SessionRestarting`, whose next step is to wait with `get_session_status`
and never to hard reset.

The session tools name their own case: `create_project_session`, `create_solution_session` and `create_bare_session`
answer `DuplicateSession`, `UnsafeSessionPath` or the session manager's own refusal, `switch_session`,
`switch_workflow` and `list_runnable_projects` answer `SessionNotFound` or the routing refusal for the session they
could not reach, and `get_message_journal` answers `NoActiveSessions` for a caller with no session. A cohort command
the cohort core refuses answers `CohortRefused`, and `fields.kind` says which refusal (`ClaimConflict`,
`NotConductor`, `OwnerUnresponsive` and the rest of `CohortFailureKind`). A server that has no cohort wired answers
`CohortOwnerNotWired`.

Positions in a reply (`line`, `column`, `endLine`, `endColumn`) are the parser's own: lines count from 1,
columns from 0 (counted in characters, not bytes), and `endColumn` is one past the last character.

### What an eval reply looks like

The reply of `send_fsharp_code` is sized for the agent that reads it ([`EvalPrintSettings`](https://github.com/WillEhrendreich/SageFs/blob/master/SageFs.Core/PrintLimits.fs), applied by both session kinds through `FsiPrintConfig`).

- A printed value is held to 20 list items, depth 6, width 78 and size 600, for a `let` (`val people: Person list = [...]`) and for a bare expression (`val it: ...`) alike. A `let` of 24 nested records echoes about 780 characters where FSI's defaults echo about 4,500. To see more of a value, evaluate a slice of it as an expression. A `let` that echoes only its type is a setting (`EvalPrintSettings.forAgentTypeOnly`) that nothing turns on yet, because the editors show the value beside a `let`.
- A reply longer than 4,000 characters keeps its first 2,666 and its last 1,334, with a line between them that says how many characters were cut. That count is of the eval's own printed output; the between-calls block below is added after it and counted apart. The session also binds the whole printed text to `lastEvalOutput`, and the line gives the expression that reads the cut, `lastEvalOutput.Substring(2666, 2025)` for a 6,025 character output: it returns exactly the characters that were left out. A text over a million characters is clipped and counted but not bound, and the line then says so by not naming the binding.
- Output that a background thread wrote between two calls (a timer, an app's log line) comes back with the next successful reply, after its own result, under `[output written since your last call]`. The session keeps the last 2,000 characters of it. Every production session runs its FSI in an isolated host, which is where that output is caught.
- An eval that took 0.5 s or more, or allocated 100 MB or more, ends with one line: `[0.84 s · 312.4 MB allocated · GCs gen0 14 / gen1 3 / gen2 1]`. The time is taken around the eval in the process that ran it, without the queue wait or the wire. The bytes are the whole process's, so the tasks the eval starts are counted, and so is anything a background thread allocated meanwhile. A failed eval carries the line too. A quick, light eval carries none. The thresholds are `Timeouts.evalCostSlow` and `EvalCost.HeavyAllocationBytes`.

## Execution and status

| Tool | What it does |
|:---|:---|
| `send_fsharp_code` | Evaluate F# code in the session. Each `;;` is a transaction boundary: a failure discards that one statement and keeps everything before it. It can also change a file. Pass both `file_path` and `block_start_line`, and a successful eval of one `let` value or function that redefines the declaration at that line is written back: that one declaration in the file is replaced with the code you sent, so `run_app` and the next build see it. It writes only to a source file of a project the session owns, only when the code differs from what the file has, and never for a type, a nested module, a bare expression, several declarations or a failed eval. The write is journaled like a `nudge_value` write, so `nudge_value` with `action=undo` and the same `file` puts the old text back. A call that passed `file_path` ends its text with `written back to <file>:<line>` or `not persisted: <reason>`, and the structured result carries it as `writeBack`. An eval with no `file_path` touches no file. `timeout_seconds` bounds the whole call (default 120, at most 600, a larger number is cut to 600): at the limit the eval is cancelled and the answer says so, with the figure that applied. A wait (a sleep, a lock, an event) stops within a second and the session stays Ready. A tight loop cannot be stopped, and neither can most native calls (a loop that calls the runtime may or may not stop): the eval's FSI host is killed 10 seconds after the cancel, and the session then says its state and definitions are gone and offers `hard_reset_fsi_session`. Every eval runs on a thread with 256 MB of stack; code that recurses past that ends the host with a `stack overflow` report that names the recursing function. |
| `write_back` | Change one declaration in source through SageFs. Pass `code` (one `let` value or function), `file_path` and `block_start_line` (the 1-based line the declaration starts at); both are required. The declaration is evaluated in the live session first, and only a successful eval that matches the declaration at that line is spliced into the file, so `run_app` and the next build see the change. Writes go through the same journal as `nudge_value`, and `nudge_value` with `action=undo` and the same file puts the old text back. The result carries `writeBack`: `written back to <file>:<line>` or `not persisted: <reason>` naming the guard that refused. Nothing is written without a successful eval. |
| `profile` | Run F# in the session like `send_fsharp_code` while the daemon records the session's FSI host from outside it, then reply with the eval's own output followed by where managed CPU time went (`mode=cpu`) or where the sampled allocations went (`mode=alloc`). The recording is made by an installed `dotnet-trace` attached to the host's process id (`dotnet tool install -g dotnet-trace`), so the host loads nothing for it; it is stopped with a signal, written, converted to Speedscope for the CPU table (the allocation table reads the nettrace file itself) and read, and every file it wrote is removed when the call returns. The table has methods by self time and your own code by total time (frames of code you typed into the session, `FSI-ASSEMBLY`, and of the projects the session loaded; rows of that table overlap because a frame counts once per sample however often it recurs), each with its share of the managed CPU sampled and an `(other)` row so the shares sum to 100. Between them, the time threads spent waiting for a garbage collection to finish (a thread seen in the runtime's GC poll), as a share of the managed time: a large share means allocation is the cost, and `mode=alloc` says where. Below, what was not counted: time in native code or waiting (idle threads sit there) and blocked time. Times are the trace's sampled time and run well under the wall clock, so read the percentages. The eval needs to run for about a second or more to be sampled. `mode` is `cpu` (the default) or `alloc`. `mode=alloc` records the runtime's GC events at verbose level, which sample one allocation for about every 100 KB with the stack of the allocating thread, keeps the nettrace file the tool writes and reads it with a reader of our own (no package): the table has bytes by type, and bytes by type at the nearest frame of your code (the first frame walking from the allocation that is code you typed into the session or a project the session loaded), each with its share and an `(other)` row. Measured on a real host: 64,008,288 bytes sampled for a record type the eval had allocated 64,000,000 bytes of, placed at the function that allocated it. An unknown mode is refused by name before a session is looked up. A refusal says what to do next and the code did not run: `dotnet-trace` missing, the recorder could not attach, the session runs in the worker process or has no running FSI. A host that ends while it is recorded gives `HostGone` and the eval's own reply is kept. A trace that holds no sample to report is `NoSamples`, never an empty table. The reply is bounded (15 rows a table, 6,000 characters). A host's diagnostics socket lives in its `TMPDIR` and a socket path holds 107 characters, so a daemon started with a `TMPDIR` longer than 63 characters starts its hosts with `TMPDIR` spelled through a short link (`/tmp/sf-<hash>`) to the same directory; if no link can be made the profile is refused by name with the directory and the limit. When the recorder cannot attach, the refusal starts with the recorder's own message. Linux and macOS only: stopping the recorder needs a POSIX signal. |
| `check_fsharp_code` | Type-check a snippet without running it, in the current FSI context. Earlier `send_fsharp_code` definitions are in scope, but namespaces still need an explicit `open`. A "not defined" error here almost always just means you forgot the `open`, nothing more sinister. |
| `signature_at_caret` | The inferred signature of the declaration under a 1-based (line, column) caret in a source file, from the session's live compiler. Pass `file_path`, `line` and `column`; the caret may sit one past the line's last character. The reply is the declaration's name and its signature on one line, then the compiler's kind, or a named reason: a bad path or out-of-range address, a caret not on an identifier, a name the compiler did not offer, or a session that could not be asked. No source file is changed. |
| `cancel_eval` | Cancel a running evaluation. Pass `session_id` to name the session (without it the call routes by `working_directory`). The cancel that `send_fsharp_code`'s `timeout_seconds` makes names its own request, so it never reaches another caller's eval: an eval still queued behind another one is cancelled before it ran, and the eval ahead of it is untouched. The eval is cancelled in the FSI host, and the call ends when the host says it stopped. A host that has not said so after 10 seconds is killed, so a session never stays stuck in `Evaluating` or `Cancelling` behind an eval nobody can stop. |
| `get_daemon_status` | Daemon version, health, memory, process telemetry, and session counts, including with no active session. `overall` is `Degraded` while a component the daemon depends on has failed (a file watcher that lost events under a deleted worktree, for one), and `componentFailures` lists each with its `name`, `reason` and a `hint` for what to check next; `sagefs status` and the dashboard header say the same. `leases` is who holds the expensive-work pool. `hatch` is how many times the `sagefs-repl-guard` hook let a `dotnet build`, `test`, `run` or `fsi` through while this daemon was up, by kind: `since` is when the daemon started, `total` and `lastRecordedAt` (null until one is reported) say how many and when, and `uses` has one row for each of the six kinds (`declaration` is `declared` or `undeclared`, `repl` is `ready`, `faulted` or `not_ready`) with its `count`, zeros included. Only a machine running the hook reports, and the count starts over when the daemon restarts. See [Agent hooks](../tools/agent-hooks/README.html#counting-the-escape-hatch). `agentSkill` appears only when the `sagefs` skill in `~/.claude/skills` is an older copy or a different skill, and names `sagefs install-skill`; a missing or current skill adds nothing. |
| `get_session_status` | The selected session's lifecycle, loaded projects, progress, and tools available in the current state. Pass `wait_seconds` (default 0, capped at 60) to wait for a warming session to become Ready, or for a rebuild to finish, instead of polling; the `wait` field in the reply says how it ended (`NotNeeded`, `BecameReady`, `Faulted`, `TimedOut`). A rebuild that is still running is waited on, because the old worker keeps serving and reads Ready the whole time: `BecameReady` means the new build's worker is up, `Faulted` means the rebuild failed (the old build is still serving), and `wait.lastRebuild` says what the rebuild did (`Succeeded`, `FailedStillServing`, `FailedNotServing`, `InProgress` when the wait ran out, `NoneRecorded`). `lastReload` says what the last save did: a patch reads `PatchPending` until the new code has been seen running, then `Patched`, or `NeverEntered` if the bound passed first. See [Hot Reload](hot-reload.html#what-patched-means). `replFreshness` says whether the REPL and live tests run the build the app runs: `InSync`, or `BehindApp` with the number of saves and what was patched, after an app started with `run_app` was patched in place, or `Unknown` with a `reason` (`SessionGone`, `LookupFailed` or `NotRead`) when it could not be read, which is never to be taken for `InSync`. `send_fsharp_code`, `check_fsharp_code`, `run_tests` and `list_sessions` say it too, after their results. `sourceState` is a different fact: whether the build the session runs is behind the files on disk. It is `InSync`, `Stale` (with the files that were written after the build, and when), `Rebuilding` (a rebuild is in progress and the old worker is still serving), or `Unknown` (with why: no project is loaded, the worker did not say when it loaded its build, a file could not be read). It is in every shape of the reply, including the warming and faulted ones. `replFreshness` is the REPL behind the app, and `sourceState` is the disk ahead of the build, so they can be true together, apart, or not at all. |
| `get_recent_fsi_events` | Recent evals, errors, and loads with timestamps. |

## Sessions and lifecycle

| Tool | What it does |
|:---|:---|
| `create_project_session` | Create an isolated session for one explicit `.fsproj`. Missing generated build state is rebuilt before the session is registered. |
| `create_solution_session` | Create an isolated session for one explicit `.sln` or `.slnx`. |
| `create_bare_session` | Create an isolated project-free REPL. It never auto-discovers. |
| `list_sessions` | List active sessions. Every entry ends with a `Source:` line: in sync with the build, no project loaded, or the same warning `get_session_status` carries as `sourceState` when files changed after the build, a rebuild is running, or it could not be told. A session an agent created also carries an `Owner:` line above that one: whether the connection that made it is still here, or how long it has been gone, and how long the session has been idle. That is what the daemon's reaper reads (see `stop_session`). A session a person made, from the dashboard, the CLI or an editor, has no `Owner:` line. |
| `switch_session` | Change which session your calls route to. |
| `stop_session` | Stop a session by id. A session another MCP connection created can only be stopped by that connection; the refusal is an error result (`isError` is true). A session with no record of a maker can be stopped from any connection, and nobody is asked first: one made from the dashboard, the CLI or an editor, or one a daemon restart resumed (the record of makers lives in memory). If the creating connection never does, the daemon stops the session for you once the connection has been gone for 12 hours and the session has been idle for 12 hours (`SAGEFS_ABANDONED_SESSION_HOURS`, `0` turns it off). It writes one log line saying why, and `list_sessions` shows the stop under the live sessions. A session with no record of an agent maker, one made from the dashboard, the CLI or an editor, is never stopped this way. Stop your own sessions when you are done. |
| `reset_fsi_session` | Soft reset: clears definitions, keeps loaded DLLs. |
| `hard_reset_fsi_session` | Full reset: rebuilds the project, reloads, starts fresh. Needed after `.fsproj` or package changes. With `rebuild=true` it answers at once and builds in the background; call `get_session_status` with `wait_seconds=60` to wait for the outcome. In a repo that builds its own SageFs.Core, the build compiles against that Core, not the daemon's. |
| `get_available_projects` | Discover `.fsproj` / `.sln` / `.slnx` files under a directory. |
| `list_members` | The members of a qualified name (namespace, module or type): one rung of the symbol ladder. Names only. The reply gives the total and a count per kind before the names (for example `12 modules, 40 methods, 3 classes`, then how many are drillable, the split the VS Code Type Explorer expands on), lists drillable kinds first, and ends with an offset footer for the next page. The kind of each member is the one the compiler gave it: the worker sends it with the name. The total is exact, or reads `at least N` when the worker's list was cut at its bound of 2000 members. A name that lists nothing says why instead of `0 total`: it is a leaf (a method, a value, a property), its path stops resolving (the reply names the prefix that lists, the member it cannot find there, and up to five near names), a parent's list was cut at the wire ceiling so the name may be past the cut, or the session could not be asked. |
| `list_references` | Every definition and use of a qualified name across the session's projects: the rung below `list_members`. The first line of the reply is the scope, `Scope: project-wide` when the compiler checked every project of the session, `Scope: partial` naming the projects it did not reach, or `Scope: unavailable` with the reason. A count never appears without that line, and a partial count covers only the projects it names. The name is walked before the compiler is asked: a name whose path stops resolving (`System.IO.Pth`) answers `Scope: unavailable, the name does not resolve past System.IO.` at once, names the member it could not find and up to five near names listed there, and does not spend the budget. A parent's member list cut at the wire ceiling, or one that could not be fetched, does not show the name is absent, so those still go to the compiler. The compiler's own full name decides what matches (a call through an alias, an `open` or a pipeline counts; a same-spelled name in another module does not; overloads of one method count together). One budget (`SAGEFS_REFERENCES_CHECK_SECONDS`) covers all projects together, and a skipped project's line states the budget and the time spent. The compiler's cache stays between asks, so a second ask goes further. The worker drops it when its resident bytes pass the ceiling (by default a share of the machine's memory, between 1280 MB and 8192 MB, so a large machine keeps a large session warm and a small one does not hold more than it can spare; `SAGEFS_REFERENCES_RESIDENT_CEILING_MB` sets it outright), when nobody has asked for ten minutes, or when the machine's memory pressure is not normal, and writes why to the worker log. The next ask after a drop starts cold and is paid for from the same budget. Files that did not check cleanly are named, because a use inside one may be missing. References are listed by file, line and column with their kind, a page at a time, ending with the offset for the next page. |
| `list_runnable_projects` | List the session's projects and which ones `run_app` can run (`OutputType=Exe`). |
| `switch_workflow` | Switch the session's workflow: `repl` (Interactive), `livetesting` (Live Testing), or `live` (Hot Reload, aliases `hotreload`/`weblive`/`web`, kept for backward compatibility). Creates a new session in the target workflow and stops the old one; VS Code and the dashboard's own `POST /api/sessions/{sid}/workflow` route restart the same session id in place instead. |

## Hot reload and running apps

| Tool | What it does |
|:---|:---|
| `enable_hot_reload` | Turn on file watching and hot reload for the session. |
| `disable_hot_reload` | Turn it off. |
| `reset_hot_reload_state` | List the live state a save kept when you edited its initializer (binding, kept value, waiting initializer), or pass a binding to run only that initializer in the running app. |
| `set_reflection_read_mode` | Show how hot reload watches values read through reflection (the mode, whether the watch is on, and any question a hot reflective loop raised), or pass `exact-every-read`, `mark-on-reflect` or `probe-callers` to switch the running app. No restart. See [Hot Reload](hot-reload.html#reflection-reads). |
| `nudge_value` | Nudge one value in a source file the session owns and write it back as just that expression. `action=inspect` lists what can be nudged (each address, its text, its hash, where it sits as `line`, `column`, `endLine` and `endColumn` and, for a literal, its kind and its `value` typed by that kind). `action=set` takes a literal or an expression plus the hash you inspected. `action=undo` and `action=redo` step through what the tool wrote. Pass `session_id` when several sessions share a directory. Only the session's project files are touched (a file outside them is refused as `NotOwned`; a project file hot reload is not watching is written, and the reply carries the `FileNotWatched` note), a stale address is refused with the reason and never guessed, a number its type cannot hold (a byte past 255, `NaN`) or outside a range chosen for it in `.SageFs/tweak-limits.json` is refused as `ValueOutOfRange`, the file is replaced by a rename so a failed write leaves it byte-identical, and every write is journaled first. A member token needs the Implementer role. See [Hot Reload](hot-reload.html#nudging-a-value). |
| `run_app` | Run the session's executable project the way `dotnet run` would, with hot reload. Applies `launchSettings.json` (first "Project" profile) and picks a free loopback port when the project sets no URL. Restarts an Interactive session into the Hot Reload workflow first, so REPL bindings are lost. Saving source then hot-patches the running app, including a route table built once at startup. |
| `stop_app` | Stop the app started by `run_app`. Its web host stops and frees its port; the session keeps running. |

## Testing and verification

| Tool | What it does |
|:---|:---|
| `list_tests` | List discovered tests, grouped by file with source locations. A compiled-project session's tests are ReflectionOnly and carry no file/line, so those come back under a separate `WithoutSourceLocation` field instead of being dropped. Optional pattern or file filter. |
| `run_tests` | Run the session's discovered tests through the live-testing engine and get a receipt. Filters: `pattern`, `file_path`, `category`. Waits up to `wait_seconds` (default 30, at most 60); a run still going hands back a `receipt_id` to call again with. |
| `targeted_verify` | Plan a trustworthy verification pass for one changed behavior. Refuses to claim green when session trust is ambiguous or loaded code is stale. It doesn't run tests itself. It returns the next trustworthy move. |
| `explain_test_failure` | Enriched failure context for a test that recently went from passing to failing. |

`run_tests` is a door into the live-testing engine, not a second test runner. It
sends the same request the dashboard and the editors send, and what comes back is
the engine's own record of that run. So `list_tests`, the dashboard and the
receipt can't disagree: they're reading one place.

The receipt never calls a test passed unless this run passed it. A pass left over
from an earlier run doesn't count, and neither does a skipped test, a test the run
was cut off before, or one that never reported. A run where every requested test
passed is `AllPassed`, a run where any failed is `SomeFailed`, and everything else
is `Incomplete`, which is not green. Each line says what happened to that test in
this run and why. If the session is still warming up, has nothing discovered, or
your filters match nothing, `run_tests` says so and runs nothing.

The tests run in the build the session loaded, and the files on disk can be newer
than that build. So a finished receipt also carries `source`, the same
`sourceState` that `get_session_status` has, read when the run was dispatched and
again when it finished (the worse of the two counts, so an edit during the run
shows up), and fixed once the run settles. `AllPassed` means every test passed and
`source` is `InSync`. A pass over anything else gets its own verdict:
`PassedOnStaleSource` (files changed on disk after the build; `source` names them),
`PassedWhileRebuilding`, or `PassedOnUnknownSource` (a file could not be read, the
worker did not say when it loaded, or no project is loaded). None of those is
green. The text says it too, as `passed, but on STALE source`, and ends with a
`Source:` line. The run still happens and the receipt says what it ran against.
`hard_reset_fsi_session` with `rebuild=true` brings the build level with the files. The mtime check can read a file as changed that only
got touched (a branch switch does that), and it cannot see an edit made inside
the window of a build that was already running.

Don't run `dotnet test` from an agent to do the same job. That's a second engine,
and its answers are the ones that drift. `dotnet test` and `dotnet run` stay as
the final gate before you push.

## Analysis and diagnostics

| Tool | What it does |
|:---|:---|
| `diagnose` | Diagnostic report for one session: its test failures with causal changes, the cells they touch, a ripple plan, suggestions, eval timing. Says which side it could not read (`Unmeasured`). |
| `coverage_intel` | Coverage-quality analysis for one session's failing tests: blind spots, correlated failures. Needs live testing's instrumented runs. |
| `impact_forecast` | How many REPL cells sit downstream of a cell, and how long the session's evals take. About cells, not source code. |
| `suggest_next_action` | Prioritized "what next" queue combining coverage, impact, and staleness. |
| `suggest_next_cell` | Type-directed suggestions for what to evaluate next, from the bindings the session's evals made. |
| `suggest_repair` | Given a failing test, trace causal changes and suggest the symbol to fix. |
| `plan_ripple` | Plan cascade re-evaluation for changed cells using the session's eval dependency graph. |
| `preview_what_if` | Preview what would change if a binding had a different value, without executing. |
| `decompose_pipeline` | Break an F# pipeline into stages, each classified pure / effectful / unknown. |
| `get_cell_dependencies` | The cell dependency graph of one session: what each eval produced and consumed, and the edges between them. Reports staleness as `NotMeasured`. |
| `discover_features` | Ranks the tools this daemon registers by the session's state. The list is read from the registered set, so it cannot name a tool that is not there. With `tool` it returns that one tool's full manual (its rules and every parameter), which `tools/list` no longer carries. It is callable in every session state, with no session at all, because a client on the starter list has none yet. |

### Measured, or not available

Seven of these (`diagnose`, `coverage_intel`, `impact_forecast`, `plan_ripple`, `preview_what_if`, `suggest_next_cell`,
`get_cell_dependencies`) used to answer an empty list, `0 downstream` or `No issues detected` when they had nothing to read. A
policy that reads that as "measured, nothing wrong" is acting on a number nobody counted. So each of them answers one of two
things, in `structuredContent.answer`:

- `Measured`: it read the data. The text block is the measurement as before. A `Measured` empty list or a `0` is a real zero.
  `unmeasured` lists any side it could not read (`diagnose` says `Tests` when the session has evals and no recorded test result).
- `NotAvailable`: the data was not there. `reason` is a closed token, `message` says what is missing, `whatToDo` says what to do,
  and the text block is that same sentence, starting `Not available (<reason>).`

| Reason | Means | What to do |
|:---|:---|:---|
| `NoSessionResolved` | No session could be found for the call. | Pass `session_id` or `working_directory`. |
| `SessionNotReady` | The session is warming up, faulted or not routable. | `get_session_status` with `wait_seconds=60`. |
| `NoEvalsYet` | The session recorded no evals. | `send_fsharp_code` in that session. |
| `NoTestRunYet` | The session has no recorded test result. | `run_tests` for that session. |
| `NothingObservedYet` | `diagnose` has neither evals nor test results. | Either of the two above. |
| `CellsNotInHistory` | The cell ids are not in that session's history. | Take ids from `get_cell_dependencies`. |
| `NoUsableCellIds` | `changed_cells` was not comma-separated integers. | Pass `'0,2'`. |
| `BindingNotInScope` | `preview_what_if` was given a name nothing bound. | Evaluate it in that session first. |
| `NeedsAWorkflow` | Coverage comes from the LiveTesting workflow and the session is not in it. | `switch_workflow` with `target='livetesting'`, then `run_tests`. |
| `NeedsLiveTesting` | LiveTesting workflow, but live testing is switched off. | Switch it on in the dashboard or an editor, then `run_tests`. |
| `NoCoverageRecorded` | Live testing is on, but no instrumented run has recorded coverage yet. | `run_tests`. |

Only `coverage_intel` fundamentally needs live testing: coverage bitmaps come from its instrumented runs and nowhere else. The
others need the session's own evals or test results and nothing more.

**One session per call.** These tools take the same `session_id` and `working_directory` routing as `run_tests`, and with neither
they answer for the session the connection is working in. They read that session's own eval history (what `send_fsharp_code`
recorded for it) and the live-testing state that owns that session's tests, which is where `run_tests` records its results. They
never read another session's data, and they never fall back to the primary session's.

**`impact_forecast` is about REPL cells.** A cell is one `send_fsharp_code` eval. Downstream means later evals that use a name this
one bound. It does not measure the blast radius of a change to your source files and it does not say which tests a change
affects, so do not gate a change on it. `run_tests` is the tool that answers about tests.

Completions, per-file coverage, the symbol-to-tests lookup and the domain-model diagram are not MCP tools.
The editors reach the first and second over the daemon's HTTP API (`/api/completions`,
`/api/live-testing/file-annotations`), and `discover_features` does not list them. The type explorer is the tool
`list_members`; the editors keep their own route for it (`/api/explore`).

`POST /api/completions` answers `{ completions: [{ label, kind, insertText, detail? }], count, total, totalKind }`.
`kind` is the compiler's own (`Method`, `Module`, `EnumMember`, ...), `count` is the items in the reply, and `total` with
`totalKind` (`exact` or `atLeast`) give the size of the set they were cut from. The default cut is 50; a request may send
`limit` (1 to 2000) for more. A reply that could not look, because the session was not active or its host was gone, carries
no items and `unavailable` (a stable word) with `reason`, so an empty `completions` always means there is nothing to list.

`GET /api/dependency-graph` is the symbol-to-tests lookup. It lists the tests that cover a symbol; it has no call edges. It
answers for one session: `?session=<id>` names it, and with none the route follows the rule `GET /api/live-testing/status`
follows (the only session, else a refusal that names the choices). Without `symbol` the reply is
`{ Session, State, Symbols: [{ Symbol, TestCount }], TotalSymbols }`; with `?symbol=<full name>` it is
`{ Session, State, Symbol, Tests: [{ TestId, TestName, Status }], TotalSymbols }`. The tests are the ones discovery found. A
symbol is tied to a test by the name graph or by recorded coverage: a symbol on a line of an analysed file is covered by the
tests whose own coverage reached that line, and lines that run when a module initializes belong to no test. `State` says why
a map is the size it is: `nothing_analysed` (no file of the session has been type-checked, so the next edit or save fills it),
`no_coverage_recorded` (files are analysed and a test run fills it), `coverage_of_another_build` (tests have coverage, but
not of the build the session holds, so a run against the built assembly fills it), `nothing_reached` (coverage is recorded and
no test reaches an analysed symbol, so it will not fill by itself) or `mapped`.

## Export and history

| Tool | What it does |
|:---|:---|
| `export_notebook` | Export the session as a notebook-style `.fsx` with cell metadata. |
| `export_session_transcript` | Export the session as a clean, topologically sorted `.fsx` transcript. |
| `get_session_filmstrip` | Visual history of evaluations: each a frame with code, bindings, and duration. |
| `get_eval_timeline` | Eval-duration sparkline and P50/P95/P99 statistics, and for each of the last 20 evals the bytes the host measured it allocating (`312.4 MB allocated`, the same figure as the reply's [cost line](#what-an-eval-reply-looks-like)), left off when the eval was not measured. |
| `get_eval_diff` | Before/after diff of recent evaluation outputs. |
| `get_message_journal` | Audit log of eval events, filterable by severity and source. |
| `manage_scratch_pad` | View, export, or promote ephemeral snippets from session history. |

## Friction telemetry (local only)

These read and write a local log. They don't phone home. I have zero
interest in your code or your keystrokes, and building a telemetry pipeline
sounds like a chore anyway.

| Tool | What it does |
|:---|:---|
| `get_friction_summary` | Compact summary of recorded MCP friction. |
| `get_friction_report` | Structured JSON report of MCP pain points. |
| `report_friction` | Record structured feedback about a confusing tool call. |
| `manage_local_data` | See what SageFs stores under its data dir (rows, bytes, oldest row, retention rules), or clear it. Clearing is the one call that asks a person first, on a client that can be asked. It is refused while ANY cohort the daemon runs is active, not only the daemon's own, and only the conductor of the cohort named by `working_directory` may call it. |

## Leases for expensive work

A full build, a test suite and an app run each cost real memory. One night five
agents did one each against a single daemon and nothing coordinated them, so
the daemon's memory was already high by the time it could tell. An agent that
starts one of these itself asks for a lease first and gets back `granted`, `wait`
with a retry time, or `refused`. SageFs's own session creation and
`hard_reset_fsi_session rebuild=true` take their own leases, so an agent doesn't
lease those. The full rules, for an agent, are in
[`skills/sagefs/leases.html`](../skills/sagefs/leases.html).

A lease belongs to the connection, the `agent_name` and the `working_directory` it
was asked for under. Claude sub-agents of one session share one MCP connection, so
each of them passes its own `agent_name` (and its own `working_directory`) to be a
holder of its own. Asking again under the same three returns the lease you already
hold (`grant: already_held`, same `leaseId`, expiry not renewed). A `wait` names who
holds the pool (agent, connection, directory, kind of work, when it was granted and
when it lapses), your place in line and when to ask again, and asking again keeps your
place. `get_daemon_status` shows the same rows under `leases`, one per holder.

| Tool | What it does |
|:---|:---|
| `acquire_full_build_lease` | A lease for a full `dotnet build` you start yourself. Takes `agent_name` and `working_directory`. |
| `acquire_test_suite_lease` | A lease for a test-suite process you start yourself (`dotnet run --project <tests>` or `dotnet test`). SageFs has no tool that runs your suite for you. It runs its own tests through the live-testing engine, and you read them with `list_tests` or `run_tests`. Takes `agent_name` and `working_directory`. |
| `acquire_run_app_lease` | A lease for a run-app process you start yourself. SageFs's own `run_app` is a different thing and needs no lease from you. Takes `agent_name` and `working_directory`. |
| `release_work_lease` | Release a lease by the id a granted acquisition returned. A lease held by another connection is never released. Sub-agents that share your connection can release it by its id, so keep the id to yourself. |

A lease that is never released is reclaimed when it expires, and a queued ask
that is not repeated within five minutes loses its place, so an agent that
crashes can't hold a slot, or a place in line, forever.

## Workspace hygiene

Agents and orchestrators leave things behind: worktrees, merged branches, the
gate's checkouts, built FSI hosts, test temp dirs, orphaned processes. These
two tools show it and tidy the part that is safe. They are about the
repository and the disk, not a session, so they work before one exists.
`sagefs hygiene` prints the same plan from a shell, and `sagefs hygiene --tidy`
runs the safe part of it. Both take `--repo PATH` for a repository you are not
standing in.

| Tool | What it does |
|:---|:---|
| `get_workspace_hygiene` | A dry run. Lists each leftover with its size, age, who made it and a standing that says why it is or is not safe to reclaim, then the plan: safe to reclaim, needs a look (with the command that saves the work first), and left alone with the reason. Ends with a plan id. |
| `tidy_workspace` | Runs the safe part of that plan. Needs `confirm=true` and the plan id you were shown. Each step looks at its target again first and skips anything that became busy. Never touches unmerged commits, uncommitted work, anything in use, or anything it could not judge. |

`create_*_session`, `get_session_status` and `get_daemon_status` add one line
when a repo has more than a handful of leftover worktrees or the gate dir has
grown past a threshold: `workspace: N leftover worktrees (X GB), M safe to
reclaim: call get_workspace_hygiene`. Work that exists nowhere else leads the
line: `workspace: 3 worktrees hold work that is nowhere else, oldest idle 38d`.

The daemon does not wait to be asked. At start, every `SAGEFS_HYGIENE_SWEEP_MINUTES`
(15 by default) and whenever a session stops, it sweeps each repository it has a
record of (a live session, or a session it made once, if the directory still
exists):

1. It writes each agent worktree into `<data dir>/hygiene-ledger.jsonl` when it
   first appears and when it goes quiet or is resumed, with who made it. The file
   only grows.
2. It commits the uncommitted files of a worktree nobody is using, ignored files
   that nothing regenerates (a local `.env`, a `*.db`) included, to
   `refs/sagefs/salvage/<name>`, with a temporary index, so the worktree itself
   is untouched. The ref is not a branch, so `git push --all` does not publish it.
   A second sweep with nothing changed commits nothing. A salvage ref is listed by
   `sagefs hygiene` and reaped once its worktree is gone and the base has
   everything on it, or after 30 days.
   A worktree locked with `git worktree lock` by a person is never unlocked or
   removed: only the harness's own lock (`claude agent <name> (pid N start M)`),
   and only when that process is dead, is released.
3. When the setting `hygiene.autoTidy` is on (the default), it tidies what is
   provably safe: a worktree whose work has reached the base branch and that the
   ledger has seen quiet for `SAGEFS_FINISHED_WORKTREE_GRACE_DAYS` (1 day; `0`
   means no grace), expired worker logs and temp runs, orphaned registry entries
   and merged agent branches. A worktree the ledger has never seen waits a full
   grace from the first sweep, however old git says it is. A commit the base only
   has by content (a rebase or squash) is kept reachable at
   `refs/sagefs/removed/<name>` first, and each removal is a ledger line with the
   tip it had. A worktree that holds commits the base lacks or uncommitted
   changes, one a session, lease, process or cohort is using, and anything outside
   the managed directories is never removed.

A checkout a cohort holds (a member token is bound to it, or it is the cohort's
integration or trunk checkout) reads as `in use: a cohort holds it`, and a
`<repo>.tiers` directory beside a repository that nothing uses (the CI
pipeline's tier work) is listed as needing a look. `sagefs hygiene` lists both and
removes neither.

`sagefs hygiene --rescue <name>` puts a worktree's work on `rescue/<name>`:
its branch and salvage commit, rebased on the base, and it says whether the base
already has the change, by patch id and by content.

## Cohort and multi-agent coordination

For running several agents against one repo at once. One implicit cohort per
daemon; the first agent to join becomes its conductor. Every tool resolves
the caller's identity from the MCP connection, not the `agentName` argument.
Two connections that pass the same name are still two different members.

A member's id in every cohort output (`get_cohort_status`, the `cohort://status`
frame, the SSE rows, the ledger export, the lease listing) is `mcp:m-<16 hex>`,
a one-way fingerprint of the connection's session id. It used to be the session
id itself, which is the SDK's bearer handle: anyone who could read the status
could present it as `Mcp-Session-Id` and act as that member, the conductor
included. The id names a member now and cannot be used to be one.

**Which name the id is a fingerprint of.** A member token, if the call presented one (the id is then `cap:<id>`).
Otherwise the **client key** of the stdio bridge, if the request carried one. Otherwise the connection's session id,
as before (HTTP clients, `sagefs call`, the dashboard).

`sagefs mcp` makes 256 random bits once, when the process starts, and sends them on every request it forwards in the
`X-SageFs-Client-Key` header, including the requests after it re-initializes against a daemon that came back. The daemon
derives the member id from the key (a SHA-256 fingerprint under its own domain, the same `mcp:m-<16 hex>` shape) at its
HTTP edge and carries only the id from there: the key is in no claim, status text, ledger row or log line. So a daemon
upgrade, a restart or a dropped connection leaves the same client the same member. It stays the conductor, and its
claims stay its own. Before 2026-11-07 every restart made the bridge a new member (`mcp:m-ed00…` became `mcp:m-ac28…`),
the old member kept the seat until its lease lapsed and `sagefs cohort seat` refuses a seat that is bound, so the
conductor was locked out for up to 30 minutes. A second bridge is a second client with a key of its own, and is its own
member. A key that is present and is not a key (wrong length, a character outside base64url) is refused with a 400 that says
why.

The key is a bearer secret held by the bridge process, as the session id was, and it goes only to the local daemon. Anyone
who can read the bridge's memory or its requests can speak as it. A client key never outranks a member token.

**What keeps a seat.** A member's lease is renewed by the daemon's reaper every minute for each member it can see is there:
one that evaluated lately, made a tool call lately (any call the daemon admitted), or holds an open push stream. A stdio
bridge keeps its stream open for as long as its client lives, so a conductor that is only waiting on its agents keeps its
seat. A member with no open stream and no call for 30 minutes (`Timeouts.cohortLeaseWindow`) is departed, as before. A
member that presents a token has the token's own lease (30 minutes without a call), and the stream does not renew it.

**Every cohort tool below takes `working_directory`.** Cohorts are scoped per repository,
so a tool needs to know WHICH repository's cohort you mean: `join_cohort` in Nehemiah and
`join_cohort` in Molina are different cohorts with different conductor seats, and one global
cohort would have made the second collide with a cohort it never asked for. It must be the
exact MCP wire name `working_directory`, the registered tool surface enforces that spelling
on every directory parameter, so one name works everywhere a client needs it. The rows
mention it only where the behaviour is worth calling out; assume the rest take it too.

**If a cohort tool says you have not joined.** The refusal reads `<tool> needs a seat in the cohort this
call acts in, and you have not joined it`. Either you never called `join_cohort`, or you joined a
different repository's cohort than the one this call names. Call `join_cohort` with the same
`working_directory` you pass to the failing tool, then retry. A call that names no directory acts in the
cohort of the repository the daemon was started in, so an agent in any other repository has to pass its
directory on every cohort call, not just the first. `get_cohort_status` with that directory shows whether
you are seated there.

A conductor-only tool (`set_integration_ref`, `mint_member`, `revoke_member`, `reassign_claim`, `delegate_conductor`,
`resolve_veto`, `manage_local_data`, `tidy_workspace`) called by someone with no seat in the cohort the call acted in is
refused the same way, naming that cohort: `<member> cannot call set_integration_ref: this call acted in the cohort
repo:/path, and you have no seat there (you have not joined it).` The next action is to join with the same
`working_directory` and pass it on the call. Daemons up to 0.6.940 said `your role is Working: set_integration_ref is
not in your grant` here, which read as a permissions problem when the caller was the conductor of the right
repository and had only called the daemon's own, empty cohort.

Daemons up to 0.6.891 got this wrong in the other direction: an Implementer who had joined a repository
other than the daemon's own (and was its conductor) was refused `acquire_claim`, `release_claim` and
`request_landing` with `your role is Working: that needs the Working role`. The gate was reading the
daemon's own cohort instead of the one the call acts in. If you see that text, the daemon predates the fix.

| Tool | What it does |
|:---|:---|
| `join_cohort` | Join your repository's coordination session. The first joiner **of that repository** becomes its conductor. Takes `working_directory`: cohorts are per repository, so an agent in a second repository joins a second cohort with its own conductor seat instead of colliding with a cohort it never asked for. The reply always says which seat you hold: that you are the conductor, who the conductor is, or that the seat is vacant and why (the conductor left, its lease lapsed, or it was revoked). Through `sagefs mcp` your identity survives a daemon restart (it comes from the bridge's client key), so you are still the conductor afterwards. A client that talks HTTP directly gets a new identity after a restart, and a reply naming a conductor that is not you means your old self still holds the seat until its lease lapses. |
| `leave_cohort` | Leave. Any claims you still hold are orphaned, and the reply names each one with its scope (the conductor reassigns them with `reassign_claim` or clears them with `release_claim`). A conductor that leaves empties the seat, and the reply says so. **The conductor is refused while it holds claims** (`ConductorHoldsClaims`): leaving would orphan them with nobody seated to hand them on, so the refusal names the claims and says to `delegate_conductor` first or `release_claim` each one. A sub-agent on its parent's MCP connection is the parent, so its `leave_cohort` departs the parent. |
| `get_cohort_status` | Members, claims and fences, the test matrix, the landing queue, and what the trunk did with each landing (see below). Wait-free: reads a published snapshot. The `cohort://status` MCP resource is the frame as JSON for subscription, and doesn't carry the trunk lines. Takes an optional `working_directory`: one daemon holds one cohort **per repository**, so pass the directory you are working in to read that repository's cohort. Omit it and you read the cohort of the directory the daemon itself started in. |
| `acquire_claim` | Take an exclusive claim over a file or project (`file:<path>` or `project:<path>`) so others know it's yours to edit. A page a script generates (`docs/roadmap.md`, `docs/configuration.md`, `docs/client-setup.md`) needs no claim: the reply says so and takes none. Asking again for a claim you already hold over the same scope keeps it and renews your lease: the reply is `You already hold claim c-... over <scope> (fence=n); your lease is renewed.`, with the fence `release_claim` needs. See [how a landing is verified](#how-a-landing-is-verified). |
| `release_claim` | Release a claim you hold. The presented fence must match the current one. **The conductor can also clear a claim that is not its own** when its holder has gone: silent for two minutes (no open stream, no call; the same measure that calls a seat's holder silent) or orphaned (the holder left). `get_cohort_status` marks such a claim `| clearable: ...` on its line. Naming a claim whose holder is here is refused, with how long the holder has been silent and how long it must be. A clear is a release: the fence moves on, the old holder's late `release_claim` is refused as stale, and a landing it had queued is blocked as stale when it reaches the front (withdraw it and request it again). Under a member token a call never clears, and a member that is not the conductor is refused. The ledger records `ClaimCleared` (claim, former holder, how long it had been silent, who cleared it, new fence), and the `claim_changed` event has kind `cleared`. |
| `reassign_claim` | Conductor-only: reassign an orphaned claim to a present member. To drop an orphaned claim with nobody to hand it to, clear it with `release_claim`. |
| `delegate_conductor` | Conductor-only: hand the conductor seat to another **present** member. Only a sitting conductor can issue it, so it cannot fill an empty seat. Refused with the roster of present members when the target is not here, when it is yourself, and when it acts under a member token (no token may call the conductor's tools, so the seat would be stranded). |
| `seat_conductor` | Ask for an **empty** conductor seat to be filled, or for a holder whose connection is gone to be replaced. The daemon asks the person at your client through MCP elicitation, naming the repository, who is asking, who would sit and in what role, and either who held the seat and why it is empty or, with `replaces`, who holds it and how long it has been silent, and changes the seat only on an explicit yes. `toMember` names the member (default: you). `replaces` names the holder, as `get_cohort_status` prints it, and is refused (with the actual holder named, and nobody asked) when that member does not hold the seat; blank fills an empty seat. A decline, a dismissal, silence, a failed question and a client that offers no elicitation all refuse and change nothing, and the refusal names `sagefs cohort seat` and the dashboard's Seat and Replace buttons. A seated Implementer calls it; it is never callable under a member token, and a member under a token is never the one seated. |
| `request_landing` | Queue a landing: your commits are rebased onto the integration head, verified against affected tests, and fast-forwarded in. Landings are strictly serial (one FIFO queue). |
| `withdraw_landing` | Take back a landing **you** requested, in any state short of landed or already withdrawn (a vetoed one included). Nobody else can withdraw it, the conductor included. |
| `veto_landing` | Object to a **live** landing (queued, rebasing or verifying) with a reason. It is blocked, awaiting the conductor, and leaves the queue so it holds nobody behind it. Allowed for a seated Implementer, Verifier or the conductor; refused for an Observer, for someone who never joined and for a member who left. A landing that landed, was withdrawn, is blocked for another reason or is already vetoed is refused, and the first veto and its reason stand. |
| `resolve_veto` | Conductor-only: clear a veto. The landing queues again as it was, and its claims are checked again when it reaches the front. |
| `set_integration_ref` | Conductor-only: configure the git ref that landings rebase onto, in a dedicated integration worktree, and the trunk checkout the landings are carried to. Takes `working_directory`, the repository the integration is for: pass it unless the daemon itself was started in that repository (`install-local` starts it in its install folder), and `projects`, the repository-relative project the session loads when you want to name it. The reply names both (`worktree=` and `trunk=`). See [the integration](#the-integration-one-per-daemon-for-one-repository). |
| `mint_member` | Conductor-only: mint a per-run member token bound to a role, a scope prefix, the one session or checkout it may act on, and an expiry. The token comes back once. See [member tokens](#member-tokens-one-identity-per-agent-run). |
| `revoke_member` | Conductor-only: cut a member token off. It is refused from the next call, its seat departs and its claims are orphaned. Takes `working_directory` for the repository whose cohort the member is in. |

### Veto, withdraw and delegate

Four commands sat in the cohort core for a long time with nothing that could issue them: handing the
conductor seat on, withdrawing a landing, vetoing one, and clearing a veto. So a conductor couldn't leave
cleanly, nobody could object to a landing, and a vetoed landing said it was waiting for the conductor when the
conductor had no verb to answer with. They're tools now (`delegate_conductor`, `withdraw_landing`,
`veto_landing`, `resolve_veto`), and the rules are the cohort's own. `SageFs.Simulation/CohortVetoSpec.fs`
explores every command against every landing and target, with a twin for each rule that the proof has to catch.

- **Who may veto.** A seated Implementer, a Verifier, or the conductor. The old design said any present member
  and checked nothing, so someone who never joined, or who had left, could block a landing, and so could an
  Observer, whose whole job is reading. A veto needs a reason (1 to 1000 characters) and a landing that's still
  live (queued, rebasing or verifying). Vetoing one that already landed or was withdrawn is refused, not
  quietly accepted. So is vetoing one that's blocked for another reason (a veto would relabel a rebase conflict
  as "awaiting the conductor") or already vetoed (the first vetoer and reason stand).
- **Who may withdraw.** Only the landing's requester.
- **Who may clear a veto or delegate.** Only the sitting conductor. An empty seat is refused as `VACANT`, and
  nothing in the tool surface fills one: delegating needs a conductor to do it, and nobody gets promoted by a
  timer. A person seats one with `sagefs cohort seat <member id>` (see "Seat a conductor" below). A seat that is held
  by a conductor whose connection is gone is replaced by a person too, with `sagefs cohort seat <member id> --replace
  <holder id>`, or by a seated member who asks with `seat_conductor` and `replaces` and a person who says yes (see
  "Replace a conductor whose connection is gone" below). No tool does either without that yes.
- **One conductor at a time.** The seat is a single binding. A delegation moves it from the caller to a present
  member in one step and the caller is an ordinary member after. A target who isn't present gets refused with
  the list of members who are. A member acting under a token can't take the seat, because no token may call
  the conductor's tools and the seat would be stuck with them.
- **Where it shows.** `get_cohort_status` prints a veto as `Blocked(vetoed by <member>: "<reason>")` plus the
  two ways out, and the dashboard's cohort panel lists each landing the same way.

A Verifier token may `veto_landing` (that's the role that reads the tests). Observer and Analysis tokens may
not. `delegate_conductor` and `resolve_veto` are conductor-only and in no token role, like `reassign_claim`.

Claim paths are canonical. `file:src/Foo/../Bar/x.fs` is `file:src/Bar/x.fs`, so
the two overlap, and a path that climbs out of the repo (`file:../x.fs`) or is
rooted (`file:/etc/x`) is refused.

### Member tokens: one identity per agent run

An orchestrator that runs N agents behind one connection used to get one member,
because identity was the connection. `mint_member` fixes that: the conductor
mints a token per run, each token is its own cohort member (`cap:<16 hex>`), and
a token outranks the connection it arrives on.

**Mint.** `mint_member role=Analysis scope=src/Foo/ ttl_minutes=60 working_directory=/abs/path/to/checkout`.
The reply has the member id, the grant and the token (`sfm_...`), once. SageFs
keeps only the token's SHA-256, so it is in no ledger row, log line or status
text, and it cannot be shown again. Tokens live in the daemon's memory and do
not survive a restart: the orchestrator mints new ones. Because no token
outlives a restart, there are no tokens from before the route binding existed
and nothing to migrate. Only the conductor mints, and a token can only be
narrower than whoever mints it: a wider role, a wider scope, another route or a
later expiry is refused with the widenings named, never clamped.

**Mint without an MCP connection.** A person or a launcher script can mint with the
operator credential instead of a conductor's connection, so the token goes from the
daemon into an environment variable and never through a model:

```sh
eval "$(sagefs member mint --role Analysis --scope src/Foo/ --ttl 60 \
  --dir /abs/path/to/checkout --print-env SAGEFS_MEMBER_TOKEN)"
```

The command reads `operator.token` from the data directory (`SAGEFS_DATA_DIR` when
set, `~/.SageFs` otherwise), calls `POST /api/members/mint` with
`Authorization: Bearer sfo_...`, and prints one `export` line on stdout. A summary of
who was minted goes to stderr, without the token. Without `--print-env` it prints the
member, the grant and the token for a person to read. `--dir` or `--session` names the
route, exactly one of them, as for `mint_member`. The route takes the same limits as
the tool, and the member it seats is `cap:<id>` as usual. The ledger and the capability
record name the minter as `operator:`.

The operator credential is `sfo_` and 43 base64url characters. The daemon makes it the
first time it needs one: it writes a temporary file with mode 0600, reads the mode back,
and publishes it with an atomic create-if-absent, so two daemons that start on one data
directory end with the same credential and nobody ever reads half of it. The daemon
holds only its SHA-256. To replace it, delete `operator.token` and restart the daemon.
If the file cannot be made owner-only (a mounted share that ignores Unix modes, say) or
is not a credential, the route answers `503` to every caller with the fix in the
message, and no other route changes.

The route refuses with a JSON body of `error`, `message`, `case` and `suggestedAction`:

| Request carries | Status | `case` |
|:--|:--|:--|
| no `Authorization` header | 401 | `no_credential` |
| a member token (`sfm_...`) | 403 | `member_not_allowed` |
| an operator credential that is not this daemon's | 403 | `operator_not_recognized` |
| a header that is not `Bearer`, is blank, has an unknown prefix or a cut-short `sfo_` | 403 | `unreadable_...` |
| the daemon could not make `operator.token` | 503 | `operator_credential_unavailable` |

A credential that was presented and cannot be used is a 403, like a member token the
daemon cannot resolve, because that is the status that makes a client's header helper
run again. Every other route still takes no credential, except `POST /api/local-data/clear`,
which takes this one.

The limit, in plain words: the operator file is readable by every process running as
the same user, so against a hostile process of your own user this adds nothing: it can
read the file and use the routes. It also does not keep out a caller that only reaches
loopback. `/exec`, the evaluation tools and every other route but the mint, seat and
local-data routes take no credential today, so a caller that can reach the daemon's port can run
code in a session, and where the worker is not sandboxed that code can read
`operator.token`. What the credential stops is a caller that can reach loopback and can
neither read your home directory nor run code through the daemon: another OS user on a
shared machine, or a forwarded dev-container port whose callers have no eval. The
`a-token-for-every-daemon-call` item on the roadmap is what closes the open routes. The
file's owner-only mode is set and read back on Unix. On Windows the file gets an ACL for
the current user alone when it is made, and that is not read back, because it has not
been run there.

**Seat a conductor.** When the conductor leaves or goes silent the seat is empty, and an empty seat stays empty until
a person says who fills it. `delegate_conductor` cannot: only a sitting conductor can issue it. There are three ways in.
No MCP tool builds the seating command without a question being put to the person, and no member token can take the seat.
A process running as the same operating-system user as the daemon can still use the second and third ways (see the limit
above), so none of them is a guarantee against a hostile process of that user. What differs is what each asks first.

The first is the tool. A seated member calls `seat_conductor`, and the daemon asks the person at that member's client
(MCP elicitation, the mechanism `manage_local_data` uses) whether to seat the member. Only an accept with the box ticked
is a yes: the form starts unticked, so a client that applies defaults and accepts, or accepts with no content, seats nobody.
Unlike `manage_local_data`, where a client that cannot be asked is let through, a client that offers no elicitation is
refused here, because for this tool the prompt is the permission. The daemon cannot know that a person answered. It knows
the client accepted, and a client that accepts every question by itself seats on its own say, which is why the reply says
"the client at <member> accepted". The seat is the authority to mint tokens, configure the integration and reassign claims,
and an MCP tool is callable by any agent, so the code is shaped so that a seating without a yes cannot be written: the
command is built from a `SeatApproval` that only `SeatingFlow.ask` makes, after the client said yes. The cohort's rules run
first (`SeatingFlow.plan`), so nobody is asked about a seating the cohort would refuse.

The second is the Seat button on the dashboard's cohort panel, next to the vacant-seat line (one per present member, after
a native confirmation). It posts to `/dashboard/cohort/seat` with a one-use ticket the page was rendered with. The daemon
holds the ticket, for that member, for 30 minutes (`Timeouts.dashboardSeatNonceLifetime`), and the first presentation
spends it, right or wrong. A request with no ticket, a used or expired one, or one issued for another member's button is
refused, and so is one without the `Sec-Fetch-Site: same-origin` header a browser sets, which is checked as well and
proves nothing alone. The dashboard has no credential, so a process that can load the page can read a ticket out of it:
the ticket stops blind, replayed and stale requests, and does not authenticate a person.

The third is a command on the machine that runs the daemon, for a person with no client that can answer a question:

```sh
sagefs cohort seat                                   # who is present, and where the seat stands
sagefs cohort seat mcp:m-0123456789abcdef            # seat that member
sagefs cohort seat mcp:m-0123456789abcdef --dir /abs/path/to/checkout
```

With no member id it prints the cohort's scope, the seat (`held by`, `vacant since ... (who held it: why)` or `never bound`)
and the present members with their roles. With one it seats that member and prints the vacancy it ended. `--dir` names
the checkout whose cohort it is and defaults to the current directory; `--mcp-port` picks the daemon. The member id is
the one `get_cohort_status` prints.

The rules are `Cohort.decide`'s, for `SeatConductor`: the seat must be `Vacant` or `NeverBound`, and the member must be
present. A bound seat is refused and names its holder (moving a held seat is the conductor's `delegate_conductor`). An
absent member is refused with the roster of those who are present. A member acting under a minted token (`cap:<id>`) is
refused too: no token may call the conductor's tools, so the seat would be stuck with it. The ledger records
`ConductorSeated` with the vacancy it ended, and replay reproduces the seat after a restart.

It uses the operator credential, exactly as `member mint` does: `GET` and `POST /api/cohort/seat` with
`Authorization: Bearer sfo_...`, refused with the table of statuses above for anything else. No member token reaches the
route and no MCP tool builds the command without a `SeatApproval`. The credential is a file the operating-system user can
read, so a process running as that user, an agent with a shell included, can run `sagefs cohort seat` and seat itself.
The `POST` body is `{"working_directory": "...", "member": "mcp:m-..."}`.

**Replace a conductor whose connection is gone.** A conductor whose bridge changed or whose daemon restarted onto a
different identity keeps the seat until its lease lapses, which is 30 minutes (`Timeouts.cohortLeaseWindow`), and a
plain seating refuses a seat that is bound. The person at the machine does not have to wait:

```sh
sagefs cohort seat mcp:m-bbbbbbbbbbbbbbbb --replace mcp:m-aaaaaaaaaaaaaaaa
sagefs cohort seat mcp:m-bbbbbbbbbbbbbbbb --replace mcp:m-aaaaaaaaaaaaaaaa --dir /abs/path/to/checkout
```

The first id is the present member who takes the seat, the id after `--replace` is the holder it replaces. Naming the
holder is the safeguard: the command is refused when that member no longer holds the seat, so a person who looked at the
seat cannot move one that changed under them (the refusal says who holds it now). The other rules are the seating's:
the target must be present (an absent one is refused with the roster of those who are), a member acting under a minted
token (`cap:<id>`) cannot take the seat, and a holder cannot replace itself. A replaced holder becomes an ordinary member:
it stays present or departed as it was, the claims it holds stay its own and follow the normal orphan rules when it
leaves, and its calls to conductor-only tools are refused as any member's are. The ledger records `ConductorReplaced`,
which carries the former holder and the moment (as the seat it lost, with the reason `Replaced`), and replay reproduces
the seat after a restart.

Without `--replace`, `sagefs cohort seat <member id>` over a bound seat is still refused, and the refusal now says who holds
the seat, whether that member is silent and for how long, when its lease lapses, and prints the exact command to run. A
holder counts as silent when its lease was not renewed for two reaper passes (`Timeouts.cohortHolderSilentAfter`): the
reaper renews a member that holds an open push stream or made a call lately on every pass, so a holder that was not
renewed has neither. With no member id the listing carries the same line. `get_cohort_status` prints it on the
`Conductor:` line (`held by X, silent for 42 min, lapses at 2026-11-07 19:30:00Z; a person can replace it: sagefs cohort
seat <member id> --replace X`), and so does the dashboard's cohort panel. A holder that is not silent is shown as before,
and the refusal says it renewed its lease lately, so a live conductor is not replaced by habit.

It is the same route and the same operator credential: `POST /api/cohort/seat` takes an optional `"replace": "mcp:m-..."`
in the body. No member token reaches the route. The credential is a file the operating-system user can read, so a process
running as that user can replace a conductor.

Two more ways to replace one need no shell, and both put the question to a person first.

By asking, in the tool. A seated member calls `seat_conductor` with `replaces` set to the holder's member id. The daemon asks
the person at that member's client the same question as for an empty seat, and names the holder and how long it has been
silent (or says it renewed its lease a few minutes ago, so a live conductor is not replaced by habit). Only an accept with the
box ticked changes the seat, and the command is `ReplaceConductor`, built from a `SeatApproval` that carries the holder the
person was shown. Only `SeatingFlow.ask` makes an approval, so no agent can replace a conductor on its own say-so. The cohort's
own compare-and-swap on the holder still applies when the command commits: a seat that changed hands while the person read the
question is refused, and the refusal names the new holder. A `replaces` that is not the holder, an empty seat, the holder
replacing itself, a caller under a token and a target under a token are refused before anybody is asked.

By clicking, on the dashboard. When the holder is silent, the cohort panel shows a Replace button for each present member who
is neither the holder nor under a token ("Replace mcp:m-aaaa with mcp:m-bbbb"), after a native confirmation that names the
holder and how long it has been silent. The click posts to `/dashboard/cohort/seat` with `replace=<holder>` and a one-use
ticket the page was rendered with, issued for that pair of holder and member. A ticket for another pair, for a Seat button, a
used one, an expired one and a request without the browser's `Sec-Fetch-Site: same-origin` header are refused, as for Seat.
The same limit holds: the dashboard has no credential, so a process that can load the page can read a ticket out of it.

**Route.** Every token names the one place it may act, and you say where with
exactly one of two parameters:

- `working_directory`: an absolute path to a checkout. The token may act on
  sessions rooted inside that directory. A git worktree nested under it is its
  own checkout, so a token for `/repo` does not reach a session in
  `/repo/.claude/worktrees/agent-x`, and a token for the worktree does not reach
  `/repo`. The member is seated in that repository's cohort.
- `session_id`: one session. The member is seated in the repository that
  session lives in.

Naming neither is refused, naming both is refused, and a relative path or the
file system root is refused. No mint can produce a token that routes anywhere:
that is the conductor's own authority, which a connection with no token has, and
it is not something a grant can carry. A token can hand out only its own route,
because whether one session is inside a checkout is a fact about the registry and
not about two grants.

How a call is held to the route depends on what the tool does with a session or
a directory. Every tool has exactly one of these kinds, and a tool with no kind
is refused to a bound token, so a tool added tomorrow cannot be forgotten:

| Kind | Tools | What a bound token may do |
|:---|:---|:---|
| Acts on a session | everything that evaluates, analyses, tests, resets, runs the app or reads a session's status or history | Name its own session or a directory inside its route. Name nothing and the call acts on its session. Name another and it is refused. |
| Lists sessions | `list_sessions` | Allowed, and it shows only the sessions inside the route. |
| Creates a session | `create_project_session`, `create_solution_session`, `create_bare_session` | A checkout token creates sessions inside its checkout and nowhere else. A session token creates none. |
| Picks a cohort | the cohort tools, `mint_member`, `revoke_member` | Must pass `working_directory` inside its route. Left out, the call would act in the daemon's own repository, so it is refused with the directory to pass. |
| Reads a directory | `get_available_projects` | Must pass a `working_directory` inside its route. |
| Daemon-wide | `get_daemon_status`, friction, leases, `decompose_pipeline` | Allowed. A session or directory it names is still held to the route. |

Two things back that up. A `session_id` or `working_directory` that a call names
is held to the route on every tool, whatever the tool does with it, and a
directory is resolved before it is compared, so `/repo/a/../b` is `/repo/b`. And
underneath every tool body the daemon shows a bound caller only the sessions
inside its route: the others are absent from `list_sessions`, from a status
lookup and from the registry a tool reads, and a stop, restart or app command on
one is refused. So a call that names nothing cannot fall through to "the only
other session", and an active-session pointer that points elsewhere finds
nothing.

**Present.** In the `X-SageFs-Member-Token` HTTP header (one value per
connection), or in the request's `_meta["sagefs/memberToken"]` (per call, so one
connection can speak for many members: the gateway sets it, the model never sees
it). `sagefs mcp` reads `SAGEFS_MEMBER_TOKEN` from its environment and sends it as
the header on every request. There is no tool argument for a token on purpose:
an agent's transcript keeps every argument. A token that is presented and bad
(unknown, expired, revoked, lapsed, unreadable) is refused. It is never quietly
downgraded to the connection's own identity.

**Roles.** A closed set. Each role is a set of tool classes, and a tool with no
class is refused, so a new tool cannot be reachable by accident.

| Role | Adds to the one above | Cohort role |
|:---|:---|:---|
| `Observer` | `get_cohort_status`, `join_cohort`, `leave_cohort`, `get_daemon_status`, `get_session_status`, `list_sessions`, `get_available_projects`, `list_runnable_projects`, `get_friction_report`, `get_friction_summary`, `discover_features`, `get_recent_fsi_events`, `switch_session`, `report_friction` | Observer |
| `Analysis` | `check_fsharp_code`, `signature_at_caret`, `diagnose`, `coverage_intel`, `impact_forecast`, `suggest_next_action`, `plan_ripple`, `preview_what_if`, `suggest_next_cell`, `get_cell_dependencies`, `decompose_pipeline`, `explain_test_failure`, `list_tests`, `suggest_repair`, `get_session_filmstrip`, `get_eval_timeline`, `get_eval_diff`, `get_message_journal`, `export_notebook`, `export_session_transcript`. No eval, no tests. | Observer |
| `Verifier` | `run_tests`, `targeted_verify`, `acquire_full_build_lease`, `acquire_test_suite_lease`, `acquire_run_app_lease`, `release_work_lease`, `veto_landing`. No eval. | Verifier |
| `Implementer` | `send_fsharp_code`, `cancel_eval`, `manage_scratch_pad`, the session tools (`create_*_session`, `reset_fsi_session`, `hard_reset_fsi_session`, `switch_workflow`, `stop_session`, the hot reload tools), `run_app`, `stop_app`, `acquire_claim`, `release_claim`, `request_landing`, `withdraw_landing` | Implementer |

No role can call `mint_member`, `revoke_member`, `reassign_claim`, `delegate_conductor`,
`seat_conductor`, `resolve_veto`, `set_integration_ref`, `manage_local_data`, `get_workspace_hygiene` or
`tidy_workspace`. A token call also passes the cohort's own role check, so an
Observer, Analysis or Verifier token can read the cohort but not claim a scope or
queue a landing. `tools/list` shows a token only the tools its role allows. The
role says which tools a token may call and the route (below) says where it may call
them, and a call must pass both.

**The operator credential in `tools/list`.** A request that carries the contents of
`operator.token` as `Authorization: Bearer sfo_...` is listed every tool, `mint_member`
included. `sagefs mcp` reads `SAGEFS_OPERATOR_TOKEN` from its environment and sends it
that way on every request. A member token on the same request narrows the list to its
role, so a launcher that holds both is listed as the member. The credential changes
the list only. A call is still judged by the seat and the role: presenting it does not
make a connection the conductor. An operator-shaped credential that is not the
daemon's (an old file, another daemon's) is refused like a bad member token: the list
holds `credential_status`, and a call gets HTTP `403` with `invalid_token`. Any other
`Authorization` header, such as another system's bearer token, is left alone.

**A token the daemon cannot use.** A token that is unknown (minted before a daemon
restart, since tokens live in memory), expired, revoked or lapsed gets one tool in
`tools/list`, `credential_status`, whose description is the refusal and what to do
about it. Connecting, `ping` and `tools/list` still succeed, so the client keeps the
server and the model can read why. Any call, including one to `credential_status`,
is answered with HTTP `403` and `{"error":"invalid_token","error_description":"..."}`.
The status is `403` on purpose: a `401` starts an OAuth sign-in in Claude Code,
Copilot CLI and opencode that the daemon cannot finish, and only a `403` makes
Claude Code run its `headersHelper` again and retry the call. MCP's authorization
spec says an invalid token must get a `401`; SageFs is not an OAuth resource server,
so it departs from that, in one function with a test that pins the status. The
refusal applies to a token in the `X-SageFs-Member-Token` header. A token in
`_meta` is refused per call inside the JSON-RPC reply.

**Scope.** ONE directory prefix such as `src/Foo/`. The token can claim only inside it, and
the path is canonicalized first, so `src/Foo/../Bar` counts as `src/Bar`. Leave the scope
out for the whole repo. A list (`SageFs.Core/,SageFs/,docs/`, or one split by `;`) is
refused by `mint_member`, by `POST /api/members/mint` and by `sagefs member mint --scope`
before any token exists: a comma is not a path separator, so a list read as one prefix
would cover no path and every claim by the token would be refused. A token carries one
prefix on purpose (decided 2026-11-08): the grant order (`isWithin`, the "never wider than
its minter" rule, the simulation's invariants) is defined over one directory, and a
run that needs two directories can take their common parent or the whole repo, because a
file claim stays exclusive per file whatever the scope. A directory whose name holds a
comma or a semicolon cannot be a scope for that reason. This is
policy, not a sandbox: it refuses claims, and it does not stop a process from
writing a file. Containment is the sandbox's job. And `Implementer` includes
`send_fsharp_code`, which runs arbitrary F# as the daemon's OS user, so against a
hostile agent only the roles without eval mean something.

**Expiry.** `ttl_minutes` from now (0 means 120, at most 480). A token also lapses
after 30 minutes with no call, the way a silent member's seat does, and every
call it makes keeps its seat renewed.

**Revoke.** `revoke_member member_id=cap:<id>`. The token is refused from the
next call, for ever: a revoked token stays revoked and its hash cannot be minted
again. The seat departs and its claims are orphaned, so the conductor can
`reassign_claim` them. A build or test lease the member already holds runs out on
its own.

**Identity policy.** `SAGEFS_IDENTITY_POLICY` on the daemon decides what a
connection with no token is. `ConnectionsAllowed` (the default, and what happens
when it is unset) leaves it a plain member, exactly as before tokens existed.
`TokenRequired` lets it read `get_cohort_status` and `get_daemon_status`, and lets
the conductor act (so it can mint); everything else is refused with a message that
says how to get a token. The call and the list answer different questions. A call
is judged by who holds the conductor seat, so the conductor on its own connection
can call `mint_member` by name. The list is judged by the credential presented, so
that same conductor, presenting none, is listed only status and `join_cohort`,
before and after it joins. To see the full list, present the daemon's operator
credential (below). The first member to `join_cohort` is still the conductor,
and a connection with no token may call `join_cohort` until there is one, so the
orchestrator starts the daemon, joins first, then mints. A value that is set but not one of the two fails closed,
as `TokenRequired`. Without `TokenRequired` the narrow roles sit beside an
unrestricted door, so the allow-list is advice.

**What a refusal looks like.**

```
Error: This member token has the Analysis role, which cannot call send_fsharp_code:
that is evaluating F#. → Next: send_fsharp_code needs the Implementer role. Ask the
conductor to mint a token with it (mint_member), or use a tool your role allows
(tools/list shows them).
```

```
Error: This member token is confined to 'src/Foo' and cannot claim file:src/Bar/a.fs.
→ Next: Claim a path inside 'src/Foo', or ask the conductor to mint a token for a
wider scope.
```

```
Error: This member token is bound to session a1b2c3d4, and session d7b45c0e is not inside that.
→ Next: Pass session_id a1b2c3d4, or no session at all to act on it. To reach another
session, ask the conductor to mint a token bound to it (mint_member).
```

```
Error: join_cohort acts in the repository of the directory it is given, and this call named
none, which would mean the daemon's own repository. This member token is bound to the
checkout /work/checkout-a.
→ Next: Pass working_directory /work/checkout-a (or a directory inside it).
```

**What the route does not stop.** It decides what the tool surface will do for a
caller holding the token, and like the role and the scope it is policy and not a
sandbox. These are specific to the route:

- An `Implementer` token can run code (`send_fsharp_code`), and that code runs as
  the daemon's OS user. It can call the daemon's HTTP API on loopback with any
  session id, read the data directory and read `/proc`. The route does not
  change that. Against a hostile agent only the roles without eval mean
  something.
- The HTTP API and the MCP resources (`sessions://list`, `cohort://status`) do
  not read the token, so they are not confined to the route.
- The daemon-wide reads show the whole daemon: `get_daemon_status` reports
  session counts, worker processes by session id prefix and which agents hold
  build and test leases for which directories, and the friction reports name
  sessions. They are allowed to every role that may call them.
- A directory is compared as a path and not through the file system, so a
  symbolic link inside a checkout that points at another checkout is inside.
- A token bound to a checkout acts on every session rooted in that checkout, not
  one of them in particular. Bind to a `session_id` when one is what you mean.
- `switch_session` by a bound token moves the daemon's active-session pointer to
  that token's own session, like any caller's, and nothing else.
- A token dies with the daemon. The route, the role and the expiry all go with it,
  and the orchestrator mints again.

**Limits.** A token is held by whatever sends it, so a leaked one is
impersonation until it expires or is revoked. A connection-wide header cannot tell
apart sub-agents that share a connection (Claude Code's `Agent` tool): only a
per-call `_meta` can, and Claude Code gives the model no per-call header. The
conductor on a `ConnectionsAllowed` daemon is still identified by its connection,
and a connection with no token routes anywhere, which is what lets the conductor
mint for any session.

### The integration: one per daemon, for one repository

`set_integration_ref working_directory=<repository>` cuts the integration worktree from THAT repository (the daemon's own
directory only when you name none), records the head in that repository's cohort, builds what the integration session
needs and starts the session. The daemon holds one integration, so it serves one cohort: the one of the repository named when
it was configured. `get_cohort_status` for any other cohort says which repository the integration serves and how to move it,
and a landing in another cohort is blocked with the same words instead of being rebased and verified in the wrong tree.

What the integration session loads is the test projects of the repository (a project that references Expecto, xunit, NUnit,
MSTest or TUnit, or sets `IsTestProject`) and, through their references, what they test. The other projects a solution lists,
such as samples that need a Rust, Python or Java toolchain, can never fail a landing and are neither built nor loaded. A
repository with no test project loads everything the solution declares. A conductor who knows better names the project its
landings are verified by with `projects=SageFs.Tests/SageFs.Tests.fsproj`, which is what a solution that lists many sample
test projects wants; a name that is not in the repository is refused with the path it looked in. The worktree is built before the session starts, so
the session reaches Ready on built outputs; a build that fails ends in `WARNING: the worktree build failed` with the cause,
the worktree to look at and the retry.

Calling `set_integration_ref` again is the retry. It stops the previous integration session, replaces the integration worktree
and cuts a branch of its own (`sagefs/cohort-<sha>`, then `-2`, `-3`) because an earlier branch may hold landings and is
never reset. A session that faulted says why in `get_cohort_status` (`Integration session: FAILED to start. ...`) with the
same retry.

**A landing in the queue forbids it.** Replacing the integration stops the session that verifies landings and deletes the
sources it reads, so the call is refused while the cohort's landing queue is not empty (a landing that is queued, rebasing or
verifying). The refusal names the landings in front and the two ways out: wait for them to land, or have each requester take
theirs back with `withdraw_landing`. Nothing is stopped or removed when it is refused. The call is also made under the gate
every landing step takes, so a landing's rebase waits behind a replacement that is under way and cannot move the worktree
while it is rebuilt.

**One worktree per cohort.** The integration worktree and the trunk checkout live under the data dir at
`cohort-integration-<repository>-<hash>` and `cohort-trunk-<repository>-<hash>`, derived from the cohort's repository, so two
repositories never share a path. Moving the integration to another repository removes the old worktree from the repository
that made it (git refuses to remove one repository's worktree from another), reads git's answer, and ends in an error that
names the path and what git said when the removal fails: the binding then reads `FAILED` with that text, never a session that
is gone. The old repository's trunk checkout is left where it is, because a session may be running an app in it.

The repository's own SageFs (a cohort for SageFs itself) also needs the daemon and the integration worktree to be one build:
see "Self-hosting skew" in `AGENTS.md`.

### How a landing is verified

A landing is rebased onto the integration head in the integration worktree, then verified, then fast-forwarded in. What
verification does depends on what the landing carries (`SageFs.Features.CohortLandingPlan`, which decides, and the daemon,
which acts):

- **Only a test project's own files** (and documents, scripts, data): the files are re-evaluated into the integration session
  over its build and the tests the diff can affect run. This is the cheap path and it is unchanged.
- **Source of a project the session loads that is not a test project** (the code the tests call into: F#, C# or Visual Basic),
  or anything that changes what the build makes (a project file of any of the three languages, props, targets, a lock file,
  `global.json`, and a resource or content file of a project in the session's closure, whatever its extension; only notes and
  scripts in a project folder are inert). The classifier fails closed: an F# or C# file whose project the index could not
  find, and a project file the index does not know, count as compiled source and a build input: the integration worktree is rebuilt at the
  rebased commit, the session restarts on what the build made, the session's tests are asked of the new worker, and the
  tests run against the rebuilt assemblies. A re-evaluation cannot do this job: the session's project already holds the file's
  types from its compiled assembly, and the first landing of `SageFs.Core/AppState.fs` was blocked three times on exactly that.
  The tests that run are the ones the session's coverage says the diff can affect, plus every test the rebuild found that was
  not known before; a diff that selects nothing runs the whole suite.
- **A landing that arrives while the integration is still being built** (`Integration session: pending` in `get_cohort_status`,
  the minutes `set_integration_ref` spends building the worktree) waits in the queue and starts when the session does. It is
  not Blocked, and a member does nothing. If `set_integration_ref` fails or is refused, the integration reads `FAILED` and the
  waiting landing is refused with that reason.
- **The wait on the integration session has no deadline.** A restart of the session loads the whole test project, which takes
  minutes when many builds share the machine, so the gate waits for as long as the session keeps changing phase (restarting,
  starting up, the worker's own progress text). It stops when the session is Ready, when it is dead, or when it has stayed in
  one phase for a stall window (`Timeouts.cohortIntegrationStallWindow`, 60 s on the default tier, scaled for the machine) and
  Blocks the landing with the phase it stuck in. A rebuild of the project is not judged by the window: the build runner
  bounds it with `Timeouts.buildCompletion`. The refusal text has a part for each party. A member is told to
  `withdraw_landing` and request again once `get_cohort_status` shows the session started; the conductor is told what the
  session is doing, for how long, and which tool revives it. It never tells a member to run a conductor's tool.
- **Tests the session cannot run are left to the release gate, and named.** A test whose full name carries the
  `[Integration]` tag (the tag `TestInfrastructure.Integration.register` puts on every registered integration suite) starts
  real processes, daemons and ports, and inside the session ended as `Skipped "Timed out after 5s"`. The verdict is
  fail-closed, so each such test Blocked every landing that touched code it covers. The gate no longer asks the session to run
  them: the release gate's `--integration-host` and dedicated tiers do. Each test left out is named in the landing's report
  file (below) and the landing's status line says how many (`N [Integration] tests were not run by the landing gate`),
  whether it landed or was Blocked. Every other test is still read fail-closed: anything but a confirmed pass blocks.
- **A landing Blocked on tests names them.** The blocker holds only test ids, hashes of the names, so the daemon records the
  names when the run ends. The status line says how many tests did not pass, separates the ones that failed from the ones that
  could not run (`3 failed, 97 could not run`, with `could not run: timed out after 5s` beside each such name), shows the
  first ten by name and how many more there are, and gives the path of a file in the integration worktree's
  git-ignored `test-results/` (`cohort-landing-<id>-failing-tests.txt`) that lists all of them with their ids. The names are
  held in the daemon's memory: after a restart the status shows the ids and says the names were not recorded, and the file
  is still on disk.
- **The rebuild trusts nothing it did not check.** It reads the integration worktree's head first and refuses (Inconclusive,
  `the integration worktree is at <sha>, not at the rebased commit <sha>`) when something moved it since the rebase. It records
  the attempt before it builds, success or not: a build that fails still writes the refused commit's output, so from that
  moment the session's build is off the head and the next landing rebuilds, even a test-only one. A landing that carries a build
  input (a project file, props, a lock file, `nuget.config`), and a session whose build came from a commit that did not land,
  restores before the rebuild: the session's own rebuild is incremental and does not restore, so a package that was added, or
  a feed that cannot be reached, would otherwise pass as a green build that never saw the package.
- **A rebuild that fails** refuses the landing as one of two kinds, and the status line says which:
  - `Blocked(the landing does not compile: <file>(<line>,<col>): error FS....) fix it in your commit and request the landing
    again`: the first compiler error (F#, C# or Visual Basic) of the rebased commit, with its file and code. The next action is
    `FixTheBuild`, and the SSE wire carries blocker kind `compile_error_in_landing` and next action `fix_the_build`.
  - `Blocked(verification inconclusive: ...) nothing is known to be wrong with your commit: request the landing again`:
    everything else. A restore that cannot reach its feed (`NU1301`), any other `NU` error (a failed restore means the compile
    did not run against the commit's packages), a locked file (`MSB3027`), a build that did not run, a session that is not
    ready. The error is quoted, and the member is not told to fix their commit.
  The session keeps serving the build it had.
- **After a landing that was refused or withdrawn**, once nothing else is queued, the integration worktree is put back at the
  integration branch's tip. The session may still hold the build of the refused commit; the next verification sees that the
  commit is not in the head's history and rebuilds before it trusts the session, even when that landing only touches tests.
  Calling `set_integration_ref` is not needed.
- **Generated pages** (`docs/roadmap.md`, `docs/configuration.md`, `docs/client-setup.md`) need no claim, so no member waits on
  one. After the rebase the daemon regenerates the pages whose inputs the landing touched (`dotnet fsi scripts/gen-roadmap.fsx`,
  `dotnet fsi scripts/gen-configuration-doc.fsx <rebased head>`, `dotnet fsi scripts/gen-client-setup-doc.fsx`) and commits the result on top of the rebased head, which is the
  head that is verified and landed. A rebase conflict that touches only generated pages is settled by taking the integration
  head's page and regenerating. A generator that fails refuses the landing and names the command to run yourself.
- **Claims** a landing names are released when it lands.
- **The queue:** `get_cohort_status` says where a queued landing stands and what is in front of it (`position 2 in queue,
  behind l-... (Verifying ...)`), so a member that waits can sleep instead of polling. A member token's lease still lapses
  after thirty minutes without a call.

### The trunk

A landing that lands is carried into the app the trunk runs. The **trunk checkout** is a daemon-owned git worktree
(`cohort-trunk` under the data dir, detached) that `set_integration_ref` creates beside the integration worktree. After a
landing has landed, and only then, the daemon moves the trunk checkout to the landing's commit. A **trunk session** is a
session whose working directory is that checkout: start one with `create_project_session` (`workflow` `hotreload`) and
`run_app`. When it runs an app, the daemon tells its worker which files the landing changed and the worker runs the same save
pipeline a person's save takes. The app serves the landing without a restart and keeps its in-memory state, or restarts and
says why.

`get_cohort_status` ends with one line per landing:

```
Trunk: checkout=/data/cohort-trunk landings (2):
  trunk l-4f2a...: session c5121ff3: no running app to update (the trunk checkout holds the landing; rebuild the session before run_app, so the app starts from it)
  trunk l-9be1...: session c5121ff3: Alice.fs PatchPending by metadata-delta
```

The case (`PatchPending`, `Patched`, `Restarted`, `RestartRequired`, `NoEffect`, `CompileFailed`, `EvalFailed`) and the mechanism
(`detour`, `metadata-delta`) are the ones `get_session_status` reports in `lastReload`. A patch is `PatchPending` until its new body has
run, and the line changes to `Patched` when the worker says it has seen that. A restart names its cause on the line.
`CompileFailed` means the compiler reported an error in the file. `EvalFailed` means the save's evaluation did not finish and it was
not a compile error: its one reason names the cause (`InternalFault`, `EvalThrew`, `Interrupted`, `RefusedByReset`,
`RefusedBySession` or `HostCrashed`) and what to do about it. A client that does not know `EvalFailed` still gets the failure as
a `failed` event with the message.
`lastReload` also carries `callers`: when a save re-signs or removes a function, it lists, per declaration, the file, line
and calling declaration of every caller in another file that still calls the old one (`CallersPending`), with the next
action ("Save Pages.fs"); it reads `CallersCurrent` once those files have landed, and `CallersNotChecked` with the reason
when the project's other files could not be searched. A
landing that was blocked, withdrawn or is still being verified never reaches the trunk, and a trunk session that runs no app
only records the landing. A worker in a trunk session takes its saves from landings only, so a save a person makes in the
trunk checkout is not hot reloaded there.

## Adding a tool

A new tool is declared in seven places, and a test goes red for each one you miss. This is the order that keeps the build green. `my_tool` stands for the new name.

1. **The tool.** A `[<McpServerTool>]` member in `SageFs/McpTools.fs`, with its description and `[<Optional; DefaultParameterValue(...)>]` on every optional parameter, as its neighbours do. A body longer than a few lines goes in a file of its own, listed in `SageFs/SageFs.fsproj`, because the file-size ratchet asks for it (`list_members` is in `SageFs/McpMembersRoute.fs`, with its pure halves in `McpListMembers.fs`, `McpMemberPage.fs` and `McpNoMembers.fs`).
2. **The gate domain.** `gatingDomain` in `SageFs.Core/Affordances.fs` needs `"my_tool", ToolGate.AlwaysAvailable`, or a state-gated entry. `McpToolGateTests` checks that the domain holds exactly the registered tools, so a missing entry and a stray one both fail.
3. **The name.** `ToolName` in the same file: the union case, its line in `ToolName.toToolName`, and its place in `ToolName.all`. `ToolName.allToolNames` is built from those.
4. **The routing kind.** The `RouteKind` assignments in `SageFs.Core/Capability.fs`. A tool that acts on a session is `OnSession`. `MemberRouteGateTests` fails for a tool with no kind, because a token bound to one session has to know where the call is going.
5. **The tool class.** `ToolClass.toolsOf` in the same file. A tool no class holds is refused to every role, and `CapabilityTests` fails for it.
6. **The docs.** A row for it in the table above that matches its job, and the tool count. `ToolSurfaceHonestyTests` holds the table to the registered set, and holds every page that writes "N tools" (this one, `Readme.md`, `docs/architecture.md`, `docs/architecture-decisions.md`, `docs/FEATURE_MATRIX.md` and `docs/agents.md`) to the registered count.
7. **The test tables.** Two hand-kept tables say what the surface is on purpose: a `requiredParamsByTool` row in `ToolDescriptionTests` for any parameter with no default, and the exact count in two places, `ToolDescriptionTests` ("keeps the tool count surgical") and `McpAffordanceHardeningTests` ("total exactly N"). They are tripwires, so a new tool means editing them in the same change. `list_members` landed without them and the default suite went red on master. The set of tool names needs no table: `McpWireProtocolTests` compares the registered tools with the `ToolName` union from step 3.

Two more things catch people. A commit that touches this page or `SageFs/McpTools.fs` is a wire-surface change, so it carries a `Plugin:` trailer (`done` with what changed in sagefs.nvim, or `n/a` with why it needs nothing), and `scripts/ship.fsx` refuses a release without one. And a name that was retired stays retired: `RetiredToolNameTests` fails on a new tool that reuses one, which is why the symbol ladder's first rung is `list_members` and not a revived old name.

## Per-client config

Prefer stdio (`command`/`args`, spawns `sagefs mcp`) over HTTP (`url`,
requires the daemon already running) for the reason above.

**Claude Code**:
```
claude mcp add sagefs -- sagefs mcp
```
That lands in local scope by default: it goes into the entry for your current
project inside `~/.claude.json`, and only loads in that project. Add `-s user`
(`--scope user`) and it's written to `~/.claude.json` for every project on the
machine. For a team, `-s project` writes a `.mcp.json` at the project root,
which you can commit:
```json
{ "mcpServers": { "sagefs": { "command": "sagefs", "args": [ "mcp" ] } } }
```
(Claude Desktop is a different app with its own `claude_desktop_config.json`.
Claude Code doesn't read it.)

**GitHub Copilot (CLI)**, `~/.copilot/github-copilot/mcp.json`:
```json
{ "servers": { "sagefs": { "type": "stdio", "command": "sagefs", "args": [ "mcp" ] } } }
```

**Cursor / Windsurf**, `.cursor/mcp.json` or the Windsurf MCP settings:
```json
{ "mcpServers": { "sagefs": { "command": "sagefs", "args": [ "mcp" ] } } }
```

**OpenCode**, `~/.opencode.json`:
```json
{ "mcp": { "sagefs": { "type": "local", "command": [ "sagefs", "mcp" ], "enabled": true } } }
```

If your client only takes a `url` (HTTP), the daemon has to be running
first, see the troubleshooting note above. The `url` is
`http://localhost:37749/` for Streamable HTTP, or `http://localhost:37749/sse`
for SSE:

**GitHub Copilot (CLI)** over HTTP:
```json
{ "servers": { "sagefs": { "type": "http", "url": "http://localhost:37749/" } } }
```

**Claude Code / Claude Desktop** over HTTP:
```json
{ "mcpServers": { "sagefs": { "url": "http://localhost:37749/" } } }
```

**Cursor / Windsurf** over HTTP:
```json
{ "mcpServers": { "sagefs": { "url": "http://localhost:37749/" } } }
```

**OpenCode** over SSE:
```json
{ "mcp": { "sagefs": { "type": "remote", "url": "http://localhost:37749/sse", "enabled": true } } }
```

Works with GitHub Copilot (CLI and VS Code), Claude Code, Claude Desktop,
OpenCode, Windsurf, Cursor, and any MCP-compatible tool. With live testing
on, agents can edit files, let SageFs re-run the affected tests, and read the
result through `list_tests` and `diagnose`, no eval round-trip needed. This
is the whole point of building an MCP server instead of just a REPL: the
agent gets the same fast feedback loop I do.
