Skip to content

Index

commands

Functions:

compile_scores

compile_scores(config=Argument(None, help='Path to the compiler config YAML file.'), preset=Option(None, '--preset', help="Built-in compiler preset to use, such as 'generic-fleet'."), workspace=Option(None, '--workspace', help='Workspace for a built-in preset. Defaults to .marianne/workspaces/<preset> under the current directory.'), output=Option(None, '--output', '-o', help='Output directory for generated score files. Defaults to <workspace>/scores when workspace is configured, otherwise scores/ next to the config file.'), agents_dir=Option(None, '--agents-dir', help='Directory for agent identity stores. Defaults to ~/.marianne/agents/.'), fleet=Option(False, '--fleet', help='Force fleet config generation even for a single agent.'), seed_only=Option(False, '--seed-only', help='Create agent identity stores without generating scores.'), dry_run=Option(False, '--dry-run', help='Show compilation summary without writing files.'), pause_before_chain=Option(False, '--pause-before-chain', help='Emit generated on_success hooks that pause before starting the next self-chain cycle.'), job_prefix=Option(None, '--job-prefix', help='Prefix generated score filenames and conductor job IDs, while leaving agent identity names unchanged.'))

Compile semantic agent definitions into Marianne scores.

Reads a YAML config that defines agents as people (voice, focus, techniques, instruments) and produces complete Marianne score YAML for each agent, plus identity directories and fleet configs.

Source code in src/marianne/cli/commands/compile.py
def compile_scores(
    config: Path | None = typer.Argument(
        None,
        help="Path to the compiler config YAML file.",
    ),
    preset: str | None = typer.Option(
        None,
        "--preset",
        help="Built-in compiler preset to use, such as 'generic-fleet'.",
    ),
    workspace: Path | None = typer.Option(
        None,
        "--workspace",
        help=(
            "Workspace for a built-in preset. Defaults to "
            ".marianne/workspaces/<preset> under the current directory."
        ),
    ),
    output: Path | None = typer.Option(
        None,
        "--output",
        "-o",
        help="Output directory for generated score files. "
        "Defaults to <workspace>/scores when workspace is configured, "
        "otherwise scores/ next to the config file.",
    ),
    agents_dir: Path | None = typer.Option(
        None,
        "--agents-dir",
        help="Directory for agent identity stores. "
        "Defaults to ~/.marianne/agents/.",
    ),
    fleet: bool = typer.Option(
        False,
        "--fleet",
        help="Force fleet config generation even for a single agent.",
    ),
    seed_only: bool = typer.Option(
        False,
        "--seed-only",
        help="Create agent identity stores without generating scores.",
    ),
    dry_run: bool = typer.Option(
        False,
        "--dry-run",
        help="Show compilation summary without writing files.",
    ),
    pause_before_chain: bool = typer.Option(
        False,
        "--pause-before-chain",
        help=(
            "Emit generated on_success hooks that pause before starting the "
            "next self-chain cycle."
        ),
    ),
    job_prefix: str | None = typer.Option(
        None,
        "--job-prefix",
        help=(
            "Prefix generated score filenames and conductor job IDs, while "
            "leaving agent identity names unchanged."
        ),
    ),
) -> None:
    """Compile semantic agent definitions into Marianne scores.

    Reads a YAML config that defines agents as people (voice, focus,
    techniques, instruments) and produces complete Marianne score YAML
    for each agent, plus identity directories and fleet configs.
    """
    from marianne_compiler.fleet import FleetGenerator
    from marianne_compiler.instruments import filter_config_to_available_instruments
    from marianne_compiler.pipeline import CompilationPipeline
    from marianne_compiler.presets import load_builtin_preset, prepare_builtin_preset

    # Load and validate config
    if preset:
        try:
            config_data = prepare_builtin_preset(
                load_builtin_preset(preset),
                name=preset,
                cwd=Path.cwd(),
                workspace=workspace,
            )
            if preset == "generic-fleet":
                available_instruments = _doctor_available_instruments()
                config_data = filter_config_to_available_instruments(
                    config_data,
                    available_instruments,
                )
                missing_tiers = _missing_instrument_tiers(config_data)
                if missing_tiers:
                    missing = ", ".join(sorted(missing_tiers))
                    raise ValueError(
                        "No doctor-available instrument remains for tiers: "
                        f"{missing}"
                    )
        except Exception as e:  # noqa: BLE001 — structured logger reports compile_preset_error
            _logger.error("compile_preset_error", preset=preset, error=str(e))
            console.print(f"[red]Error:[/red] Cannot load preset '{preset}': {e}")
            raise typer.Exit(code=1) from None
        config_base = Path.cwd()
        config_name = preset
    else:
        if config is None:
            console.print("[red]Error:[/red] Provide a config path or --preset.")
            raise typer.Exit(code=1)
        if not config.exists() or not config.is_file():
            _logger.error("compile_read_error", path=str(config), error="missing")
            console.print(f"[red]Error:[/red] Cannot read {config}")
            raise typer.Exit(code=1)
        try:
            with open(config) as f:
                config_data = yaml.safe_load(f) or {}
        except yaml.YAMLError as e:
            _logger.error("compile_yaml_error", path=str(config), error=str(e))
            console.print(f"[red]Error:[/red] Invalid YAML in {config}: {e}")
            raise typer.Exit(code=1) from None
        except OSError as e:
            _logger.error("compile_read_error", path=str(config), error=str(e))
            console.print(f"[red]Error:[/red] Cannot read {config}: {e}")
            raise typer.Exit(code=1) from None
        config_base = config.parent
        config_name = config.stem

    if pause_before_chain:
        _set_pause_before_chain(config_data)
    if job_prefix:
        _set_job_name_prefix(config_data, job_prefix)

    agents = config_data.get("agents", [])
    if not agents:
        console.print("[red]Error:[/red] Config must contain at least one agent.")
        raise typer.Exit(code=1)

    project = config_data.get("project", {})
    project_name = project.get("name", config_name)
    configured_workspace = _configured_workspace(config_data, base_dir=config_base)
    default_output = (
        Path(configured_workspace) / "scores"
        if configured_workspace
        else config_base / "scores"
    )

    # Dry run — show summary and exit
    if dry_run:
        console.print(f"[bold]Dry Run:[/bold] {project_name}")
        console.print(f"  Agents: {len(agents)}")
        for agent in agents:
            name = agent.get("name", "unnamed")
            focus = agent.get("focus", "")
            label = f"    - {name}"
            if focus:
                label += f" ({focus})"
            console.print(label)
        console.print(f"  Output: {output or default_output}")
        fleet_label = "yes" if fleet or len(agents) > 1 else "no"
        console.print(f"  Fleet: {fleet_label}")
        raise typer.Exit(code=0)

    # Resolve directories. Workspace-local scores can use portable
    # {workspace}/... self-chain hooks; fall back to config-local scores
    # only when no workspace is configured.
    output_dir = output or default_output
    resolved_agents_dir = agents_dir or Path.home() / ".marianne" / "agents"

    # Create pipeline
    pipeline = CompilationPipeline(agents_dir=resolved_agents_dir)

    # Seed-only mode — create identities without scores
    if seed_only:
        for agent_def in agents:
            identity_path = pipeline.seed_identity(agent_def, resolved_agents_dir)
            console.print(f"[green]Seeded identity:[/green] {identity_path}")
        _logger.info(
            "compile_seed_complete",
            agent_count=len(agents),
            agents_dir=str(resolved_agents_dir),
        )
        raise typer.Exit(code=0)

    # Full compilation
    try:
        score_paths = pipeline.compile_config(config_data, output_dir, base_dir=config_base)
    except Exception as e:
        _logger.error("compile_failed", error=str(e), exc_info=True)
        console.print(f"[red]Error:[/red] Compilation failed: {e}")
        raise typer.Exit(code=1) from None

    # Force fleet generation for single agent if --fleet flag set
    if fleet and len(agents) == 1:
        fleet_path = output_dir / "fleet.yaml"
        if not fleet_path.exists():
            fleet_gen = FleetGenerator()
            fleet_gen.write(config_data, output_dir, fleet_path)
            score_paths.append(fleet_path)

    for path in score_paths:
        console.print(f"[green]Generated:[/green] {path}")

    console.print(
        f"\n[bold]Compiled {len(agents)} agent(s) to {output_dir}[/bold]"
    )
    _logger.info(
        "compile_complete",
        project=project_name,
        agent_count=len(agents),
        score_count=len(score_paths),
        output_dir=str(output_dir),
    )

