# Composition Plan JSON Reference

## 1. Purpose

`easycatalog-composition-plan/1` is the portable, versioned form of a
composition plan. It contains declarative structure and references to named
EasyCatalog resources. All data-dependent decisions are stored as declarative
expressions in the document; validation and import do not accept separately
bound ExtendScript callbacks.

This reference covers accepted JSON and observable composition behaviour only.
Implementation types, functions and source architecture are intentionally out
of scope.

Use JSON when a plan is generated by another tool, stored as configuration, or
created from an AI-facing composition manifest.

JSON property names use lower camel case, for example `asset`, `autoFitVertically`, `
minimumHeight`, `overflow` and `onEmpty`.

## 2. Obtain the live grammar

```javascript
var manifestText = session.ecCompositionManifest();
var manifest = eval("(" + manifestText + ")");
```

ExtendScript may not provide `JSON.parse`, so `eval("(" + text + ")")` is the
compatible parsing pattern for trusted plugin-generated JSON.

The `easycatalog-composition-manifest/1` manifest reports the accepted plan
schema and property vocabulary, formatting rules and their settings, rule
sets, document geometry and margins, parent/master names, and a bounded data
ecSnapshot. Generate plans against the manifest produced by the current build.

## 3. Top-level document

Only `schema`, `constants`, `components`, `initialParent`, `layoutPattern`, `furniture`, `adornments`,
`continuation`, `threadCoordination`, `layoutOptimization`, `constraintGroups`,
`threads` and `finalAlignment` are valid at the root. `constants` and
`components` are expanded before the native plan is validated:

```json
{
  "schema": "easycatalog-composition-plan/1",
  "initialParent": "A-Parent",
  "layoutPattern": {
    "columns": 2,
    "columnGutter": 12,
    "readingOrder": "document"
  },
  "furniture": [
    {
      "type": "formattingRule",
      "name": "page-header",
      "asset": "Page Header",
      "deleteIfAreaEmpty": true,
      "data": { "source": "selectionRoot" },
      "propertyResolver": {
        "asset": {
          "if": {
            "condition": { "equals": [{ "context": "continuation" }, true] },
            "then": "Page Header Continued",
            "else": "Page Header"
          }
        }
      }
    }
  ],
  "continuation": {
    "parentSelector": {
      "if": {
        "condition": { "equals": [{ "context": "pageSide" }, "left"] },
        "then": "B-Left",
        "else": "B-Right"
      }
    }
  },
  "threads": [
    {
      "name": "content",
      "start": "continue",
      "direction": "top to bottom",
      "gutter": 6,
      "crossAxis": "stretch",
      "content": []
    }
  ]
}
```

`initialParent`, `layoutPattern`, `furniture`, `adornments`, `continuation`,
`threadCoordination`, `layoutOptimization`, `constraintGroups` and
`finalAlignment` are optional. The root
`layoutPattern` defines the initial plan geometry. It accepts the same columns,
rows, explicit areas, final-region policy and reading-order members as a flow
body region's `layoutPattern`.

`initialParent` is an optional non-empty parent name for document pagination.
Use `continuation.parentSelector` to choose the parent for subsequent pages, for example:

```json
{
  "initialParent": "A-Parent",
  "continuation": {
    "parentSelector": { "literal": "B-Parent" }
  }
}
```

A furniture entry is a `formattingRule` section attached to the initial layout
area. It uses the normal section properties, data selector,
`propertyResolver` and `when` selector. Furniture is
recreated for continuation areas and does not belong to a plan thread.

`deleteIfAreaEmpty` is an optional boolean accepted only on root furniture
entries. Its default is `false`. When enabled, that furniture occurrence is
removed if the physical area commits no ordinary plan content.
This prevents a header being left behind when a page or container cannot fit
the next body item. Furniture and adornments do not themselves make an area
non-empty, and furniture entries without the option are retained.

An `adornments` entry is a formatting-rule section placed after ordinary
content completes in a physical layout area. `target` is `content` by default
or `area`; `insets` and `outsets` are mutually exclusive four-value point
arrays in top, left, bottom, right order; and `zOrder` is `behind` by default
or `inFront`. The asset must produce exactly one root page item, which is moved
and resized to the resolved rectangle without consuming layout space.

`continuation.parentSelector` can be a declarative selector expression. The
expression is evaluated as part of the plan and requires no ExtendScript
callback.

For a composition plan stored on a physical, threadable EasyCatalog container,
`continuation.container` can extend the container thread after every authored
linked container has been used and the tail remains incomplete:

```json
{
  "continuation": {
    "parentSelector": {
      "switch": {
        "value": { "field": "PageType" },
        "cases": [
          { "when": "Products", "return": "A-Products" },
          { "when": "Editorial", "return": "B-Editorial" }
        ],
        "default": "A-Default"
      }
    },
    "container": {
      "extend": "page",
      "size": { "source": "first" },
      "position": {
        "relativeTo": "spine",
        "insideOffset": 18,
        "top": 36
      },
      "maximumCreated": 100
    }
  }
}
```

`extend` is required and is `page` or `spread`. Existing linked containers are
composed first. If the final thread member remains
incomplete, it inserts the requested parent, applies the parent selected from
the first still-pending data node, creates an empty continuation container,
links it to the previous tail, and lets normal root-thread recomposition
continue into it.

`size` defaults to `{ "source": "first" }`, using the first physical
container's current width and height. It may instead be
`{ "width": number, "height": number }`, with positive point values.

`position` defaults to `{ "source": "first" }`, preserving the first
container's offset within its page or spread. Page continuations may use
`{ "relativeTo": "spine", "insideOffset": number, "top": number }`.
On a left page the container's right edge is placed `insideOffset` points from
the spine; on a right page its left edge is placed that distance from the
spine. Page- and spread-relative positions use
`{ "relativeTo": "page|spread", "left": number, "top": number }`.
Spine-relative positioning requires `extend: "page"`.

`maximumCreated` is an integer from 1 to 1000 and defaults to 100. It bounds
automatic continuation growth and prevents an unplaceable item from producing
an unlimited document. The physical container must already have its normal
Threadable property enabled; the plan does not duplicate that property.

`continuation.layoutPatternResolver` can change named-area geometry as threads
finish. Cases are evaluated in order and match the exact set of thread names
which still have content. When no case matches, the initial root pattern is
repeated:

```json
{
  "continuation": {
    "layoutPatternResolver": {
      "cases": [
        {
          "remainingThreads": ["sidebar-content"],
          "layoutPattern": {
            "name": "full-width-sidebar",
            "areas": [
              { "name": "sidebar", "bounds": [0, 0, 1, 1] }
            ]
          }
        }
      ]
    }
  }
}
```

Already-created named areas are consumed before a new continuation parent is
created. Thus an independently flowing sidebar first uses the sidebar areas on
pages created by the main thread, then expands only after those pages are
exhausted and the main thread has completed.

Coupled named-area plans may set `completedThread` to `"reserve"` (the
default) or `"reclaim"`. Reclaim mode requires a layout-pattern resolver.
Coupled threads advance in lockstep by physical area, so the exact remaining
thread set is known before the next container, page or spread is configured.
When a stored container plan resumes, its persistent thread cursors are restored
before the replacement pattern is selected; it does not depend on a Data View.

`layoutOptimization` enables bounded, deterministic selection when more than
one resolver case has the same `remainingThreads` set:

```json
{
  "layoutOptimization": {
    "mode": "bounded",
    "lookAhead": 4,
    "maximumBacktracks": 1,
    "scope": "page",
    "score": {
      "areaCount": 1000,
      "unusedArea": 1,
      "raggedness": 2,
      "overflow": 10000,
      "deferredItems": 100
    }
  }
}
```

`lookAhead` is an integer from 1 to 32. It limits both the number of matching
pattern candidates examined and the number of upcoming sections used to
estimate each thread's remaining record demand. `maximumBacktracks` is from 0
to 8; it limits alternative-pattern retries and supplies the default retry
budget for named constraint groups. `scope` is `"area"`, `"page"` or
`"spread"` and supplies the default placement scope for those groups. All score
weights are non-negative, and lower total scores win. Candidate ties retain
declaration order. Without `layoutOptimization`, the resolver selects the
first matching case.

`layoutOptimization` also allows eligible ordered content to be split at legal
boundaries using its measured size, available capacity and continuation cost.
Vertical tables are currently supported. Their measurements preserve multi-row
records and prototype elements and include continued-subheader and
fragment-footer space. All linked table frames must currently have the same
usable width. If they differ, the complete thread cannot be measured, or no
bounded solution fits, the table uses normal InDesign flow.

Thread values are:

- `start`: `continue` or `new area`.
- `direction`: `top to bottom` or `left to right`.
- `gutter`: a non-negative point value.
- `crossAxis`: `start`, `center`, `end` or `stretch`.

### 3.1 Local constants

`constants` declares named, plan-local JSON values. A reference of the form
`{ "$constant": "name" }` replaces one complete JSON value. Constant
substitution runs before component expansion and normal plan validation.

```json
{
  "schema": "easycatalog-composition-plan/1",
  "constants": {
    "premiumCellCss": "topleftdiagonalline: true; toprightdiagonalline: true;",
    "iconColumnWidth": 7,
    "singleRecord": {
      "source": "selectionRoot",
      "result": "children",
      "shape": { "scope": "records", "limit": 1 }
    }
  },
  "threads": [
    {
      "name": "catalogue",
      "content": [
        {
          "type": "formattingRule",
          "name": "introduction",
          "asset": "Introduction",
          "data": { "$constant": "singleRecord" }
        }
      ]
    }
  ]
}
```

A constant may be a string, number, boolean, object, array or `null`. Constants
may reference other constants. Unknown names, cycles, empty constant names and
references containing members in addition to `$constant` are validation
errors. References replace complete values; interpolation inside strings is not
supported. Constants are compile-time values and do not create runtime data
bindings. Use `data.source: "variable"` for a record or group bound by a
runtime construct such as `forEach`.

Constants are expanded inside component definitions as well as the rest of the
plan, so a component parameter default or template may use `$constant`.

### 3.2 Local reusable components

`components` declares plan-local, compile-time templates. Components reduce
repetition in generated plans without adding a runtime section type or a new
data-variable scope. Every component is expanded before normal plan validation
and import.

```json
{
  "schema": "easycatalog-composition-plan/1",
  "components": {
    "productCard": {
      "parameters": {
        "assetName": { "type": "string", "required": true },
        "sourceName": { "type": "string", "default": "product" },
        "keep": { "type": "boolean", "default": false }
      },
      "template": {
        "type": "formattingRule",
        "name": "product-card",
        "asset": { "$parameter": "assetName" },
        "data": {
          "source": "variable",
          "name": { "$parameter": "sourceName" },
          "result": "self"
        },
        "keepWithNext": { "$parameter": "keep" }
      }
    }
  },
  "threads": [
    {
      "name": "catalogue",
      "content": [
        {
          "$component": "productCard",
          "arguments": {
            "assetName": "Product Card",
            "sourceName": "product"
          },
          "overrides": {
            "name": "featured-product-card",
            "required": true
          }
        }
      ]
    }
  ]
}
```

A component definition contains:

- `parameters`: an optional object of named parameter contracts.
- `template`: a required object or array. An array invocation is flattened
  when it appears as an element of another array, allowing a component to
  insert several adjacent sections.

A parameter contract accepts `type`, `required` and `default`. Supported types
are `any`, `string`, `number`, `boolean`, `object`, `array` and `null`.
Arguments not declared by the component are rejected. A missing required
parameter is rejected; a missing optional parameter without a default expands
to JSON `null`.

`{ "$parameter": "name" }` replaces the complete JSON value at that point.
It must be the only member of its object. There is deliberately no parameter
interpolation inside strings, so generated plans remain type-safe and
unambiguous.

An invocation contains `$component`, optional `arguments`, and optional
`overrides`. Overrides are applied after parameter substitution and nested
component expansion. Objects merge recursively; arrays and scalar values
replace the component value. Overrides require an object template.

Components may invoke other local components. Cycles are rejected and nesting
is limited to 32 component expansions. Components exist only in the document
that declares them; JSON v1 does not import external component libraries.

### 3.3 Grouped catalogue flows

`groupFlow` is a JSON v1 authoring construct for the common catalogue pattern
of nested record groups, repeating hierarchy headers and one terminal content
section. It expands into `forEach` and `flow` sections before contract
validation.

