# CLI (/docs/cli)



`@pleach/core` ships one binary, `pleach`, registered through the
package's `bin` field. It has seven subcommands today (plus the
`init` alias):

* **`pleach tui`** — the terminal UI. &#x2A;*This is what a bare
  `npx @pleach/core` runs.** It talks to the same runtime the web route
  does, through a Node sidecar.
* **`pleach dev`** — boot a self-contained local playground in your
  browser: the four-stage lattice visualizer, the event log, an
  inspector, a runtime console, and the audit ledger, all driven by
  a real graph turn. Requires a provider key — there is no keyless
  mode.
* **`pleach create`*&#x2A; (alias &#x2A;*`pleach init`**) — interactive
  wizard. Detects your stack and scaffolds a starter project (route
  handler, page, optional plugin stub, optional schema copy). Reached
  by name; it is no longer what a bare `npx @pleach/core` runs. `create` is
  the preferred verb. `init` runs the same scaffolder today and is
  reserved for a config initializer in a later release.
* **`pleach schema`** — copy the harness Postgres SQL bundle into
  your project so you can apply it against your database.
* **`pleach migrate`** — run that SQL: the base tier plus any
  `--with` tiers, in dependency order, in one transaction that
  rolls back on a failing file. `pleach schema --apply` only copies
  the files; `migrate` applies them.
* **`pleach audit`** — read-only questions over the permission
  ledger: grants in force, decision history, why a path is
  reachable, policy diffs, chain verification, and an evidence
  export. It opens the database read-only and never writes.
* **`pleach permissions`** — the operator's write path over
  permission state: `status`, `clear-taint`, `revoke` and
  `erase-approver`. `clear-taint` and `revoke` each write a ledger
  row, signed only when the install's profile or trust file requires
  it. `status` writes no ledger row. `erase-approver` removes the
  approver id from the erasable side table and writes no row.

<Callout type="warn">
  **Bare `npx @pleach/core` changed.** It used to run the `init` wizard;
  it now opens the TUI. Scripts that relied on the old behavior
  should call `npx @pleach/core init` explicitly.
</Callout>

Two routing rules are worth knowing. A &#x2A;*leading `--flag`** (rather
than a subcommand name) routes to `schema`, preserving the CLI's
older flag-first form. That includes the TUI's own flags:
`npx @pleach/core --print "…"` is refused by `schema` with exit `2`, so name
the subcommand (`npx @pleach/core tui --print "…"`). An **unrecognized bare
word** prints `unknown command` and the help banner, and exits `1`.

The binary name is `pleach`.

## `pleach dev` — the local playground [#pleach-dev--the-local-playground]

`pleach dev` boots a self-contained local playground in your
browser — no host app, no build step, no database. It runs a
**real** graph turn through the shipped `createPleachRoute()` and
folds the resulting `StreamEvent` stream into five DX panels:

* **Lattice visualizer** — the four stages (`anchor-plan`,
  `tool-loop`, `synthesize`, `post-turn`) light up live as nodes
  fire and channels are written.
* **Event log** — the raw `StreamEvent` stream, the same shape the
  ledger and `@pleach/react` hooks consume.
* **Inspector** — per-node / per-channel state at each superstep.
* **Runtime console** — the bracketed runtime log breadcrumbs.
* **Audit ledger** — one `AuditableCall` row per LLM call, rendered
  as it lands.

```bash
npx @pleach/core dev                          # → opens the playground in your browser
npx @pleach/core dev --headless --prompt "…"  # emit-stream capture, no browser
```

### Flags [#flags]

