Skip to content

validate

validate

Validate command for Marianne CLI.

This module implements the mzt validate command for comprehensive configuration validation before score execution.

★ Insight ───────────────────────────────────── 1. Multi-layer validation: The validate command performs 3 distinct validation layers: YAML syntax (parseable), Pydantic schema (structural), and extended checks (semantic). Each layer catches different classes of errors.

  1. Exit code convention: Exit codes follow a convention (0=valid, 1=errors, 2=cannot parse). This enables CI/CD integration where scripts can differentiate between "has validation errors" vs "cannot even validate" scenarios.

  2. DAG visualization: When sheet dependencies are configured, the command visualizes the execution graph. This helps users understand parallel execution potential and identify dependency bottlenecks. ─────────────────────────────────────────────────

Classes

Functions:

validate

validate(config_file=Argument(..., help='Path to YAML score configuration file', exists=True, readable=True), json_output=Option(False, '--json', '-j', help='Output validation results as JSON'), verbose=Option(False, '--verbose', '-v', help='Show detailed validation output'), strict=Option(False, '--strict', help='Treat unsuppressed warnings as failures'), errors_only=Option(False, '--errors-only', help='Show only error findings'), render_prompts=Option(None, '--render-prompts', help="Write every sheet's fully rendered prompt (deduplicated: identical renders share one section) to this Markdown file, or '-' for stdout. With --json, each sheet also carries rendered_prompt.", show_default=False))

Validate a score configuration file.

Performs comprehensive validation including: - YAML syntax and Pydantic schema validation - Jinja template syntax checking - Path existence verification - Regex pattern compilation - Configuration completeness checks

Exit codes

0: Valid (warnings/info OK) 1: Invalid (one or more errors) 2: Cannot validate (file not found, YAML unparseable)