next_actions

next_actions(mine=Option(None, '--mine', help='Only jobs whose id starts with this prefix'), since=Option(_DEFAULT_SINCE_HOURS, '--since', min=0, help='Ignore finished jobs that ended more than this many hours ago (default 24; 0 = no limit)'), idle_after=Option(None, '--idle-after', min=1, help="Seconds without activity before a running job is UNSTICK (default: the score's stale_detection timeout, else its sheet timeout)"), tasks=Option(None, '--tasks', help='Also list TASK*.md files in this directory that no job is bound to (by the task hash in the job id `mzt agents run` makes) as CAST rows'), json_output=Option(False, '--json', '-j', help='Output a JSON array (no ANSI)'))

List what needs attention across jobs: one action per job, most urgent first.

Actions: ESCALATE (a human must decide: failed, cancelled, paused at a fermata), UNSTICK (a running sheet has gone quiet), JUDGE (completed, not yet judged), CAST (with --tasks: a TASK*.md file has no job yet; the row carries task), WAIT (still running), DONE (completed and judged). An empty queue is one DONE row with a null job_id. Judged state is the marker that mzt verdict --accept writes in the job's workspace.

Examples:

mzt next --json mzt next --mine legion- --json mzt next --tasks . --json

Source code in src/marianne/cli/commands/conduct.py
def next_actions(
    mine: str | None = typer.Option(
        None, "--mine", help="Only jobs whose id starts with this prefix",
    ),
    since: float = typer.Option(
        _DEFAULT_SINCE_HOURS,
        "--since",
        min=0,
        help="Ignore finished jobs that ended more than this many hours ago "
        "(default 24; 0 = no limit)",
    ),
    idle_after: float | None = typer.Option(
        None,
        "--idle-after",
        min=1,
        help="Seconds without activity before a running job is UNSTICK "
        "(default: the score's stale_detection timeout, else its sheet timeout)",
    ),
    tasks: Path | None = typer.Option(
        None,
        "--tasks",
        help="Also list TASK*.md files in this directory that no job is bound to "
        "(by the task hash in the job id `mzt agents run` makes) as CAST rows",
    ),
    json_output: bool = typer.Option(
        False, "--json", "-j", help="Output a JSON array (no ANSI)",
    ),
) -> None:
    """List what needs attention across jobs: one action per job, most urgent first.

    Actions: ESCALATE (a human must decide: failed, cancelled, paused at a
    fermata), UNSTICK (a running sheet has gone quiet), JUDGE (completed, not
    yet judged), CAST (with --tasks: a TASK*.md file has no job yet; the row
    carries `task`), WAIT (still running), DONE (completed and judged). An
    empty queue is one DONE row with a null job_id. Judged state is the marker
    that `mzt verdict --accept` writes in the job's workspace.

    Examples:
        mzt next --json
        mzt next --mine legion- --json
        mzt next --tasks . --json
    """
    try:
        queue = asyncio.run(
            compute_next(
                mine=mine, since_hours=since, idle_seconds=idle_after, tasks_dir=tasks,
            ),
        )
    except ConductorUnreachable as exc:
        _report_unreachable(exc, json_output=json_output)
        raise
    if json_output:
        output_json(queue)
        return
    for item in queue:
        extra = f"  {item['task']}" if item.get("task") else ""
        typer.echo(f"{item['action']}  {item['job_id'] or '-'}  {item['why']}{extra}")