| Flag                               | Default                            | Effect                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--sql`                            | off                                | Durable persistence. Back the route's storage + checkpoint + event-log seams with a local [pglite](https://pglite.dev) (Postgres-in-WASM) store, so chats and checkpoints **survive a restart** — no Docker, no cloud account. Needs the optional peer `@electric-sql/pglite` (`npm install @electric-sql/pglite`); without it, falls back to the in-memory default with a hint. |
| `--sql-dir <path>`                 | `./.pleach-dev-sql`                | Where the pglite store lives. Implies `--sql`. Point it somewhere stable so a restart resumes the same chats.                                                                                                                                                                                                                                                                    |
| `--headless`                       | off                                | No browser. Drive one turn and dump the captured emit stream to stdout — for CI, sharing, or piping into another tool.                                                                                                                                                                                                                                                           |
| `--prompt <text>` (alias `--once`) | a built-in multi-tool chain prompt | The user turn to run. Pairs with `--headless`; omitted, headless runs the default chain so the full lattice fires.                                                                                                                                                                                                                                                               |
| `--markdown` (alias `--md`)        | off                                | With `--headless`, render the emit capture as a Markdown session document instead of raw events.                                                                                                                                                                                                                                                                                 |
| `--plugin <path>`                  | –                                  | Load YOUR `HarnessPlugin` module into the runtime (repeatable). Test it in the browser, or headlessly with the flags below. The module exports its plugin as `default`, a named `plugin`, or a zero-arg factory.                                                                                                                                                                 |
| `--scenarios <path>`               | –                                  | A JSON battery of prompts (array of strings, or `{ name, prompt }`, or `{ scenarios: [...] }`). Drives each headlessly and prints a per-scenario report. Implies headless.                                                                                                                                                                                                       |
| `--report <json\|md>`              | `json`                             | Harness report format when running a battery.                                                                                                                                                                                                                                                                                                                                    |
| `--assert <path>`                  | –                                  | An expectations file. Exits non-zero on any failed expectation — gate it in CI or an agent loop.                                                                                                                                                                                                                                                                                 |
| `--watch`                          | off                                | Re-run the battery and DIFF the report on every `--plugin` file edit (`run → observe → edit`).                                                                                                                                                                                                                                                                                   |
| `--model <id>`                     | the provider's default             | Pin the model the playground turn runs on.                                                                                                                                                                                                                                                                                                                                       |
| `--base-url <url>`                 | the provider's default             | Point the provider stream at a different base URL (self-hosted gateway, proxy).                                                                                                                                                                                                                                                                                                  |
| `--catalog-endpoint <url>`         | OpenRouter's `/models`             | Read the model catalog from a mirror instead.                                                                                                                                                                                                                                                                                                                                    |
| `--port <n>` (alias `-p`)          | `4111`                             | Port for the playground server.                                                                                                                                                                                                                                                                                                                                                  |
| `--open` / `--no-open`             | open                               | Auto-open the browser, or start the server without doing so.                                                                                                                                                                                                                                                                                                                     |

Every value-taking long flag also accepts the `--flag=value` form. `pleach dev` has no `--help`:
an unrecognized flag is ignored, so `pleach dev --help` boots the
playground. Run `npx @pleach/core --help` for the summary.

Note that `--plugin` **on its own keeps the interactive server** —
load your plugin and exercise it in the browser. Headless battery
mode is not requested directly; it engages when any of
`--scenarios`, `--assert`, or `--watch` is present. `--headless` is
a separate one-shot path.

### Key handling [#key-handling]

`pleach dev` reads the active provider's `<PROVIDER>_API_KEY` from
the environment first, then from the in-page key panel you can
paste into without restarting. Precedence is `process.env` first,
then the opt-in persistence store, then none.

| Provider id  | Env var                        |
| ------------ | ------------------------------ |
| `openrouter` | `OPENROUTER_API_KEY`           |
| `anthropic`  | `ANTHROPIC_API_KEY`            |
| `openai`     | `OPENAI_API_KEY`               |
| `google`     | `GOOGLE_GENERATIVE_AI_API_KEY` |
| `deepseek`   | `DEEPSEEK_API_KEY`             |
| `mistral`    | `MISTRAL_API_KEY`              |
| `moonshot`   | `MOONSHOT_API_KEY`             |

Persistence is **opt-in**. When you paste a key into the panel you
can choose to save it to `~/.pleach/dev.env` (written `0600`, one
`<PROVIDER>_API_KEY=<value>` line per provider); the key is never
logged. Without saving, the key lives only for the running session.
If no key is detected, the playground prints guidance naming the
provider env vars to set. There is no keyless mode — a canned turn
proves no value prop, so the playground requires a real key.

### Plugin-test harness — headless, continuous [#plugin-test-harness--headless-continuous]

Point the runtime at your own `HarnessPlugin` and drive a battery
of prompts with no browser. Each scenario folds the same surfaces
the playground tabs expose — conversation, runtime log, event log,
channel snapshot, audit ledger, and the `inspectRuntime` report
(`capabilities wired n/total`) — into one structured report, plus
derived signals (`reachedTerminal`, `stalled`, `notContributed`,
`eventTypes`, `terminalSyntheses`, `auditFamilies`, …):

```bash
# load your plugin into the live playground (test it in the browser)
npx @pleach/core dev --plugin ./my-plugin.mjs

# headless battery → a JSON (or --report md) report per scenario
npx @pleach/core dev --plugin ./my-plugin.mjs --scenarios ./scenarios.json --report md

# gate in CI / for an agent loop: non-zero exit on a failed expectation
npx @pleach/core dev --plugin ./my-plugin.mjs --scenarios ./scenarios.json --assert ./expect.json

# iterate: re-run the battery + DIFF the report on every plugin edit
npx @pleach/core dev --plugin ./my-plugin.mjs --scenarios ./scenarios.json --watch
```

`scenarios.json` is an array of prompts (or `{ name, prompt }`);
`expect.json` declares per-scenario or `all` expectations. Each
predicate maps to a documented guarantee, so a green battery is a
continuously-enforced value-prop contract:

* **Lifecycle** — `reachedTerminal` (the turn reaches a terminal
  answer — assert this, not the rarer natural `converged`),
  `notStalled`, `finalContentIncludes`.
* **Capability wiring** — `minCapabilitiesWired`, `contributes`,
  `eventTypes`.
* **[Channels](/docs/channels)** — `snapshotChannels` (the channels
  a feature promises are written, e.g. `costEvents`/`costRollup`).
* **[Audit ledger](/docs/audit-ledger)** — `minAuditRows`,
  `everyAuditRowClassified` (every LLM call carries a `callClass`),
  `everyAuditRowTenantScoped` (every row carries a `tenantId` —
  [isolation on every row](/docs/multi-tenant)).
* **[Call classes](/docs/call-classes)** —
  `exactlyOneTerminalSynthesis` (one final answer per turn — counts
  `terminalSynthesis` rows, so a thin-draft recovery retry doesn't
  trip it), `atMostOneTerminalSynthesis` (the robust "never two
  final answers"; passes a passthrough turn too), `maxSynthesizeCalls`
  (caps the retry budget), `auditCallClassesIn` (every call's class
  stays within the `utility | reasoning | converse | synthesize`
  taxonomy).
* **Stage lattice** — `auditStagesIn` (every call is stamped with a
  stage from the `anchor-plan | tool-loop | synthesize | post-turn`
  lattice).
* **[Family lock](/docs/family-lock)** — `singleFamily` (the turn
  never silently widens across matrix families — at most one
  resolved `family` across its audit rows).

The report is exactly the feedback an agent needs to run a
`run → observe → edit` loop on your plugin. To run the **same loop
inside your own runtime** (no CLI), flip the [`harness` chatinit
flag](/docs/playground-and-devtools#the-harness-chatinit-flag).

## `pleach init` — the wizard [#pleach-init--the-wizard]

`pleach create` and `pleach init` run the same wizard. It detects
what you already have and asks up to six questions. In order, they
are:

1. **Template** — chatbot (route + page), headless smoke script,
   or plugin-only.
2. **Provider** — `anthropic`, `openai`, `openrouter`.
   The default is whichever provider env var it finds first.
3. **Plugin stub?** — optional `pleach.plugin.ts` (or `.mjs`)
   demonstrating three [HarnessPlugin](/docs/plugin-contract)
   hooks. Skipped for plugin-only, which always writes one. With a
   stub, it also asks the plugin name and a publishing intent
   (`none`, `npm-private`, `npm-public`).
4. **Storage** — `memory` (default) or `sqlite`, a durable
   `./pleach.db`. Pass `--db memory` or `--db sqlite` to skip it.
5. **Schema scaffold?** — asked only when a `supabase/` directory or
   `@pleach/core` is already present. Copies the `base` tier only.
   Default is on when `supabase/` exists.
6. **Enable subagents?** — offers the model a `spawn_agent`
   delegation tool. Default off.

Then it prints a write plan, asks for confirmation, and writes
only files that don't already exist. Existing files are skipped,
not overwritten.

```bash
npx @pleach/core init [--template <name>] [--yes] [--cwd <dir>] [--help]
```

### Flags [#flags-1]

| Flag                   | Default                  | Effect                                                                                                                                                                                                   |
| ---------------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--template <name>`    | `chatbot` (with `--yes`) | Template for the `--yes` / non-TTY path. One of `chatbot`, `headless`, `plugin-only`. Also `flat` / `bundles` to override the plugin-stub shape (default: `bundles`). The interactive path asks instead. |
| `--facets <list>`      | `prompts,safety,tools`   | Comma-separated facet list for the plugin stub. Valid: `prompts`, `safety`, `tools`, `stream`, `lifecycle`.                                                                                              |
| `--facets-file <mode>` | `inline`                 | Single-file inline (default), or `split`, which adds a `facets/README.md` placeholder for moving each facet into `facets/<name>.ts`.                                                                     |
| `--license <SPDX>`     | `Apache-2.0`             | License for the consumer's scaffolded `package.json` (only when `--publishing` is not `none`). Independent of the `@pleach/*` substrate's own FSL-1.1-Apache-2.0 posture.                                |
| `--publishing <mode>`  | `none` (under `--yes`)   | One of `none`, `npm-private`, `npm-public`. Controls `package.json` + `README.md` scaffold.                                                                                                              |
| `--author <name>`      | `null` (under `--yes`)   | Author for scaffolded `package.json`. Interactive mode reads `npm config get init-author-name` as a default.                                                                                             |
| `--repository <url>`   | `null` (under `--yes`)   | Repository URL for scaffolded `package.json`. Interactive mode reads `npm config get init-repository`.                                                                                                   |
| `--yes`, `-y`          | off                      | CI mode — accept all defaults without prompting.                                                                                                                                                         |
| `--cwd <dir>`          | `process.cwd()`          | Run in a different directory.                                                                                                                                                                            |
| `--help`, `-h`         | –                        | Print the init help banner and exit 0.                                                                                                                                                                   |