```json
{
  "type": "groupFlow",
  "name": "category-tables",
  "data": {
    "source": "selectionRoot",
    "result": "children",
    "shape": {
      "scope": "records",
      "sort": [
        { "field": "Category1" },
        { "field": "Category2" },
        { "field": "Category3" },
        { "field": "Product" }
      ]
    }
  },
  "layoutPattern": {
    "name": "three-columns",
    "columns": 3,
    "columnGutter": 12
  },
  "groups": [
    {
      "name": "category1",
      "field": "Category1",
      "header": {
        "type": "formattingRule",
        "name": "category1-heading-{index1}",
        "asset": "Category 1 Heading",
        "continuedAsset": "Category 1 Heading Continued"
      }
    },
    {
      "name": "category2",
      "field": "Category2",
      "header": {
        "type": "formattingRule",
        "name": "category2-heading-{index1}",
        "asset": "Category 2 Heading",
        "continuedAsset": "Category 2 Heading Continued"
      }
    },
    { "name": "category3", "field": "Category3" }
  ],
  "itemData": "self",
  "item": {
    "type": "textFrame",
    "name": "category3-table-{index1}",
    "asset": "Category 3 Table",
    "autoFitVertically": true,
    "threadable": true,
    "overflow": "continue"
  }
}
```

`data` is a normal selector, but its optional `result` must be `children`.
The ordered `groups` array defines the equivalent `shape.group` operation, and
the shape scope defaults to `records`. Supplying both `groups` and
`data.shape.group` is rejected so the generated hierarchy has one unambiguous
definition.

Every group requires `name`, the stable data-variable name used by its
generated `forEach`, and `field`, the field used to construct that grouping
level. `flowName` optionally replaces the generated
`<name>-flow-{index1}` name.

A group may set `direction`, `gutter`, `horizontalGutter` and
`verticalGutter`; these are copied to its generated body region. `gutter` is a
shorthand that sets both axes, while either axis-specific value
overrides only that axis. In a top-to-bottom body the vertical gutter separates
successive items; in a left-to-right body the horizontal gutter does so. A
gutter is applied only when another section has already committed in the same
physical area, so it is suppressed at the top or left of every new column,
page, or linked container. Layout-pattern `columnGutter` and `rowGutter` remain
the spacing between the physical regions themselves.

A group may contain a compact `header` or `footer` section, a section array, or
a normal region object containing `sections`. `layoutPattern` applies to that
group's generated body region. Intermediate levels always generate flows so
they can contain the next `forEach`; a terminal level without furniture or a
layout pattern expands directly to `item`.

For a section inside a `groupFlow` header, footer or terminal `item`, an omitted
`name` defaults to its non-empty string `asset`. An explicitly supplied `name`
remains authoritative. Sections without a usable string `asset` must still
supply the ordinary non-empty `name` required by the section contract. The
`groupFlow` itself has no asset and therefore still requires its own `name`.

Group headers inherit the current group as `data`, with `result: "self"`, and
default to `repeat: "every area"`. `continuedAsset` is an optional non-empty
formatting-rule name. It expands to the ordinary declarative continuation
asset resolver and therefore cannot be combined with `propertyResolver.asset`
or another declarative property expression.

The terminal `item` inherits the final group when it has no explicit `data`.
`itemData` selects `"children"` (the default) or `"self"`. An explicitly
declared item data selector remains authoritative.

The grouped flow itself may contain compact `header` and `footer` values plus
an outer `layoutPattern`. Ordinary flow policies such as `onEmpty`, breaks,
keeps, predicates and document leaves are copied to the expanded outer flow.

## 4. Data selectors

JSON cannot contain live `ecDataNode` objects. A `data` member therefore
contains a selector object.

Selection root or its children:

```json
{ "source": "selectionRoot", "result": "self" }
```

```json
{ "source": "selectionRoot", "result": "children" }
```

Named groups are collected into a result root that preserves the Data View and
product-wrapper hierarchy:

```json
{
  "source": "selectionRoot",
  "collector": "collectNamedGroups",
  "name": "Code discount",
  "recursive": true,
  "includeSelf": false,
  "leafOnly": false,
  "maximumDepth": -1,
  "result": "self"
}
```

Use `result: "children"` to return each matching group separately. The `name`
is optional for `collectNamedGroups`.

Enhanced-tabular roots use:

```json
{
  "source": "selectionRoot",
  "collector": "collectNamedTabularFields",
  "name": "Features",
  "includeEmpty": false,
  "result": "children"
}
```

`includeEmpty` defaults to `true`. Set it to `false` when records whose
enhanced-tabular field has a row count of zero must not produce a collected
node. A section using `onEmpty: "omit"` will then be omitted when no non-empty
tabular occurrence remains.

References stored in an ordinary field can be resolved back to record
wrappers with `collectReferencedRecords`. References are split in field order,
resolved in that same order, and cloned into a transient root:

```json
{
  "source": "variable",
  "name": "product",
  "collector": "collectReferencedRecords",
  "field": "RelatedProductIDs",
  "delimiter": ",",
  "target": {
    "source": "selectionRoot",
    "keyField": "ID"
  },
  "missing": "ignore",
  "includeSelf": false,
  "distinct": true,
  "result": "children",
  "shape": { "limit": 4 }
}
```

`target.source` controls the boundary of the lookup:

- `selectionRoot` searches only records in the immutable original selection.
- `selectionDataSource` searches every display record in the data source that
  owns the original selection.
- `dataSource` searches another EasyCatalog data source and requires its exact
  `name` alongside `keyField`.

`delimiter` defaults to `,`; `includeSelf` defaults to `false`; `distinct`
defaults to `true`; and `missing` is `ignore` or `error` (default `ignore`).
An optional `shape` runs after reference resolution. This collector does not
perform a relational query and never expands a `selectionRoot` lookup beyond
the initial selection.

A `forEach` template can refer to its current item:

```json
{ "source": "variable", "name": "group", "result": "self" }
```

When a variable selector also applies a collector, use `variable` for the
iteration-variable name and reserve `name` for the group or field being
collected:

```json
{
  "source": "variable",
  "variable": "category1",
  "collector": "collectNamedGroups",
  "name": "Category2_name",
  "result": "children"
}
```

A node-ID selector is reserved for host integrations that supply a stable
node-snapshot resolver. The current native JSON compiler has no such resolver
and rejects this form; use `selectionRoot` or a bound `variable` in plans
imported through the current scripting or Pagination UI:

```json
{ "source": "node", "id": "node-id", "result": "self" }
```

### 4.1 Explicit data shaping

Every selector may contain an optional `shape` object. Shaping runs after a
collector, if present, and before `result` returns the result root or its
children. It never changes the selection or the source DSV hierarchy; the
selected wrappers are cloned into a transient root.

For example, this selects records which are not discontinued, sorts them by
brand and then numeric price, and keeps the first 50:

```json
{
  "source": "selectionRoot",
  "result": "children",
  "shape": {
    "scope": "records",
    "where": {
      "field": "Discontinued",
      "operator": "equals",
      "value": false,
      "compareAs": "boolean",
      "missing": "exclude"
    },
    "sort": [
      { "field": "Brand", "direction": "ascending" },
      { "field": "Price", "direction": "ascending", "missing": "last" }
    ],
    "limit": 50
  }
}
```

`scope` is `children` by default. `records` recursively flattens product and
relational-record descendants before applying the operations. Operations run
in this fixed order: `where`, `distinct`, `sort`, `offset`/`limit`, then
`group`.

A leaf condition has this shape:

```json
{
  "field": "Price",
  "operator": "greaterThanOrEqual",
  "value": 10,
  "compareAs": "number",
  "valueSource": "raw",
  "caseSensitive": false,
  "missing": "exclude"
}
```

Supported operators are `equals`, `notEquals`, `lessThan`,
`lessThanOrEqual`, `greaterThan`, `greaterThanOrEqual`, `contains`,
`startsWith`, `endsWith`, `in`, `isEmpty` and `isMissing`. Combine conditions
with `{ "all": [...] }`, `{ "any": [...] }` or `{ "not": {...} }`.
`compareAs` is `auto`, `text`, `number` or `boolean`; `valueSource` is `raw`
or `formatted`. Filter `missing` policy is `exclude`, `include` or `error`.
Defaults are `compareAs: "auto"`, no explicit `valueSource`,
`caseSensitive: false` and `missing: "exclude"`.

Automatic filtering uses the same resolved EasyCatalog comparison as sorting
and grouping. Numeric and date/time fields use their underlying value. A
string literal for either type is interpreted using the field's definition, so
numeric separators and the configured date input format are honoured; a JSON
number is treated as an underlying numeric value.
Textual fields use formatted content when available, otherwise raw content,
and their configured linguistic language. Without a configured language,
EasyCatalog's default text comparison is used and honours `caseSensitive`.
Explicit `compareAs` or `valueSource` values retain their requested
interpretation. Substring operators remain textual substring tests.

Sorting is a stable array of keys. Each key supports `field`, `direction`,
`compareAs`, `valueSource`, `caseSensitive` and `missing`. Direction is
`ascending` or `descending`; missing values are `first`, `last` or `error`.
Defaults are ascending, `compareAs: "auto"`, no explicit `valueSource`,
case-insensitive fallback text and missing values last. Missing-value position
is independent of direction.

Automatic sorting follows the EasyCatalog field definition. Numeric and
date/time fields compare their underlying values. Textual fields compare
formatted content when available, otherwise raw content, and use the field's
configured language for collation. Without a configured language,
EasyCatalog's default text comparison is used. `caseSensitive` applies only to
that default comparison because a configured language controls its own
collation. Supplying `compareAs` or `valueSource` explicitly overrides type or
content-source selection, but a textual field's configured language still
controls text collation.

All non-missing values for one automatic sort key must resolve to compatible
EasyCatalog field types and textual languages. An incompatible definition or
an unavailable configured language is a data-resolution error before sorting,
rather than silently producing a different order.

Distinct selection uses:

```json
"distinct": {
  "fields": ["SKU"],
  "keep": "first",
  "caseSensitive": false,
  "missing": "error"
}
```

`keep` is `first` or `last` and defaults to `first`. Missing keys may `collapse`
into one key (the default), remain `separate`, or cause an `error`. Each
distinct field uses the same automatic typed equality as filtering, sorting
and grouping: numeric/date keys use their underlying value and textual keys
use formatted content when available, otherwise raw content, plus their
configured language. Text without a language uses EasyCatalog's default text
comparison and honours `caseSensitive`. `offset` and `limit` are non-negative
integer record counts; offset defaults to zero and an omitted limit is
unbounded.

Grouping creates group nodes while preserving the requested
record order within each group:

```json
"group": [
  { "field": "Brand", "missingLabel": "Unbranded" },
  { "field": "Category" }
]
```

A grouping field must exist. Empty values are valid grouping keys and form an
empty-named group, matching an EasyCatalog grouped Data View. `missingLabel`
optionally replaces that empty value in the cloned data.

Grouping equality follows the same EasyCatalog field semantics as automatic
sorting. Numeric and date/time keys compare their real value. Textual keys use
formatted content when available, otherwise raw content, and the linguistic
comparison for the language configured in the field's text options. Without a
configured language, EasyCatalog's default text comparison is used. Values
considered equal by that comparison form one group; the first encountered value
supplies its displayed group value. Groups retain first-occurrence order, and
records retain their existing order within each group. Incompatible field types
or languages and unavailable configured languages are data-resolution errors.

## 5. Sections

Public section types are `masterPage`, `formattingRule`, `float`, `container`, `templateContainer`,
`textFrame`, `textFlow`, `table`, `fillSection`, `gridFill`, `gridSequence`,
`flow` and `fitAlternatives`. Section properties are direct members of the section object; there
is no nested `properties` object.

```json
{
  "type": "textFrame",
  "name": "records",
  "data": { "source": "variable", "name": "group" },
  "asset": "Table",
  "autoFitVertically": true,
  "threadable": true,
  "overflow": "continue"
}
```

Every section requires `type` and `name`. `data`, `propertyResolver` and `when`
are optional. Supported section properties use the unprefixed JSON names
reported by the current composition manifest.

Important enums include:

- `compositionMode`: `place`, `insert`, `compose`.
- `textFlowInsertion`: `contents`, `anchored`; valid only on a direct
  `formattingRule` contributor of a `textFlow`.
- `repeat`: `once`, `every area`, `first area`, `last area`; flow headers
  additionally support `every page` and `every spread`.
- `overflow`: `continue`, `fail`, `clip`.
- `onEmpty`: `omit`, `retain`, `error`.
- `breakBefore`, `breakAfter`: `auto`, `area`.
- `fillDirection`: `horizontal`, `vertical`, `across down` (`across down`
  uses the same left-to-right, then top-to-bottom placement as `horizontal`).
- `horizontalAlignment`: `left`, `right`, `center`, `justify`, `justify left`,
  `justify center`.
- `verticalAlignment`: `top`, `bottom`, `center`, `justify`, `justify top`,
  `justify center`.
