Skip to content

job

job

Job and sheet configuration models.

Defines the top-level JobConfig, SheetConfig, and PromptConfig models.

Attributes

MAX_VARIABLE_FAN_OUT_WIDTH module-attribute

MAX_VARIABLE_FAN_OUT_WIDTH = 1000

Upper bound on a fan-out width resolved from a prompt variable (#569).

Classes

InjectionCategory

Bases: str, Enum

Category for injected content in prelude/cadenza system.

Determines WHERE in the prompt the injected content appears: - context: Background knowledge, after template body - skill: Methodology/instructions, after preamble - tool: Available actions, after preamble

InjectionItem

Bases: BaseModel

A single injection item referencing a file or directory with a category.

Used in prelude (all sheets) and cadenzas (per-sheet) to inject file content into prompts at category-appropriate locations.

Supports two mutually exclusive modes: - file: inject a single file's content - directory: inject all files in a directory (directory cadenza)

Methods:
exactly_one_source
exactly_one_source()

Ensure exactly one of file or directory is specified.

Source code in src/marianne/core/config/job.py
@model_validator(mode="after")
def exactly_one_source(self) -> InjectionItem:
    """Ensure exactly one of file or directory is specified."""
    if self.file and self.directory:
        raise ValueError("Specify 'file' or 'directory', not both.")
    if not self.file and not self.directory:
        raise ValueError("One of 'file' or 'directory' is required.")
    return self

MovementCadenzaItem

Bases: InjectionItem

A cadenza declared on a movement, so it reaches every voice of that stage (#571).

Same shape as an :class:InjectionItem (file or directory, as, required, max_bytes), plus voice to narrow the item to one voice of the fan-out instead of every voice. Legal only under movements.<n>.cadenzas; a voice spelled under sheet.prelude or sheet.cadenzas is an unknown field there: it is stripped and reported as V010 (a warning that names movements.cadenzas.voice).

AliasEntry

Bases: BaseModel

One entry of a multi-entry alias chain: a profile and its settings.

InstrumentDef

Bases: BaseModel

A named instrument definition within a score.

Allows a score to declare reusable instrument aliases that reference registered instrument profiles with optional configuration overrides. These aliases can then be referenced by name in per-sheet or per-movement instrument assignments.

An alias binds ONE profile (profile + config) or an ordered chain of entries with select modifiers that decide which entry a given sheet starts on; the rest of the chain follows as that sheet's fallbacks. Build-time modifiers order the chain per sheet; balance is applied by the conductor at dispatch.

Example YAML::

instruments:
  fast-writer:
    profile: gemini-cli
    config:
      model: gemini-2.5-flash
      timeout_seconds: 300
  reviewer:
    chain:
      - {profile: codex-cli, config: {model: gpt-6-astra}}
      - {profile: claude-code, config: {model: claude-opus-5-5}}
      - {profile: opencode, config: {model: zai-coding-plan/glm-5.3-flash}}
    select: [spread, balance]
Attributes
entries property
entries

The alias's ordered entries: the chain, or the single profile.

MovementDef

Bases: BaseModel

Declaration of a movement within a score.

Movements are sequential execution phases. Each movement can specify a name, an instrument (overriding the score default), instrument config, and a voice count (shorthand for fan-out). A movement can also declare cadenzas — context injected into every voice of the movement (GH #571).

Example YAML::

movements:
  1:
    name: Planning
    instrument: claude-code
  2:
    name: Implementation
    voices: 3
    instrument: gemini-cli
    cadenzas:
      - {file: "{{ workspace }}/shared-plan.md", as: context}
      - {voice: 2, file: "{{ workspace }}/only-voice-2.md", as: context}
  3:
    name: Review

SheetConfig

Bases: BaseModel

Configuration for sheet processing.

In Marianne's musical theme, a composition is divided into sheets, each containing a portion of the work to be performed.

Fan-out support: When fan_out is specified, stages are expanded into concrete sheets at parse time. For example, total_items=7, fan_out={2: 3} produces 9 concrete sheets (stage 2 instantiated 3 times). After expansion, total_items and dependencies reflect expanded values, and fan_out is cleared to {} to prevent re-expansion on resume.

A count may name a prompt.variables entry instead of a literal ('{{ chapter_count }}'). It is resolved to an integer before this model validates, by :func:resolve_fan_out_width through JobConfig. Resolved references enter this class as integers; the field's own type remains dict[int, int]. This class does not resolve anything itself: built directly with a '{{ name }}' count, it refuses it as a non-integer. A reference that cannot be resolved is V338, raised while the JobConfig loads.

A loop's max_iterations or count may likewise name a prompt.variables entry ('{{ max_passes }}', dotted paths allowed). JobConfig resolves it to an integer in 1..10000 before this model validates, exactly as it resolves a fan-out width; this class resolves nothing itself, and built directly with a reference it refuses it as a non-integer. A reference that cannot be resolved is V351, raised while the JobConfig loads.

Attributes
total_sheets property
total_sheets

Calculate total number of sheets.

total_stages property
total_stages

Return the original stage count.

After fan-out expansion, total_items reflects expanded sheet count. total_stages preserves the original logical stage count from fan_out_stage_map. When no fan-out was used, total_stages == total_sheets (identity).

Methods:
strip_computed_fields classmethod
strip_computed_fields(data)

Strip computed properties that users may include in YAML.

total_sheets is computed from size/total_items, not configurable. Accept it silently for backward compatibility — rejecting it would break existing scores that include it.

119 migration guidance: skip_when_command was renamed to

skip_when (the old expression-based skip_when was never evaluated at runtime and is removed). Both legacy shapes fail LOUDLY with the fix, instead of a generic pydantic error.

Source code in src/marianne/core/config/job.py
@model_validator(mode="before")
@classmethod
def strip_computed_fields(cls, data: Any) -> Any:
    """Strip computed properties that users may include in YAML.

    total_sheets is computed from size/total_items, not configurable.
    Accept it silently for backward compatibility — rejecting it would
    break existing scores that include it.

    #119 migration guidance: ``skip_when_command`` was renamed to
    ``skip_when`` (the old expression-based skip_when was never
    evaluated at runtime and is removed). Both legacy shapes fail
    LOUDLY with the fix, instead of a generic pydantic error.
    """
    if isinstance(data, dict):
        for section in ("loops", "triggers"):
            mapping = data.get(section)
            if not isinstance(mapping, dict):
                continue
            normalized: dict[str, Any] = {}
            original: dict[str, object] = {}
            for raw, value in mapping.items():
                try:
                    span = canonical_span(raw)
                except ValueError:
                    # Pydantic reports the invalid key at its normal location.
                    continue
                if span in normalized:
                    raise FlowConfigError(
                        (
                            FlowIssue(
                                "V-FLOW-07",
                                span,
                                f"{section} keys {original[span]!r} and {raw!r} "
                                "name the same span",
                                "merge the two declarations",
                            ),
                        )
                    )
                normalized[span] = value
                original[span] = raw
            if len(normalized) == len(mapping):
                data[section] = normalized
        if "total_sheets" in data:
            data.pop("total_sheets")
        if "skip_when_command" in data:
            raise ValueError(
                "sheet.skip_when_command was renamed to skip_when (#119). "
                "Rename the key — the value shape is unchanged "
                "({sheet_num: {command: ..., description: ...}})."
            )
        skip_when = data.get("skip_when")
        if isinstance(skip_when, dict) and any(isinstance(v, str) for v in skip_when.values()):
            raise ValueError(
                "Expression-based skip_when was removed (#119) — it was "
                "never evaluated at runtime. skip_when now takes a "
                "command predicate per sheet: "
                "{sheet_num: {command: 'shell command (exit 0 = skip)'}}. "
                "For skipping when inputs did not change since the last pass, use "
                "{sheet_num: {unchanged: true}} (GH #570)."
            )
    return data
validate_per_sheet_instruments classmethod
validate_per_sheet_instruments(v)

Validate per-sheet instrument assignments.

Source code in src/marianne/core/config/job.py
@field_validator("per_sheet_instruments")
@classmethod
def validate_per_sheet_instruments(
    cls,
    v: dict[int, str],
) -> dict[int, str]:
    """Validate per-sheet instrument assignments."""
    for sheet_num, instrument in v.items():
        if not isinstance(sheet_num, int) or sheet_num < 1:
            raise ValueError(
                f"Per-sheet instrument key must be a positive integer, got {sheet_num}"
            )
        if not instrument:
            raise ValueError(
                f"Per-sheet instrument name for sheet {sheet_num} must not be empty"
            )
    return v
validate_per_sheet_fallbacks classmethod
validate_per_sheet_fallbacks(v)

Validate per-sheet fallback chain keys are positive integers.

Source code in src/marianne/core/config/job.py
@field_validator("per_sheet_fallbacks")
@classmethod
def validate_per_sheet_fallbacks(
    cls,
    v: dict[int, list[str]],
) -> dict[int, list[str]]:
    """Validate per-sheet fallback chain keys are positive integers."""
    for sheet_num in v:
        if not isinstance(sheet_num, int) or sheet_num < 1:
            raise ValueError(
                f"Per-sheet fallback key must be a positive integer, got {sheet_num}"
            )
    return v
validate_instrument_map classmethod
validate_instrument_map(v)

Validate instrument_map: no duplicate sheets, valid names.

Source code in src/marianne/core/config/job.py
@field_validator("instrument_map")
@classmethod
def validate_instrument_map(
    cls,
    v: dict[str, list[int]],
) -> dict[str, list[int]]:
    """Validate instrument_map: no duplicate sheets, valid names."""
    seen_sheets: dict[int, str] = {}
    for instrument, sheets in v.items():
        if not instrument:
            raise ValueError("Instrument name in instrument_map must not be empty")
        for sheet_num in sheets:
            if not isinstance(sheet_num, int) or sheet_num < 1:
                raise ValueError(
                    f"Sheet number in instrument_map must be a positive "
                    f"integer, got {sheet_num} for instrument '{instrument}'"
                )
            if sheet_num in seen_sheets:
                raise ValueError(
                    f"Sheet {sheet_num} assigned to multiple instruments "
                    f"in instrument_map: '{seen_sheets[sheet_num]}' and "
                    f"'{instrument}'"
                )
            seen_sheets[sheet_num] = instrument
    return v
get_fan_out_metadata
get_fan_out_metadata(sheet_num)

Get fan-out metadata for a specific sheet.

Parameters:

Name Type Description Default
sheet_num int

Concrete sheet number (1-indexed).

required

Returns:

Type Description
FanOutMetadata

FanOutMetadata with stage, instance, and fan_count.

FanOutMetadata

When no fan-out is configured, returns identity metadata

FanOutMetadata

(stage=sheet_num, instance=1, fan_count=1).

Source code in src/marianne/core/config/job.py
def get_fan_out_metadata(self, sheet_num: int) -> FanOutMetadata:  # noqa: F821
    """Get fan-out metadata for a specific sheet.

    Args:
        sheet_num: Concrete sheet number (1-indexed).

    Returns:
        FanOutMetadata with stage, instance, and fan_count.
        When no fan-out is configured, returns identity metadata
        (stage=sheet_num, instance=1, fan_count=1).
    """
    from marianne.core.fan_out import FanOutMetadata

    if self.fan_out_stage_map and sheet_num in self.fan_out_stage_map:
        meta = self.fan_out_stage_map[sheet_num]
        return FanOutMetadata(
            stage=meta["stage"],
            instance=meta["instance"],
            fan_count=meta["fan_count"],
        )
    return FanOutMetadata(stage=sheet_num, instance=1, fan_count=1)
validate_fan_out classmethod
validate_fan_out(v)

Validate fan_out field values.

Source code in src/marianne/core/config/job.py
@field_validator("fan_out")
@classmethod
def validate_fan_out(cls, v: dict[int, int]) -> dict[int, int]:
    """Validate fan_out field values."""
    for stage, count in v.items():
        if not isinstance(stage, int) or stage < 1:
            raise ValueError(f"Fan-out stage must be positive integer, got {stage}")
        if not isinstance(count, int) or count < 1:
            raise ValueError(f"Fan-out count for stage {stage} must be >= 1, got {count}")
    return v
validate_dependencies classmethod
validate_dependencies(v, info)

Validate dependency declarations.

Note: Full validation (range checks, cycle detection) happens when the DependencyDAG is built at runtime, since total_sheets isn't available during field validation.

Source code in src/marianne/core/config/job.py
@field_validator("dependencies")
@classmethod
def validate_dependencies(
    cls, v: dict[int, list[int]], info: ValidationInfo
) -> dict[int, list[int]]:
    """Validate dependency declarations.

    Note: Full validation (range checks, cycle detection) happens when
    the DependencyDAG is built at runtime, since total_sheets isn't
    available during field validation.
    """
    for sheet_num, deps in v.items():
        if not isinstance(sheet_num, int) or sheet_num < 1:
            raise ValueError(f"Sheet number must be positive integer, got {sheet_num}")
        if not isinstance(deps, list):
            raise ValueError(f"Dependencies for sheet {sheet_num} must be a list")
        for dep in deps:
            if not isinstance(dep, int) or dep < 1:
                raise ValueError(
                    f"Dependency must be positive integer, got {dep} for sheet {sheet_num}"
                )
            if dep == sheet_num:
                raise ValueError(f"Sheet {sheet_num} cannot depend on itself")
    return v
expand_fan_out_config
expand_fan_out_config()

Expand fan_out declarations into concrete sheet assignments.

This runs after field validators. When fan_out is non-empty: 1. Validates constraints (size=1, start_item=1) 2. Calls expand_fan_out() to compute concrete sheet assignments 3. Overwrites total_items and dependencies with expanded values 4. Stores metadata in fan_out_stage_map for resume support 5. Clears fan_out={} to prevent re-expansion on resume

Source code in src/marianne/core/config/job.py
@model_validator(mode="after")
def expand_fan_out_config(self) -> SheetConfig:
    """Expand fan_out declarations into concrete sheet assignments.

    This runs after field validators. When fan_out is non-empty:
    1. Validates constraints (size=1, start_item=1)
    2. Calls expand_fan_out() to compute concrete sheet assignments
    3. Overwrites total_items and dependencies with expanded values
    4. Stores metadata in fan_out_stage_map for resume support
    5. Clears fan_out={} to prevent re-expansion on resume
    """
    if not self.fan_out:
        return self

    # Enforce constraints for fan-out
    if self.size != 1:
        raise ValueError(
            f"fan_out requires size=1, got size={self.size}. "
            "Each stage must map to exactly one sheet for fan-out to work."
        )
    if self.start_item != 1:
        raise ValueError(
            f"fan_out requires start_item=1, got start_item={self.start_item}. "
            "Fan-out stages are 1-indexed from the beginning."
        )

    from marianne.core.fan_out import expand_fan_out

    expansion = expand_fan_out(
        total_stages=self.total_items,
        fan_out=self.fan_out,
        stage_dependencies=self.dependencies,
    )

    # Overwrite with expanded values
    self.total_items = expansion.total_sheets
    self.dependencies = expansion.expanded_dependencies

    # Expand skip_when: stage-keyed → sheet-keyed
    if self.skip_when:
        expanded_skip_when: dict[int, SkipWhenCommand] = {}
        for stage, cmd in self.skip_when.items():
            for sheet_num in expansion.stage_sheets.get(stage, [stage]):
                expanded_skip_when[sheet_num] = cmd
        self.skip_when = expanded_skip_when

    # Expand stdout_to the same way; a fanned-out stage's voices would
    # otherwise overwrite one file, so each voice gets its own suffix.
    if self.stdout_to:
        expanded_stdout_to: dict[int, str] = {}
        for stage, target in self.stdout_to.items():
            voices = expansion.stage_sheets.get(stage, [stage])
            for sheet_num in voices:
                if len(voices) > 1:
                    stem, dot, ext = target.rpartition(".")
                    suffixed = dot and "/" not in ext
                    expanded_stdout_to[sheet_num] = (
                        f"{stem}-{sheet_num}.{ext}" if suffixed else f"{target}-{sheet_num}"
                    )
                else:
                    expanded_stdout_to[sheet_num] = target
        self.stdout_to = expanded_stdout_to

    def concrete_span(span: str) -> str:
        first_stage, last_stage = span_bounds(span)
        first = expansion.stage_sheets.get(first_stage)
        last = expansion.stage_sheets.get(last_stage)
        if not first or not last:
            return span  # the positioned range check below reports it
        start, end = first[0], last[-1]
        return str(start) if start == end else f"{start}-{end}"

    if self.loops:
        self.loops = {concrete_span(span): loop for span, loop in self.loops.items()}
    if self.triggers:
        expanded_triggers: dict[str, SheetTriggerConfig] = {}
        for span, trigger in self.triggers.items():
            copied = trigger.model_copy(deep=True)
            for actions in (copied.on_success, copied.on_fail):
                for action in actions or ():
                    if action.goto is not None:
                        stage_sheets = expansion.stage_sheets.get(action.goto)
                        if stage_sheets:
                            action.goto = stage_sheets[0]
                    if action.skip is not None:
                        action.skip = concrete_span(action.skip)
            expanded_triggers[concrete_span(span)] = copied
        self.triggers = expanded_triggers

    # Store serializable metadata for resume
    self.fan_out_stage_map = {
        sheet_num: {
            "stage": meta.stage,
            "instance": meta.instance,
            "fan_count": meta.fan_count,
        }
        for sheet_num, meta in expansion.sheet_metadata.items()
    }

    # Clear fan_out to prevent re-expansion on resume
    self.fan_out = {}

    return self
validate_flow
validate_flow()

Collect flow load errors once, after stage keys are concrete.

Source code in src/marianne/core/config/job.py
@model_validator(mode="after")
def validate_flow(self) -> SheetConfig:
    """Collect flow load errors once, after stage keys are concrete."""
    if not self.loops and not self.triggers:
        return self
    issues: list[FlowIssue] = []
    total = self.total_sheets
    spans: dict[str, tuple[int, int]] = {}
    names: dict[str, str] = {}
    for section, mapping in (("loops", self.loops), ("triggers", self.triggers)):
        for span in mapping or {}:
            start, end = span_bounds(span)
            if start < 1 or end > total:
                issues.append(
                    FlowIssue("V-FLOW-06", span, f"{section} span {span} is outside 1-{total}")
                )
            if section == "loops":
                spans[span] = (start, end)
    for span, loop in (self.loops or {}).items():
        if loop.count is None and loop.until is None:
            issues.append(
                FlowIssue("V-FLOW-22", span, f"loop {span} needs until, count, or both")
            )
        if not re.fullmatch(r"[a-z][a-z0-9_]*", loop.index):
            issues.append(
                FlowIssue(
                    "V-FLOW-10", span, f"loop index {loop.index!r} must be lowercase ASCII"
                )
            )
        if loop.index in FLOW_RESERVED_NAMES:
            issues.append(
                FlowIssue(
                    "V-FLOW-10", span, f"loop index {loop.index!r} collides with a built-in"
                )
            )
        if loop.index in names:
            issues.append(
                FlowIssue(
                    "V-FLOW-09",
                    span,
                    f"loop index {loop.index!r} is also used by loop {names[loop.index]}",
                )
            )
        names[loop.index] = span
    for left, (a, b) in spans.items():
        for right, (c, d) in spans.items():
            if left >= right:
                continue
            if max(a, c) <= min(b, d) and not ((a <= c and d <= b) or (c <= a and b <= d)):
                issues.append(
                    FlowIssue(
                        "V-FLOW-11", left, f"loops {left} and {right} overlap without nesting"
                    )
                )
    for span, loop in (self.loops or {}).items():
        if loop.until is None:
            continue
        try:
            refs = parse_expression(loop.until).references()
        except ExpressionError as exc:
            issues.append(FlowIssue("V-FLOW-01", span, f"loop {span}: {exc}", exc.hint))
            continue
        for reserved in refs.reserved:
            issues.append(
                FlowIssue("V-FLOW-02", span, f"{reserved}() is reserved for a future release")
            )
        own_start, own_end = spans[span]
        for name in refs.loops:
            owner = names.get(name)
            if owner is None or not (
                spans[owner][0] <= own_start and own_end <= spans[owner][1]
            ):
                issues.append(
                    FlowIssue("V-FLOW-04", span, f"loop.{name} is unavailable in loop {span}")
                )
        for num in refs.sheets:
            if not 1 <= num <= total:
                issues.append(FlowIssue("V-FLOW-05", span, f"sheet({num}) does not exist"))
    for span, trigger in (self.triggers or {}).items():
        for action in (trigger.on_success or []) + (trigger.on_fail or []):
            if action.goto is not None and not 1 <= action.goto <= total:
                issues.append(
                    FlowIssue(
                        "V-FLOW-08",
                        span,
                        f"goto {action.goto} targets a sheet that does not exist",
                    )
                )
            if action.skip is not None:
                start, end = span_bounds(action.skip)
                if start < 1 or end > total:
                    issues.append(
                        FlowIssue(
                            "V-FLOW-08",
                            span,
                            f"skip {action.skip} targets a sheet that does not exist",
                        )
                    )
    if issues:
        raise FlowConfigError(tuple(issues))
    return self
validate_dependency_range
validate_dependency_range()

Validate that dependency sheet numbers are within the valid range.

Runs after fan-out expansion so total_sheets reflects the final count.

Source code in src/marianne/core/config/job.py
@model_validator(mode="after")
def validate_dependency_range(self) -> SheetConfig:
    """Validate that dependency sheet numbers are within the valid range.

    Runs after fan-out expansion so total_sheets reflects the final count.
    """
    if not self.dependencies:
        return self
    max_sheet = self.total_sheets
    for sheet_num, deps in self.dependencies.items():
        if sheet_num < 1 or sheet_num > max_sheet:
            raise ValueError(
                f"Dependency key sheet {sheet_num} is out of range (valid: 1-{max_sheet})"
            )
        for dep in deps:
            if dep < 1 or dep > max_sheet:
                raise ValueError(
                    f"Sheet {sheet_num} depends on sheet {dep}, "
                    f"which is out of range (valid: 1-{max_sheet})"
                )
    return self

PromptConfig

Bases: BaseModel

Configuration for prompt templating.

Methods:
at_least_one_template
at_least_one_template()

Warn when no template source is provided (falls back to default prompt).

Source code in src/marianne/core/config/job.py
@model_validator(mode="after")
def at_least_one_template(self) -> PromptConfig:
    """Warn when no template source is provided (falls back to default prompt)."""
    if self.template is not None and self.template_file is not None:
        raise ValueError("PromptConfig accepts 'template' or 'template_file', not both")
    if self.template is None and self.template_file is None:
        warnings.warn(
            "PromptConfig has neither 'template' nor 'template_file'. "
            "The default preamble prompt will be used.",
            UserWarning,
            stacklevel=2,
        )
    return self

ValidateConfig

Bases: BaseModel

Score-local acknowledgement of advisory validator findings.

JobConfig

Bases: BaseModel

Complete configuration for an orchestration job.

Attributes
unknown_fields property
unknown_fields

Fields removed by the tolerant score-file loader.

workspace_auto_managed property
workspace_auto_managed

Whether the loader derived workspace from name (#58).

True only when the score file omits workspace:. A run named with mzt run --job-id (GH #505) then gets ~/workspaces/<job-id> instead, so two runs of one shipped score never share a workspace.

tick_wall_seconds property
tick_wall_seconds

The tick cap, with the legacy root spelling as a one-release alias.

effective_instrument_name property
effective_instrument_name

Return the name used to resolve this score's execution instrument.

The explicit instrument: field wins when set; otherwise the default instrument (claude-code, Marianne's reference instrument) is returned. Display and dispatch paths rely on this single identifier.

Methods:
to_yaml
to_yaml(*, exclude_defaults=False)

Serialize this JobConfig to valid score YAML.

The output is semantically equivalent to the original config: from_yaml_string(config.to_yaml()) produces an equivalent config (compared via model_dump()). String-level identity with the original YAML file is NOT guaranteed because workspace paths are resolved to absolute at parse time and fan-out configs are expanded.

Parameters:

Name Type Description Default
exclude_defaults bool

If True, omit fields that match their default values for cleaner output. Defaults to False (lossless).

False

Returns:

Type Description
str

A valid YAML string that from_yaml_string() can parse.

Source code in src/marianne/core/config/job.py
def to_yaml(self, *, exclude_defaults: bool = False) -> str:
    """Serialize this JobConfig to valid score YAML.

    The output is semantically equivalent to the original config:
    ``from_yaml_string(config.to_yaml())`` produces an equivalent config
    (compared via ``model_dump()``). String-level identity with the
    original YAML file is NOT guaranteed because workspace paths are
    resolved to absolute at parse time and fan-out configs are expanded.

    Args:
        exclude_defaults: If True, omit fields that match their default
            values for cleaner output. Defaults to False (lossless).

    Returns:
        A valid YAML string that ``from_yaml_string()`` can parse.
    """
    data = self.model_dump(
        mode="python",
        by_alias=True,
        exclude_defaults=exclude_defaults,
    )
    data = _prepare_for_yaml(data)
    return yaml.dump(
        data,
        default_flow_style=False,
        sort_keys=False,
        allow_unicode=True,
    )
from_yaml classmethod
from_yaml(path)

Load job configuration from a YAML file.

Source code in src/marianne/core/config/job.py
@classmethod
def from_yaml(cls, path: Path | str) -> JobConfig:
    """Load job configuration from a YAML file."""
    path = Path(path)
    with open(path) as f:
        data = yaml.safe_load(f)
    if not isinstance(data, dict):
        raise ValueError(
            "The score file is empty or invalid. "
            "A Marianne score requires at minimum: name, sheet, and prompt sections. "
            "See 'mzt validate --help' or the score writing guide for examples."
        )
    # Pre-resolve relative workspace relative to the score file's parent
    # directory, not the current process CWD (#109).  This is critical when
    # the daemon loads a score whose path differs from the daemon's CWD.
    ws_val = data.get("workspace")
    if ws_val:
        ws = Path(str(ws_val)).expanduser()
        if not ws.is_absolute():
            data["workspace"] = str((path.resolve().parent / ws).resolve())
    auto_managed = False
    if not ws_val:
        # A loaded score that omits workspace gets a conductor-managed one
        # under ~/workspaces/<name> (#58) — workspaces "just work".
        auto_managed = _apply_default_workspace(data)
    clean, unknown = strip_unknown_score_fields(data, cls)
    config = cls.model_validate(clean)
    config._unknown_fields = unknown
    config._workspace_auto_managed = auto_managed
    config.source_path = path.resolve()
    return config
from_yaml_bytes classmethod
from_yaml_bytes(data, *, source_path)

Load job configuration from exact bytes, attributed to source_path.

Semantics match :meth:from_yaml (workspace pre-resolution relative to the score file's parent, default workspace for omitted workspace, source_path attribution), but the parsed YAML comes from the provided bytes rather than a fresh read of the path. Used by the daemon's pinned-schedule admission so the config a job executes is derived from exactly the bytes whose digest was verified against the daemon-owned pin.

Source code in src/marianne/core/config/job.py
@classmethod
def from_yaml_bytes(cls, data: bytes, *, source_path: Path | str) -> JobConfig:
    """Load job configuration from exact bytes, attributed to ``source_path``.

    Semantics match :meth:`from_yaml` (workspace pre-resolution relative
    to the score file's parent, default workspace for omitted workspace,
    ``source_path`` attribution), but the parsed YAML comes from the
    provided bytes rather than a fresh read of the path. Used by the
    daemon's pinned-schedule admission so the config a job executes is
    derived from exactly the bytes whose digest was verified against the
    daemon-owned pin.
    """
    path = Path(source_path)
    parsed = yaml.safe_load(data.decode("utf-8"))
    if not isinstance(parsed, dict):
        raise ValueError(
            "The score file is empty or invalid. "
            "A Marianne score requires at minimum: name, sheet, and prompt sections. "
            "See 'mzt validate --help' or the score writing guide for examples."
        )
    ws_val = parsed.get("workspace")
    if ws_val:
        ws = Path(str(ws_val)).expanduser()
        if not ws.is_absolute():
            parsed["workspace"] = str((path.resolve().parent / ws).resolve())
    auto_managed = False
    if not ws_val:
        auto_managed = _apply_default_workspace(parsed)
    clean, unknown = strip_unknown_score_fields(parsed, cls)
    config = cls.model_validate(clean)
    config._unknown_fields = unknown
    config._workspace_auto_managed = auto_managed
    config.source_path = path.resolve()
    return config
from_yaml_string classmethod
from_yaml_string(yaml_str)

Load job configuration from a YAML string.

Source code in src/marianne/core/config/job.py
@classmethod
def from_yaml_string(cls, yaml_str: str) -> JobConfig:
    """Load job configuration from a YAML string."""
    data = yaml.safe_load(yaml_str)
    if not isinstance(data, dict):
        raise ValueError(
            "The score content is empty or invalid. "
            "A Marianne score requires at minimum: name, sheet, and prompt sections."
        )
    # A loaded score that omits workspace gets a conductor-managed one
    # under ~/workspaces/<name> (#58). Explicit relative paths are left to
    # the model's _resolve_workspace (resolved against CWD), as before.
    auto_managed = _apply_default_workspace(data)
    clean, unknown = strip_unknown_score_fields(data, cls)
    config = cls.model_validate(clean)
    config._unknown_fields = unknown
    config._workspace_auto_managed = auto_managed
    return config
get_state_path
get_state_path()

Get the resolved state path.

Source code in src/marianne/core/config/job.py
def get_state_path(self) -> Path:
    """Get the resolved state path."""
    if self.state_path:
        return self.state_path
    if self.state_backend == "json":
        return self.workspace / ".marianne-state.json"
    return self.workspace / STATE_DB_FILENAME
get_outcome_store_path
get_outcome_store_path()

Get the resolved outcome store path for learning.

Source code in src/marianne/core/config/job.py
def get_outcome_store_path(self) -> Path:
    """Get the resolved outcome store path for learning."""
    if self.learning.outcome_store_path:
        return self.learning.outcome_store_path
    if self.learning.outcome_store_type == "json":
        return self.workspace / ".marianne-outcomes.json"
    return self.workspace / ".marianne-outcomes.db"

Functions:

resolve_variable_integer

resolve_variable_integer(value, variables, *, bound, noun, check)

Resolve one integer field that may be a bare {{ name }} reference (#569, #568).

A literal integer is returned unchanged and is left for the model field's own validation. The caller's bound applies only to variable references. A boolean or any other non-string value returns an issue saying the value is not a noun.

A string must be exactly one bare {{ name }} reference, optionally dotted ({{ a.b }}) and padded with whitespace. The variables mapping is walked along that name; a missing step, or a step whose value is None, is _not_declared. What is found must be an integer or a string of ASCII digits (no sign), in 1..bound:

  • an integer is echoed in the out-of-range message when its absolute value is below 10**10;
  • a digit string is judged by its significant digits, so leading zeroes never count against it. Surrounding whitespace is ignored. Up to the bound's own digit count it is converted and echoed like an integer; longer values return an out-of-range issue without conversion or echoing the value. This avoids CPython's integer-conversion limit.
  • any other value (a float, a bool, other text, an empty string) is _not_a_whole_number.

Parameters:

Name Type Description Default
value object

One field value, e.g. from sheet.fan_out or a loop cap.

required
variables Mapping[str, object]

The declared prompt.variables mapping.

required
bound int

The inclusive upper bound for a resolved value.

required
noun str

What the field is called in messages ("width", "loop cap").

required
check str

The flow check id stamped on every issue.

required

Returns:

Type Description
int | FlowIssue

The integer, or one FlowIssue naming the reason. The issue

int | FlowIssue

carries no span: the caller supplies it. Invalid values return

int | FlowIssue

issues rather than raising validation errors.

Source code in src/marianne/core/config/job.py
def resolve_variable_integer(
    value: object,
    variables: Mapping[str, object],
    *,
    bound: int,
    noun: str,
    check: str,
) -> int | FlowIssue:
    """Resolve one integer field that may be a bare ``{{ name }}`` reference (#569, #568).

    A literal integer is returned unchanged and is left for the model field's
    own validation. The caller's ``bound`` applies only to variable
    references. A boolean or any other non-string value returns an issue
    saying the value is not a ``noun``.

    A string must be exactly one bare ``{{ name }}`` reference, optionally
    dotted (``{{ a.b }}``) and padded with whitespace. The ``variables``
    mapping is walked along that name; a missing step, or a step whose value
    is ``None``, is ``_not_declared``. What is found must be an integer or a
    string of ASCII digits (no sign), in ``1..bound``:

    - an integer is echoed in the out-of-range message when its absolute
      value is below ``10**10``;
    - a digit string is judged by its significant digits, so leading zeroes
      never count against it. Surrounding whitespace is ignored. Up to the
      bound's own digit count it is converted and echoed like an integer;
      longer values return an out-of-range issue without conversion or
      echoing the value. This avoids CPython's integer-conversion limit.
    - any other value (a float, a ``bool``, other text, an empty string) is
      ``_not_a_whole_number``.

    Args:
        value: One field value, e.g. from ``sheet.fan_out`` or a loop cap.
        variables: The declared ``prompt.variables`` mapping.
        bound: The inclusive upper bound for a resolved value.
        noun: What the field is called in messages ("width", "loop cap").
        check: The flow check id stamped on every issue.

    Returns:
        The integer, or one ``FlowIssue`` naming the reason. The issue
        carries no span: the caller supplies it. Invalid values return
        issues rather than raising validation errors.
    """
    cap_digits = len(str(bound))
    if isinstance(value, int) and not isinstance(value, bool):
        return value
    if not isinstance(value, str):
        return _not_a_reference(value, noun=noun, check=check)
    match = _VARIABLE_INTEGER_REF.fullmatch(value.strip())
    if match is None:
        return _not_a_reference(value, noun=noun, check=check)
    name = match.group(1)
    found: object = variables
    for part in name.split("."):
        if not isinstance(found, Mapping) or found.get(part) is None:
            return _not_declared(name, check=check)
        found = found[part]
    if isinstance(found, bool):
        return _not_a_whole_number(name, found, noun=noun, check=check)
    if isinstance(found, int):
        number: int | None = found
    else:
        digits = _significant_digits(found)
        if digits is None:
            return _not_a_whole_number(name, found, noun=noun, check=check)
        if not digits:
            number = 0  # every digit is a zero: a whole number, and out of range
        elif len(digits) <= cap_digits:
            number = int(digits)  # at most the bound's own digit count: always convertible
        else:
            # More significant digits than the bound has, so out of range;
            # also too long for int() to convert or for a message to show.
            number = None
    if number is None or not 1 <= number <= bound:
        return _out_of_range(name, number, bound=bound, noun=noun, check=check)
    return number

resolve_fan_out_width

resolve_fan_out_width(width, variables)

Resolve one sheet.fan_out value to an integer width (#569).

A literal integer is returned unchanged and is left for SheetConfig to validate. The 1..MAX_VARIABLE_FAN_OUT_WIDTH bound applies only to variable references. A boolean or any other non-string value returns an invalid-width issue.

A string must be exactly one bare {{ name }} reference, optionally dotted ({{ a.b }}) and padded with whitespace. The variables mapping is walked along that name; a missing step, or a step whose value is None, is _not_declared. What is found must be an integer or a string of ASCII digits (no sign), in 1..MAX_VARIABLE_FAN_OUT_WIDTH:

  • an integer is echoed in the out-of-range message when its absolute value is below 10**10;
  • a digit string is judged by its significant digits, so leading zeroes never count against it. Surrounding whitespace is ignored. Up to the cap's own digit count it is converted and echoed like an integer; longer values return an out-of-range issue without conversion or echoing the value. This avoids CPython's integer-conversion limit.
  • any other value (a float, a bool, other text, an empty string) is _not_a_whole_number.

Parameters:

Name Type Description Default
width object

One value from sheet.fan_out.

required
variables Mapping[str, object]

The declared prompt.variables mapping.

required

Returns:

Type Description
int | FlowIssue

The width, or one FlowIssue (V-FLOW-25) naming the reason.

int | FlowIssue

The issue carries no span: the caller supplies the stage. Invalid

int | FlowIssue

widths return issues rather than raising validation errors.

Source code in src/marianne/core/config/job.py
def resolve_fan_out_width(width: object, variables: Mapping[str, object]) -> int | FlowIssue:
    """Resolve one ``sheet.fan_out`` value to an integer width (#569).

    A literal integer is returned unchanged and is left for ``SheetConfig``
    to validate. The ``1..MAX_VARIABLE_FAN_OUT_WIDTH`` bound applies only
    to variable references. A boolean or any other non-string value returns
    an invalid-width issue.

    A string must be exactly one bare ``{{ name }}`` reference, optionally
    dotted (``{{ a.b }}``) and padded with whitespace. The ``variables``
    mapping is walked along that name; a missing step, or a step whose value
    is ``None``, is ``_not_declared``. What is found must be an integer or a
    string of ASCII digits (no sign), in ``1..MAX_VARIABLE_FAN_OUT_WIDTH``:

    - an integer is echoed in the out-of-range message when its absolute
      value is below ``10**10``;
    - a digit string is judged by its significant digits, so leading zeroes
      never count against it. Surrounding whitespace is ignored. Up to the
      cap's own digit count it is converted and echoed like an integer;
      longer values return an out-of-range issue without conversion or
      echoing the value. This avoids CPython's integer-conversion limit.
    - any other value (a float, a ``bool``, other text, an empty string) is
      ``_not_a_whole_number``.

    Args:
        width: One value from ``sheet.fan_out``.
        variables: The declared ``prompt.variables`` mapping.

    Returns:
        The width, or one ``FlowIssue`` (``V-FLOW-25``) naming the reason.
        The issue carries no span: the caller supplies the stage. Invalid
        widths return issues rather than raising validation errors.
    """
    return resolve_variable_integer(
        width,
        variables,
        bound=MAX_VARIABLE_FAN_OUT_WIDTH,
        noun="width",
        check="V-FLOW-25",
    )

movement_cadenzas

movement_cadenzas(config)

Stage-keyed cadenza declarations, as authored (#571).

Returns the map of stage number to that movement's cadenza items, stages ascending, listing only the movements that declare items. The movement number is the stage — the same namespace as sheet.fan_out keys and loop spans. Nothing is copied into sheet.cadenzas: the items are resolved per sheet by :func:cadenzas_for_sheet.

Source code in src/marianne/core/config/job.py
def movement_cadenzas(config: JobConfig) -> dict[int, list[MovementCadenzaItem]]:
    """Stage-keyed cadenza declarations, as authored (#571).

    Returns the map of stage number to that movement's cadenza items,
    stages ascending, listing only the movements that declare items. The
    movement number is the stage — the same namespace as ``sheet.fan_out``
    keys and loop spans. Nothing is copied into ``sheet.cadenzas``: the
    items are resolved per sheet by :func:`cadenzas_for_sheet`.
    """
    return {
        stage: movement.cadenzas
        for stage, movement in sorted(config.movements.items())
        if movement.cadenzas
    }

cadenzas_for_sheet

cadenzas_for_sheet(config, sheet_num)

The cadenza items one concrete sheet reads, in delivery order (#571).

The movement cadenza items whose voice is None or equals the sheet's fan-out instance (1 on a solo movement), then the sheet's own sheet.cadenzas[sheet_num] items. Pure: it never writes to config, so a re-validated dump (resume) never delivers them twice.

Source code in src/marianne/core/config/job.py
def cadenzas_for_sheet(config: JobConfig, sheet_num: int) -> list[InjectionItem]:
    """The cadenza items one concrete sheet reads, in delivery order (#571).

    The movement cadenza items whose ``voice`` is ``None`` or equals the
    sheet's fan-out instance (``1`` on a solo movement), then the sheet's
    own ``sheet.cadenzas[sheet_num]`` items. Pure: it never writes to
    ``config``, so a re-validated dump (resume) never delivers them twice.
    """
    fan_meta = config.sheet.get_fan_out_metadata(sheet_num)
    composed: list[InjectionItem] = []
    movement = config.movements.get(fan_meta.stage)
    if movement is not None:
        for movement_item in movement.cadenzas:
            if movement_item.voice is None or movement_item.voice == fan_meta.instance:
                composed.append(movement_item)
    composed.extend(config.sheet.cadenzas.get(sheet_num, ()))
    return composed

stage_sheets

stage_sheets(config, stage)

The concrete sheets of a stage, lowest first (#571).

Read from fan_out_stage_map after expansion; a stage without fan-out is the sheet of that number; a stage that has no sheet (for example a movement number past the last stage) returns [].

Source code in src/marianne/core/config/job.py
def stage_sheets(config: JobConfig, stage: int) -> list[int]:
    """The concrete sheets of a stage, lowest first (#571).

    Read from ``fan_out_stage_map`` after expansion; a stage without
    fan-out is the sheet of that number; a stage that has no sheet (for
    example a movement number past the last stage) returns ``[]``.
    """
    if config.sheet.fan_out_stage_map:
        return sorted(
            num for num, meta in config.sheet.fan_out_stage_map.items() if meta["stage"] == stage
        )
    if 1 <= stage <= config.sheet.total_sheets:
        return [stage]
    return []

merge_runtime_variables

merge_runtime_variables(config, runtime_variables)

Merge per-invocation --var variables into prompt.variables (#359).

CLI variables override YAML on key collision (the documented make/terraform contract). No-op when empty. The daemon applies this at submit and resume; mzt run --dry-run applies the same seam so the preview renders the score the conductor would run (examples QA, 21 Oct: the preview ignored --var and showed [CHANGE THIS] placeholders).

Source code in src/marianne/core/config/job.py
def merge_runtime_variables(
    config: JobConfig,
    runtime_variables: dict[str, str],
) -> JobConfig:
    """Merge per-invocation ``--var`` variables into ``prompt.variables`` (#359).

    CLI variables override YAML on key collision (the documented
    make/terraform contract). No-op when empty. The daemon applies this at
    submit and resume; ``mzt run --dry-run`` applies the same seam so the
    preview renders the score the conductor would run (examples QA, 21 Oct:
    the preview ignored ``--var`` and showed `[CHANGE THIS]` placeholders).
    """
    if not runtime_variables:
        return config
    merged = dict(config.prompt.variables)
    merged.update(runtime_variables)
    return config.model_copy(
        update={"prompt": config.prompt.model_copy(update={"variables": merged})}
    )