Skip to content

sheet

sheet

Sheet entity model — the first-class execution unit in Marianne.

A Sheet carries everything a musician needs to execute: identity, instrument, prompt, context injection, validations, and timeout. Sheets are constructed at setup time from the parsed score and handed to the baton for dispatch.

The music metaphor: sheet music contains everything the musician needs to play their part — the notes, the key, the tempo, the dynamics. They don't need to see the full score. They need their sheet.

What's NOT on the Sheet: dependencies, skip_when, retry policy, execution state, cost limits. Those belong to the baton and state systems. The Sheet is execution data; the baton owns coordination logic.

Prompt rendering is deferred. The template stays unrendered because cross-sheet context ({{ previous_outputs[2] }}) only exists after earlier sheets complete. The baton renders at dispatch time.

Attributes

Classes

Sheet

Bases: BaseModel

A fully self-contained execution unit. Everything a musician needs.

Constructed at setup time from the parsed score YAML. Immutable after construction — the baton dispatches Sheet entities as-is.

Identity

num: Concrete sheet number (1-indexed, globally unique within a job) movement: Which movement this sheet belongs to (was: stage) voice: Which voice in a harmonized movement (was: instance), None if solo voice_count: Total voices in this movement (was: fan_count)

Execution

instrument_name: Resolved instrument name (e.g. 'gemini-cli') instrument_config: Overrides for instrument defaults (model, timeout, etc.) prompt_template: Raw Jinja2 template (rendered at dispatch time) template_file: External template file (alternative to inline) variables: Static template variables from the score timeout_seconds: Per-sheet execution timeout

Context injection

prelude: Shared context injected into all sheets cadenza: Per-sheet context injection — this sheet's movement cadenza items (every voice of its stage, or one voice via voice:) read first, then its sheet.cadenzas items prompt_extensions: Additional prompt directives

Acceptance criteria

validations: What "done" means for this sheet

Methods:
template_variables
template_variables(total_sheets, total_movements)

Build the full template variable dict for Jinja2 rendering.

Merges built-in variables (identity, workspace, instrument) with the score's custom variables. Built-in variables take precedence over custom variables to prevent accidental overrides.

New and old terminology aliases are both provided — old names (stage, instance, fan_count, total_stages) are kept forever for backward compatibility.

Parameters:

Name Type Description Default
total_sheets int

Total concrete sheet count in the job.

required
total_movements int

Total movement count in the job.

required

Returns:

Type Description
dict[str, Any]

Dict of all template variables for Jinja2 rendering.

Source code in src/marianne/core/sheet.py
def template_variables(
    self,
    total_sheets: int,
    total_movements: int,
) -> dict[str, Any]:
    """Build the full template variable dict for Jinja2 rendering.

    Merges built-in variables (identity, workspace, instrument) with
    the score's custom variables. Built-in variables take precedence
    over custom variables to prevent accidental overrides.

    New and old terminology aliases are both provided — old names
    (stage, instance, fan_count, total_stages) are kept forever for
    backward compatibility.

    Args:
        total_sheets: Total concrete sheet count in the job.
        total_movements: Total movement count in the job.

    Returns:
        Dict of all template variables for Jinja2 rendering.
    """
    # Start with custom variables (lowest precedence)
    tvars: dict[str, Any] = dict(self.variables)

    # Built-in variables (override custom)
    tvars.update({
        # Core identity
        SHEET_NUM_KEY: self.num,
        "total_sheets": total_sheets,
        "workspace": str(self.workspace),
        "instrument_name": self.instrument_name,
        "instrument_alias": self.instrument_alias,
        # movement/voice vocabulary + legacy stage/instance aliases, from
        # the one shared table (GH #267)
        **positional_template_variables(
            movement=self.movement,
            voice=self.voice,
            voice_count=self.voice_count,
            total_movements=total_movements,
        ),
    })

    # Score-location anchor: the resolved directory holding this score
    # file. Prompts, validations, and hooks use it to reference repo
    # files and sibling scores portably. Emitted ONLY when the Sheet
    # knows its score file — never a bogus default.
    if self.score_path is not None:
        tvars["score_dir"] = str(self.score_path.parent)

    return tvars

