---
title: "Schema and records"
description: "Custom models, custom field types, formulas, tag families, and file attachments in Forge."
---

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

# Schema and records

In Forge, schema is versioned data. Custom models, custom fields, tag families, and tags live in the same commit DAG as business records, so adding a custom field or reorganizing a department or cost-center tree happens on a branch and goes through commits and change requests like any other edit.

## Custom models and API names

When you create a custom model or a custom field, you give it a human-readable display `name`, such as `"Line item"` or `"Unit cost"`. Each one has two identifiers:

- **API name (`api_name`)**: The lowercase snake_case slug derived from the display name, used in API paths, record payloads, reference targets, diffs, merge conflicts, violations, and formulas, such as `line_item` or `unit_cost`. Renaming a custom model or custom field updates its `api_name`, so requests after a rename address the updated `api_name`.
- **ID (`id`)**: Kept for the lifetime of the model or custom field, so a rename never changes it, or the ID prefix of the model's records.

```sh
# Create a custom model with two initial custom fields
forge custom-models create-custom-model --repo "$REPO" --branch main --data '{
  "name": "Line item",
  "fields": [
    { "name": "Description", "type": "text", "required": true },
    { "name": "Quantity", "type": "decimal", "default_value": 1 }
  ]
}'

# Add another custom field to the model
forge custom-models create-custom-field --repo "$REPO" --branch main --model line_item --data '{
  "name": "Unit cost",
  "type": "currency",
  "required": true,
  "default_value": 0
}'
```

## Custom field types

Every plain custom field declares a `type` from the 17 built-in custom field types. Reads and writes use the same JSON representation for each type:

