Skip to content

instruments

instruments

Instrument management commands — mzt instruments list|check.

These commands let users discover available instruments, check their readiness, and diagnose configuration issues. They build on the InstrumentProfileLoader and InstrumentRegistry — YAML profiles loaded from built-in, organization, and venue directories.

The music metaphor: these commands are the instrument workshop's front desk. list shows what's on the rack. check picks one up and plays a test note.

Classes

ResolvedRow

Bases: TypedDict

One sheet's binding as mzt instruments resolve reports it.

LiveCall

Bases: TypedDict

One real prompt through the conductor's backend factory.

LiveReport

Bases: TypedDict

mzt instruments check --live / mzt doctor --live result.

Functions:

show_classes

show_classes(json_output=Option(False, '--json'))

Show effective chains, their layers, and local availability.

Source code in src/marianne/cli/commands/instruments.py
@classes_app.command(name="show")
def show_classes(json_output: bool = typer.Option(False, "--json")) -> None:
    """Show effective chains, their layers, and local availability."""
    report, _ = _class_report()
    if json_output:
        output_json(report)
        return
    for name, entry in report["classes"].items():
        console.print(
            f"{name} ({entry['source_layer']}): "
            + " → ".join(item["profile"] for item in entry["chain"])
        )
    for layer in report["layers"]:
        console.print(f"{layer['layer']}: {layer['path']} sha256={layer['sha256']}")

check_classes

check_classes(class_name=Option(None, '--class', help='Require this class to be runnable.'))

Refuse broken layers and configured chains with no available entry.

Source code in src/marianne/cli/commands/instruments.py
@classes_app.command(name="check")
def check_classes(
    class_name: str | None = typer.Option(
        None, "--class", help="Require this class to be runnable."
    ),
) -> None:
    """Refuse broken layers and configured chains with no available entry."""
    report, broken = _class_report()
    if class_name is not None:
        selected = report["classes"].get(class_name)
        if selected is None or not any(item["availability"] for item in selected["chain"]):
            broken = True
    if broken:
        output_error("Capability class configuration has unavailable chains or invalid layers")
        raise typer.Exit(1)
    console.print(f"Checked {len(report['classes'])} capability classes")

show_tier_classes

show_tier_classes(catalog_dir=Option(None, '--catalog', help="Catalog v2 directory (default: the checkout's plugins submodule)."), write_proposal=Option(None, '--write-proposal', help='Write a classes-file fragment you can merge by hand. Never the user layer.'), force=Option(False, '--force', help='Replace an existing proposal file.'), json_output=Option(False, '--json'))

Print the frontier/balanced/light chains this machine resolves from the catalog.

Read-only: this never writes ~/.marianne/classes.yaml (your ordering is yours). --write-proposal PATH writes a fragment for you to merge.

