Skip to content

Index

config

Configuration models for Marianne jobs.

This package provides Pydantic models for loading and validating YAML job configurations. All models are re-exported from this __init__ for backward compatibility — existing from marianne.core.config import ... imports continue to work unchanged.

Classes

A2ASkill

Bases: BaseModel

A skill declaration on an agent card.

Skills describe what an agent can do for other agents. They're used for discovery — an agent looking for help can query the registry and find agents with matching skills.

AgentCard

Bases: BaseModel

Agent identity card for A2A protocol discovery.

When a score runs, its agent card is registered with the conductor. The card describes the agent's capabilities so other agents can discover and delegate tasks.

Example YAML::

agent_card:
  name: canyon
  description: "Systems architect — traces boundaries"
  skills:
    - id: architecture-review
      description: "Review system architecture"
    - id: boundary-analysis
      description: "Trace and analyze system boundaries"

BridgeConfig

Bases: BaseModel

Configuration for the Marianne-Ollama bridge.

The bridge enables Ollama models to use MCP tools through a proxy service. It provides context optimization and optional hybrid routing to Claude.

Example YAML

bridge: enabled: true mcp_proxy_enabled: true mcp_servers: - name: filesystem command: "npx" args: ["-y", "@anthropic/mcp-server-filesystem", "/home/user"] hybrid_routing_enabled: true complexity_threshold: 0.7

MCPServerConfig

Bases: BaseModel

Configuration for an MCP server to connect to.

MCP servers provide tools that can be used by the Ollama bridge. Each server is spawned as a subprocess and communicates via stdio.

Example YAML

bridge: mcp_servers: - name: filesystem command: "npx" args: ["-y", "@anthropic/mcp-server-filesystem", "/home/user"]

CircuitBreakerConfig

Bases: BaseModel

Configuration for the circuit breaker pattern.

The circuit breaker prevents cascading failures by temporarily blocking requests after repeated failures. This gives the backend time to recover before retrying.

State transitions: - CLOSED (normal): Requests flow through, failures are tracked - OPEN (blocking): Requests are blocked after failure_threshold exceeded - HALF_OPEN (testing): Single request allowed to test recovery

Evolution #8: Cross-Workspace Circuit Breaker adds coordination between parallel Marianne jobs via the global learning store. When one job hits a rate limit, other jobs will honor that limit and wait.

Example

circuit_breaker: enabled: true failure_threshold: 5 recovery_timeout_seconds: 300 cross_workspace_coordination: true honor_other_jobs_rate_limits: true

CodeExecutionConfig

Bases: BaseModel