| Type | JSON value format | Notes |
| --- | --- | --- |
| `text` | `string` | Empty string `""` is treated as missing for `required` checks |
| `rich_text` | `string` | Empty string `""` is treated as missing for `required` checks |
| `integer` | `number` (safe integer) | Whole numbers |
| `decimal` | `number` (finite IEEE 754 float) | Floating-point numbers |
| `currency` | `number` (safe integer) | Stored and sent in **cents** (for example, `1250` for `$12.50`) |
| `percent` | `number` (safe integer) | Stored and sent in **basis points** (for example, `750` for `7.5%`) |
| `boolean` | `boolean` | `true` or `false` |
| `date` | `string` (`YYYY-MM-DD`) | Must be a valid UTC calendar date (for example, `"2026-10-22"`) |
| `datetime` | `number` (safe integer) | Epoch milliseconds (for example, `Date.parse("2026-10-22T19:00:00Z")`) |
| `duration` | `number` (safe integer) | Duration in seconds |
| `picklist` | `string` | One option key from the custom field's `options` array |
| `multi_picklist` | `Array<string>` | Non-empty array of unique option keys from `options`, or `null` when empty |
| `geo` | `{ "lat": number, "lng": number }` | Decimal degrees with `lat` in `[-90, 90]` and `lng` in `[-180, 180]` |
| `reference` | `string` (target record ID) | Requires `target_model` (the target model's `api_name`). Takes an optional `on_delete: "cascade"`, or a `target_repo` that points it at another repo |
| `user` | `string` (user ID) | Must name a user who is or has been a member of the repo's org |
| `attachment` | `{ "id": "attachment_blob_..." }` | References an uploaded attachment blob in the same repo |
| `multi_attachment` | `Array<{ "id": "attachment_blob_..." }>` | Non-empty array of unique attachment blob references, or `null` when empty |

Plain custom fields also support these settings:

- `required`: Every live record must have a non-missing value at commit time.
- `unique`: No two live records in the model may share the same non-null value.
- `default_value`: The initial value used when `createRepoCustomRecord` omits the custom field. When a merge brings in a custom field one side added, the records the other side created take its default as well. Adding a default to a custom field both sides already had fills nothing. A `unique` custom field takes no default, because every record that omits it would share the default.
- `options`: Required for `picklist` and `multi_picklist` custom fields. Updating `options` replaces the entire list, and removing an option key that a record still holds is refused until no record uses that key.
- `target_model`: Required for `reference` custom fields. It names a custom model on the same branch. Changing it moves the custom field to a new column, as a type change does: every record starts empty in it, because its old values name records of the old target, while earlier commits keep reading the old values. Deleting a model that a `reference` custom field targets is refused with a `reference_field_target` violation; retarget or delete that custom field first.
- `on_delete`: Optional for `reference` custom fields. Setting `on_delete: "cascade"` means that deleting the target record with `?cascade=true` also deletes the referencing records.
- `target_repo`: Points a `reference` custom field at the custom model named `target_model` on the `main` branch of another repo in the org. A record write that names a record that repo's `main` doesn't hold, or a repo the writer can't read, fails with `InvalidCustomRecord`. Because the other repo can delete its record at any time, a cross-repo reference can't be `required` or take an `on_delete`. The custom field returns the target as `target_repo_id` and `target_model_id`.

### Custom field type changes

Updating a plain custom field's `type` via `PATCH /repos/:repo_id/branches/:branch/custom-models/:model_api_name/fields/:field_api_name` keeps the custom field's ID and converts its values when a lossless cast exists:

- `integer` converts to `text`, `decimal`, or `currency` (multiplying by 100 so `12` becomes `1200` cents).
- `decimal` converts to `text`.
- `date` converts to `text` or `datetime` (midnight UTC in epoch milliseconds).
- `picklist` converts to `text` or `multi_picklist` (a one-element array).
- `text` converts to `rich_text`, to `date` for strings that are valid `YYYY-MM-DD` dates, to `integer` for whole numbers written as digits with an optional leading `-` (such as `"12"`), and to `decimal` for those with an optional fraction (such as `"-2.5"`).

Values that do not convert start as `null`, while historical commits continue to read the original values. If the custom field had a `default_value`, the update request must also provide an updated `default_value` (or `null` to clear it).

Formulas and row formulas that read the custom field keep reading it and recompute from the converted values. A type change that leaves one of them unable to compute, such as text where it adds numbers, is refused with `WriteRefused`; change that formula first.

### How many custom fields a model holds

A model holds at most 250 custom fields, counted on the branch you write to. A deleted custom field no longer counts, and changing a custom field's type or formula never adds to the count. Creating a model with more than 250 custom fields, or adding a custom field once all 250 are taken, fails with `InvalidCustomModel`; delete a custom field or add the new one to another model. A merge that would leave a model with more than 250 custom fields, because each branch added some, is refused with `MergeRefused` and a `custom_field` violation naming the newest custom fields past the limit; delete enough of them on either branch and merge again.

## Records

Records are created and listed under their model's `api_name`, and updated or deleted by their `record_id` alone:

```sh
# Create a record
forge custom-records create-custom-record --repo "$REPO" --branch main --model line_item --data '{
  "fields": {
    "description": "Reserved compute instances",
    "quantity": 120,
    "unit_cost": 14500
  }
}'

# List records (up to 1,000 per page, with cursor pagination)
forge custom-records list-custom-records --repo "$REPO" --branch main --model line_item

# Update a record (omitted custom fields keep their stored values; null clears a value)
forge custom-records update-custom-record --repo "$REPO" --branch main --record "$RECORD_ID" --data '{
  "fields": {
    "quantity": 135
  }
}'

# Delete a record (pass --cascade to delete records that reference it with on_delete: "cascade")
forge custom-records delete-custom-record --repo "$REPO" --branch main --record "$RECORD_ID"
```

`list-custom-records` returns `{ data, next_cursor, references, users }`. `references` resolves the in-repo records that the page's `reference` fields name as `{ record_id, live: { model_api_name, label } | null }` (omitting records you can't read), where `label` comes from the target model's `primary_field` (set via `forge custom-models update-custom-model` to any plain `text`, `integer`, `picklist`, or `date` field, defaulting to the first plain `text` field or else the first plain `integer`, `picklist`, or `date` field, and falling back to `<model name> · <id suffix>` when empty or absent). `users` gives `{ id, display_name }` for the page's `user` fields. For cross-repo references, resolve labels on the target repo's `main` with `forge custom-records search-custom-record-labels`.