verdict

verdict(job_id=Argument(..., help="The score's run id (job id) to read the verdict of"), pattern=Option(DEFAULT_VERDICT_PATTERN, '--pattern', help="Regex for a verdict line; group 'word' (or group 1) is the verdict word. Default matches 'VERDICT: <word>' lines."), workspace=Option(None, '--workspace', '-w', help='Read this workspace directly instead of asking the conductor for it'), accept=Option(False, '--accept', '--judged', help='Record this job as judged so `mzt next` stops saying JUDGE (accepted, or sent back for rework). Written to .mzt-judged.json in the workspace.'), json_output=Option(False, '--json', '-j', help='Output one JSON object (no ANSI)'))

Read a score's review verdict as PASS, REWORK, BLOCKED or unknown.

Finds the newest review/inspect artifact in the score's workspace that has a 'VERDICT:' line and maps its word: PASS/APPROVE/ACCEPT -> PASS, REWORK/REJECT -> REWORK, HOLD/BLOCK -> BLOCKED. Anything else, or no such line, is unknown. The JSON also carries findings (the report's FINDINGS bullets, else REQUIRED FIXES/FAILURES, else the bullets after a non-PASS VERDICT line), accept ({ran, passed} over the sheets' validation results), result_path (the task's REPORT file in the workspace) and round (2 when the task file has a FINDINGS: line, else 1; null when the job has no mzt agents run task file).

Examples:

mzt verdict my-job --json mzt verdict my-job --accept --json

Source code in src/marianne/cli/commands/conduct.py
def verdict(
    job_id: str = typer.Argument(..., help="The score's run id (job id) to read the verdict of"),
    pattern: str = typer.Option(
        DEFAULT_VERDICT_PATTERN,
        "--pattern",
        help="Regex for a verdict line; group 'word' (or group 1) is the verdict word. "
        "Default matches 'VERDICT: <word>' lines.",
    ),
    workspace: Path | None = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Read this workspace directly instead of asking the conductor for it",
    ),
    accept: bool = typer.Option(
        False,
        "--accept",
        "--judged",
        help="Record this job as judged so `mzt next` stops saying JUDGE (accepted, or sent "
        "back for rework). Written to .mzt-judged.json in the workspace.",
    ),
    json_output: bool = typer.Option(
        False, "--json", "-j", help="Output one JSON object (no ANSI)",
    ),
) -> None:
    """Read a score's review verdict as PASS, REWORK, BLOCKED or unknown.

    Finds the newest review/inspect artifact in the score's workspace that has
    a 'VERDICT:' line and maps its word: PASS/APPROVE/ACCEPT -> PASS,
    REWORK/REJECT -> REWORK, HOLD/BLOCK -> BLOCKED. Anything else, or no
    such line, is unknown. The JSON also carries `findings` (the report's
    FINDINGS bullets, else REQUIRED FIXES/FAILURES, else the bullets after a
    non-PASS VERDICT line), `accept` ({ran, passed} over the sheets'
    validation results), `result_path` (the task's REPORT file in the
    workspace) and `round` (2 when the task file has a FINDINGS: line, else
    1; null when the job has no `mzt agents run` task file).

    Examples:
        mzt verdict my-job --json
        mzt verdict my-job --accept --json
    """
    job_id = validate_job_id(job_id)
    submitted_at: float | None = None
    state: dict[str, Any] | None = None
    config_path: str | None = None
    if workspace is None:
        try:
            row = asyncio.run(_job_row(job_id))
        except JobNotFound:
            output_error(
                f"Score not found: {job_id}",
                hints=["Run 'mzt list' to see available scores."],
                json_output=json_output,
            )
            raise typer.Exit(1) from None
        except ConductorUnreachable as exc:
            _report_unreachable(exc, json_output=json_output)
            raise  # unreachable: report_daemon_route_error exits
        raw_ws = row.get("workspace")
        if not raw_ws:
            output_error(
                f"The conductor has no workspace recorded for {job_id}",
                hints=["Pass --workspace DIR to read a workspace directly."],
                json_output=json_output,
            )
            raise typer.Exit(1)
        workspace = Path(str(raw_ws))
        submitted_at = row.get("submitted_at")
        config_path = str(row["config_path"]) if row.get("config_path") else None
        state = asyncio.run(_safe_status(_route, job_id))

    result = build_verdict(workspace, pattern, state, config_path)
    if accept:
        try:
            _write_marker(workspace, job_id, submitted_at, result["verdict"])
        except OSError as exc:
            output_error(
                f"Could not record the verdict as judged: {exc}",
                hints=[f"Check that {workspace} is writable."],
                json_output=json_output,
            )
            raise typer.Exit(1) from None
        result["judged"] = True
    if json_output:
        output_json(result)
    else:
        typer.echo(f"{result['verdict']}: {result['source_path'] or 'no verdict line found'}")
        for finding in result["findings"]:
            typer.echo(f"  - {finding}")

