# AI Memory

Create one store for your app (no kind needed). It holds, for each of your end users: conversation threads (append turns, read the last N back to build the next prompt), memory records (short facts like "is vegan", found later by meaning) and key-value data with a TTL (carts, settings, flags).

Every call names the end user with `userId` (1–64 characters: letters, digits and . _ - : @ + =, so a user id or an email address fits as-is). It is required: a call without it is a 400 `user_id_required`, never a read of one shared pool that mixes every user. For app-wide data use a fixed id such as "app". `user_id` and the older `scope` are accepted as the same thing. It is the same word Vector DB uses: there `userId` is the namespace a vector belongs to, so one id names a user across both.

AI Memory is your app's memory of its users. It is not the business memory, and not a project's context. Visitor chat with an agent cannot reach it.

## In plain words

Lets the AI in your app remember: facts about each person, the conversation so far, and notes it can look up later by meaning.

For example: A cooking assistant remembers that someone is vegetarian the next time they ask for a recipe.

## A chat app in four calls

**REST from your server**

```js
const base = 'https://harakumo.com/api/memory/' + storeId;
const headers = { authorization: 'Bearer ' + process.env.HARAKUMO_API_KEY, 'content-type': 'application/json' };
const post = (path, body) => fetch(base + path, { method: 'POST', headers, body: JSON.stringify(body) }).then(r => r.json());

// 1. After each turn, save it to this user's thread
await post('/messages', { userId, threadId, messages: [{ role: 'user', content: text }, { role: 'assistant', content: reply }] });

// 2. Save what you learned about them (the same fact twice is one memory)
await post('/memories', { userId, text: 'Is vegan' });

// 3. Before replying, recall what matters
const { memories } = await post('/memories/search', { userId, query: text, topK: 5 });

// 4. Forget them on request: threads, memories and keys
await fetch(base + '/users/' + encodeURIComponent(userId), { method: 'DELETE', headers });
```

## Memory records

- `POST /memories { userId, text, metadata?, ttlSeconds? }` answers 201 with the record `{ id, text, user_id, metadata, created_at, updated_at, expires_at }` and `indexed`. `memory` is accepted for `text`.
- The same text for the same user, ignoring case and spacing, is the same record: sent again it answers 200 with `duplicate: true`, and nothing is written or charged. So an app can send what it learned every turn.
- `text` is at most 2,000 characters (400 `input_too_long`: split it). `metadata` is up to 16 fields of short text, numbers, booleans or null.
- `PATCH /memories/:memoryId` corrects one: `metadata` is replaced whole and a new `text` is embedded again. An id comes from its text, so new text gives the memory a new id: use the `id` in the answer from then on (`previous_id` is the old one); 409 `already_exists` when the user already has that text. `DELETE /memories/:memoryId?userId=` removes it from search, then from the store.
- A record that could not be indexed (credits, the AI Gateway switched off) is still stored, with `indexed: false` and a note; PATCH it with its text to retry.

## Threads

- `threadId` keeps a user's separate conversations apart; without it a call uses the user's default thread.
- `POST /messages` takes `{ role, content }` or `{ messages: [...] }` with 1–100 messages, all checked before any is written, for one call.
- Each thread keeps its 1,000 most recent messages; one read returns up to 500. `DELETE /messages?userId=` without `threadId` removes every thread of that user.

## Keys with TTL

- `PUT /keys/:key { userId, value, ttlSeconds? }` stores any JSON up to 1 MB under a key of up to 512 characters, for one user. A store's `ttlSeconds` is the default expiry; a key's own overrides it.
- Keys may not start with `msg:`, `msg@` or `mem:` (400 `reserved_key`): that is where the store keeps threads and records.

## Paging and listing

- Lists answer one page and `nextCursor`: send it back as `cursor` for the next page; it is null on the last. `GET /memories?userId=&limit=` (1–100, default 20), `GET /users` (every user the store holds anything for), `GET /api/memory/:id?userId=&limit=` (the store and its keys).
- A store answers `kind`, `searchable` (whether search works), `user_id_required` (true on kind "memory"), `quota`, `item_count`, `size_bytes`, `ttl_seconds`, `created_at` and `edge_fallback` (an older key-value store still reading some values from before they moved). Creating a searchable store and deleting a store each spend one call of the data allowance. Deleting a store whose search index cannot be removed answers 502 and keeps the store: try again.

## Freshness

- A new memory becomes searchable by meaning about a minute after it is saved. A search answers `pending`, how many of the user's memories were saved in the last two minutes, and says so when that is why it found nothing.

## Limits

- Values up to 1 MB, a conversation message up to 100 KB (413), keys up to 512 characters, memory text up to 2,000 characters.
- Search returns at most 50 results; one store can search for up to 50,000 different users.
- Each plan caps items per store, and the bytes of every store together: on Hobby per workspace, on a paid plan across the workspaces it covers. Every kind of store counts (hobby: 10,000 items per store, 25 MB in all per workspace; indie: 10,000 items per store, 50 MB in all per workspace; pro: 100,000 items per store, 250 MB in all shared by the workspaces it covers; team: 250,000 items per store, 500 MB in all shared by the workspaces it covers; scale: 1,000,000 items per store, 1 GB in all shared by the workspaces it covers); a write past the cap gets a 402 naming it. Expired values are removed nightly.
- Saving a memory or searching embeds text on AI credits, and shares the plan's per-minute embeddings rate limit (429 `ai_rate_limited`). A read-only key can search, not write.
- Every memory call spends from the workspace's data allowance of 600 calls per 5 minutes, shared with databases, vectors and video status checks: reading, writing or deleting a key-value value, appending to, reading or forgetting a conversation, listing keys and a flush are one call each, and so is a semantic write, delete or search. A batch of up to 100 messages is one call, and so is each memory saved, read, changed, deleted or searched. Past it, 429 `rate_limited` (`limit_name: workspace_data_plane`) with Retry-After, and nothing runs. Calls that reach the search index also count toward the platform ceiling all workspaces share. Forgetting a user removes up to 1,000 memories per call and answers `partial: true` until it is done; call it again.
- Keys: a key limited to the project works for everything here; a read-only key can read and search but not write.