Source code in src/marianne/cli/commands/validate.py
def validate(
    config_file: Path = typer.Argument(
        ...,
        help="Path to YAML score configuration file",
        exists=True,
        readable=True,
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Output validation results as JSON",
    ),
    verbose: bool = typer.Option(
        False,
        "--verbose",
        "-v",
        help="Show detailed validation output",
    ),
    strict: bool = typer.Option(False, "--strict", help="Treat unsuppressed warnings as failures"),
    errors_only: bool = typer.Option(False, "--errors-only", help="Show only error findings"),
    render_prompts: str | None = typer.Option(
        None,
        "--render-prompts",
        help=(
            "Write every sheet's fully rendered prompt (deduplicated: identical "
            "renders share one section) to this Markdown file, or '-' for stdout. "
            "With --json, each sheet also carries rendered_prompt."
        ),
        show_default=False,
    ),
) -> None:
    """Validate a score configuration file.

    Performs comprehensive validation including:
    - YAML syntax and Pydantic schema validation
    - Jinja template syntax checking
    - Path existence verification
    - Regex pattern compilation
    - Configuration completeness checks

    Exit codes:
      0: Valid (warnings/info OK)
      1: Invalid (one or more errors)
      2: Cannot validate (file not found, YAML unparseable)
    """
    configure_global_logging(console)

    # First try to read and parse YAML
    try:
        raw_yaml = config_file.read_text()
    except Exception as e:  # noqa: BLE001 — CLI boundary reports the error and exits unsuccessfully
        output_error(
            f"Cannot read score file: {e}",
            hints=["Check that the file exists and you have read permission."],
            json_output=json_output,
        )
        raise typer.Exit(2) from None

    # Try to parse YAML
    try:
        parsed = yaml.safe_load(raw_yaml)
    except yaml.YAMLError as e:
        output_error(
            f"YAML syntax error: {e}",
            hints=["Check for indentation issues or invalid YAML characters."],
            json_output=json_output,
        )
        raise typer.Exit(2) from None

    # Ensure parsed YAML is a mapping (dict), not a scalar or list
    if not isinstance(parsed, dict):
        got_type = type(parsed).__name__ if parsed is not None else "empty file"
        output_error(
            f"Score must be a YAML mapping (key-value pairs), got: {got_type}",
            hints=[
                "A Marianne score needs key-value fields like: name: my-score",
                "Check that your file isn't plain text, a list, or empty.",
                "See: docs/score-writing-guide.md",
            ],
            json_output=json_output,
        )
        raise typer.Exit(2) from None

    # Detect fleet configs — they aren't scores, so skip score validation
    if parsed.get("type") == "fleet":
        if json_output:
            import json as json_mod

            console.print(
                json_mod.dumps(
                    {
                        "type": "fleet",
                        "valid": True,
                        "skipped": True,
                        "message": ("Fleet config — not subject to score validation."),
                        "file": str(config_file),
                    },
                    indent=2,
                ),
                soft_wrap=True,
                highlight=False,
            )
        else:
            console.print(
                f"\n[cyan]{config_file.name}[/cyan] is a fleet config, not a score."
                " Fleet configs are not subject to score validation.",
            )
        raise typer.Exit(0) from None

    if not any(key in parsed for key in ("name", "sheet", "prompt")):
        output_error(
            "This YAML is not a Marianne score (expected name, sheet, prompt).",
            json_output=json_output,
        )
        raise typer.Exit(2) from None

    # Try Pydantic validation
    try:
        config = JobConfig.from_yaml(config_file)
    except ValidationError as e:
        load_issues = _structured_load_issues(e, raw_yaml)
        if load_issues is not None:
            reporter = ValidationReporter(console)
            if json_output:
                import json as json_mod

                data = json_mod.loads(reporter.report_json(load_issues))
                data["rendering"] = {"total_sheets": None, "sheets": [], "render_errors": []}
                data["summary"] = _raw_score_summary(parsed)
                data["suppressed"] = []
                if errors_only:
                    data["issues"] = [i for i in data["issues"] if i["severity"] == "error"]
                console.print(json_mod.dumps(data, indent=2), soft_wrap=True, highlight=False)
            else:
                summary = _raw_score_summary(parsed)
                console.print(f"Score: {summary['score']}")
                console.print(f"Loops: {', '.join(summary['loops']) or 'none'}")
                reporter.report_terminal(
                    load_issues, str(summary["score"]), verbose=verbose, errors_only=errors_only
                )
            raise typer.Exit(1) from None
        hints = _schema_error_hints(str(e))
        output_error(f"Schema validation failed: {e}", hints=hints, json_output=json_output)
        raise typer.Exit(2) from None
    except Exception as e:  # noqa: BLE001 — CLI boundary reports the error and exits unsuccessfully
        hints = _schema_error_hints(str(e))
        output_error(
            f"Schema validation failed: {e}",
            hints=hints,
            json_output=json_output,
        )
        raise typer.Exit(2) from None

    # Show basic info first
    if not json_output:
        console.print(f"\nValidating [cyan]{config.name}[/cyan]...")
        console.print()
        console.print("[green]✓[/green] YAML syntax valid")
        console.print("[green]✓[/green] Schema validation passed (Pydantic)")
        console.print()
        console.print("Running extended validation checks...")

    # Run extended validation checks
    runner = ValidationRunner(create_default_checks())
    issues = runner.validate(config, config_file, raw_yaml)
    issues, suppressed = apply_suppression(config, issues)
    summary = structural_summary(config)
    summary["classes"] = class_summary(config)

    # Output results
    reporter = ValidationReporter(console)

    if json_output:
        import json as json_mod

        from marianne.validation.rendering import generate_preview

        # Build combined JSON with validation issues and rendering preview
        validation_data = json_mod.loads(reporter.report_json(issues))
        validation_data["summary"] = summary
        validation_data["suppressed"] = suppressed
        if errors_only:
            validation_data["issues"] = [
                issue for issue in validation_data["issues"] if issue["severity"] == "error"
            ]
        preview = generate_preview(config, config_file)
        validation_data["rendering"] = reporter.report_rendering_json(
            preview, full_prompts=render_prompts is not None,
        )
        if render_prompts is not None and render_prompts != "-":
            _write_rendered_prompts(preview, config.name, Path(render_prompts))
        console.print(
            json_mod.dumps(validation_data, indent=2),
            soft_wrap=True,
            highlight=False,
        )
    else:
        console.print(f"\nScore: {summary['score']}")
        console.print(f"Sheets: {summary['sheets']} ({summary['stages']} stages)")
        console.print(f"Instruments: {summary['instruments']['primary']}")
        class_info = summary.get("classes") or {}
        for row in class_info.get("used", []):
            chain = ", ".join(row["chain"])
            console.print(
                f"Instruments: {row['class']} → {chain} "
                f"({row['layer']} layer, sha256 {row['layer_sha256'] or 'n/a'})"
            )
        for layer in class_info.get("layers", []):
            if layer["present"]:
                console.print(
                    f"[dim]Class layer {layer['layer']}: {layer['path']} "
                    f"(sha256 {layer['sha256']})[/dim]"
                )
        console.print(f"Variables: {summary['variables']['declared']} declared")
        if summary["loops"]:
            console.print(f"Loops: {', '.join(summary['loops'])}")
        if summary["triggers"]:
            console.print(f"Triggers: {', '.join(summary['triggers'])}")
        if suppressed:
            console.print(f"Suppressed: {sum(int(row['count']) for row in suppressed)}")
        reporter.report_terminal(issues, config.name, verbose=verbose, errors_only=errors_only)

        if render_prompts is not None:
            # Every sheet, full text, whatever the findings say: the prompts
            # are what the composer wants to read when a finding is about them.
            from marianne.validation.rendering import generate_preview

            full = generate_preview(config, config_file)
            if render_prompts == "-":
                console.print(render_prompts_markdown(full, config.name), markup=False)
            else:
                written = _write_rendered_prompts(full, config.name, Path(render_prompts))
                console.print(
                    f"Rendered prompts: {written} "
                    f"({full.total_sheets} sheet(s), "
                    f"{_distinct_prompt_count(full)} distinct)",
                    markup=False,
                )

        # Show config summary if no errors
        if not runner.has_errors(issues):
            console.print()
            console.print("[dim]Configuration summary:[/dim]")
            console.print(f"  Sheets: {config.sheet.total_sheets}")
            instrument_display = config.effective_instrument_name
            console.print(f"  Instrument: {instrument_display}")
            console.print(f"  Validations: {len(config.validations)}")
            console.print(f"  Notifications: {len(config.notifications)}")

            # Show DAG visualization if dependencies configured (v17 evolution)
            if config.sheet.dependencies:
                _show_dag_visualization(config, verbose)

            # Show rendering preview when validation passes
            from marianne.validation.rendering import generate_preview

            preview = generate_preview(
                config,
                config_file,
                max_sheets=1 if not verbose else None,
            )
            reporter.report_rendering_terminal(preview, verbose=verbose)

            # Report any rendering errors
            for err in preview.render_errors:
                console.print(f"  [red]Rendering error:[/red] {err}")
            for sheet in preview.sheets:
                if sheet.render_error:
                    console.print(
                        f"  [red]Sheet {sheet.sheet_num} render error:[/red] {sheet.render_error}"
                    )

    # Exit with appropriate code
    exit_code = runner.get_exit_code(issues, strict=strict)
    if exit_code != 0:
        raise typer.Exit(exit_code) from None