From 5915499037e13563f42e3a995f80fd8b0e2fdd03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?= <289370046+zarubinphil@users.noreply.github.com> Date: Wed, 17 Jun 2026 15:26:07 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD-=D1=83?= =?UTF-8?q?=D1=87=D1=91=D1=82=20=D0=B2=20chezmoi-=D0=BA=D0=B0=D0=BD=D0=BE?= =?UTF-8?q?=D0=BD=D0=B5=20(=D0=BF=D0=B0=D1=80=D0=B8=D1=82=D0=B5=D1=82-?= =?UTF-8?q?=D0=B4=D1=8B=D1=80=D0=B0=20=D0=B7=D0=B0=D0=BA=D1=80=D1=8B=D1=82?= =?UTF-8?q?=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit session-token-log.sh + token-spend.sh мигрированы live → канон (chezmoi/dot_claude/scripts/, executable_-префикс). Добавлен SessionEnd-хук в settings.json.tmpl (portable {{.chezmoi.homeDir}}, async, как live). Канон-жнец (7482e48) опирался на эти скрипты через guard — на новом Mac учёт молча ломался: скриптов нет + хук не проведён. Оба скрипта чисты ($HOME, ноль хардкода/личного). dry-validate + smoke зелёные, settings.json рендерится валидным. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../scripts/executable_session-token-log.sh | 21 +++++++++ .../scripts/executable_token-spend.sh | 46 +++++++++++++++++++ chezmoi/dot_claude/settings.json.tmpl | 13 ++++++ 3 files changed, 80 insertions(+) create mode 100755 chezmoi/dot_claude/scripts/executable_session-token-log.sh create mode 100755 chezmoi/dot_claude/scripts/executable_token-spend.sh diff --git a/chezmoi/dot_claude/scripts/executable_session-token-log.sh b/chezmoi/dot_claude/scripts/executable_session-token-log.sh new file mode 100755 index 0000000..23bd520 --- /dev/null +++ b/chezmoi/dot_claude/scripts/executable_session-token-log.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# session-token-log.sh — SessionEnd-хук: пишет токен-расход сессии в self-learning лог. +# Получает на stdin JSON хука (transcript_path). Тихий, без падений (хук не должен ломать выход). +set -uo pipefail + +LOG="$HOME/.claude/self-learning/token-spend.log" +mkdir -p "$(dirname "$LOG")" + +IN=$(cat 2>/dev/null || true) +TP=$(printf '%s' "$IN" | python3 -c "import sys,json; +try: print(json.load(sys.stdin).get('transcript_path','')) +except Exception: print('')" 2>/dev/null) + +[ -n "$TP" ] && [ -f "$TP" ] || exit 0 # нет транскрипта — тихо выходим + +{ + echo "── $(date '+%F %T') ──" + "$HOME/.claude/scripts/token-spend.sh" "$TP" 2>/dev/null + echo +} >> "$LOG" 2>/dev/null || true +exit 0 diff --git a/chezmoi/dot_claude/scripts/executable_token-spend.sh b/chezmoi/dot_claude/scripts/executable_token-spend.sh new file mode 100755 index 0000000..ee4c162 --- /dev/null +++ b/chezmoi/dot_claude/scripts/executable_token-spend.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# token-spend.sh — разбивка токен-расхода сессии из jsonl (для конца сессии / token-аудита самообучения). +# Использование: token-spend.sh [path/to/session.jsonl] +# без аргумента — берёт самый свежий jsonl проекта текущего cwd. +set -uo pipefail + +F="${1:-}" +if [ -z "$F" ]; then + # имя проекта в ~/.claude/projects кодируется через замену '/' на '-' + KEY=$(pwd | sed 's#/#-#g') + DIR="$HOME/.claude/projects/$KEY" + F=$(ls -t "$DIR"/*.jsonl 2>/dev/null | head -1) +fi +[ -n "$F" ] && [ -f "$F" ] || { echo "jsonl не найден ($F). Передай путь явно."; exit 1; } + +python3 - "$F" <<'PY' +import json, sys +f = sys.argv[1] +it = ot = cc = cr = n = 0 +models = set() +for line in open(f): + try: d = json.loads(line) + except Exception: continue + m = d.get("message", {}) + u = m.get("usage") or {} + if not u: continue + n += 1 + it += u.get("input_tokens", 0); ot += u.get("output_tokens", 0) + cc += u.get("cache_creation_input_tokens", 0); cr += u.get("cache_read_input_tokens", 0) + if m.get("model"): models.add(m["model"]) +# Opus-rate (груб): in $15 / out $75 / cache-write $18.75 / cache-read $1.50 за Mtok +cost = it/1e6*15 + ot/1e6*75 + cc/1e6*18.75 + cr/1e6*1.5 +tot = it + ot + cc + cr +print(f"сессия: {f.split('/')[-1]}") +print(f"вызовов с usage: {n} | модели: {', '.join(models) or '—'}") +print(f"input(uncached): {it:>13,}") +print(f"output: {ot:>13,}") +print(f"cache-write: {cc:>13,}") +print(f"cache-read: {cr:>13,}") +print(f"ВСЕГО: {tot:>13,}") +print(f"≈ стоимость: ${cost:,.2f} (груб. Opus-rate)") +# доминанта +parts = {"input": it, "output": ot, "cache-write": cc, "cache-read": cr} +dom = max(parts, key=parts.get) +print(f"доминанта: {dom} ({parts[dom]/tot*100:.0f}%)") +PY diff --git a/chezmoi/dot_claude/settings.json.tmpl b/chezmoi/dot_claude/settings.json.tmpl index 6f91e39..74e6df3 100644 --- a/chezmoi/dot_claude/settings.json.tmpl +++ b/chezmoi/dot_claude/settings.json.tmpl @@ -46,6 +46,19 @@ } ] } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "bash \"{{ .chezmoi.homeDir }}/.claude/scripts/session-token-log.sh\"", + "async": true, + "timeout": 20, + "statusMessage": "Token-spend → self-learning..." + } + ] + } ] }, "enabledPlugins": {