wait

wait(job_id=Argument(..., help="The score's run id (job id) to wait for"), max_seconds=Option(_WAIT_DEFAULT_MAX, '--max', '-m', min=0, help='Give up after this many seconds and report wait_expired (default 1800)'), json_output=Option(False, '--json', '-j', help='Output one JSON object (no ANSI)'))

Block until a score is finished or needs a human decision.

Returns one of four states: done, needs_you, conductor_down, wait_expired. Exit codes: 0 done, 2 needs_you, 3 conductor_down, 4 wait_expired (1 is an error such as an unknown score). Rate limits, retries and fallbacks happen inside the conductor and do not end the wait.

Examples:

mzt wait my-job --json mzt wait my-job --max 600 --json

Source code in src/marianne/cli/commands/conduct.py
def wait(
    job_id: str = typer.Argument(..., help="The score's run id (job id) to wait for"),
    max_seconds: float = typer.Option(
        _WAIT_DEFAULT_MAX,
        "--max",
        "-m",
        min=0,
        help="Give up after this many seconds and report wait_expired (default 1800)",
    ),
    json_output: bool = typer.Option(
        False, "--json", "-j", help="Output one JSON object (no ANSI)",
    ),
) -> None:
    """Block until a score is finished or needs a human decision.

    Returns one of four states: done, needs_you, conductor_down, wait_expired.
    Exit codes: 0 done, 2 needs_you, 3 conductor_down, 4 wait_expired
    (1 is an error such as an unknown score). Rate limits, retries and
    fallbacks happen inside the conductor and do not end the wait.

    Examples:
        mzt wait my-job --json
        mzt wait my-job --max 600 --json
    """
    job_id = validate_job_id(job_id)

    async def fetch() -> dict[str, Any]:
        result = await _route("job.status", {"job_id": job_id, "workspace": None})
        return result if isinstance(result, dict) else {}

    try:
        outcome = asyncio.run(wait_for_job(fetch, job_id, max_seconds))
    except JobNotFound:
        output_error(
            f"Score not found: {job_id}",
            hints=["Run 'mzt list' to see available scores."],
            json_output=json_output,
        )
        raise typer.Exit(1) from None
    if json_output:
        output_json(outcome)
    else:
        typer.echo(f"{outcome['state']}: {outcome['job_id']} - {outcome['reason']}")
    code = WAIT_EXIT_CODES[outcome["state"]]
    if code:
        raise typer.Exit(code)

errors

errors(job_id=Argument(..., help="The score's run id (job id) to show errors for"), sheet=Option(None, '--sheet', '-b', help='Filter errors by specific sheet number'), error_type=Option(None, '--type', '-t', help='Filter by error type: transient, rate_limit, or permanent'), error_code=Option(None, '--code', '-c', help='Filter by error code (e.g., E001, E101)'), verbose=Option(False, '--verbose', '-V', help='Show full stdout/stderr tails for each error'), workspace=Option(None, '--workspace', '-w', help='Workspace directory to search for score state (debug override)', hidden=True), json_output=Option(False, '--json', '-j', help='Output errors as JSON'))

List all errors for a score with detailed information.

Displays errors grouped by sheet, with color-coding by error type: - Red: Permanent errors (non-retriable, fatal) - Yellow: Transient errors (retriable with backoff) - Blue: Rate limit errors (retriable after wait)

Examples:

mzt errors my-job # Show all errors mzt errors my-job --sheet 3 # Errors for sheet 3 only mzt errors my-job --type transient # Only transient errors mzt errors my-job --code E001 # Only timeout errors mzt errors my-job --verbose # Show stdout/stderr details