Source code in src/marianne/cli/commands/instruments.py
@classes_app.command(name="tiers")
def show_tier_classes(
    catalog_dir: Path | None = typer.Option(
        None, "--catalog", help="Catalog v2 directory (default: the checkout's plugins submodule)."
    ),
    write_proposal: Path | None = typer.Option(
        None,
        "--write-proposal",
        help="Write a classes-file fragment you can merge by hand. Never the user layer.",
    ),
    force: bool = typer.Option(False, "--force", help="Replace an existing proposal file."),
    json_output: bool = typer.Option(False, "--json"),
) -> None:
    """Print the frontier/balanced/light chains this machine resolves from the catalog.

    Read-only: this never writes ``~/.marianne/classes.yaml`` (your ordering is
    yours). ``--write-proposal PATH`` writes a fragment for you to merge.
    """
    from marianne.core.config.catalog import CatalogError, load_catalog
    from marianne.instruments.classes import class_source_paths
    from marianne.instruments.tier_classes import (
        TIER_CLASSES,
        render_proposal,
        tier_chains,
    )

    directory = catalog_dir or _default_catalog_dir()
    if directory is None:
        output_error("No catalog v2 found; pass --catalog DIR (plugins/marianne/docs/ref/catalog)")
        raise typer.Exit(1)
    try:
        catalog = load_catalog(directory)
    except CatalogError as exc:
        output_error(str(exc))
        raise typer.Exit(1) from exc

    profiles = _load_all_profiles()
    registry = InstrumentRegistry()
    for profile in profiles.values():
        registry.register(profile)
    chains = tier_chains(catalog, profiles_available=profiles)

    if write_proposal is not None:
        layers = class_source_paths()
        if write_proposal.expanduser().resolve() in {layers[1], layers[2]}:
            output_error(
                f"{write_proposal} is a class layer file; the proposal is for you to merge, "
                "so write it elsewhere"
            )
            raise typer.Exit(1)
        if write_proposal.exists() and not force:
            output_error(f"{write_proposal} exists; use --force to replace it")
            raise typer.Exit(1)
        note = (
            f"catalog {directory} (generated_at {catalog.index.generated_at}); "
            f"{len(profiles)} registered profiles; non-provisional tiers, no metered routes."
        )
        write_proposal.parent.mkdir(parents=True, exist_ok=True)
        write_proposal.write_text(render_proposal(chains, machine_note=note), encoding="utf-8")

    report: dict[str, list[dict[str, Any]]] = {}
    for tier in TIER_CLASSES:
        rows = []
        for entry in chains[tier]:
            available, reason = check_instrument_available(entry.profile, registry)
            rows.append(
                {
                    "profile": entry.profile,
                    "model": entry.model,
                    "effort": entry.effort,
                    "family": entry.family,
                    "access": entry.access,
                    "availability": available,
                    "reason": reason,
                }
            )
        report[tier] = rows
    if json_output:
        output_json(report)
        return
    for tier_name, rows in report.items():
        console.print(f"{tier_name}:")
        if not rows:
            console.print("  (no non-provisional, non-metered entry reaches this tier here)")
        for row in rows:
            effort = f" effort={row['effort']}" if row["effort"] else ""
            mark = "ok " if row["availability"] else "n/a"
            console.print(
                f"  [{mark}] {row['profile']} {row['model']}{effort}  "
                f"({row['family']}, {row['access']})",
                markup=False,
                highlight=False,
                soft_wrap=True,
            )
    if write_proposal is not None:
        console.print(f"Proposal written to {write_proposal} (not installed; merge by hand)")

write_classes

write_classes(dry_run=Option(False, '--dry-run'), force=Option(False, '--force'), if_absent=Option(False, '--if-absent'))

Generate a user map from shipped profiles available on this machine.

Source code in src/marianne/cli/commands/instruments.py
@classes_app.command(name="write")
def write_classes(
    dry_run: bool = typer.Option(False, "--dry-run"),
    force: bool = typer.Option(False, "--force"),
    if_absent: bool = typer.Option(False, "--if-absent"),
) -> None:
    """Generate a user map from shipped profiles available on this machine."""
    try:
        path, content, changed = write_user_classes(
            dry_run=dry_run,
            force=force,
            if_absent=if_absent,
        )
    except (OSError, ValueError) as exc:
        output_error(str(exc))
        raise typer.Exit(1) from exc
    if dry_run:
        console.print(content)
    else:
        console.print(f"{path}: {'written' if changed else 'already exists'}")
        for line in content.splitlines():
            if line.startswith("# not seated: "):
                console.print(line[len("# "):])

convert_catalog

convert_catalog(source=Argument(..., help='v1 instrument-catalog.yaml to read.'), out_dir=Argument(..., help='Directory to write the v2 family files and index.yaml.'))

Convert a v1 instrument catalog to the v2 directory (one YAML per family).

