Skip to content

agents_cmd

agents_cmd

mzt agents list and mzt agents run (SC1c, interim).

A small model conducting persistent agents needs two commands and a closed vocabulary: who can I cast, and start this task with that person. Both print one JSON object (or array) with --json, no ANSI, and run exits 0 on ok and 1 otherwise. The shapes are the ones the SC1 conductor card was qualified against.

list [{name, role, owns, free, open_debt, last_outcome}] run {ok, job_id, workspace, result_path} or {ok: false, code, hint}

INTERIM. run always engages the targeted-work shape with --defer-lifecycle (consolidate, reflect, maturity and resurrect become pending lifecycle debt; engage already refuses at 3 pending debts). It is replaced when the one-episode score (P2c) exists. Nothing here edits an agent: the agents directory is read, and every write lands in the runs directory.

The engage path is the compiler's bind_engagement called in process; the submit is the same value-returning function mzt run uses (:func:run.submit_score), not a subprocess and not scraped printed text. All conductor access goes through conduct._route and the submit through :func:_submit_score, so tests replace those two seams.

Classes

SubmitOutcome dataclass

SubmitOutcome(ok, job_id=None, hint='', job_exists=False)

What the conductor did with a bound score.

Functions:

parse_task

parse_task(text)

Field name -> value for the card's TASK.md (first occurrence of each).

A field is a line NAME: value; leading list/quote/heading marks are tolerated. Lines after it, up to the next field line, continue the value. Only the six fields and FINDINGS are recognised.

Source code in src/marianne/cli/commands/agents_cmd.py
def parse_task(text: str) -> dict[str, str]:
    """Field name -> value for the card's TASK.md (first occurrence of each).

    A field is a line ``NAME: value``; leading list/quote/heading marks are
    tolerated. Lines after it, up to the next field line, continue the value.
    Only the six fields and FINDINGS are recognised.
    """
    names = "|".join(_FIELD_NAMES)
    start = re.compile(rf"^[ \t>*#-]*({names})[ \t]*:[ \t]*(.*)$")
    fields: dict[str, str] = {}
    current: str | None = None
    for line in text.splitlines():
        match = start.match(line)
        if match:
            name: str = str(match.group(1))
            if name in fields:
                current = None  # a repeated field never overwrites the first
                continue
            current = name
            fields[name] = str(match.group(2)).strip()
        elif current is not None and line.strip():
            fields[current] = (fields[current] + " " + line.strip()).strip()
    return fields

task_problems

task_problems(fields)

A hint naming missing/empty fields, or None when all six are present.

Source code in src/marianne/cli/commands/agents_cmd.py
def task_problems(fields: dict[str, str]) -> str | None:
    """A hint naming missing/empty fields, or None when all six are present."""
    missing = [f for f in TASK_FIELDS if f not in fields]
    empty = [f for f in TASK_FIELDS if f in fields and not fields[f]]
    if not missing and not empty:
        return None
    parts = []
    if missing:
        parts.append("missing: " + " ".join(missing))
    if empty:
        parts.append(
            "empty: "
            + " ".join(empty)
            + (" (ACCEPT must name a check)" if "ACCEPT" in empty else "")
        )
    return "; ".join(parts)

rank_score

rank_score(task_goal, task_files, entry)

Deterministic overlap score of a task against one agent.

score = |task words & agent words| + 3 * (owned paths that prefix a FILES path) where task words come from GOAL and FILES, and agent words from role, group, focus, owns and the static role-hint table. Words are lowercase alphanumerics of 3+ characters minus a small stoplist. No stemming, no synonyms beyond the role-hint table, no model.

Source code in src/marianne/cli/commands/agents_cmd.py
def rank_score(task_goal: str, task_files: str, entry: dict[str, Any]) -> int:
    """Deterministic overlap score of a task against one agent.

    ``score = |task words & agent words| + 3 * (owned paths that prefix a FILES path)``
    where task words come from GOAL and FILES, and agent words from role, group,
    focus, ``owns`` and the static role-hint table. Words are lowercase
    alphanumerics of 3+ characters minus a small stoplist. No stemming, no
    synonyms beyond the role-hint table, no model.
    """
    task_words = _words(task_goal) | _words(task_files)
    role = str(entry["role"]).lower()
    agent_words = _words(" ".join([role, entry["_group"], entry["_focus"], *entry["owns"]]))
    for key, hints in _ROLE_HINTS.items():
        if key in role:
            agent_words |= set(hints)
    score = len(task_words & agent_words)
    files = [f.strip().strip("`'\",;") for f in re.split(r"[\s,;]+", task_files) if f.strip()]
    for owned in entry["owns"]:
        owned = owned.strip()
        if owned and any(f.startswith(owned) for f in files):
            score += 3
    return score

