Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions dokimi/changelog.d/20261205_120000_cli-paid-guards-4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### Added

- **`eval triggers generate --rewrite` can be priced before it spends.** `--dry-run` prices one rewrite call per question at list prices and prints the estimate. It builds no model client, calls no model and writes no set. Without `--rewrite` it makes no model call and says so. The estimate assumes 200 reply tokens per rewrite.

- **`eval triggers generate --rewrite --max-usd X`.** A real run exits 3 before its first call and builds no client if the estimate exceeds the cap or the model has no list price. A stop mid-run exits 1 and writes no set. `--max-usd` without `--rewrite` is an input error (exit 2).

### Changed

- **`--max-usd` holds each call's estimate while the call is in flight.** A call's list-price estimate is reserved from the cap until the call finishes, so calls running together under `--concurrency` cannot pass the cap between them. A call that raises gives its reservation back. This applies to `eval questions analyze` and `eval questions review`; the other metered leaves keep check-then-record.

- **The cap refusal names only the flags the leaf has.** The refusal said `--tier` and `--max-atoms` on every leaf. Now `--tier` and `--max-atoms` are named only on the novelty leaves that take them; the other leaves get "measure less".
2 changes: 2 additions & 0 deletions dokimi/docs/reference/cli-interface.json
Original file line number Diff line number Diff line change
Expand Up @@ -1345,9 +1345,11 @@
"allow_abbrev": true,
"params": [
{"key": "--catalog", "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": true, "type": null},
{"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": "--fail-on", "action": "_StoreAction", "choices": ["'warn'"], "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": "--format", "action": "_StoreAction", "choices": ["'questions'", "'reach'", "'skill-creator'"], "const": null, "default": "reach", "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": "--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": null, "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": true, "type": null},
{"key": "--questions", "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},
Expand Down
34 changes: 10 additions & 24 deletions dokimi/dokimi/commands/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@
import argparse
import json
import sys
from collections.abc import Callable
from functools import cache
from pathlib import Path

from dokimi.cli_model_ref import add_model_flag
from dokimi.cli_types import positive_usd
from dokimi.commands.catalog_rewrite import build_queries
from dokimi.commands.catalog_scan import (
ROW_STATES, fail_on_reason, fails_on_finding, is_plain_markdown, listing_failed, listing_message, listing_tally, not_checked, row_ignore,
ok_text, plain_note, print_skill_row, skill_row, skipped_note, unrestricted_and_risky,
)
from dokimi.external.catalog_rates import RateTally, text_lines
from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES, is_litellm_route
from dokimi.files import InputError
from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES, is_litellm_route


def _print_strict_reasons(rows: list, strict: bool) -> None:
Expand Down Expand Up @@ -415,24 +415,6 @@ def _trigger_rewrite_model(model: str, provider: str, *, named: bool) -> tuple[s
return model, provider


def _trigger_rewriter(args: argparse.Namespace, prompt: str) -> Callable[[str], str] | None:
if not args.rewrite:
return None
if not args.model:
raise InputError("--rewrite needs --model")
from dokimi.llm import llm_call

@cache
def rewrite_model() -> tuple[str, str]:
return _trigger_rewrite_model(args.model, args.provider, named=args.rewrite_provider_named)

def rewrite(text: str) -> str:
model, provider = rewrite_model()
return llm_call(prompt + text, model=model, provider=provider)

return rewrite


def cmd_catalog_trigger_set(args: argparse.Namespace) -> None:
import json

Expand All @@ -458,10 +440,8 @@ def cmd_catalog_trigger_set(args: argparse.Namespace) -> None:
specs = list(args.questions or []) + [
None if args.format == "questions" else spec for spec in (args.trigger_set or [])]

rewrite = _trigger_rewriter(args, ts.REWRITE_PROMPT)

try:
queries = ts.build_trigger_set(sources, catalog, rewrite=rewrite, specs=specs)
queries = build_queries(args, sources, catalog, specs, _trigger_rewrite_model)
except (ts.TriggerSetInputError, InputError) as exc:
raise InputError(str(exc)) from exc
except ValueError as exc:
Expand Down Expand Up @@ -777,6 +757,12 @@ def register(sub, positive_int, eval_sub) -> None:
ts_p.add_argument("--target", help="Target skill for --format skill-creator")
ts_p.add_argument("--rewrite", action="store_true",
help="Rewrite each question into first-person user voice (model sees only the question)")
ts_p.add_argument("--max-usd", type=positive_usd, default=None, dest="max_usd", metavar="X",
help=("With --rewrite: refuse before the first call if the cost estimate exceeds the cap or has "
"no list price (USD, exit 3). A mid-run stop exits 1 and writes no set."))
cli_flags.add(ts_p, "dry_run", "--dry-run", action="store_true", dest="dry_run",
help="With --rewrite: price the rewrite calls at list prices and print the estimate; call no "
"model, build no client, write nothing")
add_model_flag(
ts_p, "--model", dest="model", provider_dest="provider",
providers=(*ANSWER_PROVIDERS, *PROVIDER_ALIASES), named_dest="rewrite_provider_named",
Expand Down
8 changes: 6 additions & 2 deletions dokimi/dokimi/commands/catalog_novelty.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,8 @@ def _review_one(item: _Item, *, args: argparse.Namespace, run_cap: "SpendCap", p

if run_cap.spent:
return None
cap = NestedSpendCap(limit_usd=per_skill, parent=run_cap, hard_stop=hard_stop)
cap = NestedSpendCap(limit_usd=per_skill, parent=run_cap, hard_stop=hard_stop,
measure_less=run_cap.measure_less)

def row(status: str, **fields: Any) -> dict:
return make_row(key=item.key, name=item.name, path=str(item.skill_md),
Expand Down Expand Up @@ -460,7 +461,10 @@ def cmd_catalog_novelty(args: argparse.Namespace) -> None:
kept, todo, others = _plan(items, all_items, jsonl, args, fingerprint)
print(f"# catalog novelty: {len(items)} skills under {root}; {len(kept)} measured and kept, "
f"{len(todo)} to run", file=sys.stderr)
run_cap = SpendCap(limit_usd=args.max_usd, max_calls=getattr(args, "max_calls", None))
from dokimi.novelty.cost import measure_less

run_cap = SpendCap(limit_usd=args.max_usd, max_calls=getattr(args, "max_calls", None),
measure_less=measure_less(args))
per = f", ${args.max_usd_per_skill:g} per skill" if args.max_usd_per_skill else ""
whole = " and ".join(([f"${args.max_usd:g}"] if args.max_usd is not None else [])
+ ([f"{args.max_calls} calls"] if getattr(args, "max_calls", None) else []))
Expand Down
103 changes: 103 additions & 0 deletions dokimi/dokimi/commands/catalog_rewrite.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""The ``--rewrite`` calls of ``eval triggers generate``: priced under ``--dry-run``, capped by ``--max-usd``.

Part of #94 (F1b, spend: paid-guards slice 4). The command's flags and writes stay in
:mod:`dokimi.commands.catalog`; this module owns what a rewrite costs and when it may run.
"""

from __future__ import annotations

import argparse
import sys
from collections.abc import Callable
from functools import cache

from dokimi import spend_preview
from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE
from dokimi.files import InputError
from dokimi.spend import SpendCap, SpendCapReached

# A rewrite's reply is one short first-person question: 200 tokens is the assumption the estimate prices.
REWRITE_REPLY_TOKENS = 200

Check warning on line 23 in dokimi/dokimi/commands/catalog_rewrite.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `200` -> `201`


# The provider resolver of ``eval triggers generate`` (catalog's ``_trigger_rewrite_model``), passed in: this module
# is imported by the command module, so it cannot import that module back.
Resolver = Callable[..., tuple[str, str]]


def build_queries(args: argparse.Namespace, sources, catalog, specs, resolve: Resolver):
"""The trigger set with its --rewrite calls priced and capped. A dry run exits 0 before any call is made.

A stop at the --max-usd cap exits 1 here: the set is written after the last rewrite, so no file is left.
"""
from dokimi.external import trigger_set as ts

check_rewrite_flags(args)

Check warning on line 38 in dokimi/dokimi/commands/catalog_rewrite.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `check_rewrite_flags(args)` -> `pass`
if args.rewrite and (args.dry_run or args.max_usd is not None):

Check warning on line 39 in dokimi/dokimi/commands/catalog_rewrite.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `args.rewrite and (args.dry_run or args.max_usd is not None)` -> `(args.dry_run or args.max_usd is not None)`
rewrite_gate(args, sources, catalog, specs, resolve)
cap = SpendCap(args.max_usd) if args.max_usd is not None else None

Check warning on line 41 in dokimi/dokimi/commands/catalog_rewrite.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `SpendCap(args.max_usd) if args.max_usd is not None else None` -> `(None)`
rewrite = trigger_rewriter(args, ts.REWRITE_PROMPT, resolve, cap)
try:
return ts.build_trigger_set(sources, catalog, rewrite=rewrite, specs=specs)
except SpendCapReached as exc:
print(f"Error: the --max-usd cap was reached: {exc}", file=sys.stderr)
sys.exit(EXIT_FAILURE)


def check_rewrite_flags(args: argparse.Namespace) -> None:
"""Refuse a bad combination of --rewrite flags before any call; a dry run without --rewrite exits 0 here."""
if args.max_usd is not None and not args.rewrite:

Check warning on line 52 in dokimi/dokimi/commands/catalog_rewrite.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `args.max_usd is not None and not args.rewrite` -> `(args.max_usd is not None)`
raise InputError("--max-usd needs --rewrite: a trigger set makes no model call without it")
if args.dry_run and not args.rewrite:

Check warning on line 54 in dokimi/dokimi/commands/catalog_rewrite.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `args.dry_run and not args.rewrite` -> `(args.dry_run)`
print("Dry run: no --rewrite, so the trigger set makes no model call; nothing is written.")
sys.exit(0)
if args.rewrite and not args.model:
raise InputError("--rewrite needs --model")


def trigger_rewriter(args: argparse.Namespace, prompt: str, resolve: Resolver,
cap: SpendCap | None = None) -> Callable[[str], str] | None:
if not args.rewrite:
return None
from dokimi.llm import llm_call, llm_call_with_usage

@cache
def rewrite_model() -> tuple[str, str]:
return resolve(args.model, args.provider, named=args.rewrite_provider_named)

def rewrite(text: str) -> str:
model, provider = rewrite_model()
if cap is None:
return llm_call(prompt + text, model=model, provider=provider)
# Under --max-usd: the cap is checked before the call and the call's usage is counted after it.
cap.before_call(model)
reply, usage = llm_call_with_usage(prompt + text, model=model, provider=provider)
cap.record(usage, model)
return reply

return rewrite


def price_rewrites(args: argparse.Namespace, sources, catalog, specs, resolve: Resolver) -> str | None:
"""Price the --rewrite calls before any is made: one per question. Returns the gate verdict (None: go ahead)."""
from dokimi.external import trigger_set as ts

# Client-free: labels and lint only, the rewrite step is left out.
queries = ts.build_trigger_set(sources, catalog, rewrite=None, specs=specs)
model, provider = resolve(args.model, args.provider, named=args.rewrite_provider_named)
prompts = [ts.REWRITE_PROMPT + q.text for q in queries]
return spend_preview.gate(lambda: prompts, model=model, provider=provider, reply_tokens=REWRITE_REPLY_TOKENS,
dry_run=args.dry_run, max_usd=args.max_usd,
mid_run_stop_note=f"a stop mid-run exits {EXIT_FAILURE} and writes no set")


def rewrite_gate(args: argparse.Namespace, sources, catalog, specs, resolve: Resolver) -> None:
"""Under --dry-run or --max-usd: exit 0 after a dry run, exit 3 when the estimate is refused; otherwise return."""
verdict = price_rewrites(args, sources, catalog, specs, resolve)
if verdict == spend_preview.REFUSED:
sys.exit(EXIT_INCONCLUSIVE)
if verdict == spend_preview.DRY:
sys.exit(0)
5 changes: 1 addition & 4 deletions dokimi/dokimi/commands/questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@
from dokimi.model_names import warn_recorded_self_judge
from dokimi.spend import SpendCap, SpendCapReached

# Reply tokens assumed per call for the --dry-run estimate and the --max-usd check before the first call.
# A classification is a short JSON object; a panel vote is one score per dimension, a reason and flags.
CLASSIFY_REPLY_TOKENS = 400
REVIEW_REPLY_TOKENS = 800
from dokimi.spend_preview import CLASSIFY_REPLY_TOKENS, REVIEW_REPLY_TOKENS


def _load_questions_json(path: str):
Expand Down
18 changes: 10 additions & 8 deletions dokimi/dokimi/novelty/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,27 +73,29 @@

def __init__(self, limit_usd: float | None, spent_usd: float = 0.0, calls: int = 0, *,
parent: SpendCap | None = None, hard_stop: threading.Event | None = None,
**counts: int) -> None:
super().__init__(limit_usd, spent_usd, calls, **counts)
measure_less: str = "measure less", **counts: int) -> None:
super().__init__(limit_usd, spent_usd, calls, measure_less=measure_less, **counts)
self.parent, self.hard_stop = parent, hard_stop

def before_call(self, model: str, *, reserve: bool = True) -> None:
def before_call(self, model: str, *, reserve: bool = True, reserve_usd: float = 0.0) -> None:
if self.hard_stop is not None and self.hard_stop.is_set():
raise SpendCapReached(f"stopped by a second signal; not calling {model}", reason="stopped")
super().before_call(model, reserve=reserve)
super().before_call(model, reserve=reserve, reserve_usd=reserve_usd)
if self.parent is not None:
try:
self.parent.before_call(model, reserve=reserve)
self.parent.before_call(model, reserve=reserve, reserve_usd=reserve_usd)
except SpendCapReached:
if reserve:
with self._lock:
self.release_call() # the call is not made: its slot here is free again
self._release_usd_locked(reserve_usd)

Check warning on line 91 in dokimi/dokimi/novelty/client.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `self._release_usd_locked(reserve_usd)` -> `pass`
raise

def record(self, usage: UsageRecord | None, model: str, *, reserved: bool = True) -> None:
def record(self, usage: UsageRecord | None, model: str, *, reserved: bool = True,

Check warning on line 94 in dokimi/dokimi/novelty/client.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `True` -> `False`
reserve_usd: float = 0.0) -> None:
if self.parent is not None:
self.parent.record(usage, model, reserved=reserved)
super().record(usage, model, reserved=reserved)
self.parent.record(usage, model, reserved=reserved, reserve_usd=reserve_usd)
super().record(usage, model, reserved=reserved, reserve_usd=reserve_usd)


@dataclass
Expand Down
9 changes: 8 additions & 1 deletion dokimi/dokimi/novelty/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,13 @@
"price per call. Cap the run with --max-calls N instead, or use an API provider")


def measure_less(args: argparse.Namespace) -> str:
"""What a cap refusal suggests besides a higher ``--max-usd``: only the cost flags this leaf has."""
flags = [text for name, text in (("tier", "a cheaper --tier"), ("max_atoms", "a lower --max-atoms"))
if hasattr(args, name)]

Check warning on line 225 in dokimi/dokimi/novelty/cost.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-filter `hasattr(args, name)` -> `True`
return f"measure less ({', '.join(flags)})" if flags else "measure less"

Check warning on line 226 in dokimi/dokimi/novelty/cost.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `f"measure less ({', '.join(flags)})" if flags else "measure less"` -> `None`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix (blocking): If measure_less returns None, the tests still pass, so no test reads the hint a novelty leaf gets, and its cap refusal would end in or None.
If I change the return at dokimi/dokimi/novelty/cost.py:226 to None, the spend and novelty test files in the PR's list all still pass (131 tests).

Suggestion: Add a test that runs a novelty leaf over its --max-usd and asserts the refusal names the cost flags that leaf takes, the way tests/test_triggers_dry_run_and_cap.py checks the trigger leaf.

Details

A novelty leaf's cap refusal would then end with or None. The PR's tests check the hint only for the trigger leaf and for a hint passed in directly, so nothing reads the novelty text. I'd expect a test to read a novelty leaf's hint, since that is the line a user sees when the cap is hit.



def spend_cap(args: argparse.Namespace, provider: str | None = None):
"""The invocation's one cap (``--max-usd``, ``--max-calls`` or both), shared by every role client.

Expand All @@ -237,7 +244,7 @@
return args._spend_cap
if limit is None and max_calls is None:
return None
args._spend_cap = SpendCap(limit_usd=limit, max_calls=max_calls)
args._spend_cap = SpendCap(limit_usd=limit, max_calls=max_calls, measure_less=measure_less(args))
return args._spend_cap


Expand Down
28 changes: 23 additions & 5 deletions dokimi/dokimi/questions/metered.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,42 @@
from dokimi.spend import Spend, SpendCap



class MeteredCalls:
"""One analyzer run's model calls: the usage of each is added to ``spend`` and, with a cap, checked first."""
"""One analyzer run's model calls: the usage of each is added to ``spend`` and, with a cap, checked first.

With a cap, a call's list-price estimate (``reply_tokens`` assumed back) is held from the cap while the call
is in flight, so ``--concurrency`` calls cannot pass ``--max-usd`` together; a call that raises gives it back.
"""

def __init__(self, model: str, provider: str, cap: Optional[SpendCap]):
def __init__(self, model: str, provider: str, cap: Optional[SpendCap], reply_tokens: int = 0):
self.model = model
self.provider = provider
self.cap = cap
self.reply_tokens = reply_tokens
self.spend = Spend()
self._lock = threading.Lock()

def _estimate(self, prompt: str) -> float:
"""The call's list price, as ``spend_preview`` prices it; 0 when it has none (the cap refuses that on record)."""
from dokimi.spend_preview import price_calls

return price_calls([prompt], self.model, self.provider, self.reply_tokens)["usd"] or 0.0

def __call__(self, prompt: str,
call: Callable[..., Tuple[str, UsageRecord]]) -> str:
"""Make one call through ``call`` (the caller passes its ``llm_call_with_usage``) and return the reply text."""
held = self._estimate(prompt) if self.cap is not None and self.cap.limit_usd is not None else 0.0
if self.cap is not None:
self.cap.before_call(self.model)
text, usage = call(prompt, model=self.model, provider=self.provider)
self.cap.before_call(self.model, reserve_usd=held)
try:
text, usage = call(prompt, model=self.model, provider=self.provider)
except BaseException:
if self.cap is not None:
self.cap.release_usd(held)
raise
with self._lock:
self.spend.add_call(usage)
if self.cap is not None:
self.cap.record(usage, self.model)
self.cap.record(usage, self.model, reserve_usd=held)
return text
Loading
Loading