Functions:

order_alias_entries

order_alias_entries(definition, *, use_index, movement_use_index, profiles=None)

The alias's entries in the order this use of the alias should try them.

use_index counts every sheet that binds the alias (score order); movement_use_index counts uses within the sheet's movement. Modifiers compose in the order written: cheapest/widest sort, cycle/ spread rotate the sorted order by the matching index, balance is left to dispatch. Entries whose metric is unknown keep their authored position after the known ones (a missing profile never reorders silently into first place).

Source code in src/marianne/core/sheet.py
def order_alias_entries(
    definition: InstrumentDef,
    *,
    use_index: int,
    movement_use_index: int,
    profiles: dict[str, Any] | None = None,
) -> list[AliasEntry]:
    """The alias's entries in the order this use of the alias should try them.

    ``use_index`` counts every sheet that binds the alias (score order);
    ``movement_use_index`` counts uses within the sheet's movement. Modifiers
    compose in the order written: ``cheapest``/``widest`` sort, ``cycle``/
    ``spread`` rotate the sorted order by the matching index, ``balance`` is
    left to dispatch. Entries whose metric is unknown keep their authored
    position after the known ones (a missing profile never reorders silently
    into first place).
    """
    entries = list(definition.entries)
    if len(entries) < 2 or not definition.select:
        return entries
    profiles = profiles if profiles is not None else _alias_profiles()
    def _by_metric(field: str, *, descending: bool) -> list[AliasEntry]:
        scored = [(_entry_metric(e, profiles, field), e) for e in entries]
        known = [(m, e) for m, e in scored if m is not None]
        unknown = [e for m, e in scored if m is None]
        known.sort(key=lambda t: -t[0] if descending else t[0])
        return [e for _, e in known] + unknown

    for modifier in definition.select:
        if modifier == "cheapest":
            entries = _by_metric("cost_per_1k_input", descending=False)
        elif modifier == "widest":
            entries = _by_metric("context_window", descending=True)
        elif modifier == "cycle":
            k = use_index % len(entries)
            entries = entries[k:] + entries[:k]
        elif modifier == "spread":
            k = movement_use_index % len(entries)
            entries = entries[k:] + entries[:k]
        # "balance" is a dispatch-time choice; the order is left as built.
    return entries

build_sheets

build_sheets(config, *, classes=None)

Construct Sheet entities from a JobConfig.

This bridges the old scattered-dict model (SheetConfig with separate dicts for descriptions, cadenzas, prompt_extensions, etc.) to the new first-class Sheet entity. Each concrete sheet in the job gets a fully self-contained Sheet object.

The music metaphor: this is the librarian distributing parts to musicians before the concert. Each musician gets their own sheet with everything they need — they don't need to consult the full score.

Parameters:

Name Type Description Default
config JobConfig

Parsed and validated JobConfig from the score YAML.

required

Returns:

Type Description
list[Sheet]

List of Sheet entities, one per concrete sheet, in sheet_num order.