- `anchorPoint`: `top left`, `top center`, `top right`, `middle left`,
  `middle center`, `middle right`, `bottom left`, `bottom center`,
  `bottom right`.

For a `formattingRule` section, horizontal and vertical alignment are applied
to the completed section fragment. An explicitly specified `anchorPoint`
instead selects the fragment's final two-dimensional position inside the
available area, so it takes precedence over both alignment properties. With
`assetForEach`, the objects are packed first and then positioned together as
one group. Each continuation area positions its own fragment independently.
For aggregate formatting-rule alignment, `justify` and its start-edge variants
use the corresponding start edge and `justify center` uses the centre; unlike a
physical container, the section does not redistribute inter-item gaps.

Geometry is in points. `bounds` is `[top, left, bottom, right]`.
For `textFrame` sections, `minimumWidth` and `minimumHeight` are checked before
the formatting rule is placed. If the remaining area cannot contain that
minimum size, the flow retries the section in its next area without creating a
frame in the current one.

A `textFlow` creates one story from several independently authored assets. Its
required `asset` is a geometry-only host containing exactly one text frame and
no table. The host does not accept `data` or `ruleSet`. Its non-empty `sections`
array accepts only ordered `formattingRule` and `table` contributors:

```json
{
  "type": "textFlow",
  "name": "product-story",
  "asset": "Product Story Host",
  "threadable": true,
  "overflow": "continue",
  "sections": [
    {
      "type": "formattingRule",
      "name": "summary",
      "asset": "Product Summary",
      "textFlowInsertion": "anchored",
      "data": { "source": "variable", "name": "product" }
    },
    {
      "type": "table",
      "name": "dimensions",
      "asset": "Dimensions Table",
      "data": { "source": "variable", "name": "dimensions" },
      "when": { "notEquals": [{ "field": "Width" }, ""] },
      "onEmpty": "omit",
      "table": { "mode": "vertical" }
    }
  ]
}
```

Each contributor keeps its own `asset`, `data`, `propertyResolver`, `when`,
`onEmpty` and `required` behaviour. A false `when` omits that contributor before
its asset is placed. Product Style actions may also delete a contributor while
populating it. If no replacement page item survives, the contributor is treated
as an empty result: `onEmpty: "error"` fails a required contributor, while the
other policies omit it because the action's deletion is authoritative. No
placement is counted and anchored insertion is not attempted.

A direct `formattingRule` contributor may set `textFlowInsertion` to `contents`
or `anchored`, either statically or through its `propertyResolver`. `contents`
is the default: the asset must contain exactly one text frame and the complete
donor story is copied into the host story, preserving text attributes, inline
objects and EasyCatalog links. `anchored` instead requires exactly one root page
item and inserts that complete populated item into the host story as one
InDesign anchored object using the standard inline position. It is inserted at
the contributor's ordered story position without adding a paragraph return.
An asset with several root items is rejected; author those items as one group
when they must form one anchor. An anchored object is atomic as it flows through
continuation frames and is not split between them.
`textFlowInsertion` is rejected on `table` contributors and on sections outside
this direct-child context.

Every table contributor must produce exactly one top-level table in the shared
story; nested tables generated inside its cells are content of that owned table
and do not become additional contributors. Its own table configuration finalizes
the top-level table after all continuation frames have been created. In
`contents` mode, a normal `formattingRule` contributor containing a top-level or
nested table is rejected so table ownership cannot be ambiguous. A table inside
an anchored page item remains opaque content of that anchor and is not managed
or finalized as a text-flow table. Contributor `assetForEach` is not supported;
emit one contributor for each ordered asset occurrence instead.

A `table` section extends `textFrame` with a `table` definition and requires a
formatting-rule asset whose single text story contains exactly one top-level
InDesign table prototype. The story may contain ordinary text and inline
content before and after the table. Those two regions are each populated once
from the section's resolved data node and then flow with the table through its
continuation frames. They are not repeated for every table record. The table
and its surrounding story are atomic: when empty-data handling omits the table,
the surrounding content is omitted as well. Its
`table.mode` is `vertical` (plan-managed records down rows), `horizontal`
(plan-managed records across columns), `easyCatalogVertical`, or
`easyCatalogHorizontal`. The explicit EasyCatalog modes use normal EasyCatalog
table population; the plan-managed modes materialize all resolved records
before placement. In plan-managed
`horizontal`, `headers.groups` produces merged group rows before the
corresponding field rows.

For plan-managed `vertical`, `table.structure` may be `generated` (the default)
or `authored`. `authored` copies and populates the formatting rule's existing
logical row prototypes without rebuilding its columns, InDesign header rows,
cell spans, field positions or formatting. A logical prototype may occupy
several physical rows when its cells are vertically spanned. Group rows still
use `subheaders` to identify the grouping field and their authored prototype.
`cellAttributes.fields` may override EasyCatalog cell attributes on a record
prototype cell containing the named linked field. `columns.byIndex` is an array
of column-attribute objects in the formatting rule's zero-based physical column
order. It does not inspect header text or require a linked field in the column.
`fields`, `headers`, `styles` and `overrides` are not accepted with
`structure: "authored"` because those members generate or alter table
structure.

Table group labels and per-field override labels accept either a non-empty
string or an enhanced label definition:

```json
{
  "label": {
    "content": "<img width='4mm' height='4mm'>DIMENSIONS (MM)",
    "fieldOptions": {
      "stylesheet": "Table Group Header",
      "css": "img { vertical-align: middle; }"
    }
  }
}
```

Generated labels default to Alphanumeric, Formatted and Enhanced HTML with CSS
enabled (`htmlflags` 8). Values in `fieldOptions` override those defaults.
String labels use the defaults with no overrides.

Plan-managed `vertical` and `horizontal` tables may add fields that are not
backed by EasyCatalog data by using `table.fields.generated`:

```json
{
  "fields": {
    "include": ["Product", "Price"],
    "generated": [
      {
        "name": "PremiumMarker",
        "position": { "after": "Price" },
        "text": {
          "when": {
            "greaterThan": [
              { "number": { "field": "Price" } },
              100
            ]
          },
          "content": "<img>",
          "fieldOptions": {
            "css": "img { width: 3mm; height: 3mm; fillcolor: #0000ff; }"
          }
        }
      }
    ]
  },
  "overrides": {
    "PremiumMarker": { "label": "Premium" }
  }
}
```

Every generated field requires a unique `name` and a `text` object containing
exactly one of `value` or `content`. `value` may be a declarative expression;
`content` uses the same enhanced-content and `fieldOptions` contract as a table
label. An optional `when` expression controls the content for each record. A
false condition leaves that record's cell empty. The generated field is placed
at the end unless `position` supplies exactly one non-empty `before` or `after`
field name. The position target must survive the table's field selection.

Generated fields participate in headers, header groups, field overrides,
column settings and cell attributes under their generated name. `exclude` may
remove one explicitly, and `removeEmpty: true` removes it when its text is empty
for every selected record. A generated field cannot shadow a real field or act
as a subheader grouping field. Its cells contain no EasyCatalog field link;
they are regenerated with the composition. The engine renders generated text
only after the complete logical record row, multi-row span or horizontal record
column has populated. Generated fields are not supported by
`easyCatalogVertical` or `easyCatalogHorizontal` population.

A field entry in `table.overrides` may supply `text` in plan-managed
`vertical` and `horizontal` tables:

```json
{
  "overrides": {
    "Price": {
      "text": {
        "operation": "append",
        "when": {
          "greaterThan": [
            { "number": { "field": "Price" } },
            100
          ]
        },
        "content": "&nbsp;<img>",
        "fieldOptions": {
          "css": "img { width: 3mm; height: 3mm; fillcolor: #0000ff; }"
        }
      }
    }
  }
}
```

`operation` is `prefix`, `replace`, or `append`; when omitted it defaults to
`replace`. Supply exactly one of `value` or `content`. `value` is a string or a
declarative expression resolving to a string or null. `content` is the
label-style enhanced-content form: a non-empty string accompanied by optional
`fieldOptions`. Those options have the same defaults and value types as table
labels, so HTML, CSS and image placeholders can use the normal text styler.
The optional `when` expression uses ordinary declarative truthiness; when it is
absent the operation always runs, and when it is false the populated cell is unchanged.
Text operations run only after the complete logical record row, multi-row
span, or horizontal record column has populated. Prefix and append preserve
the linked EasyCatalog field already in the cell. Replace deliberately removes
the populated cell contents. An empty replacement clears the cell.

A field entry in `table.overrides` may also supply `css`. A string is a static
cell property block; a declarative expression may return a different property
block for each record. CSS applies only to materialized body value cells in
plan-managed `vertical` and `horizontal` tables. The engine waits until the
complete logical record row, multi-row span, or horizontal record column has
been populated and its ordinary cell styles have been applied, then evaluates
and applies the CSS to each surviving anchor cell. Text overrides run before
CSS, so CSS observes the final cell contents. A null or empty result does
nothing. For example:

```json
{
  "overrides": {
    "Price": {
      "css": {
        "if": {
          "condition": {
            "greaterThan": [
              { "number": { "field": "Price" } },
              100
            ]
          },
          "then": "topleftdiagonalline: true; toprightdiagonalline: true;"
        }
      }
    }
  }
}
```

Plan-managed `vertical` tables additionally accept `table.subheaders`, an array
of `{ "field": "...", "prototypeRow": 0, "omitWhenSingle": true|false,
"prototypes": [{"value":"Office","prototypeRow":2,"bodyPrototypeRow":6}],
"keep":{"atStart":2,"atEnd":2},
"repeat": "once"|"every area"|{"mode":"every area","prototypeRow":1,
"prototypes":[{"value":"Office","prototypeRow":4}]},
"footer":{"prototypeRow":8,"prototypes":[{"value":"Office",
"prototypeRow":9}]},
"fragmentFooter":{"prototypeRow":10,"prototypes":[{"value":"Office",
"prototypeRow":11}]} }`
objects. They group record rows in stable
first-seen order and copy authored
group-row prototypes into the body. `prototypeRow` is a zero-based index within
the formatting rule's authored body rows; it needs no EasyCatalog row metadata,
takes precedence over `prototype`, and is excluded when the first remaining
body row is selected as the record prototype.

Existing EasyCatalog metadata is also supported: Row Type `Header`, Populate
With `Group`, and optional `prototype` matching the EasyCatalog Group Name. When
`omitWhenSingle` is absent, an available Allow Single Instances setting controls
whether a lone group row is retained; a plan-nominated row without that metadata
retains it by default. Native prototype row properties, including
keep-with-next, are preserved. `repeat` defaults to `"once"`; `"every area"`
copies the active subheader hierarchy to the start of each physical text-frame
column where its records continue. Existing subheaders at an area boundary are
not duplicated. Repetition is independent of `mergeScope`, although both use
the same composed-area stabilization pass.

`footer` is optional on every subheader level. It closes each emitted group
after that group's nested content and accepts `prototype`, `prototypeRow`, and
`prototypes:[{"value":"...","prototypeRow":n}]`. An omitted footer emits
nothing. With no explicit selector, authored Row Type `Footer`, Populate With
`Group` prototypes are assigned by level. Footer content and merges are copied
as authored; linked fields are populated from the final record in the group.
`omitWhenSingle` suppresses the opening subheader and its footer together.

`fragmentFooter` is optional and accepts `prototype`, `prototypeRow`, and
`prototypes:[{"value":"...","prototypeRow":n}]`; unlike the final `footer`, at
least one selector is required. It is inserted at the bottom of each physical
text-frame column only when the same group continues in the following fragment.
Its linked fields use the outgoing fragment's final record. Nested active
levels close inside-out. Each generated fragment footer is kept with its
preceding logical record, and pagination is retried until the footer remains in
the outgoing fragment. Reflow recreates generated rows from the formatting-rule
prototype.

Any header, repeat-header, final-footer, or fragment-footer `prototypeRow` that intersects a vertical
merge selects the complete connected authored row span as one logical element.
All spanned rows and their row/cell formatting, content, and merges are copied.
Different levels and exact values may therefore select independent multi-row
prototype elements.