Source code in src/marianne/cli/commands/diagnose.py
def errors(
    job_id: str = typer.Argument(..., help="The score's run id (job id) to show errors for"),
    sheet: int | None = typer.Option(
        None,
        "--sheet",
        "-b",
        help="Filter errors by specific sheet number",
    ),
    error_type: str | None = typer.Option(
        None,
        "--type",
        "-t",
        help="Filter by error type: transient, rate_limit, or permanent",
    ),
    error_code: str | None = typer.Option(
        None,
        "--code",
        "-c",
        help="Filter by error code (e.g., E001, E101)",
    ),
    verbose: bool = typer.Option(
        False,
        "--verbose",
        "-V",
        help="Show full stdout/stderr tails for each error",
    ),
    workspace: Path | None = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace directory to search for score state (debug override)",
        hidden=True,
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output errors as JSON",
    ),
) -> None:
    """List all errors for a score with detailed information.

    Displays errors grouped by sheet, with color-coding by error type:
    - Red: Permanent errors (non-retriable, fatal)
    - Yellow: Transient errors (retriable with backoff)
    - Blue: Rate limit errors (retriable after wait)

    Examples:
        mzt errors my-job                   # Show all errors
        mzt errors my-job --sheet 3         # Errors for sheet 3 only
        mzt errors my-job --type transient  # Only transient errors
        mzt errors my-job --code E001       # Only timeout errors
        mzt errors my-job --verbose         # Show stdout/stderr details
    """
    from ._shared import validate_job_id

    job_id = validate_job_id(job_id)
    asyncio.run(_errors_job(job_id, sheet, error_type, error_code, verbose, workspace, json_output))

history

history(job_id=Argument(..., help="The score's run id (job id) to show execution history for"), sheet=Option(None, '--sheet', '-b', help='Filter by specific sheet number'), limit=Option(50, '--limit', '-n', help='Maximum number of records to show'), workspace=Option(None, '--workspace', '-w', help='Workspace directory to search for score state (debug override)', hidden=True), json_output=Option(False, '--json', '-j', help='Output history as JSON'))

Show execution history for a score.

One row per attempt, newest first: sheet, attempt, instrument and model, outcome, exit code, duration, timestamp, and the redacted cause of a failure. Read from the score's checkpoint (the last 50 attempts per sheet), so it survives completion and conductor restarts.

Examples:

mzt history my-job # Show all history mzt history my-job --sheet 3 # History for sheet 3 only mzt history my-job --limit 100 # Show more records mzt history my-job --json # Machine-readable output

Source code in src/marianne/cli/commands/diagnose.py
def history(
    job_id: str = typer.Argument(
        ..., help="The score's run id (job id) to show execution history for"
    ),
    sheet: int | None = typer.Option(
        None,
        "--sheet",
        "-b",
        help="Filter by specific sheet number",
    ),
    limit: int = typer.Option(
        50,
        "--limit",
        "-n",
        help="Maximum number of records to show",
    ),
    workspace: Path | None = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace directory to search for score state (debug override)",
        hidden=True,
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output history as JSON",
    ),
) -> None:
    """Show execution history for a score.

    One row per attempt, newest first: sheet, attempt, instrument and model,
    outcome, exit code, duration, timestamp, and the redacted cause of a
    failure. Read from the score's checkpoint (the last 50 attempts per sheet),
    so it survives completion and conductor restarts.

    Examples:
        mzt history my-job                  # Show all history
        mzt history my-job --sheet 3        # History for sheet 3 only
        mzt history my-job --limit 100      # Show more records
        mzt history my-job --json           # Machine-readable output
    """
    from ._shared import validate_job_id

    job_id = validate_job_id(job_id)
    asyncio.run(_history_job(job_id, sheet, limit, workspace, json_output))

logs

logs(job_id=Argument(None, help="The score's run id (job id) to filter logs for (optional, shows all if not specified)"), workspace=Option(None, '--workspace', '-w', help='Workspace directory to find logs (debug override)', hidden=True), log_file=Option(None, '--file', '-f', help='Specific log file path (overrides workspace default)'), follow=Option(False, '--follow', '-F', help='Follow the log file for new entries (like tail -f)'), lines=Option(50, '--lines', '-n', help='Number of lines to show (0 for all)'), level=Option(None, '--level', '-l', help='Filter by minimum log level (DEBUG, INFO, WARNING, ERROR)'), json_output=Option(False, '--json', '-j', help='Output raw JSON log entries'))

Show or tail log files for a score.

Displays log entries from Marianne log files. Supports both current log files and compressed rotated logs (.gz).

Examples:

mzt logs # Show recent logs mzt logs my-job # Filter by job ID mzt logs --follow # Follow log file (like tail -f) mzt logs --lines 100 # Show last 100 lines mzt logs --level ERROR # Show only ERROR and above mzt logs --json # Output raw JSON entries

Note

Daemon-managed logs live under the conductor logging root by default. Use --file only for explicit offline/debug log files.