reserved_names

reserved_names(path=None)

{agent: reason} from the reservations file; empty when it is absent.

A conductor seat that has queued work for a person writes reserved: {NAME: "why, until when"} there (env MZT_AGENTS_RESERVATIONS, default ~/.marianne/agents-reserved.yaml). A reserved agent counts as busy for agents list --free and is refused by agents run with AGENT_BUSY, so a second seat cannot add a writer or a debt to a person the first seat is carrying. An unreadable file reserves nobody and says so on stderr.

Source code in src/marianne/cli/commands/agents_cmd.py
def reserved_names(path: Path | None = None) -> dict[str, str]:
    """``{agent: reason}`` from the reservations file; empty when it is absent.

    A conductor seat that has queued work for a person writes
    ``reserved: {NAME: "why, until when"}`` there (env ``MZT_AGENTS_RESERVATIONS``,
    default ``~/.marianne/agents-reserved.yaml``). A reserved agent counts as
    busy for ``agents list --free`` and is refused by ``agents run`` with
    ``AGENT_BUSY``, so a second seat cannot add a writer or a debt to a person
    the first seat is carrying. An unreadable file reserves nobody and says so
    on stderr.
    """
    target = path or Path(os.environ.get(ENV_RESERVATIONS) or DEFAULT_RESERVATIONS).expanduser()
    if not target.is_file():
        return {}
    try:
        data = yaml.safe_load(target.read_text(encoding="utf-8")) or {}
    except (OSError, UnicodeError, yaml.YAMLError) as exc:
        typer.echo(f"warning: reservations file {target} unreadable: {exc}", err=True)
        return {}
    entries = data.get("reserved") if isinstance(data, dict) else None
    if not isinstance(entries, dict):
        return {}
    return {str(k).strip().lower(): str(v or "") for k, v in entries.items() if str(k).strip()}

load_agents

load_agents(agents_dir)

Engageable agents: (entries, warnings), sorted by name.

An agent is listed when its directory holds profile.yaml and an installed scores/targeted-work.yaml. Read-only. owns is the profile's owns list when it has one (today's profiles do not).

Source code in src/marianne/cli/commands/agents_cmd.py
def load_agents(agents_dir: Path) -> tuple[list[dict[str, Any]], list[str]]:
    """Engageable agents: ``(entries, warnings)``, sorted by name.

    An agent is listed when its directory holds ``profile.yaml`` and an
    installed ``scores/targeted-work.yaml``. Read-only. ``owns`` is the
    profile's ``owns`` list when it has one (today's profiles do not).
    """
    loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
    entries: list[dict[str, Any]] = []
    warnings: list[str] = []
    try:
        dirs = sorted(p for p in agents_dir.iterdir() if p.is_dir())
    except OSError as exc:
        return [], [f"cannot read agents dir {agents_dir}: {exc}"]
    for path in dirs:
        profile_path = path / "profile.yaml"
        if not profile_path.is_file() or not (path / "scores" / f"{_SHAPE}.yaml").is_file():
            continue
        try:
            profile = yaml.load(profile_path.read_text(encoding="utf-8"), Loader=loader)  # noqa: S506 - safe loader
        except (OSError, yaml.YAMLError) as exc:
            warnings.append(f"skipped {path.name}: unreadable profile.yaml ({str(exc)[:80]})")
            continue
        if not isinstance(profile, dict):
            warnings.append(f"skipped {path.name}: profile.yaml is not a mapping")
            continue
        entries.append(
            {
                "name": path.name,
                "role": str(profile.get("role") or ""),
                "owns": _as_list(profile.get("owns")),
                "_focus": str(profile.get("focus") or ""),
                "_group": str(profile.get("group") or ""),
            }
        )
    return entries, warnings

build_list

build_list(agents_dir, runs_dir, *, busy, pending_debt, for_task=None, free_only=False)

The agents list payload (pure apart from reads).

Source code in src/marianne/cli/commands/agents_cmd.py
def build_list(
    agents_dir: Path,
    runs_dir: Path,
    *,
    busy: set[str],
    pending_debt: Callable[[Path, str], tuple[int, str]],
    for_task: tuple[str, str] | None = None,
    free_only: bool = False,
) -> tuple[list[dict[str, Any]], list[str]]:
    """The ``agents list`` payload (pure apart from reads)."""
    entries, warnings = load_agents(agents_dir)
    rows: list[tuple[int, int, str, dict[str, Any]]] = []
    for entry in entries:
        name = entry["name"]
        free = name not in busy
        if free_only and not free:
            continue
        debt = pending_debt(agents_dir, name)[0]
        score = rank_score(for_task[0], for_task[1], entry) if for_task else 0
        rows.append(
            (
                -score,
                debt,
                name,
                {
                    "name": name,
                    "role": entry["role"],
                    "owns": entry["owns"],
                    "free": free,
                    "open_debt": debt,
                    "last_outcome": _last_outcome(runs_dir, name),
                },
            )
        )
    rows.sort(key=lambda r: r[:3])
    return [r[3] for r in rows], warnings

