# Modeling guide

> The complete Layerz modeling guide for agents, session start, structure, stocks, lists, values, branches, sources, templates, checks, versions and rebuilds.

The guide the MCP server gives agents (`modeling-guide://reference`), in full. Section numbers (§) refer to this page.

How to build and maintain a Layerz financial model through the MCP tools. The
formula language is in `formula-spec://reference`, the number formats in
`format-spec://reference`. This guide is the method; each tool description is
the contract.

## 1. Session start

1. **Conventions first.** `layerz_get_conventions({ model_id })` returns the
   conventions of the model's workspace (the standing preferences its members
   share: conventions, tone, modelling habits, on every model of the
   workspace) and the model's FINANCE.md (currency,
   units, sign convention, glossary, objective, statement structure). Every
   value returned by the tools is expressed in those conventions: `12000` may
   be 12k EUR or 12M USD depending on `units` and `currency`. The same two
   documents come back as `conventions` in the results of `layerz_get_model`,
   `layerz_create_model`, `layerz_build_from_blueprint` and an unfiltered
   `layerz_read`, so a session that opens a model already has them.
2. **Push a local FINANCE.md.** When the local project root carries a
   `FINANCE.md`, push it with `layerz_set_finance_md({ content, source: "imported" })`
   so later writes follow the same conventions.
3. **Keep the FINANCE.md complete.** Its Markdown body documents the objective
   (what the model builds, the deliverable expected), the structure of the P&L,
   the Cash Flow and the Balance Sheet (sections, key line items, how they
   connect: net income → retained earnings, cash flow → closing cash) and the
   conventions. When any of this is missing or stale, reconstruct it from the
   live model (`layerz_read` returns every item with `role` + `parent_uid`;
   that hierarchy IS the statements structure) and persist it with
   `layerz_set_finance_md`. Update it in the same turn as any change to the
   model's identity, structure or conventions (`layerz_set_finance_md` or the
   `meta` op of `layerz_patch`).