## Errors

Every refusal is `{ error, code, param? }`; `param` names the field at fault.

| Code | Status | When |
| --- | --- | --- |
| user_id_required | 400 | A call on a store of kind "memory" named no user. Send `userId`. |
| invalid_user_id | 400 | `userId` (or `scope`) is not 1–64 letters, digits and . _ - : @ + = |
| conflicting_param | 400 | `userId` and `scope` were both sent and name different users. |
| input_too_long | 400 | A memory's text (or a search query) is over 2,000 characters: split it. |
| reserved_key | 400 | A key starts with `msg:`, `msg@` or `mem:`. |
| invalid_request | 400 | Anything else malformed, with `param` when one field is at fault. |
| ai_gateway_off | 403 | A search while the AI Gateway is switched off. A memory saved meanwhile is kept with `indexed: false`; threads and keys need no AI. |
| not_found | 404 | No such store, memory or key for this user (or it expired), or it is in another workspace. |
| already_exists | 409 | A PATCH gave a memory text the user already has. |
| wrong_store_kind | 409 | A call this kind of store does not have (memory records on an older kind, say). |
| plan_limit | 402 | A memory quota is used up; `limit_name` says which. |
| rate_limited / ai_rate_limited | 429 | The data allowance, or the per-minute embedding limit; retry after `Retry-After`. |
| embedding_failed | 502 | The embedding model failed on a search; nothing was charged. A memory saved meanwhile is kept with `indexed: false`. |
| index_unavailable | 409 / 501 / 502 | The store's search index is missing or not answering; the sentence says what to do. |

## Older kinds

- Stores created with `kind` "kv", "conversation" or "semantic" keep working as before, with `userId` (or `scope`) optional. New code leaves `kind` out.
- `PATCH /api/memory/:id { "action": "flush", "scope"? }` clears one user (scope, also accepted as `?scope=`) or, without one, the whole store: every value of every user. A scope sent empty or malformed is a 400, so only a request with none clears everything. A whole-store flush of a semantic store that answers 502 with `index_reset: false` should be run again. `DELETE /users/:userId` is the one call taught for forgetting a user.
- Without `userId`, `GET /api/memory/:id` on an older store lists every key, a user's as "@user/key", and up to 100 users (`scopes`; the next ones with `scopes_after=` from `next_scopes_after`). `unscoped=1` lists only keys stored without a user. The older `after=` paging (`next_after`) still works beside `cursor`.

## Reference

**SDK**

```js
const { store } = await hk.memory.create(project.id, { name: 'app' });
await hk.memory.append(store.id, { userId: 'user-42', threadId: 'chat-1', messages: [{ role: 'user', content: 'I am vegan' }] });
await hk.memory.add(store.id, { userId: 'user-42', text: 'Is vegan' });
const { memories } = await hk.memory.search(store.id, { userId: 'user-42', query: 'food preferences', topK: 5 });
await hk.memory.set(store.id, 'cart', { items: 3 }, { userId: 'user-42', ttlSeconds: 3600 });
await hk.memory.forgetUser(store.id, 'user-42');
```

**CLI**

```bash
harakumo memory <projectId>                                 # list stores
harakumo memory create <projectId> app
harakumo memory add <storeId> --user user-42 "Is vegan"
harakumo memory search <storeId> --user user-42 "food preferences"
harakumo memory list <storeId> --user user-42                 # memory users <storeId> lists the users
harakumo memory forget <storeId> --user user-42 --yes         # threads, memories and keys
```

**REST**

```http
GET    /api/projects/:id/memory                                   # list stores
POST   /api/projects/:id/memory          { "name", "ttlSeconds"? }   # kind "memory" when none is given
GET    /api/memory/:id?userId=&cursor=&limit=                     # the store, its quota and a page of keys
DELETE /api/memory/:id                                            # delete the store and everything in it
POST   /api/memory/:id/memories          { "userId", "text", "metadata"?, "ttlSeconds"? }
GET    /api/memory/:id/memories?userId=&cursor=&limit=20          → { memories, nextCursor }
GET    /api/memory/:id/memories/:memoryId?userId=
PATCH  /api/memory/:id/memories/:memoryId { "userId", "text"?, "metadata"?, "ttlSeconds"? }
DELETE /api/memory/:id/memories/:memoryId?userId=
POST   /api/memory/:id/memories/search   { "userId", "query", "topK"?: 10 }   → { memories, pending }
POST   /api/memory/:id/messages          { "userId", "threadId"?, "role", "content" } | { "userId", "threadId"?, "messages": [...] }
GET    /api/memory/:id/messages?userId=&threadId=&limit=50        # oldest → newest
DELETE /api/memory/:id/messages?userId=&threadId=                 # one thread, or every thread of the user
PUT    /api/memory/:id/keys/:key         { "userId", "value": {...}, "ttlSeconds"? }
GET    /api/memory/:id/keys/:key?userId=
DELETE /api/memory/:id/keys/:key?userId=
GET    /api/memory/:id/users?cursor=&limit=                       → { users, nextCursor }
DELETE /api/memory/:id/users/:userId                              # forget a user → { removed, partial }
```