Plan-managed vertical tables and individual subheaders accept a numeric row-keep
object: `"keep":{"atStart":3,"atEnd":2}`. The table-level object also accepts
`"mechanism":"controlColumn"|"rowKeepWithNext"`; it defaults to
`"rowKeepWithNext"` and governs table, subheader, repeated-header,
fragment-footer, and planned-fragment constraints. At table level, `atStart` keeps the
first number of body records together and `atEnd` keeps the final number
together; no subheaders are required. On a subheader, `atStart` keeps the
complete subheader element and that many following body records together,
while `atEnd` keeps the final number of records and optional footer element in
that group together. A subheader may also use
`"keep":{"together":"ifPossible","atStart":2,"atEnd":2}`. With bounded
global optimization, a complete group that fits an available physical area is
first treated as indivisible. Oversized groups retain the start/end splitting
rules. When the available area set cannot preserve every eligible group, the
planner minimizes the number of distinct groups split before considering its
normal weighted layout score. Counts skip nested subheader and footer rows, but the
protected span includes any such rows between the records. Overlapping
table, outer-group and nested-group constraints are
combined. `"mechanism":"controlColumn"` adds a minimum-width, empty control
column after all normal column sizing and
vertically merges its cells across each protected span. The authored
right-edge attributes remain on the last visible cells; no stroke overrides
are applied to the auxiliary control cells or their neighbours. The minimum
width, empty content and `None` fill keep the control cells visually inert,
and existing data-column widths are not reduced. With
`"mechanism":"rowKeepWithNext"`, the same boundary map is represented by
InDesign's row Keep with Next attribute instead, so no control column is
appended. In this mode composition owns and rewrites the body-row Keep with
Next values while it refines continuation furniture and fragment boundaries.
Repeated subheaders receive their `atStart` constraint during composed-area
stabilization and are always kept with at least the first complete following
record. A larger `atStart` count extends that protection; a count larger than
the available records protects the complete table or group. Both counts are
optional non-negative integers, and zero otherwise disables that side. Native
authored keep-with-next remains supported in addition to these numeric
constraints.

The object form of `repeat` selects a different authored row for continuation
subheaders. `mode` is `"once"` or `"every area"`; `prototypeRow` is valid with
`"every area"` and is a zero-based index in the formatting rule's authored body
rows. The nominated row remains available after table population, retains its
authored row and cell formatting and literal content, and populates linked
fields from the first record in the continuation fragment.

`prototypes` selects authored rows for exact displayed group values. It is
accepted both on the subheader and inside the object form of `repeat`; the
ordinary `prototypeRow` remains the fallback. Each entry requires a string
`value` and a non-negative authored-body `prototypeRow`. Values must be unique
within the array, compare exactly and may be empty. Every nominated row is
reserved as a prototype and cannot become the ordinary record prototype. A
top-level value entry may add `bodyPrototypeRow`, causing every record in that
group to use the nominated authored body row. A selected body row that
intersects a vertical cell merge resolves to the entire transitively connected
authored row span. That span is copied once per record as a logical record
element, retaining its row heights, cell merges, formatting, literal content
and linked fields; every linked field in the span is populated from the same
record. The same rule applies to a default authored record prototype, including
a vertical table without subheaders. A connected element cannot be split across
pagination fragments, and table or subheader keeps count logical records rather
than their physical rows. For nested subheaders, the
innermost matching body prototype wins. `bodyPrototypeRow` is deliberately not
supported inside `repeat`, whose prototypes select continuation subheaders only.

`footer.prototypes` and `fragmentFooter.prototypes` use the same exact string
matching and fallback rules, but their entries accept only `value` and
`prototypeRow`.

Body value cells may receive EasyCatalog cell attributes through
`table.cellAttributes`. `default` supplies inherited values and `fields`
overlays exact runtime field names:

```json
{
  "cellAttributes": {
    "default": {
      "mergeHorizontal": "none",
      "mergeVertical": "none",
      "distributeSpannedColumns": false,
      "distributeSpannedRows": false
    },
    "fields": {
      "Department": {
        "mergeVertical": "matchingNonEmpty"
      },
      "Category": {
        "mergeVertical": "matchingNonEmpty",
        "mergeKeep": { "atStart": 2, "atEnd": 2 },
        "applyWhenLeftMerges": true,
        "distributeSpannedRows": true
      },
      "Description": {
        "cellStyleFromField": "DescriptionCellStyle"
      }
    }
  }
}
```

The merge values are `none`, `matching`, `matchingNonEmpty`, and
`matchingInRange`; `matchingNonEmpty` is EasyCatalog's matching-content merge
with empty cells ignored. Every adjacent cell participating in a horizontal or
vertical merge run must have compatible merge attributes.
`distributeSpannedColumns` and `distributeSpannedRows` map to the corresponding
EasyCatalog span-distribution options. `cellStyleFromField` names a field whose
formatted value selects an InDesign cell style, and follows the table's
`missingStyle` policy. Omitted properties preserve the prototype value. These
attributes apply only to materialized body value cells, not header, subheader, or
footer cells.

With `structure: "authored"`, a field override targets each record-prototype
cell containing that linked field, independently of the cell's position or
span. The attributes are applied after the copied row has been populated. This
allows `mergeScope: "composedArea"` to re-evaluate matching values separately
within each composed frame area.

For authored tables, `columns.byIndex` applies options by physical prototype
column. Array item zero applies to the first column, item one to the second, and
so on. An item may contain `width` and `delete` using the same column-option
values as generated tables. This remains deterministic when headers contain
ordinary text and when a body cell contains no linked field or several linked
fields.

For plan-managed `vertical` tables, `applyWhenLeftMerges: true` applies the
field's vertical merge option only within a qualifying span from the nearest
preceding generated field with vertical merging enabled. Dependent fields are
processed left-to-right, so the condition chains through all preceding merge
levels and prevents a repeated child value from crossing a parent boundary.
The first vertically merged field remains an independent root. Other table
modes reject this option because their final record cells are not available
while the composition plan prepares the prototype.

For a field with vertical merging, `mergeKeep` may protect records at both ends
of every matching run:

```json
{
  "mergeVertical": "matchingNonEmpty",
  "mergeKeep": { "atStart": 2, "atEnd": 2 }
}
```

`atStart` and `atEnd` are non-negative logical-record counts. For example,
`atStart: 2` prevents the first record of a run from being left by itself at
the bottom of a frame, while `atEnd: 2` prevents the final record from being
left by itself at the top of the next frame. Authored multi-row record
prototypes count as one record. `mergeKeep` is supported by plan-managed
`vertical` tables with `mergeScope: "composedArea"`.

`table.mergeScope` defaults to `table`, which merges across the complete table
body. A plan-managed `vertical` table may instead use `composedArea`. In that
mode only complete, contiguous body rows in one composed frame column are
merged. A merge never crosses a frame or column boundary. If the visible ranges
do not stabilise after recomposition, the section fails and its partial output
is removed.

### Master-page sections

For a preparation and execution walkthrough, see the
[Data Sheet Pagination Guide](Data%20Sheet%20Pagination%20Guide.md).

A `masterPage` section uses the single top-level item on a named InDesign
master (parent) page as a live template. A group counts as one top-level item.
A container becomes a `templateContainer`, a text frame becomes a `textFrame`,
and other artwork or a group becomes a `formattingRule` section. The source
master artwork remains unchanged. Master text frames inherit container-data
auto-fit flags, minimum/maximum dimensions, Threadable and Keep With Next.
Active pagination fitting attributes can enable fitting and override positive
height limits; unspecified limits retain the container-data settings. Explicit
JSON section properties override inherited settings.

```json
{
  "schema": "easycatalog-composition-plan/1",
  "threads": [
    {
      "name": "selected-pages",
      "direction": "top to bottom",
      "crossAxis": "start",
      "content": [
        {
          "type": "masterPage",
          "name": "CP-1",
          "master": "CP-1",
          "page": 1,
          "insideMargins": true,
          "data": { "source": "selectionRoot", "result": "self" },
          "overflow": "continue",
          "spaceAfter": 0
        },
        {
          "type": "masterPage",
          "name": "CP-2",
          "master": "CP-2",
          "page": 1,
          "insideMargins": true,
          "data": { "source": "selectionRoot", "result": "self" },
          "overflow": "continue",
          "spaceAfter": 0
        }
      ]
    }
  ]
}
```

Replace `CP-1` and `CP-2` with exact master spread names, including their
prefixes. `page` is a one-based index **within that master spread**, not a
document page number or a `left`/`right` string. The source page must contain
exactly one top-level item. Do not supply `asset`, `ruleSet`, `sections` or
`plan` on a `masterPage` section; the source item determines its content type.

The creation command asks once whether the intended area is **Inside Margins**
or **Outside Margins** (full page). It writes `insideMargins: true` or
`insideMargins: false` on every generated section. Cancel leaves no saved plan.

With `insideMargins: true` (also the default for older plans), offsets are
measured from the source page's **margin top-left**. Destination pages and
spreads use their margin area; a destination container uses its content bounds.
In a top-to-bottom thread:

- The first section on a new page starts at its top margin plus the source
  item's margin-relative Y offset.
- Each subsequent section starts below the preceding section's rendered
  bottom, plus its `spaceAfter`, the thread `gutter`, and the next source
  item's margin-relative Y offset.
- X remains relative to the destination's left margin or container left edge.
- Artwork extending past a source margin retains that edge's outset. Negative
  offsets are preserved. These allowances belong to that section and do not
  enlarge the margin area for later sections.

For example, an item 12 pt below its source top margin starts 12 pt below the
new destination's top margin. Following another section with `spaceAfter: 6`
and a zero thread gutter, it starts 18 pt below that section's rendered bottom.
On a new destination it restarts from the top margin, rather than carrying the
previous page's trailing gap. Left-to-right threads advance horizontally.

With `insideMargins: false`, offsets are measured from the **source page
origin** instead. This adds the source left/top margins to the margin-relative
position. For an item on a 12 mm top margin, the Y offset is zero in inside
mode and 12 mm in outside mode. The full-page destination starts at its page
origin; a container starts at its content origin. Subsequent sections still
flow below the preceding result, adding the next source page-relative offset.
Extensions beyond the source page bounds remain per-section outsets.

Use a full-page target
for outside mode. Explicitly constrained target areas and container bounds
remain constraints; this setting does not enlarge an authored layout slot.
The boolean is specific to `masterPage` sections. It can be edited in existing
JSON without recreating the plan.

The plan can be stored in a plan container.
Master content and margins are resolved again when the plan is compiled for
pagination or population; an existing `masterPage` plan does not need to be
recreated after changing the source artwork. Keep the referenced masters in
the destination document. Exporting the plan JSON does not package those
masters or any formatting rules used by their containers.

A normal `when` condition can omit a section's content. It does not delete a
physical document page. The referenced master must still exist and satisfy
the one-item requirement because source resolution happens during compilation.
Older generated plans without `spaceAfter` retain the default of zero; add
`"spaceAfter": 0` to make the setting explicit without regenerating them.

### Fit-aware formatting-rule alternatives

For most sections, `asset` is one formatting-rule name. `formattingRule` and
`float` sections may instead provide `asset` as an ordered, non-empty array of
exact formatting-rule names. `"auto"` is not valid in this array. Array entries
are tried in order only when the preceding asset cannot fit the current
physical area.

```json
{
  "type": "formattingRule",
  "name": "product-card",
  "asset": [
    "Large Product Card",
    "Compact Product Card",
    "Text-only Product Card"
  ],
  "data": { "source": "variable", "name": "product", "result": "self" }
}
```

Each attempt is transactional: rejected page items, cursor movement and area
state are rolled back before the next asset is tried. Only a genuine
`noAvailableSpace` result advances the array. An unavailable asset, invalid rule
or population failure remains an immediate error, so alternatives do not hide
broken plans. Empty arrays and duplicate names are invalid. If `asset` is
omitted, the normal implicit section-name asset is used. A declarative
`propertyResolver.asset` produces one string and therefore overrides the static
array with that single resolved asset.

### Atomic section-layout alternatives

Use `fitAlternatives` when one choice must govern an entire section subtree,
not each formatting-rule item independently. It may decorate any concrete
section (including a `flow`) and accepts one to eight ordered entries. Each
entry contains a required `parameters` object. Parameter references inside the
decorated section use the same complete-value syntax as local components:
`{ "$parameter": "name" }`.

```json
{
  "type": "flow",
  "name": "related-products",
  "fitAlternatives": [
    { "parameters": { "cardAsset": "Related Product 1-up" } },
    { "parameters": { "cardAsset": "Related Product 2-up" } },
    { "parameters": { "cardAsset": "Related Product 3-up" } },
    { "parameters": { "cardAsset": "Related Product 4-up" } },
    { "parameters": { "cardAsset": "Related Product Compact" } }
  ],
  "retainLastOnOverflow": true,
  "body": {
    "direction": "left to right",
    "wrap": true,
    "sections": [{
      "type": "formattingRule",
      "name": "cards",
      "asset": { "$parameter": "cardAsset" },
      "assetForEach": true,
      "data": { "source": "selectionRoot", "result": "children" }
    }]
  }
}
```

Each expanded subtree is evaluated transactionally against the physical area.
The first candidate that consumes the entire subtree with no overset is
committed. A candidate that leaves content or overset is rolled back together
with its cursor movement, placed items, tracked areas, and progress state before
the next candidate is tried. If every applicable candidate fails to fit, the
decorated section follows its ordinary `overflow` policy and may retry from its
initial state in the next area. `clip` is rejected because alternatives are
atomic. A candidate whose parameterised `when` expression is false is skipped.