4. **Model identity.** A model carries a `glyph`: a kebab-case Lucide icon
   name (https://lucide.dev/icons) shown as its emblem in the app and on shared
   links. When `glyph` is absent from `layerz_get_model`,
   set one coherent with the business via the `meta` op of `layerz_patch`
   (SaaS → `trending-up`, coffee shop → `coffee`, real estate → `house`,
   banking → `landmark`, energy → `wind`, HR → `users`, valuation → `scale`,
   treasury → `wallet`), without asking.
5. **Read before writing.** `layerz_read` (structure, optional values) and
   `layerz_get_model` (full detail, branches, sharing roster) are the two
   reads; `layerz_validate_model` audits the DAG. Values returned with
   `computable: false` are zero-filled placeholders: fix the model first.
6. **A `notice` is for the user.** A tool result can carry a `notice`
   (the AI actions of the billing cycle nearing the plan's cap). Relay it to
   the user in one sentence, once, and carry on with the task. Past the cap,
   the tools answer `QUOTA_EXCEEDED` with the reset date and the link to
   pass on.

## 2. Structure: roles and hierarchy

Roles: `section` (structural grouping, no value), `assumption` (typed input),
`formula` (expression, or an aggregator summing its children when it has no
expression), `callup` (typed mirror of one source), `balance` (rolling stock:
opening + flows), `dashboard` (container of `chart` / `kpi` / `mini_table`).

- Only `section` and `dashboard` live at root. A `section` accepts every role
  except widgets and nests inside another `section` for true sub-sections.
  A `dashboard` accepts widgets only.
- **Tab order** (the app's tabs and the Excel sheets): root dashboards first,
  then root sections, then list tabs; each group in its own order. Place a tab
  when you create it (`after` / `before` a tab of the same group; none = last
  of its group) and reorder it later with `move { uid, after | before }` (or
  `list_update { uid, after | before }` for a list). The same anchors order a
  container's children. `layerz_read` returns items in that order.
- A no-expression `formula` is an aggregate VALUE ("Total Revenue"); a nested
  `section` is grouping with no value. A `formula` is an aggregator XOR a
  transformation: an expression AND children is rejected
  (`FORMULA_EXPR_AND_CHILDREN`).
- **Callup** = a typed mirror of ONE source whose value flows INTO its parent:
  use it for balance flows and to surface a value inside a section or subtotal.
  It shows the source's name unless given its own (`name` on the callup:
  "Grant" on the P&L mirroring "Grant received"), and inherits its
  `timeline_ref` (none on a callup). Never use a callup for arithmetic:
  inside a formula, reference the source directly (`Revenue * 1.2`); a
  callup's own name is not a formula identifier. A single bare reference with
  no `timeline_ref` override is auto-posed as a callup on create/replace
  (the response says so in `notes`).
- Every item has a single `name` (visible label + formula identifier), unique
  case-insensitively within the model; multi-word names use back-ticks in
  formulas (`\`Annual Revenue\` * 12`).
- **Aggregation** (how a month folds into a year): a flow sums, a balance is a
  `stock` (its closing), a callup folds like its source, and a formula that
  copies, lags, adds or subtracts stocks is a `stock` too: ARR or a
  headcount copied by a formula is not summed over the year. A stock times a
  rate or a price (headcount × salary, debt × rate) is a flow and sums. Set
  `aggregation` only to override: `stock` for a level built from a rate
  (MRR = clients × price), `average` for a rate, `first` for an opening
  read on the first month (opening cash in a yearly cash-flow table).

## 3. Building: blueprint vs patch

- **`layerz_build_from_blueprint`** for bulk creation of whole sections with
  their hierarchy (items reference each other by `name`; `mode: "merge"` adds
  to the model reusing items by name, `mode: "replace"` rebuilds it). Send it
  once with `apply_if_clean: true`: it validates and writes only when there
  is no error (errors come back with a path, nothing written). A large
  blueprint goes as a JSON file (`layerz_create_upload_url`, then
  `file_id`). The answer is concise (`name_to_uid`, counters, errors,
  health); UIDs are stable for a model, so a dry run's `name_to_uid` holds.
- **`layerz_patch`** for incremental edits (a batch of
  `create/replace/update/delete/move/list_*/meta` ops, all-or-nothing). Give a
  `create` a temp `id` (`_rev`) and reference it from later ops in the same
  batch (`parent`, `source`, `target`, `series`, `liste_ref`, `after`) and
  inside formulas (`$_rev * 1.2`, whole tokens only, lag suffix kept:
  `$_cum_Y-1`). A create may reference its own temp id or name in its formula:
  the self-referential counter `IF($_y_Y-1 = 0, $start, $_y_Y-1 + 1)` ships in
  one op.
- **Swap with `replace`**, not create + rewire + delete: `replace` keeps the
  item's UID, so inbound references (formulas, callups, widgets, children) stay
  valid, and it carries over the presentation fields `new_item` omits (style,
  format, note, check, placement).
- **`update` is a strict partial merge**: only the named fields change.
  Styling, formats, notes, checks and tile placement set in the web editor
  survive every agent write that does not mention them.
- Read the `map` field of the patch result (temp id → real UID) before the
  next batch: temp ids are batch-scoped.
- Every item or list reference takes a temp id, a UID or the name: `uid`,
  `from_uid`, `parent`, `after` / `before`, `source`, `target`,
  `series`, `rows`, `compute`, a list op's `uid`, and the `uids` of
  `layerz_read` / `layerz_diff`. A UID wins over a name.

## 4. Stock-flow (rolling balances)

Cash, ARR, retained earnings, debt, fixed assets:

1. create a `balance` with `opening_balance`;
2. for each flow, a `formula` whose value is the per-period delta (outflows
   negative);
3. attach each flow as a `callup` child of the balance (`source: <flow>`);
4. when a flow depends on the balance itself (interest on debt, churn on ARR),
   read the previous period with the lag suffix `_M-1` / `_Q-1` / `_Y-1` on
   the balance to break the cycle.

A balance without callup children stays flat at `opening_balance` forever:
almost always a modeling bug. The balance rolls at the finest active grain
whatever its declared `timeline_ref`.

## 5. Lists (per-element series)

Three concepts:

- the **lists registry** (`list_create` / `list_update` / `list_delete`): a
  named registry of elements (Functions, Products, Channels, Debt Tranches…),
  idempotent by name, at most 500 elements;
- **list-mode items**: an `assumption` / `formula` / `balance` carrying
  `liste_ref`, expanded to one virtual instance per element;
- **branches** (§ 7), which are scenario coordinates, not lists.

Pattern: `list_create` (each element may carry a temp `id`), bind the consumer
with `liste_ref` (temp id, name or UID), populate `timeline_values` keyed by
element UID, label or temp id (`null | number | (number|null)[]`, a scalar is
wrapped into a 1-element array). Unset cells read as 0 (a flux), never a
forward-filled stock: send a full array or `timeline_ref: "constant"` for a
value held every period. Temp ids of list elements resolve only in the batch
that declares the list; later batches key by label or UID. The map is the full
set of series of the branch written: an element it omits loses its series
there. Removing an element from the list (`list_update` without it) drops its
series on every item bound to the list.

- **Balance-list rule**: when a `balance` carries `liste_ref`, every list-typed
  child shares the same `liste_ref`; scalar children broadcast. A callup child
  takes the list of its source: the callup of a list-mode flow feeds each
  element its own flow (the stock-flow pattern of § 4 holds per element).
- **Cross-list bridging** is declared on the element: `list_update` with
  `items: [{ label: "Direct", mapped_to: { Products: ["Pro", "Enterprise"] } }]`.
  Declare a link once, on either side: it serves both directions (aggregation
  children → parent, broadcast parent → children with `Item[i]`).
  Group subtotal example: creditors `Bank 1`, `Bank 2`, `Supplier` and a
  `Groups` list with `Banks`; link them on the group
  (`{ label: "Banks", mapped_to: { Creditors: ["Bank 1", "Bank 2"] } }`) or on each
  creditor (`{ label: "Bank 1", mapped_to: { Groups: ["Banks"] } }`), then
  `Bank repayments = Repayment[\`Banks\`]`.
- **Formula-list (cross-dimension aggregation)**: a scalar formula whose operand
  carries a `liste_ref` sums that operand across its dimension; with
  `mapped_to`, the subscript `Operand[\`key\`]` rolls up the mapped source
  elements (a SUMIF over the mapping). Prefer it over a parallel "code" column
  + `SUMIF(..., = N)`. A bare reference to a list item is always its TOTAL; the
  per-element value inside a list-mode formula is `Item[i]`. Never add a scalar
  callup to get a total.
- **Chart list rendering**: `list_mode: "split"` (default) explodes EVERY
  list-backed source into one series per element; `"total"` plots each item's
  aggregate as one series.
- **List total row**: `list_total: true` shows the aggregate row's values; the
  aggregate is still computed and referenceable when it is off.
- **Subscript syntax**: `Item[\`key\`]` slices a list-dimensioned item by an
  element of its list, or by a key of a list reachable via `mapped_to`
  (auto-aggregates the matching sources). Lags apply to a subscript
  (`Salary[\`Sales\`]_Y-1`, `Item[i]_M-1`).
- **2D patterns (list × time)**: seasonality (`[i]` × scalar monthly curve),
  ramp-up / cohorts (`Curve_M-$Offset` with a per-element offset auto-populated
  by `LIST_INDEX`), per-element roll-forward (`X[i] = Flow[i] + X[i]_M-1`),
  allocation (`G&A[i] = Shared G&A * Revenue[i] / Revenue`).

## 6. Values: two regimes

Branch on `liste_ref` alone:

- **list-mode item** → `timeline_values` keyed by element (§ 5); `value` /
  `values` are rejected;
- **non-list item** → `value` (scalar, broadcast to every period) or
  `values` (array at the item's grain); `timeline_values` is rejected: on a
  non-list assumption or a computed line (`formula` / `balance`) it is
  **import-owned** (actuals and overrides come from `layerz_import_branch` or
  the Sources panel).

A one-cell edit on a non-list item passes a period-keyed `timeline_values`
map (`{ "2026-06": [-119.19] }`, keys `YYYY` / `YYYY-MM` / `YYYY-Qn` at the
item's grain): it is rerouted into the typed `values` series and leaves the
other periods intact; a canonical map (`{ "yearly": [...] }`) is rejected. KPI `target_period` on
monthly data accepts the annual shorthand `2028` (normalized to `2028-12`).

Timelines share one horizon, snapped to whole months; a yearly period is a
calendar year and needs its December in range. A value array starts at the
first period of that horizon: check `notes` after setting `timelines`, it
names any bound applied other than requested. A `values` array shorter than
the horizon carries its last value to the end, a longer one is cut: `notes`
says so; send one value per period when the tail should differ.

`layerz_read` values `v` always sit under their labels `p`: yearly by
default when the model has a yearly timeline, else its finest grain; a
`granularity` the model does not carry is refused
(`GRANULARITY_UNAVAILABLE`).

Formats: an item `format` names a pre-installed format, `date`, or a
`model.formats` key declared in the same batch (`meta.formats`), otherwise
`UNKNOWN_FORMAT`. `currency` / `currency_2` resolve live from the FINANCE.md
currency.

## 7. Branches, scenarios and actuals

A branch is a scenario coordinate: the model reads as `base ⊕ branch`.

- **Create a scenario branch** with `layerz_update_branch({ display_name })`
  (no `dataset_id` = create; a second call with the same name updates it).
  No data source is involved.
- **Write scenario values** with `layerz_patch({ branch_id, ops })`: an
  `update` / `replace` carrying `value` / `values` / `timeline_values` on an
  assumption stores only the cells that differ from the base as that branch's
  overlay, exactly what a value edit does in the web editor with the branch
  checked out. Structural ops and non-value fields apply model-wide.
  `compute_branch` defaults to `branch_id`, so the returned `compute` series
  are the scenario's. Writes on a computed line overlaid by a branch are
  rejected; import the actual instead.
- **Import actuals** with `layerz_import_branch`: the `file_id` path parses a
  spreadsheet server-side and classifies its rows with the model's mapping
  rules (§ 8); `entries[]` with `record_import` writes values you computed
  yourself with provenance (a data source is materialized so the Sources panel
  and `layerz_list_transactions` audit it). Bare `entries[]` (no `file_id`,
  no `record_import`) is a manual overlay identical to `layerz_patch { branch_id }`.
  Each entry's `timeline_ref` equals the target item's grain (or `constant`);
  aggregate or split the source to that grain first. An entry on a `formula` /
  `balance` is a per-period override (actual) that seeds downstream periods.
  `replace: true` wipes the branch then writes (carry-forward keeps periods the
  entries do not cover: send an explicit 0 to clear one; with
  `replace_scope: "import"` the entries are the source's whole contribution and
  uncovered periods are dropped, `purged_periods`; a new version that would
  empty the source's lines is refused, `IMPORT_CONFIRMATION_REQUIRED`: check
  the file, then `confirm_replace: true`); `merge: true` upserts
  cell by cell. Preview with `dry_run: true` (`overridden_items`,
  `validation_errors_new`), then commit.
- **One file per exercise (a FEC per year, a monthly export).** Several
  sources may feed the same lines: each owns its rows, a sync rewrites only
  its own months and the dry run names only them. The close in one call each:
  a new version of a file → `file_id` + `replace_source_id` (from
  `layerz_list_integrations` or a dry run's `suggested_replace_source`),
  nothing else, the default branch included; a new exercise → `file_id` +
  `rules_from_source_id` (the sibling's rules classify it and are copied
  onto the new source); a rule correction on every exercise →
  `layerz_manage_mapping { op: "set", source_ids: [...] }` then
  `layerz_manage_integration { op: "sync" }` on each source, in any order.
  An opening journal (à-nouveaux: AN, RAN, ANO, AD) is read from the journal
  column of any ledger and opens a balance (`opening_entries`).
- **Cutover.** `actuals_through` on the model (or a branch override) is the
  last real period; `IS_ACTUAL` in a formula switches actual/forecast logic
  (`IF(IS_ACTUAL, actual_line, forecast_line)`) and follows every sync.
  `layerz_update_branch({ actuals_through })` pins it; `null` resets to auto.
- **Year to date.** A KPI or a mini-table with `period_mode: "ytd"` shows the
  cumulative from January through its `target_period` (flows summed, a ratio
  line `a / b` recomputed on the cumulated operands), so a close dashboard
  needs no YTD line per account. Inside the model, `YTD(x)` and `TTM(x)`
  are the formula equivalents; a rate to date is `YTD(margin) / YTD(revenue)`,
  never the YTD of a rate.
- **Base by default.** Without `branch_id`, reads and writes are the base
  plan: `items[].values`, `v` and `layerz_get_model` never mix in an
  overlay. Read a branch with `layerz_read({ branch_id })` (`v` and
  `vv`, the branch minus the base, follow it).
- **Default branch on open**: `meta.default_branch` (and a dashboard's
  `default_branch`) sets the branch checked out when the model opens.
- `layerz_delete_branch` removes the branch, its rows and the data sources
  that fed only that branch.

## 8. Sources and mapping rules

`layerz_list_integrations` lists every data source (API connectors and file
imports, plus linked external models with `include_external_refs`). Lines of
other models link through `layerz_external_ref { op: "link" }`, one per call or
up to 200 in `links` (one version for the batch).
`layerz_list_transactions` shows each staged row with its routing: mapping is
the only routing path (no fuzzy match), so a row with no matching rule is
`unmapped` and its cost is masked.

The loop: read `unmapped` (from `layerz_list_transactions`, or
`layerz_list_mappings { include_coverage: true }`) → write a rule with
`layerz_manage_mapping { op: "set", source_id, pattern, target }` (a rule
belongs to the source whose rows it classifies; glob `*` anywhere;
`secondary_pattern` for a double key; `__ignore__` to route a
row nowhere on purpose; a whole plan goes in ONE call as `rules: [...]`, up to
500, validated whole and replay-safe: identical rules report `unchanged`) or
import a catalog onto a source (`op: "import_template", source_id`), or give a
source the rules of a sibling (`op: "copy", source_id, rules_from_source_id`;
`on_conflict` `keep` by default, `replace` to overwrite) → replay
the projection with `layerz_manage_integration { op: "sync" }` (a file source
replays over its staged rows). A projecting op reports `unmapped`,
`proposed_window` (the staged span, auto-applied as `config.window`; edit it
with `layerz_manage_integration { op: "update", config: { window } }`),
`deletable_items` (import-only items a remap emptied, proposed, never
auto-deleted) and `shadowed` (cells an earlier import already wrote).
Connecting a new API key stays in the web app; credentials never transit MCP.

## 9. Templates

A template is a read-only copy of a model, published from the web app. Two
scopes: `official` (curated by Layerz) and
`workspace` (the library of a workspace, read by its members). The MCP
consumes templates and never publishes one. `layerz_list_templates` lists
them (`template_id` on one entry returns its blueprint and its
`description`, the template's FINANCE.md, the usage guide). A curated
template carries a `card`: `use_when`, `keywords`, `not_for`, and its
`parts` (top-level sections with their UIDs): match the user's request on the
card, not on the name. One part alone goes in as a module: take that section
from the template's blueprint and send it as `blueprint`. Start a new model from a whole
template with `layerz_create_model({ template_id, timelines })` (sources,
staged transactions and mapping rules copied; connector credentials excluded),
or apply one as a module into an existing model with
`layerz_build_from_blueprint({ template_id, mode: "merge" })`. The template is
never modified. Then adapt the new model (list contents via `layerz_patch`,
timeline bounds) and update its own FINANCE.md so its objective and
conventions match the project.

## 10. Checks, health and broken DAGs

A **check** flags an `assumption` or `formula` as a control (`check: {}`,
`check: { tolerance: 0.01 }`, `check: null` removes it). The line is judged on
its own value: an amount passes when `ABS(value) < tolerance` (default 1); a
boolean formula (comparison / AND / OR / NOT) passes when true. Values are
rounded to 2 decimals and empty periods read 0 (write `>= 0` rather than
`> 0` for a line legitimately empty early on). A failing check never blocks a
write. After a patch, `layerz_read { health: true }` reports every violation
in one call. The verdict is judged on a branch checkout, the view the user
sees: pass `branch_id` to audit one
branch (the same basis as `v`), or read `health.by_branch` on a multi-branch
model, where `health.branch_id` names the branch the top-level verdict is for.

On `computable: false` (a cycle, a `#REF!`), every series is zero-filled and
`health.status` is `unknown`: run `layerz_validate_model` for the cycle path
and fix the DAG before reasoning on values.

`layerz_validate_model` and `layerz_build_from_blueprint` also return
`quality`: at most five hints, most severe first, on what a reviewer flags
before any figure (a formula rolling its own previous value instead of a
balance, a balance without flows, balances without a check line, a dashboard
without KPI, a month written in a name, a model of typed values). Fix them
before handing the model over. The dashboards a blueprint declares get a
default layout where it says nothing (2 or 3 KPIs share the row, a mini-table
spans the width, a KPI compares with the model's only budget branch): send
`span` / `compare_to` only to override.

## 11. Versions

Every persist writes a snapshot; `revision_id` (sha256) on `layerz_read` /
`layerz_get_model` / `layerz_history` detects concurrent writes (a stable id
between two reads = unchanged). `layerz_history { uid }` traces one item's
changes; `layerz_diff` compares two revisions (omit `to` for the live model);
`values: true` adds the computed-values diff: the cells that moved on the
key lines (checks, totals) or on `uids`: the way to verify a refactor is
neutral on the numbers; `layerz_patch { dry_run: true, compare_values: true }`
previews the same report before applying a batch.
Read the history and the diff before `layerz_manage_version { op: "restore" }`
(the live state is backed up first); `op: "pin"` keeps a version past the plan
retention window. A no-op patch creates no version. A patch retried after a
timeout re-applies its `create` ops (new UIDs): read the history first.

## 12. Rebuilding a workbook

The target is the same results as the source, not the same cells. A
workbook spells a model out cell by cell; the same work in Layerz primitives is
an order of magnitude smaller (a restructuring workbook of 11 sheets rebuilds
in about 600 items, identical to Excel in every scenario).

| Excel construction | Layerz primitive |
|---|---|
| A block of rows repeated per creditor, client or case | One list-mode line on a list (§ 5) |
| Groups of rows summed | `mapped_to` on the list, `Item[\`Group\`]` |
| A selector cell read by `CHOOSE`, `INDEX` or `IF` | Branches overriding the selector's input (§ 7) |
| A table whose columns are metrics, not periods | Constant list-mode items, or a mini-table on the list |
| A monthly row that switches to reading the yearly column | A cross-grain reference under `IF(CURRENT_PERIOD >= …)`, or `YTD` |
| Guards (`IFERROR`, `ISNUMBER`, `NA()`) | Nothing: the formula language has no error values |
| Computed dates (`EDATE`, `EOMONTH`) | The timeline and `CURRENT_PERIOD` |

- **A value is not always an input.** A pasted or frozen block that the
  workbook computed elsewhere (a macro output, a data table, a copied
  scenario) is a result: rebuild the rule that produced it. A constant that
  changes between scenarios is a rule, not an input.
- **The import map.** `layerz_parse_file` (`workbook`) and the result of
  `layerz_create_model { file_id }` (`import.structures`) list the scenario
  selectors with their scenarios, the value lines that hide a scenario rule,
  the pasted results, the two-regime rows and the lists.
- **Slice by slice.** Build one statement or schedule, then compare its key
  lines with the source recalculated in every scenario before moving on:
  `layerz_diff { source: { set: { "Sheet!D16": 1 } }, branch_id }` computes the
  model on the scenario's branch and the workbook with the selector set
  (`source.refs` links a rebuilt line to its source range).
  `layerz_patch { dry_run: true, compare_values: true }` previews the numbers
  a batch moves.
- **Keep the objective honest.** The FINANCE.md states what the model computes,
  not that it replicates the workbook cell for cell.

## 13. Patch examples

### tab order: a dashboard first, a section placed after the P&L, a tab moved

```json
{
  "ops": [
    {
      "op": "create",
      "role": "dashboard",
      "name": "Summary",
      "id": "_sum",
      "before": "dsh00001"
    },
    {
      "op": "create",
      "role": "section",
      "name": "Inventory",
      "after": "sec00001"
    },
    {
      "op": "move",
      "uid": "sec00003",
      "before": "sec00002"
    }
  ]
}
```

### section with children via temp id

```json
{
  "ops": [
    {
      "op": "create",
      "role": "section",
      "name": "P&L",
      "id": "_pl"
    },
    {
      "op": "create",
      "role": "assumption",
      "name": "Revenue",
      "parent": "_pl",
      "timeline_ref": "monthly",
      "value": 1000
    },
    {
      "op": "create",
      "role": "formula",
      "name": "Gross Margin",
      "parent": "_pl",
      "formula": "Revenue - COGS"
    }
  ]
}
```

### nested section (true sub-section, no computed value)

```json
{
  "ops": [
    {
      "op": "create",
      "role": "section",
      "name": "Revenue",
      "id": "_rev"
    },
    {
      "op": "create",
      "role": "section",
      "name": "Subscription",
      "parent": "_rev",
      "id": "_sub"
    },
    {
      "op": "create",
      "role": "assumption",
      "name": "MRR",
      "parent": "_sub",
      "timeline_ref": "monthly",
      "value": 50000
    }
  ]
}
```

### atomic swap via replace

```json
{
  "ops": [
    {
      "op": "replace",
      "from_uid": "rev12345",
      "new_item": {
        "role": "formula",
        "name": "Revenue",
        "formula": "price123 * vol123"
      }
    }
  ]
}
```

### stock-flow: balance with flow callup

```json
{
  "ops": [
    {
      "op": "create",
      "role": "balance",
      "name": "Cash EoP",
      "opening_balance": 1500000,
      "id": "_cash"
    },
    {
      "op": "create",
      "role": "formula",
      "name": "Net Cash Change",
      "formula": "Operating CF + Investing CF + Financing CF",
      "timeline_ref": "monthly",
      "id": "_flow"
    },
    {
      "op": "create",
      "role": "callup",
      "name": "Net Cash Change",
      "source": "_flow",
      "parent": "_cash"
    }
  ]
}
```

### list-mode: assumption keyed by RH function

```json
{
  "ops": [
    {
      "op": "list_create",
      "name": "Functions",
      "items": [
        {
          "label": "Engineering"
        },
        {
          "label": "Sales"
        },
        {
          "label": "G&A"
        }
      ]
    },
    {
      "op": "create",
      "role": "assumption",
      "name": "Salaries by Function",
      "timeline_ref": "yearly",
      "liste_ref": "Functions",
      "timeline_values": {
        "Engineering": [
          1200000,
          1500000
        ],
        "Sales": [
          800000,
          950000
        ],
        "G&A": [
          400000,
          420000
        ]
      }
    }
  ]
}
```

### balance-list: debt tranches roll-forward

```json
{
  "ops": [
    {
      "op": "list_create",
      "name": "Debt Tranches",
      "items": [
        {
          "label": "Senior"
        },
        {
          "label": "Mezzanine"
        }
      ]
    },
    {
      "op": "create",
      "role": "balance",
      "name": "Debt Outstanding",
      "liste_ref": "Debt Tranches",
      "timeline_values": {
        "Senior": [
          10000000
        ],
        "Mezzanine": [
          3000000
        ]
      },
      "id": "_debt"
    },
    {
      "op": "create",
      "role": "formula",
      "name": "Drawdowns",
      "timeline_ref": "yearly",
      "liste_ref": "Debt Tranches",
      "timeline_values": {
        "Senior": [
          500000,
          0
        ],
        "Mezzanine": [
          0,
          200000
        ]
      },
      "parent": "_debt"
    },
    {
      "op": "create",
      "role": "formula",
      "name": "Repayments",
      "timeline_ref": "yearly",
      "liste_ref": "Debt Tranches",
      "timeline_values": {
        "Senior": [
          -300000,
          -300000
        ],
        "Mezzanine": [
          0,
          -100000
        ]
      },
      "parent": "_debt"
    }
  ]
}
```

### cohorts: retention via LIST_INDEX + variable lag

```json
{
  "ops": [
    {
      "op": "list_create",
      "id": "_cohorts",
      "name": "Cohorts",
      "items": [
        {
          "id": "_c1",
          "label": "Jan 26"
        },
        {
          "id": "_c2",
          "label": "Feb 26"
        },
        {
          "id": "_c3",
          "label": "Mar 26"
        }
      ]
    },
    {
      "op": "create",
      "id": "_curve",
      "role": "assumption",
      "name": "RetentionCurve",
      "timeline_ref": "monthly",
      "values": [
        1,
        0.8,
        0.65,
        0.52
      ]
    },
    {
      "op": "create",
      "id": "_age",
      "role": "formula",
      "name": "CohortAge",
      "liste_ref": "_cohorts",
      "timeline_ref": "monthly",
      "formula": "LIST_INDEX"
    },
    {
      "op": "create",
      "id": "_new",
      "role": "assumption",
      "name": "New Customers",
      "liste_ref": "_cohorts",
      "timeline_ref": "constant",
      "timeline_values": {
        "_c1": [
          120
        ],
        "_c2": [
          140
        ],
        "_c3": [
          160
        ]
      }
    },
    {
      "op": "create",
      "role": "formula",
      "name": "Active Customers",
      "liste_ref": "_cohorts",
      "timeline_ref": "monthly",
      "formula": "`New Customers`[i] * RetentionCurve_M-$CohortAge"
    }
  ]
}
```

### scenario overlay: write one value on a branch (no data source)

```json
{
  "ops": [
    {
      "op": "update",
      "uid": "tick1234",
      "timeline_values": {
        "2027": [
          1.1
        ]
      }
    }
  ]
}
```