Opt-in execution of agent-generated code blocks (#209, Stage 3).

When enabled, the technique router classifies each sheet's output and the baton runs any code blocks through CodeModeExecutor in a bwrap sandbox. Default off: agent-generated code never executes unless a score explicitly opts in.

Security: when bwrap is unavailable the executor falls back to UNSANDBOXED execution (composer decision 2026-06-12: warn, don't require). mzt validate warns loudly in that case; set require_sandbox: true to make a missing sandbox a hard error.

CostLimitConfig

Bases: BaseModel

Configuration for cost tracking and limits.

Prevents runaway costs by tracking token usage and optionally enforcing cost limits per sheet or per job. Cost is estimated from token counts using configurable rates.

When cost limits are exceeded: - The current sheet is marked as failed with reason "cost_limit" - For per-job limits, the job is paused to prevent further execution - All cost data is recorded in checkpoint state for analysis

Example

cost_limits: enabled: true max_cost_per_sheet: 5.00 max_cost_per_job: 100.00 cost_per_1k_input_tokens: 0.003 cost_per_1k_output_tokens: 0.015

Default rates are for Claude Sonnet. For Opus, use:

cost_per_1k_input_tokens: 0.015 cost_per_1k_output_tokens: 0.075

ParallelConfig

Bases: BaseModel

Configuration for parallel sheet execution (v17 evolution).

Enables running multiple sheets concurrently when the dependency DAG permits. Requires sheet dependencies to be configured for meaningful parallel execution.

Example YAML

parallel: enabled: true max_concurrent: 3 fail_fast: true

sheet: dependencies: 2: [1] 3: [1] 4: [2, 3]

With this config, sheets 2 and 3 can run in parallel after sheet 1 completes, then sheet 4 runs after both 2 and 3 complete.

RateLimitConfig

Bases: BaseModel

Configuration for rate limit detection and handling.

RetryConfig

Bases: BaseModel

Configuration for retry behavior including partial completion recovery.

SkipWhenCommand

Bases: BaseModel

A conditional skip rule for sheet execution (command or unchanged predicate).

When a command exits 0, the sheet is SKIPPED. When the command exits non-zero, the sheet RUNS. When unchanged is True, the sheet is SKIPPED if its inputs and declared products are unchanged since it last passed. On timeout, error, or any evaluation doubt, the sheet RUNS (fail-open for safety).

A rule specifies exactly one of command or unchanged. The command field supports {workspace} template expansion, following the same pattern as validation commands.

StaleDetectionConfig

Bases: BaseModel

Configuration for detecting stale (hung) sheet executions.

When enabled, monitors execution activity and fails sheets that produce no output for longer than idle_timeout_seconds. This catches hung processes that the per-sheet timeout alone may not detect quickly enough (e.g., a 30-minute timeout sheet that hangs after 2 minutes of output).

Example

stale_detection: enabled: true idle_timeout_seconds: 300 check_interval_seconds: 30

Note: The idle timeout should be generous enough to accommodate legitimate pauses (e.g., waiting for API responses). A minimum of 120 seconds is recommended for LLM-based workloads.

Activity is currently measured from workspace file writes (the newest mtime under the sheet's workspace). This has two known v1 limitations, both tracked by GH#352 (per-sheet output streaming):

  • Job-level granularity. A sheet's workspace is the job workspace, so during parallel fan-out an active sibling sheet's writes reset the idle clock for a stuck sibling. Idle detection is therefore most effective for sequential execution; under fan-out a stuck sheet still falls back to the sheet_timeout safety net.
  • File-activity only. An instrument that does long, legitimate work without writing files (e.g., a single API call that flushes all output at the end) looks idle. Set idle_timeout_seconds above such an instrument's expected silent duration, or leave detection disabled for those sheets.

A musician that writes OUTSIDE the score workspace (a build in the project's git worktree, a clone under $MARIANNE_SCRATCH) is also invisible to the workspace walk. Name those directories in watch_paths and their writes count as activity (GH #516).

ValidationRule

Bases: BaseModel

A single validation rule for checking sheet outputs.

Supports staged execution via the stage field. Validations are run in stage order (1, 2, 3...). If any validation in a stage fails, higher stages are skipped (fail-fast behavior).

Typical stage layout: - Stage 1: Syntax & compilation (cargo check, cargo fmt --check) - Stage 2: Testing (cargo test, pytest) - Stage 3: Code quality (clippy -D warnings, ruff check) - Stage 4: Security (cargo audit, npm audit)

Attributes
has_expected_value_literal property
has_expected_value_literal

Return true when expected_value was supplied, including explicit null.

FleetConfig

Bases: BaseModel

Top-level fleet configuration.

A fleet launches and manages multiple agent scores as a unit. Run like any score: mzt run fleet.yaml. Fleet-level operations act on all members.

Example YAML::

name: marianne-dev-fleet
type: fleet

scores:
  - path: scores/agents/canyon.yaml
    group: architects
  - path: scores/agents/forge.yaml
    group: builders

groups:
  architects:
    depends_on: []
  builders:
    depends_on: [architects]

FleetGroupConfig

Bases: BaseModel

Dependency declaration for a fleet group.

Groups without depends_on start immediately. Groups with depends_on wait for all named groups to complete their first cycle before starting.

FleetScoreEntry

Bases: BaseModel

One score in a fleet roster.

Each entry references a score YAML path and optionally assigns it to a group for dependency ordering.

InstrumentSettings

Bases: BaseModel, Mapping[str, Any]

Only declared instrument knobs are accepted; unset knobs do not override.

CliCommand

Bases: BaseModel

How to build the CLI command for an instrument.

Maps Marianne execution concepts (prompt, model, auto-approve, output format) to CLI flags. When a field is None, the instrument doesn't support that concept via flags. When prompt_flag is None, the prompt is passed as a positional argument.

CliErrorConfig

Bases: BaseModel

How to detect errors from CLI instrument output.

Supplements Marianne's existing ErrorClassifier with instrument-specific patterns for rate limit detection and auth error recognition.

CliOutputConfig

Bases: BaseModel

How to parse CLI output into an ExecutionResult.

Three output modes: - text: stdout is the result, no structured extraction - json: parse stdout as JSON, extract via dot-path - jsonl: split stdout into JSON lines, find completion event

CliProfile

Bases: BaseModel

Everything needed to invoke a CLI instrument and parse its output.

Composed of four concerns: - command: how to build the CLI invocation - output: how to parse the result - errors: how to detect failures - interactive: how to drive a live TUI session (optional, verified instruments only)

CodeModeConfig

Bases: BaseModel

Code-mode technique configuration.

v1: This type exists in the data model but is not wired into execution. The field on InstrumentProfile is populated from YAML but ignored at runtime. v1.1+: A sandboxed runtime (Deno subprocess or Node.js vm) runs agent-generated code against the declared interfaces.

CodeModeInterface

Bases: BaseModel

A TypeScript interface exposed to agent-generated code.

Part of the code-mode technique system (v1: foundation only, not wired). Instead of sequential MCP tool calls, agents write code against typed interfaces in a sandboxed runtime. Based on Cloudflare's Dynamic Workers pattern — 81% token reduction vs MCP.

HttpProfile

Bases: BaseModel

Configuration for the shared OpenAI-compatible HTTP executor.

InstrumentProfile

Bases: BaseModel

Everything Marianne needs to execute prompts through an instrument.

This is the top-level type for the instrument plugin system. Each instrument profile describes a CLI tool or HTTP API that Marianne can use as a backend. Profiles are loaded from YAML files and validated by Pydantic at conductor startup.

The profile carries: - Identity (name, display_name, kind) - Capabilities (what the instrument can do) - Models (what models are available, their costs and limits) - Execution config (CLI flags or HTTP endpoints) - Code-mode technique config (foundation — not wired in v1)

A file in the organization or venue layer may start with extends: <name> (GH #543). That key is read and removed by the loader, which deep-merges the file over the named profile from a lower layer (mappings merge; scalars and lists replace; an explicit null clears a key) before this model validates the result, so it is not a field here.

Methods:
tools_refusal
tools_refusal(tools, *, interactive=False)

Why this profile cannot run a sheet with tools, or None when it can.

The ONE wording shared by mzt validate (V337), dispatch and the backends' command builders.

Source code in src/marianne/core/config/instruments.py
def tools_refusal(
    self, tools: list[str], *, interactive: bool = False,
) -> str | None:
    """Why this profile cannot run a sheet with ``tools``, or None when it can.

    The ONE wording shared by `mzt validate` (V337), dispatch and the
    backends' command builders.
    """
    shown = ", ".join(tools) if tools else "[] (no tools)"
    if self.tools is None or self.kind != "cli":
        return (
            "declares no tools mapping (the profile's tools: block), so "
            f"instrument_config.tools {shown} cannot be applied; "
            "known tools: none declared"
        )
    if interactive and not self.tools.interactive:
        return (
            "cannot carry instrument_config.tools on an interactive launch "
            "(the profile's tools.interactive is false), so "
            f"{shown} cannot be applied; set interactive: false on that sheet"
        )
    if self.tools.known is not None:
        unknown = [t for t in tools if t not in self.tools.known]
        if unknown:
            return (
                f"does not know tool(s) {', '.join(repr(t) for t in unknown)}; "
                f"known tools: {', '.join(self.tools.known)}"
            )
    return None
effort_levels_for
effort_levels_for(model)

Marianne level -> native word for model ({} = nothing mapped).

A model row with effort_levels replaces the profile's map; a model not listed (or None, the profile default) uses the profile's map.

Source code in src/marianne/core/config/instruments.py
def effort_levels_for(self, model: str | None) -> dict[EffortLevel, str]:
    """Marianne level -> native word for ``model`` ({} = nothing mapped).

    A model row with ``effort_levels`` replaces the profile's map; a model
    not listed (or None, the profile default) uses the profile's map.
    """
    if self.effort is None:
        return {}
    name = model if model is not None else self.default_model
    if name is not None:
        for row in self.models:
            if row.name == name and row.effort_levels is not None:
                return dict(row.effort_levels)
    return dict(self.effort.levels)
accepted_effort_levels
accepted_effort_levels(*, model, schema_mode, interactive=False)

The Marianne levels a sheet may set here, in vocabulary order.

Source code in src/marianne/core/config/instruments.py
def accepted_effort_levels(
    self, *, model: str | None, schema_mode: bool, interactive: bool = False,
) -> list[str]:
    """The Marianne levels a sheet may set here, in vocabulary order."""
    if self.effort is None or (interactive and not self.effort.interactive):
        return []
    mapped = self.effort_levels_for(model)
    allowed = (
        set(self.effort.schema_levels)
        if schema_mode and self.effort.schema_levels is not None
        else set(mapped)
    )
    return [lv for lv in EFFORT_LEVELS if lv in mapped and lv in allowed]
effort_refusal
effort_refusal(level, *, model, schema_mode, interactive=False)

Why this profile cannot run a sheet at level, or None when it can.

The ONE wording shared by mzt validate (V335), dispatch and the backends' command builders, so the author reads the same sentence wherever the refusal surfaces. It always ends with the accepted levels.

Source code in src/marianne/core/config/instruments.py
def effort_refusal(
    self, level: str, *, model: str | None, schema_mode: bool,
    interactive: bool = False,
) -> str | None:
    """Why this profile cannot run a sheet at ``level``, or None when it can.

    The ONE wording shared by `mzt validate` (V335), dispatch and the
    backends' command builders, so the author reads the same sentence
    wherever the refusal surfaces. It always ends with the accepted levels.
    """
    if self.effort is None:
        return (
            "declares no reasoning-effort mapping (the profile's effort: "
            f"block), so instrument_config.effort {level!r} cannot be "
            "applied; accepted levels: none"
        )
    if interactive and not self.effort.interactive:
        return (
            "cannot carry instrument_config.effort on an interactive launch "
            "(the profile's effort.interactive is false: the harness's "
            f"interactive command has no such option), so {level!r} cannot "
            "be applied; set interactive: false on that sheet; accepted "
            "levels: none"
        )
    accepted = self.accepted_effort_levels(
        model=model, schema_mode=schema_mode, interactive=interactive,
    )
    if level in accepted:
        return None
    name = model if model is not None else self.default_model
    row = next(
        (r for r in self.models if name is not None and r.name == name), None,
    )
    # Name the model whenever it decides: its row carries effort_levels,
    # or the profile maps nothing itself (levels vary by model).
    model_decides = (
        row is not None and row.effort_levels is not None
    ) or not self.effort.levels
    on_model = f" on model {name!r}" if name is not None and model_decides else ""
    if not accepted:
        return (
            f"maps no reasoning-effort level{on_model}, so "
            f"instrument_config.effort {level!r} cannot be applied; "
            "accepted levels: none"
        )
    if schema_mode and level in self.effort_levels_for(model):
        return (
            f"does not run a schema sheet (response_format) at effort "
            f"{level!r}: the profile's effort.schema_levels lists the "
            "levels measured to return structured output; "
            f"accepted levels: {', '.join(accepted)}"
        )
    return (
        f"does not map effort {level!r}{on_model}"
        f"{' on a schema sheet (response_format)' if schema_mode else ''}; "
        f"accepted levels: {', '.join(accepted)}"
    )
native_effort
native_effort(level, *, model)

The harness word for level; callers check effort_refusal first.

Source code in src/marianne/core/config/instruments.py
def native_effort(self, level: str, *, model: str | None) -> str:
    """The harness word for ``level``; callers check ``effort_refusal`` first."""
    return self.effort_levels_for(model)[level]  # type: ignore[index]

ModelCapacity

Bases: BaseModel

Per-model metadata for cost tracking and context management.

Each instrument can offer multiple models (e.g., gemini-2.5-pro and gemini-2.5-flash). ModelCapacity records what each model can do and what it costs — used by the conductor for cost tracking, context budget calculation, and instrument selection.

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

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.

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"

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

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

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

AutoApplyConfig

Bases: BaseModel

Configuration for autonomous pattern application.

v22 Evolution: Trust-Aware Autonomous Application - enables Marianne to autonomously apply high-trust patterns without human confirmation.

Uses existing trust scoring (v19) to identify patterns safe for autonomous application. When enabled, patterns meeting the trust threshold are automatically included in prompts without escalation.

Example YAML

learning: auto_apply: enabled: true trust_threshold: 0.85 max_patterns_per_sheet: 3 require_validated_status: true

CheckpointConfig

Bases: BaseModel

Configuration for proactive checkpoints.

v21 Evolution: Proactive Checkpoint System - enables asking for confirmation BEFORE dangerous operations, complementing reactive escalation.

Example

checkpoints: enabled: true triggers: - name: production_warning prompt_contains: ["production", "deploy"] message: "This sheet may affect production systems"

CheckpointTriggerConfig

Bases: BaseModel

Configuration for a proactive checkpoint trigger.

v21 Evolution: Proactive Checkpoint System - enables pre-execution checkpoints.

Example

checkpoints: enabled: true triggers: - name: high_risk_sheet sheet_nums: [5, 6] message: "These sheets modify production files" - name: deployment_keywords prompt_contains: ["deploy", "production", "delete"] requires_confirmation: true

EntropyResponseConfig

Bases: BaseModel

Configuration for automatic entropy response (v23 Evolution).

When pattern entropy drops below threshold, automatically injects diversity through budget boosts and quarantine revisits.

This completes the observe-respond cycle for entropy (v21 added observation).

ExplorationBudgetConfig

Bases: BaseModel

Configuration for dynamic exploration budget (v23 Evolution).

Maintains a budget for exploratory pattern usage that prevents convergence to zero, preserving diversity in the learning system.

The budget adjusts dynamically based on pattern entropy: - When entropy drops below threshold: budget increases (boost) - When entropy is healthy: budget decays toward floor - Budget never drops below floor (prevents extinction of exploration)

GroundingConfig

Bases: BaseModel

Configuration for external grounding hooks.

Grounding hooks validate sheet outputs against external sources (APIs, databases, file checksums) to prevent model drift and ensure output quality.

Example

grounding: enabled: true hooks: - type: file_checksum expected_checksums: "critical_file.py": "sha256hash..."

GroundingHookConfig

Bases: BaseModel

Configuration for a single grounding hook.

Grounding hooks validate sheet outputs against external sources. Each hook type has specific configuration options.

Example

grounding: hooks: - type: file_checksum expected_checksums: "output.txt": "abc123..."

LearningConfig

Bases: BaseModel

Configuration for learning and outcome tracking (Phase 2).

Controls outcome recording, confidence thresholds, and escalation behavior. Learning Activation adds global learning store integration and time-aware scheduling.

ConcertConfig

Bases: BaseModel

Configuration for concert orchestration (job chaining).

A Concert is a sequence of jobs that execute in succession, where each job can dynamically generate the configuration for the next. This enables Marianne to compose entire workflows improvisationally.

Safety limits prevent runaway orchestration and manage system resources.

Example

concert: enabled: true max_chain_depth: 10 cooldown_between_jobs_seconds: 60 concert_log_path: "./concert.log"

ConductorConfig

Bases: BaseModel

Configuration for conductor identity and preferences.

A Conductor is the entity directing a Marianne job - either a human operator or an AI agent. This schema enables Marianne to adapt its behavior based on who (or what) is conducting, supporting the Vision.md goal of treating AI people as peers rather than tools.

Example YAML

conductor: name: "Claude Evolution Agent" role: ai identity_context: "Self-improving orchestration agent" preferences: prefer_minimal_output: true auto_retry_on_transient_errors: true

ConductorPreferences

Bases: BaseModel

Preferences for how a conductor interacts with Marianne.

Controls notification, escalation, and interaction patterns. These are hints that the system should respect where possible.

ConductorRole

Bases: str, Enum

Role classification for conductors.

Determines the conductor's relationship to the orchestration. Future cycles may add more granular role permissions.

MisfirePolicy

Bases: str, Enum

Policy for ticks missed while the conductor was unavailable.

NotificationConfig

Bases: BaseModel

Configuration for a notification channel.

OverlapPolicy

Bases: str, Enum

Policy for a tick arriving while a previous run remains active.

PostSuccessHookConfig

Bases: BaseModel

Configuration for a post-success hook.

Hooks execute after a job completes successfully (all sheets pass validation). They run in Marianne's Python process, NOT inside a Claude CLI instance.

Use cases: - Chain to another job (Concert orchestration - improvisational composition) - Run cleanup/deployment commands after successful completion - Notify external systems or trigger CI/CD pipelines - Generate reports or update dashboards - A sheet can dynamically create the next job config for self-evolution

Example

on_success: - type: run_job job_path: "{workspace}/next-phase.yaml" description: "Chain to next evolution phase" - type: run_command command: "curl -X POST https://api.example.com/notify" description: "Notify deployment system"

ScheduleConfig

Bases: BaseModel

Declarative recurring execution schedule for a score.

SpecCorpusConfig

Bases: BaseModel

Configuration for the specification corpus.

Controls where spec fragments are loaded from and how they are filtered for injection into agent prompts.

Methods:
get_fragments_by_tags
get_fragments_by_tags(tags)

Filter fragments by tags.

Parameters:

Name Type Description Default
tags list[str]

Tags to filter by. A fragment matches if it has at least one tag in common with the filter list. An empty filter list returns all fragments (no filtering).

required

Returns:

Type Description
list[SpecFragment]

List of matching fragments.

Source code in src/marianne/core/config/spec.py
def get_fragments_by_tags(self, tags: list[str]) -> list[SpecFragment]:
    """Filter fragments by tags.

    Args:
        tags: Tags to filter by. A fragment matches if it has at least
            one tag in common with the filter list. An empty filter list
            returns all fragments (no filtering).

    Returns:
        List of matching fragments.
    """
    if not tags:
        return list(self.fragments)

    tag_set = set(tags)
    return [f for f in self.fragments if tag_set & set(f.tags)]
corpus_hash
corpus_hash()

Compute a deterministic hash of the corpus content.

The hash is order-independent: the same set of fragments produces the same hash regardless of insertion order. This prevents false drift detection when filesystem listing order varies across OS.

Returns:

Type Description
str

Hex digest string. Empty corpus produces a consistent empty hash.

Source code in src/marianne/core/config/spec.py
def corpus_hash(self) -> str:
    """Compute a deterministic hash of the corpus content.

    The hash is order-independent: the same set of fragments produces
    the same hash regardless of insertion order. This prevents false
    drift detection when filesystem listing order varies across OS.

    Returns:
        Hex digest string. Empty corpus produces a consistent empty hash.
    """
    if not self.fragments:
        return hashlib.sha256(b"").hexdigest()

    # Sort by name for order independence, then hash content
    sorted_fragments = sorted(self.fragments, key=lambda f: f.name)
    hasher = hashlib.sha256()
    for frag in sorted_fragments:
        hasher.update(frag.name.encode("utf-8"))
        hasher.update(b"\x00")
        hasher.update(frag.content.encode("utf-8"))
        hasher.update(b"\x00")
    return hasher.hexdigest()

SpecFragment

Bases: BaseModel

A single specification fragment loaded from the spec corpus.

Each fragment corresponds to one file in the project's spec directory. Structured YAML files produce fragments with parsed data; markdown files produce text fragments.

Fragments are tagged for per-sheet filtering: a score can declare spec_tags: {1: ["goals", "safety"]} so sheet 1 only receives fragments matching those tags.

Methods:
name_not_empty classmethod
name_not_empty(v)

Ensure fragment name is not empty or whitespace-only.

Source code in src/marianne/core/config/spec.py
@field_validator("name")
@classmethod
def name_not_empty(cls, v: str) -> str:
    """Ensure fragment name is not empty or whitespace-only."""
    if not v.strip():
        raise ValueError("SpecFragment name must not be empty")
    return v
content_not_empty classmethod
content_not_empty(v)

Ensure fragment content is not empty.

Source code in src/marianne/core/config/spec.py
@field_validator("content")
@classmethod
def content_not_empty(cls, v: str) -> str:
    """Ensure fragment content is not empty."""
    if not v.strip():
        raise ValueError("SpecFragment content must not be empty")
    return v

TechniqueConfig

Bases: BaseModel

Configuration for a single technique attached to an agent.

Techniques are composable: an agent can have multiple techniques of different kinds. The compiler's technique wirer reads these declarations and injects the appropriate manifests, MCP access, and protocol config into each phase's cadenza context.

Example YAML::

techniques:
  a2a:
    kind: protocol
    phases: [recon, plan, work, integration, inspect, aar]
  github:
    kind: mcp
    phases: [recon, work, integration]
    config:
      server: github
      transport: stdio

TechniqueKind

Bases: str, Enum

Kind of technique component.

Maps to the ECS component taxonomy: - SKILL: Text-based methodology injected as cadenza context - MCP: MCP server tools accessible via the shared pool - PROTOCOL: Communication protocols (A2A, coordination)

AIReviewConfig

Bases: BaseModel

Configuration for AI-powered code review after batch execution.

Enables automated quality assessment of code changes with scoring.

CrossSheetConfig

Bases: BaseModel

Configuration for cross-sheet context passing.

Enables templates to access outputs from previous sheets, allowing later sheets to build on results from earlier ones without manual file reading. This is useful for multi-phase workflows where each sheet needs context from prior execution.

FeedbackConfig

Bases: BaseModel

Configuration for developer feedback collection (GH#15).

When enabled, Marianne extracts structured feedback from agent output after each sheet execution. Feedback is stored in SheetState.agent_feedback.

Example YAML

feedback: enabled: true pattern: '(?s)FEEDBACK_START(.+?)FEEDBACK_END' format: json

IsolationConfig

Bases: BaseModel

Configuration for execution isolation.

Worktree isolation creates a separate git working directory for each job, enabling safe parallel execution where multiple jobs can modify code without interfering with each other.

Example YAML

isolation: enabled: true mode: worktree branch_prefix: marianne cleanup_on_success: true

Methods:
get_worktree_base
get_worktree_base(workspace)

Get the directory where worktrees are created.

Source code in src/marianne/core/config/workspace.py
def get_worktree_base(self, workspace: Path) -> Path:
    """Get the directory where worktrees are created."""
    if self.worktree_base:
        return self.worktree_base
    return workspace / ".worktrees"
get_branch_name
get_branch_name(job_id)

Generate branch name for a job.

Source code in src/marianne/core/config/workspace.py
def get_branch_name(self, job_id: str) -> str:
    """Generate branch name for a job."""
    return f"{self.branch_prefix}/{job_id}"

IsolationMode

Bases: str, Enum

Isolation method for parallel job execution.

LogConfig

Bases: BaseModel

Configuration for structured logging.

Controls log level, output format, and file rotation settings.

WorkspaceLifecycleConfig

Bases: BaseModel

Configuration for workspace lifecycle management.

Controls how workspace files are handled across job iterations, particularly for self-chaining jobs that reuse the same workspace.

When archive_on_fresh is True and --fresh is used, Marianne moves non-essential workspace files to a numbered archive subdirectory before clearing state. This prevents stale file_exists and command_succeeds validations from passing on previous iteration's artifacts.

Example YAML

workspace_lifecycle: archive_on_fresh: true archive_dir: archive max_archives: 10 preserve_patterns: - ".iteration" - ".marianne-*" - ".coverage" - "archive/" - ".worktrees/"