# Data

Four operations cover the working data of a Space: data.read, data.write,
data.changes and data.grep. Records are the rows of the record types
(read_docs("records")), documents the live Markdown documents and the extracted text of
uploaded files (read_docs("documents")). Several agents and people can work in the
same records and documents at once; the rules below keep their changes apart.

## Naming a target

- Record by id: `{"record": {"id": "<uuid>"}}`.
- Record by unique key: `{"record": {"type": "invoices", "key": {"code": "inv_0042"}}}`.
  `type` is the record type key; `key` holds the value of a unique field or
  all fields of one unique key (records.types.describe lists them).
- Document by path: `{"doc": {"path": "/guides/tone.md"}}`; by id:
  `{"doc": {"id": "<uuid>"}}`. Paths are the ones documents.ls shows; a live
  Markdown document is stored with a `.docx` export extension, both names find it.

Every target has a version: a record its `revision` (integer), a document
its `hash`. Keep the version of what you read; writes take it in `if`.

## Reading

data.read takes up to 100 `items`, records and documents mixed, and answers
one result per item in the same order:

- Record: status `ok` with id, type, revision, values, relations, documents.
- Document: status `ok` with id, path, hash, content, total_chars,
  next_offset. `section: "## Steps"` returns that section only; `offset` and
  `limit` page by characters.
- Uploaded CSV, TSV, TXT, MD and JSON files are read (and found by data.grep) as they are, byte for byte, even while extraction runs; other uploads return their extracted text.
- `if_none_match` with the revision or hash you hold answers `unchanged`
  without content.
- `not_found` covers missing and unreadable targets alike; `not_ready` is an
  uploaded file whose text is still being extracted or whose extraction
  failed; `no_text` is a processed file without text, its `hint` names the
  next call (documents.reprocess with reading ocr for PDFs and images,
  tools.audio.transcribe for audio, documents.download otherwise);
  `too_large` (over 2 MB) points to documents.download.

For questions across many records use records.sql; records.rows.query lists
one type with filter, sort and cursor.

## Writing

data.write takes up to 200 `ops` for one Space, at most 20 of them documents,
and applies all of them or none. Each target may appear once per call.

Record entries carry one of:

- `create`: field values of a new record. With `record.key` the key values
  are part of the record; a taken key fails with `exists`.
- `update`: field values to set; other fields keep their value. `unset`
  lists field keys to clear.
- `upsert`: needs `record.key`; creates the record or updates the one that
  has the key. An archived match fails with `archived_match`.
- `archive` (`true`, or `{"unlink_relations": true}`) and `restore`.
- Relations and document links ride along with create, update and upsert, or
  stand alone: `link` and `unlink` add or remove single targets per relation
  field, `set_links` replaces the whole list. All take
  `{field_key: [ids]}`.

Document entries carry one of:

- `patch`: steps applied in order to the current text.
  `{"replace": old, "with": new}` needs `old` to occur exactly once
  (`anchor_not_found`, `anchor_ambiguous` otherwise; `"all": true` replaces
  every occurrence). `{"append": text}` adds to the end.
  `{"section": "## Heading", "with": text}` replaces the body under that
  heading up to the next heading of the same or a higher level;
  `{"section": "## Heading", "append": text}` adds to its end.
- `put`: the whole text.
- `create`: a new live Markdown document at `doc.path` with this content;
  missing folders are created, a taken path fails with `exists`. The result
  carries the stored `path`.

A patch changes only the ranges it names, so text a person types elsewhere in
the document at the same moment stays. Edits a browser made in the last two
seconds may not be visible to the hash check yet; they are merged, not lost.

### Conditions

`if` on an entry lists what must be true:

- `revision` (record) or `hash` (document): the version you last read.
- `where` (record): a filter tree, checked on the record under its lock;
  operators per field type and value forms are in read_docs("records"),
  section Filter tree (`"$now"` is the current time). This makes "take it if
  nobody has it" one call:
  `{"combinator": "or", "conditions": [{"field": "assigned_to", "op":
  "empty"}, {"field": "assigned_until", "op": "before", "value": "$now"}]}`.
  A new record created by upsert has nothing to check.
- `schema_version` (record): fails with `schema_changed` when the type was
  published again.

### Write mode: when the version is required

A Space has a `write_mode` (spaces.get), a record type can override it
(records.types.describe). Documents follow the Space.