Source code in src/marianne/cli/commands/instruments.py
@catalog_app.command(name="convert")
def convert_catalog(
    source: Path = typer.Argument(..., help="v1 instrument-catalog.yaml to read."),
    out_dir: Path = typer.Argument(
        ..., help="Directory to write the v2 family files and index.yaml."
    ),
) -> None:
    """Convert a v1 instrument catalog to the v2 directory (one YAML per family)."""
    from marianne.core.config.catalog import load_catalog
    from marianne.instruments.catalog_v1 import write_catalog

    try:
        index = write_catalog(source, out_dir)
        load_catalog(out_dir)
    except (OSError, ValueError, KeyError) as exc:
        output_error(f"catalog conversion failed: {exc}")
        raise typer.Exit(1) from exc
    console.print(
        f"{index.model_count} models in {len(index.families)} families written to {out_dir}"
    )

check_catalog

check_catalog(directory=Argument(..., help='v2 catalog directory (holds index.yaml).'))

Validate a v2 catalog directory against the schema.

Source code in src/marianne/cli/commands/instruments.py
@catalog_app.command(name="check")
def check_catalog(
    directory: Path = typer.Argument(..., help="v2 catalog directory (holds index.yaml)."),
) -> None:
    """Validate a v2 catalog directory against the schema."""
    from marianne.core.config.catalog import CatalogError, load_catalog

    try:
        catalog = load_catalog(directory)
    except CatalogError as exc:
        output_error(str(exc))
        raise typer.Exit(1) from exc
    provisional = sum(1 for m in catalog.models() if m.tier_status.provisional)
    console.print(
        f"{len(catalog.models())} models in {len(catalog.files)} families; "
        f"{provisional} with provisional tiers"
    )

instruments_callback

instruments_callback(ctx)

Show instrument overview if no subcommand given.

Source code in src/marianne/cli/commands/instruments.py
@instruments_app.callback(invoke_without_command=True)
def instruments_callback(ctx: typer.Context) -> None:
    """Show instrument overview if no subcommand given."""
    if ctx.invoked_subcommand is None:
        # Default to list when called without a subcommand
        ctx.invoke(list_instruments)

list_instruments

list_instruments(json_output=Option(False, '--json', help='Output as JSON'))

List all available instruments and their readiness status.

Source code in src/marianne/cli/commands/instruments.py
@instruments_app.command(name="list")
def list_instruments(
    json_output: bool = typer.Option(
        False,
        "--json",
        help="Output as JSON",
    ),
) -> None:
    """List all available instruments and their readiness status."""
    profiles = _load_all_profiles()

    if not profiles:
        if json_output:
            console.print("[]")
        else:
            console.print(
                "[dim]No instruments configured.[/dim]\n"
                "Add instrument profiles to ~/.marianne/instruments/ "
                "or .marianne/instruments/"
            )
        return

    if json_output:
        _list_json(profiles)
    else:
        _list_table(profiles)

resolve_score

resolve_score(score=Argument(..., help='Score YAML to resolve'), json_output=Option(False, '--json', help='Output as JSON'))

Show, per sheet, the profile and model each instrument binding resolves to.

Reads the score the way the conductor does at admission — score aliases, capability classes from this machine's class map, per-sheet and instrument_map pins — and prints one row per sheet: the alias (or class) the sheet was bound through, the profile it resolved to, the model, and the fallback chain. This is what a score's diversity claim actually configures; the prose says what the author meant.

