Skip to content

class_policy

class_policy

Machine probe and ordered policy for a generated class map.

Classes

Functions:

parse_class_hint

parse_class_hint(value)

'after opencode' → ('after', 'opencode'); 'first' → ('first', None).

Raises ValueError on any other shape — a profile hint is a seating instruction, not free text.

Source code in src/marianne/instruments/class_policy.py
def parse_class_hint(value: str) -> tuple[str, str | None]:
    """``'after opencode'`` → ``('after', 'opencode')``; ``'first'`` → ``('first', None)``.

    Raises ValueError on any other shape — a profile hint is a seating
    instruction, not free text.
    """
    match = _HINT_RE.match(value.strip())
    if match is None:
        raise ValueError(
            f"class hint {value!r} is not one of: first, last, after <profile>, before <profile>"
        )
    if match.group(2):
        return match.group(1).split()[0], match.group(2)
    return match.group(1), None

probe_builtin_profiles

probe_builtin_profiles(profiles, hinted=None)

Probe effective shipped names and additional profiles with class_hints.

Same-named user/venue overrides supply the actual execution contract for shipped names. Additional user names need a hint: their ranking is a decision the profile's author makes, not the writer (GH #469).

Source code in src/marianne/instruments/class_policy.py
def probe_builtin_profiles(
    profiles: dict[str, InstrumentProfile],
    hinted: dict[str, InstrumentProfile] | None = None,
) -> dict[str, object]:
    """Probe effective shipped names and additional profiles with ``class_hints``.

    Same-named user/venue overrides supply the actual execution contract for
    shipped names. Additional user names need a hint: their ranking is a
    decision the profile's author makes, not the writer (GH #469).
    """
    record: dict[str, object] = {}
    overrides = hinted or {}
    profiles = {name: overrides.get(name, profile) for name, profile in profiles.items()}
    hinted_extras = {
        name: profile for name, profile in overrides.items() if profile.class_hints
    }
    for name, profile in sorted({**profiles, **hinted_extras}.items()):
        # The same probe `classes check` applies later (GH #447): a chain the
        # writer emits is one the checker accepts on the same machine. A local
        # server that answers but does not serve the profile's model is NOT
        # available — the old /api/tags-200 probe wrote `local: [ollama]`
        # that `classes check` then refused.
        record[name] = {
            "kind": profile.kind,
            "available": probe_profile(profile).runnable,
            "execution_status": profile.execution_status,
            "capabilities": sorted(profile.capabilities),
            "zero_cost": bool(profile.models)
            and all(
                model.cost_per_1k_input == 0 and model.cost_per_1k_output == 0
                for model in profile.models
            ),
            "raw_prompt": profile.raw_prompt,
            "class_hints": {
                cls: parse_class_hint(hint) for cls, hint in sorted(profile.class_hints.items())
            } if name in hinted_extras else {},
        }
    return {
        "profiles": record,
        "openrouter_api_key": bool(os.getenv("OPENROUTER_API_KEY")),
        "zai_api_key": bool(os.getenv("ZAI_API_KEY")),
    }

select_class_chains

select_class_chains(probe)

Apply the policy table, preserving priority and a four-entry cap.

Source code in src/marianne/instruments/class_policy.py
def select_class_chains(probe: dict[str, object]) -> dict[str, list[str]]:
    """Apply the policy table, preserving priority and a four-entry cap."""
    profiles = probe["profiles"]
    assert isinstance(profiles, dict)
    selected: dict[str, list[str]] = {}
    for class_name, policy in CLASS_POLICIES.items():
        order = list(policy.order)
        if not probe["openrouter_api_key"] and "crush" in order:
            order.remove("crush")
            order.append("crush")
        order = _seat_hinted(order, class_name, profiles)
        chain: list[str] = []
        for name in order:
            row = profiles.get(name)
            if not isinstance(row, dict):
                continue
            caps = set(row["capabilities"])
            if not row["available"] or row["execution_status"] != "ready":
                continue
            if row["raw_prompt"] and not policy.allow_raw:
                continue
            if policy.requires - caps or (policy.either and not policy.either & caps):
                continue
            if policy.zero_cost and not row["zero_cost"]:
                continue
            chain.append(name)
            if len(chain) == 4:
                break
        if chain:
            selected[class_name] = chain
    return selected

explain_hinted_exclusions

explain_hinted_exclusions(probe)

One line per (hinted profile, class) the policy refused, saying why.

A first-run user who wrote a local http profile with class_hints: {workhorse: first} otherwise sees workhorse: empty and nothing that says an http endpoint has no filesystem (GH #494).

Source code in src/marianne/instruments/class_policy.py
def explain_hinted_exclusions(probe: dict[str, object]) -> list[str]:
    """One line per (hinted profile, class) the policy refused, saying why.

    A first-run user who wrote a local ``http`` profile with
    ``class_hints: {workhorse: first}`` otherwise sees ``workhorse:`` empty
    and nothing that says an http endpoint has no filesystem (GH #494).
    """
    profiles = probe["profiles"]
    assert isinstance(profiles, dict)
    lines: list[str] = []
    for name in sorted(profiles):
        row = profiles[name]
        hints = row.get("class_hints") if isinstance(row, dict) else None
        if not hints:
            continue
        caps = set(row["capabilities"])
        for class_name in sorted(hints):
            policy = CLASS_POLICIES.get(class_name)
            if policy is None:
                if class_name in _CATALOG_GENERATED:
                    lines.append(
                        f"{name}: class '{class_name}' is generated from the instrument catalog "
                        "(model and effort per entry), not seated by hints; see "
                        "`mzt instruments classes tiers`"
                    )
                else:
                    lines.append(f"{name}: class '{class_name}' is not a shipped class")
                continue
            reason: str | None = None
            if not row["available"]:
                reason = "not available on this machine"
            elif row["execution_status"] != "ready":
                reason = f"execution_status is {row['execution_status']}"
            elif row["raw_prompt"] and not policy.allow_raw:
                reason = "raw-prompt instrument; this class needs an agent harness"
            elif policy.requires - caps:
                missing = ", ".join(sorted(policy.requires - caps))
                reason = f"lacks {missing}"
                if row.get("kind") == "http":
                    reason += (
                        " (an http endpoint answers but has no filesystem; route it "
                        "through opencode for file-writing classes)"
                    )
            elif policy.either and not policy.either & caps:
                reason = "needs one of " + ", ".join(sorted(policy.either))
            elif policy.zero_cost and not row["zero_cost"]:
                reason = "not zero-cost"
            if reason:
                lines.append(f"{name}: not seated in '{class_name}': {reason}")
    return lines