agents_list

agents_list(for_task=Option(None, '--for', help="Rank by overlap of this TASK.md's GOAL and FILES words with each agent's role, group, focus and owns (deterministic; see docs). Without it the order is by name."), free=Option(False, '--free', help=f'Only agents with no running, queued, pending or paused conductor job whose id contains -NAME-, and not reserved in {DEFAULT_RESERVATIONS} (env {ENV_RESERVATIONS})'), agents_dir=Option(None, '--agents-dir', help=f'Agents root (env {ENV_AGENTS_DIR}; default {DEFAULT_AGENTS_DIR})'), runs_dir=Option(None, '--runs-dir', help=f'Where `agents run` writes (env {ENV_RUNS_DIR}; default {DEFAULT_RUNS_DIR}); read here for last_outcome'), json_output=Option(False, '--json', '-j', help='One JSON array (no ANSI)'))

List the agents you can cast: [{name, role, owns, free, open_debt, last_outcome}].

An agent appears when it has an installed targeted-work score. free is false while the conductor holds a running, queued, pending or paused job whose id contains -NAME-. open_debt is the pending-lifecycle-debt count that marianne-agents engage refuses on at 3. last_outcome is "PASS 2026-11-12" from the agent's newest run under the runs dir, or null. Read-only.

Examples:

mzt agents list --json mzt agents list --for TASK.md --free --json

Source code in src/marianne/cli/commands/agents_cmd.py
@agents_app.command("list")
def agents_list(
    for_task: Path | None = typer.Option(
        None,
        "--for",
        help="Rank by overlap of this TASK.md's GOAL and FILES words with "
        "each agent's role, group, focus and owns (deterministic; see docs). Without it "
        "the order is by name.",
    ),
    free: bool = typer.Option(
        False,
        "--free",
        help="Only agents with no running, queued, pending or paused "
        "conductor job whose id contains -NAME-, and not reserved in "
        f"{DEFAULT_RESERVATIONS} (env {ENV_RESERVATIONS})",
    ),
    agents_dir: Path | None = typer.Option(
        None,
        "--agents-dir",
        help=f"Agents root (env {ENV_AGENTS_DIR}; default {DEFAULT_AGENTS_DIR})",
    ),
    runs_dir: Path | None = typer.Option(
        None,
        "--runs-dir",
        help=f"Where `agents run` writes (env {ENV_RUNS_DIR}; "
        f"default {DEFAULT_RUNS_DIR}); read here for last_outcome",
    ),
    json_output: bool = typer.Option(False, "--json", "-j", help="One JSON array (no ANSI)"),
) -> None:
    """List the agents you can cast: ``[{name, role, owns, free, open_debt, last_outcome}]``.

    An agent appears when it has an installed targeted-work score. ``free`` is
    false while the conductor holds a running, queued, pending or paused job
    whose id contains ``-NAME-``. ``open_debt`` is the pending-lifecycle-debt
    count that ``marianne-agents engage`` refuses on at 3. ``last_outcome`` is
    ``"PASS 2026-11-12"`` from the agent's newest run under the runs dir, or
    null. Read-only.

    Examples:
        mzt agents list --json
        mzt agents list --for TASK.md --free --json
    """
    agent_cli = _require_compiler(json_output=json_output)
    task_words: tuple[str, str] | None = None
    if for_task is not None:
        try:
            fields = parse_task(for_task.expanduser().read_text(encoding="utf-8"))
        except OSError as exc:
            raise _refuse(
                "TASK_FIELD_MISSING",
                f"cannot read task file {for_task}: {exc}",
                json_output=json_output,
            ) from None
        if "GOAL" not in fields and "FILES" not in fields:
            raise _refuse(
                "TASK_FIELD_MISSING",
                "missing: GOAL FILES (nothing to rank by)",
                json_output=json_output,
            )
        task_words = (fields.get("GOAL", ""), fields.get("FILES", ""))
    resolved = _agents_dir(agents_dir)
    entries, _ = load_agents(resolved)
    try:
        busy = asyncio.run(_busy_names([e["name"] for e in entries]))
    except conduct.ConductorUnreachable as exc:
        raise _refuse(
            "CONDUCTOR_DOWN", f"the conductor did not answer: {exc}", json_output=json_output
        ) from None
    rows, warnings = build_list(
        resolved,
        _runs_dir(runs_dir),
        busy=busy,
        pending_debt=agent_cli.pending_debt,
        for_task=task_words,
        free_only=free,
    )
    for warning in warnings:
        typer.echo(f"warning: {warning}", err=True)
    if json_output:
        output_json(rows)
        return
    for row in rows:
        typer.echo(
            f"{row['name']}  {row['role']}  {'free' if row['free'] else 'busy'}  "
            f"debt={row['open_debt']}  last={row['last_outcome'] or '-'}"
        )