Source code in src/marianne/cli/commands/instruments.py
@instruments_app.command(name="resolve")
def resolve_score(
    score: Path = typer.Argument(..., help="Score YAML to resolve"),
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
) -> None:
    """Show, per sheet, the profile and model each instrument binding resolves to.

    Reads the score the way the conductor does at admission — score aliases,
    capability classes from this machine's class map, per-sheet and
    instrument_map pins — and prints one row per sheet: the alias (or class)
    the sheet was bound through, the profile it resolved to, the model, and
    the fallback chain. This is what a score's diversity claim actually
    configures; the prose says what the author meant.
    """
    from marianne.core.config.job import JobConfig
    from marianne.core.sheet import build_sheets
    from marianne.instruments.classes import load_class_map, resolve_job_classes

    try:
        config = JobConfig.from_yaml(score)
    except Exception as exc:  # noqa: BLE001 — the score's own error is the answer
        output_error(f"cannot load {score}: {exc}")
        raise typer.Exit(1) from exc
    profile_names = set(_load_all_profiles())
    try:
        snapshot = resolve_job_classes(
            config, profile_names, load_class_map(profile_names=profile_names)
        )
    except ValueError as exc:
        output_error(str(exc))
        raise typer.Exit(1) from exc
    sheets = build_sheets(config, classes=snapshot)
    rows: list[ResolvedRow] = []
    for sheet in sheets:
        resolution = sheet.instrument_resolution
        bound_through = sheet.instrument_alias or (
            resolution.requested if resolution is not None else ""
        )
        model = sheet.instrument_config.get("model")
        rows.append({
            "sheet": sheet.num,
            "movement": sheet.movement,
            "voice": sheet.voice,
            "bound_through": bound_through,
            "profile": sheet.instrument_name,
            "model": str(model) if model is not None else None,
            "fallbacks": list(sheet.instrument_fallbacks),
        })
    if json_output:
        output_json({"score": str(score), "sheets": rows})
        return
    table = Table(title=f"Resolved bindings — {config.name}", show_header=True,
                  header_style="bold", padding=(0, 2))
    for col in ("SHEET", "MOVEMENT", "VOICE", "BOUND THROUGH", "PROFILE", "MODEL", "FALLBACKS"):
        table.add_column(col, no_wrap=col != "FALLBACKS")
    for r in rows:
        table.add_row(
            str(r["sheet"]), str(r["movement"]),
            "" if r["voice"] is None else str(r["voice"]),
            r["bound_through"] or "[dim](direct)[/dim]", r["profile"],
            r["model"] or "[dim](profile default)[/dim]",
            ", ".join(r["fallbacks"]) or "[dim]none[/dim]",
        )
    console.print(table)
    distinct = {(r["profile"], r["model"]) for r in rows}
    console.print(f"{len(rows)} sheets, {len(distinct)} distinct profile+model bindings")

check_instrument

check_instrument(name=Argument(help='Instrument name to check'), json_output=Option(False, '--json', help='Output as JSON'), live=Option(False, '--live', help='Run one real prompt through the same backend the conductor uses (and one schema-mode prompt when the profile declares json_schema_flag). Proves the profile against the installed CLI, not just its schema. Spends one or two model calls.'), model=Option(None, '--model', help="Model for --live (default: the profile's default_model)"), timeout=Option(180.0, '--timeout', help='Seconds per --live call', min=5.0), record=Option(None, '--record', help="With --live: write each call's raw stdout, stderr and exit code plus the CLI version to DIR/<instrument>/ as a parser fixture (GH #472: tests should read what the CLI actually prints)"))

Check readiness and configuration of a specific instrument.

Source code in src/marianne/cli/commands/instruments.py
@instruments_app.command(name="check")
def check_instrument(
    name: str = typer.Argument(help="Instrument name to check"),
    json_output: bool = typer.Option(
        False,
        "--json",
        help="Output as JSON",
    ),
    live: bool = typer.Option(
        False,
        "--live",
        help=(
            "Run one real prompt through the same backend the conductor uses "
            "(and one schema-mode prompt when the profile declares "
            "json_schema_flag). Proves the profile against the installed CLI, "
            "not just its schema. Spends one or two model calls."
        ),
    ),
    model: str | None = typer.Option(
        None, "--model", help="Model for --live (default: the profile's default_model)",
    ),
    timeout: float = typer.Option(
        180.0, "--timeout", help="Seconds per --live call", min=5.0,
    ),
    record: Path | None = typer.Option(
        None,
        "--record",
        help=(
            "With --live: write each call's raw stdout, stderr and exit code "
            "plus the CLI version to DIR/<instrument>/ as a parser fixture "
            "(GH #472: tests should read what the CLI actually prints)"
        ),
    ),
) -> None:
    """Check readiness and configuration of a specific instrument."""
    profiles = _load_all_profiles()

    if name not in profiles:
        if json_output:
            output_json({"error": f"Unknown instrument: {name}"})
        else:
            output_error(
                f"Unknown instrument: '{name}'",
                error_code="INSTR-001",
                hints=[
                    "Run 'mzt instruments list' to see available instruments",
                    "Add profiles to ~/.marianne/instruments/ or .marianne/instruments/",
                ],
            )
        raise typer.Exit(1)

    profile = profiles[name]

    if live:
        report = live_probe(profile, model=model, timeout=timeout, record=record)
        if json_output:
            output_json(report)
        else:
            _live_rich(report)
        if not report["ok"]:
            raise typer.Exit(1)
        return

    if json_output:
        _check_json(profile)
    else:
        _check_rich(profile)

