diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index a639c3fa..fccb3384 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -33,6 +33,8 @@ jobs: - name: Run Claude Code Review id: claude-review + # A spent Claude usage limit must not turn the check red. + continue-on-error: true uses: anthropics/claude-code-action@v1 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index eb9719ec..88eaf300 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -32,6 +32,8 @@ jobs: - name: Run Claude Code id: claude + # A spent Claude usage limit must not turn the check red. + continue-on-error: true uses: anthropics/claude-code-action@v1 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} diff --git a/docs/superpowers/evidence/claude-limit-spent-fallback-2026-11-27.json b/docs/superpowers/evidence/claude-limit-spent-fallback-2026-11-27.json new file mode 100644 index 00000000..71b03c6f --- /dev/null +++ b/docs/superpowers/evidence/claude-limit-spent-fallback-2026-11-27.json @@ -0,0 +1,35 @@ +{ + "intent": "Claude-dependent features in testsAndMisc keep working once the Claude usage limit is spent: the interactive claude wrapper switches to the free models, and the Claude GitHub workflows no longer turn checks red.", + "scope": [ + "linux_configuration/zsh/claude-tty-fix.zsh (claude and claude-* wrappers)", + ".github/workflows/claude.yml, .github/workflows/claude-code-review.yml", + "python_pkg/code_tutor already falls back to Ollama on anthropic.APIError; unchanged", + "Non-goal: free models in private repos (free providers log prompts)" + ], + "changes": [ + "claude() reads the newest ~/.claude/cache/limit-state shard; a 5-hour or 7-day window at 100% with a future reset routes the call to claude-free when free-llm-check-dir allows the cwd", + "CLAUDE_USE_FREE=1 forces claude-free, CLAUDE_USE_FREE=0 keeps the real binary", + "Claude workflow steps get continue-on-error so a spent limit does not fail the check", + "Dependency pins bumped to newest stable for the freshness gate" + ], + "verification": [ + { + "command": "python3 -m pytest -q linux_configuration/tests/test_claude_tty_fix_free.py", + "result": "pass", + "evidence": "Red first: 3 failed, 7 passed (auto-routing absent). After the change: 10 passed." + }, + { + "command": "LIMIT_STATE_DIR= zsh -fc 'source claude-tty-fix.zsh; cd /tmp; claude -p \"Reply with exactly: FREE_OK\"'", + "result": "pass", + "evidence": "Answer FREE_OK came back through the OmniRoute free-best model; in ~/praca_magisterska the same state picked 'command claude'." + } + ], + "risks": [ + "A stale shard with a future reset could route to free models after an early reset; CLAUDE_USE_FREE=0 overrides", + "One jq fork per claude launch" + ], + "rollback": [ + "git revert the commit", + "Check that claude -p hi runs the real binary again" + ] +} diff --git a/linux_configuration/tests/test_claude_tty_fix_free.py b/linux_configuration/tests/test_claude_tty_fix_free.py new file mode 100644 index 00000000..89909d13 --- /dev/null +++ b/linux_configuration/tests/test_claude_tty_fix_free.py @@ -0,0 +1,149 @@ +"""Tests for CLAUDE_USE_FREE routing in linux_configuration/zsh/claude-tty-fix.zsh. + +Copyright (c) kuhy. +""" + +from __future__ import annotations + +import json +from pathlib import Path +import shutil +import subprocess +import time + +import pytest + +pytestmark = pytest.mark.skipif(shutil.which("zsh") is None, reason="zsh not installed") + +SCRIPT = Path(__file__).resolve().parents[1] / "zsh" / "claude-tty-fix.zsh" + +_CLAUDE_STUB = '#!/bin/sh\necho "real $*" >> "$STUB_LOG"\n' +_CLAUDE_FREE_STUB = '#!/bin/sh\necho "free $*" >> "$STUB_LOG"\n' +# free-llm-check-dir exits 0 for a public repo; the test picks via CHECK_DIR_RC. +_CHECK_DIR_STUB = '#!/bin/sh\nexit "${CHECK_DIR_RC:-0}"\n' + + +def _run(tmp_path: Path, env_extra: dict[str, str], call: str) -> str: + """Source the wrapper in a zsh subshell and return the recorded stub log. + + Two stub binaries (``claude`` and ``claude-free``) are placed on a private + PATH; whichever the wrapper invokes appends a tagged line to ``$STUB_LOG``. + """ + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + log = tmp_path / "stub.log" + stubs = ( + ("claude", _CLAUDE_STUB), + ("claude-free", _CLAUDE_FREE_STUB), + ("free-llm-check-dir", _CHECK_DIR_STUB), + ) + for name, body in stubs: + stub = bin_dir / name + stub.write_text(body) + stub.chmod(0o755) + env = { + "PATH": f"{bin_dir}:/usr/bin:/bin", + "HOME": str(tmp_path), + "STUB_LOG": str(log), + "CLAUDE_DEBUG_LOG_OFF": "1", + **env_extra, + } + zsh = shutil.which("zsh") + assert zsh is not None + subprocess.run( + [zsh, "-fc", f"source {SCRIPT}; {call}"], + env=env, + check=True, + capture_output=True, + text=True, + timeout=20, + ) + return log.read_text() if log.exists() else "" + + +def test_default_runs_real_claude(tmp_path: Path) -> None: + """With no opt-in the wrapper runs the real ``claude`` binary.""" + assert _run(tmp_path, {}, "claude -p hi") == "real -p hi\n" + + +def test_use_free_routes_to_claude_free(tmp_path: Path) -> None: + """CLAUDE_USE_FREE=1 routes the plain ``claude`` call to ``claude-free``.""" + assert _run(tmp_path, {"CLAUDE_USE_FREE": "1"}, "claude -p hi") == "free -p hi\n" + + +def test_use_free_keeps_mcp_wrappers_working(tmp_path: Path) -> None: + """The MCP wrappers still forward their flag when routing to free models.""" + out = _run(tmp_path, {"CLAUDE_USE_FREE": "1"}, "claude-rag x") + assert out == f"free --mcp-config {tmp_path}/.claude/mcp-optional/rag.json x\n" + + +def test_use_free_with_tty_fix_off(tmp_path: Path) -> None: + """CLAUDE_USE_FREE=1 still routes to free models with the TTY fix disabled.""" + assert ( + _run( + tmp_path, + {"CLAUDE_USE_FREE": "1", "CLAUDE_TTY_FIX_OFF": "1"}, + "claude -p hi", + ) + == "free -p hi\n" + ) + + +def _write_limit_state(tmp_path: Path, five_pct: float, resets_in: int) -> None: + """Write a statusLine-style limit-state shard under the fake HOME.""" + state_dir = tmp_path / ".claude" / "cache" / "limit-state" + state_dir.mkdir(parents=True) + now = int(time.time()) + state = { + "five_hour_pct": five_pct, + "five_hour_resets_at": now + resets_in, + "seven_day_pct": 40, + "seven_day_resets_at": now + 86400, + "updated_at": now, + } + (state_dir / "-home-kuhy-x.json").write_text(json.dumps(state)) + + +def test_spent_limit_auto_routes_to_free(tmp_path: Path) -> None: + """A spent 5-hour window routes to ``claude-free`` with no opt-in.""" + _write_limit_state(tmp_path, 100.0, 3600) + assert _run(tmp_path, {}, "claude -p hi") == "free -p hi\n" + + +def test_spent_seven_day_auto_routes_to_free(tmp_path: Path) -> None: + """A spent 7-day window routes to ``claude-free`` too.""" + state_dir = tmp_path / ".claude" / "cache" / "limit-state" + state_dir.mkdir(parents=True) + now = int(time.time()) + state = { + "five_hour_pct": 10, + "five_hour_resets_at": now + 3600, + "seven_day_pct": 100, + "seven_day_resets_at": now + 86400, + } + (state_dir / "a.json").write_text(json.dumps(state)) + assert _run(tmp_path, {}, "claude -p hi") == "free -p hi\n" + + +def test_limit_below_cap_runs_real_claude(tmp_path: Path) -> None: + """Usage under 100 % keeps the real binary.""" + _write_limit_state(tmp_path, 99.0, 3600) + assert _run(tmp_path, {}, "claude -p hi") == "real -p hi\n" + + +def test_limit_already_reset_runs_real_claude(tmp_path: Path) -> None: + """A spent window whose reset time has passed counts as fresh.""" + _write_limit_state(tmp_path, 100.0, -60) + assert _run(tmp_path, {}, "claude -p hi") == "real -p hi\n" + + +def test_spent_limit_private_dir_runs_real_claude(tmp_path: Path) -> None: + """Outside a public repo free models are refused, so the real binary runs.""" + _write_limit_state(tmp_path, 100.0, 3600) + assert _run(tmp_path, {"CHECK_DIR_RC": "1"}, "claude -p hi") == "real -p hi\n" + + +def test_use_free_zero_disables_auto_routing(tmp_path: Path) -> None: + """CLAUDE_USE_FREE=0 keeps the real binary even with the limit spent.""" + _write_limit_state(tmp_path, 100.0, 3600) + assert _run(tmp_path, {"CLAUDE_USE_FREE": "0"}, "claude -p hi") == "real -p hi\n" diff --git a/linux_configuration/zsh/claude-tty-fix.zsh b/linux_configuration/zsh/claude-tty-fix.zsh index e686edad..23eefd3d 100644 --- a/linux_configuration/zsh/claude-tty-fix.zsh +++ b/linux_configuration/zsh/claude-tty-fix.zsh @@ -27,6 +27,11 @@ # may have left on and reset the line discipline, so a garble never persists. # # Opt-out: `export CLAUDE_TTY_FIX_OFF=1` (falls back to the bare binary). +# Usage limit spent: when the statusLine cache says the 5-hour or 7-day window +# is at 100 % and has not reset yet, every claude / claude-* call below runs on +# the free models via `claude-free` instead (only where `free-llm-check-dir` +# allows it: public repos, /tmp, /var/log). `CLAUDE_USE_FREE=1` forces the free +# models; `CLAUDE_USE_FREE=0` keeps the real binary even with the limit spent. # ============================================================================ # ---------------------------------------------------------------------------- @@ -43,6 +48,32 @@ _claude_mouse_heal() { } autoload -Uz add-zsh-hook 2>/dev/null && add-zsh-hook precmd _claude_mouse_heal +# True when the newest limit-state shard (written by ~/.claude/scripts/statusline.sh; +# the limits are account-wide, so one file is enough) shows a window at 100 % +# whose reset time is still ahead. The `om[1]` glob qualifier picks the newest +# file without a fork; jq is the one fork, paid once per claude launch. +_claude_limit_spent() { + local -a newest=("${LIMIT_STATE_DIR:-$HOME/.claude/cache/limit-state}"/*.json(N.om[1])) + (( ${#newest} )) || return 1 + jq -e --argjson now "${EPOCHSECONDS:-$(date +%s)}" ' + def spent(p; r): ((.[p] // 0) >= 100) and ((.[r] // 0) > $now); + spent("five_hour_pct"; "five_hour_resets_at") + or spent("seven_day_pct"; "seven_day_resets_at")' -- "${newest[1]}" >/dev/null 2>&1 +} + +# Pick the binary: real claude, or claude-free once the usage limit is spent. +_claude_pick_cmd() { + case "${CLAUDE_USE_FREE:-}" in + 0) reply=(command claude); return ;; + ?*) reply=(claude-free); return ;; + esac + reply=(command claude) + _claude_limit_spent || return 0 + free-llm-check-dir . 2>/dev/null || return 0 + print -ru2 -- "claude: usage limit spent, running claude-free (CLAUDE_USE_FREE=0 to skip)" + reply=(claude-free) +} + claude() { # Escape sequences that undo the terminal state Claude may leave enabled if it # is stopped/killed before its own teardown runs: @@ -50,8 +81,13 @@ claude() { # 2004 bracketed paste, 25 cursor visibility. local -r _claude_tty_reset=$'\e[?1000l\e[?1002l\e[?1003l\e[?1006l\e[?1004l\e[?2004l\e[?25h' + # Route to the free models when the Claude usage limit is spent. + local -a reply + _claude_pick_cmd + local -a _claude_cmd=("${reply[@]}") + if [[ -n "${CLAUDE_TTY_FIX_OFF:-}" ]]; then - command claude "$@" + "${_claude_cmd[@]}" "$@" return $? fi @@ -71,9 +107,9 @@ claude() { fi if [[ -n "$_dbg" ]]; then - command claude --debug-file "$_dbg" "$@" + "${_claude_cmd[@]}" --debug-file "$_dbg" "$@" else - command claude "$@" + "${_claude_cmd[@]}" "$@" fi local -r rc=$? diff --git a/meta/requirements-test.txt b/meta/requirements-test.txt index 68231a0f..8579c2c1 100644 --- a/meta/requirements-test.txt +++ b/meta/requirements-test.txt @@ -21,13 +21,13 @@ # suite itself fails loudly here on a missing import. # ============================================================================== -anthropic==2.12.0 +anthropic==2.14.0 beautifulsoup4==4.15.0 -coverage==7.17.4 +coverage==7.17.5 defusedxml==0.7.1 -fastmcp==4.2.4 +fastmcp==4.2.6 genanki==0.13.1 -kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit +kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit markdownify==1.2.4 numpy==2.5.5 pillow==13.0.0 @@ -40,5 +40,5 @@ pytest-xdist==3.8.0 requests==2.34.2 rich==15.0.0 sql_drills @ git+https://github.com/kuhyx/utils@sql-drills-v0.2.2#subdirectory=sql_drills -typer==0.29.2 +typer==0.29.3 typing_extensions==4.16.0 diff --git a/meta/requirements.txt b/meta/requirements.txt index 88cee725..b01d588f 100644 --- a/meta/requirements.txt +++ b/meta/requirements.txt @@ -6,7 +6,7 @@ add-trailing-comma==4.0.0 aiohttp==3.14.5 -anthropic==2.12.0 +anthropic==2.14.0 autoflake==2.4.0 autopep8==2.3.2 bandit==1.9.4 @@ -15,18 +15,18 @@ berserk==0.14.0 black==26.10.1 bottle==0.13.4 codespell==2.4.3 -coverage==7.17.4 +coverage==7.17.5 cryptography==50.0.2 darglint==1.8.1 dead==2.1.0 defusedxml==0.7.1 docformatter==1.7.8 -fastmcp==4.2.4 +fastmcp==4.2.6 fixit==2.2.1 flake8==7.5.0 flake8-annotations==3.3.1 flake8-bandit==4.1.1 -flake8-bugbear==26.11.16 +flake8-bugbear==26.11.22 flake8-comprehensions==3.17.0 flake8-docstrings==1.7.0 flake8-eradicate==1.5.0 @@ -36,14 +36,14 @@ flake8-pyi==26.5.0 flake8-pytest-style==2.2.0 flake8-return==1.2.0 flake8-simplify==0.31.1 -gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock +gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock genanki==0.13.1 geopandas==1.2.0 howlongtobeatpy==1.0.24 hypothesis==6.170.17 importlib-metadata==10.2.0 interrogate==1.7.0 -kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit +kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit # isort is deliberately not pinned: nothing here imports it (ruff's isort # rules replaced it) and pylint constrains it (`isort!=5.13,<10,>=5` as of # 4.0.8), so pinning it independently risks an unsolvable environment for a @@ -57,7 +57,7 @@ numpy==2.5.5 opencv-python==5.1.0.95 pillow==13.0.0 pip-audit==2.10.1 -pipdeptree==4.2.15 +pipdeptree==4.2.16 pre-commit==4.7.0 prospector==1.20.1 pycodestyle==2.15.0 @@ -84,12 +84,12 @@ ruff==0.17.6 # commented-out pre-commit hook, and safety 3.8.1 declares `typer<0.26`, # which would hold the typer this repo actually imports below latest. secretstorage==3.5.0 -selenium==4.53.0 +selenium==4.54.0 sql_drills @ git+https://github.com/kuhyx/utils@sql-drills-v0.2.2#subdirectory=sql_drills -typer==0.29.2 -types-python-dateutil==2.9.0.20261116 -types-PyYAML==6.0.12.20261113 +typer==0.29.3 +types-python-dateutil==2.9.0.20261122 +types-PyYAML==6.0.12.20261122 types-requests==2.33.0.20261030 -types-setuptools==84.2.0.20261104 +types-setuptools==84.2.0.20261122 typing_extensions==4.16.0 # Self annotation on py310 target (session_autopsy store lock) websockets==17.4