Metadata-Version: 2.4
Name: xmemcli
Version: 0.0.8
Summary: Command-line client for the xmemory HTTP API: PKCE auth, instances, read/write, schema and XMD tools.
Keywords: api,cli,llm,memory,xmemory
Requires-Python: <4,>=3.12
Description-Content-Type: text/markdown

# `xmemcli` — xmemory command-line client

Single-command CLI for reading from, writing to, and managing xmemory instances over the HTTP API at `$XMEM_API_URL` (default `https://api.xmemory.ai`), using an API key from the Console UI or `xmemcli auth login`.

Full command reference is included below.

## Usage

```text
xmemcli auth login [--no-browser] [--timeout S] [--console-url URL]
xmemcli auth logout
xmemcli auth status
xmemcli read <query>
xmemcli write <text>
xmemcli write-status <write_id> [<id> …]
xmemcli quota
xmemcli binding list [--autoload]
xmemcli binding add <instance_id> [--tier autoload|available|off] [--scope project|user]
xmemcli binding remove <instance_id> [--scope project|user]
xmemcli context [--text] [--max-tokens N] [--no-live-state]
```

Global flags / env: `--api-key` / `$XMEM_API_KEY`, `--instance-id` / `$XMEM_INSTANCE_ID`, `--api-url` / `$XMEM_API_URL`, `--rc-dir` / `$XMEM_RC_DIR`, `--binding-dir` / `$XMEM_BINDING_DIR`, `--json`, `--verbose`. See `xmemcli help options`.

Credential resolution: `--api-key` → `$XMEM_API_KEY` → nearest `.xmemrc.json` (walk up from `--rc-dir` toward `$HOME`). Origin: `--api-url` → `$XMEM_API_URL` → rc `api_url` → default.

`context` is the exception: it runs unattended from a session-start hook, with no person and no chosen directory behind it, so it resolves the credential from `$HOME` **only** — a project `.xmemrc.json` is used only when `--api-key` / `$XMEM_API_KEY` or `--rc-dir` / `$XMEM_RC_DIR` names it explicitly. That stops a cloned repository shipping the key and origin its own context is fetched with.

Two local files, same discovery rule, different jobs: `.xmemrc.json` holds the credential (`0600`, never committed, nearest wins); `.xmemory.json` holds the instance binding (`0644`, *meant* to be committed at project scope, every scope merged). `binding` commands are local-only — no network, no credential.

## Read / write modes

| CLI | API field |
|-----|-----------|
| `xmemcli write --extraction fast` (default) | `extraction_logic: "fast"` |
| `xmemcli write --extraction deep` | `extraction_logic: "deep"` |
| `xmemcli write --no-wait` | async write; poll with `write-status` |
| `xmemcli read --read-mode single` (default) | `mode: "single-answer"` |
| `xmemcli read --read-mode raw` | `mode: "raw-tables"` |
| `xmemcli read --read-mode xresponse` | `mode: "xresponse"` |

`--read-mode` selects the **server-side answer shape**; `--json` and the TTY rule govern stdout format.

## Curated output

The CLI does not echo raw API payloads. Server internals (`sql`, `diff_plan`, extraction trees) are never emitted. Read responses keep `pending_suggestions` (schema-evolution hint). `--verbose` adds `trace_id` and `console_url` when present.

## Output personality — JSON vs pretty

- **Non-TTY stdout** or **`--json`**: exactly one JSON document.
- **Interactive TTY** without `--json`: short one-line summaries per command.

Scripts can rely on `xmemcli … | jq` without `--json`.

## Example session

```bash
export XMEM_API_KEY="xmem_..."
export XMEM_INSTANCE_ID="<uuid>"

xmemcli write "John likes orange"
xmemcli read "what colour does John like?"

ID1=$(xmemcli write --no-wait "Ivy likes amber"  | jq -r .write_id)
ID2=$(xmemcli write --no-wait "Lev likes indigo" | jq -r .write_id)
xmemcli write-status "$ID1" "$ID2"
```

## Install

Requires **Python 3.12+**. Stdlib only — no runtime dependencies.

Preferred:

```bash
uv tool install xmemcli
```

When uv is not available:

```bash
pip install xmemcli
```

Then:

```bash
xmemcli version
xmemcli auth login
```

Version: **0.0.8**.


---

# `xmemcli` auth flow — PKCE handoff and credentials

The CLI is **human-governed for key acquisition**: an AI-assisted IDE may run reads, writes, and inventory, but **acquiring an API key** stays under human control in the browser. A key must **never enter the AI transcript** — it is handed to the CLI out-of-band via `xmemcli auth login` or environment / `.xmemrc.json`.

**Model:** the CLI sends the human to **`/xmemcli/<challenge>`** on the Console, listens on **`127.0.0.1:9636/callback`**, and the Console redirects a signed short-lived **code** (not the key) to that callback.

> **Scope.** Shipped in this package: `.xmemrc.json` discovery, PKCE `auth login` / `logout` / `status`, `/whoami` consumption, and `quota`. Server endpoints: `POST /cli/handoff`, `POST /cli/token`.

## Acquiring a key

The human either:

- **Provides a key they already hold** (`$XMEM_API_KEY`, `.xmemrc.json`, or paste at login), or
- **Creates a key** in the Console and clicks **"Use this key in the CLI"** (when the page was opened via `/xmemcli/<challenge>`).

During **onboarding**, the Console may auto-handoff an onboarding key while a short-lived cookie bridge is active.

### Why a code, not the key

Plaintext keys in URLs leak to history and proxies. Handoff uses **PKCE + signed code + localhost callback**:

1. CLI mints **`verifier`**, derives **`challenge`** = `base64url(SHA256(verifier))`, opens **`/xmemcli/<challenge>`**.
2. Human clicks **"Use this key in the CLI"** → Console **`POST`s the key** to `/cli/handoff` bound to the challenge → receives a short-lived **`code`**.
3. Browser navigates to **`http://127.0.0.1:9636/callback?code=…&state=<challenge>`** — key never in the URL.
4. CLI **`POST /cli/token`** with `{ code, verifier }` → receives key → writes `0600` `.xmemrc.json`.

### Sequence

```
AI-assisted IDE ── xmemcli auth login ──► CLI: PKCE verifier + localhost listener
Human ── opens Console URL ──► creates key → "Use this key in the CLI"
CLI ◄── localhost redirect ── redeems code + verifier → writes .xmemrc.json
AI-assisted IDE ── xmemcli read/write ──► CLI resolves key; never handles plaintext key
```

## Credential store (`.xmemrc.json`)

Project-local **`.xmemrc.json`**: `{email, api_url, api_key}`. Found by walking up from `--rc-dir` / CWD, ceiling `$HOME`.

Resolution order: `--api-key` → `$XMEM_API_KEY` → `.xmemrc.json`. Origin: `--api-url` → `$XMEM_API_URL` → rc `api_url` → default — **except** when the key is explicit (`--api-key` / `$XMEM_API_KEY`): the rc's `api_url` is skipped and the origin falls back to the built-in default unless you also set `--api-url` / `$XMEM_API_URL`. The localhost-key-at-prod guard applies when the key comes from the rc and an explicit `--api-url` / `$XMEM_API_URL` mismatches that rc origin.

## Identity — `/whoami`

`xmemcli auth status` calls **`GET /whoami`** with the active bearer key and reports `{authenticated, email, key_prefix}`. Exit `0` when the key resolves; auth error when it does not.

## Security model

| Threat | Mitigation |
| --- | --- |
| Key in AI transcript | localhost callback → `0600` store; login stdout shows `key_prefix` only |
| Key in URL | URL carries code only; key over TLS on handoff/token |
| Captured code replay | PKCE verifier never leaves CLI; code is TTL-bounded |
| CSRF on callback | state = PKCE challenge; redeem requires verifier |
| Wrong Console page | CLI button only on `/xmemcli/<challenge>` |

Fixed port **9636** ("xmem" on phone keypad) allows SSH/devcontainer forwarding; security rests on PKCE, not port secrecy.

## Quota (observe vs escalate)

**`xmemcli quota`** observes usage freely. **Raising** limits requires human approval in the Console — the CLI must not self-grant quota increases.

---

# `xmemcli` — capabilities reference

**Version:** `0.0.8` (see `xmemcli version`)

