> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moda.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# State writes

> Report writes to your agent's own state (memories, calendar, rules, files, config) so replays rebuild it exactly: recordStateWrite, POST /v1/state-writes, and the moda.state_write span event.

A replay runs one past turn of your agent again. To do that faithfully it needs the state your agent read at the start of that turn: its memories, calendar, rules, prompt-visible files and configuration. Moda can infer that state from your traces (what the prompt rendered, what tool calls changed), but inference misses writes no prompt ever shows. When your agent reports its writes directly, the replay uses exactly what you reported.

Reported writes take precedence over inferred state for the same row from the first report on. Rows you never report, and the time before you started reporting, still come from inference.

> [!NOTE]
>
> State writes are enabled per workspace. Ask Moda to turn them on; until then `POST /v1/state-writes` answers `404` and span events are ignored.

## Node and Workers SDK

`moda-ai/state` (moda-ai 1.19.0 or later) works on Node and Cloudflare Workers. Report each write at the storage helper every writer goes through, after the write has landed:

```typescript theme={"dark"}
import { waitUntil } from 'cloudflare:workers'; // Workers only
import { createStateWriter } from 'moda-ai/state';

const state = createStateWriter({
  apiKey: env.MODA_API_KEY,
  waitUntil,                                   // keeps the batch alive after the response
  stores: ['memories', 'calendar_posts', 'files', 'config'],
});

state.recordStateWrite({ store: 'memories', op: 'upsert', key: memory.id, value: memory, userId });
state.recordStateWrite({ store: 'calendar_posts', op: 'update', key: post.id, fields: { status: 'scheduled' }, userId });
state.recordStateWrite({ store: 'memories', op: 'delete', key: memory.id, userId });
```

`recordStateWrite` returns immediately and never throws. Outside a traced turn, writes are batched and sent to `POST /v1/state-writes`. Inside one (an active, recording OpenTelemetry span), the write becomes a `moda.state_write` event on that span and is exported with the trace, which links it to the turn.

Fields named like credentials (`token`, `secret`, `password`, `api_key`, `cookie`, `authorization`, `credential`, and similar) are removed at any depth before anything is sent. Narrow further with `stores` (an allowlist) and `redact` (a hook that may change a write or drop it by returning `null`).

## Write fields

| Field | Type | |
| - | - | - |
| `store` | string, required | The collection the row lives in: letters, digits, `_ . : / -`, at most 128 characters, starting with a letter or digit. A replay groups rows by store, so use the names your replay seed reads. |
| `op` | string, required | `create` or `upsert` (send the whole row in `value`), `update` (send the changed `fields`), or `delete`. |
| `key` | string, required | The row's id in the store, at most 512 characters. `*` is reserved. |
| `value` | JSON | The row after the write. A value that is not an object (a file's text) is stored as `{ "value": ... }`. |
| `fields` | object | The changed fields of an `update`. |
| `before` | JSON | The row before an `update`, when you have it: a replay uses it to fill fields the update did not touch. |
| `userId` | string | The end user the row belongs to, the same id your traces carry. Omit for state shared by every user. |
| `conversationId`, `traceId` | string | Optional links to the conversation and turn. |
| `at` | ISO 8601 string or epoch ms, required on the wire | When the write landed. The SDK fills in the current time. Must be within the last 730 days and at most 24 hours ahead. |
| `writeId` | string | Idempotency id, `[A-Za-z0-9_.:-]`, at most 128 characters. The SDK generates one. A write sent again with the same `writeId` is stored once; without one, Moda derives it from the write's content. |
| `sequence` | integer | The write's place among the writes your writer sent, `0` to `2147483647`. Writes with the same `at` apply in this order. The SDK fills it in with a per-writer counter. Resend it unchanged on a retry. |

`value`, `fields` and `before` together may be at most 64 KiB of JSON per write.

## POST /v1/state-writes

```bash theme={"dark"}
curl -X POST https://moda-ingest.modas.workers.dev/v1/state-writes \
  -H "Authorization: Bearer $MODA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "schema": "moda_state_writes.v1",
    "writes": [
      { "writeId": "w-7f3a", "store": "memories", "op": "create", "key": "m_123",
        "value": { "text": "Prefers short posts" }, "userId": "user_42", "at": "2026-11-13T10:00:00Z" }
    ]
  }'
```

Up to 500 writes and 512 KiB per request. Each write is validated on its own:

```json theme={"dark"}
{ "accepted": 1, "rejected": [], "writeIds": ["w-7f3a"] }
```

| Status | Meaning |
| - | - |
| `202` | Stored. `rejected` lists `{ index, reason }` for writes that failed validation (`missing_<field>`, `invalid_<field>`, `value_too_large`); fix those rather than retrying them. |
| `400` | The body is not JSON, has no `"schema": "moda_state_writes.v1"`, or has no writes. |
| `401` | Missing or invalid API key. |
| `404` | State writes are not enabled for this workspace. |
| `413` | More than 500 writes or 512 KiB. |
| `503` | Storage or authentication is temporarily unavailable. Retry with the same body: writes keep their `writeId`, so a retry never stores a write twice. |

## Span event

Inside a traced turn, attach the same write object (one per event) to the turn's span:

* event name `moda.state_write`
* string attribute `moda.state_write.json` holding the write as JSON

The trace id comes from the span. When the write has no `conversationId` or `userId`, the span's `moda.conversation_id` and `moda.user_id` attributes are used. Invalid events are dropped without affecting the trace.

## How replays use reported writes

For a replay of a turn, Moda builds the state from every reported write up to the turn's start, in time order: `create` and `upsert` replace the row, `update` patches it, `delete` removes it. Writes made during the turn itself or after it are never included. From a row's first reported write on, what Moda inferred about that row is ignored.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.