Skip to content

conduct

conduct

Conducting commands for Marianne CLI (GH #547): wait, next, verdict.

A conductor today polls mzt status hundreds of times and parses rich tables. These three commands answer the three questions a conductor asks with a closed enum and one small JSON object each, so a small model can hold the loop:

  • mzt wait JOB blocks until the job needs a decision or is finished.
  • mzt next says which job needs attention and what to do about it (--tasks DIR also lists TASK files nobody has started).
  • mzt verdict JOB reads the review sheet's VERDICT line as PASS/REWORK/BLOCKED and adds the findings, the validation counts, the report path and the round (GH #554).

All conductor access goes through :func:_route, so tests replace one function and never touch a real conductor.

Classes

ConductorUnreachable

ConductorUnreachable(cause=None)

Bases: Exception

The conductor did not answer (absent, busy, or protocol failure).

Source code in src/marianne/cli/commands/conduct.py
def __init__(self, cause: Exception | None = None) -> None:
    super().__init__(str(cause) if cause else "conductor not running")
    self.cause = cause

JobNotFound

Bases: Exception

The conductor answered and does not know the job.

Functions:

classify_job

classify_job(state)

Map a job.status payload to (state, outcome, reason).

Returns None while the job is still moving and nobody has to decide.

Source code in src/marianne/cli/commands/conduct.py
def classify_job(state: dict[str, Any]) -> tuple[str, str | None, str] | None:
    """Map a ``job.status`` payload to ``(state, outcome, reason)``.

    Returns ``None`` while the job is still moving and nobody has to decide.
    """
    status = str(state.get("status", "")).lower()
    fermata = _fermata_sheets(state)
    if status == "completed":
        return "done", "completed", "job completed"
    if status == "cancelled":
        return "done", "cancelled", "job was cancelled"
    if status == "failed":
        return "needs_you", "failed", str(state.get("error_message") or "job failed")
    if status == "paused_at_chain":
        return "needs_you", "paused", _CHAIN_REASON
    if status == "paused":
        if fermata:
            return "needs_you", "paused", _fermata_text(fermata)
        return "needs_you", "paused", "job is paused"
    if fermata:
        return "needs_you", "paused", _fermata_text(fermata)
    return None

wait_for_job async

wait_for_job(fetch, job_id, max_seconds, *, clock=monotonic, sleep=sleep)

Poll fetch with backoff until the job needs a decision or ends.

The conductor IPC has no per-job subscription, so the polling lives here (not in the caller). clock and sleep are injectable so tests never sleep. JobNotFound from fetch propagates.

Source code in src/marianne/cli/commands/conduct.py
async def wait_for_job(
    fetch: Callable[[], Awaitable[dict[str, Any]]],
    job_id: str,
    max_seconds: float,
    *,
    clock: Clock = time.monotonic,
    sleep: Sleeper = asyncio.sleep,
) -> dict[str, Any]:
    """Poll ``fetch`` with backoff until the job needs a decision or ends.

    The conductor IPC has no per-job subscription, so the polling lives here
    (not in the caller). ``clock`` and ``sleep`` are injectable so tests never
    sleep. ``JobNotFound`` from ``fetch`` propagates.
    """
    deadline = clock() + max_seconds
    delay = _POLL_START
    failures = 0
    last_status: str | None = None
    while True:
        try:
            state = await fetch()
        except ConductorUnreachable as exc:
            failures += 1
            if failures >= _DOWN_AFTER:
                return _wait_result(
                    "conductor_down", job_id, last_status, None, f"conductor unreachable: {exc}",
                )
        else:
            failures = 0
            last_status = str(state.get("status", "")).lower() or last_status
            verdict = classify_job(state)
            if verdict is not None:
                kind, outcome, reason = verdict
                return _wait_result(kind, job_id, last_status, outcome, reason)
        remaining = deadline - clock()
        if remaining <= 0:
            return _wait_result(
                "wait_expired", job_id, last_status, None,
                f"still {last_status or 'unknown'} after {max_seconds:g}s",
            )
        await sleep(min(delay, remaining))
        delay = min(delay * _POLL_FACTOR, _POLL_CAP)

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)

find_verdict

find_verdict(workspace, pattern=DEFAULT_VERDICT_PATTERN)

Newest artifact in workspace carrying a mappable VERDICT line.

Within that file the last such line wins. No prose interpretation beyond the word mapping; round is None here (mzt verdict fills it from the task file, see :func:task_round).