### What it detects [#what-it-detects]

All best-effort, all from the filesystem and env:

| Signal                   | Values                                                                                 | How                                                                              |
| ------------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Framework                | `next-app`, `next-pages`, `astro`, `sveltekit`, `remix`, `vite`, `react-other`, `node` | `package.json` deps + presence of `app/`                                         |
| Package manager          | `bun`, `pnpm`, `yarn`, `npm`                                                           | Lockfile presence                                                                |
| `@pleach/core` installed | yes / no                                                                               | `package.json` deps                                                              |
| TypeScript project       | yes / no                                                                               | `tsconfig.json` exists                                                           |
| Supabase migrations dir  | yes / no                                                                               | `supabase/` exists                                                               |
| Provider env vars        | which provider keys are reachable                                                      | `process.env` first, then `.env.local`, `.env.development`, `.env` in that order |

Detection runs most-specific to least-specific. Next.js wins
over Vite over plain React, because plain React often hides
under a Next or Vite shell. The fallback for "nothing matched"
is plain Node.

The `.env*` walk is intentionally minimal — no interpolation, no
multi-line values, first occurrence wins. Just enough to surface
a provider key you set but never exported.

### Provider env-var matrix [#provider-env-var-matrix]

| Provider id  | Env var              |
| ------------ | -------------------- |
| `anthropic`  | `ANTHROPIC_API_KEY`  |
| `openai`     | `OPENAI_API_KEY`     |
| `openrouter` | `OPENROUTER_API_KEY` |

The wizard offers every provider whose env var it can find. The
first reachable one is the default selection; if none is set,
the default is `anthropic`.

