# Blueprint and patch

> The two ways an agent writes a Layerz model, a blueprint to build whole sections in one validated pass and a patch for incremental edits, with examples.

## Building and editing

- **`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.

## 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).

## Patch examples

Each example below is validated against the patch schema by the test suite.

### 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
        ]
      }
    }
  ]
}
```