Source code in src/marianne/cli/commands/conduct.py
def find_verdict(workspace: Path, pattern: str = DEFAULT_VERDICT_PATTERN) -> dict[str, Any]:
    """Newest artifact in ``workspace`` carrying a mappable VERDICT line.

    Within that file the last such line wins. No prose interpretation beyond
    the word mapping; ``round`` is ``None`` here (``mzt verdict`` fills it from
    the task file, see :func:`task_round`).
    """
    return _scan_verdict(workspace, pattern)[0]

extract_findings

extract_findings(text, verdict_index, verdict_word)

The reviewer's findings, verbatim, from the report that carries the verdict.

Rule, first match wins:

  1. a section headed FINDINGS (FINDINGS: or ## Findings): its bullets;
  2. else the sheets' own review labels REQUIRED FIXES then FAILURES;
  3. else, when the verdict is not PASS, the bullet lines after the VERDICT line up to the next heading or label (non-blank lines when it has no bullets).

Bullet markers are stripped, the text is not edited. At most 20 items of 500 characters. A PASS with no FINDINGS section has none.

Source code in src/marianne/cli/commands/conduct.py
def extract_findings(text: str, verdict_index: int, verdict_word: str) -> list[str]:
    """The reviewer's findings, verbatim, from the report that carries the verdict.

    Rule, first match wins:

    1. a section headed ``FINDINGS`` (``FINDINGS:`` or ``## Findings``): its bullets;
    2. else the sheets' own review labels ``REQUIRED FIXES`` then ``FAILURES``;
    3. else, when the verdict is not PASS, the bullet lines after the VERDICT line
       up to the next heading or label (non-blank lines when it has no bullets).

    Bullet markers are stripped, the text is not edited. At most 20 items of
    500 characters. A PASS with no FINDINGS section has none.
    """
    if not text:
        return []
    lines = text.splitlines()
    for names in (_PRIMARY_SECTIONS, _SECONDARY_SECTIONS):
        found = _section_items(lines, names)
        if found:
            return found
    if verdict_word == "PASS" or verdict_index < 0:
        return []
    after: list[str] = []
    for line in lines[verdict_index + 1:]:
        if _SECTION_BREAK.match(line):
            break
        after.append(line)
    return _items_from(after)

accept_counts

accept_counts(state)

{ran, passed} over the validations the job's sheets recorded.

Reads the checkpoint (job.status): each sheet's validation_details (latest attempt), or its passed_validations/failed_validations name lists when the details were not kept. {0, 0} means no validation result is available, not that all passed.

Source code in src/marianne/cli/commands/conduct.py
def accept_counts(state: dict[str, Any] | None) -> dict[str, int]:
    """``{ran, passed}`` over the validations the job's sheets recorded.

    Reads the checkpoint (``job.status``): each sheet's ``validation_details``
    (latest attempt), or its ``passed_validations``/``failed_validations`` name
    lists when the details were not kept. ``{0, 0}`` means no validation result
    is available, not that all passed.
    """
    ran = passed = 0
    for sheet in ((state or {}).get("sheets") or {}).values():
        if not isinstance(sheet, dict):
            continue
        details = sheet.get("validation_details")
        if isinstance(details, list) and details:
            rows = [d for d in details if isinstance(d, dict)]
            ran += len(rows)
            passed += sum(1 for d in rows if d.get("passed"))
        else:
            ok = sheet.get("passed_validations") or []
            bad = sheet.get("failed_validations") or []
            ran += len(ok) + len(bad)
            passed += len(ok)
    return {"ran": ran, "passed": passed}

parse_task_fields

parse_task_fields(text)

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

Same grammar as mzt agents run: a field is NAME: value (list, quote and heading marks tolerated); following lines up to the next field line continue the value.

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

    Same grammar as ``mzt agents run``: a field is ``NAME: value`` (list, quote
    and heading marks tolerated); following lines up to the next field line
    continue the value.
    """
    fields: dict[str, str] = {}
    current: str | None = None
    for line in text.splitlines():
        match = _TASK_FIELD_START.match(line)
        if match:
            name = str(match.group(1))
            if name in fields:
                current = None
                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

find_task_file

find_task_file(workspace, config_path)

The task file mzt agents run copied for this job, or None.

agents run binds the engagement in a run dir (the bound score and the read-only copy task-<source name>) and, by default, uses that same directory as the workspace. Looked for beside the bound score first (config_path; its marianne_agent.task.copy names the copy), then in the workspace as task-* carrying the card's REPORT field.

Source code in src/marianne/cli/commands/conduct.py
def find_task_file(workspace: Path, config_path: str | None) -> Path | None:
    """The task file ``mzt agents run`` copied for this job, or None.

    ``agents run`` binds the engagement in a run dir (the bound score and the
    read-only copy ``task-<source name>``) and, by default, uses that same
    directory as the workspace. Looked for beside the bound score first
    (``config_path``; its ``marianne_agent.task.copy`` names the copy), then in
    the workspace as ``task-*`` carrying the card's REPORT field.
    """
    dirs: list[Path] = []
    score = Path(config_path) if config_path else None
    if score is not None:
        dirs.append(score.parent)
    if workspace not in dirs:
        dirs.append(workspace)
    if score is not None:
        copy = _bound_task_copy_name(score)
        if copy and (score.parent / copy).is_file():
            return score.parent / copy
    for directory in dirs:
        try:
            matches = sorted(
                (p for p in directory.glob("task-*") if p.is_file()),
                key=lambda p: p.stat().st_mtime,
                reverse=True,
            )
        except OSError:
            continue
        for path in matches:
            try:
                text = path.read_text(encoding="utf-8", errors="replace")
            except OSError:
                continue
            if "REPORT" in parse_task_fields(text):
                return path
    return None

task_extras

task_extras(task_path, workspace)

(round, result_path) from the task file; (None, None) without one.

round is 2 when the task carries a FINDINGS: line (the rework task), else 1. result_path is the REPORT field's file name resolved in the workspace, the path mzt agents run printed.

Source code in src/marianne/cli/commands/conduct.py
def task_extras(task_path: Path | None, workspace: Path) -> tuple[int | None, str | None]:
    """``(round, result_path)`` from the task file; ``(None, None)`` without one.

    ``round`` is 2 when the task carries a ``FINDINGS:`` line (the rework
    task), else 1. ``result_path`` is the REPORT field's file name resolved in
    the workspace, the path ``mzt agents run`` printed.
    """
    if task_path is None:
        return None, None
    try:
        fields = parse_task_fields(task_path.read_text(encoding="utf-8", errors="replace"))
    except OSError:
        return None, None
    report = Path(fields.get("REPORT", "")).name
    return (2 if "FINDINGS" in fields else 1), str(workspace / (report or "REPORT.md"))

build_verdict

build_verdict(workspace, pattern, state, config_path=None)

The full mzt verdict object: the four #547 keys plus the #554 extras.

Source code in src/marianne/cli/commands/conduct.py
def build_verdict(
    workspace: Path,
    pattern: str,
    state: dict[str, Any] | None,
    config_path: str | None = None,
) -> dict[str, Any]:
    """The full ``mzt verdict`` object: the four #547 keys plus the #554 extras."""
    result, text, index = _scan_verdict(workspace, pattern)
    round_no, result_path = task_extras(find_task_file(workspace, config_path), workspace)
    result["round"] = round_no
    result["findings"] = extract_findings(text, index, result["verdict"])
    result["accept"] = accept_counts(state)
    result["result_path"] = result_path
    return result

is_judged

is_judged(workspace, job_id, submitted_at)

Whether mzt verdict --accept was recorded for this run of the job.

Keyed on submitted_at so a fresh run under a reused job id is not mistaken for the run that was judged.

Source code in src/marianne/cli/commands/conduct.py
def is_judged(workspace: str | None, job_id: str, submitted_at: float | None) -> bool:
    """Whether ``mzt verdict --accept`` was recorded for this run of the job.

    Keyed on ``submitted_at`` so a fresh run under a reused job id is not
    mistaken for the run that was judged.
    """
    if not workspace:
        return False
    entry = _read_markers(Path(workspace)).get(job_id)
    if not isinstance(entry, dict):
        return False
    return entry.get("submitted_at") == submitted_at

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}")