Set `retainLastOnOverflow` to `true` to make the final candidate a visible
diagnostic fallback. Earlier candidates are still rolled back atomically, but
when the final candidate succeeds with remaining content or overset, its placed
items are committed and the result remains overflowed. In a single plan
container this leaves the last layout visible with the container's overflow
state, making an undersized fallback easy to spot while designing templates.
When linked continuation areas exist, the selected final candidate and its
progress are persisted and resumed rather than restarting at an earlier
alternative. The default is `false`. Population errors still fail and roll
back, and a final candidate that cannot place anything has no successful
overflow result to retain.

The compiler also accepts the explicit section form
`{"type":"fitAlternatives","name":"choice","candidates":[...]}`,
where each candidate is a complete section object. The decorated form above
expands to this section type before execution.

This is suitable for one-, two-, three-, four-, and higher-count product
layouts. Order candidates from the preferred/spacious layout to the most
compact fallback. The number of candidates is not limited to two; the maximum
is eight. If exact count-to-layout mapping is required rather than physical-fit
selection, use a candidate parameter in the decorated section's `when`
expression to make only the matching count candidate applicable.

### Text-wrap floats

A `float` places one formatting-rule asset at the left or right of the current
flow position and applies InDesign's standard bounding-box text wrap. The float
does not advance the composition cursor. A following full-width `textFrame`
therefore occupies the normal flow area, while InDesign wraps its story around
the placed page item and continues at full width below it.

```json
{
  "type": "float",
  "name": "product-image",
  "asset": "Product Image",
  "data": { "source": "variable", "name": "product", "result": "self" },
  "side": ["outside", "inside"],
  "textWrap": {
    "mode": "boundingBox",
    "offset": [0, 0, 10, 12]
  },
  "floatLayout": {
    "lane": "product-callouts",
    "placement": "stack",
    "direction": "top to bottom",
    "insets": [0, 0, 0, 0],
    "gutter": 10,
    "collision": "nextArea",
    "avoidObstructions": true
  }
}
```

`side` is `left`, `right`, `inside`, `outside`, or `auto`, or an ordered,
non-empty array of those values. `inside` and `outside` resolve against the
physical left/right page. On a non-facing page they resolve to left and right
respectively. `auto` tries the outside edge and then the inside edge. Duplicate
array entries are invalid. `textWrap.mode` is currently `boundingBox` and
`offset` is `[top, left, bottom, right]` in points. A float places one asset only, so
`assetForEach` is not supported; use `forEach` when each data node requires a
separate float. Multiple floats may precede the same text frame, for example a
large image on the left and a small callout on the right. InDesign performs the
line wrapping; the story is not split into artificial side and below regions.

`floatLayout` optionally positions multiple floats automatically. Floats with
the same non-empty `lane` are stacked in source order. `placement` is `stack`,
`collision` is `advance` or `nextArea`, and `direction` is `top to bottom`, `bottom to top`,
`left to right`, or `right to left`. The non-negative `gutter` is measured in
points. Optional `insets` are `[top, left, bottom, right]` point distances from
the current physical composition area; they are deliberately not percentages.
`avoidObstructions: true` rejects a candidate whose populated bounds overlap an
item already registered in the composition area.

The first float is aligned to the lane's starting edge (top-to-bottom also
honours a later current flow position). Each later float advances beyond the
preceding committed float by the gutter. Horizontal directions set left or
right alignment and vertical directions set top or bottom alignment. Different
lane names remain independent. The asset is placed and populated speculatively
before its bounds are accepted. Consequently, text auto-sizing and any other
population-driven size change are included in the fit and obstruction tests.
When a candidate side does not fit, its page items, data changes, cursor and lane
state are rolled back before the next side is tried. Lane state stores the
actual committed populated rectangle,
belongs to one physical composition area, participates in checkpoints, and
starts empty in a continuation area. If the remaining bounded lane cannot
contain the asset, ordinary section continuation retries it in the next area.
`nextArea` makes that fallback explicit after all declared sides fail.
`moveDown` is a top-to-bottom alias for `advance`. This contract coordinates
named floats and, when requested, items known to the composition area; it does
not discover arbitrary unregistered page objects.

## 6. Repetition with forEach

`forEach` expands one section template for every selected node. It is a thread
content entry, not a section type:

```json
{
  "type": "forEach",
  "itemName": "group",
  "data": {
    "source": "selectionRoot",
    "collector": "collectNamedGroups",
    "name": "Code discount",
    "result": "children"
  },
  "template": {
    "type": "flow",
    "name": "group-{index1}",
    "data": { "source": "variable", "name": "group" },
    "body": {
      "sections": [
        {
          "type": "textFrame",
          "name": "records-{index1}",
          "asset": "Table",
          "threadable": true,
          "overflow": "continue"
        }
      ]
    }
  }
}
```

`itemName` defaults to `item`. `{index}` is zero-based and `{index1}` is
one-based in expanded names. These are name-template tokens; the equivalent
runtime value for expressions and property resolvers is
`{ "context": "forEachIndex" }`. `forEachIndex` is zero-based, remains the
same for descendants imported from that expanded template, and is `-1` for a
section that was not produced by `forEach`.

## 7. Flow sections

A flow requires a `body`; `header` and `footer` are optional. Each region owns
a layout pattern and a `sections` array:

```json
{
  "type": "flow",
  "name": "category",
  "data": { "source": "variable", "name": "category" },
  "header": {
    "sections": [
      {
        "type": "formattingRule",
        "name": "category-header",
        "asset": "Category Header",
        "mergeAdjacentHeaders": true,
        "propertyResolver": {
          "asset": {
            "if": {
              "condition": { "greaterThan": [{ "context": "regionSpan" }, 1] },
              "then": "Category Header Spanning",
              "else": "Category Header"
            }
          }
        }
      }
    ]
  },
  "body": {
    "direction": "top to bottom",
    "horizontalGutter": 14,
    "verticalGutter": 10,
    "layoutPattern": {
      "name": "two-columns",
      "columns": 2,
      "columnGutter": 5,
      "readingOrder": "right to left",
      "finalRegion": "balance"
    },
    "sections": [
      {
        "type": "textFrame",
        "name": "records",
        "asset": "Records",
        "threadable": true,
        "overflow": "continue"
      }
    ]
  },
  "footer": {
    "sections": [
      {
        "type": "formattingRule",
        "name": "category-footer",
        "asset": "Category Footer",
        "keepWithPrevious": true
      }
    ]
  }
}
```

Every flow region accepts `direction`, `gutter`, `horizontalGutter` and
`verticalGutter`. `gutter` sets both axes; an axis-specific
property overrides just that axis. The region uses the vertical value when
flowing top to bottom and the horizontal value when flowing left to right.
Spacing is inserted only between consecutive committed sections in the same
physical area. It is therefore not added before the first section in a new
column, page, or linked container. Use the layout pattern's `columnGutter` or
`rowGutter` for spacing between physical regions.

For a `left to right` region, `horizontalDistribution` is `"packed"` by
default. Set it to `"space between"` to spread a completed row's items across
the row's available width. The horizontal gutter remains the minimum gap; a
row with fewer than two items is left packed. The last row remains packed unless
`distributeFinalRow: true` is set. `space between` requires an explicit
`"direction": "left to right"`, and `distributeFinalRow: true` requires
`horizontalDistribution: "space between"`.

Set `wrap: true` to use the remaining cross-axis space before continuing to the
next physical area. Left-to-right flow opens a new row below the tallest item
and separates wrapped rows with `verticalGutter`. Top-to-bottom flow opens a new
column to the right of the widest item and separates wrapped columns with
`horizontalGutter`. Complete children remain intact during either wrap. A failed placement in an empty local row or column does not create another empty wrap. Wrapping requires occupied extent in that lane and a strictly advancing origin within the available bounds; otherwise normal area continuation or a cannot-fit result applies.

On a wrapped flow, section-level `horizontalAlignment` and `verticalAlignment`
can position the completed items in each physical area. Along the fill axis,
justification distributes free space between items in each row or column;
`justify left`/`justify top` and `justify center` alter the final lane when
multiple lanes exist. End/centre alignment also positions the packed block on
the cross axis. Auto-fit axes align against occupied extent or the declared
minimum, rather than the maximum working area. This final alignment is for
wrapped row/column flows, not masonry.
Final alignment of the whole area is separate: set root `finalAlignment` to
one of `top left`, `top center`, `top right`, `middle left`, `middle center`,
`middle right`, `bottom left`, `bottom center` or `bottom right`. It applies after
all normal threads have composed into each target/continuation area, regardless
of their section types. For example, `"finalAlignment": "bottom center"` centres
the fitted content block horizontally and places it against the available
area's bottom edge. The relative positions within the block are preserved.
The target may be a page, spread or container; a nested plan can also
specify this property for its own target. Container targets supply their stored
final-align setting when the plan omits it. Fixed area furniture is excluded,
and area adornments are placed afterwards using the final content bounds.
The operation participates in plan rollback and updates result fragment bounds.

`packing` is `"rows"` by default. Set it to `"masonry"` on a body with a
`layoutPattern` when variable-height, indivisible children should use the
shortest available patterned column instead of sharing row bottoms. Masonry
tracks the physical bounds of every committed descendant, so a full-width
category header can advance both columns while cards beneath it advance only
the columns they actually occupy. When all column frontiers align, the next
child receives their combined width; otherwise it receives only the shortest
column. Category headers should be authored at one-column width and set
`mergeAdjacentHeaders: true`. After the category commits, masonry widens that
header across only the adjacent columns occupied by the same category. A
one-record category therefore keeps its one-column header even when it begins
at an aligned frontier; a category whose cards occupy both columns receives a
two-column header.
Nested masonry can remove tall-row white space inside a category. Give the
nested body the same multi-column `layoutPattern` and set
`minimumAreaWidth` to the normal card width. A full-width category then uses
independent inner columns, while a category offered only one outer column
collapses responsively to a single inner area. A collapsed one-area pattern is
valid masonry and retains the same placement policy without narrowing cards.

```json
"body": {
  "direction": "left to right",
  "packing": "masonry",
  "layoutPattern": { "columns": 2, "columnGutter": 6 },
  "sections": []
}
```

For an auto-fit container, `initialWidth` and `initialHeight` are preferred
working dimensions rather than keep constraints. If a preferred dimension
does not fit the remaining flow area and a smaller declared minimum does, the
section is retried at `minimumWidth` and/or `minimumHeight`, populated, and
accepted only when its final populated bounds fit the parent.
This permits a card that shrinks after population to use the end of a column
without permitting its real content to overflow that column.

`keepWithPrevious` is an optional static boolean supported only by sections in
a flow `footer`. When the final body placement leaves too little room for that
footer, the flow retries the final region with footer space reserved. Trailing
body content therefore continues with the footer instead of leaving the footer
alone at the start of the next column, page, or linked plan container.

Each `header`, `body` or `footer` region may also contain an `adornments`
array. Its definitions are copied to every child area instantiated by that
region and finalized after the area's ordinary content succeeds. With
`target: "content"`, each adornment measures only content committed in its own
child area; separated areas therefore receive independent panels:

```json
"body": {
  "layoutPattern": {
    "areas": [
      { "name": "upper", "bounds": [0, 0, 0.47, 1] },
      { "name": "lower", "bounds": [0.53, 0, 1, 1] }
    ]
  },
  "sections": [
    { "type": "formattingRule", "name": "products", "asset": "Product Card" }
  ],
  "adornments": [
    {
      "type": "formattingRule",
      "name": "region-panel",
      "asset": "Rounded Section Border",
      "target": "content",
      "outsets": [6, 6, 6, 6],
      "zOrder": "behind",
      "onEmpty": "omit"
    }
  ]
}
```

A layout pattern must define exactly one of:

```json
{ "columns": 2, "columnGutter": 5, "finalRegion": "compact" }
```

```json
{ "rows": 3, "rowGutter": 5, "finalRegion": "balance" }
```

```json
{
  "areas": [
    {
      "name": "main",
      "bounds": [0, 0, 1, 0.66],
      "insets": [0, 0, 0, 5]
    },
    {
      "name": "side",
      "bounds": [0, 0.66, 1, 1]
    }
  ]
}
```

Optional `readingOrder` values are `document` (the default), `left to right`,
and `right to left`. `document` follows the InDesign document's page binding.
Reading order changes area traversal only; it does not mirror or otherwise
alter the declared bounds.

