# Shared sharded `pi-durable` daemon & `pi-fabric` CLI

`pi-fabric` includes a user-scoped, sharded `pi-durable` daemon that shares one
runtime across every `pi` process (with `pi-fabric` installed) and powers the
standalone `pi-fabric` interactive TUI and headless CLI.

## Why a shared daemon?

Running one isolated Pi SDK worker process per agent does not scale to hundreds
or thousands of agents on a single machine: each isolated worker imports
`@earendil-works/pi-coding-agent` and opens its own JSONL store, costing
~200–300 MiB RSS and 2–3 OS processes per agent.

The shared daemon collapses that overhead into a small, bounded pool of Node 24
processes (Shard 0 in-process in the coordinator, plus up to `maxShards - 1`
forked shard workers on demand):

- **One SQLite WAL `Harness` per shard** (`openNodeSqliteStorage`) with built-in
  group commit and configurable idle context/document eviction
  (`contextRetentionMs`, `documentRetentionMs`).
- **One shared `ModelRuntime` per shard** (credentials, model catalog, HTTP
  connection pool).
- **One shared QuickJS WASM module per shard** via `pi-fabric/durable-extension`
  (`fabric_exec`), granting per-conversation `pi.*`, `mesh.*`, `state.*`, and
  `agents.*` providers.
- **Native coding tools** (`read`, `write`, `edit`, `bash`, `grep`, `find`,
  `ls`) with per-conversation `cwd`, write confinement (`writePolicy`),
  exact-model pinning (`modelMatch: "exact"`), and durable `defineSignal` tool
  approval gates (`approvalMode: "ask"`).
- **Coordinator SQLite index (`index.sqlite`)** mapping external conversation
  IDs, prefixes, cwd recency, parent/root lineage, and status across all shards.

## Two-tier routing from `pi` (`AgentManager` & `ActorManager`)

Existing `pi` sessions with `pi-fabric` installed require no workflow changes:

1. **Tier 1 (Shared Daemon, default for eligible `pi-durable` runs)**:
   `AgentManager` and `ActorManager` route eligible `pi-durable` runs and
   persistent actors through `createSharedDaemonHostedRunner` over the local
   Unix socket / Windows named pipe. Persistent actors reuse one durable
   conversation (`actor:<actorId>`) across activations without spawning a new
   worker process per turn.
2. **Tier 2 (Isolated Pi Worker, automatic fallback)**:
   Runs automatically fall back to the isolated `dist/durable/worker.js` process
   when:
   - `agents.sharedDaemon.mode` is `"off"` (or `PI_FABRIC_SHARED_DAEMON=0`)
   - Third-party Pi `ExtensionAPI` extensions are enabled (non-Fabric entries in
     `~/.pi/agent/settings.json` or `.pi/extensions`)
   - `agents.launchWrapper`, `agents.durableWorkerRecovery`,
     `agents.durableWorkerSession`, or a custom test `workerPath` is configured
   - A different runner (`pi`, `claude`, `veda`) or a custom external hosted
     runner is selected.

### Configuration (`~/.pi/agent/fabric.json` or `.pi/fabric.json`)

```json
{
  "agents": {
    "maxConcurrent": 2000,
    "sharedDaemon": {
      "mode": "auto",
      "autoStart": true,
      "maxShards": 8,
      "idleExitMs": 120000,
      "contextRetentionMs": 60000,
      "documentRetentionMs": 60000
    }
  }
}
```