task_hash8

task_hash8(path)

The 8 hex digits mzt agents run puts in the job id for this task file.

Source code in src/marianne/cli/commands/conduct.py
def task_hash8(path: Path) -> str:
    """The 8 hex digits ``mzt agents run`` puts in the job id for this task file."""
    return hashlib.sha256(path.read_bytes()).hexdigest()[:8]

unbound_tasks

unbound_tasks(tasks_dir, job_ids)

CAST entries for TASK*.md files in tasks_dir that no job is bound to.

Bound means some job id (any age, any status) contains -task-<hex8>- with the file's hash, so editing a task (a rework adds FINDINGS:) makes it new again. Only the hash is compared, not the agent name or the date. Unreadable files are skipped. Sorted by file name.

Source code in src/marianne/cli/commands/conduct.py
def unbound_tasks(tasks_dir: Path, job_ids: list[str]) -> list[dict[str, Any]]:
    """CAST entries for ``TASK*.md`` files in ``tasks_dir`` that no job is bound to.

    Bound means some job id (any age, any status) contains ``-task-<hex8>-`` with
    the file's hash, so editing a task (a rework adds ``FINDINGS:``) makes it new
    again. Only the hash is compared, not the agent name or the date. Unreadable
    files are skipped. Sorted by file name.
    """
    bound = {m.group(1) for job_id in job_ids for m in _TASK_JOB_PART.finditer(job_id)}
    base = tasks_dir.expanduser()
    out: list[dict[str, Any]] = []
    try:
        files = sorted(p for p in base.glob(_TASK_GLOB) if p.is_file())
    except OSError:
        return out
    for path in files:
        try:
            digest = task_hash8(path)
        except OSError:
            continue
        if digest in bound:
            continue
        absolute = os.path.abspath(path)
        out.append({
            "job_id": None,
            "action": "CAST",
            "why": f"{path.name} has no agent yet",
            "task": absolute,
        })
    return out