Explicit area bounds are normalized relative coordinates; insets are points.
Every explicit area name must be unique within its layout pattern. The same
area name may be reused by a separate continuation pattern to identify the
corresponding lane in the next physical area set. A duplicate reports
`duplicate-area-name` at the second area's `/name` JSON Pointer and identifies
the first area's index in `message`; `expected` is `unique area name`.
Flow sections may nest, allowing outer furniture to remain active while an
inner flow moves through its own regions.

`minimumAreaWidth` and `minimumAreaHeight` make a multi-area pattern
responsive. If instantiation inside the current parent would make any child
area smaller than a declared non-zero minimum, the pattern collapses to one
area spanning that parent. This is useful when an outer obstruction leaves a
region suitable for one normal column but not for another complete set of
nested columns:

```json
{
  "columns": 2,
  "columnGutter": 12,
  "minimumAreaWidth": 240
}
```

### Named-layer obstructions

A layout pattern can exclude page items on a named layer. Items may be on the
physical document page, its applied parent page, or both:

```json
{
  "columns": 2,
  "columnGutter": 12,
  "obstructions": {
    "source": "layer",
    "layer": "Catalog Obstructions",
    "include": ["page", "parent"],
    "clearance": [6, 6, 6, 6],
    "flow": "around",
    "minimumWidth": 72,
    "minimumHeight": 36
  }
}
```

`clearance` is either one point value for every edge, or
`[top, left, bottom, right]`. Items are used only when their named layer is visible.
Outer stroke bounds are transformed into the document page's pasteboard
coordinates before the clearance is applied.

The supported `flow` values are:

- `around`: rebuild the usable footprint as rectangular bands around each
  obstruction, then traverse those bands in the layout reading order.
- `block`: reject the full horizontal band crossed by an obstruction.
- `preserveRegions`: split each declared row, column, or explicit area
  independently, preserving its identity and ordering.
- `gridCells`: retain each declared rectangular area and project intersecting
  obstruction rectangles onto any `gridFill` or `gridSequence` section using
  that area. Every intersected grid cell is unavailable to records and
  fillers, so all placement strategies route around the same blocked cells.
  Use this policy only for grid-driven threads; ordinary flow sections do not
  subtract the retained obstruction geometry.

`minimumWidth` and `minimumHeight` discard unusably small fragments. The
obstruction geometry is captured once for a physical page so retries and final
region balancing see the same geometry. On every continuation page the layout
pattern is instantiated again and scans that page (and its applied parent when
requested); obstruction-derived regions from an earlier page are never copied
forward. A continuation page with no matching obstruction therefore retains
the pattern's normal unsplit geometry.

Cell projection uses the grid's resolved physical tracks, including its row
and column gutters. An obstruction which overlaps any part of a cell blocks
the complete cell; an obstruction lying only in a gutter does not block either
adjacent cell. The declared obstruction `clearance` is applied before this
projection.

Flows may also contain non-placement boundary leaves:

```json
{
  "startLeaves": [
    {
      "type": "page",
      "name": "chapter-opener",
      "parent": "B-Chapter Opener",
      "pageSide": "right",
      "alignmentParent": "A-Blank",
      "populateTags": true
    }
  ]
}
```

`pageSide` is `any` (default), `left`, or `right`, and is valid only for page
leaves. In a facing-pages document, a blank page is inserted before the
requested page when needed. `alignmentParent` selects the parent for that blank
page and defaults to `"[None]"`; the page is not populated or exposed as a
layout area.

`mergeAdjacentHeaders` is valid on a formatting-rule section or an
unconstrained text-frame section in a flow header. After an outer area
completes, matching headers at the same vertical position in adjacent regions
are merged. A formatting-rule section is recomposed as a spanning header; its
named property resolver receives `context.regionSpan`: `1` for normal
placement and the number of adjacent regions for a merge attempt. A text-frame
section must omit `bounds`, `initialWidth`, `minimumWidth` and
`maximumWidth`; its first existing frame is widened across the regions and
the duplicate frames are removed. Both forms must preserve the original
header height.

## 8. Containers and fill sections

A container may omit `sections` and use its own `asset`, contain exactly one
formatting-rule section, or own a nested composition plan.

```json
{
  "type": "container",
  "name": "images",
  "data": { "source": "variable", "name": "group" },
  "asset": "Image",
  "fillDirection": "horizontal",
  "horizontalGutter": 4,
  "verticalGutter": 4,
  "autoFitVertically": true,
  "threadable": true
}
```

A nested plan is represented by `plan.threads`. It implies compose mode and
uses the owning container as its runtime layout area:

```json
{
  "type": "container",
  "name": "category",
  "data": { "source": "variable", "name": "category" },
  "autoFitVertically": true,
  "plan": {
    "threads": [
      {
        "name": "category-content",
        "content": [
          {
            "type": "formattingRule",
            "name": "category-heading",
            "asset": "Category Heading"
          },
          {
            "type": "container",
            "name": "products",
            "asset": "Product"
          }
        ]
      }
    ]
  }
}
```

`sections` and `plan` are mutually exclusive. A nested plan supports the same
thread and section grammar as a root plan, including nested flows, fill
sections, declarative decisions, data selectors and further container-owned plans. Root
`continuation` and root `furniture` are intentionally not valid inside a
nested `plan`; continuation is controlled by the owning container and its
parent executor.

The nested plan may also be built and persisted separately from the outer
layout. Assign its JSON to a physical page item's `ecCompositionPlanJSON`, save
that item as a container formatting rule, and place the rule using
`templateContainer`:

```json
{
  "type": "templateContainer",
  "name": "product-card",
  "asset": "PRODUCT_CARD",
  "data": { "source": "variable", "variable": "product", "result": "self" },
  "initialHeight": 220,
  "autoFitVertically": true,
  "keepTogether": true,
  "onEmpty": "error"
}
```

The imported formatting-rule container retains its stored plan and other
container settings. `templateContainer` supplies the runtime data; it does not
copy the nested plan into the outer JSON document.

Set `keepTogether: true` when the template represents an atomic card or item.
The placement is then committed only if the template's owned composition plan
finishes inside that one physical container. An incomplete owned plan, overset
content, or a continuation link rejects and rolls back the whole trial card so
the outer flow can retry it in the next layout area. Auto-fit may still shrink
or grow the card, but it cannot split the card's flow elements.

A fill section requires one shared source node. It chooses a candidate prefix and
applies it to all participating children:

```json
{
  "type": "fillSection",
  "name": "matched",
  "data": { "source": "variable", "name": "records" },
  "strategy": "adaptive",
  "minimumItems": 1,
  "sections": [
    {
      "type": "container",
      "name": "tiles",
      "asset": "Tile",
      "usesFillData": true
    },
    {
      "type": "textFrame",
      "name": "table",
      "asset": "Table",
      "usesFillData": true
    }
  ]
}
```

Fill strategies are `adaptive`, `binary`, `incremental` and `decremental`.

### Stronger section constraints

Any composable section can declare constraints that are evaluated against the
current layout area. Constraints use the same checkpoint and rollback path as
keeps and overflow, so a required constraint retries the complete section in
the next area without leaving partial output behind:

```json
{
  "type": "textFrame",
  "name": "product-table",
  "asset": "Product Table",
  "constraints": {
    "mode": "required",
    "minimumAvailableHeight": 144,
    "minimumFollowingItems": 3,
    "minimumRemainingItems": 2
  }
}
```

`mode` is `required` or `preferred` and defaults to `required`.

- `minimumAvailableHeight` is the minimum vertical space, in points, that must
  remain in the current area before the section is attempted.
- `minimumFollowingItems` is the minimum number of data items that this section
  occurrence must place when it places any items. It is useful for preventing a
  continuation area from starting with an undersized fragment.
- `minimumRemainingItems` prevents a successful occurrence from leaving fewer
  than the specified number of source items for its continuation. It applies to
  sections that expose fill progress, such as fill sections and continuing
  data-driven sections.

Zero disables an individual constraint. Values must be non-negative;
item-count values must be integers. A required violation rolls the section
back and lets normal continuation try the next area. If no area can satisfy the
constraint, composition fails with a constraint-specific diagnostic. A
preferred violation is accepted and recorded in the composition session log.

Constraints are resolved section properties. They therefore behave the same
inside flows, fill-section children, local components and container-owned
nested plans.

### Named multi-section constraint groups

Use a named constraint group when more than two adjacent sections form one
indivisible layout unit. Definitions live at the plan root; each direct sibling
section joins a definition with `constraintGroup`:

```json
{
  "schema": "easycatalog-composition-plan/1",
  "constraintGroups": {
    "departmentOpening": {
      "mode": "required",
      "placement": "same page",
      "minimumFollowers": 2,
      "keepStartTogether": true,
      "maximumSeparation": 1,
      "maximumAttempts": 4,
      "onUnsatisfied": "error"
    }
  },
  "threads": [{
    "name": "catalogue",
    "content": [
      {
        "type": "formattingRule",
        "name": "department-heading",
        "asset": "Department Heading",
        "constraintGroup": "departmentOpening"
      },
      {
        "type": "formattingRule",
        "name": "intro-image",
        "asset": "Department Image",
        "constraintGroup": "departmentOpening"
      },
      {
        "type": "textFrame",
        "name": "first-products",
        "asset": "Product Table",
        "constraintGroup": "departmentOpening"
      }
    ]
  }]
}
```

The group definition supports:

- `mode`: `"required"` (the default) or `"preferred"`.
- `placement`: `"same area"` (the default), `"same page"`, or
  `"same spread"`. The scope applies to the complete group occurrence.
- `minimumFollowers`: the minimum number of non-omitted members after the
  first member. The default is `0`.
- `keepStartTogether`: when `true`, the first fragment of every member must
  start in the same layout area as the first member. A member may continue
  within the wider configured page or spread scope. The default is `false`.
- `maximumSeparation`: the largest permitted difference between the first and
  final layout-area indices. Omit it for no explicit distance limit.
- `maximumAttempts`: the maximum number of complete-group placement attempts,
  from `1` to `100`. The default is `2`.
- `onUnsatisfied`: `"error"` (the default) or `"relax"`.

The executor checkpoints the layout area, group members, continuation state,
created areas, document leaves and placed-result counts before the first
member. A required group commits only after its final member satisfies the
definition. An atomic fit failure rolls the complete run back and retries it
in a fresh area, bounded by `maximumAttempts`; final failure produces a named
group diagnostic without leaving partial output.

A preferred group, or a group with `onUnsatisfied: "relax"`, first attempts the
same constrained placement. If the remaining space cannot accept a member it
continues normally, commits the resulting layout, and records the relaxed
constraint in the composition-session log. This is deliberately bounded
best-effort placement, not a global page optimiser.

A group is one **contiguous sibling run** in one thread. Reusing the same name
later starts another independent occurrence. Local components may expand to
several adjacent group members. Repeated imports receive an occurrence suffix,
so neighbouring `forEach` expansions cannot accidentally merge. Groups do not
coordinate separate threads in version 1. Section breaks inside a group are an
error, and a grouped section must not use `when`; use `onEmpty` for optional
content while preserving the transaction boundary.

### Strict-order grid fill

`gridFill` places one formatting-rule item per immediate child of its resolved
source wrapper into a fixed logical grid. A child can be a record, group,
named collection or tabular collection. The formatting rule receives the
complete child wrapper, including its descendants. Its placement strategy
controls whether later fitting children may overtake an item that cannot use
the remaining cells:

Only immediate children become positions. If `shape.group` creates
`Category1` groups, each `Category1` group occupies one grid position. In a
multi-level hierarchy the first-level groups are the positions; use a nested
`forEach`, or resolve `children` from a particular group, to grid-fill the next
level instead.

```json
{
  "type": "gridFill",
  "name": "mixed-product-cards",
  "data": { "source": "selectionRoot", "result": "self" },
  "grid": {
    "columns": 12,
    "rows": 12,
    "columnGutter": 6,
    "rowGutter": 6,
    "order": "across then down"
  },
  "placement": { "strategy": "strictOrder" },
  "span": "auto",
  "item": {
    "type": "formattingRule",
    "name": "product-card",
    "asset": "Product Card",
    "onEmpty": "omit"
  }
}
```

`span` can instead be an explicit `{ "columns": 2, "rows": 1 }` object.
With `"auto"`, the selected formatting-rule asset is measured, its dimensions
are rounded up to logical grid cells, and larger spans are tried if populated
content needs more room.

`placement.strategy` supports:

- `strictOrder`: never overtakes the earliest pending child.
- `firstFit`: places the first later fitting child, then stops looking ahead.
- `dense`: repeatedly scans later children to fill every available hole it can.
- `boundedDense`: dense scanning limited to `lookAhead` source positions after
  the earliest pending child. It requires a positive integer `lookAhead`, for
  example `{ "strategy": "boundedDense", "lookAhead": 6 }`.
