# CLI

> xmemcli command-line client and the agent skill.

Canonical page: https://xmemory.ai/cli/

`xmemcli` creates memory instances, reads and writes data, and manages access from the terminal. For an agent that calls memory tools through a connector, see [MCP](https://xmemory.ai/mcp/).

## Install

Install it as a persistent tool (recommended for regular use — the examples below call `xmemcli` directly):

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

Or run it with no install — handy for a quick try, CI, or letting an agent invoke it — via [uv](https://docs.astral.sh/uv/)'s `uvx` (prefix any command with `uvx`):

```bash
uvx xmemcli help
```

---

## Authenticate

Sign in through your browser to save a key in `.xmemrc.json`:

```bash
xmemcli auth login       # opens the browser; --no-browser for headless
xmemcli auth status
```

For a terminal without a browser, sign in by email. Open the approval link within ten minutes:

```bash
xmemcli auth login --rc-dir "$HOME" --email <your-email>
```

`--rc-dir "$HOME"` writes the key to `~/.xmemrc.json` wherever you run it; without it, `auth login`
writes `.xmemrc.json` into the current directory. The home file is the only one the xmemory
plugin's session-start hook reads, in Claude Code and in Codex.

Alternatively, create an API key in the [Console](https://console.xmemory.ai). Prefer keeping it in
a `.xmemrc.json` (which `auth login` writes for you) over the environment — a `$XMEM_API_KEY` env
var also works and is handy for CI. `xmemcli` resolves credentials `--api-key` → `$XMEM_API_KEY` →
the nearest `.xmemrc.json` (walking up from the current directory). Add `.xmemrc.json` to
`.gitignore` — it holds secrets.

---

## Try a first write and read

Create an instance with a ready-made contacts schema:

```bash
xmemcli instance create --name contacts --template personal_crm
```

If the CLI asks which cluster to use, run `xmemcli org list clusters`, set `XMEM_CLUSTER_ID` to the target cluster UUID in your environment, and repeat the create command.

Copy the instance UUID from the result, then run:

```bash
export XMEM_INSTANCE_ID="<instance UUID>"
xmemcli write "Anna Petrova lives in Lisbon."
xmemcli read "Where does Anna Petrova live?"
```

The answer should be Lisbon. The synchronous write finishes before the read runs.

To share this instance with a teammate or an application, see [Manage access](#manage-access).

## Onboard: create an instance from a description

For a custom schema, you can author [XMD](https://xmemory.ai/xmd/) directly and pass
the validated file to `instance create`. For an easier description-first path, give the
`xmemory-instance-creation` skill a plain-language account of what to remember and the questions
you expect to ask; it handles generation, validation, approval, and creation.

Using the CLI directly, describe the domain, let `xmemcli` synthesize XMD, validate it, then create
the instance:

```bash
xmemcli xmd generate "Track contacts with name, email, company, and notes." -o schema.yml
xmemcli xmd validate schema.yml
xmemcli instance create --name contacts --description "People we talk to" --schema-file schema.yml
# → save the returned UUID:
export XMEM_INSTANCE_ID="<uuid from output>"
```

See the [XMD schema format](https://xmemory.ai/xmd/) for the complete object, field, enum, key, relation, and
description reference before reviewing or deliberately editing `schema.yml`. Note that
`instance create --description` is instance metadata; the generation prompt belongs to
`xmd generate`.

List the memory stores available to you any time:

```bash
xmemcli org list instances
```

---

## Add the agent skill (optional)

`xmemcli` ships an **agent skill** that teaches AI coding agents to use xmemory. Install it into your
agents (Claude Code, Cursor, Codex, Gemini CLI, and more) with the [`skills`](https://github.com/vercel-labs/skills)
installer:

```bash
npx skills add xmemory-ai/xmemory-skill
```

The agent then uses xmemory on its own — listing available instances, checking what's already
stored before redoing work, and writing down what it learns for next time.

---

## Connect an agent to an instance

Creating an instance does not connect anything to it. `instance setup` prints how to connect this
one, ordered by where it is likely to be used:

```bash
xmemcli instance setup "$XMEM_INSTANCE_ID"
```

The instance id is optional — it falls back to `--instance-id` or `XMEM_INSTANCE_ID`. The steps are
computed from the instance's current settings, so they keep up as it changes, and they carry **no
credential**: each connection signs in separately.

`instance create` already returns these instructions alongside the new id, so the common path needs
no second call.

For a whole team, `--format project` additionally prints the shared setup files to commit once.
Each teammate still approves the install and signs in themselves:

```bash
xmemcli instance setup "$XMEM_INSTANCE_ID" --format project
```

### Serve one instance to an MCP client

`xmemcli mcp` is a stdio transport, and it **arrived in 0.0.7**. An MCP client starts it, and it
forwards each frame to that instance with the credential read from `.xmemrc.json` **per
connection**. Nothing is captured when the entry is registered, so a client configured today still
works in a session opened next week on a machine whose environment carries nothing:

```bash
claude mcp add xmemory-<FIRST8> -- xmemcli mcp <INSTANCE_ID>
codex mcp add xmemory-<FIRST8> -- xmemcli mcp <INSTANCE_ID>
```

Name each entry `xmemory-` plus the first eight characters of the instance id — what
`instance setup` prints for it. Two instances registered under one name leave one entry, the
second having quietly replaced the first.

Check the client before registering, because an older one accepts the command and then cannot run
it, leaving a server that fails to start:

```bash
xmemcli --json status                    # reports `version` and `authenticated`, contacts nothing
uv tool install --upgrade xmemcli        # if version is below 0.0.7
```

Signed out, the client is told which command fixes it rather than being left with a server that
failed to start for no stated reason.

---

## Standing instructions for an instance

An instance can carry **standing instructions**: the owner's own words about how agents should use
that memory. They are authoritative rather than advisory — rendered verbatim wherever they are
shown — and they reach every agent that connects the instance.

Reading is the default, so it is always safe to look:

```bash
xmemcli instance instructions "$XMEM_INSTANCE_ID"
```

Set them by passing the text, and remove them with `--clear`:

```bash
xmemcli instance instructions "$XMEM_INSTANCE_ID" "Prefer short answers. Always cite the record you used."
xmemcli instance instructions "$XMEM_INSTANCE_ID" --clear
```

The id is optional — pin it with `--instance-id` or `$XMEM_INSTANCE_ID` and give the text alone.
Clearing is its own flag rather than an empty string, because `""` is what a shell substitutes for
a variable that was never set, and that should not delete a standing rule.

The same field is editable from the console and from the instance chat, so a write composed
against text someone has since replaced is refused rather than applied. Read them again and
reapply; retrying would overwrite whatever the other editor just wrote.

`instance instructions` arrived in **0.0.8**.

---

## Bind instances to a project

A **binding** records which instances an agent working in this directory should know about, and how
eagerly to engage each one. It is local bookkeeping — no network, no credential — and it grants no
access by itself.

```bash
xmemcli binding add "$XMEM_INSTANCE_ID" --tier autoload --purpose "Team decisions"
xmemcli binding list
xmemcli binding remove "$XMEM_INSTANCE_ID"
```

Three tiers: `autoload` pulls that instance's context into every session, `available` (the default)
engages on demand, and `off` keeps the binding dormant.

Bindings live in `.xmemory.json`, found by walking up from the working directory. Scopes **merge**,
git-config style: `~/.xmemory.json` supplies your personal instances, a repository's committed
`.xmemory.json` adds the team's, and the nearer file wins field by field. `--scope user` writes the
personal file; the default writes the committable one.

**`.xmemory.json` holds no secrets and is meant to be committed** — an instance id is an identifier,
not a credential. A teammate who opens a session there fetches those instances with *their* own
credential, so they see only what their access already reaches. `.xmemrc.json` sits in the same
directory and holds a plaintext API key; that one is never committed.

To see what a session-start hook would inject for the `autoload` bindings here:

```bash
xmemcli context --text
```

This is the only binding command that needs a credential. Where nothing is tiered `autoload`, it
makes no request at all.

---

## Read and write

`write` and `read` act on the **active instance** — the `XMEM_INSTANCE_ID` you exported above (they take no instance argument, unlike control-plane commands such as `schema`/`instance`, which name the instance explicitly).

```bash
xmemcli write "Alice Johnson works at Acme Corp. Her email is alice@acme.com."
xmemcli read "What is Alice's email?"
xmemcli read --related-types "Which courses require an English test?"   # + what else the read could ask about
xmemcli read --related-types-depth 2 "Which courses require an English test?"   # follow the relations two levels out

# bulk / non-blocking:
xmemcli write --no-wait "..."      # returns a write_id
xmemcli write-status <write_id>
```

Writes take plain language — xmemory maps the text onto the instance's schema.

`read --related-types` also returns what else the memory could answer about — the object types the read touched, the fields it did not return, and the types a declared relation links them to ([shape](https://xmemory.ai/api/#related-types)). Pretty mode prints one line per touched type under the answer; `--json` carries the full `related_types` object. `--related-types-depth N` (1 to 3) follows the relations N levels out and implies `--related-types`; pretty mode then also lists each reached type with its distance, nearest first ([shape](https://xmemory.ai/api/#following-relations-further)). The API key needs `instance.get`, the permission `schema` needs.

`write` and `write-status` print what the write changed, one indented line per change under the status line — created, updated (old → new per field), deleted — capped at 50 lines. A bulk change prints as one line (`deleted 3 × Ticket where status='open'`), a refused one says why (`not deleted Ticket: refused — <reason>`), and advisory `note:` lines follow. `--json` returns the server's `changes` block verbatim. With `--no-wait`, `write` returns only the `write_id`; `write-status` reports the changes once the write completes. Requires `xmemcli` 1.4.0.

```text
write w1 ok · extracted: Person(name='Bob')
  updated Person name='Bob': city: 'Paris' → 'Rome'
  deleted Person name='Carl'
```

**Structured writes** skip extraction and apply exact changes you name ([shape](https://xmemory.ai/api/#structured-writes)). They require `xmemcli` 1.4.0, and a deployment can have them turned off.

```bash
xmemcli write --mutations-file changes.json     # a JSON array, the API's structured_mutations
xmemcli write --mutations-stdin < changes.json
xmemcli write --delete Person:name=Carl --delete Ticket:<xuid>   # delete by key or xuid, repeatable
```

A write takes either text or mutations, not both. Structured writes refuse `--scope` and `--extraction deep`, and their output has no `extracted` list. Empty or whitespace-only text is refused (exit 2). Files and stdin are read as UTF-8; a byte-order mark is accepted.

**Scoped writes** confine a text write to named records ([rules](https://xmemory.ai/api/#scoped-writes)). `--scope TYPE:ID` is repeatable; the ID is an xuid or a key such as `name=Ada`. Only the scoped records may be updated or deleted. By default new records and links to them are allowed, and a write that would change anything else fails and changes nothing.

```bash
xmemcli write --scope Ticket:code=T-42 "T-42 is resolved."
xmemcli write --scope Ticket:code=T-42 --scope-mode drop "T-42 is resolved; so is T-43."
```

`--scope-mode drop` (needs `--scope`) applies the in-scope changes and skips the rest instead of failing. Each skipped operation prints as a `skipped_out_of_scope` line with its type, fields and `count=N`; the record's key appears only when the scope named it ([report](https://xmemory.ai/api/#what-a-drop-mode-write-skipped)). In drop mode a write creates only records a `--scope` names by primary key, so you can scope a record that is not stored yet. `--scope-mode` applies to text writes only. A server that predates drop mode refuses it (exit 3). Requires `xmemcli` 1.5.0.

**Mergeable text fields** combine a text write's value with the stored text instead of replacing it ([XMD `merge`](https://xmemory.ai/xmd/#mergeable-text-fields)). Each contradiction such a merge resolved prints as a `note:` line under the changes, within the same 50-line cap; `--json` carries them as `changes.merge_contradictions` ([shape](https://xmemory.ai/api/#mergeable-text-fields)). Requires `xmemcli` 1.9.3 or later.

---

## Manage access

Use `xmemcli org manage RESOURCE ACTION` to administer [roles and access](https://xmemory.ai/roles-and-access/). For a user session, set `XMEM_CONSOLE_URL` to your Console origin and supply `--email`. Each command requests approval and keeps its session in memory. Use `auth login` when you want a reusable key in your CLI configuration. Email login uses the organisation’s configured default API role.

```bash
export XMEM_CONSOLE_URL=https://console.xmemory.ai
xmemcli org manage roles list --email "$ADMIN_EMAIL"
xmemcli org manage assignments list --subject-kind api_key --subject-id "$KEY_ID" --email "$ADMIN_EMAIL"
```

To give that key write access to Sandbox, copy the returned revision and prepare the grant in [the assignment request example](https://xmemory.ai/api/#edit-an-assignment). Apply it, then list the subject’s assignments again to verify the role and instance UUIDs.

```bash
xmemcli org manage assignments apply --body assignments.json --email "$ADMIN_EMAIL"
xmemcli org manage assignments list --subject-kind api_key --subject-id "$KEY_ID" --email "$ADMIN_EMAIL"
```

To withdraw just the Sandbox grant, prepare [the revocation request](https://xmemory.ai/api/#remove-write-access-to-sandbox) and run `xmemcli org manage assignments apply --body revoke-writer.json --email "$ADMIN_EMAIL"`. List the assignments again to confirm the organisation-wide reader role is still assigned.

Use `--as-key` to act with the configured key’s grants. For example, inspect visible keys or issue a child key for one cluster. Supply the role UUID when its name is ambiguous. The issuing key needs `api_key.create` and authority to delegate that role on the cluster. The secret goes to a new owner-only file.

```bash
xmemcli org manage keys list --as-key
xmemcli org key "$KEY_PREFIX"
xmemcli org create key --name sandbox-agent --role "$ROLE_ID" --cluster "$CLUSTER_ID" --out ./sandbox-agent.key
```

| Resource | Actions |
| --- | --- |
| `permissions`, `roles` | `permissions list`. For roles, `list`, `get`, `create`, `update`, `delete`. |
| `assignments`, `memberships` | `list`, `apply`. Apply sends a revision-checked batch. |
| `keys` | `list`, `get`, `create`, `rename`, `activate`, `deactivate`. Use `list --all-users` for authorised organisation-wide inventory. |
| `invitations` | `list`, `create`, `resend`, `revoke`, `preview`, `accept`. Acceptance requires a verified user session. |
| `users` | `list`, `get`, `activate`, `deactivate`. To add a teammate, use `invitations create`. |
| `instances`, `clusters` | List either resource. Instances also support `get` and `update`. |
| `default-api-role`, `role-names`, `capabilities` | Use `default-api-role get` to see the onboarding role, list or apply role renames, or use `capabilities get --body request.json` to check a proposed operation. |

Use `--id UUID` for a single resource and `--body FILE` for a request body. Key creation and invitation creation or resend require `--out NEW_FILE`. Supply invitation tokens in the preview or acceptance body. Resending invalidates the previous token.

### Change cluster membership

Adding an instance to a cluster makes it available to that cluster’s assignees. The editor needs `instance.manage_clusters` and metadata access on both the instance and cluster. An instance’s billing cluster must be a current member. To remove the billing cluster, first use `org manage instances update` with the current `name` and `description` and the new member’s `billing_cluster_id`.

To add a membership, run `xmemcli org memberships list --instance-id "$INSTANCE_ID" --as-key`, then `xmemcli org memberships edit --expected-revision "$REVISION" --add "$INSTANCE_ID" "$CLUSTER_ID" --as-key`. A conflict requires a fresh list and review. After a lost response, read back the memberships before submitting another edit.

## Evolve the schema

There are two paths. Both end in a versioned migration — see the
[schema evolution](https://xmemory.ai/schema-evolution/) post for the product story.

### Suggestion engine from read traffic

When agents ask questions the schema cannot answer, those misses become signal.
xmemory consolidates recurring gaps into a proposal: concrete ops (add a field,
introduce an object, wire a relation), each with a fingerprint, evidence
queries, and a `proposal_version` token. Until recently that loop lived in the
Console and MCP; from **xmemcli 0.0.6** it is also a CLI path:
`schema suggestions review` → `decide` → `apply`.

**When to use it.** Prefer this path when `read` responses show a non-zero
`pending_suggestions` count, or when you know agents keep asking for fields the
schema does not hold. In pretty mode that count also prints as a one-line hint
on single-answer reads (for example
`(2 pending schema suggestion(s) — xmemcli schema suggestions review)`);
structured / raw / xresponse reads still carry the count in JSON only. Prefer
hand-driven redesign (below) when you want to describe a change yourself in
plain language.

**Review** is read-only — it fetches the current consolidated proposal without
changing the schema:

```bash
xmemcli schema suggestions review "$XMEM_INSTANCE_ID"
# optional: --session-id <id>  (forwarded on review, decide, and apply for tracing)
```

Curated output includes each item's fingerprint, a short `op_summary` (for
example `add_field Task due_date`), frequency, rationale, sample queries, and
`apply_blocked` (shown as `· can't apply`). Do not `--accept` a blocked item:
it cannot be applied as proposed, its rationale says why, and accepting it
fails the whole apply.
Copy the `proposal_version` from this response and pass it to decide.
After decide, apply with `next_proposal_version` from the decide response
(not the review token). If the engine is busy, review returns
`status: evolution_in_progress` with exit 0 (and often `retry_after_seconds`);
wait and review again — that is a status, not an error stage.

**Decide** records accept / reject / defer for items in that proposal. Always
pass `--proposal-version` from the review you just ran. There is no silent
version swap: if the server has moved on, you get a clear stale-version error
(`stage: stale_proposal`) and re-review.

```bash
xmemcli schema suggestions decide "$XMEM_INSTANCE_ID" \
  --proposal-version "<from review>" \
  --accept "<fingerprint>" \
  --reject "<fingerprint>"
```

Pass exactly one input mode per invocation: the repeatable
`--accept` / `--reject` / `--defer` flags, **or** a JSON decisions file via
`--file` (`[{item_fingerprint, decision}, ...]` or `{decisions: [...]}`).
Do not combine `--file` with the fingerprint flags. Conflicting decisions for
the same fingerprint are a usage error.

Other suggestion-specific failure stages to watch for: `invalid_decision`
(bad fingerprint or decision), `dependency` (accept the dangling dependencies
first), `not_initialised` (write once to initialize the instance), and `apply`
(apply-time failure).

**Apply** commits the accepted items as a single versioned migration. After
decide, pass `next_proposal_version` from the decide response (not the review
token). You can apply with the review `proposal_version` only when you skip
decide and the proposal is already decided. `--confirm-destructive` is required
(preview removals in the Console first if the proposal may drop data):

```bash
xmemcli schema suggestions apply "$XMEM_INSTANCE_ID" \
  --proposal-version "<next_proposal_version from decide>" \
  --confirm-destructive
```

End-to-end sketch:

```bash
# 1. Notice pending work (optional — also on read responses)
xmemcli read "What is the due date for task X?"

# 2. Review the proposal
xmemcli schema suggestions review "$XMEM_INSTANCE_ID"
# → note proposal_version and fingerprints

# 3. Decide with a human
xmemcli schema suggestions decide "$XMEM_INSTANCE_ID" \
  --proposal-version "<from review>" \
  --accept "<fingerprint>"

# 4. Apply
xmemcli schema suggestions apply "$XMEM_INSTANCE_ID" \
  --proposal-version "<next_proposal_version from decide>" \
  --confirm-destructive
```

**Boundaries.** Before/after YAML **preview** for a proposal remains
Console-only (API-key callers cannot use `/suggestions/preview`). Hand-driven
schema work stays on the commands below. Full help: `xmemcli help`,
`xmemcli help schema`, and `xmemcli help schema suggestions`.

### Hand-driven redesign

When you describe a change yourself (not traffic-driven gaps):

```bash
xmemcli schema get "$XMEM_INSTANCE_ID" -o schema.yml
xmemcli xmd enhance schema.yml "Add a Contact.phone field." -o schema-v2.yml
xmemcli xmd validate schema-v2.yml
xmemcli schema dry-run "$XMEM_INSTANCE_ID" --schema-file schema-v2.yml   # preview the migration
xmemcli schema update "$XMEM_INSTANCE_ID" --schema-file schema-v2.yml    # apply it
```

`xmemcli help` and `xmemcli help <topic>` document every command.