agents_run

agents_run(name=Argument(..., help='Agent name from `mzt agents list`'), task=Option(..., '--task', '-t', help='TASK.md with GOAL FILES KIND ACCEPT DO_NOT_TOUCH REPORT'), phase_class=Option([], '--class', help='PHASE=CLASS, repeatable (passed through to engage --class)'), inventory=Option(None, '--inventory', '-i', help=f'Live-verified capability inventory YAML (env {ENV_INVENTORY}; no default: refused when neither is set)'), runs_dir=Option(None, '--runs-dir', '-r', help=f'Receives one directory per run (env {ENV_RUNS_DIR}; default {DEFAULT_RUNS_DIR})'), agents_dir=Option(None, '--agents-dir', help=f'Agents root, read only (env {ENV_AGENTS_DIR}; default {DEFAULT_AGENTS_DIR})'), json_output=Option(False, '--json', '-j', help='One JSON object (no ANSI)'))

Start one agent on a task.

Prints {ok, job_id, workspace, result_path} or {ok: false, code, hint}.

INTERIM: engages the targeted-work shape with --defer-lifecycle (lifecycle becomes pending debt; refused at 3) until the one-episode score replaces it. Binds in process with the compiler's engage path (the task is copied read-only and injected into every sheet), then submits with the same function as mzt run, with escalation on. Exit 0 when ok, 1 otherwise. Codes: TASK_FIELD_MISSING, AGENT_BUSY, AGENT_UNKNOWN, DEBT_REFUSED, SUBMIT_REFUSED. Writes only under the runs dir.

Examples:

mzt agents run forge --task TASK.md --json mzt agents run forge --task TASK.md --class work=strong --json

Source code in src/marianne/cli/commands/agents_cmd.py
@agents_app.command("run")
def agents_run(
    name: str = typer.Argument(..., help="Agent name from `mzt agents list`"),
    task: Path = typer.Option(
        ..., "--task", "-t", help="TASK.md with GOAL FILES KIND ACCEPT DO_NOT_TOUCH REPORT"
    ),
    phase_class: list[str] = typer.Option(
        [],
        "--class",
        help="PHASE=CLASS, repeatable (passed through to engage --class)",
    ),
    inventory: Path | None = typer.Option(
        None,
        "--inventory",
        "-i",
        help=f"Live-verified capability inventory YAML (env {ENV_INVENTORY}; "
        "no default: refused when neither is set)",
    ),
    runs_dir: Path | None = typer.Option(
        None,
        "--runs-dir",
        "-r",
        help=f"Receives one directory per run (env {ENV_RUNS_DIR}; default {DEFAULT_RUNS_DIR})",
    ),
    agents_dir: Path | None = typer.Option(
        None,
        "--agents-dir",
        help=f"Agents root, read only (env {ENV_AGENTS_DIR}; default {DEFAULT_AGENTS_DIR})",
    ),
    json_output: bool = typer.Option(False, "--json", "-j", help="One JSON object (no ANSI)"),
) -> None:
    """Start one agent on a task.

    Prints ``{ok, job_id, workspace, result_path}`` or ``{ok: false, code, hint}``.

    INTERIM: engages the targeted-work shape with --defer-lifecycle (lifecycle
    becomes pending debt; refused at 3) until the one-episode score replaces it.
    Binds in process with the compiler's engage path (the task is copied
    read-only and injected into every sheet), then submits with the same
    function as `mzt run`, with escalation on. Exit 0 when ok, 1 otherwise.
    Codes: TASK_FIELD_MISSING, AGENT_BUSY, AGENT_UNKNOWN, DEBT_REFUSED,
    SUBMIT_REFUSED. Writes only under the runs dir.

    Examples:
        mzt agents run forge --task TASK.md --json
        mzt agents run forge --task TASK.md --class work=strong --json
    """
    _run(
        name,
        task,
        phase_class,
        inventory,
        runs_dir,
        agents_dir,
        json_output,
        submit=_submit_score,
    )