Source code in src/marianne/cli/commands/diagnose.py
def logs(
    job_id: str | None = typer.Argument(
        None,
        help="The score's run id (job id) to filter logs for "
        "(optional, shows all if not specified)",
    ),
    workspace: Path | None = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Workspace directory to find logs (debug override)",
        hidden=True,
    ),
    log_file: Path | None = typer.Option(
        None,
        "--file",
        "-f",
        help="Specific log file path (overrides workspace default)",
    ),
    follow: bool = typer.Option(
        False,
        "--follow",
        "-F",
        help="Follow the log file for new entries (like tail -f)",
    ),
    lines: int = typer.Option(
        50,
        "--lines",
        "-n",
        help="Number of lines to show (0 for all)",
    ),
    level: str | None = typer.Option(
        None,
        "--level",
        "-l",
        help="Filter by minimum log level (DEBUG, INFO, WARNING, ERROR)",
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output raw JSON log entries",
    ),
) -> None:
    """Show or tail log files for a score.

    Displays log entries from Marianne log files. Supports both current log files
    and compressed rotated logs (.gz).

    Examples:
        mzt logs                         # Show recent logs
        mzt logs my-job                  # Filter by job ID
        mzt logs --follow                # Follow log file (like tail -f)
        mzt logs --lines 100             # Show last 100 lines
        mzt logs --level ERROR           # Show only ERROR and above
        mzt logs --json                  # Output raw JSON entries

    Note:
        Daemon-managed logs live under the conductor logging root by default.
        Use --file only for explicit offline/debug log files.
    """
    from ._shared import validate_job_id

    if job_id is not None:
        job_id = validate_job_id(job_id)
    configure_global_logging(console)

    # Parse log level filter
    min_level = 0
    if level:
        level_upper = level.upper()
        if level_upper not in _LEVEL_ORDER:
            console.print(
                f"[red]Invalid log level:[/red] {level}\n"
                "Valid levels: DEBUG, INFO, WARNING, ERROR, CRITICAL"
            )
            raise typer.Exit(1)
        min_level = _LEVEL_ORDER[level_upper]

    if job_id is not None and workspace is None and log_file is None:
        sources = asyncio.run(_resolve_job_log_sources(job_id))
        if sources:
            if follow:
                source = next((item for item in sources if item.follow), sources[0])
                follower = LogFollower(
                    log_path=source.path,
                    job_id=source.job_filter,
                    min_level=min_level,
                    json_output=json_output,
                )
                if not is_quiet() and not json_output:
                    console.print(
                        "[dim]Log source: "
                        f"{source.path} ({source.label}, {source.kind}, "
                        f"alias={source.alias_state}, raw={source.raw_state})[/dim]"
                    )
                follower.follow()
                return

            for source in sources:
                _display_log_source(
                    source,
                    min_level=min_level,
                    json_output=json_output,
                    num_lines=lines if lines > 0 else None,
                )
            return

    # Determine log file path
    ws = workspace or Path.cwd()
    target_log = log_file or get_default_log_path(ws)

    # Check if log file exists
    if not target_log.exists():
        # Try to find any log files in the workspace
        available_logs = find_log_files(ws, target_log)
        if not available_logs:
            console.print(f"[yellow]No log files found at:[/yellow] {target_log}")
            console.print(
                "\n[dim]Hint: daemon logs are owned by the conductor logging root.\n"
                "Use --file only when inspecting an explicit offline/debug log.[/dim]"
            )
            raise typer.Exit(1)
        # Use the first available log
        target_log = available_logs[0]

    follower = LogFollower(
        log_path=target_log,
        job_id=job_id,
        min_level=min_level,
        json_output=json_output,
    )

    # Show log file info
    if not is_quiet() and not json_output:
        console.print(f"[dim]Log file: {target_log}[/dim]")

    # Either follow or display
    if follow:
        follower.follow()
    else:
        follower.display(num_lines=lines if lines > 0 else None)

init

init(score_name=Argument(None, help="Score name (e.g. 'my-project'). Same as --name."), path=Option('.', '--path', '-p', help='Directory to initialize (default: current directory)'), name=Option('my-score', '--name', '-n', help='Name for the starter score'), force=Option(False, '--force', '-f', help='Overwrite existing files'), json_output=Option(False, '--json', '-j', help='Output result as JSON'))

Scaffold a new Marianne project with a starter score.

Creates a starter score YAML and .marianne/ project directory. Edit the score with your task, then run it with the conductor.

Examples:

mzt init mzt init my-project mzt init --path ./my-project mzt init --name data-pipeline mzt init --force mzt init --json

