diff --git a/dokimi/changelog.d/20261205_120000_napetrov_cli-json-paid-2.md b/dokimi/changelog.d/20261205_120000_napetrov_cli-json-paid-2.md new file mode 100644 index 000000000..142cc26c2 --- /dev/null +++ b/dokimi/changelog.d/20261205_120000_napetrov_cli-json-paid-2.md @@ -0,0 +1,20 @@ + + +### Added + +- **`--json` on five more paid leaves: `skill novelty analyze`, `catalog routing`, `skill sensitivity`, + `eval questions analyze` and `eval questions review`.** Each prints one `cli_output.v1` document: the + estimate under `--dry-run` (the two `eval questions` leaves also refuse under `--max-usd` before the first + call: `budget_stopped`, exit 3), the saved result on + success, and, after a stop, the result it kept (`budget_stopped` at exit 3, `partial` at exit 1). Where a + run keeps no result (`eval questions analyze` writes its report only at the end, so a cap reached mid-run + leaves none) the stop is a `failed` document that carries the cost. An input error names the leaf's + `--help` as its `next` step. The other leaves keep their human output. Part of #94. + +### Fixed + +- **`tools preference`: a refused `--out` or `--items-out` path after the model calls exits 2 with its + `next` step.** The document had an empty `next`; it now names the leaf's `--help`. diff --git a/dokimi/docs/reference/cli-interface.json b/dokimi/docs/reference/cli-interface.json index 7f35347ea..12c25904b 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -481,6 +481,7 @@ {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--include-disabled", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--include-invalid", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--keep-copies-under", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--max-calls", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, {"key": "--max-output-tokens", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, @@ -1035,6 +1036,7 @@ {"key": "--concurrency", "action": "_StoreAction", "choices": null, "const": null, "default": 5, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "int"}, {"key": "--dry-run", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--max-usd", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_usd#3f7e5c8902a3"}, {"key": "--model", "action": "ProviderModelAction", "choices": null, "const": null, "default": "gpt-6.1-sol", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--out", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, @@ -1092,6 +1094,7 @@ {"key": "--concurrency", "action": "_StoreAction", "choices": null, "const": null, "default": 6, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, {"key": "--dry-run", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--limit", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, {"key": "--max-usd", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_usd#3f7e5c8902a3"}, {"key": "--model", "action": "ProviderModelAction", "choices": null, "const": null, "default": "gpt-6.1-sol", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, @@ -1946,6 +1949,7 @@ {"key": "--format", "action": "_StoreAction", "choices": ["'html'", "'md'"], "const": null, "default": "html", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--include-resources", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--judge", "action": "_AppendAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--judge-aggregate", "action": "_StoreAction", "choices": ["'majority'", "'median'", "'unanimous'"], "const": null, "default": "median", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--judge-model", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, @@ -2133,6 +2137,7 @@ {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--include-disabled", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--include-invalid", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--keep-copies-under", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--max-calls", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, {"key": "--max-output-tokens", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, diff --git a/dokimi/dokimi/cli.py b/dokimi/dokimi/cli.py index 85961e04e..e60035cef 100755 --- a/dokimi/dokimi/cli.py +++ b/dokimi/dokimi/cli.py @@ -452,6 +452,9 @@ def _document_on_exit(args: argparse.Namespace, code: int) -> None: if code in (2, 5): doc = cli_output.error_document(kind, "input" if code == 2 else "infra", "see stderr", run_id=cli_output.current_run_id(), reason=reason) + help_argv = getattr(args, "_leaf_help_argv", None) + if code == 2 and help_argv and getattr(args, "input_help_next", False): # a refused path exits 2 (#94 F2) + doc["next"] = [cli_output.free_step(help_argv, "Show the accepted syntax of this command.")] else: doc = cli_output.envelope(kind, run_id=cli_output.current_run_id(), status="failed", reason=reason) cli_output.emit(doc) @@ -482,7 +485,7 @@ def main() -> None: except Exception as exc: # noqa: BLE001 - printed with its traceback, exit 5 # A crash is an infra failure, exit 5 for every command (§2.6): it never reads as a failed verdict. traceback.print_exc() - if _emits_cli_output(args): # a --json leaf still prints its one document on a crash + if _emits_cli_output(args) and not cli_output.printed(): # a leaf that printed its document keeps it _exit_with_document(args, "infra", f"{type(exc).__name__}: {exc}") sys.exit(EXIT_INFRA) except SystemExit as exc: # every exit code of a --json leaf carries its document (§2.7) diff --git a/dokimi/dokimi/cli_output.py b/dokimi/dokimi/cli_output.py index ab3e23e63..6b4120126 100644 --- a/dokimi/dokimi/cli_output.py +++ b/dokimi/dokimi/cli_output.py @@ -98,6 +98,55 @@ def emit_estimate(kind: str, data: Any, *, cap_usd: float | None, limits=[{"code": limit_code, "text": refusal}]) +def limit_code_of(data: Any) -> str: + """The ``limits`` code of a budget stop: ``max_calls`` when the run's partial block says --max-calls stopped it.""" + block = data.get("partial") if isinstance(data, dict) else None + reason = block.get("reason") if isinstance(block, dict) else None + return "max_calls" if reason == "call_cap" else "max_usd" + + +def stop_document(kind: str, data: Any, stop: SystemExit, *, limit_code: str = "max_usd", + reason: str | None = None, **fields: Any) -> dict[str, Any]: + """The document of a run that stopped with ``stop`` (#94 F2, X1). + + Exit 3 is a budget stop: status ``budget_stopped``, the message under ``limits``. Any other exit is ``partial`` + when the run kept a result (``data`` is not None) and ``failed`` when it kept none. ``reason`` overrides the + message, which otherwise is the stop's own text; an int-coded ``SystemExit(3)`` has no text of its own. The + caller prints this, then re-raises ``stop`` to keep its exit code. + """ + from dokimi.exit_codes import EXIT_INCONCLUSIVE + + text = str(stop) + if not text or text == str(stop.code): + text = f"the run stopped (exit {stop.code})" + message = reason or text + budget = stop.code == EXIT_INCONCLUSIVE + limits = [{"code": limit_code, "text": message}] if budget else [] + status = "budget_stopped" if budget else ("partial" if data is not None else "failed") + return envelope(kind, run_id=current_run_id(), status=status, reason=message, data=data, limits=limits, **fields) + + +def write_failure_document(kind: str, exc: BaseException, cost: dict[str, Any], *, help_argv: list[str] | None = None, + subjects: list[dict[str, Any]] | None = None, + artifacts: dict[str, Any] | None = None) -> dict[str, Any]: + """The document of a run that made its paid calls and then failed to write its output (#94 F2): the cost of the + calls is kept. An input refusal is exit 2 and names the leaf's help step; any other failure is ``failed``. The + caller prints this, then re-raises ``exc`` (cli.py then sees a printed document and keeps the exit code).""" + from dokimi.files import InputError + + reason = f"the run made its calls, then it failed: {str(exc) or type(exc).__name__}" + if isinstance(exc, InputError): + doc = error_document(kind, "input", str(exc) or type(exc).__name__, run_id=current_run_id(), reason=reason, + cost=cost) + if help_argv: + doc["next"] = [free_step(help_argv, "Show the accepted syntax of this command.")] + return doc + # the exit is 5 (infra) and the error says so, as the crash document does + return envelope(kind, run_id=current_run_id(), status="failed", reason=reason, subjects=subjects, + artifacts=artifacts, cost=cost, + error=error_object("infra", str(exc) or type(exc).__name__)) + + def free_step(argv: list[str], why: str) -> dict[str, Any]: """One ``next`` entry for a command that costs nothing to run: ``spends`` false, ``est_usd`` 0 (#941).""" return {"argv": argv, "why": why, "spends": False, "est_usd": 0, "kind": "sequence"} diff --git a/dokimi/dokimi/commands/novelty.py b/dokimi/dokimi/commands/novelty.py index d29e2cfd7..46e7bc902 100644 --- a/dokimi/dokimi/commands/novelty.py +++ b/dokimi/dokimi/commands/novelty.py @@ -15,6 +15,7 @@ import json import sys from pathlib import Path +from typing import Any from dokimi.commands.inputs import placebo_text_for_arms_or_exit from dokimi.commands.novelty_run import (attach_panel, exit_if_analyze_partial, @@ -25,6 +26,76 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: + """`skill novelty analyze`, and with --json its cli_output.v1 document (the human output then goes to stderr).""" + if not getattr(args, "json", False): + _novelty_analyze(args, {}) + return + from dokimi import cli_output + from dokimi.novelty.client import SpendCapReached + + state: dict = {} + stop: SystemExit | None = None + try: + with cli_output.quiet_stdout(): + _novelty_analyze(args, state) + except SystemExit as exc: + stop = exc + except SpendCapReached as exc: # what stops_at_cap says of it, so the document reports the same exit + stop = SystemExit(f"{exc}; nothing was written") + except Exception as exc: # a write after the paid calls keeps their cost in the document, then it re-raises + if "payload" in state: + cli_output.emit(cli_output.write_failure_document( + "skill novelty analyze", exc, _spent_so_far(args, state), + help_argv=getattr(args, "_leaf_help_argv", None), subjects=[{"subject": args.artifact, "verdict": None}], + artifacts={"out": str(state["out"])} if state.get("saved") else None)) + raise + _emit_analyze(args, state, stop) + if stop is not None: + raise stop + + +def _spent_so_far(args: argparse.Namespace, state: dict) -> dict: + """The cost of the run so far: the calls its clients made (the judge2 regrade included), if they were built.""" + from dokimi import cli_output + from dokimi.novelty.client import roll_up_cost + + if "clients" not in state: + return cli_output.cost_of(cap_usd=args.max_usd) + rolled = roll_up_cost(state["clients"]) + return cli_output.cost_of(spent_usd=rolled.get("usd"), calls=rolled.get("llm_calls", 0), cap_usd=args.max_usd) + + +def _emit_analyze(args: argparse.Namespace, state: dict, stop: SystemExit | None) -> None: + """The document: the estimate under --dry-run, the saved run (complete, or the stop that kept it). An input + error has no state: it propagates to cli.py, which writes its document.""" + from dokimi import cli_output + + kind = "skill novelty analyze" + if "estimate" in state: + cli_output.emit_estimate(kind, {"dry_run": True, "estimate": state["estimate"]}, cap_usd=args.max_usd) + return + subjects = [{"subject": args.artifact, "verdict": None}] + if "payload" not in state: # nothing was saved: an input error (exit 2) goes to cli.py, which names its next step + if stop is not None and stop.code != 2: + cli_output.emit(cli_output.envelope(kind, run_id=cli_output.current_run_id(), status="failed", + reason=str(stop) or type(stop).__name__, subjects=subjects, + cost=_spent_so_far(args, state))) + return + payload = state["payload"] + spent = payload.get("cost") or {} + # the clients' calls, judge2 regrade included (payload["cost"] leaves judge2 out) + cost = _spent_so_far(args, state) if "clients" in state else cli_output.cost_of( + spent_usd=spent.get("usd"), calls=spent.get("llm_calls", 0), cap_usd=args.max_usd) + saved = not state["partial"] # a partial run is kept in a sidecar file, not at the novelty.json path + fields: dict[str, Any] = {"cost": cost, "artifacts": {"out": str(state["out"])} if saved else None, "subjects": subjects} + if stop is None: + cli_output.emit_leaf(kind, payload, **fields) + else: + cli_output.emit(cli_output.stop_document(kind, payload, stop, limit_code=cli_output.limit_code_of(payload), + **fields)) + + +def _novelty_analyze(args: argparse.Namespace, state: dict) -> None: """Run the full pipeline over one artifact and write the novelty artifact + views.""" from dokimi.novelty import cost from dokimi.artifacts import save_artifact @@ -62,7 +133,7 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: print(f" overridden by flags: {sorted(record['overrides'])}", file=sys.stderr) if args.estimate_only: - print_estimate_only(args, settings, artifact_bundle.text, cost.estimate_usd) + state["estimate"] = print_estimate_only(args, settings, artifact_bundle.text, cost.estimate_usd) # --json return cache_dir = usable_cache_dir(args.cache_dir) print_run_estimate(args, settings, artifact_bundle.text, cost.estimate_usd) @@ -71,6 +142,8 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: extractor, answerer, judge = cost.clients(args) panel = panel_clients(args, cost.client) judge2 = judge2_client(args, answerer, judge, cost.client, panel) + # The clients are kept for --json: a stop before the payload still reports the calls the run made + state["clients"] = [extractor, answerer, judge, *panel, *([judge2] if judge2 is not None else [])] config = AnalyzeConfig( artifact_ref=args.artifact, artifact_kind=artifact_bundle.kind, @@ -99,9 +172,11 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: raise SystemExit(str(exc)) from None out_dir = Path(args.out_dir) if args.out_dir else default_dir(args.artifact) out_json = Path(args.out_json) if args.out_json else out_dir / "novelty.json" + state.update(payload=result.artifact, partial=bool(result.partial), out=out_json) # kept for --json exit_if_analyze_partial(result, out_json) # a run the cap stopped keeps what it paid for stamp(result.artifact, args, result.measure_result, answerer=answerer, judge=judge, judge2=judge2) save_artifact("novelty", result.artifact, out_json) + state["saved"] = True # novelty.json is this run's from here on (a failed write names no file) verdicts_path = save_panel_verdicts(result, out_json) atom_verdicts_path = save_atom_verdicts(result, out_json) atoms_path = save_run_atoms(result, out_json, extractor=extractor.model, diff --git a/dokimi/dokimi/commands/novelty_budget.py b/dokimi/dokimi/commands/novelty_budget.py index fa5e66dfc..c0842ab04 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -280,8 +280,8 @@ def print_run_estimate(args: argparse.Namespace, settings, text: str, estimate_u file=sys.stderr) -def print_estimate_only(args: argparse.Namespace, settings, text: str, estimate_usd) -> None: - """The ``--dry-run`` output of ``analyze``: the projection as JSON, and what it rests on.""" +def print_estimate_only(args: argparse.Namespace, settings, text: str, estimate_usd) -> dict: + """The ``--dry-run`` output of ``analyze``: the projection as JSON, and what it rests on. Returns the estimate.""" from dokimi.novelty import cost from dokimi.novelty.tiers import FITTED_TOKENS_MAX @@ -308,3 +308,4 @@ def print_estimate_only(args: argparse.Namespace, settings, text: str, estimate_ "dollar figure.", file=sys.stderr, ) + return estimate diff --git a/dokimi/dokimi/commands/novelty_routing.py b/dokimi/dokimi/commands/novelty_routing.py index 3c244f837..c43ac062c 100644 --- a/dokimi/dokimi/commands/novelty_routing.py +++ b/dokimi/dokimi/commands/novelty_routing.py @@ -13,7 +13,7 @@ import json import sys from pathlib import Path -from typing import NoReturn +from typing import Any, NoReturn from dokimi.commands.novelty import default_dir from dokimi.commands.novelty_routing_inputs import checked_out_path, load_all_vs_all_field, load_routing_field @@ -39,7 +39,7 @@ from dokimi.files import InputError -def _cmd_routing_all_vs_all(args: argparse.Namespace) -> None: +def _cmd_routing_all_vs_all(args: argparse.Namespace) -> tuple[dict, Path, None] | None: """Every skill in the field is the gold in turn: confusion matrix and attractors.""" from dokimi.novelty import cost from dokimi.novelty.all_vs_all import all_vs_all, check_acceptable, load_queries_with_acceptable @@ -61,9 +61,10 @@ def _cmd_routing_all_vs_all(args: argparse.Namespace) -> None: unloaded) check_acceptable([c.name for c in field], queries_by_skill, acceptable) if args.estimate_only: - print_all_vs_all_estimate(args, field, queries_by_skill) - return + args.estimate_doc = print_all_vs_all_estimate(args, field, queries_by_skill) # --json reads it + return None selector = cost.client(args.model, args.provider, "selector", args) if args.model else None + args.cost_clients = [selector] if selector is not None else None # --json: the cost of a stop after the calls if selector is not None: # One call per query with a content word and per repeat, each sending every card. calls = sum(bool(tokenize(q)) for qs in queries_by_skill.values() for q in qs) @@ -98,16 +99,55 @@ def _cmd_routing_all_vs_all(args: argparse.Namespace) -> None: payload["cost"] = roll_up_cost([selector]) out = save_result(payload, out, model_arm) summary = (result, len(field), len(queries_by_skill), model_arm, payload.get("cost")) - # A failed model call is a runtime failure (exit 1) even when the cap stopped the run too. - stop_if_partial(payload, out, lambda: print_all_vs_all_summary(*summary), - f"{failed} of {sent} model call(s) failed" if failed else "") - if failed: - exit_partial_all_vs_all(model_arm, payload.get("cost"), failed, sent, out) + try: + # A failed model call is a runtime failure (exit 1) even when the cap stopped the run too. + stop_if_partial(payload, out, lambda: print_all_vs_all_summary(*summary), + f"{failed} of {sent} model call(s) failed" if failed else "") + if failed: + exit_partial_all_vs_all(model_arm, payload.get("cost"), failed, sent, out) + except SystemExit as stop: # the result is saved: --json prints its document, then the exit stands + raise RoutingStopped(stop, payload, out, None) from None print(f"OK Saved all-vs-all routing: {out}") print_all_vs_all_summary(*summary) + return payload, out, None + +def cmd_catalog_routing(args: argparse.Namespace) -> None: + """`catalog routing ROOT`, and with --json its cli_output.v1 document. Report only: no verdict.""" + if not getattr(args, "json", False): + cmd_routing(args) + return + from dokimi import cli_output + + stopped = failure = None + with cli_output.quiet_stdout(): + try: + done = cmd_routing(args) + except RoutingStopped as stop: + done, stopped = stop.result, stop + except Exception as exc: # noqa: BLE001 - re-raised below; a write after the calls keeps their cost in the document + failure = exc + if failure is not None: + clients = getattr(args, "cost_clients", None) # the calls made before the failure, if any were made + if clients is not None: + from dokimi.novelty.client import roll_up_cost -def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: + rolled = roll_up_cost(clients) + cost = cli_output.cost_of(spent_usd=rolled.get("usd"), calls=rolled.get("llm_calls", 0), + cap_usd=args.max_usd) + cli_output.emit(cli_output.write_failure_document( + "catalog routing", failure, cost, help_argv=getattr(args, "_leaf_help_argv", None))) + raise failure + if done is None: # --dry-run: the estimate, nothing measured + cli_output.emit_estimate("catalog routing", {"dry_run": True, "estimate": args.estimate_doc}, + cap_usd=args.max_usd) + return + _emit_saved("catalog routing", args, done, stopped, subjects=None) + if stopped is not None: + raise stopped + + +def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str | None] | None: """Can a skill (or each skill under a root) be selected against its competitors? Lexical floor, model on top.""" from dokimi.novelty import cost if args.repeats > 1 and not args.model: @@ -119,8 +159,7 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: ) if args.all_vs_all: - _cmd_routing_all_vs_all(args) - return None + return _cmd_routing_all_vs_all(args) gold, body, competitors, left_out, conflicts = load_routing_field(args) # Checked before the query file is read, so the message is about the real problem. if not competitors and conflicts: @@ -131,7 +170,7 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: candidates = [gold, *competitors] if args.estimate_only: refuse_estimate_without_queries(args, queries, self_derived) - print_routing_estimate(args, candidates, queries) + args.estimate_doc = print_routing_estimate(args, candidates, queries) # --json reads it return None lexical = dict(lexical_routing(candidates, queries, gold=0), queries_self_derived=self_derived) @@ -153,6 +192,7 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: from dokimi.novelty.client import roll_up_cost selector = cost.client(args.model, args.provider, "selector", args) + args.cost_clients = [selector] # --json: the cost of a stop after the calls payload["model"] = dict( model_routing(candidates, queries, client=selector, gold=0, seed=args.seed, repeats=args.repeats), @@ -195,7 +235,7 @@ def _mark_failed_calls(payload: dict) -> str: class RoutingStopped(SystemExit): """A routing run the cap or a model error cut short: it exits as before, and carries the saved result for --json.""" - def __init__(self, stop: SystemExit, payload: dict, out: Path, skill: str) -> None: + def __init__(self, stop: SystemExit, payload: dict, out: Path, skill: str | None) -> None: super().__init__(*stop.args) # the message, already printed by stop_if_partial self.code = stop.code self.result = (payload, out, skill) @@ -219,29 +259,39 @@ def cmd_skill_routing(args: argparse.Namespace) -> None: except RoutingStopped as stop: # the result is saved: its document is printed, then the exit stands done, stopped = stop.result, stop if done is None: # --dry-run: an estimate, nothing measured - cli_output.emit_leaf("skill routing", None, reason="estimate only, nothing measured") + cli_output.emit_estimate("skill routing", {"dry_run": True, "estimate": args.estimate_doc}, + cap_usd=args.max_usd) return - payload, out, skill = done - lexical, model = payload["lexical"], payload.get("model") or {} + _emit_saved("skill routing", args, done, stopped, subjects=[{"subject": done[2], "verdict": None}]) + if stopped is not None: + raise stopped + + +def _emit_saved(kind: str, args: argparse.Namespace, done: tuple, stopped: SystemExit | None, + subjects: list | None) -> None: + """The document of a routing result that was saved: complete, budget_stopped (exit 3), partial (a failed call).""" + from dokimi import cli_output + + payload, out, _skill = done + lexical, model = payload.get("lexical") or {}, payload.get("model") or {} spent = (payload.get("cost") or {}).get("usd") calls = (payload.get("cost") or {}).get("llm_calls", 0) cost = {"spent_usd": spent or 0.0, "cap_usd": getattr(args, "max_usd", None), "calls": calls, "priced": None if not calls else spent is not None} if cost["cap_usd"] is not None and cost["priced"] is not False: # an unpriced spend leaves no remainder to state cost["remaining_usd"] = round(cost["cap_usd"] - cost["spent_usd"], 6) - partial = payload.get("partial") - status = "complete" if partial is None else ("budget_stopped" if partial["reason"] in ("spend_cap", "call_cap") else "partial") - reason = partial and partial["message"] - if partial is None and stopped is not None: # a failed model call, no cap - status, reason = "partial", str(stopped) - cli_output.emit_leaf( - "skill routing", payload, status=status, reason=reason, - subjects=[{"subject": skill, "verdict": None}], - summary={"queries_self_derived": payload["queries_self_derived"], "n_candidates": payload["n_candidates"], - "lexical_recall_at_1": lexical.get("recall_at_1"), "model_selection_rate": model.get("selection_rate")}, - artifacts={"out": str(out)}, cost=cost) - if stopped is not None: - raise stopped + summary = {"n_candidates": payload["n_candidates"]} + if "lexical" in payload: # a skill routing measurement: the lexical floor and the model's rate + summary.update(queries_self_derived=payload["queries_self_derived"], + lexical_recall_at_1=lexical.get("recall_at_1"), + model_selection_rate=model.get("selection_rate")) + fields: dict[str, Any] = {"subjects": subjects, "summary": summary, "artifacts": {"out": str(out)}, "cost": cost} + if stopped is None: + cli_output.emit_leaf(kind, payload, **fields) + else: # the exit the run took decides the status: 3 budget_stopped, 1 partial (a failed call) + message = (payload.get("partial") or {}).get("message") # the run's own words; the stop text adds the path + cli_output.emit(cli_output.stop_document(kind, payload, stopped, limit_code=cli_output.limit_code_of(payload), + reason=message or None, **fields)) def _refuse_no_queries(args: argparse.Namespace, queries: list[str], self_derived: bool, diff --git a/dokimi/dokimi/commands/novelty_routing_report.py b/dokimi/dokimi/commands/novelty_routing_report.py index 2f4e5a7c8..1d09ec439 100644 --- a/dokimi/dokimi/commands/novelty_routing_report.py +++ b/dokimi/dokimi/commands/novelty_routing_report.py @@ -316,7 +316,7 @@ def drop_queries_left_out(queries_by_skill: dict[str, list[str]], field: list[Ca def _print_estimate(args: argparse.Namespace, candidates: list, sent: list[str], - estimate: dict) -> None: + estimate: dict) -> dict: """The estimate as JSON, with the list-price USD of the calls ``sent`` makes; nothing is sent.""" from dokimi.novelty.routing_estimate import ( SELECTION_CHARS_PER_TOKEN, @@ -328,10 +328,10 @@ def _print_estimate(args: argparse.Namespace, candidates: list, sent: list[str], if args.model and estimate["n_calls"]: usd = estimate_routing_usd(args.model, args.provider, selection_prompt_tokens(candidates, sent), args.repeats) - print(json.dumps({"estimate_only": True, "artifact": args.artifact, "model": args.model, - "provider": args.provider if args.model else None, - "n_candidates": len(candidates), **estimate, - "expected_usd": usd}, indent=2)) + doc = {"estimate_only": True, "artifact": args.artifact, "model": args.model, + "provider": args.provider if args.model else None, + "n_candidates": len(candidates), **estimate, "expected_usd": usd} + print(json.dumps(doc, indent=2)) print("Estimate only, nothing was measured. Input is the selection prompt at " f"{SELECTION_CHARS_PER_TOKEN} characters per token (chars_per_input_token); output is " f"{SELECTION_REPLY_TOKENS} tokens a call (output_tokens_per_call), inside the 114 to 193 " @@ -341,10 +341,11 @@ def _print_estimate(args: argparse.Namespace, candidates: list, sent: list[str], if args.model and estimate["n_calls"] and usd is None: print(f"expected_usd is null: {args.model} has no list price in the litellm price map", file=sys.stderr) + return doc -def print_routing_estimate(args: argparse.Namespace, candidates: list, queries: list[str]) -> None: - """The model arm's calls, tokens and list-price USD, as JSON; nothing is sent. +def print_routing_estimate(args: argparse.Namespace, candidates: list, queries: list[str]) -> dict: + """The model arm's calls, tokens and list-price USD, as JSON; nothing is sent. Returns the estimate. No client is built. Without ``--model`` the run is lexical only, so the bill is zero. """ @@ -353,11 +354,11 @@ def print_routing_estimate(args: argparse.Namespace, candidates: list, queries: # Without --model there is no selector, so no call is made, whatever --reps says. estimate = selection_estimate(candidates, queries, repeats=args.repeats if args.model else 0) - _print_estimate(args, candidates, queries, estimate) + return _print_estimate(args, candidates, queries, estimate) def print_all_vs_all_estimate(args: argparse.Namespace, field: list[Candidate], - queries_by_skill: dict[str, list[str]]) -> None: + queries_by_skill: dict[str, list[str]]) -> dict: """The all-vs-all run's calls, priced as :func:`print_routing_estimate` prices one artifact's. The model arm sends each query with a content word, every skill's queries with the whole field @@ -369,7 +370,7 @@ def print_all_vs_all_estimate(args: argparse.Namespace, field: list[Candidate], sent = [query for queries in queries_by_skill.values() for query in queries if tokenize(query)] estimate = selection_estimate(field, sent, repeats=args.repeats if args.model else 0) estimate["n_queries"] = sum(len(queries) for queries in queries_by_skill.values()) - _print_estimate(args, field, sent, estimate) + return _print_estimate(args, field, sent, estimate) def print_routing_summary(payload: dict, n_competitors: int, self_derived: bool) -> None: diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index 953c67fc1..002e0c302 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -93,8 +93,60 @@ def _panel_questions(questions_data, source: str): return [q for q in questions if q], recorded # drop empty strings +def _emit_questions(kind: str, args: argparse.Namespace, state: dict[str, Any], stop: SystemExit | None) -> None: + """The cli_output.v1 document of a --json run of ``kind``: the estimate (dry run or refusal), the run's data, + or the stop that kept a partial result. A stop before any data still prints here: an input error (exit 2, with its help step) or a failed document.""" + from dokimi import cli_output + + gate = state.get("gate") or {} + verdict = state.get("verdict") + meter = state.get("meter") # the client that made the calls: its spend is read only for the document + cost = None + if meter is not None: + spend = meter.spend + cost = cli_output.cost_of(spent_usd=spend.spent_usd, calls=spend.calls, cap_usd=args.max_usd, + priced=not spend.unpriced_calls if spend.calls else None) + if verdict == spend_preview.DRY: + cli_output.emit_estimate(kind, {"dry_run": True, "estimate": gate["estimate"]}, cap_usd=args.max_usd) + elif verdict == spend_preview.REFUSED: + cli_output.emit_estimate(kind, {"dry_run": False, "estimate": gate["estimate"], "refusal": gate["refusal"]}, + cap_usd=args.max_usd, refusal=gate["refusal"]) + elif stop is not None and stop.code == 2 and "data" not in state: + # An input error, or an output the run could not write (exit 2): the document names the leaf's help step, + # as cli.py's document does for an exit 2 with no document of its own. + doc = cli_output.error_document(kind, "input", "see stderr", run_id=cli_output.current_run_id(), + reason="exit 2: see stderr", cost=cost) + help_argv = getattr(args, "_leaf_help_argv", None) + if help_argv: + doc["next"] = [cli_output.free_step(help_argv, "Show the accepted syntax of this command.")] + cli_output.emit(doc) + elif stop is not None: + cli_output.emit(cli_output.stop_document(kind, state.get("data"), stop, reason=state.get("reason"), + cost=cost, artifacts=state.get("artifacts"))) + elif "data" in state: + cli_output.emit_leaf(kind, state["data"], cost=cost, artifacts=state.get("artifacts")) + + def cmd_questions_panel_review(args: argparse.Namespace) -> None: - """Panel review of question quality with 3 role-differentiated LLM reviewers.""" + """Panel review of question quality with 3 role-differentiated LLM reviewers. + + With --json the run's human output goes to stderr and one cli_output.v1 document is printed on stdout.""" + state: dict[str, Any] = {} + if not getattr(args, "json", False): + _panel_review(args, state) + return + from dokimi import cli_output + + try: + with cli_output.quiet_stdout(): + _panel_review(args, state) + except SystemExit as stop: + _emit_questions("eval questions review", args, state, stop) + raise + _emit_questions("eval questions review", args, state, None) + + +def _panel_review(args: argparse.Namespace, state: dict[str, Any]) -> None: from dokimi.questions.panel_reviewer import QuestionPanelReviewer, DEFAULT_REVIEWERS reviewers = [r.strip() for r in args.reviewers.split(",") if r.strip()] if args.reviewers else DEFAULT_REVIEWERS @@ -110,6 +162,7 @@ def cmd_questions_panel_review(args: argparse.Namespace) -> None: reviewers=reviewers, model=args.model, provider=args.provider, concurrency=args.concurrency, cap=cap, ) + state["meter"] = reviewer # the calls this run makes are read for its document, stopped or not # Priced and refused before any client is built: a dry run or an over-cap estimate stops here. warn_recorded_self_judge(recorded, [(args.model, args.provider)], "eval questions review", roles=("generator", "reviewer")) @@ -118,7 +171,9 @@ def cmd_questions_panel_review(args: argparse.Namespace) -> None: provider=args.provider, reply_tokens=REVIEW_REPLY_TOKENS, dry_run=args.dry_run, max_usd=args.max_usd, mid_run_stop_note=f"a stop mid-run exits {EXIT_INCONCLUSIVE} with saved reviews " - f"or exits {EXIT_FAILURE} before any review is saved") + f"or exits {EXIT_FAILURE} before any review is saved", + into=state.setdefault("gate", {})) + state["verdict"] = verdict if verdict == spend_preview.DRY: return if verdict == spend_preview.REFUSED: @@ -136,6 +191,11 @@ def cmd_questions_panel_review(args: argparse.Namespace) -> None: kept = (f"reviews made before the stop are in {output_path}" if reviewer.reviews_saved else "no complete review was saved before the stop") print(f"Error: the --max-usd cap was reached: {exc}; {kept}", file=sys.stderr) + state.update(reason=f"the --max-usd cap was reached: {exc}; {kept}") + if reviewer.reviews_saved: # data exists only when reviews were saved, and that stop exits 3 (budget_stopped) + state.update(data={"product": args.product, "output": str(output_path), + "reviews_saved": reviewer.reviews_saved}, + artifacts={"out": str(output_path)}) sys.exit(EXIT_INCONCLUSIVE if reviewer.reviews_saved else EXIT_FAILURE) s = report.summary @@ -149,6 +209,8 @@ def cmd_questions_panel_review(args: argparse.Namespace) -> None: if s.get("top_flags"): print(f" Top issues : {', '.join(f'{k}({v})' for k, v in s['top_flags'])}") print(f"\n✅ Full report: {output_path}") + state.update(data={"product": args.product, "total": report.total, "summary": s}, + artifacts={"out": str(output_path)}) def cmd_questions_refine(args: argparse.Namespace) -> None: @@ -227,7 +289,25 @@ def _validate_before_fill(cleaned: list) -> None: def cmd_questions_analyze(args: argparse.Namespace) -> None: - """Analyze question quality: difficulty distribution and triviality detection.""" + """Analyze question quality: difficulty distribution and triviality detection. + + With --json the run's human output goes to stderr and one cli_output.v1 document is printed on stdout.""" + state: dict[str, Any] = {} + if not getattr(args, "json", False): + _questions_analyze(args, state) + return + from dokimi import cli_output + + try: + with cli_output.quiet_stdout(): + _questions_analyze(args, state) + except SystemExit as stop: + _emit_questions("eval questions analyze", args, state, stop) + raise + _emit_questions("eval questions analyze", args, state, None) + + +def _questions_analyze(args: argparse.Namespace, state: dict[str, Any]) -> None: from dokimi.questions.quality_analyzer import QuestionQualityAnalyzer from dokimi.questions.normalizer import normalize_questions @@ -246,12 +326,14 @@ def cmd_questions_analyze(args: argparse.Namespace) -> None: concurrency=args.concurrency, cap=cap, ) + state["meter"] = analyzer # the calls this run makes are read for its document, stopped or not # Priced and refused before any client is built: a dry run or an over-cap estimate stops here. warn_recorded_self_judge(questions_data, [(args.model, args.provider)], "eval questions analyze", roles=("generator", "reviewer")) verdict = spend_preview.gate(lambda: analyzer.classify_prompts(questions, args.product), model=args.model, provider=args.provider, reply_tokens=CLASSIFY_REPLY_TOKENS, - dry_run=args.dry_run, max_usd=args.max_usd) + dry_run=args.dry_run, max_usd=args.max_usd, into=state.setdefault("gate", {})) + state["verdict"] = verdict if verdict == spend_preview.DRY: return if verdict == spend_preview.REFUSED: @@ -264,6 +346,7 @@ def cmd_questions_analyze(args: argparse.Namespace) -> None: report = analyzer.analyze(questions, library_name=args.product) except SpendCapReached as exc: # nothing is written before the report, so a stop here leaves no file print(f"Error: the --max-usd cap was reached: {exc}", file=sys.stderr) + state["reason"] = f"the --max-usd cap was reached: {exc}; no report was written" sys.exit(EXIT_FAILURE) # Print summary @@ -289,6 +372,10 @@ def cmd_questions_analyze(args: argparse.Namespace) -> None: with exit_on_unwritable(output_path), exit_on_rejected("question_quality"): analyzer.save_report(report, output_path) print(f"\n✅ Full report saved to {output_path}") + state.update(data={"product": args.product, "total": report.total, "trivial_count": report.trivial_count, + "trivial_pct": report.trivial_pct, "diversity_score": report.diversity_score, + "difficulty_distribution": dist, "recommendations": report.recommendations}, + artifacts={"out": str(output_path)}) def print_validation_stats(stats: Dict[str, Any]) -> None: @@ -519,7 +606,11 @@ def register(eval_sub, positive_int) -> None: cli_flags.add(analyze_q_p, "dry_run", "--dry-run", action="store_true", dest="dry_run", help="Price the classification calls at list prices and print the estimate; call no model, " "build no client, write nothing") - analyze_q_p.set_defaults(func=cmd_questions_analyze) + analyze_q_p.add_argument("--json", action="store_true", + help="Print cli_output.v1 on stdout (the quality report under data; the estimate under " + "a dry run or a refusal); the human output goes to stderr") + analyze_q_p.set_defaults(func=cmd_questions_analyze, emits_cli_output=True, cli_kind="eval questions analyze", + input_help_next=True) # questions refine refine_q_p = questions_sub.add_parser("refine", help="Refine question set: normalise, deduplicate, filter trivial, report gaps") @@ -568,7 +659,11 @@ def register(eval_sub, positive_int) -> None: cli_flags.add(panel_q_p, "dry_run", "--dry-run", action="store_true", dest="dry_run", help="Price the review calls at list prices and print the estimate; call no model, " "build no client, write nothing") - panel_q_p.set_defaults(func=cmd_questions_panel_review) + panel_q_p.add_argument("--json", action="store_true", + help="Print cli_output.v1 on stdout (the review summary under data; the estimate under " + "a dry run or a refusal); the human output goes to stderr") + panel_q_p.set_defaults(func=cmd_questions_panel_review, emits_cli_output=True, cli_kind="eval questions review", + input_help_next=True) from dokimi.commands import answer_formats diff --git a/dokimi/dokimi/commands/routing_parser.py b/dokimi/dokimi/commands/routing_parser.py index 99ee05c0a..0536ac5f1 100644 --- a/dokimi/dokimi/commands/routing_parser.py +++ b/dokimi/dokimi/commands/routing_parser.py @@ -10,7 +10,7 @@ from dokimi.cli_model_ref import add_model_flag from dokimi import cli_flags -from dokimi.commands.novelty_routing import cmd_routing, cmd_skill_routing +from dokimi.commands.novelty_routing import cmd_catalog_routing, cmd_skill_routing from dokimi.commands.skill_sensitivity import cmd_skill_sensitivity from dokimi.commands.novelty_run import add_spend_cap, stops_at_cap from dokimi.defaults import DEFAULT_ANSWER_PROVIDER @@ -83,7 +83,11 @@ def add_skill_sensitivity(skill_sub, positive_int) -> None: sens_p.add_argument("--out", default=None, help="Path for the sentence sensitivity result JSON") add_spend_cap(sens_p) # Not offered here (headings would set the skill's own relevance); routing_queries reads the attribute. - sens_p.set_defaults(func=stops_at_cap(cmd_skill_sensitivity), queries_from_headings=False) + sens_p.add_argument("--json", action="store_true", + help="Print cli_output.v1 on stdout (the sensitivity result under data; the estimate under " + "--dry-run); the summary goes to stderr") + sens_p.set_defaults(func=stops_at_cap(cmd_skill_sensitivity), queries_from_headings=False, + emits_cli_output=True, cli_kind="skill sensitivity", input_help_next=True) def add_catalog_routing(catalog_sub, positive_int) -> None: @@ -97,7 +101,11 @@ def add_catalog_routing(catalog_sub, positive_int) -> None: help="A JSON object of skill name to the list of " "requests that should select that skill") _add_routing_options(routing_p, positive_int, refused=True) - routing_p.set_defaults(all_vs_all=True, artifact=None, func=stops_at_cap(cmd_routing)) + routing_p.add_argument("--json", action="store_true", + help="Print cli_output.v1 on stdout (the all-vs-all measurement under data, report only); " + "the summary goes to stderr; the estimate under --dry-run") + routing_p.set_defaults(all_vs_all=True, artifact=None, func=stops_at_cap(cmd_catalog_routing), + emits_cli_output=True, cli_kind="catalog routing", input_help_next=True) def _add_routing_options(routing_p, positive_int, refused: bool = False) -> None: diff --git a/dokimi/dokimi/commands/skill.py b/dokimi/dokimi/commands/skill.py index 6603f1816..ae09aa3ff 100644 --- a/dokimi/dokimi/commands/skill.py +++ b/dokimi/dokimi/commands/skill.py @@ -99,6 +99,9 @@ def register_skill(skill_sub, positive_int) -> None: help="novelty.v1 JSON path (default: novelty.json in --out-dir)") cli_flags.add(analyze_p, "output", "--format", default="html", choices=["html", "md"], dest="view_format", help="Rendered view format: html or md (default: html)") + analyze_p.add_argument("--json", action="store_true", + help="Print cli_output.v1 on stdout (the novelty result under data; the estimate under " + "--dry-run); the summary goes to stderr") analyze_p.add_argument("--no-classify", action="store_true", dest="no_classify", help="Skip the judged content categories (cheaper; the artifact " "records the skip as a warning)") @@ -122,7 +125,8 @@ def register_skill(skill_sub, positive_int) -> None: help="Print the projected model-call bill and exit without " "spending anything") add_bundle_args(analyze_p, positive_int) - analyze_p.set_defaults(func=stops_at_cap(cmd_novelty_analyze)) + analyze_p.set_defaults(func=stops_at_cap(cmd_novelty_analyze), emits_cli_output=True, + cli_kind="skill novelty analyze", input_help_next=True) atoms_p = novelty_sub.add_parser("atoms", help="Extract knowledge atoms and spans only") add_common_args(atoms_p, positive_int) diff --git a/dokimi/dokimi/commands/skill_sensitivity.py b/dokimi/dokimi/commands/skill_sensitivity.py index 25646582e..d14c322de 100644 --- a/dokimi/dokimi/commands/skill_sensitivity.py +++ b/dokimi/dokimi/commands/skill_sensitivity.py @@ -8,6 +8,7 @@ import argparse import json import sys +from typing import Any from dokimi.commands.novelty import default_dir from dokimi.commands.novelty_routing_inputs import checked_out_path, load_routing_field @@ -24,6 +25,51 @@ def cmd_skill_sensitivity(args: argparse.Namespace) -> None: + """`skill sensitivity`, and with --json its cli_output.v1 document (the human output then goes to stderr).""" + if not getattr(args, "json", False): + _sensitivity(args, {}) + return + from dokimi import cli_output + + state: dict = {} + try: + with cli_output.quiet_stdout(): + _sensitivity(args, state) + except SystemExit as stop: + _emit(args, state, stop) + raise + _emit(args, state, None) + + +def _emit(args: argparse.Namespace, state: dict, stop: SystemExit | None) -> None: + """The document: the estimate under --dry-run, the saved result (complete, or the stop that kept it).""" + from dokimi import cli_output + + if "estimate" in state: + cli_output.emit_estimate("skill sensitivity", {"dry_run": True, "estimate": state["estimate"]}, + cap_usd=args.max_usd) + elif "payload" in state: + payload = state["payload"] + calls = (payload.get("cost") or {}).get("llm_calls", 0) + spent = (payload.get("cost") or {}).get("usd") + cost = cli_output.cost_of(spent_usd=spent, calls=calls, cap_usd=args.max_usd, + priced=None if not calls else spent is not None) + fields: dict[str, Any] = {"cost": cost, "artifacts": {"out": str(state["out"])}} + if stop is not None and payload.get("status") == "failed" and getattr(stop, "code", None) != 3: + # every selector call failed: as the file says (a budget stop keeps its budget_stopped status) + cli_output.emit(cli_output.envelope("skill sensitivity", run_id=cli_output.current_run_id(), + status="failed", reason=str(stop), data=payload, + subjects=[{"subject": args.artifact, "verdict": None}], **fields)) + elif stop is None: + cli_output.emit_leaf("skill sensitivity", payload, subjects=[{"subject": args.artifact, "verdict": None}], + **fields) + else: + cli_output.emit(cli_output.stop_document("skill sensitivity", payload, stop, + limit_code=cli_output.limit_code_of(payload), + subjects=[{"subject": args.artifact, "verdict": None}], **fields)) + + +def _sensitivity(args: argparse.Namespace, state: dict) -> None: from dokimi.novelty import cost from dokimi.novelty.client import roll_up_cost from dokimi.novelty.routing import check_field, tokenize @@ -41,7 +87,7 @@ def cmd_skill_sensitivity(args: argparse.Namespace) -> None: "Pass --queries with requests a user would write") plan = arm_plan(gold, competitors) if args.estimate_only: - _print_estimate(args, plan, queries) + state["estimate"] = _print_estimate(args, plan, queries) return out = checked_out_path(args.out, "skill sensitivity", default=str(default_dir(args.artifact) / "sensitivity.json")) out.parent.mkdir(parents=True, exist_ok=True) @@ -63,6 +109,7 @@ def cmd_skill_sensitivity(args: argparse.Namespace) -> None: "cost": roll_up_cost([selector]), } out = save_result(payload, out, result) + state.update(payload=payload, out=out) stop_if_partial(payload, out, lambda: _print_summary(result, payload["cost"])) if failed: _print_summary(result, payload["cost"]) @@ -72,8 +119,8 @@ def cmd_skill_sensitivity(args: argparse.Namespace) -> None: _print_summary(result, payload["cost"]) -def _print_estimate(args: argparse.Namespace, plan: list, queries: list[str]) -> None: - """The calls and list-price USD of the run, as JSON; nothing is sent.""" +def _print_estimate(args: argparse.Namespace, plan: list, queries: list[str]) -> dict: + """The calls and list-price USD of the run, as JSON; nothing is sent. Returns the estimate.""" from dokimi.commands.novelty_routing_report import estimate_routing_usd from dokimi.novelty.routing_estimate import selection_prompt_tokens @@ -82,14 +129,16 @@ def _print_estimate(args: argparse.Namespace, plan: list, queries: list[str]) -> arm_usd = estimate_routing_usd(args.model, args.provider, selection_prompt_tokens(field, queries), args.repeats) usd = None if arm_usd is None or usd is None else round(usd + arm_usd, 6) - print(json.dumps({"estimate_only": True, "artifact": args.artifact, "model": args.model, - "provider": args.provider, "arms": len(plan), "n_queries": len(queries), - "repeats": args.repeats, "n_calls": len(plan) * len(queries) * args.repeats, - "expected_usd": usd}, indent=2)) + estimate = {"estimate_only": True, "artifact": args.artifact, "model": args.model, + "provider": args.provider, "arms": len(plan), "n_queries": len(queries), + "repeats": args.repeats, "n_calls": len(plan) * len(queries) * args.repeats, + "expected_usd": usd} + print(json.dumps(estimate, indent=2)) print("Estimate only, nothing was measured. One arm per sentence of the description plus the baseline; " "each arm sends every query once per repeat.", file=sys.stderr) if usd is None: print(f"expected_usd is null: {args.model} has no list price in the litellm price map", file=sys.stderr) + return estimate def _print_summary(result: dict, cost: dict) -> None: diff --git a/dokimi/dokimi/commands/tools.py b/dokimi/dokimi/commands/tools.py index 42612998b..22e636616 100644 --- a/dokimi/dokimi/commands/tools.py +++ b/dokimi/dokimi/commands/tools.py @@ -328,8 +328,12 @@ def _emit_preference(args: argparse.Namespace, result: _PreferenceResult) -> Non error = None if result.exit_code == EXIT_USAGE and result.reason is not None: error = cli_output.error_object("input", result.reason) + # A refused path after the calls exits 2 from here, so its document names the help step itself (#94 F2). + help_argv = getattr(args, "_leaf_help_argv", None) + next_steps = ([cli_output.free_step(help_argv, "Show the accepted syntax of this command.")] + if error is not None and help_argv else None) cli_output.emit_leaf(kind, result.payload, status=status, reason=result.reason, error=error, - cost=cost, limits=limits, artifacts=result.artifacts or None) + cost=cost, limits=limits, artifacts=result.artifacts or None, next_steps=next_steps) def cmd_tools_preference(args: argparse.Namespace) -> None: diff --git a/dokimi/dokimi/spend_preview.py b/dokimi/dokimi/spend_preview.py index 866637f19..b3d1360dc 100644 --- a/dokimi/dokimi/spend_preview.py +++ b/dokimi/dokimi/spend_preview.py @@ -59,14 +59,18 @@ def cap_refusal(max_usd: float | None, est: dict[str, Any], *, provider: str = " def gate(build_prompts: Callable[[], Sequence[str]], *, model: str, provider: str, reply_tokens: int, - dry_run: bool, max_usd: float | None, mid_run_stop_note: str = "a stop mid-run exits 1") -> str | None: + dry_run: bool, max_usd: float | None, mid_run_stop_note: str = "a stop mid-run exits 1", + into: dict[str, Any] | None = None) -> str | None: """None when the run may make its calls; DRY after a dry run's estimate (exit 0); REFUSED when a real run's estimate is over ``max_usd``, the model has no list price or the run uses a CLI login. - A plain run is not priced at all. ``mid_run_stop_note`` describes the caller's exit on a cap stop.""" + A plain run is not priced at all. ``mid_run_stop_note`` describes the caller's exit on a cap stop. + ``into`` receives the ``estimate`` and the ``refusal`` (or None) when the run is priced, for a --json document.""" if not dry_run and max_usd is None: return None est = price_calls(build_prompts(), model, provider, reply_tokens) refusal = cap_refusal(max_usd, est, provider=provider) + if into is not None: + into.update(estimate=est, refusal=refusal) if dry_run: print(estimate_line(est)) if max_usd is not None: diff --git a/dokimi/tests/test_cli_json_novelty.py b/dokimi/tests/test_cli_json_novelty.py new file mode 100644 index 000000000..a32ab1303 --- /dev/null +++ b/dokimi/tests/test_cli_json_novelty.py @@ -0,0 +1,390 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""``skill novelty analyze --json`` (#94 F2): the dry-run estimate, a stopped run, a finished run and an input +error's ``next``. The dry run and the unit documents make no model call; the stop is raised by the fake run. + +Part of #94. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +import pytest + +from dokimi import cli +from dokimi.commands import novelty as novelty_cmd +from dokimi.commands.novelty_routing_report import PartialStop +from dokimi.novelty.client import SpendCapReached + + +def _cli(monkeypatch, capsys, *argv: str) -> tuple[int, dict[str, Any]]: + """Run the CLI; return its exit code and the one cli_output.v1 document it printed on stdout.""" + monkeypatch.setattr("sys.argv", ["dokimi", *argv]) + code = 0 + try: + cli.main() + except SystemExit as exc: + code = int(exc.code or 0) + return code, json.loads(capsys.readouterr().out) + + +def _skill(tmp_path) -> str: + body = "\n\n".join(f"Section {i}. Do not enable the legacy driver number {i} on a production host." + for i in range(20)) + (tmp_path / "SKILL.md").write_text(f"---\nname: s\ndescription: d\n---\n\n# S\n\n{body}\n", encoding="utf-8") + return f"skill:{tmp_path}" + + +def _doc(capsys, state: dict, stop: SystemExit | None, *, max_usd: float | None = 0.05) -> dict[str, Any]: + args = argparse.Namespace(artifact="skill:x", max_usd=max_usd, json=True) + novelty_cmd._emit_analyze(args, state, stop) + return json.loads(capsys.readouterr().out) + + +def test_analyze_dry_run_json_is_a_complete_estimate_and_writes_nothing(tmp_path, monkeypatch, capsys): + monkeypatch.chdir(tmp_path) + code, doc = _cli(monkeypatch, capsys, "skill", "novelty", "analyze", "--artifact", _skill(tmp_path), + "--dry-run", "--json") + + assert code == 0 and doc["status"] == "complete" and doc["error"] is None + assert doc["kind"] == "skill novelty analyze" + assert doc["data"]["dry_run"] is True and "expected_usd" in doc["data"]["estimate"] + assert doc["cost"]["calls"] == 0 and doc["cost"]["spent_usd"] == 0.0 + assert not list(tmp_path.rglob("novelty.json")) + + +def test_analyze_input_error_json_names_its_help_as_the_next_step(tmp_path, monkeypatch, capsys): + monkeypatch.chdir(tmp_path) + code, doc = _cli(monkeypatch, capsys, "skill", "novelty", "analyze", "--artifact", + f"skill:{tmp_path / 'missing'}", "--json") + + assert code == 2 and doc["status"] == "failed" and doc["error"]["code"] == "input" + assert len(doc["next"]) == 1 + step = doc["next"][0] + assert step["argv"][-1] == "--help" and step["argv"][:-1] == ["dokimi", "skill", "novelty", "analyze"] + assert step["spends"] is False and step["est_usd"] == 0 + + +def test_a_run_the_cap_stopped_is_budget_stopped_and_keeps_its_cost(tmp_path, capsys): + state = {"payload": {"cost": {"usd": 0.02, "llm_calls": 3}, "status": "partial"}, "partial": True, + "out": tmp_path / "novelty.json"} + doc = _doc(capsys, state, PartialStop("the measurement stopped at the cap", 3)) + + assert doc["status"] == "budget_stopped" and doc["reason"] == "the measurement stopped at the cap" + assert doc["limits"] == [{"code": "max_usd", "text": "the measurement stopped at the cap"}] + assert doc["cost"]["spent_usd"] == 0.02 and doc["cost"]["calls"] == 3 and doc["cost"]["cap_usd"] == 0.05 + assert doc["artifacts"] is None # the partial record is a sidecar: no novelty.json path is claimed + assert doc["data"] == state["payload"] + + +def test_a_finished_run_with_a_failed_call_is_partial_and_names_the_saved_file(tmp_path, capsys): + out = tmp_path / "novelty.json" + state = {"payload": {"cost": {"usd": 0.01, "llm_calls": 2}}, "partial": False, "out": out} + doc = _doc(capsys, state, PartialStop("1 call failed; the result is saved, so this exits 1", 1)) + + assert doc["status"] == "partial" and doc["limits"] == [] + assert doc["artifacts"] == {"out": str(out)} + assert doc["cost"]["spent_usd"] == 0.01 + + +def test_a_finished_run_is_complete_and_names_the_saved_file(tmp_path, capsys): + out = tmp_path / "novelty.json" + state = {"payload": {"cost": {"usd": 0.01, "llm_calls": 2}}, "partial": False, "out": out} + doc = _doc(capsys, state, None) + + assert doc["status"] == "complete" and doc["verdict"] is None and doc["error"] is None + assert doc["artifacts"] == {"out": str(out)} + assert doc["subjects"] == [{"subject": "skill:x", "verdict": None}] + + +def test_a_spend_cap_raised_inside_the_run_exits_as_stops_at_cap_does_and_documents_it(monkeypatch, capsys, tmp_path): + def capped(_args, _state): + raise SpendCapReached("the spend cap was reached") + + monkeypatch.setattr(novelty_cmd, "_novelty_analyze", capped) + args = argparse.Namespace(artifact="skill:x", max_usd=0.01, json=True) + + with pytest.raises(SystemExit) as exc: + novelty_cmd.cmd_novelty_analyze(args) + + assert "nothing was written" in str(exc.value.code) + doc = json.loads(capsys.readouterr().out) + assert doc["status"] == "failed" and "nothing was written" in doc["reason"] # nothing was saved to keep + + +# --- the other paid leaves of this slice: eval questions analyze, skill sensitivity -------------------------- + +QUESTIONS = ["What is oneTBB?", "How to use parallel_for?", "Explain task_arena internals"] + + +@pytest.fixture +def no_client(monkeypatch): + """A dry run and a refused cap make no model call and build no client.""" + from dokimi import llm + from dokimi.novelty import client as client_mod + + def refuse(*_a, **_k): + raise AssertionError("a model client was built or called") + + monkeypatch.setattr(llm.LLM, "__init__", refuse) + monkeypatch.setattr(client_mod.LLMClient, "__init__", refuse) + return refuse + + +@pytest.fixture +def priced(monkeypatch): + """List price 0.01 per call, so the estimate is a known figure.""" + from dokimi import llm_pricing + + monkeypatch.setattr(llm_pricing, "list_cost_usd", lambda *_a: 0.01) + + +def test_questions_analyze_dry_run_json_is_the_estimate_and_writes_nothing(tmp_path, monkeypatch, capsys, + no_client, priced): + questions = tmp_path / "questions.json" + questions.write_text(json.dumps({"questions": QUESTIONS}), encoding="utf-8") + out = tmp_path / "quality.json" + code, doc = _cli(monkeypatch, capsys, "eval", "questions", "analyze", "--questions", str(questions), + "--product", "oneTBB", "--out", str(out), "--dry-run", "--json") + + assert code == 0 and doc["status"] == "complete" and doc["kind"] == "eval questions analyze" + assert doc["data"]["dry_run"] is True and doc["data"]["estimate"]["calls"] == len(QUESTIONS) + assert doc["cost"]["calls"] == 0 and not out.exists() + + +def test_questions_analyze_refused_cap_json_is_budget_stopped_and_exits_3(tmp_path, monkeypatch, capsys, + no_client, priced): + questions = tmp_path / "questions.json" + questions.write_text(json.dumps({"questions": QUESTIONS}), encoding="utf-8") + code, doc = _cli(monkeypatch, capsys, "eval", "questions", "analyze", "--questions", str(questions), + "--product", "oneTBB", "--model", "codex-cli/openai/gpt-4o", "--max-usd", "5", "--json") + + assert code == 3 and doc["status"] == "budget_stopped" + assert doc["limits"][0]["code"] == "max_usd" and "CLI login" in doc["limits"][0]["text"] + assert doc["cost"]["calls"] == 0 and doc["cost"]["spent_usd"] == 0.0 + + +def test_skill_sensitivity_dry_run_json_is_the_estimate_and_sends_nothing(tmp_path, monkeypatch, capsys, + no_client, priced): + def skill(name, description): + path = tmp_path / name + path.mkdir() + (path / "SKILL.md").write_text(f"---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n", + encoding="utf-8") + return str(path) + + artifact = skill("gold", "Tunes parallel loops. Pins threads to cores.") + rival = skill("rival", "Formats dates for reports.") + queries = tmp_path / "queries.json" + queries.write_text(json.dumps(["speed up my loop", "format a date"]), encoding="utf-8") + code, doc = _cli(monkeypatch, capsys, "skill", "sensitivity", artifact, "--competitors", rival, + "--queries", str(queries), "--model", "selector-m", "--reps", "1", "--dry-run", "--json") + + assert code == 0 and doc["status"] == "complete" and doc["kind"] == "skill sensitivity" + assert doc["data"]["dry_run"] is True and doc["data"]["estimate"]["estimate_only"] is True + assert doc["cost"]["calls"] == 0 + + +# --- stop_document: the reason of an int-coded exit, and a stop that kept no result ---------------------------- + + +def test_an_int_coded_stop_has_a_reason_that_says_it_stopped_not_its_bare_code(): + from dokimi.cli_output import stop_document + + doc = stop_document("eval questions review", {"reviews_saved": True}, SystemExit(3)) + + assert doc["status"] == "budget_stopped" and doc["reason"] == "the run stopped (exit 3)" + assert doc["limits"] == [{"code": "max_usd", "text": "the run stopped (exit 3)"}] + + +def test_a_call_cap_stop_names_the_call_limit_not_the_usd_cap(): + from dokimi.cli_output import limit_code_of, stop_document + + data = {"partial": {"reason": "call_cap", "message": "the --max-calls cap was reached"}} + doc = stop_document("skill routing", data, PartialStop("the --max-calls cap was reached", 3), + limit_code=limit_code_of(data)) + + assert doc["status"] == "budget_stopped" and doc["limits"][0]["code"] == "max_calls" + assert limit_code_of({"partial": {"reason": "spend_cap"}}) == "max_usd" + + +def test_a_stop_that_kept_no_result_is_failed_and_takes_the_reason_given(): + from dokimi.cli_output import stop_document + + doc = stop_document("eval questions review", None, SystemExit(1), reason="no complete review was saved") + + assert doc["status"] == "failed" and doc["data"] is None and doc["reason"] == "no complete review was saved" + + +def test_questions_analyze_cap_reached_mid_run_json_is_a_failed_document_with_its_cost(tmp_path, monkeypatch, + capsys, no_client): + from dokimi import spend_preview + from dokimi.questions.quality_analyzer import QuestionQualityAnalyzer + from dokimi.spend import SpendCapReached as CapReached + + questions = tmp_path / "questions.json" + questions.write_text(json.dumps({"questions": QUESTIONS}), encoding="utf-8") + monkeypatch.setattr(spend_preview, "gate", lambda *_a, **_k: None) # the gate passes: the run starts + + def capped(self, *_a, **_k): + self.spend.calls += 2 # the calls made before the cap: their cost is what the document keeps + self.spend.spent_usd += 0.02 + raise CapReached("the spend cap was reached") + + monkeypatch.setattr(QuestionQualityAnalyzer, "analyze", capped) + code, doc = _cli(monkeypatch, capsys, "eval", "questions", "analyze", "--questions", str(questions), + "--product", "oneTBB", "--max-usd", "0.05", "--json") + + assert code == 1 and doc["status"] == "failed" and doc["data"] is None + assert doc["cost"]["calls"] == 2 and doc["cost"]["spent_usd"] == 0.02 + assert "the --max-usd cap was reached" in doc["reason"] and "no report was written" in doc["reason"] + assert doc["cost"]["cap_usd"] == 0.05 and doc["artifacts"] is None + + +def test_a_stop_before_the_payload_reports_the_calls_its_clients_made(tmp_path, capsys): + """A cap reached in a stage that returns no partial result still reports what the run paid: the clients' + spend, not zero (the cost of the stop is read from the clients the run built).""" + from dokimi.spend import Spend + + class FakeClient: + def spend(self): + return Spend(calls=2, spent_usd=0.02) + + def cost_summary(self): + return {"role": "answerer", "usd": 0.02, "llm_calls": 2} + + state = {"clients": [FakeClient()]} + doc = _doc(capsys, state, SystemExit("the spend cap was reached; nothing was written")) + + assert doc["status"] == "failed" and doc["cost"]["calls"] == 2 and doc["cost"]["spent_usd"] == 0.02 + assert doc["cost"]["remaining_usd"] == 0.03 and doc["artifacts"] is None + + +def test_questions_analyze_exit_2_after_its_calls_is_an_input_document_that_names_its_help(tmp_path, monkeypatch, + capsys, no_client): + from dokimi import spend_preview + from dokimi.questions.quality_analyzer import QuestionQualityAnalyzer + + questions = tmp_path / "questions.json" + questions.write_text(json.dumps({"questions": QUESTIONS}), encoding="utf-8") + monkeypatch.setattr(spend_preview, "gate", lambda *_a, **_k: None) + + def unwritable(self, *_a, **_k): + raise SystemExit(2) # what exit_on_unwritable does after the calls + + monkeypatch.setattr(QuestionQualityAnalyzer, "analyze", unwritable) + code, doc = _cli(monkeypatch, capsys, "eval", "questions", "analyze", "--questions", str(questions), + "--product", "oneTBB", "--json") + + assert code == 2 and doc["status"] == "failed" and doc["error"]["code"] == "input" + assert len(doc["next"]) == 1 and doc["next"][0]["argv"][-1] == "--help" + + +def test_catalog_routing_status_follows_the_exit_the_stop_took(): + import contextlib + import io + + from dokimi.commands.novelty_routing import _emit_saved + + def doc_of(stop, reason): + payload = {"n_candidates": 2, "partial": {"reason": reason, "message": "m"}} + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + _emit_saved("catalog routing", argparse.Namespace(max_usd=None), (payload, Path("r.json"), None), + stop, subjects=None) + return json.loads(buf.getvalue()) + + # a cap reached with a failed call too: the run exits 1 (failed call), so the document is partial + assert doc_of(PartialStop("1 of 4 model call(s) failed", 1), "spend_cap")["status"] == "partial" + assert doc_of(SystemExit(3), "no_price")["status"] == "budget_stopped" + + +class _SpentClient: + """A client that made two priced calls: the cost a document must keep when a write fails after them.""" + + def spend(self): + from dokimi.spend import Spend + + return Spend(calls=2, spent_usd=0.02) + + def cost_summary(self): + return {"role": "selector", "usd": 0.02, "llm_calls": 2} + + +def test_a_write_failing_after_the_paid_calls_keeps_their_cost_in_the_document(monkeypatch, capsys, tmp_path): + (tmp_path / "x.json").write_text("{}") # an earlier run's novelty.json: this run did not write it + def wrote_nothing(_args, state): + state.update(payload={"cost": {"usd": 0.02, "llm_calls": 2}}, partial=False, out=tmp_path / "x.json") + state["clients"] = [_SpentClient()] + raise OSError("read-only file system") + + monkeypatch.setattr(novelty_cmd, "_novelty_analyze", wrote_nothing) + args = argparse.Namespace(artifact="skill:x", max_usd=0.05, json=True) + + with pytest.raises(OSError): + novelty_cmd.cmd_novelty_analyze(args) + + doc = json.loads(capsys.readouterr().out) + assert doc["status"] == "failed" and "then it failed" in doc["reason"] + assert doc["cost"]["calls"] == 2 and doc["cost"]["spent_usd"] == 0.02 + assert doc["artifacts"] is None # not the earlier run's file + assert doc["error"]["code"] == "infra" and doc["error"]["retryable"] is True # the exit is 5 (infra) + + +def test_a_finished_novelty_run_costs_the_judge2_regrade_too(tmp_path, capsys): + # payload["cost"] rolls up the pipeline's roles only; the --judge2 regrade's calls live in the clients + state = {"payload": {"cost": {"usd": 0.01, "llm_calls": 1}}, "partial": False, "out": tmp_path / "novelty.json", + "clients": [_SpentClient()]} + novelty_cmd._emit_analyze(argparse.Namespace(artifact="skill:x", max_usd=0.05, json=True), state, None) + + doc = json.loads(capsys.readouterr().out) + assert doc["status"] == "complete" and doc["cost"]["calls"] == 2 and doc["cost"]["spent_usd"] == 0.02 + + +def test_skill_sensitivity_whose_saved_result_failed_is_a_failed_document(tmp_path, capsys): + from dokimi.commands import skill_sensitivity as sens + + payload = {"status": "failed", "cost": {"usd": 0.0, "llm_calls": 3}} + state = {"payload": payload, "out": tmp_path / "sensitivity.json"} + sens._emit(argparse.Namespace(artifact="skill:x", max_usd=None, json=True), state, + SystemExit("Model call failures left no shared queries for a measurement.")) + + doc = json.loads(capsys.readouterr().out) + assert doc["status"] == "failed" and doc["cost"]["calls"] == 3 + + +def test_catalog_routing_a_write_failing_after_the_calls_keeps_their_cost(monkeypatch, capsys): + from dokimi.commands import novelty_routing as nr + + def wrote_nothing(args): + args.cost_clients = [_SpentClient()] + raise OSError("read-only file system") + + monkeypatch.setattr(nr, "cmd_routing", wrote_nothing) + args = argparse.Namespace(max_usd=None, json=True) + + with pytest.raises(OSError): + nr.cmd_catalog_routing(args) + + doc = json.loads(capsys.readouterr().out) + assert doc["status"] == "failed" and doc["cost"]["calls"] == 2 and doc["cost"]["spent_usd"] == 0.02 + + +def test_a_crash_after_the_document_is_printed_leaves_one_document_and_exits_5(tmp_path, monkeypatch, capsys): + """Through cli.main: the write failure's document is the only one on stdout (cli.py's crash handler does not + print a second), and the exit is the crash's exit 5.""" + + def wrote_nothing(_args, state): + state.update(payload={"cost": {"usd": 0.02, "llm_calls": 2}}, partial=False, out=tmp_path / "x.json") + state["clients"] = [_SpentClient()] + raise OSError("read-only file system") + + monkeypatch.setattr(novelty_cmd, "_novelty_analyze", wrote_nothing) + code, doc = _cli(monkeypatch, capsys, "skill", "novelty", "analyze", "--artifact", _skill(tmp_path), "--json") + + assert code == 5 and doc["status"] == "failed" and doc["cost"]["calls"] == 2 diff --git a/dokimi/tests/test_cli_json_paid.py b/dokimi/tests/test_cli_json_paid.py index d8f1a88e4..4c556aa89 100644 --- a/dokimi/tests/test_cli_json_paid.py +++ b/dokimi/tests/test_cli_json_paid.py @@ -434,7 +434,8 @@ def caller(item): assert code == 2 and doc["status"] == "failed" and doc["error"]["code"] == "input" assert doc["cost"]["calls"] == 40 and doc["cost"]["spent_usd"] == pytest.approx(0.04) - assert doc["next"] == [] + assert len(doc["next"]) == 1 and doc["next"][0]["argv"] == ["dokimi", "tools", "preference", "--help"] + assert doc["next"][0]["spends"] is False and doc["next"][0]["est_usd"] == 0 def test_tools_preference_a_run_whose_calls_all_fail_json_exits_1_with_the_payload(monkeypatch, capsys, tmp_path): diff --git a/dokimi/tests/test_cli_output.py b/dokimi/tests/test_cli_output.py index da496c963..baf2d5aeb 100644 --- a/dokimi/tests/test_cli_output.py +++ b/dokimi/tests/test_cli_output.py @@ -651,6 +651,9 @@ def test_a_leaf_usage_error_without_json_prints_its_message_on_stderr_only(monke ("runs", "baseline", "list"), ("runs", "baseline", "rm"), ("runs", "baseline", "save"), ("skill", "routing"), ("trace", "consistency"), ("trace", "inspect"), ("trace", "prefilter"), ("eval", "personas", "discover"), ("eval", "skill-coverage"), ("tools", "preference"), + # F2 slice 2 (#94): paid leaves; a success prints no `next`, an input error prints the help step + ("catalog", "routing"), ("eval", "questions", "analyze"), ("eval", "questions", "review"), + ("skill", "novelty", "analyze"), ("skill", "sensitivity"), }