## Writing many records

A bulk write takes up to 500 rows in one request, and writes every row or none. Each row reads as the single write's body:

| Endpoint | CLI | Each row |
| --- | --- | --- |
| `POST …/custom-models/:model_api_name/records/bulk` (`createRepoCustomRecords`) | `custom-records create-custom-records --model` | `{ fields, formulas? }` |
| `PATCH …/branches/:branch/records/bulk` (`updateRepoCustomRecords`) | `custom-records update-custom-records` | `{ id, fields, formulas? }`, of any models |
| `POST …/custom-models/:model_api_name/records/bulk-upsert?match_on=` (`upsertRepoCustomRecords`) | `custom-records upsert-custom-records --model --match-on` | `{ fields, formulas? }` |

An upsert matches each row to a record by `match_on`, the `api_name` of a custom field marked `unique`, so a value matches at most one record. A row whose value a live record holds updates that record, and any other row creates one. It answers `{ "data": [...] }` with one `{ "action", "record" }` per row, in row order: `action` is `"created"` or `"updated"`, and `record` is the record written, with its `id`. Sending the same rows again creates nothing, which suits a sync that keeps an outside system's id in a unique field:

```sh
forge custom-records upsert-custom-records --repo "$REPO" --branch main --model vendor --match-on procore_id --data '{
  "records": [
    { "fields": { "procore_id": "pc-4411", "name": "Acme Steel Co." } },
    { "fields": { "procore_id": "pc-9020", "name": "Northwind Glass" } }
  ]
}'
```

A refused batch answers `BulkWriteRefused`: `items` lists the first 20 refused rows by their `index` in `records`, each with everything wrong with it, and `more_items` counts the rest. Fix the listed rows and send the whole batch again. Two rows can't name the same record or hold the same `match_on` value, and a `match_on` that names no unique custom field answers `InvalidMatchField`.

## Searching records

A search reads the records that a filter holds at a branch's working state or a commit, sorted and a page at a time. It answers `{ data, next_cursor, references, users, total }`: `references` and `users` resolve labels and display names just as `list-custom-records` does, and `total` is how many records the filter holds at the revision read, on every page (on a branch, as of that request). The API takes it as `POST …/custom-models/:model_api_name/records/search` (`searchRepoCustomRecordsAtBranch` and `searchRepoCustomRecordsAtCommit`) with the body `{ where, sort, limit, cursor, explain }`:

```sh
# Open or submitted bids over $50,000 whose company is tagged CSI 09, earliest due first
forge custom-records search-custom-records --repo "$REPO" --branch main --model bid \
  --data '{"where":{"and":[
    {"field":"status","op":"in","value":["open","submitted"]},
    {"field":"amount","op":"gt","value":5000000},
    {"field":"company","op":"matches","where":{"tag":"'"$CSI_09"'"}}
  ]},"sort":[{"field":"due_date","direction":"asc"}]}'

# Companies with more than one contact
forge custom-records search-custom-records --repo "$REPO" --branch main --model company \
  --data '{"where":{"referenced_by":{"model":"contact","field":"company","count":{"gt":1}}},"limit":1}'
```

`where` is a tree. Each node has one kind:

| Node | Holds for |
| --- | --- |
| `{ "and": [...] }`, `{ "or": [...] }`, `{ "not": {...} }` | Every, any, or none of the nested filters. An empty `and` holds for every record and an empty `or` for none. |
| `{ "field", "op", "value" }` | A custom field, named by `api_name`, compared with an operator its type takes. |
| `{ "field", "op": "matches", "where" }` | Records whose reference field points at a record that matches `where`. |
| `{ "tag": TAG_ID }` | Records carrying the tag or any tag beneath it in its tree. |
| `{ "ids": [RECORD_ID, ...] }` | The records with those IDs, such as the ones a [diff](https://buildrforge.com/docs/introduction/version-control/#diffs) names. |
| `{ "referenced_by": { "model", "field", "where" } }` | Records that at least one record of `model` points at through its reference `field`, matching `where` if given. With `count`, such as `{ "gt": 1 }` or `{ "eq": 0 }`, how many do. With `every` instead of `where` and `count`, every such record matches `every`, which holds for a record nothing points at. |

Each custom field in a model listing carries `filter`: the operators its type takes, whether it sorts, and the form its values take. Values are written as records are: currency in cents, percent in basis points, dates as `YYYY-MM-DD`, datetimes as epoch milliseconds, durations in seconds, references and users by ID, and picklists by option key. A formula field filters as the type it infers.

Every condition is true or false, never unknown. `ne`, `not_in`, `not_contains`, `has_none`, and `not` hold for records whose value is empty, and no other operator does; `is_empty` and `is_not_empty` ask for empty values, and `null` is refused as a value. `in: []` holds for nothing. Text compares ignoring case for the ASCII letters A to Z only: `É` and `é` differ.

`sort` takes up to three keys `{ "field", "direction", "nulls" }`. Empty values sort last unless `nulls` says `first`, in either direction; text sorts ignoring ASCII case and a picklist in option order; records that tie sort by ID. To read the next page, pass `next_cursor` back as `cursor` with the same `where` and `sort`. A cursor from another search, or from before a field the search reads changed type, column, or options, is refused with `InvalidCursor`. `explain: true` adds the filter as the API read it, with each field's type and operators.

A search the model can't answer is refused with `InvalidRecordFilter`, which lists up to 20 of its problems at once as `{ path, reason }` and counts the rest in `more_problems`. A body past 65,536 bytes is refused with `RequestBodyTooLarge`. A search must also stay within fixed caps, so every search fits what a repo's storage runs; past one, `RecordSearchLimitExceeded` names the cap, its maximum, and the actual count:

| Cap | Maximum |
| --- | --- |
| Nodes in `where` | 160 |
| Nesting depth of `where` | 7 |
| Nested `matches` and `referenced_by` | 3 |
| `matches` and `referenced_by` conditions in all | 16 |
| Values in one list | 1,000 |
| Bytes in one text value | 256 |
| Sort keys | 3 |

## Formulas

A custom field declared with a `formula` expression is computed automatically by the engine. You declare a formula custom field with `name`, `formula`, and optional `required` and `unique` flags, without specifying `type` or `default_value`:

```sh
# Compute extended amount on each line item
forge custom-models create-custom-field --repo "$REPO" --branch main --model line_item --data '{
  "name": "Amount",
  "formula": "Math.round(ctx.record.values.quantity * ctx.record.values.unit_cost)"
}'
```

The engine infers the storage type from the expression (`decimal` for numbers, `text` for strings, `boolean` for booleans, or `currency` / `percent` when wrapped in `formula.currency(...)` or `formula.percent(...)`).

### Formula context and helpers

Inside a formula expression, `ctx` provides two properties:

- `ctx.record`: The current record as `{ id, values }`, where `values` holds each custom field's value keyed by `api_name`.
- `ctx.state.models.<model_api_name>.records`: All live records of any custom model in the repo, allowing cross-model rollups and lookups. On both `ctx.record` and `ctx.state`, a `reference` custom field's value is the referenced record object `{ id, values }` (or `null`), so you can traverse references directly or match by `?.id`. A reference to another repo has only an `id`: a formula that reads its `.values` is refused.

The `formula` namespace provides domain and aggregation functions:

- `formula.sum(records, selector)`: Sums numeric values selected from an array of records (returns `0` on an empty array).
- `formula.avg(records, selector)`, `formula.min(records, selector)`, and `formula.max(records, selector)`: Aggregate numeric values (return `null` on an empty array).
- `formula.currency(x)` and `formula.percent(x)`: Return `Math.round(Number(x) * 100)` and type the custom field as `currency` (cents) or `percent` (basis points).
- `formula.grossUp(base, ...rates)`: Divides `base` by `1 - (sum(rates) / 10000)` and rounds with `Math.round`.
- A formula is a subset of JavaScript, not the whole language. Beside the `formula` functions, it can call `Number`, `String`, and `Boolean`, the `Math` functions `Math.round`, `Math.abs`, `Math.floor`, `Math.ceil`, `Math.min`, and `Math.max`, the array methods `filter`, `map`, `reduce`, `some`, and `every`, the string methods `trim`, `toUpperCase`, `toLowerCase`, and `includes`, and read `.length`. Forge refuses a formula that calls anything else.

```sh
# Roll up line item amounts onto a budget record
forge custom-models create-custom-field --repo "$REPO" --branch main --model budget --data '{
  "name": "Total",
  "formula": "formula.sum(ctx.state.models.line_item.records.filter(x => x.values.budget?.id === ctx.record.id), x => x.values.amount)"
}'
```

A change recomputes every formula it reaches before it answers, and the repo answers nothing else meanwhile, so one write or merge may call formula callbacks at most 500,000 times. A callback is the function given to `filter`, `map`, `reduce`, `some`, `every`, or a helper such as `formula.sum`, and it is called once for each record it visits. A formula that reads a whole model for each of its records, such as a rank over every line item, recomputes on every record whenever any of them changes, and reaches that limit at about 700 records. Past it, Forge refuses the change with a `formula` violation that names the field. Narrow the collection to the records tied to this one, such as those that reference it, or remove the field. Removing the field or replacing its formula with a cheaper one always succeeds; deleting records doesn't, since each deletion recomputes the formula on every remaining record.

### Row-level formula overrides

Individual records can override a formula custom field with a custom row expression or a fixed literal by passing `formulas` alongside `fields` when creating or updating a record:

```sh
# Override the formula for a single record
forge custom-records update-custom-record --repo "$REPO" --branch main --record "$RECORD_ID" --data '{
  "fields": {},
  "formulas": {
    "amount": "ctx.record.values.quantity * 12000"
  }
}'
```

The override's return type must match the custom field's inferred type. Passing `"formulas": { "amount": null }` removes the row override and restores the model's default formula.

## Tag families and tags

Taxonomies such as cost centers, departments, or regions are modeled as **tag families** rather than rigid tables. A tag family has a `kind` of either `flat` (a simple ordered list) or `tree` (where tags nest under `parent_id`):

```sh
# Create a hierarchical tag family
forge tags create-tag-family --repo "$REPO" --branch main --data '{
  "name": "Cost centers",
  "kind": "tree"
}'

# Create a root tag
forge tags create-tag --repo "$REPO" --branch main --family "$FAMILY_ID" --data '{
  "name": "Engineering",
  "code": "ENG",
  "parent_id": null,
  "position": 0
}'

# Attach a tag to any custom record
forge tags create-record-tag --repo "$REPO" --branch main --record "$RECORD_ID" --tag "$TAG_ID"
```

Tagging a record that already carries the tag, or untagging one that does not, is idempotent.

## File attachments

File bytes live in Forge's object storage and move over presigned URLs, never through the API. A file becomes an attachment blob in three steps:

1. **Create the blob**: Call `POST /repos/:repo_id/attachment-blobs` with `filename`, `content_type`, and `size` in bytes. Creating a blob takes write access to the repo. The API returns the `attachment_blob`, its upload `parts`, and the `expires_at` of their URLs.
2. **Send the bytes**: For each part, send a `PUT` to its `url` with the `length` bytes starting at `offset` in the file as the body, and with exactly the part's `headers`.
3. **Name the blob in a record**: Write the blob's ID in an `attachment` custom field as `{ "id": "attachment_blob_..." }`, or in a `multi_attachment` custom field as `[{ "id": "attachment_blob_..." }]`. The record write confirms the upload.

```json
{
  "attachment_blob": { "id": "attachment_blob_...", "filename": "a-101.pdf", "content_type": "application/pdf", "size": 48213, "created_by_id": "user_...", "created_at": "...", "uploaded_at": null, "promoted_at": null },
  "parts": [
    {
      "url": "https://<object-storage>/...",
      "offset": 0,
      "length": 48213,
      "headers": {
        "content-type": "application/pdf",
        "content-disposition": "attachment; filename=\"a-101.pdf\"; filename*=UTF-8''a-101.pdf",
        "if-none-match": "*"
      }
    }
  ],
  "expires_at": "..."
}
```

### Upload parts

The blob's `size` decides how its bytes are sent:

| Size | Parts | Headers to send |
| --- | --- | --- |
| Up to 16 MiB | One `PUT` | The part's `content-type`, `content-disposition`, and `if-none-match`. The URL signs them, so storage refuses a request that changes or leaves one out. |
| More than 16 MiB, up to 5 TiB minus 5 GiB | Up to 10,000 parts of at least 16 MiB each. Every part but the last is the same size. | None |

A single `PUT` writes its object once. Its `if-none-match: *` header makes storage answer `412 Precondition Failed` when the bytes are already there, so a repeated `PUT` after a success changes nothing. You can send multipart parts in any order and in parallel.

### Confirm an upload

A record write that names a blob checks that all of its bytes arrived and that they add up to its `size`. When they don't, the API refuses the write with `WriteRefused` (HTTP 422), whose violation has `kind: "attachment"` and names the blob in `attachment_blob_id`. Send the missing bytes, then write the record again.

Once a write confirms a blob, its `uploaded_at` is set, and Forge copies its bytes to permanent storage in the background and sets `promoted_at`. Forge keeps a confirmed blob forever, and nothing about it changes after that.

### Upload time limits

An upload has these deadlines, counted from the blob's creation:

| Limit | Duration | What happens after it |
| --- | --- | --- |
| Upload URLs | 1 day | Storage refuses the URLs. No endpoint signs new ones, so create a new blob. |
| Unfinished multipart upload | 1 day | Storage abandons the upload and its parts. |
| Confirming record write | 6 days | A write that names the blob is refused. |
| Unconfirmed bytes | 7 days | Storage deletes the bytes of a blob that no record write confirmed. |

A blob belongs to the repo that created it. A record names only blobs of its own repo.

### Download files

Downloading a blob takes read access to its repo. Two endpoints check that access, then hand out a signed storage URL that lasts five minutes:

- **`GET /repos/:repo_id/attachment-blobs/:attachment_blob_id/content`**: Answers a `302` redirect to the signed URL. Use it where a browser follows the redirect itself, such as a link or an `<img src>`.
- **`GET /repos/:repo_id/attachment-blobs/:attachment_blob_id/download`**: Answers the signed URL as `{ "url": "...", "expires_at": "..." }`. Use it in agent code, `ctx.forge`, and other clients that can't follow the redirect.

Fetch a signed URL right before you use it, and don't store it. Storage serves a file with `Content-Disposition: attachment`, so opening a URL downloads the file instead of rendering it as a page. An `<img>` still displays an image. To show a PNG, JPEG, GIF, WebP, or AVIF image or a PDF in place, as in a frame or a new tab, pass `?disposition=inline` to either endpoint; any other type still downloads.

### Attachments in the CLI

The CLI creates the blob, sends its parts, and downloads it, each in one command:

```sh
forge attachment-blobs upload --repo "$REPO" --file contract.pdf
forge attachment-blobs download --repo "$REPO" --attachment-blob "$BLOB_ID" --output contract.pdf
```

Source: https://buildrforge.com/docs/introduction/schema-and-records/index.mdx