The wizard offers Anthropic, OpenAI and OpenRouter. The
[quickstart subpath](/docs/getting-started#what-you-just-got)'s
`providerDetection` also recognizes `deepseek`, `google`, `mistral`
and `moonshot` keys. `createPleachRoute` streams a DeepSeek or Google
key from that vendor's own endpoint; it has no built-in stream for
Mistral or Moonshot, so with only one of those keys set the route
answers 503 `no_provider_key` until you pass a `providerStream`.

### Templates [#templates]

The detected framework picks the app files, whichever template you
choose:

| Framework              | Files written                                                                                                                    |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `next-app`             | `app/api/chat/route.ts`, `app/page.tsx`, plus an audit view: `app/auditStore.ts`, `app/api/audit/route.ts`, `app/audit/page.tsx` |
| `next-pages`           | `pages/api/chat.ts`, `pages/index.tsx`                                                                                           |
| `astro`                | `src/pages/api/chat.ts`, `src/pages/index.astro`                                                                                 |
| `sveltekit`            | `src/routes/api/chat/+server.ts`, `src/routes/+page.svelte`                                                                      |
| `remix`                | `app/routes/api.chat.ts`, `app/routes/_index.tsx`                                                                                |
| `vite` / `react-other` | `src/App.tsx` (no server route — pair with a Node server)                                                                        |
| `node`                 | `agent.mjs` — smoke script that runs one real turn through `createPleachRoute` and prints the streamed answer                    |

The template decides the plugin stub. `plugin-only` always writes
`pleach.plugin.{ts,mjs}` (bundled stub by default; `--template flat`
for the legacy single-facet shape). `chatbot` writes one under
`--yes`, and asks interactively. `headless` writes none under
`--yes`, and asks interactively. A stub with
publishing `npm-private` or `npm-public` also gets a `package.json`,
and `npm-public` a `README.md`.

The chatbot route templates import `createPleachRoute` from
[`@pleach/core/quickstart`](/docs/subpath-exports); the page
templates import `ChatBox` from `@pleach/core/quickstart/react`. The
headless template's `agent.mjs` builds a `createPleachRoute` handler
and posts one message to it, reading the event stream with `readStreamEvents`. The plugin stub uses `createPlugin`,
`appendPrompt`, and `gatedPrompt` — three of the
[plugin contract](/docs/plugin-contract) hooks. For the full
quickstart subpath surface (`createPleachRoute`, `useChat` and
`<ChatBox />` on the `/react` subpath, `defaultPlugin`, `createBenchmarkPlugin`,
`providerDetection`), see
[Getting started → What you just got](/docs/getting-started#what-you-just-got).

### Idempotence [#idempotence]

Files that already exist are skipped, never overwritten. The
wizard's `done` block reports written, skipped, and failed
counts. For a clean re-run, delete the files the wizard wrote
the first time.

### CI mode [#ci-mode]

`--yes` runs without prompts. Defaults: `template = chatbot`,
provider = whichever the env detection picked (or `anthropic`),
`withPlugin = true` for chatbot or plugin-only,
`withSchema = true` if `supabase/` exists.

```bash
npx @pleach/core init --yes --template plugin-only --cwd ./my-app
```

Non-TTY invocations (CI runners, piped stdin) take the `--yes`
path automatically even without the flag.

### Exit codes [#exit-codes]

| Code | When                                                                    |
| ---- | ----------------------------------------------------------------------- |
| 0    | Success, help, an aborted write plan, or `--yes` with zero write errors |
| 1    | One or more files failed to write                                       |
| 2    | An unknown facet in `--facets`                                          |

### Worked example — Next.js App Router [#worked-example--nextjs-app-router]

```
$ npx @pleach/core init

pleach init — charm-style wizard for @pleach/core

┌─ environment
│ directory      › /Users/you/my-app
│ framework      › Next.js (App Router) (tsconfig.json)
│ package mgr    › pnpm
│ @pleach/core   › not yet installed
│ provider env   › anthropic (.env.local)
│ supabase/      › found
└─

? Template
  ● 1) Chatbot (route + page)   default — streaming UI
  ○ 2) Headless smoke script    node agent.mjs, no UI
  ○ 3) Plugin stub only         add to an existing app
› (1-3, default 1)

? Provider
  ● 1) anthropic                ANTHROPIC_API_KEY set
  ○ 2) openai                   OPENAI_API_KEY unset
  ○ 3) openrouter               OPENROUTER_API_KEY unset
› (1-3, default 1)

? Generate a sample plugin stub? (y/N) y
› plugin name (default: my-plugin) triage-plugin

? Publishing intent
  ● 1) Local-only (no package.json scaffold)
  ○ 2) npm-private
  ○ 3) npm-public
› (1-3, default 1)

? Scaffold the base Postgres schema into supabase/migrations? (extensions: npx @pleach/core schema --list) (Y/n)

? Enable subagents? (offer the model a spawn_agent delegation tool) (y/N)

┌─ write plan
│ • app/api/chat/route.ts
│ • app/page.tsx
│ • app/auditStore.ts
│ • app/api/audit/route.ts
│ • app/audit/page.tsx
│ • pleach.plugin.ts
│ • supabase/migrations/20260608120000_base__<bundle-file>.sql  (from schema bundle)
└─
? Write 7 file(s)? (Y/n)

done
  ✓ wrote      app/api/chat/route.ts
  ✓ wrote      app/page.tsx
  ✓ wrote      app/auditStore.ts
  ✓ wrote      app/api/audit/route.ts
  ✓ wrote      app/audit/page.tsx
  ✓ wrote      pleach.plugin.ts
  ✓ wrote      supabase/migrations/20260608120000_base__<bundle-file>.sql

next steps
  1. pnpm add @pleach/core
  2. ANTHROPIC_API_KEY loaded from .env.local (framework auto-loads at dev time)
  3. pnpm dev — chat lives at the root page
```

The plan shows one line per `base` file; one is shown here.
Step 1 works once `@pleach/core` is published; it's
[not on npm yet](/docs/install#not-on-npm-yet).
The "next steps" block adapts to the package manager the wizard
detected. With bun it suggests `bun add` and `bun run dev`; with
npm, the npm equivalents. Same with the provider-key line — if
the key was found in `process.env`, the line is dropped from
next-steps entirely.

### Plugin stub shape [#plugin-stub-shape]

When `template = plugin-only` (or you accept the plugin stub), the
wizard scaffolds a `pleach.plugin.ts` file. The default shape is now
**bundle-aware**: each facet (`prompts`, `safety`, `tools` by default)
gets its own `definePleachPlugin` const, composed into a single
exported plugin array.

```ts
// pleach.plugin.ts (default — bundle-aware shape)
import { definePleachPlugin } from "@pleach/core";

const promptsFacet = definePleachPlugin("my-plugin", { prompts: [] });
const safetyFacet  = definePleachPlugin("my-plugin", { safetyPolicies: [] });
const toolsFacet   = definePleachPlugin("my-plugin", { tools: [] });

export const myPlugin = [promptsFacet, safetyFacet, toolsFacet];
```

Wire at the runtime registration site via array spread:

```ts
new SessionRuntime({ plugins: [...myPlugin] });
```

This shape teaches the multi-facet pattern from day 1 — when a facet
grows past \~50 lines, move its const to `facets/<facet>.ts` per
[plugin authoring standards](/docs/plugin-authoring-standards).

The single-facet shape (one `definePleachPlugin` call covering all
hooks) is still available via `--template flat`:

```bash
npx @pleach/core init --template flat
```

See [plugin bundles](/docs/plugin-bundles) for the rationale behind
the multi-facet pattern and the planned `composePlugin` upgrade path.

## `pleach init plugin` — monorepo subcommand [#pleach-init-plugin--monorepo-subcommand]

For an existing project that needs to add a plugin without re-running
framework detection:

```bash
npx @pleach/core init plugin --name corpus-safety --facets safety,prompts
```

Scaffolds `plugins/corpus-safety/` with four files:

| File                   | Content                                                   |
| ---------------------- | --------------------------------------------------------- |
| `src/pleach.plugin.ts` | Bundle-aware stub with the requested facets               |
| `package.json`         | License + peer-dep + scripts, standards-aware defaults    |
| `README.md`            | Install + use + standards reference seed                  |
| `tsconfig.json`        | TypeScript config seed (ES2022, strict, declaration emit) |

If a `tsconfig.json` exists at the top level, the wizard also inserts
a path-map entry (`compilerOptions.paths["corpus-safety"]`) as a
courtesy. Best-effort: skips and warns if the tsconfig can't be parsed.

### Subcommand flags [#subcommand-flags]

| Flag                          | Default                | Effect                                                                                                                               |
| ----------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `--name <kebab>`              | required               | Plugin identity. Required under `--yes`.                                                                                             |
| `--facets <list>`             | `prompts,safety,tools` | Same vocabulary as `pleach init`.                                                                                                    |
| `--template flat\|bundles`    | `bundles`              | Stub shape override.                                                                                                                 |
| `--facets-file inline\|split` | `inline`               | Single-file vs split-file layout.                                                                                                    |
| `--at <path>`                 | `plugins/<name>/`      | Scaffold target.                                                                                                                     |
| `--license <SPDX>`            | `Apache-2.0`           | License id for the consumer's generated `package.json`. (Independent of the `@pleach/*` substrate's own FSL-1.1-Apache-2.0 posture.) |
| `--publishing <mode>`         | `npm-private`          | One of `none`, `npm-private`, `npm-public`.                                                                                          |
| `--author <name>`             | (none)                 | Skipped under `--yes` unless supplied.                                                                                               |
| `--repository <url>`          | (none)                 | Skipped under `--yes` unless supplied.                                                                                               |
| `--yes`, `-y`                 | off                    | CI mode. `--name` becomes required.                                                                                                  |
| `--cwd <dir>`                 | `process.cwd()`        | Run in a different directory.                                                                                                        |
| `--help`, `-h`                | –                      | Print the subcommand help banner and exit 0.                                                                                         |

The subcommand never modifies the top-level `package.json` or app
code beyond the optional path-map insertion. It writes only inside
the target directory.

## `pleach schema` — copy the SQL bundle [#pleach-schema--copy-the-sql-bundle]

Scaffolds the harness storage schema into a target directory.
This is the surface that used to live under `pleach init`. A
command line that starts with a flag (`npx @pleach/core --apply`) still
routes here so existing scripts don't break. `pleach init --apply`
now runs the wizard and ignores `--apply`.

```bash
npx @pleach/core schema [--apply] [--with a,b,...] [--list] [--timestamped] [--target <dir>]
```

The bundle is tiered: the `base` tier is always copied, and `--with`
adds opt-in tiers. See [Schema](/docs/schema) for what each tier holds.

### Flags [#flags-2]

| Flag               | Default                                                           | Effect                                                                                                                 |
| ------------------ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `--with <tier>`    | –                                                                 | Add a core extension, e.g. `team`, `outbox`, `vector-search`, `compliance`. Comma-separate several or repeat the flag. |
| `--with <package>` | –                                                                 | Add a package that ships SQL through `"pleach": { "schema": … }` in its `package.json`, e.g. `@pleach/gateway`         |
| `--with all`       | –                                                                 | Every core extension plus every first-party `@pleach/*` package that declares a schema                                 |
| `--list`           | –                                                                 | List `base`, every core extension (with what it requires), and every resolvable package schema, then exit 0            |
| `--target <dir>`   | `./supabase/migrations` if it exists, else `./harness-migrations` | Destination for the copied SQL files                                                                                   |
| `--dry-run`        | on                                                                | Print the file-copy plan; write nothing                                                                                |
| `--apply`          | off                                                               | Actually write the files                                                                                               |
| `--timestamped`    | off                                                               | Name files `YYYYMMDDHHMMSS_<tier>__<file>.sql` (UTC) so they slot into a Supabase migration history                    |
| `--help`, `-h`     | –                                                                 | Print the banner and exit 0                                                                                            |

An unknown flag, a stray positional argument, or a flag missing its
value is refused (exit 2) rather than ignored, so a misspelt `--with`
never copies less SQL than you asked for.

### What it does [#what-it-does]

1. Locates the schema bundle inside the installed package
   (`node_modules/@pleach/core/src/schema/postgres/`). The SQL
   ships as source files in the published tarball; the build does
   not copy it into `dist/`.
2. Selects `base` plus each `--with` tier, closed over each tier's
   `requires`, and orders them so a tier applies after the tiers it
   depends on.
3. Names each file `<rank>_<tier>__<original>.sql`. The rank is fixed
   per tier (base `000`, core extensions `100`+, packages `200`+), so a
   tier's names never depend on what else you select. With
   `--timestamped`, a UTC timestamp replaces the rank, and an earlier
   copy is recognised by `<tier>__<original>` under any timestamp.
4. Copies the files into your target directory (creating it if
   needed).

### What it doesn't do [#what-it-doesnt-do]

* Connect to your database.
* Run the migrations.
* Overwrite a file whose content differs. A target file with
  identical content is skipped, so you can add tiers later (`--apply`,
  then `--apply --with team`). A same-named file with different
  content makes `--apply` exit 3 before anything is written.

### Exit codes [#exit-codes-1]

| Code | When                                                                                                                                                      |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 0    | Success, dry-run completed, `--list`, or `--help`                                                                                                         |
| 2    | Schema bundle missing (is `@pleach/core` installed?), no SQL files in the bundle, an unknown extension or unresolvable package in `--with`, or a bad flag |
| 3    | A target file already exists with different content — nothing written                                                                                     |

### Applying the migrations by hand [#applying-the-migrations-by-hand]

The tables install into the `public` schema. Apply each file inside
its own transaction, in sorted order:

```bash
for f in harness-migrations/*.sql; do
  psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -1 -f "$f" || break
done
```

If you're using the Supabase CLI, which wraps each file in a
transaction:

```bash
pleach schema --apply --timestamped
supabase db push
```

Re-applying the bundle is safe and upgrades an older install in
place. The package's `CHANGELOG.md` records the version each schema
change shipped in.

## `pleach audit` — read the permission ledger [#pleach-audit--read-the-permission-ledger]

Answers questions over the permission ledger: the `permission.*`
rows in the event log. It reads the same answers as the
[`@pleach/core/audit/permission-ledger`](/docs/audit-ledger#permission-ledger)
module, so a script and an auditor see the same rows.

```bash
npx @pleach/core audit <command> [source] [filters] [--json]
```

The command is read-only. A SQLite file is opened with SQLite's
read-only flag plus `PRAGMA query_only`; a Postgres session is set to
read-only transactions. A database without the permission views is
refused, never upgraded.

### Commands [#commands]

| Command               | Answers                                                                                                                                                               |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `permissions`         | Grants in force (the current-grants view)                                                                                                                             |
| `history`             | Every permission decision, oldest first                                                                                                                               |
| `why <path>`          | The grants whose scope covers `<path>`, current grants first, then earlier decisions naming it. The path is resolved first: symlinks, `.` and `..`. It need not exist |
| `diff-policy <a> <b>` | A structured diff of two stored policy documents, named by SHA-256 or a unique prefix of 8 or more hex digits                                                         |
| `verify`              | Re-walks every chain that carries a permission decision, and checks each permission row's signature                                                                   |
| `export --out <dir>`  | Writes the evidence bundle and its `manifest.json` to a new directory                                                                                                 |

`export` writes `decisions.json`, `current-grants.json`,
`policies.json`, `signers.json`, `chains.json`, `verification.json`
and a `manifest.json` with each file's SHA-256. The directory is
created with mode `0700` and each file with `0600`; an existing path
is refused. An export whose content matches a key-material marker is
refused. No key material is read or exported.

### Source [#source]

| Flag                   | Reads                                                                                                                                   |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `--db <path>`          | A `pleach.db`. Default `<config>/pleach.db`, where `<config>` is `$PLEACH_CONFIG_DIR`, else `$XDG_CONFIG_HOME/pleach`, else `~/.pleach` |
| `--database-url <url>` | A Postgres database with the `permissions` schema tier                                                                                  |
| `--postgres`           | Postgres at `$DATABASE_URL`                                                                                                             |

Give one source. Postgres needs the `pg` package (`npm install pg`).
SQLite needs Node 22.5 or later (`node:sqlite`) or the optional
`better-sqlite3`. Apply the Postgres tier with
`npx @pleach/core schema --apply --with permissions`.

### Filters and options [#filters-and-options]

| Flag                              | Applies to            | Effect                                                                                                                                        |
| --------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `--tenant <id>`                   | all but `diff-policy` | One tenant                                                                                                                                    |
| `--chain-kind <kind>`             | all but `diff-policy` | `chat`, `session`, `subject`, `tenant-audit`, `auth` or `workspace`                                                                           |
| `--chain <id>`                    | all but `diff-policy` | One chain id                                                                                                                                  |
| `--workspace <path>`              | all but `diff-policy` | The workspace chains of this folder, resolved to its real path. A missing folder is a usage error                                             |
| `--decision <d>`                  | `history`             | `granted`, `escalated`, `denied` or `revoked`. Repeat or comma-separate                                                                       |
| `--capability <kind>`             | `history`             | One capability kind, e.g. `fs` or `code_exec_sandbox`                                                                                         |
| `--since <iso>` / `--until <iso>` | `history`             | `created_at >=` / `created_at <`, as ISO-8601 or `YYYY-MM-DD`                                                                                 |
| `--limit <n>`                     | `history`             | At most `n` rows (a positive integer)                                                                                                         |
| `--out <dir>`                     | `export`              | Required. The new directory to write                                                                                                          |
| `--include-chain-rows`            | `export`              | Also write every row of the exported chains to `chain-rows.jsonl`, so they can be re-walked offline. Those rows can hold conversation content |
| `--trusted-signers <file>`        | `verify`, `export`    | Signer fingerprints to trust, one per line. Default `<config>/trusted-signers`. A file writable by group or others is ignored                 |
| `--json`                          | all                   | Machine-readable JSON on stdout                                                                                                               |
| `--help`, `-h`                    | –                     | Print the command's help and exit 0                                                                                                           |

### Reading `verify` [#reading-verify]

Each chain row prints a `RESULT` of `verified` or
`FAILED at <where>: <reason>`. `verified` means the links and hashes
match and every chained row the walk could place was graded. A chain
with zero chained rows is not verified.

The `NOTE` column lists rows the verdict could not fully grade:

* **Rows not graded** (a stored hash that is not a digest) fail the chain.
* **Payloads not verifiable** (no payload hash, or a hash taken over insertion order) are noted only.
* **Rows with no sequence number** (Postgres) are noted only. The walk never sees them.

`HEAD` reads `checked` when the walk was also checked against the
chain's committed head, which catches a deleted tail. SQLite keeps no
committed head, so it reads `not kept` there.

Each permission row then gets a signature status: `signed`,
`unsigned`, `unsigned (read-only)`, `unsigned (no profile row)`,
`bad signature`, `untrusted signer`, `bad envelope` or `bad position`.
These fail verification:

* an unsigned row under a profile above read-only;
* an unsigned row after a signed one on the same chain;
* an unsigned row when the trusted-signers file names any signer;
* a bad signature, an untrusted signer, a bad envelope or a bad position.

A change of signer between two valid rows is printed as a key
boundary, not a failure.

### Exit codes [#exit-codes-2]

| Code | When                                                                                                                                    |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------- |
| 0    | Answered. For `verify` and `export`: at least one chain, and every chain, verified                                                      |
| 1    | `verify` or `export`: a chain or signature failed, or no chain was verified. `diff-policy`: a stored digest does not match its document |
| 2    | Usage error, unreadable source, a database without the permission views, or a refused export                                            |

## `pleach tui` — the terminal UI [#pleach-tui--the-terminal-ui]

```bash
npx @pleach/core             # bare invocation opens the TUI
npx @pleach/core tui         # the same thing, named
npx @pleach/core tui --help  # args pass straight through to the TUI binary
```

Everything after `tui` is forwarded verbatim to the binary, so the
TUI owns its own flag surface.

The TUI is a compiled Go binary. It does not reimplement the
runtime — it starts a **Node sidecar** and drives it, so a terminal
session and an HTTP route execute the same code:

```
pleach tui  →  the Go binary  →  the Node sidecar  →  core's own agent
```

The sidecar runs `createPleachAgent` from `@pleach/core`, the same
factory behind `createPleachRoute`. It adds local-only tools (learning
review and background process control) and a turn deadline: a turn
that runs past 10 minutes parks, and the TUI continues it. It never
calls your route handler. To drive your own server instead, point the
TUI at it with `--url`.

### Flags [#flags-3]

Everything after `tui` is forwarded verbatim, so this is the binary's
own surface, not a wrapper's.

| Flag                    | What it does                                                                                                                                                                                      |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--url <server>`        | Connect to a **remote** `@pleach/core` server instead of starting the local sidecar.                                                                                                              |
| `--continue`, `-c`      | Resume the last session. Local sessions persist in the durable SQLite store.                                                                                                                      |
| `--resume <id>`         | Resume one specific prior session id.                                                                                                                                                             |
| `--print <msg>`         | **Headless.** Send one message, stream just the answer to stdout, exit — no TUI. This is the scriptable smoke/verify path.                                                                        |
| `--output-format <f>`   | With `--print`: `text` (answer only, default), `json` (one result object), or `stream-json` (one JSON object per wire event, then the result). `--json` is an alias for `json`.                   |
| `--login`               | **Headless credential path, SSH/container safe.** Prints an authorization URL, waits for the code the provider's page displays, exchanges it, and saves the credential. No loopback listener.     |
| `--provider <id>`       | Provider for `--login` (default `openrouter`).                                                                                                                                                    |
| `--events`              | With `--print` (or a positional/stdin message): stream *every* graph event — nodes, stages, channels, tools, deltas — instead of only the answer. Requests the server's verbose diagnostics tier. |
| `--tune`                | Print what this machine's ledger would derive for the agent's tuning knobs, beside the values in force, then exit. Read-only — never writes a knob.                                               |
| `--heartwood-url <url>` | Absolute URL of a persisted-identity endpoint for `/heartwood`. Falls back to the local `~/.pleach/heartwood.md`.                                                                                 |

`--print` with `--events` is the pairing to reach for when you want to
*see* the four-stage lattice rather than read about it: one command,
every node firing and every stage transition on stdout.

```bash
npx @pleach/core tui --print "What is 47 x 89?"            # just the answer
npx @pleach/core tui --print "What is 47 x 89?" --events   # the full event lattice
npx @pleach/core tui --print "..." --json                  # {"type":"result","text":...}
npx @pleach/core tui --login                               # paste-the-code sign-in (SSH)
```

Headless exit codes are classed, so a script can branch without parsing
stderr: `0` success, `2` usage (bad flag / no message / unknown output
format), `3` caller or credential (10xxx), `4` provider (5xxx), `5` cost
budget, `1` anything else.

### Interactive conventions worth knowing [#interactive-conventions-worth-knowing]

| Input                                      | Behaviour                                                                                                                                                                          |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Enter`                                    | Send. While a turn is running the message is **queued** and sent when it ends — it is never dropped.                                                                               |
| `Esc`                                      | Interrupt the running turn. With a draft or queued message it arms a quit (press again) instead of exiting and losing work; `Ctrl+C` quits immediately.                            |
| `Shift+Tab`                                | Cycle permission mode: `ask` → `read-only` (mutating tools auto-denied) → `accept-edits` (file edits and test runs auto-approved). The mode is in the status line.                 |
| `Ctrl+O`                                   | Move a focus ring across this turn's tool cards; `Enter` on an empty composer expands the focused card.                                                                            |
| `@path`                                    | Inline file reference with completion; the file rides the next turn as a reference (same 256 KB and UTF-8 validation as `/attach`).                                                |
| `/mode`                                    | Set or report the permission mode (`ask`, `read-only`, `accept-edits`).                                                                                                            |
| `/diff`                                    | The last turn's edit-tool changes. Shell-driven workspace changes are named as unobserved rather than omitted.                                                                     |
| `/undo`                                    | Restore the newest checkpoint (confirmation names it). `/rewind` is an alias.                                                                                                      |
| `/status`                                  | Version, runtime, permission mode, root/branch, credential, model, store durability, folder trust, docs.                                                                           |
| `/init`                                    | Create `PLEACH.md` in the launch root. The local sidecar reads `PLEACH.md` (else `AGENTS.md`) and appends it to the system prompt; `/init` never overwrites an existing file.      |
| `/compact`                                 | Context budget and compaction state. Compaction itself is automatic at the runtime threshold; no manual trigger is exposed.                                                        |
| `/agents` (`/swarm`)                       | Live sub-agent lifecycle from the durable ledger: running/completed/failed, depth, steps, tools, duration, error. Refreshes every 2 s; `/lineage` remains the post-hoc spawn tree. |
| `/jobs`                                    | Background processes the `process` tool started: list, `k` kill (SIGTERM), refresh. Uses the same backend as the tool.                                                             |
| `/schedule add <when> <prompt> [every=1d]` | Create a durable scheduled task (same validation as the model's `schedule` tool). `/schedule cancel N` removes one.                                                                |
| `/login`                                   | Re-authorize the provider credential in the browser (local sidecar only); the saved key is used on the next launch.                                                                |

The model catalog is prefetched at **every** launch (local sidecar or `--url`)
and reused by `/model` for ten minutes; it is the static matrix filtered to the
route's locked transport, so native providers list only their own family and
OpenRouter lists the exposed set.

<Callout type="warn">
  **Every `--print` / `--events` run is a real, billed model turn.** There
  is no keyless mode on any `pleach` CLI — headless output is a different
  *projection* of a live turn, never a canned one. (`--login`, `--tune`
  and the interactive TUI's own inspection commands cost no model turn.)

  A deprecated `--demo` alias for `--print --events` still parses and
  prints a deprecation notice. Do not reach for it: the name reads
  keyless and the turn is billed. Use `--print --events`.
</Callout>

### The sidecar's `/mcp` endpoint [#the-sidecars-mcp-endpoint]

The local sidecar admits only the `pleach` process that launched it:
every request carries a per-launch bearer token that exists only in
that parent. Upgrade the `pleach` binary and `@pleach/core` together,
because an older binary passes no token and the sidecar exits.

Its `/mcp` `tools/call` must name a session in
`params._meta["pleach/sessionId"]`, and runs against that session's
live runtime:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "fs_read",
    "arguments": { "path": "README.md" },
    "_meta": { "pleach/sessionId": "018f..." }
  }
}
```

* A `tools/call` that names no session gets JSON-RPC error `-32602`.
* A session with no live runtime gets `-32001`.
* Neither falls back to another session's runtime.
* A tool that needs approval is refused, because `tools/call` can't
  collect one.
* `tools/list` without a session serves the configured catalog (the
  same listing as `GET /api/harness/tools`); with one, that session's
  live catalog.

Standard MCP clients can't set `params._meta`, so external clients
such as Claude Desktop can't call tools on the sidecar. To expose tools
to an MCP client, see [MCP](/docs/mcp).

### The binary is built at install time [#the-binary-is-built-at-install-time]

The Go binary is materialized by the package's `postinstall`
script. Installs that skip lifecycle scripts — `npm ci --ignore-scripts`, common in regulated and SBOM-generating
environments — will not have it.

<Callout type="info">
  **A missing TUI binary is an expected state, not a failure.**
  Bare `npx @pleach/core` falls back to the help banner rather than
  erroring, so it never dead-ends. Rebuild it with `npm rebuild
    @pleach/core`. Every other subcommand is pure Node and keeps
  working regardless.
</Callout>

## Local development without a database [#local-development-without-a-database]

If you don't want to run any migrations during development, skip
the CLI entirely and omit `storage` and `checkpointer` when you
construct the runtime. With both absent it falls back to
`MemoryAdapter` + `MemorySaver`, so nothing touches a database.
See [environment variables](/docs/env-vars) for the full list of
runtime-read env vars.

## Project layout — after the wizard [#project-layout--after-the-wizard]

The [baseline](/docs/project-layout#a-layout-that-works) plus
the files `pleach init` writes. This is what a Next.js App
Router project looks like one command after `npx @pleach/core init`
on the chatbot template with plugin stub and schema scaffold:

```
my-app/
  app/
    api/
      chat/route.ts             # wizard-written — createPleachRoute({ provider, plugins })
    page.tsx                    # wizard-written — <ChatBox apiUrl="/api/chat" />
    auditStore.ts               # wizard-written — in-memory audit rows for /audit
    api/audit/route.ts          # wizard-written — per-provider audit summary
    audit/page.tsx              # wizard-written — the /audit view
  pleach.plugin.ts              # wizard-written — definePleachPlugin facets + appendPrompt + gatedPrompt
  supabase/
    migrations/
      20260608120000_base__*.sql    # wizard-copied from the schema bundle
  .env.local                    # ANTHROPIC_API_KEY (or your provider key)
  package.json
  tsconfig.json
```

What changes from the baseline:

* **The route handler is one line.** `createPleachRoute({...})`
  is what you'd normally write by hand; the wizard writes it for
  you. Wire your own [`HarnessPlugin`](/docs/plugin-contract)
  set into the `plugins:` array as you grow.
* **`pleach.plugin.ts` is the starting point**, not the final
  shape. The stub shows three hooks — `prompts`, `runtimePrompts`,
  and the plugin-construction call. The
  [plugin contract](/docs/plugin-contract) covers the full set
  (`contributeTools`, `contributeSafetyPolicies`, etc.); replace
  the stub when you outgrow it.
* **`supabase/migrations/` holds the `base` tier.** With a
  `supabase/` directory the wizard timestamps the files
  (`<UTC timestamp>_base__<file>.sql`) so Supabase's lexicographic
  migration order matches the bundle order. Without one it writes
  `harness-migrations/000_base__<file>.sql`, ranked for applying by
  hand. Add extension tiers with `npx @pleach/core schema --apply --with <tier>`.

## Sibling-SKU binaries [#sibling-sku-binaries]

Sibling SKUs (`@pleach/compliance@0.1.0`,
`@pleach/eval@0.1.0`, `@pleach/gateway@0.1.0`,
`@pleach/replay@0.1.0`, `@pleach/mcp@0.1.0`,
`@pleach/coding-agent@0.1.0`) are built (not on npm yet). None of them
ships a bin yet: `pleach` in `@pleach/core` is the only one. The
convention when a sibling gains one is a bin under its own name
(`pleach-compliance`, `pleach-eval`, and so on). The `pleach` bin in
core is reserved for substrate-level
operations, and the terminal UI is one of them: it ships &#x2A;*inside
`@pleach/core`** rather than as a sibling SKU, so `pleach tui`
needs no additional install. Per-sibling bins land alongside each SKU's first
useful command surface; check the package's npm page for the
current bin inventory.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Getting started" href="/docs/getting-started" description="Install, wire a SessionRuntime, stream your first message." />

  <Card title="Project layout" href="/docs/project-layout" description="The orienting layout the wizard produces — described, not prescribed." />

  <Card title="Plugin contract" href="/docs/plugin-contract" description="The full HarnessPlugin surface the wizard's plugin stub demonstrates three hooks of." />

  <Card title="Environment variables" href="/docs/env-vars" description="Every env var the runtime reads, with defaults." />

  <Card title="Subpath exports" href="/docs/subpath-exports" description="The schema bundle and every other named subpath you can import." />
</Cards>