Source code in src/marianne/core/sheet.py
def build_sheets(config: JobConfig, *, classes: ClassSnapshot | None = None) -> list[Sheet]:
    """Construct Sheet entities from a JobConfig.

    This bridges the old scattered-dict model (SheetConfig with separate
    dicts for descriptions, cadenzas, prompt_extensions, etc.) to the new
    first-class Sheet entity. Each concrete sheet in the job gets a fully
    self-contained Sheet object.

    The music metaphor: this is the librarian distributing parts to musicians
    before the concert. Each musician gets their own sheet with everything
    they need — they don't need to consult the full score.

    Args:
        config: Parsed and validated JobConfig from the score YAML.

    Returns:
        List of Sheet entities, one per concrete sheet, in sheet_num order.
    """
    sheets: list[Sheet] = []
    total_sheets = config.sheet.total_sheets
    products = declared_products_from_config(config)
    # Proxy-only scores retain their legacy guard behavior, including shared
    # validation paths. Explicit declarations/stdout enable co-ownership.
    product_signals = products if has_declared_outputs(config) else config.validations

    # Alias select modifiers (#473): each alias use is counted in sheet order
    # (`cycle`) and per movement (`spread`), so rotation is deterministic for
    # a given score and survives resume (build_sheets is replayed, not saved).
    alias_uses: dict[str, int] = {}
    alias_movement_uses: dict[tuple[str, int], int] = {}
    alias_profiles: dict[str, Any] | None = None

    # Pre-build reverse lookup for instrument_map: sheet_num -> instrument_name
    instrument_map_lookup: dict[int, str] = {}
    for instr_name, sheet_nums in config.sheet.instrument_map.items():
        for sn in sheet_nums:
            instrument_map_lookup[sn] = instr_name

    for sheet_num in range(1, total_sheets + 1):
        # --- Identity ---
        fan_meta = config.sheet.get_fan_out_metadata(sheet_num)
        movement = fan_meta.stage
        voice: int | None = fan_meta.instance if fan_meta.fan_count > 1 else None
        voice_count = fan_meta.fan_count

        description = config.sheet.descriptions.get(sheet_num)

        # --- Instrument resolution chain ---
        # Priority: per_sheet > instrument_map > movement > score instrument > backend.type
        instrument_config: dict[str, Any] = dict(config.instrument_config)

        # Walk the resolution chain from highest to lowest priority
        resolved_instrument: str | None = None

        if sheet_num in config.sheet.per_sheet_instruments:
            # Highest priority: explicit per-sheet assignment
            resolved_instrument = config.sheet.per_sheet_instruments[sheet_num]
        elif sheet_num in instrument_map_lookup:
            # Batch assignment via instrument_map
            resolved_instrument = instrument_map_lookup[sheet_num]
        else:
            # Check movement-level instrument and config
            if movement in config.movements:
                movement_def = config.movements[movement]
                if movement_def.instrument is not None:
                    resolved_instrument = movement_def.instrument
                # Movement-level instrument_config merges with score-level
                # regardless of whether the movement also overrides the
                # instrument name. A score author should be able to say
                # "same instrument, different model" without repeating
                # the instrument name. F-150: this was gated behind
                # instrument is not None, silently dropping config-only
                # movement overrides.
                if movement_def.instrument_config:
                    instrument_config = {
                        **instrument_config,
                        **movement_def.instrument_config,
                    }
            # Fall through to score-level or the default instrument
            if resolved_instrument is None:
                resolved_instrument = config.effective_instrument_name

        requested_instrument = resolved_instrument
        class_tail: list[ClassEntry] = []
        class_primary = False

        # Resolve score-level instrument aliases to profile names.
        # If the resolved name matches a key in config.instruments, replace
        # it with the profile name and merge the InstrumentDef config.
        alias_tail: list[AliasEntry] = []
        alias_level_config: dict[str, Any] = {}
        balance_chain = False
        bound_alias = ""
        if resolved_instrument in config.instruments:
            instrument_def = config.instruments[resolved_instrument]
            alias_name = resolved_instrument
            bound_alias = alias_name
            if instrument_def.chain is not None:
                if instrument_def.select and any(
                    m in ("cheapest", "widest") for m in instrument_def.select
                ) and alias_profiles is None:
                    alias_profiles = _alias_profiles()
                use_index = alias_uses.get(alias_name, 0)
                movement_use_index = alias_movement_uses.get((alias_name, movement), 0)
                alias_uses[alias_name] = use_index + 1
                alias_movement_uses[(alias_name, movement)] = movement_use_index + 1
                ordered = order_alias_entries(
                    instrument_def,
                    use_index=use_index,
                    movement_use_index=movement_use_index,
                    profiles=alias_profiles,
                )
                head, alias_tail = ordered[0], ordered[1:]
                resolved_instrument = head.profile
                if instrument_def.config:
                    alias_level_config = dict(instrument_def.config)
                    instrument_config = {**instrument_config, **alias_level_config}
                if head.config:
                    instrument_config = {**instrument_config, **head.config}
                balance_chain = "balance" in instrument_def.select
            else:
                resolved_instrument = instrument_def.profile or resolved_instrument
                if instrument_def.config:
                    instrument_config = {**instrument_config, **instrument_def.config}
        elif classes is not None and resolved_instrument in classes.classes:
            class_primary = True
            chain = classes.classes[resolved_instrument].chain
            resolved_instrument = chain[0].profile
            if chain[0].config.model is not None:
                instrument_config["model"] = chain[0].config.model
            # A class entry's effort is the default for its seat; a score,
            # movement or sheet scope that names effort (even null) wins.
            if chain[0].config.effort is not None and "effort" not in instrument_config:
                instrument_config["effort"] = chain[0].config.effort
            if chain[0].config.tools is not None and "tools" not in instrument_config:
                instrument_config["tools"] = list(chain[0].config.tools)
            class_tail = chain[1:]

        instrument_name: str = resolved_instrument

        # Per-sheet instrument config overrides everything
        if sheet_num in config.sheet.per_sheet_instrument_config:
            instrument_config = {
                **instrument_config,
                **config.sheet.per_sheet_instrument_config[sheet_num],
            }

        # --- Timeout ---
        # From the merged instrument_config (score -> movement -> alias ->
        # per-sheet merges above), so per-scope timeout_seconds overrides
        # compose exactly like every other instrument knob. Falls back to
        # the 30-minute default. (Replaced the legacy backend.timeout_*
        # fields when backend: was stripped, #347.)
        raw_timeout = instrument_config.get("timeout_seconds")
        try:
            timeout = float(raw_timeout) if raw_timeout is not None else 1800.0
        except (TypeError, ValueError):
            timeout = 1800.0

        # --- Prompt ---
        prompt_template = config.prompt.template
        template_file = config.prompt.template_file
        variables = dict(config.prompt.variables)

        # --- Context Injection ---
        prelude = list(config.sheet.prelude)
        cadenza = cadenzas_for_sheet(config, sheet_num)

        # Prompt extensions: score-level + per-sheet
        extensions = list(config.prompt.prompt_extensions)
        per_sheet_ext = config.sheet.prompt_extensions.get(sheet_num, [])
        extensions.extend(per_sheet_ext)

        # --- Validations ---
        # Score-level validations apply to all sheets
        validations = list(config.validations)
        # Artifacts other, non-ancestor sheets are declared to produce (#386).
        foreign = foreign_artifacts(sheet_num, product_signals, config.sheet.dependencies)

        # --- Instrument Fallbacks ---
        # Resolution: per_sheet > movement > score-level
        # Per-sheet replaces (does not merge) inherited chain.
        if sheet_num in config.sheet.per_sheet_fallbacks:
            fallbacks = list(config.sheet.per_sheet_fallbacks[sheet_num])
        elif (
            movement in config.movements
            and "instrument_fallbacks" in config.movements[movement].model_fields_set
        ):
            fallbacks = list(config.movements[movement].instrument_fallbacks)
        else:
            fallbacks = list(config.instrument_fallbacks)

        # Resolve score-local aliases in the fallback chain to profile names and
        # capture each alias's config, index-aligned (#342). Mirrors the primary
        # resolution above (:261-268), but keeps each fallback's config separate
        # rather than merging into the sheet's instrument_config — the baton
        # applies it on fallback advance. A bare profile name → empty config.
        resolved_fallbacks: list[str] = []
        fallback_configs: list[dict[str, Any]] = []
        used_class = class_primary
        # The rest of a multi-entry alias chain comes first: it is the alias's
        # own fallback order, ahead of any score-level fallbacks (#473).
        for alias_entry in alias_tail:
            resolved_fallbacks.append(alias_entry.profile)
            merged_entry = {**alias_level_config, **dict(alias_entry.config)}
            fallback_configs.append(merged_entry)
        for entry in class_tail:
            resolved_fallbacks.append(entry.profile)
            fallback_configs.append(_class_entry_config(entry))
        for fb_name in fallbacks:
            fb_def = config.instruments.get(fb_name)
            if fb_def is not None:
                # An alias in a fallback list contributes every entry, in its
                # authored order (modifiers rotate primaries, not fallbacks).
                for fb_entry in fb_def.entries:
                    resolved_fallbacks.append(fb_entry.profile)
                    merged = (
                        {**dict(fb_def.config), **dict(fb_entry.config)}
                        if fb_def.chain else dict(fb_entry.config)
                    )
                    fallback_configs.append(merged if merged else {})
            elif classes is not None and fb_name in classes.classes:
                used_class = True
                for entry in classes.classes[fb_name].chain:
                    resolved_fallbacks.append(entry.profile)
                    fallback_configs.append(_class_entry_config(entry))
            else:
                resolved_fallbacks.append(fb_name)
                fallback_configs.append({})

        dropped_duplicates: list[str] = []
        if used_class:
            seen = {(instrument_name, instrument_config.get("model"))}
            unique_names: list[str] = []
            unique_configs: list[dict[str, Any]] = []
            for name, fb_config in zip(resolved_fallbacks, fallback_configs, strict=True):
                model = fb_config.get("model")
                key = (name, model)
                if key in seen:
                    dropped_duplicates.append(_entry_label(name, model))
                    continue
                seen.add(key)
                unique_names.append(name)
                unique_configs.append(fb_config)
            resolved_fallbacks = unique_names
            fallback_configs = unique_configs

        resolution = None
        if class_primary and classes is not None:
            resolution = InstrumentResolution(
                requested=requested_instrument,
                chain=[
                    _entry_label(instrument_name, instrument_config.get("model")),
                    *[
                        _entry_label(name, fb_config.get("model"))
                        for name, fb_config in zip(
                            resolved_fallbacks, fallback_configs, strict=True,
                        )
                    ],
                ],
                dropped_duplicates=dropped_duplicates,
                snapshot_digest=classes.digest,
            )

        sheets.append(
            Sheet(
                num=sheet_num,
                movement=movement,
                voice=voice,
                voice_count=voice_count,
                mailbox_siblings=(
                    {
                        num: config.sheet.descriptions.get(num, f"Sheet {num}")
                        for num, meta in (config.sheet.fan_out_stage_map or {}).items()
                        if meta["stage"] == movement
                    }
                    if voice_count > 1 and config.sheet.fan_out_messaging == "file" else {}
                ),
                description=description,
                workspace=config.workspace,
                score_path=config.source_path,
                instrument_name=instrument_name,
                instrument_alias=bound_alias,
                instrument_config=instrument_config,
                instrument_fallbacks=resolved_fallbacks,
                instrument_fallback_configs=fallback_configs,
                instrument_resolution=resolution,
                balance_chain=balance_chain,
                prompt_template=prompt_template,
                template_file=template_file,
                variables=variables,
                prelude=prelude,
                cadenza=cadenza,
                prompt_extensions=extensions,
                validations=validations,
                foreign_artifacts=foreign,
                foreign_artifact_policy=config.workspace_lifecycle.foreign_artifacts,
                stdout_to=config.sheet.stdout_to.get(sheet_num),
                timeout_seconds=timeout,
            )
        )

    return sheets