- `boundedBestFit`: searches the bounded `lookAhead` window and chooses the
  fitting record/anchor combination that leaves the least-fragmented grid.
- `groupAware`: keeps the earliest pending child's field group together while using
  `withinGroup: "firstFit" | "dense" | "boundedDense"`. It requires
  `groupField`; bounded group placement also requires `lookAhead`.
- `pattern`: preserves source order and cycles through exact `slots`, each an
  object with positive `columns` and `rows`, an optional non-empty `asset`
  name, and an optional declarative `assetResolver`. Asset precedence is:
  `slot.assetResolver`, `slot.asset`, `item.propertyResolver.asset`, then
  `item.asset`. An empty resolver result falls through; an evaluation error
  fails composition. Other item properties remain shared. The cycle restarts
  per physical grid area.

  A page-side-aware pattern uses named `patterns`. `pattern` names the fallback
  definition and `patternResolver` is evaluated once for each physical grid
  area. It may select a different definition from `pageSide`; continuation
  areas resolve it again. `pageSide` reflects actual page geometry (`left`,
  `right`, or `single`), not page-number parity.

  ```json
  "placement": {
    "strategy": "pattern",
    "pattern": "right-page",
    "patternResolver": {
      "if": {
        "condition": { "equals": [{ "context": "pageSide" }, "left"] },
        "then": "left-page",
        "else": "right-page"
      }
    },
    "patterns": [
      {
        "name": "left-page",
        "slots": [
          { "columns": 4, "rows": 2, "asset": "Small Card" },
          { "columns": 8, "rows": 2, "asset": "Wide Card" }
        ]
      },
      {
        "name": "right-page",
        "slots": [
          { "columns": 8, "rows": 2, "asset": "Wide Card" },
          { "columns": 4, "rows": 2, "asset": "Small Card" }
        ]
      }
    ]
  }
  ```

  `slots` and `patterns` are mutually exclusive. Named patterns require a
  valid fallback `pattern`. Pattern selection precedes slot selection; within
  the selected pattern, asset precedence remains `slot.assetResolver`,
  `slot.asset`, `item.propertyResolver.asset`, then `item.asset`.
- `largestFirst`: chooses the largest fitting measured span from all remaining
  children, with source order as its deterministic tie-break.

Skipped children are never dropped; they remain in persisted continuation state
and are retried in later cells or layout areas. `fillers` may contain ordered,
non-data-consuming formatting-rule items used to occupy holes left after data
placement stops.

Set `placement.searchBudgetSeconds` to a positive number to limit search time
per grid area. Fractional seconds are supported; omitting it leaves search
unlimited. For example:

```json
"placement": {
  "strategy": "boundedBestFit",
  "lookAhead": 20,
  "searchBudgetSeconds": 2
}
```

When the budget expires, ranked strategies finish their best valid candidate
found so far, then stop searching that area. Other strategies finish the current
item. Pending records continue into subsequent areas; no records are discarded.
Further filler searches stop too, and a warning appears in the result.

This is a soft search budget, not an overall composition timeout. An in-progress
formatting rule is not interrupted. A fresh area is allowed to find and process
an initial candidate so very small budgets still make progress. Those operations
can exceed the budget. Each continuation area gets a new budget; in a
`gridSequence`, each region gets its own budget. Timing-dependent cutoffs may
produce different packing on different machines.

### Compact final grid area

For `gridFill`, `placement.finalAreaPacking` accepts `unchanged` (the default),
`minimumHeight`, or `minimumWidth`:

```json
"placement": {
  "strategy": "dense",
  "finalAreaPacking": "minimumHeight",
  "searchBudgetSeconds": 2
}
```

Once all remaining grid records have fitted, the final area's already-populated
items can be rearranged to reduce their occupied bottom or right edge. Earlier
areas are unchanged. Item sizes and grid spans remain fixed; items are neither
rotated nor repopulated. Obstructions and gutters are respected. The physical
page/container is not resized. A one-area grid can also be compacted.

This option explicitly permits reordering on the final area, including with
`strictOrder`. It is not supported with `pattern` or `groupAware`, or in
`gridSequence` regions. Fillers cannot extend the final occupied height/width.

The search uses the remaining `searchBudgetSeconds` for that grid area, with
safety limits of 64 placed items and 100,000 candidate positions. It retains
the best complete improvement found, or the original arrangement when none
is found. A search-limit warning means the mathematical minimum is not proven.

### Sequenced grid regions

`gridSequence` divides one physical layout area with a discrete outer allocation
grid and assigns ordered regions to integer cell rectangles within it.
It uses one shared data cursor, one shared `item` template and one shared optional
`fillers` list. Each region supplies its own `grid`, `placement` and `span`, so a
page can use a patterned feature band followed by a dense product grid without
running two independent data selections or replaying records.

```json
{
  "type": "gridSequence",
  "name": "mixed-page-grid",
  "data": { "source": "selectionRoot", "result": "self" },
  "grid": { "columns": 12, "rows": 10, "columnGutter": 6, "rowGutter": 6 },
  "continuation": "restartRegions",
  "regions": [
    {
      "name": "feature-band",
      "area": { "column": 1, "row": 1, "columnSpan": 12, "rowSpan": 4 },
      "grid": { "columns": 12, "rows": 4, "columnGutter": 6, "rowGutter": 6 },
      "placement": {
        "strategy": "pattern",
        "slots": [
          { "columns": 8, "rows": 4, "asset": "Wide Product Card" },
          { "columns": 4, "rows": 4, "asset": "Small Product Card" }
        ]
      },
      "span": "auto"
    },
    {
      "name": "product-grid",
      "area": { "column": 1, "row": 5, "columnSpan": 12, "rowSpan": 6 },
      "grid": { "columns": 12, "rows": 8, "columnGutter": 6, "rowGutter": 6 },
      "placement": { "strategy": "dense" },
      "span": "auto"
    }
  ],
  "item": {
    "type": "formattingRule",
    "name": "product-card",
    "asset": "Product Card",
    "onEmpty": "omit"
  }
}
```

The top-level `grid` defines the region-allocation tracks for the complete space
available to the section. Its `columns` and `rows` are positive integers;
`columnGutter` and `rowGutter` are optional non-negative point values. A region's
one-based `area` selects cells in that grid. `columnSpan` and `rowSpan` are cell
counts. Region areas must remain inside the allocation grid and cannot overlap.
The region's own `grid` is separate: it controls item placement inside the
allocated rectangle. Regions are visited in array order.

`continuation` is required:

- `restartRegions` starts every new physical continuation area at the first
  region. This is appropriate when each page repeats the same upper-to-lower
  design.
- `resumeRegion` remembers the first region that still had data but could not
  place an item. The next physical continuation area begins with that region,
  then proceeds through the later regions. This is useful when earlier regions
  are optional phases and should not be revisited after a blocked later phase.

Both policies preserve exactly one source position and one deferred-item set.
They alter only which region is tried first on the next area; they never reset,
duplicate or independently reshape the data.

## 9. Declarative selectors

Declarative selectors allow a stored JSON plan to make data-dependent and
continuation-dependent choices without JavaScript callbacks. Expressions can
be used by:

- a section's direct dynamic properties;
- a section's `propertyResolver` property map;
- a section's `when` inclusion predicate;
- `continuation.parentSelector`;
- a document leaf's `parentSelector`.

For example, select an asset from an EasyCatalog field:

```json
{
  "type": "container",
  "name": "product",
  "asset": {
    "if": {
      "condition": {
        "equals": [
          { "field": "ProductType" },
          "Furniture"
        ]
      },
      "then": "Furniture Product",
      "else": "Standard Product"
    }
  }
}
```

The equivalent explicit property map is:

```json
{
  "propertyResolver": {
    "asset": {
      "if": {
        "condition": { "equals": [{ "field": "ProductType" }, "Furniture"] },
        "then": "Furniture Product",
        "else": "Standard Product"
      }
    },
    "verticalGutter": {
      "if": {
        "condition": { "equals": [{ "context": "occurrenceIndex" }, 0] },
        "then": 12,
        "else": 0
      }
    }
  }
}
```

Conditionally include a section:

```json
{
  "type": "formattingRule",
  "name": "published-label",
  "asset": "Published Label",
  "when": { "equals": [{ "field": "Published" }, "Yes"] }
}
```

Choose a continuation parent by area index:

```json
{
  "continuation": {
    "parentSelector": {
      "switch": {
        "value": { "context": "areaIndex" },
        "cases": [
          { "when": 0, "return": "B-Chapter" }
        ],
        "default": "C-Chapter Continued"
      }
    }
  }
}
```

Expression sources are:

- `{ "field": "Field Name" }`: current data-node field content;
- `{ "number": expression }`: the numeric value of an expression. When its
  operand is a direct field expression, the field definition's numeric parsing
  and separators are used;
- `{ "tabular": { "field": "VariantsXML", "property": "rowCount|columnCount" } }`:
  the current record's tabular backing-store dimensions;
- `{ "node": "name|path|type|groupName|count|indexInGroup|isFirstInGroup|isLastInGroup" }`;
- `{ "context": "..." }`: the context supplied to that selector;
- `{ "literal": value }`, or a scalar value directly.

`rowCount` is the number of actual tabular data records. It excludes DSV
grouping and display-header rows. `columnCount` is the tabular field's visible
column count. The operand returns `null` when the field, record, project or
tabular backing data cannot be resolved. Use `coalesce` when an unavailable
tabular field should behave as zero:

```json
{
  "when": {
    "greaterThan": [
      {
        "coalesce": [
          {
            "tabular": {
              "field": "VariantsXML",
              "property": "rowCount"
            }
          },
          0
        ]
      },
      0
    ]
  }
}
```

This reads the source tabular data without changing the plan's selected data.
The same operand can select a layout or asset. For
example, a `switch` can choose a compact variant table when `rowCount` is at
most four and a full-width table for larger data sets.

Resolver expressions use the same comparison and logical vocabulary as
`data.shape.where`: `equals`, `notEquals`, `lessThan`, `lessThanOrEqual`,
`greaterThan`, `greaterThanOrEqual`, `contains`, `startsWith`, `endsWith`,
`in`, `isEmpty`, `isMissing`, `all`, `any` and `not`. `and` and `or` are also
accepted as equivalents of `all` and `any`. Resolver expressions additionally
provide `modulo`, `if`, `switch`, `coalesce` and `concat` for calculation and
value selection.

`lessThan`, `lessThanOrEqual`, `greaterThan`, `greaterThanOrEqual` and
`modulo` require numeric operands. `contains`, `startsWith` and `endsWith`
compare their string representations case-sensitively. `in` has the form
`{ "in": [expression, [candidate, ...]] }`. `isEmpty` matches an existing
empty string and `isMissing` matches `null`. `modulo` returns the
remainder and rejects a zero divisor; for example,
`{ "modulo": [{ "context": "forEachIndex" }, 2] }` alternates between zero
and one. Use `number` to convert field content for a numeric comparison, for
example `{ "greaterThan": [{ "number": { "field": "Price" } }, 100] }`.
Expression structure is validated before composition begins.

Declarative section properties currently include asset and ruleset selection,
keep/required/detach policies, minimum items, offsets, mode, overflow, empty,
repeat and break policies, and the supported container geometry, fitting,
gutter, flow-direction and anchor properties.

String callback names are invalid in `propertyResolver`, section `when`,
continuation `parentSelector` and document-leaf `parentSelector`.

## 10. Declarative decision example

Sections carry their complete decision logic directly:

```json
{
  "type": "formattingRule",
  "name": "heading",
  "propertyResolver": {
    "asset": {
      "if": {
        "condition": { "equals": [{ "context": "continuation" }, true] },
        "then": "Header Continued",
        "else": "Header"
      }
    }
  },
  "when": { "equals": [{ "field": "Published" }, "Yes"] }
}
```

This makes both candidate formatting rules visible to validation and the plan
explanation before composition is attempted.

## 11. Validate and import

```javascript
var reportText = session.ecValidateCompositionPlanJSON(planText);
var report = eval("(" + reportText + ")");
if (!report.success) {
    throw new Error(report.errors[0].message);
}

var area = session.ecNewLayoutArea(app.activeDocument.pages[0], true);
var plan = area.ecNewCompositionPlanFromJSON(planText);
var result = plan.ecCompose();
```

Validation checks schema, known members, enum values, required structure,
nesting, declarative expressions, selectors and layout-pattern definitions. It does
not modify the document.

For checks against live EasyCatalog data and document resources, use:

```javascript
var check = JSON.parse(session.ecCheckCompositionPlanJSON(planText, {
    mode: "layout",
    target: app.activeDocument.pages[0],
    insideMargins: true,
    maximumAreas: 2,
    maximumDepth: 16
}));
```