| Field | Default | Description |
| --- | --- | --- |
| `mode` | `"auto"` | `"auto"` (use daemon when eligible), `"always"` (force shared daemon for `pi-durable`), `"off"` (always use isolated worker). Overridable via `PI_FABRIC_SHARED_DAEMON=auto\|always\|off\|1\|0`. |
| `autoStart` | `true` | Automatically start the daemon on first use if not already running. |
| `maxShards` | `8` | Maximum shard count (1–32). Shard 0 runs in the coordinator; shards `1..maxShards-1` fork lazily as load grows. |
| `idleExitMs` | `120000` | Shut down cleanly after being idle with zero connected clients and zero active runs (`0` disables idle exit). |
| `contextRetentionMs` | `60000` | Evict idle conversation contexts from RAM while keeping full history in SQLite WAL. |
| `documentRetentionMs` | `60000` | Evict idle conversation documents from RAM. |
| `bridgePiExtensions` | `true` | Automatically bridge compatible Pi `ExtensionAPI` extensions (custom providers once per shard, tools/overrides/hooks/decisions/commands scoped per conversation) and native `pi.durableExtensions` packages inside the shared daemon. Set `false` to restrict the daemon to native `pi-durable` extensions only. |

## Standalone `pi-fabric` CLI & TUI

Bare interactive `pi-fabric` launches a **zero-heap C11 native TTY proxy**
(`native/pi-fabric-tty.c`, ~41–71 KiB stripped, cross-compiled for `darwin-arm64`,
`darwin-x64`, `linux-x64`, and `linux-arm64` via `zig cc`) through a 35-line
POSIX `exec` launcher (`dist/cli/pi-fabric`), so interactive windows keep **zero
Node.js process** on the client side (~`97.4 KiB` PSS on Linux / ~`1.67 MiB` RSS
on macOS). The proxy connects over an auto-detected **Binary v2 (`PFU2`)**
`AF_UNIX` wire protocol to a lazily sharded **Interactive UI Host Daemon** pool
(`src/cli/host/`, defaulting to 1 warm shard up to 256 windows and spilling
lazily across up to 8 shards via `REDIRECT`). Inside each UI host shard, every
window runs Pi's native `InteractiveMode` over a virtual `SocketTerminal` backed
by per-session `pi-durable` SQLite WAL storage (`<agentDir>/durable-sessions/`),
sharing V8, `@earendil-works/pi-coding-agent`, `ModelRuntime`, and the warm Pi
extension cache across windows while preserving 100% of Pi's native UI and every
user Pi extension (editor overlays, `/fabric` dashboard, thinking traces,
`/hide-models`, `/resume`, `Ctrl+Z`, `Ctrl+G`, themes, and keybindings).

Spawned agents and persistent actors route through the shared sharded
`pi-durable` daemon. Non-interactive subcommands (`daemon`, `mesh`, `decisions`,
`attach`, `-p`, `--mode json|rpc`, `--thin-tui`, `--help`, `-v`, or non-TTY
stdio) and fallback paths (`--isolated` or `PI_FABRIC_SHARED_HOST=0`, Windows,
or unsupported architectures) immediately `execvp("node", ...)` into
`dist/cli/index.js` (`pi-fabric-node` also points directly to `dist/cli/index.js`)
without importing `@earendil-works/pi-coding-agent` for headless/daemon modes.