Source code in src/marianne/cli/commands/init_cmd.py
def init(
    score_name: str | None = typer.Argument(
        None,
        help="Score name (e.g. 'my-project'). Same as --name.",
    ),
    path: Path = typer.Option(
        ".",
        "--path",
        "-p",
        help="Directory to initialize (default: current directory)",
    ),
    name: str = typer.Option(
        "my-score",
        "--name",
        "-n",
        help="Name for the starter score",
    ),
    force: bool = typer.Option(
        False,
        "--force",
        "-f",
        help="Overwrite existing files",
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output result as JSON",
    ),
) -> None:
    """Scaffold a new Marianne project with a starter score.

    Creates a starter score YAML and .marianne/ project directory.
    Edit the score with your task, then run it with the conductor.

    Examples:
        mzt init
        mzt init my-project
        mzt init --path ./my-project
        mzt init --name data-pipeline
        mzt init --force
        mzt init --json
    """
    # Resolve name: positional arg is convenience shorthand for --name.
    # --name flag takes precedence when both are provided (flag is explicit).
    if score_name is not None and name == "my-score":
        name = score_name

    # Validate name before touching the filesystem
    name_error = _validate_name(name)
    if name_error:
        output_error(
            name_error,
            hints=["Use a simple name like 'my-score' or 'data-pipeline'."],
            json_output=json_output,
        )
        raise typer.Exit(1)

    target = path.resolve()
    score_file = target / f"{name}.yaml"
    marianne_dir = target / ".marianne"

    # Safety: refuse to overwrite without --force
    if not force:
        if score_file.exists():
            output_error(
                f"Score already exists: {score_file}",
                severity="warning",
                hints=["Use --force to overwrite."],
                json_output=json_output,
            )
            raise typer.Exit(1)
        if marianne_dir.exists():
            output_error(
                f"Marianne project already initialized: {marianne_dir}",
                severity="warning",
                hints=["Use --force to reinitialize."],
                json_output=json_output,
            )
            raise typer.Exit(1)

    # Create .marianne/ directory
    marianne_dir.mkdir(parents=True, exist_ok=True)

    # Create workspaces/ directory so `mzt validate` passes immediately
    workspaces_dir = target / "workspaces"
    workspaces_dir.mkdir(parents=True, exist_ok=True)

    # Generate and write starter score. On a machine whose only ready
    # instrument is a local model server, the starter binds that server
    # (GH #494); otherwise it binds the `strong` class as before.
    local_instrument = _ready_local_http_profile()
    score_content = _generate_starter_score(name, local_instrument)
    score_file.write_text(score_content)

    # Setup owns only an absent user layer; a later init never rewrites edits.
    from marianne.instruments.classes import write_user_classes

    try:
        write_user_classes(if_absent=True)
    except (OSError, ValueError) as exc:
        output_error(f"Starter score created, but classes setup failed: {exc}")
        raise typer.Exit(1) from exc

    _logger.info("init.complete", target_path=str(target), score_name=name)

    # Output
    if json_output:
        output_json({
            "success": True,
            "name": name,
            "score_file": str(score_file),
            "target_path": str(target),
            "instrument": local_instrument or "strong",
        })
    else:
        console.print(
            f"\n[bold green]Marianne project initialized[/bold green] in {target}\n"
        )
        console.print(
            f"  Created: [bold]{name}.yaml[/bold]"
            "        (starter score — edit with your task)"
        )
        if local_instrument:
            console.print(
                f"  Bound to: [bold]{local_instrument}[/bold]"
                "        (the only ready instrument is a local model server;"
                " the starter passes replies between sheets, not files)"
            )
        console.print(
            "  Created: [bold].marianne/[/bold]"
            "              (project config directory)"
        )
        console.print()
        console.print("[dim]Next steps:[/dim]")
        console.print("  0. [bold]mzt doctor[/bold]              (check your environment)")
        console.print(f"  1. Edit [bold]{name}.yaml[/bold] with your task")
        console.print(
            f"  2. [bold]mzt start[/bold] && "
            f"[bold]mzt run {name}.yaml[/bold]"
        )
        console.print(f"  3. [bold]mzt status {name}[/bold] to watch progress")
        console.print()

modify

modify(job_id=Argument(..., help="The score's run id (job id) to modify"), config=Option(..., '--config', '-c', help='New configuration file', exists=True, readable=True), resume_flag=Option(False, '--resume', '-r', help='Immediately resume with new config after pausing'), wait=Option(False, '--wait', help='Wait for score to pause before resuming (when --resume)'), timeout=Option(60, '--timeout', '-t', help='Timeout in seconds for pause acknowledgment'), json_output=Option(False, '--json', '-j', help='Output result as JSON'))

Apply a new configuration to a score and optionally resume execution.

This is a convenience command that combines pause + config update. If the score is running, it will be paused first. Use --resume to immediately resume with the new configuration.

Examples:

mzt modify my-job --config updated.yaml mzt modify my-job -c new-config.yaml --resume mzt modify my-job -c updated.yaml -r --wait

Source code in src/marianne/cli/commands/pause.py
def modify(
    job_id: str = typer.Argument(..., help="The score's run id (job id) to modify"),
    config: Path = typer.Option(
        ...,
        "--config",
        "-c",
        help="New configuration file",
        exists=True,
        readable=True,
    ),
    resume_flag: bool = typer.Option(
        False,
        "--resume",
        "-r",
        help="Immediately resume with new config after pausing",
    ),
    wait: bool = typer.Option(
        False,
        "--wait",
        help="Wait for score to pause before resuming (when --resume)",
    ),
    timeout: int = typer.Option(
        60,
        "--timeout",
        "-t",
        help="Timeout in seconds for pause acknowledgment",
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output result as JSON",
    ),
) -> None:
    """Apply a new configuration to a score and optionally resume execution.

    This is a convenience command that combines pause + config update.
    If the score is running, it will be paused first.
    Use --resume to immediately resume with the new configuration.

    Examples:
        mzt modify my-job --config updated.yaml
        mzt modify my-job -c new-config.yaml --resume
        mzt modify my-job -c updated.yaml -r --wait
    """
    from ._shared import validate_job_id

    job_id = validate_job_id(job_id)
    asyncio.run(
        _modify_job(job_id, config, resume_flag, wait, timeout, json_output)
    )

clear_rate_limits

clear_rate_limits(instrument=Option(None, '--instrument', '-i', help='Clear rate limit for a specific instrument only (e.g. claude-cli)'), json_output=Option(False, '--json', '-j', help='Output result as JSON'))

Clear stale rate limits on instruments.

When a backend rate limit expires but the conductor still has it cached, sheets may stay blocked unnecessarily. This command clears the cached limit so dispatch resumes immediately.