live_failure

live_failure(report)

(mode, reason) of the first failed call, or None when the probe passed.

Source code in src/marianne/cli/commands/instruments.py
def live_failure(report: LiveReport) -> tuple[str, str] | None:
    """(mode, reason) of the first failed call, or None when the probe passed."""
    for mode in ("plain", "schema"):
        call = report["plain"] if mode == "plain" else report["schema"]
        if call is None or call.get("ok"):
            continue
        reason = (
            call.get("classification")
            or call.get("error")
            or f"exit {call.get('exit_code')}"
        )
        return mode, str(reason)
    return None

live_probe

live_probe(profile, *, model=None, timeout=180.0, record=None)

Exercise profile against the installed instrument, end to end.

The probe builds the backend through the conductor's own factory and classifies each result with the baton's own classifier, so what it reports is what a sheet would see: success, the error bucket the chain would act on, the wall time, and (in schema mode) whether the validated object came back. A profile can pass schema validation and still fail every dispatch: a flag the installed CLI rejects, an output shape the parser does not read, a provider that is not configured. This is the check that catches those.

Source code in src/marianne/cli/commands/instruments.py
def live_probe(
    profile: InstrumentProfile,
    *,
    model: str | None = None,
    timeout: float = 180.0,
    record: Path | None = None,
) -> LiveReport:
    """Exercise ``profile`` against the installed instrument, end to end.

    The probe builds the backend through the conductor's own factory and
    classifies each result with the baton's own classifier, so what it
    reports is what a sheet would see: success, the error bucket the chain
    would act on, the wall time, and (in schema mode) whether the validated
    object came back. A profile can pass schema validation and still fail
    every dispatch: a flag the installed CLI rejects, an output shape the
    parser does not read, a provider that is not configured. This is the
    check that catches those.
    """
    import asyncio
    import tempfile
    import time

    from marianne.daemon.baton.backend_pool import _create_backend_for_profile
    from marianne.daemon.baton.musician import _classify_error

    def _one(
        prompt: str, response_format: dict[str, object] | None, mode: str,
    ) -> LiveCall:
        with tempfile.TemporaryDirectory(prefix="mzt-live-probe-") as wd:
            started = time.monotonic()
            raw: dict[str, list[bytes]] = {"stdout": [], "stderr": []}
            try:
                backend = _create_backend_for_profile(
                    profile, working_directory=Path(wd), model=model,
                )
                if response_format is not None:
                    backend.set_response_format(response_format)  # type: ignore[attr-defined]
                if record is not None and hasattr(backend, "set_output_callback"):
                    backend.set_output_callback(
                        lambda stream, chunk: raw.setdefault(stream, []).append(chunk)
                    )
                result = asyncio.run(backend.execute(prompt, timeout_seconds=timeout))
                if record is not None:
                    _write_fixture(
                        record, profile, mode, prompt, response_format, raw,
                        result.exit_code,
                    )
            except Exception as exc:  # noqa: BLE001 — the probe reports any failure as data
                return {
                    "ok": False,
                    "seconds": round(time.monotonic() - started, 2),
                    "classification": "PROBE_ERROR",
                    "error": f"{type(exc).__name__}: {exc}"[:300],
                }
            cls = _classify_error(result)
            row: LiveCall = {
                "ok": bool(result.success),
                "seconds": round(time.monotonic() - started, 2),
                "exit_code": result.exit_code,
                "error_type": result.error_type,
                "classification": (
                    "RATE_LIMITED" if result.rate_limited and not result.success
                    else cls.classification
                ),
                "error_code": cls.error_code,
                "error": (result.error_message or "")[:300] or None,
                "output_head": (result.stdout or "")[:120],
            }
            return row

    plain = _one("Reply with exactly the word: ok", None, "plain")
    ok = bool(plain["ok"])
    schema: LiveCall | None = None
    schema_capable = (
        profile.kind == "http"
        or (
            profile.cli is not None
            and profile.cli.command.json_schema_flag is not None
        )
    )
    if schema_capable:
        schema = _one(_LIVE_PROMPT, _LIVE_SCHEMA, "schema")
        if schema.get("ok"):
            schema["structured_ok"] = _live_structured_ok(str(schema.get("output_head", "")))
            schema["ok"] = bool(schema["structured_ok"])
        ok = ok and bool(schema.get("ok"))
    return {
        "name": profile.name,
        "model": model or profile.default_model,
        "availability": probe_profile(profile).state,
        "plain": plain,
        "schema": schema,
        "ok": ok,
    }