compute_next async

compute_next(*, mine, since_hours, idle_seconds, route=None, now=None, tasks_dir=None)

The ordered attention queue: [{job_id, action, why}].

With tasks_dir, unbound TASK*.md files there add CAST rows that also carry task (the file's absolute path).

Source code in src/marianne/cli/commands/conduct.py
async def compute_next(
    *,
    mine: str | None,
    since_hours: float,
    idle_seconds: float | None,
    route: Callable[[str, dict[str, Any]], Awaitable[Any]] | None = None,
    now: float | None = None,
    tasks_dir: Path | None = None,
) -> list[dict[str, Any]]:
    """The ordered attention queue: ``[{job_id, action, why}]``.

    With ``tasks_dir``, unbound ``TASK*.md`` files there add ``CAST`` rows that
    also carry ``task`` (the file's absolute path).
    """
    call = route or _route
    clock_now = time.time() if now is None else now
    rows = await call("job.list", {})
    cast_rows: list[dict[str, Any]] = []
    if tasks_dir is not None:
        known = [
            str(r.get("job_id", ""))
            for r in (rows if isinstance(rows, list) else [])
            if isinstance(r, dict)
        ]
        cast_rows = unbound_tasks(tasks_dir, known)
    ranked: list[tuple[int, float, dict[str, Any]]] = []
    for row in rows if isinstance(rows, list) else []:
        if not isinstance(row, dict):
            continue
        job_id = str(row.get("job_id", ""))
        status = str(row.get("status", "")).lower()
        if not job_id or status == "scheduled":
            continue
        if mine and not job_id.startswith(mine):
            continue
        if _is_test_artifact(row):
            continue
        terminal = status in ("completed", "failed", "cancelled")
        if terminal and since_hours > 0:
            end = _job_end(row)
            if end is not None and clock_now - end > since_hours * 3600:
                continue

        if status == "completed":
            if is_judged(row.get("workspace"), job_id, row.get("submitted_at")):
                action, why = "DONE", "completed and judged"
            else:
                action, why = "JUDGE", "completed; run `mzt verdict` then `mzt verdict --accept`"
        elif status == "failed":
            action, why = "ESCALATE", str(row.get("error_message") or "job failed")
        elif status == "cancelled":
            action, why = "ESCALATE", "job was cancelled"
        elif status == "paused_at_chain":
            action, why = "ESCALATE", _CHAIN_REASON
        elif status == "paused":
            fermata = _fermata_sheets(await _safe_status(call, job_id) or {})
            action = "ESCALATE"
            why = _fermata_text(fermata) if fermata else "job is paused"
        elif status in ("running", "queued", "pending"):
            if status == "running":
                action, why = _running_row(
                    await _safe_status(call, job_id), clock_now, idle_seconds,
                )
            else:
                action, why = "WAIT", status
        else:
            continue
        ranked.append((
            _ACTION_ORDER.index(action),
            float(row.get("submitted_at") or 0.0),
            {"job_id": job_id, "action": action, "why": why},
        ))
    for row_ in cast_rows:
        ranked.append((_ACTION_ORDER.index("CAST"), 0.0, row_))
    ranked.sort(key=lambda item: (item[0], item[1]))
    queue = [item[2] for item in ranked]
    if not queue:
        queue = [{"job_id": None, "action": "DONE", "why": "no jobs need attention"}]
    return queue

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}")