Clears both the rate limit coordinator (used by the scheduler) and the baton's per-instrument state (used by the dispatch loop).

Examples:

mzt clear-rate-limits # Clear all mzt clear-rate-limits -i claude-cli # Clear one instrument mzt clear-rate-limits --json # JSON output

Source code in src/marianne/cli/commands/rate_limits.py
def clear_rate_limits(
    instrument: str | None = typer.Option(
        None,
        "--instrument",
        "-i",
        help="Clear rate limit for a specific instrument only (e.g. claude-cli)",
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output result as JSON",
    ),
) -> None:
    """Clear stale rate limits on instruments.

    When a backend rate limit expires but the conductor still has it cached,
    sheets may stay blocked unnecessarily. This command clears the cached
    limit so dispatch resumes immediately.

    Clears both the rate limit coordinator (used by the scheduler) and
    the baton's per-instrument state (used by the dispatch loop).

    Examples:
        mzt clear-rate-limits                    # Clear all
        mzt clear-rate-limits -i claude-cli      # Clear one instrument
        mzt clear-rate-limits --json             # JSON output
    """
    asyncio.run(_clear_rate_limits(instrument=instrument, json_output=json_output))

clear

clear(job=Option(None, '--score', '-j', help='Specific score ID(s) to clear. Can be repeated.'), status_filter=Option(None, '--status', '-s', help='Status(es) to clear: failed, completed, cancelled. Can be repeated. Defaults to all terminal statuses.'), older_than=Option(None, '--older-than', help='Only clear scores older than this many seconds.'), yes=Option(False, '--yes', '-y', help='Skip confirmation prompt.'))

Clear completed, failed, and cancelled scores from the conductor registry.

Removes completed, failed, and/or cancelled scores from the conductor's tracking. Running and queued scores are never cleared.

Examples:

mzt clear # Clear all terminal scores mzt clear --score conductor-fix # Clear a specific score mzt clear --status failed # Clear only failed scores mzt clear --status failed -s cancelled # Clear failed + cancelled mzt clear --older-than 3600 # Terminal scores older than 1h mzt clear -y # Skip confirmation

Source code in src/marianne/cli/commands/status.py
def clear(
    job: list[str] | None = typer.Option(
        None,
        "--score",
        "-j",
        help="Specific score ID(s) to clear. Can be repeated.",
    ),
    status_filter: list[str] | None = typer.Option(
        None,
        "--status",
        "-s",
        help="Status(es) to clear: failed, completed, cancelled. "
        "Can be repeated. Defaults to all terminal statuses.",
    ),
    older_than: float | None = typer.Option(
        None,
        "--older-than",
        help="Only clear scores older than this many seconds.",
    ),
    yes: bool = typer.Option(
        False,
        "--yes",
        "-y",
        help="Skip confirmation prompt.",
    ),
) -> None:
    """Clear completed, failed, and cancelled scores from the conductor registry.

    Removes completed, failed, and/or cancelled scores from the conductor's
    tracking. Running and queued scores are never cleared.

    Examples:
        mzt clear                                 # Clear all terminal scores
        mzt clear --score conductor-fix           # Clear a specific score
        mzt clear --status failed                 # Clear only failed scores
        mzt clear --status failed -s cancelled    # Clear failed + cancelled
        mzt clear --older-than 3600               # Terminal scores older than 1h
        mzt clear -y                              # Skip confirmation
    """
    asyncio.run(_clear_jobs(job, status_filter, older_than, yes))

list_jobs

list_jobs(all_jobs=Option(False, '--all', '-a', help='Show all scores including completed, failed, and cancelled'), status_filter=Option(None, '--status', '-s', help='Filter by score status (queued, running, completed, failed, paused)'), limit=Option(20, '--limit', '-l', help='Maximum number of terminal (completed/failed/cancelled) scores to display; live scores (queued, running, paused) are always all shown'), json_output=Option(False, '--json', help='Output as JSON array for machine parsing'), workspace=Option(None, '--workspace', '-w', help='Reserved for future per-workspace filtering.', hidden=True))

List scores from the conductor.

By default shows only active scores (queued, running, paused). Use --all to include completed, failed, and cancelled scores.

Source code in src/marianne/cli/commands/status.py
def list_jobs(
    all_jobs: bool = typer.Option(
        False,
        "--all",
        "-a",
        help="Show all scores including completed, failed, and cancelled",
    ),
    status_filter: str | None = typer.Option(
        None,
        "--status",
        "-s",
        help="Filter by score status (queued, running, completed, failed, paused)",
    ),
    limit: int = typer.Option(
        20,
        "--limit",
        "-l",
        help="Maximum number of terminal (completed/failed/cancelled) scores to "
        "display; live scores (queued, running, paused) are always all shown",
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        help="Output as JSON array for machine parsing",
    ),
    workspace: Path | None = typer.Option(
        None,
        "--workspace",
        "-w",
        help="Reserved for future per-workspace filtering.",
        hidden=True,
    ),
) -> None:
    """List scores from the conductor.

    By default shows only active scores (queued, running, paused).
    Use --all to include completed, failed, and cancelled scores.
    """
    asyncio.run(_list_jobs(all_jobs, status_filter, limit, workspace, json_output))