prices_command

prices_command(json_output=Option(False, '--json', help='Output as JSON'), write=Option(False, '--write', help="Rewrite the drifted price fields on the BUILTIN profiles (the files under the installed package). User (~/.marianne/instruments/) and venue (.marianne/instruments/) profiles are reported and left alone: they are the composer's. Commit the result like any other builtin change."), offline=Option(False, '--offline', help='Do not fetch; compare against the last saved snapshot (see --snapshot).'), snapshot=Option(None, '--snapshot', help='Path of a models.dev api.json to compare against instead of fetching (default cache: ~/.marianne/cache/models.dev.api.json, written on every fetch).'), show_all=Option(False, '--all', help='Also list rows that match, are absent from models.dev, or are unmapped.'))

Compare every profile's model prices with models.dev; --write updates the builtins.

Marianne prices a sheet from the profile's models rows; they drift as providers reprice. models.dev (MIT, bot-synced) carries input, output, cache-read and cache-write prices per model. Exit 0 when nothing drifts, 1 when a row drifts and was not written, 2 when the snapshot cannot be had.

Source code in src/marianne/cli/commands/instruments.py
@instruments_app.command(name="prices")
def prices_command(
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
    write: bool = typer.Option(
        False,
        "--write",
        help=(
            "Rewrite the drifted price fields on the BUILTIN profiles (the files under "
            "the installed package). User (~/.marianne/instruments/) and venue "
            "(.marianne/instruments/) profiles are reported and left alone: they "
            "are the composer's. Commit the result like any other builtin change."
        ),
    ),
    offline: bool = typer.Option(
        False,
        "--offline",
        help="Do not fetch; compare against the last saved snapshot (see --snapshot).",
    ),
    snapshot: Path | None = typer.Option(
        None,
        "--snapshot",
        help=(
            "Path of a models.dev api.json to compare against instead of fetching "
            "(default cache: ~/.marianne/cache/models.dev.api.json, written on every fetch)."
        ),
    ),
    show_all: bool = typer.Option(
        False,
        "--all",
        help="Also list rows that match, are absent from models.dev, or are unmapped.",
    ),
) -> None:
    """Compare every profile's model prices with models.dev; --write updates the builtins.

    Marianne prices a sheet from the profile's `models` rows; they drift as
    providers reprice. models.dev (MIT, bot-synced) carries input, output,
    cache-read and cache-write prices per model. Exit 0 when nothing drifts,
    1 when a row drifts and was not written, 2 when the snapshot cannot be had.
    """
    from marianne.instruments.loader import profile_source_dirs
    from marianne.instruments.prices import (
        MODELS_DEV_URL,
        PRICE_FIELDS,
        PriceRow,
        apply_drift,
        compare_profiles,
        default_cache_path,
        fetch_snapshot,
        load_layers,
        load_snapshot_file,
        save_snapshot,
        summarize,
    )

    cache = snapshot if snapshot is not None else default_cache_path()
    source: str
    try:
        if snapshot is not None or offline:
            data = load_snapshot_file(cache)
            source = str(cache)
        else:
            data = fetch_snapshot()
            save_snapshot(data, cache)
            source = MODELS_DEV_URL
    except Exception as exc:  # noqa: BLE001 - every failure here is "no snapshot"
        hint = "" if offline or snapshot is not None else f" (--offline reads {cache})"
        output_error(f"cannot load models.dev prices: {exc}{hint}")
        raise typer.Exit(2) from None

    builtins_dir, org_dir, venue_dir = profile_source_dirs()
    builtins, overlays = load_layers(builtins_dir, [org_dir, venue_dir])
    rows = compare_profiles(builtins, data, builtins_dir=builtins_dir)
    rows += compare_profiles(overlays, data, builtins_dir=builtins_dir)
    counts = summarize(rows)

    written: list[PriceRow] = []
    refused: list[PriceRow] = []
    if write:
        written, refused = apply_drift(rows, builtins_dir=builtins_dir)

    if json_output:
        output_json(
            {
                "source": source,
                "snapshot": str(cache),
                "counts": counts,
                "rows": [r.as_dict() for r in rows if show_all or r.status == "drift"],
                "written": [f"{r.profile}:{r.model}" for r in written],
                "refused": [f"{r.profile}:{r.model}" for r in refused],
            }
        )
    else:
        console.print(f"[dim]Prices from {source}[/dim]")
        shown = [r for r in rows if show_all or r.status == "drift"]
        if shown:
            table = Table(title="Model prices vs models.dev (USD per 1K tokens)")
            table.add_column("PROFILE")
            table.add_column("MODEL")
            table.add_column("STATUS")
            table.add_column("FIELD")
            table.add_column("OURS", justify="right")
            table.add_column("MODELS.DEV", justify="right")
            table.add_column("UPDATED")
            for r in shown:
                if r.status != "drift":
                    table.add_row(r.profile, r.model, r.status, "", "", "", r.last_updated or "")
                    continue
                first = True
                for f in PRICE_FIELDS:
                    if f not in r.drifted:
                        continue
                    ours = r.ours.get(f)
                    theirs = r.theirs.get(f)
                    layer = "" if r.builtin else " (user layer)"
                    table.add_row(
                        r.profile if first else "",
                        r.model if first else "",
                        ("drift" + layer) if first else "",
                        f.removeprefix("cost_per_1k_"),
                        "unset" if ours is None else f"{ours:g}",
                        "" if theirs is None else f"{theirs:g}",
                        (r.last_updated or "") if first else "",
                    )
                    first = False
            console.print(table)
        console.print(
            f"{counts['match']} match, {counts['drift']} drift, {counts['absent']} absent from "
            f"models.dev, {counts['unmapped']} unmapped (subscription, local or harness-own ids)"
        )
        if write:
            console.print(f"[green]wrote {len(written)} builtin row(s)[/green]")
            for r in refused:
                console.print(
                    f"[yellow]left alone (not a builtin): {r.profile}:{r.model} "
                    f"in {r.source_path}[/yellow]"
                )
        elif counts["drift"]:
            console.print(
                "[dim]Run with --write to update the builtin rows; "
                "user-layer rows are yours to edit.[/dim]"
            )

    if counts["drift"] and len(written) < counts["drift"]:
        raise typer.Exit(1)