`contract` performs JSON contract validation only. `resolve` imports the plan,
resolves its data selectors and declarative properties against the selected
data and initial target context, and verifies required formatting rules and
rule sets without placing or populating plan output. It checks every literal
asset candidate referenced by the plan, including resources in furniture,
adornments, flow regions, fit alternatives and nested plans. Optional missing
resources are warnings. Resolve mode also validates the authored rows, columns
and named groups required by table prototypes; enumerates literal continuation
parent alternatives; instantiates every continuation layout pattern against
each reachable parent page and its layer obstructions; and proves that a
remaining named thread can receive its required area. This catches unusable
parents and no-progress continuation branches before pages are inserted.
Resolve mode leaves the document unchanged, including when library resources
must be inspected. `layout`
performs a bounded trial composition and is the check for fit, overflow,
continuation-only choices and other geometry-dependent behaviour. Trial
placements, new pages, area state, furniture, and other InDesign commands are
rolled back before the method returns. Failures are returned in the report
rather than raised as scripting exceptions.

```json
{
  "schema": "easycatalog-composition-check/1",
  "success": false,
  "phase": "layout",
  "diagnostics": [
    {
      "level": "error",
      "code": "compositionFailed",
      "path": "",
      "message": "Could not place formatting-rule section: spacer-1"
    }
  ],
  "logs": [],
  "preview": {
    "placedCount": 6,
    "areaCount": 1,
    "hasRemainingContent": true,
    "threads": []
  },
  "rolledBack": true
}
```

The returned `easycatalog-composition-plan-validation/1` report contains an
`errors` array. Each diagnostic has a stable `code`, an RFC 6901 JSON Pointer
`path` and a human-readable `message`. When a close valid value is known, the
diagnostic also contains `expected`. Shape fields are checked against the
current selected EasyCatalog hierarchy, including fields used by nested
`where`, `sort`, `distinct` and `group` operations. For example:

```json
{
  "schema": "easycatalog-composition-plan-validation/1",
  "pathFormat": "json-pointer",
  "success": false,
  "errors": [
    {
      "code": "invalidShapeField",
      "path": "/threads/0/content/2/data/shape/sort/1/field",
      "message": "Field 'Prices' does not exist.",
      "expected": "Price"
    }
  ]
}
```

## 12. Structured results and compatibility

`ecCompositionResult.details` is versioned structured JSON describing section
results, committed placements, areas, fragments, continuation and rollback.
Use it for tests and diagnostics.

The result also contains `logs`, an immutable snapshot of messages emitted by
that validation or composition operation. Each message has `index`, `level`
and `message`. Failed results always contain their final error message. When
the composition session was created with logging enabled, the snapshot also
contains the scoped EasyCatalog trace messages and the same messages accumulate
in `ecCompositionSession.log`.

Compatibility rules:

1. Require the exact supported `schema` value.
2. Validate before import and composition.
3. Express all runtime choices through declarative selectors and expressions.
4. Generate plans from the current session manifest, not copied enum lists.
5. Do not emit properties not listed by the current manifest.
6. Keep geometry in points and bounds in `[top, left, bottom, right]` order.

## 13. Declarative and runtime boundaries

JSON v1 has parity with reusable composition-plan definitions: threads, all
section types and properties, flow regions and boundary leaves, layout
patterns, area furniture, nested container plans, data selectors and
declarative selectors. ExtendScript supplies the JSON and observes progress;
the JSON contract does not accept executable semantic callbacks.

### 13.1 Validation diagnostics

Each diagnostic contains `level`, `code`, an RFC 6901 JSON Pointer in `path`,
and `message`; `expected` is supplied when validation can identify a valid
replacement or close-name suggestion. When the selected hierarchy's field
names are available, field and expression errors can be reported before
composition. Validation results use the
`easycatalog-composition-plan-validation/1` schema.

Diagnostic codes are assigned by structural validation rules and are never
inferred from the wording of `message`. A fail-fast semantic check that has not
yet been given a narrower structured rule reports the honest fallback code
`invalid-plan` at the document root instead of guessing a type from English
text.

Validation, checking and plan import use the same JSON rules and diagnostic
contract, so accepted syntax and diagnostics do not vary between those entry
points.

The following are execution state rather than plan definition and remain in
the live ExtendScript API:

- the initial page, spread or layout-area object;
- explicit live continuation-area objects;
- document cursors and cursor persistence;
- compose-time progress, cancellation and maximum-area/depth limits;

These values are supplied when a JSON plan is imported or composed; they are
not serialized into the plan document.

### Outermost used group selection

A `collectNamedGroups` selector may specify `outermostUsedGroups`, a non-empty array of group names. The collector starts at the source itself, walks in hierarchy order, and stops descending each branch at the first matching group. This scopes generated plans to their outermost used group independently of section order. It reports an error if no group matches. This option cannot be combined with `name`, `recursive`, `includeSelf`, `leafOnly` or `maximumDepth`.

```json
{
  "source": "selectionRoot",
  "collector": "collectNamedGroups",
  "outermostUsedGroups": ["Department", "Category"],
  "result": "children"
}
```

The selection converter binds each result to `outerGroup` in a surrounding `forEach`. Selectors inside that sequence use `{"source":"variable","variable":"outerGroup"}` instead of `selectionRoot`; inner repeat variables remain unchanged.

### Positional authored cell attributes

`table.cellAttributes.byIndex` is an array of prototype cell settings, available
with `structure: "authored"`. `row` and `column` are zero-based coordinates in the
original table, including header and footer rows, before population expands it.
Every coordinate must be unique and identify an existing cell anchor; covered
positions in merged cells are invalid. Bounds and anchor validity are checked
against the actual asset during composition.

```json
"cellAttributes": {
  "byIndex": [
    {
      "row": 1,
      "column": 1,
      "mergeVertical": "matching",
      "mergeHorizontal": "none",
      "distributeSpannedRows": false,
      "distributeSpannedColumns": false
    }
  ]
}
```

Supported properties are `mergeHorizontal`, `mergeVertical`,
`distributeSpannedRows`, `distributeSpannedColumns` and `cellStyleFromField`,
with the same values as field-based cell attributes. Omitted properties retain
the asset's setting. Positional properties are applied before prototype copying;
subsequent `default` and `fields` overrides take precedence for properties they
explicitly specify. Existing group-furniture merge isolation still applies.
`mergeKeep` and `applyWhenLeftMerges` remain field-based options and are rejected
inside `byIndex`.

Plan conversion emits an entry for every logical authored cell, including blank
and static-text cells, with explicit merge and span-distribution settings and a
nonempty style-field name where configured. Static InDesign appearance and cell
topology remain supplied by the existing formatting-rule asset; conversion never creates a rule.

`spaceAfter` is a non-negative section spacing value in points (default 0; declarative expressions are supported). It advances the next section vertically after completion, independently of physical content bounds. Continuation fragments do not receive this trailing gap until the section completes. Nested flow bodies propagate their final child’s trailing spacing; a flow’s own spaceAfter is additional. Keep With Next probes include the spacing. Unused trailing space does not make an otherwise fitting item overset. Selection conversion now writes each outgoing authored edge gap as spaceAfter on its preceding item, replacing the nested-group boundary-flow workaround. Regenerate older converted plans to use this representation.

`trimTrailingSpace` is a flow boolean (default `false`; declarative expressions supported). On completion it discards inherited spacing from the final body/header/footer result, then the flow's own `spaceAfter` is added normally. Spacing between children and before a footer is unchanged. Continuation fragments retain their existing behaviour. Final-region balancing uses physical content bounds, which exclude this trailing spacing. Use `"trimTrailingSpace": true, "spaceAfter": 0` on the flow owning a multi-column body to remove inherited gaps before the following full-width heading. A nonzero outer `spaceAfter` gives an explicit group gap. Other section types have no trimming behaviour.


Flow header/footer regions and furniture use independent placements. A text-frame section is populated afresh for each repeated copy even when its authored `threadable` setting is true. The engine clears the saved story-continuation frame for each independent copy without changing its authored Threadable or fit settings; it preserves the continuation expression context (for example `when: {"context": "continuation"}`). Body text continues to use normal story threading.

### Space before

`spaceBefore` is non-negative vertical spacing in points, defaulting to `0`. It supports declarative expressions and adds to `verticalOffset`. It applies to the first fragment of each section occurrence, including a new occurrence starting at the top of a fresh area. Subsequent fragments of that same occurrence do not repeat it. Independently repeated headers receive the spacing on each occurrence. Omitted sections leave no spacing.

For example, put `"spaceBefore": 12` on the nested Category2 flow to separate each complete Category2 block from what precedes it. Put it on the header section instead when the gap belongs specifically to that header. The preceding section's `spaceAfter`, the thread gutter and this `spaceBefore` are additive; they do not collapse to a maximum.

```json
{
  "type": "formattingRule",
  "name": "group-heading",
  "asset": "Category heading",
  "spaceBefore": 12,
  "spaceAfter": 6,
  "keepWithNext": true
}
```

The gap consumes available vertical space for fitting and keep-with-next placement, but is not painted content. Static negative values are rejected; negative resolved expression values are clamped to zero. This is vertical spacing even in horizontal layouts. Adornments use their target-relative positioning and do not apply normal section spacing. Existing plans without `spaceBefore` retain their previous behaviour. Selection conversion continues to emit authored outgoing gaps as `spaceAfter`; this addition does not change conversion.

### Space before at an area boundary

`spaceBeforeAtAreaStart` accepts `"retain"` (default) or `"suppress"`, including declarative string expressions. Invalid values are rejected.

```json
"spaceBefore": 12,
"spaceBeforeAtAreaStart": "suppress"
```

With `suppress`, the leading space is dropped when the section is the first item in the current flow region. This includes the first body item beneath a header and the first item in a fresh continuation region. Sections following a previous item keep their leading space. Each nested flow body has its own boundary. A section retried into an empty region is evaluated there, so it can lose its leading space on retry.

Only `spaceBefore` is affected: an explicit `verticalOffset`, header `spaceAfter`, or gutter is not removed by this option. Continuations of the same occurrence still do not repeat leading space, regardless of this setting. Default `retain` preserves existing plans. This property does not insert breaks or change keep-with-next rules.

Container and template-container sections always use V2 composition. `legacyComposition` is not a supported plan property; remove it from older plans. This also overrides legacy settings inherited from a template asset.

`frameType` is no longer a supported plan property and is omitted during conversion. Remove it from older plan JSON. Native primary-text-frame markers in authored assets and automatic text-threading setup remain in effect.

A layout pattern may specify `columnWidth` (positive points) instead of `columns`, `rows`, or `areas`, with `columnGutter`. Each composition creates as many complete fixed-width columns as fit; unused width remains at the right for left-to-right reading. A container narrower than one column receives one area at its available width, with ordinary section fit/overflow rules. Resizing recalculates the columns. Existing fixed-count patterns are unchanged.

Selection conversion captures this pattern when a uniform, aligned vertical chain starts with a header linked to a separate continuation header on its right. The vertical chain width supplies `columnWidth`; the gap to the continuation header supplies `columnGutter`. The continuation header retains its existing repeat behavior. Self-links do not supply a gutter and do not trigger this inference.

Flow header sections support `"repeat": "every page"`. The header appears when its group starts and when that flow continues onto a different physical page; additional columns or containers on the same page omit it. Each flow/group occurrence tracks its own last header page. A first-area header and a separate every-page continuation variant share that page boundary, so the continuation variant does not appear in the second column of the initial page. Ordinary `when` conditions still apply.

Page-header state participates in progress checkpoints and persisted continuation state. Failed placement, balancing probes and rollback restore the previous page state; a fresh composition after resize starts with fresh state. Areas without an identifiable physical page repeat per area. This policy applies to flow headers; `"every area"` and converter defaults remain unchanged.

Flow headers also support `"repeat": "every spread"`. They appear when their group starts, then repeat on a different physical spread; crossing columns or left/right pages within the same spread does not repeat them. Spread tracking is independent of page tracking and participates in the same progress checkpoints and persisted continuation state. Areas with no identifiable spread repeat per area. Existing repeat policies and converter defaults are unchanged.

### AI-facing manifest guidance

The live manifest includes additive `authoring` instructions,
`authoring.documentationRoot`, and `compositionPlanJSON.layoutPatternContract`.
These describe authoring workflow, the published reference URL and grammar;
none belongs in a submitted plan. `authoring.documentationRoot` supplies the
version-appropriate published reference URL. The live manifest remains
authoritative for installed capabilities and document-specific names.
See [START-HERE](START-HERE.md) and
[AI Authoring Guide](Composition%20Plan%20AI%20Authoring%20Guide.md) for offline
use. The documentation URL is not a machine-readable discovery endpoint.
