Metadata-Version: 2.4
Name: xmemcli
Version: 0.0.2
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
```

Global flags / env: `--api-key` / `$XMEM_API_KEY`, `--instance-id` / `$XMEM_INSTANCE_ID`, `--api-url` / `$XMEM_API_URL`, `--rc-dir` / `$XMEM_RC_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.

## 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. `--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.

```bash
uv tool install xmemcli
# or
pip install xmemcli
```

Then:

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

Version: **0.0.2**.


---

# `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. Explicit key + mismatched rc origin is rejected (localhost-key-at-prod guard).

## 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.2` (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 |
| **`instance list`** | Alias for **`org list instances`** |
| **`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`. |

**Operator-only (intentionally omitted from help and this table):** `instance delete` exists for humans at an interactive TTY (type `yes` to confirm) but is **not advertised** in primary CLI docs yet. Automation should use `DELETE /instances/{id}` over HTTP.

---

### 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`** `<migration_id>` | Instance from `--instance-id` / `$XMEM_INSTANCE_ID`. `--include-yaml`. |
| 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 / suggestion-engine only today): pending schema suggestions review/apply.

#### 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 MIGRATION_UUID
```

#### 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`** `<migration_id>` | One record; instance from global instance flags. `--include-yaml`. |
| **`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`** (except `migrations get`, which takes only `migration_id`).

---

### 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. |
| **`version`** | CLI release version (no network) |
| **`status`** | Local health: version + whether `.xmemrc.json` exists (no network) |

**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 non-zero when **remaining** quota is below that share of the limit (`0.1` or `10%`). See `xmemcli help quota`.

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

---

## 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 |

**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 list
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 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`.

---

## Command aliases

Canonical names appear in `xmemcli` and in help. **Aliases are accepted on the command line but never listed in the overview** — use them in scripts if you already have them; prefer canonical names in new work.

| Canonical command | Accepted aliases |
|-------------------|------------------|
| **`write-status`** | `write_status`, `writestatus`, `async_write_status`, `asyncwritestatus`, `async-write-status` |
| **`quota`** | `quota get` |

**Help topic aliases** (same targets, for `xmemcli help …` only):

| `help` topic you type | Resolves to |
|-----------------------|-------------|
| `login` | `auth login` |
| `logout` | `auth logout` |
| `write-status`, `write_status`, `writestatus`, `async_write_status`, `asyncwritestatus`, `async-write-status` | `write-status` |
| `quota get`, `quota-get` | `quota` |

---

## 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, trial paywall** | 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 delete` (advertised)** | Implemented for human operators at a TTY (type `yes`); intentionally **omitted from help and this doc's command table** until product is ready to advertise it. Automation should use `DELETE /instances/{id}` over HTTP. |

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` |
| `--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.*

**Origin resolution:** `--api-url` → `$XMEM_API_URL` → rc `api_url` → default.

**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`.