| | strict (default) | merge |
|---|---|---|
| create, upsert that creates | free | free |
| update, unset, link, unlink | `if.revision` required; any newer revision is a `conflict` | `if.revision` optional; with it, `conflict` only when one of the written fields changed since; without it the last write wins per field |
| document patch with replace or append | `if.hash` required | `if.hash` optional; replace still needs its old text to be there |
| archive, restore, set_links, put, section replacement, replace all | version required and current | version required and current |

`base_required` means the entry needed a version and had none. Space managers
set the mode with spaces.update and records.types.update; types that sync
scripts fill by upsert belong on merge.

### Result and errors

The answer has one result per entry: `{status, id, revision}` for records,
`{status, id, hash}` for documents; status is created, updated, unchanged,
archived or restored. `unchanged` means every value, link and document link
already matched: no new revision, no event. A changed value is a change, a
sync timestamp included; leave fields out of `upsert` that should not count.
`include: "values"` returns each written record in full. `dry_run: true`
rehearses the call and leaves nothing behind, not even its idempotency_key.

Many records linking the same record (rows of one statement pointing at it)
give that record one new revision per call, not one per link.

The first entry that fails aborts the call. The error names it in
`details.path` (`ops[2]`):

- `conflict`: the target changed; `details.current` holds the record as it
  is now. Decide again and send a new idempotency_key.
- `condition_failed`: `if.where` no longer applies; `details.current` shows why.
- `exists`, `not_found`, `base_required`, `anchor_not_found`,
  `anchor_ambiguous`: fix the entry.
- `busy`: another write holds the same targets. Retry with the same
  idempotency_key.
- `write_timeout` (413): the call ran longer than 15 seconds and nothing was
  saved. Repeating it times out again: split it into calls of at most
  `details.max_entries` entries, each with its own idempotency_key.
- Field errors of the record type (required_field_missing,
  invalid_field_value, unique_violation, ...) come through unchanged.

### Idempotency keys

`idempotency_key` (1-200 characters) is required on every data.write call,
also with `dry_run: true`. A dry run does not keep its key, so the real call
may reuse it. Repeating a key with the same arguments returns the first
result without writing again; the same key with other arguments fails with
`integration_idempotency_conflict` (use a new key).

The key identifies one intended action. Agents that share a Space build it as
`<agent>:<target>:<step>`, for example `cs-ana:conv-4711:take`, so two agents
never reuse each other's key and a retry of the same step replays its result.

## Following changes

data.changes keeps a copy of a Space current. The first call (no cursor)
lists every record and document once, page by page; keep calling with the
returned `cursor` until `has_more` is false. Later calls return only what
changed since, each target once with its newest state:
`{seq, kind, id, type or path, revision or hash, deleted, by, at}`.

- Items can repeat and intermediate states are skipped; apply each item as
  "this target is now at this version".
- `deleted: true` marks archived records and deleted documents.
- A document item with `hash: null` was edited in the browser and not read
  since; data.read returns its text and hash.
- `types: ["invoices"]` and `docs: true` narrow the feed; `include:
  "values"` adds record values and document text up to 64 KB.
- `wait_seconds` (up to 60) holds the call until something changes; at most
  two calls of one user wait at a time.
- `resync_required`: the cursor is too old or a record type of the Space was
  published again; start again without a cursor.

## Searching text

data.grep finds a literal text (no regex, case-insensitive, at least three
characters) in the documents of a Space, optionally under `folder`. Each
match has path, id, hash, line, text and, with `context_lines`, the lines
around it. `skipped` lists documents whose text was not searched: too large,
or still being prepared (repeat the call). Search records with records.sql.

## Example

One working step of a support agent: take the conversation if it is free,
note a learning, add a line to the session log.

```json
{
  "operation_key": "data.write",
  "arguments": {
    "space_id": "<space uuid>",
    "idempotency_key": "cs-ana:conv-4711:take",
    "ops": [
      {"record": {"type": "conversations", "key": {"chatwoot_id": "4711"}},
       "upsert": {"status": "in_progress", "assigned_to": "cs-ana",
                  "assigned_until": "2026-10-04T15:30:00Z"},
       "if": {"where": {"combinator": "or", "conditions": [
         {"field": "assigned_to", "op": "empty"},
         {"field": "assigned_until", "op": "before", "value": "$now"}]}}},
      {"record": {"type": "learnings"}, "create": {"name": "Refund wording", "rule": "..."}},
      {"doc": {"path": "/sessions/log.md"},
       "patch": [{"append": "\n| 4711 | Ana | in progress |"}]}
    ]
  }
}
```

The record types of this example are on merge, so the upsert and the append
need no version.