| Environment variable | Default | Description |
| --- | --- | --- |
| `PI_FABRIC_SHARED_HOST` | `1` | Set `0` / `false` to disable the shared UI host and run interactive Pi in-process (`--isolated`). |
| `PI_FABRIC_UI_HOST_SHARDS` | `8` | Max lazy UI host shards (`1..64`). Shard 0 handles normal usage; shards `1..N-1` boot lazily on overflow. |
| `PI_FABRIC_UI_HOST_MAX_WINDOWS` | `256` | Soft window capacity per UI host shard before spilling new attaches to the next shard via `REDIRECT`. |
| `PI_FABRIC_UI_HOST_IDLE_MS` | `600000` | Idle auto-exit delay (ms) after the last window closes (`0` disables). |
| `PI_FABRIC_UI_HOST_DIR` | auto | Override the base runtime directory (`pf-ui-<uid>-<agentHash>-<buildTag>` under `os.tmpdir()` or `/tmp` to stay under macOS's 104-byte `sun_path` limit). |

```sh
# Shared warm interactive Pi host (native C11 proxy -> Binary v2 -> sharded UI host)
pi-fabric
pi-fabric -c                          # continue latest session in cwd
pi-fabric -r                          # interactive session picker
pi-fabric --attach-ui <window-id>     # reattach to a detached window (s<k>-... routes directly to shard k)
pi-fabric --isolated                  # force standalone in-process interactive Pi
pi-fabric auth login                  # Pi CLI commands forward directly

# Lightweight zero-SDK daemon socket TUI & attach
pi-fabric --thin-tui
pi-fabric attach <conversation-id>    # attach to any running session/agent/actor

# Headless modes (zero pi-coding-agent import)
pi-fabric -p "Summarize src/daemon"   # print streaming answer
pi-fabric --mode json -p "Inspect"    # NDJSON Chord watch + settlement stream
pi-fabric --mode rpc                  # Pi-compatible JSON-RPC loop over stdio

# Daemon & UI host shard administration
pi-fabric daemon start
pi-fabric daemon status [--json]
pi-fabric daemon ls [--cwd ...] [--kind session|agent|actor] [--json]
pi-fabric daemon abort <id|--all>
pi-fabric daemon logs [--lines 100]
pi-fabric daemon stop
```

### Per-window identity in the shared UI host

One host process runs every window's session, but each window keeps the
terminal identity and command line of the terminal it was opened in. Each
client sends its own values when it attaches, and the host scopes
`process.env` and `process.argv` to the window for everything that window's
session runs: extension handlers, tools, timers they start, and child
processes. A `node:child_process` call that passes no `env` gets the window's
environment too.

- **Environment.** The client (the native terminal proxy on macOS and Linux,
  or the Node client) forwards `TERM`, `TERM_PROGRAM`,
  `TERM_PROGRAM_VERSION`, `COLORTERM`, `TERM_SESSION_ID`, `ITERM_SESSION_ID`,
  `WINDOWID`, `WT_SESSION`, `TMUX`, `TMUX_PANE`, `STY`, `WINDOW`, `ZELLIJ`,
  `ZELLIJ_SESSION_NAME`, `ZELLIJ_PANE_ID`, `WEZTERM_PANE`,
  `WEZTERM_UNIX_SOCKET`, `KITTY_WINDOW_ID`, `KITTY_LISTEN_ON`,
  `SSH_CONNECTION`, `SSH_CLIENT`, and `SSH_TTY`. Add names with
  `PI_FABRIC_WINDOW_ENV`, separated by commas or spaces; `PREFIX*` forwards
  every variable that starts with `PREFIX` (for example
  `PI_FABRIC_WINDOW_ENV="MY_MUX_*,SSH_AUTH_SOCK"`). Set it in the shell that
  starts `pi-fabric`. Inside a window, a forwarded variable the client does not
  have is unset, so a window never sees another window's value. Every other
  variable keeps the host's value. Names starting with `PI_FABRIC_` or
  `PI_CODING_AGENT` are never forwarded. The host strips control characters
  and drops values longer than 4096 characters.
- **Command line.** Inside a window, `process.argv` is the runtime, the
  `pi-fabric` entry script, then the arguments the user typed. The Node client
  sends its own `process.argv`; for the native proxy the host builds
  `[node, <package>/dist/cli/index.js, ...args]`. That is what `--isolated` shows, so an extension
  that rebuilds a relaunch command from `process.argv.slice(2)` works in both
  modes. The host's own bootstrap flags are never visible to a window.
- **Limits.** The host may evaluate an extension module once and reuse it for
  later windows, so a value read at module load can belong to another window.
  Read identity variables in the extension factory or its handlers. `process.cwd()`, `process.pid`, and
  `process.title` remain the host's; use the session's `cwd`.
- **Reading identity explicitly.** `getWindowEnv()` from `pi-fabric/window`
  returns a frozen copy of the forwarded variables the calling window's
  terminal set, `{}` in a window whose terminal set none, and `undefined`
  outside every shared-host window (`--isolated` or plain Pi). Unlike
  `process.env`, it tells "this window has no `TMUX_PANE`" apart from "not in
  a shared window". Call it in the factory or a handler, not at module load.

  ```ts
  import { getWindowEnv } from "pi-fabric/window";

  const windowEnv = getWindowEnv();
  const pane = windowEnv ? windowEnv.TMUX_PANE : process.env.TMUX_PANE;
  ```

Interactive Node paths (the shared-host Node client, `--isolated`, `--thin-tui`,
and `attach`) set `process.title` to `pi`, as Pi's own CLI does. The native
POSIX terminal proxy also sets its process/thread name to `pi` (`prctl(PR_SET_NAME)`
and `argv[0]` on Linux; `pthread_setname_np` and `argv[0]` on macOS, where the
kernel's executable basename remains `pi-fabric-tty-darwin-*`).

### Thin TUI (`--thin-tui` / `attach`) shortcuts & commands

- **Shortcuts**: `Enter` send/steer, `Alt+Enter` queue follow-up, `Esc` abort,
  `Ctrl+C` clear input or detach (leaving active turns running in the daemon),
  `Ctrl+L` model picker, `Ctrl+O` expand/collapse tool outputs, `Ctrl+T` toggle
  thinking blocks, `Shift+Tab` cycle thinking level.
- **Inline tools**: `!command` runs shell commands via the daemon; `@file`
  attaches files or images with autocomplete.
- **Slash commands**: `/new`, `/resume`, `/agents` (jump to any of 2,000 live
  daemon agents/actors), `/fork`, `/tree`, `/compact`, `/model`, `/thinking`,
  `/name`, `/more` (load older history), `/daemon` (live shard & RSS stats),
  `/clear`, `/help`, `/quit`.

## Isolation & durability

- **Build-hashed socket & state isolation**: Runtime sockets live under a
  user-private `0700` temp directory (`pf-<uid>-<agentHash>-<buildTag>/d.sock`
  on POSIX to stay well under macOS's 104-byte `sun_path` limit; named pipes on
  Windows). Persistent SQLite databases live under
  `<agentDir>/fabric-daemon/<buildHash>/` (`index.sqlite` + `shard-N.sqlite`).
- **Authentication**: Clients authenticate with a per-daemon random token stored
  in `0600` `owner.json` beside a heartbeat timestamp.
- **Crash recovery**: Every conversation transcript, metadata document, and
  parked approval signal lives in SQLite WAL. Restarting the daemon rehydrates
  `index.sqlite` and all shard mappings automatically.

## Embedding & replacing components (`pi-fabric/daemon`)

Hosts that embed Pi + `pi-fabric` (alongside `pi-fabric/durable-host`,
`pi-fabric/durable-extension`, or `pi-fabric/runners`) can drop into or replace
any layer of the shared daemon architecture without forking:

```ts
import {
  FabricDaemonServer,
  setSharedDaemonRunnerFactory,
} from "pi-fabric/daemon";
import { MemoryStorage } from "@earendil-works/pi-durable";

// 1. Embed a customized daemon in-process with your own models, extensions,
//    coding-tool overrides (e.g. anchor-aware `read`), providers, or storage:
const server = await FabricDaemonServer.start({
  models: hostModels,
  extensions: [anchorAwareReadExtension, customHooksExtension],
  replaceCodingTools: false, // true to omit default coding tools completely
  providers: { custom: myDomainProvider },
  storageFactory: async (_shardId, _dbPath) => new MemoryStorage(),
});

// 2. Or replace the shared daemon runner process-wide for every AgentManager:
const restore = setSharedDaemonRunnerFactory((options) => myCustomHostedRunner(options));
```

- **Custom runner precedence**: Registering an external runner via
  `registerAgentRunner("my-runner", adapter)` (`pi-fabric/runners`) **always**
  takes precedence over the built-in shared daemon (proven by
  `eligibility_external_runner_dominates` in `proofs/daemon.ts`). To replace the
  built-in `pi-durable` shared daemon path globally across all `AgentManager`
  instances without renaming the runner, call `setSharedDaemonRunnerFactory(...)`
  from `pi-fabric/daemon`.
- **Launch wrapper safety**: Configuring `agents.launchWrapper` (including via
  live `/fabric reload`) **always** keeps launches on the wrapped worker path
  even if `agents.sharedDaemon.mode` is `"always"` (proven by
  `eligibility_wrapper_never_bypassed` in `proofs/daemon.ts`).
- **Decisions & child questions**: Routed tool approvals (`approvalMode: "ask"`)
  flow through `AgentManager`'s `onChildQuestion` into `DecisionStore` and the
  `pi-fabric:decisions:changed:v1` / `pi-fabric:decisions:answer:v1` extension
  hooks automatically.

## Automatic Pi extension & `pi.durableExtensions` bridge

To run existing Pi setups inside the shared daemon without forcing every extension
repo to rewrite for `pi-durable`, each shard runs
[`createPiExtensionBridge`](../src/daemon/pi-extension-bridge.ts) under the
verified `daemonExtensionBridge` policy kernel:

1. **Native `pi.durableExtensions` packages (`NativeDurable`)**: Any package in
   `~/.pi/agent/settings.json` or `.pi/settings.json` declaring
   `"pi": { "durableExtensions": ["./dist/durable.js"] }` loads directly into
   the shard `Harness` with zero shim overhead.
2. **Custom provider extensions (`BridgeProviderOnly`)**: Extensions calling
   `pi.registerProvider` / `registerNativeProvider` / `registerVirtualModel`
   (plus `before_provider_request`, `before_provider_headers`,
   `after_provider_response`, `provider_stream_event`) load **once per shard**
   into the shared `ModelRuntime` (0 per-conversation closures) and remain
   available even for `extensions: false` child runs.
3. **Runtime, tool, markdown, UI RPC, & decisions extensions (`BridgeScoped`)**: Legacy Pi
   extensions registering custom tools or overriding built-in coding tools (e.g.
   anchor-aware `read`), registering markdown transformers
   (`pi.registerMarkdownTransformer`), keyboard shortcuts
   (`pi.registerShortcut`), slash commands (`pi.registerCommand` with TUI
   autocomplete), hooking **38 of 41** Pi `ExtensionAPI` events
   (`agent_start`/`agent_end`/`agent_settled`, `turn_start`/`turn_end`,
   `message_start`/`message_update`/`message_end`, `tool_call`, `tool_result`,
   `tool_execution_start`/`update`/`end`, `context`/`context_with_system`,
   `before_agent_start`, `agent_before_settle`, `input`, `user_bash`,
   `model_select`, `thinking_level_select`, `session_before_compact` /
   `session_compact` / `session_compact_failed`, `session_before_fork` /
   `session_before_tree` / `session_tree`, `session_before_switch`,
   `session_info_changed`, `ui_prompt_start`/`ui_prompt_end`,
   `resources_discover`), persisting state via `pi.appendEntry` (durable in
   SQLite WAL via `PiExtensionEntriesDoc`), emitting `ctx.ui.*` effects &
   blocking dialogs (`notify`, `setStatus`, `setWidget`, `setWorkingMessage`,
   `setTitle`, `setEditorText`, `select`, `confirm`, `input`, `editor`) to
   attached interactive `pi-fabric` TUI clients over daemon RPC (failing closed
   automatically on headless runs), or using `pi.events`
   (`pi-fabric:decisions:capability:v1` / `request:v1` / `changed:v1` /
   `answer:v1`) load their module **once per shard** and instantiate an
   isolated, LRU-evicted closure per active conversation, so concurrent agents
   never corrupt each other's closure state. Conversations created with
   `piExtensionsEnabled: false` automatically exclude bridged tools/hooks/wraps
   via `pi-durable` extension selection.
4. **UI-only & fail-closed fallback (`SkipUiOnly` / `RequireIsolatedWorker`)**:
   In-process custom TUI component extensions (`ctx.ui.custom`, custom tool /
   message / entry renderers, or Pi `InteractiveMode` internals) skip cleanly on
   headless child runs without blocking the shared daemon, while interactive
   sessions requiring custom TUI renderers or any missing/unreadable extension
   fail closed to the isolated worker / `pi-fabric --compat-pi`.

## Verified policy kernels

Seven safety-critical daemon decisions and statecharts are formally proven with
`gdp-wired` in [`proofs/daemon.ts`](../proofs/daemon.ts) and executed directly
from their compiled machines in [`src/verified/daemon.ts`](../src/verified/daemon.ts):

- `daemonEligibility`: Tier-1 vs Tier-2 routing, env precedence, `launchWrapper`
  non-bypass, external runner precedence, and third-party extension fallback.
- `daemonExtensionBridge`: per-extension classification (Fabric native priority,
  fail-closed load errors, `pi.durableExtensions` native priority, interactive
  custom-TUI isolation, headless UI-only skip, provider-only shard sharing,
  per-conversation scoped bridging, and exact fallback equivalence).
- `daemonShardRouting`: `maxShards` bounds, explicit shard validation, and
  `softLimit` scale-out without exceeding `maxShards`.
- `daemonAuthGate`: closing refusal, mandatory `hello` handshake, protocol
  version, and token enforcement.
- `daemonApprovalStep`: write-policy dominance over approval prompts, top-level
  parking, nested pass-through, and terminal finality (`Approved`/`Denied`/`Expired`).
- `daemonIdleStep`: busy protection (`clients > 0 || activeRuns > 0`), `idleExitMs == 0`
  disablement, deadline enforcement, underflow-free accounting, and terminal `Closing`.
- `daemonUiPromptStep`: Daemon ↔ interactive TUI blocking UI prompt lifecycle
  (headless fail-closed never parks, owner-only `Answer`, immediate `Abort` on
  owner disconnect/cancel/timeout, and terminal `Resolved`/`Cancelled` finality).

## 2,000-agent scale benchmark

Run the offline multi-shard scale benchmark alongside the real isolated
`pi` + `pi-fabric` worker baseline (`dist/worker.js` -> `dist/durable/worker.js`)
on the same host:

```sh
node --expose-gc scripts/benchmark-shared-daemon.mjs --agents 2000 --shards 8 --concurrency 64 --baseline 8
```

Measured on the same 8 vCPU / 15.6 GiB Linux x64 host (Node `v24.22.3`, offline
faux provider, `supercomputer` batch `20261130-210034-icpr8l`):

| Metric | `pi` + `pi-fabric` Today (isolated worker / agent) | Shared Sharded `pi-durable` Daemon (8 shards) | Improvement |
| --- | --- | --- | --- |
| **OS processes (2,000 agents)** | **4,000** (`2` / agent: `worker.js` + `durable/worker.js`) | **1–8** (Shard 0 in-process + up to 7 forked shards) | **500× – 4,000× fewer** |
| **Max concurrent agents on 15.6 GiB host** | **~60** before OOM (and hard-capped at `32` by old `maxConcurrent`) | **2,000+** (`maxConcurrent` raised to `4,096`) | **33× – 62×+ higher** |
| **Peak RSS (2,000 concurrent agents)** | **~437.9 GiB** (projected from **1,793.8 MiB** for 8 concurrent, **224.2 MiB / agent**; single agent **255.0 MiB**) | **377.4 MiB** (**138.7 KiB / agent**, baseline 106.5 MiB) | **~1,650× less RAM/agent** |
| **Idle heap after 1.5 s eviction** | N/A (each live worker keeps ~224 MiB RSS) | **52.4 MiB** JS heap (all 2,000 durable in SQLite) | Bounded & evicted |
| **Startup / spawn latency** | **1,145.6 ms** per cold isolated agent | **33.5 ms** daemon boot; **61.8 ms** p50 conv create | **~18× – 34× faster** |
| **Throughput (2,000 turns)** | **5.74 turns/s** (8-way wave: 1.39 s, p50 1,280.9 ms -> **~348.4 s** / ~5.8 min for 2,000) | **249.6 turns/s** (2,000 turns in **8.01 s**, p50 118.3 ms) | **~43× faster** |
| **Disk footprint (2,000 agents)** | **~67.0 MiB** (**34.3 KiB / agent** across 2,000 `runs/` dirs) | **60.7 MiB** (**31.1 KiB / agent** across 8 SQLite WAL DBs + index) | Smaller & indexed |

## Interactive UI Host & 2,000-Window Scale Benchmarks

### 1. Multi-window Interactive UI Host vs isolated Pi + 2,000 agents with live TUI (`0.144.0` baseline)

Reproduce with:

```sh
node --expose-gc scripts/benchmark-interactive-host.mjs --windows 20 --isolated-windows 6 --agents 2000 --shards 8 --concurrency 64
```

Measured on an 8 vCPU / 15.6 GiB Linux x64 host (Node `v22.23.3`, offline faux
provider, `supercomputer` batch `20261201-213842-19syuu`, raw artifact in
[`docs/benchmarks/interactive-host-2026-12-01.json`](./benchmarks/interactive-host-2026-12-01.json)):

| Metric | Isolated Pi `InteractiveMode` | Shared UI Host + pure-Node proxy (`0.144.0`) | Notes |
| --- | --- | --- | --- |
| **Warm window attach latency (p50 / p95)** | **448.7 ms** / **458.7 ms** | **143.1 ms** / **191.1 ms** | **3.13× faster** warm attach (`242.9 ms` cold window #1) |
| **Host RSS (idle -> 1 -> 5 -> 10 -> 20 windows)** | `188.6 MiB` / window (`3,771.6 MiB` for 20) | `140.2 -> 149.3 -> 162.6 -> 169.2 -> 181.9 MiB` | **`+2.09 MiB` / window** incremental on host; **1** shared `ModelRuntime` |
| **Client RSS per window (pure-Node proxy)** | n/a | `47.6 MiB` (`25.1 ms` import) | Total for 20 windows: `1,133.9 MiB` (**3.33× less** than isolated) |
| **2,000 durable agents + live hosted `SocketTerminal` UI** | n/a | Create: **1.86 s** (`1,074 agents/s`, p50 `48.8 ms`); 2,000 turns: **5.60 s** (`357 turns/s`, p50 `132.0 ms`); Peak RSS: **`242.7 MiB`** (`53.3 MiB` SQLite WAL) | Dashboard snapshot warm p50: **`1.58 ms`**; `FabricWidget` render p95: **`0.04 ms`**; live keystroke latency at 2k agents: **p50 `0.26 ms` / p95 `0.99 ms` / p99 `2.52 ms`** |

### 2. 2,000 Simultaneous Interactive Windows: Native C11 `zig cc` Proxy + 8 UI Host Shards (`0.145.0`)

Replacing the pure-Node proxy client (`47.8 MiB` RSS / `12.9 MiB` PSS each) with
the zero-heap C11 native binary (`pi-fabric-tty-linux-x64`, `56.8 KiB` static
musl ELF, `PFU2` Binary v2 framing) and lazily sharding across 8 UI host shards
(`256 × 7 + 208 = 2,000` live `InteractiveMode` windows, 1 shared `ModelRuntime`
per shard) collapses 2,000 simultaneous interactive windows from ~`98 GiB` RSS
(`27.4 GiB` PSS) down to **`1.50–2.35 GiB` total physical RAM**.

Reproduce with:

```sh
# 2,000 simultaneous live windows (--no-session)
ulimit -n 65536
node scripts/benchmark-2000-windows.mjs --windows 2000 --shards 8 --max-windows 256 --concurrency 64

# 2,000 simultaneous live windows with per-session pi-durable SQLite WAL
node scripts/benchmark-2000-windows.mjs --windows 2000 --shards 8 --max-windows 256 --concurrency 64 --with-session
```

Measured on a 16 vCPU / 31.4 GiB Linux x64 host (Node `v22.23.3`, Zig `0.14.1`,
real Linux kernel `/proc/<pid>/smaps_rollup` PSS / Private Dirty and
`/proc/<pid>/status` VmRSS across all 2,000 client PIDs + all 8 host shard PIDs):

- **`--no-session`** (`supercomputer` batch `20261202-035847-qpqp8r`):
  [`docs/benchmarks/interactive-2000-windows-2026-12-02.json`](./benchmarks/interactive-2000-windows-2026-12-02.json)
- **`--with-session` (per-session `pi-durable` SQLite WAL)** (`supercomputer` batch `20261202-040223-bxwjvp`):
  [`docs/benchmarks/interactive-2000-windows-durable-2026-12-02.json`](./benchmarks/interactive-2000-windows-durable-2026-12-02.json)

| Metric (2,000 simultaneous live windows) | Native C11 proxy (`--no-session`) | Native C11 proxy + per-session SQLite WAL (`--with-session`) | Pure-Node proxy (same 8 shards, projected from measured Node client) | Isolated Pi processes (projected from 6-window baseline) |
| --- | --- | --- | --- | --- |
| **Native proxy binary size** | `56.8 KiB` static musl ELF (`230 KiB` all 4 POSIX targets) | `56.8 KiB` static musl ELF | JS (`dist/cli/host/client.js`) | n/a |
| **2,000 client processes (total PSS)** | **`0.186 GiB`** (`190.2 MiB`) | **`0.186 GiB`** (`190.3 MiB`) | `25.19–25.20 GiB` (`95.6–95.7 GiB` RSS sum) | n/a |
| **Avg PSS / Private Dirty per client** | **`97.4 KiB`** (`157.4 KiB` RSS) | **`97.4 KiB`** (`157.4 KiB` RSS) | `12.9 MiB` PSS (`47.8 MiB` RSS) | n/a |
| **8 UI host shards (total PSS / RSS)** | **`1.309 GiB`** (`1.662 GiB` RSS; `+0.29 MiB`/win) | **`2.159 GiB`** (`2.523 GiB` RSS; `+0.72 MiB`/win) | `1.31–2.16 GiB` | n/a |
| **Grand total physical RAM (PSS / RSS sum)** | **`1.495 GiB`** (`1.962 GiB` RSS) | **`2.345 GiB`** (`2.823 GiB` RSS) | `26.50–27.36 GiB` (`~97.2–98.2 GiB` RSS) | `~368–420+ GiB` |
| **Effective physical RAM / window (PSS)** | **`0.77 MiB`** | **`1.20 MiB`** | `13.25–13.68 MiB` | `~188.6–210+ MiB` |
| **Client RAM reduction vs Node proxy** | **`135.6×`** | **`135.6×`** | `1×` | n/a |
| **Total RAM reduction vs Node proxy** | **`17.7×`** | **`11.7×`** | `1×` | n/a |
| **8-shard boot time** | `478.0 ms` | `530.5 ms` | n/a | n/a |
| **Open & render all 2,000 windows** | `31.62 s` (`63.25 windows/s`) | `52.51 s` (`38.09 windows/s`) | n/a | n/a |
| **Live keystroke -> ANSI frame at 2,000 windows** | **p50 `0.68 ms` / p95 `3.96 ms` / p99 `4.09 ms`** | **p50 `1.25 ms` / p95 `5.00 ms` / p99 `6.17 ms`** | n/a | n/a |
| **Close all 2,000 windows via `SIGTERM`** | `0.15 s` | `1.50 s` | n/a | n/a |

On macOS Apple Silicon (live real PTY via `./dist/cli/pi-fabric`), the `exec`-ed
`pi-fabric-tty-darwin-arm64` (`70.6 KiB`) process measures **`1.67 MiB` RSS**
(`1,712 KiB`, mostly shared `libSystem`/dyld pages) with zero resident Node
parent process, vs `47.6 MiB` for the pure-Node proxy.
