release: Themiz на Gitea

This commit is contained in:
public-repo-gate
2026-10-19 11:10:53 +03:00
parent e52e76d4ea
commit 067c6c2414
225 changed files with 240125 additions and 26157 deletions
+461 -73
View File
@@ -15,20 +15,22 @@
token_ledger.py # свежая сессия активного провайдера в cwd
token_ledger.py SESSION.jsonl # конкретная сессия
token_ledger.py --all # все сессии проекта, сводно
token_ledger.py --track FAST # + вердикт по цели трека (exit 3 при перерасходе)
token_ledger.py --track FAST # + отчет по цели; стоп лишь при THEMIZ_TOKEN_LIMITS=1
token_ledger.py --ctx-limit 150000 # потолок контекста запроса (exit 3 при пробое, 0 — выкл)
token_ledger.py --provider codex # текущая Codex-сессия: cumulative tokens, без цены
token_ledger.py --provider kimi # текущая Kimi-сессия: сумма step.end, без цены
token_ledger.py --json # машинный вывод
token_ledger.py --selftest # проверка без сети и без реальных сессий
Колонка «преамбула × вызовы» (M08): пол контекста потока (минимальный контекст его
запроса) × число вызовов = счет за повторную доставку одного и того же. Цифра из
журнала, нижняя граница. Считает context_ledger; здесь — свод по потокам и потолок
контекста фазы: превышение — ненулевой код, а не молчание.
контекста фазы: превышение дает ненулевой код лишь при явно включенном потолке.
"""
from __future__ import annotations
import glob
import hashlib
import json
import os
import re
@@ -38,22 +40,22 @@ from collections import defaultdict
from pathlib import Path
import _obshee as obs
import cli_registry
try:
from swarm_contract import SUBST_RE as _SUBST_RE
except ImportError: # прибор лежит рядом; его отсутствие не роняет замер расхода
_SUBST_RE = None
# Цена за миллион токенов: [input, output, cache-write, cache-read]
RATES = {
"opus": [15.0, 75.0, 18.75, 1.50],
"sonnet": [3.0, 15.0, 3.75, 0.30],
"haiku": [1.0, 5.0, 1.25, 0.10],
}
# Цена за миллион токенов: [input, output, cache-write, cache-read].
RATES = cli_registry.token_rates()
_TEST_RATE_MODELS = tuple(sorted(RATES, key=lambda key: RATES[key][0], reverse=True))
MAX_RATE_KEY = _TEST_RATE_MODELS[0]
# Политика Фемиды: рабочие лимиты поставляются подпиской, не API-долларами.
# Тарифы ниже оставлены исключительно для явного разбора старых Claude-журналов.
SUBSCRIPTION_ONLY = True
TOKEN_LIMITS_ENABLED = os.environ.get("THEMIZ_TOKEN_LIMITS") == "1"
# Пороги трека — ИЗМЕРЕННЫЕ базовые линии по 26 сессиям проекта на 03.08.2026,
# всего токенов (input + output + cache-write + cache-read).
@@ -124,7 +126,7 @@ MAIN_SIGNALS = [
(r"quality_gate|document_guard|table_guard|verify_inn|verify_act|crosscheck_numbers|"
r"sroki|02_hearings/", "5 проверка"),
(r"_index\.md|_clients\.md|_client\.md|registry_check|redline", "6 архив"),
(r"themiz_status|token_ledger|retro\.py|setup_doctor|pd_guard|claude_guard|preflight_search|"
(r"themiz_status|token_ledger|retro\.py|setup_doctor|pd_guard|themiz_guard|claude_guard|preflight_search|"
r"update_legal_corpus|lessons-log|_logs/|scripts/|\.claude/", "система"),
]
@@ -138,19 +140,19 @@ STEP_ORDER = ["основной поток", "0 интейк", "1 карта", "
"4 составление", "5 проверка", "6 архив", "система", "прочее"]
ROLE_LIMITS_PATH = obs.dom_proekta() / "config" / "limity_roley.json"
MEASUREMENT_GLOB = "docs/remont/zamer/*.json"
# Неизвестная модель. Прежде любая строка без opus|sonnet|haiku молча считалась
# по верхней ставке и складывалась в строку «opus» — в логах проекта такой была
# claude-fable-5 (1356 вызовов, 73,1 млн токенов, 5,0 % свода). Прибор при этом
# показывал «opus», и понять, что это другая модель, было нельзя ни по одной цифре.
# Неизвестная модель прежде молча считалась по верхней ставке и
# складывалась в ее строку. Прибор скрывал сам факт
# подмены: по цифрам нельзя было понять, что в журнале другая модель.
# Оценка по верхней ставке остается (занижать расход опаснее, чем завышать), но
# СТРОКА В РАЗРЕЗЕ теперь своя, с явной пометкой, что цена — верхняя оценка.
UNKNOWN_PREFIX = "неизвестная: "
def model_key(model: str) -> str:
"""Ключ разреза. Неизвестная модель — собственная строка, а не «opus»."""
"""Ключ разреза. Неизвестная модель получает собственную строку."""
ml = (model or "").lower()
for k in RATES:
if k in ml:
@@ -164,7 +166,7 @@ def rate_key(model_or_key: str) -> str:
for k in RATES:
if k in ml:
return k
return "opus"
return MAX_RATE_KEY
def cost(u: dict, model: str) -> float:
@@ -437,6 +439,209 @@ def tokens(u: dict) -> int:
return u["in"] + u["out"] + u["cw"] + u["cr"]
def adapter_usage(value: object, calls: int = 0) -> dict:
"""Normalize provider-reported usage without applying another provider's tokenizer."""
result = {"input": None, "output": None, "cache_write": None,
"cache_read": None, "tokens": None, "calls": calls, "measured": False}
if value is None:
return result
if isinstance(value, bool):
raise ValueError("usage cannot be boolean")
if isinstance(value, int):
if value < 0:
raise ValueError("usage cannot be negative")
return {**result, "tokens": value, "measured": True}
if not isinstance(value, dict):
raise ValueError("usage must be an object or integer")
nested_total = value.get("total_token_usage")
if isinstance(nested_total, dict):
value = {**nested_total, **value}
aliases = {
"input": ("input", "in", "input_tokens", "inputOther"),
"output": ("output", "out", "output_tokens"),
"cache_write": ("cache_write", "cw", "cache_creation_input_tokens",
"inputCacheCreation"),
"cache_read": ("cache_read", "cr", "cache_read_input_tokens", "inputCacheRead"),
}
found = False
for target, names in aliases.items():
raw = next((value[name] for name in names if name in value), None)
if raw is None:
continue
if isinstance(raw, bool) or not isinstance(raw, int) or raw < 0:
raise ValueError(f"usage.{target} must be a non-negative integer")
result[target], found = raw, True
raw_total = next((value[name] for name in ("tokens", "total", "total_tokens")
if name in value), None)
if raw_total is not None:
if isinstance(raw_total, bool) or not isinstance(raw_total, int) or raw_total < 0:
raise ValueError("usage.tokens must be a non-negative integer")
result["tokens"], found = raw_total, True
elif found:
result["tokens"] = sum(result[name] or 0 for name in aliases)
raw_calls = value.get("calls", calls)
if isinstance(raw_calls, bool) or not isinstance(raw_calls, int) or raw_calls < 0:
raise ValueError("usage.calls must be a non-negative integer")
result["calls"], result["measured"] = raw_calls, found
return result
def _attempt_id(run_id: str, kind: str, index: int, item: dict) -> str:
explicit = item.get("attempt_id")
if isinstance(explicit, str) and explicit:
return explicit
packed = json.dumps(item, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(f"{run_id}\0{kind}\0{index}\0{packed}".encode()).hexdigest()[:24]
return f"{kind}-{digest}"
def _usage_index(journal: dict, source: str) -> dict[tuple[str, str], dict]:
"""Usage may be embedded in an event or supplied as normalized adapter records."""
candidates = []
for key in ("usage_records", "usage"):
value = journal.get(key)
if isinstance(value, list):
candidates.extend(value)
elif isinstance(value, dict) and isinstance(value.get("records"), list):
candidates.extend(value["records"])
ledger = journal.get("token_ledger")
if isinstance(ledger, dict) and isinstance(ledger.get("records"), list):
candidates.extend(ledger["records"])
result = {}
for item in candidates:
if not isinstance(item, dict):
raise ValueError(f"{source}: usage record must be an object")
run_id, attempt_id = item.get("run_id"), item.get("attempt_id")
if not isinstance(run_id, str) or not run_id:
raise ValueError(f"{source}: usage record has no run_id")
if not isinstance(attempt_id, str) or not attempt_id:
raise ValueError(f"{source}: usage record has no attempt_id")
key = (run_id, attempt_id)
if key in result:
raise ValueError(f"{source}: duplicate usage key {run_id}/{attempt_id}")
result[key] = item
return result
def _journal_records(journal: dict, source: str) -> list[dict]:
journal_cli = journal.get("cli")
pipeline_report = journal.get("pipeline_report")
runs = pipeline_report.get("runs", []) if isinstance(pipeline_report, dict) else []
if not runs and isinstance(journal.get("pipeline"), dict):
runs = [journal["pipeline"]]
if not isinstance(runs, list):
return []
usage_by_attempt = _usage_index(journal, source)
records = []
joined_usage = set()
run_clis = {}
for run in runs:
if (not isinstance(run, dict) or not isinstance(run.get("run_id"), str)
or not run["run_id"]):
continue
run_id = run["run_id"]
cli = run.get("cli") or journal_cli
if not isinstance(cli, str) or not cli:
continue
run_clis[run_id] = cli
events = run.get("events", []) if isinstance(run.get("events"), list) else []
for index, event in enumerate(events):
if not isinstance(event, dict) or not isinstance(event.get("step"), str):
continue
attempt_id = _attempt_id(run_id, "event", index, event)
calls = event.get("llm_calls", 0)
calls = calls if isinstance(calls, int) and not isinstance(calls, bool) and calls >= 0 else 0
usage_key = (run_id, attempt_id)
adapter_record = usage_by_attempt.get(usage_key, {})
raw_usage = event.get("usage", adapter_record.get("usage", adapter_record.get("tokens")))
joined_usage.add(usage_key)
records.append({
"cli": cli, "run_id": run_id, "attempt_id": attempt_id,
"step": event["step"], "status": event.get("status", "attempted"),
"at": event.get("at"), "usage": adapter_usage(raw_usage, calls),
"source": source,
})
# Stops and resolved refusals are attempts too. Stable derived IDs keep retries distinct.
for kind, status in (("stops", "stopped"), ("refusals", "refused")):
values = journal.get(kind, [])
if not isinstance(values, list):
continue
for index, item in enumerate(values):
if not isinstance(item, dict) or not isinstance(item.get("step"), str):
continue
item_run = item.get("run_id")
if item_run is not None and item_run != run_id:
continue
if item_run is None and len(runs) != 1:
raise ValueError(f"{source}: {status} attempt has no run_id")
attempt_id = _attempt_id(run_id, status, index, item)
usage_key = (run_id, attempt_id)
adapter_record = usage_by_attempt.get(usage_key, {})
joined_usage.add(usage_key)
records.append({
"cli": cli, "run_id": run_id, "attempt_id": attempt_id,
"step": item["step"], "status": status, "at": item.get("time"),
"usage": adapter_usage(item.get(
"usage", adapter_record.get("usage", adapter_record.get("tokens")))),
"source": source,
})
for (run_id, attempt_id), item in usage_by_attempt.items():
if (run_id, attempt_id) in joined_usage:
continue
cli, step = item.get("cli") or run_clis.get(run_id) or journal_cli, item.get("step")
if not isinstance(cli, str) or not cli:
raise ValueError(f"{source}: usage record has no cli")
if not isinstance(step, str) or not step:
raise ValueError(f"{source}: usage record has no step")
records.append({
"cli": cli, "run_id": run_id, "attempt_id": attempt_id,
"step": step, "status": item.get("status", "attempted"),
"at": item.get("at"),
"usage": adapter_usage(item.get("usage", item.get("tokens")), item.get("calls", 0)),
"source": source,
})
return records
def adapter_usage_report(root: Path | None = None) -> dict:
"""Join adapter journals by run_id and attempt_id; every retry remains one record."""
root = Path(root or obs.dom_proekta())
paths = sorted(root.glob(MEASUREMENT_GLOB))
paths += sorted(root.glob("cases/*/*/.agent/context/run.json"))
records, seen, clis = [], {}, set()
for path in paths:
try:
journal = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ValueError(f"{path.relative_to(root).as_posix()}: journal not read: {exc}") from exc
if not isinstance(journal, dict):
raise ValueError(f"{path.relative_to(root).as_posix()}: journal must be an object")
if isinstance(journal.get("cli"), str) and journal["cli"]:
clis.add(journal["cli"])
for record in _journal_records(journal, path.relative_to(root).as_posix()):
clis.add(record["cli"])
key = (record["run_id"], record["attempt_id"])
if key in seen:
if ({name: value for name, value in seen[key].items() if name != "source"}
!= {name: value for name, value in record.items() if name != "source"}):
raise ValueError(f"duplicate attempt key {key[0]}/{key[1]}")
continue
seen[key] = record
records.append(record)
records.sort(key=lambda item: (item["cli"], item["run_id"], item.get("at") or "",
item["attempt_id"]))
totals = {}
for record in records:
total = totals.setdefault(record["cli"], {"tokens": 0, "measured_attempts": 0,
"attempts": 0})
total["attempts"] += 1
if record["usage"]["measured"]:
total["tokens"] += record["usage"]["tokens"]
total["measured_attempts"] += 1
return {"schema": 1, "key": ["run_id", "attempt_id"], "clis": sorted(clis),
"records": records, "totals": totals}
def load_role_limits(path: str | os.PathLike[str] | None = None) -> dict[str, int]:
"""Прочитать положительные целые потолки ролей из JSON-конфигурации."""
source = path or ROLE_LIMITS_PATH
@@ -462,7 +667,7 @@ def role_warnings(by_role: dict[str, dict], limits: dict[str, int]) -> list[str]
spent_text = f"{spent:,}".replace(",", " ")
if role in ("", "?"):
warnings.append(
f"СТОП: запись расхода не называет роль (role={role!r}, потрачено "
f"⚠ запись расхода не называет роль (role={role!r}, потрачено "
f"{spent_text} токенов); нужно машинное поле agentType/attributionAgent.")
elif role not in limits:
warnings.append(f"⚠ РОЛЬ БЕЗ ЛИМИТА: {role}; потрачено {spent_text} токенов.")
@@ -557,7 +762,8 @@ def render(rep: dict, track: str | None, ctx_limit: int = 0) -> int:
if unknown:
n = sum(tokens(v) for v in unknown.values())
print(f"⚠ модель вне тарифной таблицы: {n:,} токенов ({n/total_tok*100:.1f}%). "
"Цена по ним — ВЕРХНЯЯ оценка (ставка opus). Внести тариф в RATES.")
f"Цена по ним — ВЕРХНЯЯ оценка (ставка {MAX_RATE_KEY}). "
"Внести тариф в реестр CLI.")
# Подмена модели харнессом — ОТДЕЛЬНАЯ строка разреза, не растворена в строке
# фактически сработавшей модели: 15 подмен за прогон 01.09 были невидимы.
@@ -570,7 +776,7 @@ def render(rep: dict, track: str | None, ctx_limit: int = 0) -> int:
rc = 0
if track:
if SUBSCRIPTION_ONLY:
if not TOKEN_LIMITS_ENABLED:
text, rc = track_note(track, tokens(t)), obs.KOD_OK
else:
text, rc = track_verdict(track, tokens(t))
@@ -578,9 +784,7 @@ def render(rep: dict, track: str | None, ctx_limit: int = 0) -> int:
ctext, crc = ctx_verdict(rep.get("max_ctx", 0), ctx_limit)
if ctext:
print(ctext)
role_rc = obs.KOD_STOP if any(w.startswith("СТОП:")
for w in rep.get("role_warnings", [])) else 0
return max(rc, crc, role_rc)
return max(rc, crc)
def track_verdict(track: str, spent: int) -> tuple[str, int]:
@@ -621,13 +825,30 @@ def latest_session(cwd: str) -> str | None:
def active_provider(explicit: str = "auto") -> str:
"""Явный выбор сильнее среды; Codex активен только с session/thread id."""
if explicit in ("codex", "claude"):
"""Явный выбор сильнее признаков активной сессии из реестра CLI."""
registry = {name: entry for name, entry in cli_registry.load().items()
if isinstance(entry, dict) and entry.get("enabled") is not False}
if explicit in registry:
return explicit
if explicit != "auto":
raise ValueError(f"неизвестный провайдер: {explicit}")
return "codex" if (os.environ.get("CODEX_THREAD_ID")
or os.environ.get("CODEX_SESSION_ID")) else "claude"
active = []
for name, entry in registry.items():
markers = entry.get("session_env", ())
if (not isinstance(markers, (list, tuple))
or not all(isinstance(marker, str) and marker for marker in markers)):
raise ValueError(f"{name}: session_env должен быть списком имен")
if any(os.environ.get(marker) for marker in markers):
active.append(name)
if len(active) > 1:
raise ValueError(f"несколько активных CLI: {', '.join(active)}")
if active:
return active[0]
defaults = [name for name, entry in registry.items()
if entry.get("token_ledger_default") is True]
if len(defaults) != 1:
raise ValueError("реестр должен задавать один token_ledger_default")
return defaults[0]
class NoCodexSessions(Exception):
@@ -688,7 +909,7 @@ def _codex_usage(path: str) -> int:
def codex_usage(cwd: str) -> tuple[int, int]:
"""Независимый от token_audit счет latest root-thread Codex и его детей."""
"""Счет latest root-thread Codex и его детей."""
target = os.path.realpath(cwd)
records = []
for path in glob.glob(str(Path.home() / ".codex" / "sessions" / "**" / "*.jsonl"), recursive=True):
@@ -752,19 +973,126 @@ def codex_report(cwd: str) -> dict:
}
def render_codex(rep: dict, track: str | None, ctx_requested: bool) -> int:
print(f"провайдер: Codex сессия: {rep['session']} потоков: {rep['streams']}")
def render_external(rep: dict, track: str | None, ctx_requested: bool) -> int:
"""Вывод подписочного провайдера без цены (Codex, Kimi): только токены."""
label = str(rep.get("provider", "codex")).capitalize()
print(f"провайдер: {label} сессия: {rep['session']} потоков: {rep['streams']}")
print(f"токены: {rep['tokens']:,} ({rep['token_status']})".replace(",", " "))
print("деньги: НЕ ПРИМЕНЯЕТСЯ (подписка Codex, USD не является лимитом)")
print(f"деньги: НЕ ПРИМЕНЯЕТСЯ (подписка {label}, USD не является лимитом)")
print("контекст / модель / роль: ДАННЫХ НЕТ (events не дают нужного разреза)")
rc = obs.KOD_NE_RABOTAL if ctx_requested else obs.KOD_OK
if ctx_requested:
print("потолок контекста: ДАННЫХ НЕТ — проверка не выполнена")
if track:
print(track_note(track, rep["tokens"]))
if TOKEN_LIMITS_ENABLED:
note, track_rc = track_verdict(track, rep["tokens"])
print(note)
rc = max(rc, track_rc)
else:
print(track_note(track, rep["tokens"]))
return rc
def render_codex(rep: dict, track: str | None, ctx_requested: bool) -> int:
return render_external(rep, track, ctx_requested)
class NoKimiSessions(Exception):
"""Нет Kimi-сессий для cwd; Claude-источник не подставляется."""
class CorruptKimiSession(Exception):
"""Выбранный Kimi-журнал не разобран как JSONL или дал нечисловой usage."""
def _kimi_session_dirs(cwd: str) -> list[str]:
"""Каталоги session_* проекта по пути из реестра CLI.
Имя каталога площадки — `wd_<слаг>_<sha256(абсолютный cwd)[:12]>`; слаг не
восстанавливаем, привязка идет по хеш-суффиксу.
"""
key = hashlib.sha256(os.path.abspath(cwd).encode()).hexdigest()[:12]
try:
base = Path.home() / cli_registry.unique("sessions_dir")
except ValueError as exc:
raise NoKimiSessions(str(exc)) from exc
out = []
for wd in glob.glob(str(base / f"wd_*_{key}")):
out.extend(glob.glob(os.path.join(wd, "session_*")))
return [d for d in out if os.path.isdir(d)]
def _kimi_wire_usage(path: str) -> int:
"""Сумма usage по событиям step.end одного wire.jsonl.
Событие несет uuid: повторная запись того же step.end (переоткрытие
сессии) считается один раз, как дубль requestId у Claude.
"""
total = 0
seen = set()
with open(path, encoding="utf-8", errors="replace") as fh:
for line in fh:
if not line.strip():
continue
try:
entry = json.loads(line)
except json.JSONDecodeError as exc:
raise CorruptKimiSession(f"битая JSONL-строка: {os.path.basename(path)}") from exc
if not isinstance(entry, dict) or entry.get("type") != "context.append_loop_event":
continue
event = entry.get("event") or {}
if event.get("type") != "step.end":
continue
uid = event.get("uuid")
if uid in seen:
continue
seen.add(uid)
usage = event.get("usage") or {}
values = [usage.get(k) for k in ("inputOther", "output",
"inputCacheRead", "inputCacheCreation")]
if any(type(v) is not int or v < 0 for v in values):
raise CorruptKimiSession(f"step.end без целого usage: {os.path.basename(path)}")
total += sum(values)
return total
def kimi_usage(cwd: str) -> tuple[int, int]:
"""Сумма usage последней Kimi-сессии проекта по всем агентам (main + субагенты)."""
sessions = _kimi_session_dirs(cwd)
if not sessions:
raise NoKimiSessions(os.path.abspath(cwd))
latest = max(sessions, key=os.path.getmtime)
wires = glob.glob(os.path.join(latest, "agents", "*", "wire.jsonl"))
if not wires:
raise NoKimiSessions(latest)
return sum(_kimi_wire_usage(w) for w in wires), len(wires)
def kimi_report(cwd: str) -> dict:
"""Фактический, но неполный отчёт текущей Kimi-сессии по cwd.
wire.jsonl дает сумму step.end usage по агентам; цены, модели и разреза
контекста там нет. Не переносим туда Claude-оценки.
"""
spent, streams = kimi_usage(cwd)
return {
"provider": "kimi",
"session": "последняя Kimi-сессия по cwd",
"streams": streams,
"tokens": spent,
"token_status": "sum step.end usage (inputOther+output+cache-read+cache-write)",
"money": None,
"money_status": "not_applicable(subscription)",
"context_status": "unknown",
"model_status": "unknown",
"role_status": "unknown",
}
def render_kimi(rep: dict, track: str | None, ctx_requested: bool) -> int:
return render_external(rep, track, ctx_requested)
def selftest() -> int:
"""Проверка без сети: дубли по requestId, вложенные агенты, привязка к шагам."""
with tempfile.TemporaryDirectory() as tmp:
@@ -792,36 +1120,35 @@ def selftest() -> int:
with open(main, "w", encoding="utf-8") as fh:
# одна реплика записана трижды с одним requestId — считается один раз
for _ in range(3):
fh.write(assistant("claude-opus-5", 10, 20, 30, 40, "req_a"))
# Модель вне тарифной таблицы. В логах проекта это claude-fable-5:
# 1356 вызовов, 73,1 млн токенов — и все они молча считались «opus».
fh.write(assistant("claude-fable-5", 5, 6, 7, 8, "req_f"))
fh.write(assistant(_TEST_RATE_MODELS[0], 10, 20, 30, 40, "req_a"))
# Модель вне тарифной таблицы должна остаться отдельной строкой.
fh.write(assistant("fixture-unpriced", 5, 6, 7, 8, "req_f"))
# синтетическая строка не считается вовсе
fh.write(assistant("<synthetic>", 999, 999, 999, 999, "req_syn"))
# прибор дела из главного потока — это шаг протокола, а не «прочее»
fh.write(with_tool("claude-opus-5", 1, 2, 3, 4, "req_b", "Bash",
fh.write(with_tool(_TEST_RATE_MODELS[0], 1, 2, 3, 4, "req_b", "Bash",
{"command": "python3 scripts/registry_check.py"}))
# реплика без своего сигнала остается в текущем шаге
fh.write(assistant("claude-opus-5", 1, 1, 1, 1, "req_h"))
fh.write(assistant(_TEST_RATE_MODELS[0], 1, 1, 1, 1, "req_h"))
fh.write(line(type="user", message={"content": [
{"type": "tool_use", "id": "tu1", "name": "Agent",
"input": {"description": "Картирую дело"}}]}))
fh.write(line(type="user", toolUseResult={
"agentId": "aaa", "agentType": "case-mapper", "toolUseID": "tu1",
"resolvedModel": "claude-opus-5"}))
"resolvedModel": _TEST_RATE_MODELS[0]}))
# харнесс молча подменил недоступную модель — отдельный счетчик разреза
fh.write(line(type="system",
text="claude-sonnet-5[1m] is temporarily unavailable, "
text="fixture-model[1m] is temporarily unavailable, "
"auto mode cannot determine"))
with open(os.path.join(sub_dir, "agent-aaa.jsonl"), "w", encoding="utf-8") as fh:
fh.write(assistant("claude-sonnet-5", 100, 200, 300, 400, "req_c"))
fh.write(assistant("claude-sonnet-5", 100, 200, 300, 400, "req_c")) # дубль
fh.write(assistant(_TEST_RATE_MODELS[1], 100, 200, 300, 400, "req_c"))
fh.write(assistant(_TEST_RATE_MODELS[1], 100, 200, 300, 400, "req_c")) # дубль
fh.write(line(type="assistant", toolUseResult={
"agentId": "bbb", "agentType": "pdf-reader", "resolvedModel": "claude-haiku-4-5"}))
"agentId": "bbb", "agentType": "pdf-reader", "resolvedModel": _TEST_RATE_MODELS[2]}))
with open(os.path.join(sub_dir, "agent-bbb.jsonl"), "w", encoding="utf-8") as fh:
fh.write(assistant("claude-haiku-4-5", 1000, 2000, 3000, 4000, "req_d"))
fh.write(assistant(_TEST_RATE_MODELS[2], 1000, 2000, 3000, 4000, "req_d"))
# агент воркфлоу лежит глубже — subagents/workflows/<run>/
wf_dir = os.path.join(sub_dir, "workflows", "wf_test")
@@ -829,7 +1156,7 @@ def selftest() -> int:
with open(os.path.join(wf_dir, "agent-ccc.jsonl"), "w", encoding="utf-8") as fh:
fh.write(line(type="user", isSidechain=True, attributionAgent="doc-reviewer",
message={"content": [{"type": "text", "text": "проверь документ"}]}))
fh.write(assistant("claude-opus-5", 7, 8, 9, 10, "req_e"))
fh.write(assistant(_TEST_RATE_MODELS[0], 7, 8, 9, 10, "req_e"))
rep = collect(main)
# Через .get: сломанная атрибуция должна давать НАЗВАННЫЙ провал проверки,
@@ -873,20 +1200,21 @@ def selftest() -> int:
("агент воркфлоу не валится в «прочее»",
step_of("workflow-subagent", "You are an epistemics specialist") == "система"),
("модели разнесены",
{"opus", "sonnet", "haiku"} <= set(rep["by_model"])),
# Неизвестная модель обязана быть ВИДНА, а не растворяться в opus.
set(RATES) <= set(rep["by_model"])),
# Неизвестная модель обязана быть видна отдельно.
("неизвестная модель — отдельная строка разреза",
any(k.startswith(UNKNOWN_PREFIX) and "fable" in k for k in rep["by_model"])),
("неизвестная модель не приписана opus",
rep["by_model"]["opus"]["in"] == 19),
any(k.startswith(UNKNOWN_PREFIX) and "unpriced" in k for k in rep["by_model"])),
("неизвестная модель не приписана верхней ставке",
rep["by_model"][MAX_RATE_KEY]["in"] == 19),
("токены неизвестной модели не потеряны",
sum(v["in"] for k, v in rep["by_model"].items()
if k.startswith(UNKNOWN_PREFIX)) == 5),
# Цена по ней — верхняя оценка: занизить расход опаснее, чем завысить.
("неизвестная модель считается по верхней ставке",
rate_key("claude-fable-5") == "opus"),
rate_key("fixture-unpriced") == MAX_RATE_KEY),
("известная модель тариф не меняет",
rate_key("claude-sonnet-5") == "sonnet" and rate_key("claude-haiku-4-5") == "haiku"),
rate_key(_TEST_RATE_MODELS[1]) == _TEST_RATE_MODELS[1]
and rate_key(_TEST_RATE_MODELS[2]) == _TEST_RATE_MODELS[2]),
("агент воркфлоу учтен", st("5 проверка")["out"] == 8),
# Подмена модели харнессом — отдельный счетчик, а не растворение в
# строке фактически сработавшей модели (15 невидимых подмен 01.09).
@@ -909,13 +1237,13 @@ def selftest() -> int:
("перерасход дает 3", track_verdict("FAST", TRACK_BUDGET["FAST"] * 2)[1] == 3),
("граница цели — еще не перерасход",
track_verdict("FAST", TRACK_BUDGET["FAST"])[1] == 0),
# Тариф: opus дороже sonnet и haiku на одном и том же объеме.
# Тарифы разных классов не подменяются.
("тариф модели не подменяется",
cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, "claude-opus-5") == 15.0
and cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, "claude-sonnet-5") == 3.0
and cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, "claude-haiku-4-5") == 1.0),
cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, _TEST_RATE_MODELS[0]) == 15.0
and cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, _TEST_RATE_MODELS[1]) == 3.0
and cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, _TEST_RATE_MODELS[2]) == 1.0),
("неизвестная модель считается по верхней ставке в деньгах",
cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, "claude-fable-5") == 15.0),
cost({"in": 1_000_000, "out": 0, "cw": 0, "cr": 0}, "fixture-unpriced") == 15.0),
]
# Порог путь-резолва (b8086b2): project_dir указывал на литеральный
@@ -1009,11 +1337,50 @@ def selftest() -> int:
("основной поток не выдается за роль",
role_warnings({"основной поток": {"in": 99_000, "out": 0, "cw": 0,
"cr": 0, "calls": 1}}, {}) == []),
("неназванная роль требует машинный признак",
len(unnamed) == 1 and "СТОП:" in unnamed[0]
("неназванная роль названа без токенового стопа",
len(unnamed) == 1 and "⚠" in unnamed[0]
and "agentType/attributionAgent" in unnamed[0]),
]
measured = {
"cli": "fixture-cli",
"pipeline_report": {"runs": [{"run_id": "run-1", "events": [
{"attempt_id": "try-1", "step": "2", "status": "accepted",
"usage": {"inputOther": 7, "output": 3,
"inputCacheRead": 5, "inputCacheCreation": 1}},
{"attempt_id": "try-2", "step": "2", "status": "accepted",
"usage": {"total_token_usage": {"total_tokens": 19}}},
]}]},
}
attempts = _journal_records(measured, "fixture.json")
joined = _journal_records({
"cli": "fixture-cli",
"pipeline_report": {"runs": [
{"run_id": "run-a", "events": [{"attempt_id": "same", "step": "2"}]},
{"run_id": "run-b", "events": [{"attempt_id": "same", "step": "2"}]},
]},
"usage_records": [
{"run_id": "run-a", "attempt_id": "same", "usage": 11},
{"run_id": "run-b", "attempt_id": "same", "usage": 22},
{"run_id": "run-b", "attempt_id": "standalone", "step": "3",
"usage": {"total_tokens": 33}},
],
}, "joined.json")
checks += [
("usage адаптера несет run_id и attempt_id",
all(item["run_id"] == "run-1" and item["attempt_id"]
for item in attempts)),
("повтор попытки не слит", [item["attempt_id"] for item in attempts]
== ["try-1", "try-2"]),
("родной usage адаптеров нормализован",
attempts[0]["usage"]["tokens"] == 16
and attempts[1]["usage"]["tokens"] == 19),
("usage сведен по run_id и attempt_id",
[item["usage"]["tokens"] for item in joined] == [11, 22, 33]),
("отдельная попытка адаптера не потеряна",
joined[2]["attempt_id"] == "standalone" and joined[2]["step"] == "3"),
]
bad = [name for name, ok in checks if not ok]
for name, ok in checks:
print(f" {'✓' if ok else '✗'} {name}")
@@ -1028,38 +1395,61 @@ def main() -> int:
ap = obs.parser("Замер расхода токенов по шагам конвейера Фемиды")
ap.add_argument("session", nargs="?", help="путь к session.jsonl (по умолчанию — свежая сессия проекта)")
ap.add_argument("--all", action="store_true", help="все сессии проекта сводно")
ap.add_argument("--provider", choices=("auto", "claude", "codex"), default="auto",
help="источник: auto выбирает Codex при CODEX_THREAD_ID/SESSION_ID")
ap.add_argument("--track", choices=sorted(TRACK_BUDGET), help="сверить с целью трека, exit 3 при перерасходе")
ap.add_argument("--provider", choices=("auto", "claude", "codex", "kimi"), default="auto",
help="источник: auto выбирает Codex при CODEX_THREAD_ID/SESSION_ID; "
"kimi — только явно (маркера среды у Kimi нет)")
ap.add_argument("--track", choices=sorted(TRACK_BUDGET),
help="отчет о цели трека; стоп только при THEMIZ_TOKEN_LIMITS=1")
ap.add_argument("--ctx-limit", type=int, default=None, metavar="N",
help="потолок контекста запроса главного потока, exit 3 при пробое; "
"0 — выключить (по умолчанию 200 000)")
"0 — выключить (по умолчанию выключен)")
ap.add_argument("--json", action="store_true", help="машинный вывод")
args = ap.parse_args()
if args.selftest:
return selftest()
# --all без явного провайдера — общая сводка трех адаптеров.
# Явный --provider сохраняет прежний контракт одного CLI.
if args.all and args.provider == "auto":
try:
combined = adapter_usage_report()
except (OSError, ValueError) as exc:
print(f"журналы usage адаптеров не сведены: {exc}", file=sys.stderr)
return obs.KOD_OSHIBKA
if args.json:
print(json.dumps(combined, ensure_ascii=False, indent=2))
else:
print(f"попыток адаптеров: {len(combined['records'])}")
for cli, total in sorted(combined["totals"].items()):
print(f"{cli}: попыток {total['attempts']}, измерено "
f"{total['measured_attempts']}, токенов {total['tokens']}")
return obs.KOD_OK
provider = active_provider(args.provider)
if provider == "codex":
if provider in ("codex", "kimi"):
label = provider.capitalize()
if args.session or args.all:
print("Codex: session и --all пока не поддержаны; доступна только текущая сессия по cwd",
print(f"{label}: session и --all пока не поддержаны; доступна только текущая сессия по cwd",
file=sys.stderr)
return obs.KOD_NE_RABOTAL
try:
rep = codex_report(os.getcwd())
except (NoCodexSessions, CorruptCodexSession) as exc:
print(f"Codex-сессия для cwd не найдена ({exc}) — ДАННЫХ НЕТ", file=sys.stderr)
rep = codex_report(os.getcwd()) if provider == "codex" else kimi_report(os.getcwd())
except (NoCodexSessions, CorruptCodexSession, NoKimiSessions, CorruptKimiSession) as exc:
print(f"{label}-сессия для cwd не найдена ({exc}) — ДАННЫХ НЕТ", file=sys.stderr)
return obs.KOD_NE_RABOTAL
if args.json:
rep["ctx_limit"] = args.ctx_limit if args.ctx_limit is not None else None
if args.track:
rep["track"] = args.track
rep["track_status"] = "informational_not_subscription_limit"
rep["track_status"] = ("enforced" if TOKEN_LIMITS_ENABLED
else "informational_not_subscription_limit")
print(json.dumps(rep, ensure_ascii=False, indent=2))
rc = obs.KOD_NE_RABOTAL if args.ctx_limit is not None else obs.KOD_OK
if args.track and TOKEN_LIMITS_ENABLED:
rc = max(rc, track_verdict(args.track, rep["tokens"])[1])
return rc
return render_codex(rep, args.track, args.ctx_limit is not None)
return render_external(rep, args.track, args.ctx_limit is not None)
ctx_limit = args.ctx_limit
if ctx_limit is None:
@@ -1067,7 +1457,7 @@ def main() -> int:
import context_ledger as _cl
ctx_limit = _cl.CTX_LIMIT_DEFAULT
except ImportError:
ctx_limit = 200_000
ctx_limit = 0
if args.all:
files = sorted(glob.glob(os.path.join(project_dir(os.getcwd()), "*.jsonl")))
@@ -1094,16 +1484,14 @@ def main() -> int:
if args.json:
rep["ctx_limit"] = ctx_limit
if args.track:
if SUBSCRIPTION_ONLY:
if not TOKEN_LIMITS_ENABLED:
rep["track_status"] = "informational_not_subscription_limit"
else:
rep["track_status"] = "enforced"
print(json.dumps(rep, ensure_ascii=False, indent=2))
rc = ctx_verdict(rep.get("max_ctx", 0), ctx_limit)[1]
if args.track and not SUBSCRIPTION_ONLY:
if args.track and TOKEN_LIMITS_ENABLED:
rc = max(rc, track_verdict(args.track, tokens(rep["total"]))[1])
if any(w.startswith("СТОП:") for w in rep["role_warnings"]):
rc = max(rc, obs.KOD_STOP)
return rc
return render(rep, args.track, ctx_limit)