`xmemcli` is the command-line client for the **xmemory HTTP API**. It is **human-governed for key acquisition**; an AI-assisted IDE may run reads, writes, and inventory once credentials exist. Humans acquire API keys and change quota limits in the **Console UI**.

```bash
xmemcli …   # installed CLI
```

---

## Commands

Every command below has dedicated help — see [Help](#help).

### Data

| Command | Description |
|---------|-------------|
| **`write`** `<text>` | Sync write (`POST …/write`). `--extraction fast\|deep` (default `fast`). `--no-wait` queues async write, returns `write_id`. |
| **`write-status`** `<write_id>` … | Poll async writes until terminal or `--timeout` (default 60s). Accepts multiple ids. |
| **`read`** `<query>` | Read from active instance. `--read-mode single\|raw\|xresponse`, `--scope TYPE:ID` (repeatable), `--scope-relations`. |

Requires **`--instance-id`** or **`$XMEM_INSTANCE_ID`** for read/write (or auto-pick when exactly one instance is visible — see [Global flags](#global-flags--environment)).

---

### Org inventory

Permission-filtered view of what this API key can see.

| Command | Description |
|---------|-------------|
| **`org list clusters`** | Clusters visible to this credential |
| **`org list instances`** | Instances visible to this credential |
| **`org list keys`** | API keys visible to this credential (metadata only; plaintext never returned) |

---

### Instances

| Command | Description |
|---------|-------------|
| **`instance get`** `<instance_id>` | Fetch one instance |
| **`instance create`** | Create from XMD/JSON schema. Required `--name`; schema via `--schema-file` or `--schema-stdin`. |
| **`instance instructions`** `[instance_id]` `[text]` `[--clear]` | Read, set or clear the instance's standing instructions to an agent — the owner's own words, carried to every agent that connects it. No text and no `--clear` reads and changes nothing. Setting reads the current value first and writes with the epoch it read, so an edit composed against instructions someone has since replaced is refused rather than applied (the console form and the instance chat write the same field). Clearing is `--clear`; an empty string is refused, because that is what a shell substitutes for an unset variable. The id may be pinned with `--instance-id` or `$XMEM_INSTANCE_ID` and the text given alone — a lone positional that is not an id is read as the text. |
| **`instance setup`** `[instance_id]` `[--format agent\|project]` | How to connect this instance to an agent, ordered for where it is likely to be used. Prints the same steps the `get_setup_instructions` MCP tool gives an agent, so a person and the agent beside them read the same thing. `--format project` additionally prints the shared setup files to commit; each teammate still approves the install and signs in once. Carries no credential. |

---

### Schema & XMD

XMD (xmemory Data) is the typed schema format for instances. These commands mirror the Console schema workflow (read/update/dry-run/migrations, LLM generate/enhance, and validation).

#### Command map

| User task | CLI command | Notes |
|----------|-------------|-------|
| Read live schema | **`schema get`** `[instance_id]` | Live schema for one instance. `-o` writes YAML. |
| Apply migration | **`schema update`** `[instance_id]` | `--schema-file`, optional `--migration-plan`, `--confirm-destructive`. |
| Preview migration | **`schema dry-run`** `[instance_id]` | Same flags as `schema update`; returns planned DDL without applying. |
| List migrations | **`schema migrations list`** `[instance_id]` | Newest first. `--limit`, `--before-id`, `--include-yaml`. |
| Fetch one migration | **`schema migrations get`** `[instance_id]` `<migration_id>` | Optional positional instance id; else `--instance-id` / `$XMEM_INSTANCE_ID`. `--include-yaml`. |
| Review suggestions | **`schema suggestions review`** `[instance_id]` | Suggestion engine: consolidated proposal from read-traffic gaps. |
| Decide suggestions | **`schema suggestions decide`** `[instance_id]` | `--proposal-version` (required) + `--accept`/`--reject`/`--defer`/`--file`. |
| Apply suggestions | **`schema suggestions apply`** `[instance_id]` | `--proposal-version` plus mandatory `--confirm-destructive`; preview removals in Console first. |
| Enhance bound schema | **`xmd enhance --from-instance`** `<description>` | Uses live schema; requires instance id. |
| Synthesize schema | **`xmd generate`** `<description>` | Cluster-scoped LLM synthesis. `-o` writes YAML. |
| Enhance from file | **`xmd enhance`** `[schema_file]` `<description>` | From a file, or `--from-instance` for bound enhance. `-o`, `--plan-output`. |
| Create instance | **`instance create`** | `--name`, `--schema-file` or `--schema-stdin`. |
| Validate schema | **`xmd validate`** / **`validate-yaml`** / **`validate-json`** | Cluster-scoped server validation. |
| Convert JSON Schema | **`xmd convert`** | JSON Schema → XMD YAML via the API (`validate_json_schema`). |

**Not exposed in CLI** (Console-only today): the suggestions before/after YAML **preview**.

#### Typical workflow

```text
# 1. Synthesize or enhance
xmemcli xmd generate "people and their pets" -o schema.yml
xmemcli xmd enhance schema.yml "add a Pet.breed field" -o next.yml --plan-output plan.json

# 2. Validate before create or update
xmemcli xmd validate next.yml

# 3. Create instance OR migrate existing
xmemcli instance create --name demo --schema-file schema.yml
xmemcli schema dry-run INST_ID --schema-file next.yml --migration-plan plan.json
xmemcli schema update INST_ID --schema-file next.yml --migration-plan plan.json --confirm-destructive

# 4. Inspect history
xmemcli schema migrations list INST_ID
xmemcli schema migrations get INST_ID MIGRATION_UUID

# 5. Suggestion engine (from real read traffic) — confirm with the user before decide/apply
xmemcli schema suggestions review INST_ID
xmemcli schema suggestions decide INST_ID --proposal-version PV --accept FP1 --accept FP2
xmemcli schema suggestions apply INST_ID --proposal-version NEXT_PV --confirm-destructive
```

#### Commands

| Command | Description |
|---------|-------------|
| **`schema get`** `[instance_id]` | Live XMD schema. Optional `-o` file. |
| **`schema update`** `[instance_id]` | Replace schema from `--schema-file`. Optional `--schema-type`, `--migration-plan`, `--confirm-destructive`. |
| **`schema dry-run`** `[instance_id]` | Preview migration (same schema/plan flags as update). |
| **`schema migrations list`** `[instance_id]` | Applied migrations, newest first. `--limit` (default 50), `--before-id`, `--include-yaml`. |
| **`schema migrations get`** `[instance_id]` `<migration_id>` | One record. Optional positional instance id; else global instance flags. `--include-yaml`. |
| **`schema suggestions review`** `[instance_id]` | Consolidated proposal from read-traffic gaps. Returns `proposal_version` + items. |
| **`schema suggestions decide`** `[instance_id]` | Record accept/reject/defer. Requires `--proposal-version` plus fingerprints or `--file`. |
| **`schema suggestions apply`** `[instance_id]` | Apply accepted items as one migration. Requires `--proposal-version` and `--confirm-destructive`. |
| **`xmd generate`** `<description>` | LLM-synthesize XMD. Optional `-o`. Requires cluster resolution. |
| **`xmd enhance`** `[schema_file]` `<description>` | LLM-augment schema from file, or **`--from-instance`** for live schema. `-o`, `--plan-output`. |
| **`xmd validate`** `<schema_file>` | Validate; YAML vs JSON inferred from `.json` extension. |
| **`xmd validate-yaml`** `<schema_file>` | Force YAML validation endpoint. |
| **`xmd validate-json`** `<schema_file>` | Force JSON Schema validation endpoint. |
| **`xmd convert`** `<json_schema_file>` | JSON Schema → XMD YAML via the API (`validate_json_schema`). Optional `-o`, `--root-object`. |

Instance id for `schema *` commands: positional `[instance_id]`, else **`--instance-id`** / **`$XMEM_INSTANCE_ID`**.

---

### Binding (local only — no network, no credential)

Which instances an agent working in **this directory** should know about, and how eagerly to
engage each one. Stored in `.xmemory.json`, discovered by walking **up** from `--binding-dir` /
`$XMEM_BINDING_DIR` (or the cwd), ceilinged at `$HOME` — the same rule `.xmemrc.json` has always
used, and **no git anywhere**. From a start outside `$HOME` the walk checks that directory and
stops, rather than climbing into a shared parent like `/work` or `/tmp` where another user's file
could be planted. A session-start hook passes the project root explicitly, so it never depends on
the walk at all.
`~/.xmemory.json` is consulted as the outermost scope whenever `$HOME` is the user's own rather than part of the tree being read. Where the session root *is* the home directory — a dotfiles repository, a devcontainer or an archive unpacked as `$HOME` — that file is treated as project scope like any other file inside the tree.

Unlike the rc — where the nearest file simply wins — every scope is **merged**, git-config style:
`~/.xmemory.json` supplies personal instances, a repository's committed `.xmemory.json` adds the
team's, and the nearer file wins **field by field** on any instance both mention.

| Command | Description |
|---------|-------------|
| **`binding list`** | Merged view for this directory. `--autoload` lists only what a session-start hook would pull. |
| **`binding add <id>`** | Bind an instance, or update the binding it already has. `--name`, `--purpose`, `--tier`, `--engage` (repeatable), `--scope`. |
| **`binding remove <id>`** | Unbind from **one** scope. To silence an instance inherited from a wider scope, bind it here with `--tier off` instead. |
| **`context`** | Session-start pack for the `autoload`-tiered bindings here. `--text` prints the pack alone, `--max-tokens`, `--no-live-state`, `--timeout`. The only one of these that needs a credential. |

**Tiers:** `autoload` (pull its context every session) · `available` (default; engage on demand) ·
`off` (bound but dormant).

**Scopes:** `--scope project` (default) writes the committable file — at an existing nearer
binding, else the git work-tree root **when git can say and the reader would actually look
there**, else the cwd. git only ever suggests: no git, or a directory that is not a checkout, is
an ordinary state and never blocks a write. The one refusal left is when the target would resolve
onto the home directory, which would write the user-scope file while calling it a project one.
`--scope user` always writes `~/.xmemory.json`.

`context` makes no request when nothing is tiered `autoload`, and resolves no credential
either — a hook running on every session start must not error in a project that was never
going to fetch anything. A server without the endpoint is treated as nothing to inject, so a
client ahead of its deployment degrades quietly instead of failing every session, as does a
binding this build cannot parse.

**`--timeout` bounds the whole command.** Not the request — *everything*: binding discovery,
the credential preflight, the git provenance lookup, name resolution, TLS, response headers and
body. It is a wall-clock limit, because it is the only bound a session-start hook has (POSIX
`sh` has no portable `timeout`) and a bound with an exception in it is not one. Expiry degrades
like every other failure: exit **0**, empty pack, one `warning:` line naming the budget.

`--text` prints the pack and nothing else, for a caller that will **wrap** it. Do not point a
hook at it directly: a hook's stdout is parsed as its control document on some events, so a
pack that happened to be valid JSON would be read as control fields rather than injected. A
companion editor-integration plugin wraps this output in the documented hook envelope its own
client expects; it ships from a separate repository and is not part of this one.

**No secrets.** An instance id is not a credential, so a *project* `.xmemory.json` is written
`0644` and is *meant* to be committed — the opposite of `.xmemrc.json` (`0600`, never
committed). `~/.xmemory.json` is written `0600`: it stays on one machine, and on a shared host
its instance names and purposes are nobody else's business.

**Scope precedence has one exception: your own entries are a ceiling.** A nearer scope normally
wins field by field, but a project file arrives by `git clone` and is the less trusted of the
two. So for any instance `~/.xmemory.json` lists, a committed file may make it **less** eager,
never more:

- **Tier.** Ranked `autoload` > `available` > `off`. A project may take your `autoload` down to
  `available` or `off`; it can never raise `off` to `available`, or `available` to `autoload`.
  **An omitted `tier` in your file means `available` and binds as one** — so `binding add --scope
  user <id>` with no `--tier` caps that instance at `available` everywhere. If you want a
  project's `autoload` to stand, say `--tier autoload` in your own file: your entry states the
  most eager you are willing to be, not merely that you know the id.
- **`engage`.** Replaced by a nearer scope for every other instance, but not for one of yours —
  otherwise a committed file could rewrite the cues attached to your own instance, which is a
  quieter version of raising its tier.

Everything else (`name`, `purpose`) still merges nearest-wins, and a project may always add
detail to an instance you listed.

**File format** (v1). `id` is required; everything else is optional. Unknown keys are rejected,
so a typo fails loudly rather than being ignored.

```json
{
  "version": 1,
  "instances": [
    {
      "id": "9c421cd4-77ab-4a51-a7e3-b8fd5d09d394",
      "name": "Team Knowledge",
      "purpose": "shared dev conventions",
      "tier": "autoload",
      "engage": ["a convention is learned or corrected"]
    }
  ]
}
```

---

### Auth & meta

| Command | Description |
|---------|-------------|
| **`auth login`** | PKCE via Console `/xmemcli/<challenge>` → `.xmemrc.json`. `--no-browser`, `--timeout`, `--console-url`. |
| **`auth logout`** | Remove active `.xmemrc.json` |
| **`auth status`** | Call `/whoami`. No key → exit 0; bad key → auth error; good key → email + prefix. |
| **`mcp <instance-id>`** | Serve one instance to an MCP client over stdio, using this CLI's credential. Not for humans — see below. |
| **`version`** | CLI release version (no network) |
| **`status`** | Local health: version + whether `.xmemrc.json` exists (no network) |

**`mcp` is a transport, not a command you run.** An MCP client starts it and speaks
JSON-RPC to it over stdio; it forwards each frame to `<mcp-url>/instance/<id>` with this
CLI's credential attached, and writes the answer back. Register it with
`claude mcp add <name> -- xmemcli mcp <instance-id>` (or the equivalent for another
client).

It exists because an MCP client can reference an environment variable in an
`Authorization` header but cannot read `.xmemrc.json`. Reading the credential per
connection means nothing is captured when the server is registered, so a configuration
written today still works in a session opened next week with an empty environment.

Two consequences worth knowing:

- **stdout is the protocol.** Alone among these commands it emits no JSON document and
  honours neither `--json` nor the exit-code table above; its exit code is a process
  status. Diagnostics go to stderr.
- **Signed out is reported, not fatal.** Every request is answered with a JSON-RPC error
  naming `auth login`, because a client that is told only "the server failed to start"
  gives the reader nothing to act on. Exit code and stage do not apply.

**Console `/xmemcli` routing:**

- **Onboarding** → silent onboarding-key handoff to the CLI (no overlay, no button click).
- **Post-onboarding** → API Keys create modal → “Use this key in the CLI”.

---

### Quota (read-only)

| Command | Description |
|---------|-------------|
| **`quota`** | Usage / limit / window start for the key's cluster (derived from instance → cluster). |

- **Default:** exit `0` when quota is readable; stderr **warning** when usage is high.
- **`--fail-if-under THRESHOLD`** — exit **7** when **remaining** quota is below that share of the limit (`0.1` or `10%`). Distinct from exit **6** (API quota exhausted). See `xmemcli help quota`.

Quota **increases** are Console-only — see [What `xmemcli` does not do](#what-xmemcli-does-not-do).

### Exit codes

| Code | Meaning |
|------|---------|
| **0** | Success |
| **2** | Usage error (bad flags, unknown `help` topic, missing required args) |
| **3** | HTTP / request failure — see [HTTP status mapping](#http-status--exit-code-and-json-stage) (includes permission denied, other API errors, and unwritable `-o` paths) |
| **4** | Auth error — invalid or missing API key (`401`; `stage: "auth"`) |
| **5** | Timeout |
| **6** | Quota exhausted (API quota-exceeded response; `stage: "quota"`) |
| **7** | Quota headroom below `--fail-if-under` |
| **130** | Interrupted (Ctrl+C) |

### HTTP status → exit code and JSON `stage`

`xmemcli` mirrors the API's **401 vs 403** distinction on the process exit code and on the machine-readable `stage` field. This is the single contract for **every** command that performs an HTTP call (read/write, `org list *`, schema/XMD, quota, `auth status`, …) — with one deliberate exception, below.

**`context` is exempt, by design** — from the release that introduces `context`, which is the
first one where this carve-out means anything. It is the one command nobody invokes: a
session-start hook runs it unattended, and a non-zero exit there costs the user their session
rather than their context. So **every** HTTP outcome — 401 and 403 included — exits **0** with an
empty context and an explanatory `warnings[]` entry. Use `auth status` to tell a credential
problem apart from an empty binding; `context` will not.

The exemption goes further than HTTP status. Any runtime failure inside `context` — a malformed
binding, an unreadable response shape, a timeout, a bug nobody anticipated — exits **0** with an
empty pack and a `warning:` line naming the cause. This is enforced in code rather than by
enumerating failure modes, so an unforeseen one degrades like the rest.

**And it is exempt from the one-JSON-document rule on stdout.** Every other command emits a JSON
error document in machine mode, including on usage errors. A piped, non-`--json` `context` whose
arguments fail to parse writes **zero bytes to stdout** and puts its reason on stderr instead,
because a hook discards stdout at exit **2** — so a JSON error document there is a session start
failing with no stated cause anywhere the user can see it. Usage and parse errors are the only
paths that still exit **2**; they are a mistake in the hook's own configuration, not a runtime
condition, and the hook author is the one reading stderr.

#### Quick reference

| API HTTP status | Shell exit code | JSON `stage` | Meaning |
|-----------------|-----------------|--------------|---------|
| **401** | **4** | `auth` | **Bad credential** — missing, invalid, expired, or inactive API key |
| **403** | **3** | `permission` | **Bad authorization** — key is valid but this key/role cannot perform the operation |
| **Other 4xx/5xx** | **3** | `request` | Request failed for another reason (404, 422, 5xx, …) |
| **402** (quota exhausted) | **6** | `quota` | Quota window exhausted — human must extend quota in Console |

#### How to interpret failures

1. **Exit 4 / `stage: "auth"` / HTTP 401** → fix the key: login again, rotate the key, check `$XMEM_API_KEY` / `.xmemrc.json`, confirm `--api-url` points at the environment that issued the key.
2. **Exit 3 / `stage: "permission"` / HTTP 403** → the key works, but the operation needs a broader API role (for example `data.write`, `instance.generate_schema`, `cluster.get_own`). Do **not** treat this as a wrong password.
3. **Exit 3 / `stage: "request"`** → other HTTP failure (instance not found, validation error, server error). Read the error message and HTTP status in the JSON body.

Some commands attach a more specific `stage` (`validate`, `usage`, `limit`, …) while still using exit **3** unless the row above applies. The `schema suggestions` commands add their own stages: `stale_proposal` (re-run review for a fresh `proposal_version`), `invalid_decision`, `dependency` (accept the dangling dependencies first), `not_initialised` (submit a write first), and `apply`; `review` reports an `evolution_in_progress` condition as a successful status with exit 0.

**Envelope errors** (HTTP **200** with non-empty `errors[]`) are not HTTP 401/403; they typically exit **3** with `stage: "request"`.

**Breaking change in 0.0.5:** HTTP **403** previously exited **4** (`auth`); it now exits **3** (`permission`). Scripts that treated exit **4** as “any auth-layer failure” must check `stage` or handle exit **3** for permission denials.

See also [`ACCOUNTS_AUTH.md`](../ACCOUNTS_AUTH.md) for the server-side 401/403/404 rules.

---

## Help

`xmemcli` supports root `-h` / `--help` (same overview as bare `xmemcli`) and the **`help`** subcommand for nested topics.

| Invocation | What you get |
|------------|--------------|
| **`xmemcli`** | Full command overview (grouped list of every capability) |
| **`xmemcli help`** | Same as bare `xmemcli` |
| **`xmemcli help options`** | Global flags (`--api-url`, `--api-key`, `--json`, …) |
| **`xmemcli help <topic>`** | Usage, options, and subcommands for that topic |
| **`xmemcli <cmd> … -h`** / **`--help`** | Same as `help <topic>` for that command path |

Unknown help topics exit **2** (same as other usage errors).

**Every command in this document has help.** Examples:

```text
xmemcli help write
xmemcli help write-status
xmemcli help read
xmemcli help org
xmemcli help org list instances
xmemcli help instance create
xmemcli help schema
xmemcli help schema get
xmemcli help schema update
xmemcli help schema dry-run
xmemcli help schema migrations
xmemcli help schema migrations list
xmemcli help schema migrations get
xmemcli help schema suggestions
xmemcli help schema suggestions review
xmemcli help schema suggestions decide
xmemcli help schema suggestions apply
xmemcli help xmd
xmemcli help xmd generate
xmemcli help xmd enhance
xmemcli help xmd validate
xmemcli help xmd validate-yaml
xmemcli help xmd validate-json
xmemcli help xmd convert
xmemcli help auth login
xmemcli help quota
xmemcli help options
```

Nested topics work at any level that exists in the parser (`help org`, `help org list`, `help org list keys`, …). Unknown topics print a short error and suggest `xmemcli` or `help options`.

---

## What `xmemcli` does **not** do

| Area | Use the Console instead |
|------|-------------------------|
| **Quota increases** | No `quota request-increase`. Observe with `xmemcli quota`; **raise limits in Billing / Quotas UX**. |
| **Routine API key creation** | Post-onboarding: API Keys UI (CLI opens that flow via `/xmemcli`). |
| **Billing & plans** | Console only |
| **Users, roles, org admin** | Console only |
| **Instance chat / trace inspection** | Console only |
| **Cluster create/delete** | CLI lists clusters; provisioning in Console |
| **`read --extraction deep`** | Server has no read-depth knob today |
| **Raw REST proxy** | Curated response fields only |
| **Instance deletion** | **Human operators only** — a hidden `instance delete` exists for interactive TTY use (type `yes` to confirm). It is omitted from help and must not be used by agents or automation. Console UI remains the primary human path. |

On HTTP **402** (quota exhausted), stop and ask a human to extend quota in the Console.

---

## Global flags & environment

These apply **before** any subcommand (`xmemcli help options`).

| Flag | Env var | Purpose |
|------|---------|---------|
| `--api-url` | `XMEM_API_URL` | API origin (default `https://api.xmemory.ai`) |
| `--api-key` | `XMEM_API_KEY` | Bearer API key |
| `--instance-id` | `XMEM_INSTANCE_ID` | Default instance for read/write and cluster derivation |
| `--rc-dir` | `XMEM_RC_DIR` | Where `auth login` writes `.xmemrc.json`; reads walk **up** toward `$HOME` |
| `--binding-dir` | `XMEM_BINDING_DIR` | Where `binding` commands look for `.xmemory.json`; reads walk **up** toward `$HOME` and **merge** every scope |
| `--json` | — | Force one JSON document on stdout |
| `--verbose` | — | Add `trace_id` / `console_url` when present (never SQL, diff plans, or internals) |

**Credential resolution:** `--api-key` → `$XMEM_API_KEY` → nearest `.xmemrc.json` → *Not logged in — run `xmemcli auth login` first.*

**`context` is the one exception, and it is a security boundary.** Every other command walks up
from the current directory for the nearest `.xmemrc.json`, which is deliberate: a person chose
that directory and ran the command in it. `context` has neither — a session-start hook runs it
unattended, in whatever tree the editor happened to open — so it resolves the credential from
**`$HOME` only**, and consults a project `.xmemrc.json` only when the caller named that source
explicitly with `--api-key` / `$XMEM_API_KEY` or `--rc-dir` / `$XMEM_RC_DIR`. Without the pin, a
cloned repository could ship a key *and* an origin and have both used automatically. This is a
rule rather than a detector: earlier versions tried to *detect* a checkout-supplied credential
and each delivery mechanism turned out to be a fresh bypass.

**Origin resolution:** `--api-url` → `$XMEM_API_URL` → rc `api_url` → default — **with one escape hatch**: when the key comes from `--api-key` / `$XMEM_API_KEY` (not from the rc), the rc's `api_url` is **not** consulted and the origin falls back to the built-in default (`https://api.xmemory.ai`) unless you also set `--api-url` / `$XMEM_API_URL`. That keeps an explicitly supplied key from being silently paired with an unrelated origin in a project `.xmemrc.json`. If `$XMEM_API_KEY` is set without `$XMEM_API_URL`, the CLI warns once per invocation.

**Instance resolution (read/write):** `--instance-id` → `$XMEM_INSTANCE_ID` → if exactly **one** instance is visible, auto-select with a **stderr warning** → else error.

**Output:** Pipes and non-TTY stdout → JSON. Interactive TTY → one-line summaries unless `--json`.
