Coach on OmniRoute free-best after a Claude limit
Some checks are pending
file length / file-length (push) Waiting to run
focus-project pre-commit / pre-commit (push) Waiting to run
focus-project tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
leetcode-coach pre-commit / pre-commit (push) Waiting to run
leetcode-coach tests / test (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run

The REPL, relay and graders fall back to OmniRoute free-best, then
Ollama, through the same no-solution gate. leetcode --free starts
claude-free with the skill from /tmp/leetcode-free. v0.1.7.

Todo: 9005c9b4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-27 11:45:10 +01:00
parent ad89ea9714
commit 9b82aba9c8
19 changed files with 786 additions and 50 deletions

View File

@ -28,7 +28,7 @@ Stdlib only unless noted. Import only what you need.
| Review | `review_cli` (`/leetcode review`, skeleton sheets), `flagged` (guard CLI reader), `review_ledger` (the coach's own signed ledger) |
| Content | `fetch_problem`, `toolbox.json`, `answer_key`, `clusters.json` |
| Cards | `toolbox_cards`, `card_rules`, `make_cards` (needs genanki), `anki_connect` |
| Models | `claude_cli` (haiku/sonnet via `claude -p`), `local_backend` (Ollama) |
| Models | `claude_cli` (haiku/sonnet via `claude -p`), `local_backend` (Ollama), `omniroute_backend` (OmniRoute `free-best`), `free_chain` (OmniRoute, then Ollama) |
| Relay | `relay.*`: state machine, grading, run-code, HTTP + RTDB (needs requests, crdt-sync) |
| Clients | `leetcode_repl` (`leetcode` command), `cluster_cli`, `local_session`, `how_to` |
@ -52,9 +52,9 @@ means paste it), `fetch_problem.render(q, lang) -> str` (markdown with
refuse and show `note`; otherwise forward `sent` to the coach and show `note`
if non-empty. Logs `req`, `req_check`, `code`, `reveal`.
- `ask` (gate, `req_check.check`, `looks_like_code`, graders) is CLI-style `(args, prompt, **kw)`
(default: haiku, then Ollama) or a structured `(system, prompt, schema) -> dict`
(default: haiku, then the free chain) or a structured `(system, prompt, schema) -> dict`
model function such as the tutor's `ask_model` (answers are labelled `via: "model"`;
any raise falls through to Ollama, then fails open to `unverified`).
any raise falls through to the free chain, then fails open to `unverified`).
- `gate.refusal_note()`, `gate.code_seen()`, `gate.events()`, `gate.sql()`,
`gate.leaks(reply, user_texts) -> [names]` (bounce and regenerate),
`gate.after_reply(text) -> text without the rung marker` (logs `rung`).

View File

@ -11,10 +11,16 @@ toolbox name, but the TUI has already streamed it (2026-09-21: the blocked
`for` loop was visible above the rewrite); print mode waits. TUI: best-effort.
**Offline / out of quota.** `leetcode --local <url>` coaches on
`qwen3:30b-a3b-instruct-2507` via Ollama, and the REPL switches there by
itself, history intact, on "You've hit your ... limit". With no hooks there,
`local_coach.py` runs the same detectors on every draft; three leaky drafts
are withheld. Everything above `## Model and client` is its system prompt,
`qwen3:30b-a3b-instruct-2507` via Ollama. On "You've hit your ... limit" the
REPL, the relay coach and the graders switch by themselves, history intact, to
the free chain (`free_chain.py`, kuhy 2026-11-27): OmniRoute `free-best` on
127.0.0.1:20128 (`omniroute_backend.py`, Bearer key from
`~/.config/omniroute/api_key`), then Ollama when the gateway is down, empty or
too small for the prompt. One timeout covers the whole chain. With no hooks
there, `local_coach.py` runs the same detectors on every draft, whichever
rung wrote it; three leaky drafts are withheld. `leetcode --free <url>` runs
interactive `claude-free` with this skill from a fresh `/tmp` dir (the free
providers log prompts; nothing private is in reach there). Everything above `## Model and client` is its system prompt,
minus section 1. `python3 -m leetcode_coach.eval_local`: acceptance run.
## The req-before-code gate (DOCS-coach-spec.md decisions 4-8)
@ -22,7 +28,8 @@ minus section 1. `python3 -m leetcode_coach.eval_local`: acceptance run.
Both REPL paths run `phase.PhaseGate` on every block kuhy sends:
- `req: ...` is the requirement list. `req_check` judges it on
`claude -p --model haiku` (no tools, hooks or session file), then on Ollama,
`claude -p --model haiku` (no tools, hooks or session file), then on the
free chain (OmniRoute, then Ollama),
and fails OPEN (`unverified`) when neither answers. It may only name
missing properties from the `toolbox.json` vocabulary; anything else it says
is dropped before kuhy sees it.

View File

@ -242,9 +242,9 @@ opening message is
then continue with the opening (`hooks/leetcode_model_gate_userprompt.sh`).
The right client is `leetcode <url>` (print mode: the Stop hook can still
withhold a reply; the TUI has already streamed it). `leetcode --local` runs
offline on Ollama; its system prompt is everything above this section. Docs:
`DOCS-clients.md` (clients, gates, session log), `DOCS-how-to.md` (commands).
withhold a reply; a usage limit moves it to OmniRoute, then Ollama). `--local`:
Ollama only; `--free`: `claude-free` from /tmp. The local system prompt is all
above this section. Docs: `DOCS-clients.md` (clients, gates), `DOCS-how-to.md`.
Skeleton sheets: only when kuhy asks, only after his first code, and one
counts above H1. Rules: `DOCS-skeletons.md`; the command: `DOCS-review.md`.

View File

@ -0,0 +1,71 @@
"""The coach's model chain once Claude is out: OmniRoute ``free-best``, then Ollama.
kuhy 2026-11-27: on a Claude usage limit the REPL, the relay and the graders go
on with the free models through OmniRoute, and with the local Ollama model only
when the gateway is down, empty or the prompt too long for it. Each rung is a
``chat(messages, timeout=...) -> LocalReply``; any transport error (``OSError``
covers ``URLError``, refused connections, timeouts and
:class:`~leetcode_coach.omniroute_backend.GatewayError`) or a context overflow
moves on to the next. The last rung's error propagates, so the callers' own
"model is down" handling stays as it was.
"""
from __future__ import annotations
from collections.abc import Callable
import logging
import time
from typing import TYPE_CHECKING
from leetcode_coach import local_backend, omniroute_backend
if TYPE_CHECKING:
from collections.abc import Sequence
_LOG = logging.getLogger(__name__)
Rung = Callable[..., local_backend.LocalReply]
"""One model of the chain: ``rung(messages, timeout=seconds) -> LocalReply``."""
def chat(
messages: list[dict[str, str]],
*,
timeout: float = omniroute_backend.REQUEST_TIMEOUT_S,
rungs: Sequence[Rung] | None = None,
on_fallback: Callable[[str], None] | None = None,
clock: Callable[[], float] = time.monotonic,
) -> local_backend.LocalReply:
"""The first rung's reply that comes back; ``on_fallback`` hears each skip.
``timeout`` bounds the whole chain, not each rung: a rung gets what the
ones before it left, so the relay's per-request cap still holds.
Raises:
OSError: every rung's transport failed (the last error).
ContextOverflowError: the last rung could not fit the prompt either.
"""
# Looked up per call, so a test that swaps a backend's `chat` is honoured.
chain = (
(omniroute_backend.chat, local_backend.chat) if rungs is None else tuple(rungs)
)
deadline = clock() + timeout
for rung in chain[:-1]:
try:
return rung(messages, timeout=_left(deadline, clock))
except (OSError, local_backend.ContextOverflowError) as exc:
why = f"omniroute failed ({type(exc).__name__}: {exc}); next model"
_LOG.warning("%s", why)
if on_fallback is not None:
on_fallback(why)
return chain[-1](messages, timeout=_left(deadline, clock))
def _left(deadline: float, clock: Callable[[], float]) -> float:
"""Seconds until ``deadline``; a ``TimeoutError`` when under one is left."""
left = deadline - clock()
if left < 1.0:
msg = "no time left for another model"
raise TimeoutError(msg)
return left

View File

@ -5,6 +5,11 @@
# Print mode matters: the no-solution Stop gate can only withhold a reply
# from a client that waits for hooks, and the interactive TUI streams first.
# leetcode <url-or-slug> [what you are stuck on...]
# leetcode --free <url-or-slug> [...] interactive claude-free (OmniRoute
# free-best, no Claude quota) with the /leetcode skill, started in
# /tmp/leetcode-free: claude-free runs only from a public directory, and
# the free providers log prompts, so nothing private is in reach. One
# fixed dir, so Claude Code asks to trust it once, not every session.
#
# Symlinked from ~/.local/bin/leetcode. The package is found through
# install.sh's editable install, like the Stop-hook shim; no PYTHONPATH here,
@ -14,4 +19,24 @@
set -euo pipefail
readonly CLAUDE_FREE="${LEETCODE_CLAUDE_FREE_BIN:-claude-free}"
readonly FREE_DIR="${LEETCODE_FREE_DIR:-/tmp/leetcode-free}"
run_free() {
[[ -e "${FREE_DIR}" || -L "${FREE_DIR}" ]] || mkdir -m 700 "${FREE_DIR}"
# /tmp is shared: never start in a dir someone else planted there.
[[ -O "${FREE_DIR}" && ! -L "${FREE_DIR}" ]] || {
echo "leetcode: ${FREE_DIR} is not a directory you own" >&2
exit 77
}
cd "${FREE_DIR}"
exec "${CLAUDE_FREE}" "/leetcode $*"
}
if [[ "${1:-}" == --free ]]; then
shift
[[ $# -gt 0 ]] || { echo "Usage: leetcode --free <url-or-slug> [stuck on...]" >&2; exit 64; }
run_free "$@"
fi
exec /usr/bin/python3 -P -m leetcode_coach.leetcode_repl "$@"

View File

@ -12,8 +12,10 @@ sent before an accepted ``req:`` list is refused here and never reaches the
model. Replies lose their ``<!-- rung:Hn -->`` marker (logged) before printing.
When Claude answers with its usage-limit message (`claude_cli.is_limit_hit`)
the session continues on the local model (`local_session.py`) with the
conversation so far and the same gate; `--local` starts there.
the session continues on the free models (`local_session.py`, `free=True`:
OmniRoute `free-best`, then Ollama) with the conversation so far and the same
gate; `--local` starts on Ollama alone. `--free` starts `claude-free` itself
(the launcher, from a fresh /tmp dir).
Input: a block ends on an empty line (paste code, then press Enter twice).
`quit` or Ctrl-D leaves. `reveal` is passed through like any other message.
@ -70,8 +72,10 @@ def run_claude(model: str, problem: list[str]) -> int:
opener = local_session.opening_message(problem[1:])
first = ask(["--model", model], "/leetcode " + " ".join(problem))
if is_limit_hit(first):
print(f"[{first.get('result', 'usage limit')} -- switching to local model]")
return local_session.run(problem[0], [], opener, read_block, gate=gate)
print(f"[{first.get('result', 'usage limit')} -- switching to the free models]")
return local_session.run(
problem[0], [], opener, read_block, gate=gate, free=True
)
session = first.get("session_id")
print(gate.after_reply(str(first.get("result", ""))))
if not session:
@ -89,8 +93,11 @@ def run_claude(model: str, problem: list[str]) -> int:
print("\n...", flush=True)
reply = ask(["--model", model, "--resume", session], sent)
if is_limit_hit(reply):
print(f"[{reply.get('result', 'usage limit')} -- continuing locally]")
return local_session.run(problem[0], history, sent, read_block, gate=gate)
why = reply.get("result", "usage limit")
print(f"[{why} -- continuing on the free models]")
return local_session.run(
problem[0], history, sent, read_block, gate=gate, free=True
)
print(gate.after_reply(str(reply.get("result", ""))))
history += [
{"role": "user", "content": sent},
@ -117,6 +124,7 @@ def main(argv: list[str]) -> int:
print("Usage: leetcode [--local] <url-or-slug> [what you are stuck on...]")
print(" LEETCODE_MODEL=sonnet|fable leetcode ... (default: opus)")
print(" --local coach on the local Ollama model (free, offline)")
print(" --free interactive claude-free (OmniRoute free models), from /tmp")
print(" leetcode due | --cluster <name> | --retest <slug> (--dry-run)")
print(" leetcode report req-before-code, max rung, reveal per problem")
return 0

View File

@ -49,6 +49,10 @@ class LocalReply:
text: str
seconds: float
prompt_tokens: int
via: str = "ollama"
"""Which rung answered: ``ollama`` or ``omniroute`` (``free_chain``)."""
model: str = MODEL
"""The model that answered (an OmniRoute ``free-best`` member's own name)."""
def strip_think(text: str) -> str:

View File

@ -1,9 +1,12 @@
"""Run a /leetcode coaching loop on the local model.
"""Run a /leetcode coaching loop without Claude.
Entered by `leetcode --local`, or by the REPL mid-session when Claude reports a
usage limit -- in which case `history` already holds the turns so far, so the
local model picks up where Claude stopped instead of starting over. Its prints
ARE the session (T201 exemption in pyproject.toml).
Entered by `leetcode --local` (Ollama only), or by the REPL mid-session when
Claude reports a usage limit (`free=True`: OmniRoute `free-best` first, Ollama
only when the gateway fails, `free_chain`) -- in which case `history` already
holds the turns so far, so the model picks up where Claude stopped instead of
starting over. Every draft passes the same no-solution gate
(`local_coach.respond`). Its prints ARE the session (T201 exemption in
pyproject.toml).
"""
from __future__ import annotations
@ -14,7 +17,13 @@ import sys
from typing import TYPE_CHECKING
import urllib.error
from leetcode_coach import local_backend, local_cards, local_coach
from leetcode_coach import (
free_chain,
local_backend,
local_cards,
local_coach,
omniroute_backend,
)
if TYPE_CHECKING:
from collections.abc import Callable
@ -121,15 +130,80 @@ def _screen(gate: phase.PhaseGate | None, block: str) -> str | None:
return sent
class GpuRefusedError(ConnectionError):
"""kuhy declined to load the local model: the chain has no rung left."""
class OllamaAfterGpuCheck:
"""The free chain's last rung: Ollama, once kuhy agrees to load it (asked once)."""
def __init__(self) -> None:
"""Nothing asked yet."""
self.agreed = False
def __call__(
self, messages: list[dict[str, str]], *, timeout: float
) -> local_backend.LocalReply:
"""Announce the fall-through, check the GPU once, then ask Ollama."""
if not self.agreed:
print(f"[OmniRoute down: local {local_backend.MODEL} via Ollama]")
if not confirm_gpu():
print("[not loading the local model]")
msg = "local model declined"
raise GpuRefusedError(msg)
self.agreed = True
return local_backend.chat(messages, timeout=timeout)
def free_chat(
rung: OllamaAfterGpuCheck,
) -> Callable[[list[dict[str, str]]], local_backend.LocalReply]:
"""One session's chat: OmniRoute, then ``rung``."""
def chat(messages: list[dict[str, str]]) -> local_backend.LocalReply:
return free_chain.chat(messages, rungs=(omniroute_backend.chat, rung))
return chat
def _coach(
statement: str,
history: list[dict[str, str]],
gate: phase.PhaseGate | None,
*,
free: bool,
) -> local_coach.LocalCoach | None:
"""The coach, announced; ``None`` when kuhy declines the local model."""
if not free and not confirm_gpu():
print("[not loading the local model]")
return None
coach = local_coach.LocalCoach.start(statement, history)
if free:
coach.chat = free_chat(OllamaAfterGpuCheck())
if gate is not None:
gate.known = statement
coach.leak_guard = gate.leaks
label = (
f"free: {omniroute_backend.MODEL} via OmniRoute"
if free
else f"local: {local_backend.MODEL} via Ollama"
)
print(f"[{label}]\n\n...", flush=True)
return coach
def run(
problem: str,
history: list[dict[str, str]],
first: str,
read: Callable[[], str | None],
gate: phase.PhaseGate | None = None,
*,
free: bool = False,
) -> int:
"""Coach locally until kuhy quits. `first` is sent before reading input.
"""Coach without Claude until kuhy quits. `first` is sent before reading input.
`free` (the usage-limit hand-over) coaches on OmniRoute first, Ollama after.
With a `gate`, every block passes the req-before-code phase gate first and
every reply the toolbox leak check (`first` was screened by the caller).
"""
@ -137,20 +211,18 @@ def run(
if not statement:
return 1
try:
if not confirm_gpu():
print("[not loading the local model]")
coach = _coach(statement, history, gate, free=free)
if coach is None:
return 1
coach = local_coach.LocalCoach.start(statement, history)
if gate is not None:
gate.known = statement
coach.leak_guard = gate.leaks
print(f"[local: {local_backend.MODEL} via Ollama]\n\n...", flush=True)
show(coach.respond(first), coach, gate)
while (block := read()) is not None and not is_quit(block):
if (sent := _screen(gate, block)) is None:
continue
print("\n...", flush=True)
show(coach.respond(sent), coach, gate)
except GpuRefusedError:
print("[neither OmniRoute nor Ollama answered: try again later]")
return 1
except (urllib.error.URLError, ConnectionError) as exc:
_LOG.warning("Ollama is not reachable: %s", exc)
print(f"[Ollama is not reachable at {local_backend.OLLAMA_URL}: {exc}]")

View File

@ -0,0 +1,131 @@
"""OmniRoute transport for the /leetcode coach: the free models, after Claude.
When Claude reports a usage limit the coach goes on with OmniRoute's
``free-best`` chain (kuhy 2026-11-27), and with Ollama only if the gateway is
down (``free_chain``). One non-streaming OpenAI ``/v1/chat/completions`` call
per reply, so the no-solution gate in ``local_coach`` judges the whole draft
before anything reaches the screen, exactly as for Ollama.
The gateway is local (docker ``omniroute`` on 127.0.0.1:20128); a non-loopback
URL is refused. The free providers behind it log prompts: the coach's prompts
carry the problem and kuhy's attempts and nothing else (kuhy accepted that).
An empty answer (``content: null`` from a reasoning member, an empty choice
list) is a :class:`GatewayError`, so the chain falls through instead of
showing nothing.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import time
from typing import TYPE_CHECKING, Any, Final
import urllib.parse
import urllib.request
from leetcode_coach import local_backend
if TYPE_CHECKING:
from collections.abc import Callable
DEFAULT_URL: Final = "http://127.0.0.1:20128"
URL_ENV: Final = "LEETCODE_OMNIROUTE_URL"
"""Overrides :data:`DEFAULT_URL` (a test's fake gateway, a dead port)."""
KEY_FILE = Path.home() / ".config" / "omniroute" / "api_key"
MODEL: Final = "free-best"
MAX_TOKENS: Final = 4000
"""Reasoning members spend small budgets on thinking and return nothing."""
CONTEXT_TOKENS: Final = 32768
"""The combo's prompt limit; a longer prompt would be cut silently."""
TEMPERATURE: Final = 0.4
REQUEST_TIMEOUT_S: Final = 120.0
_LOOPBACK: Final = frozenset({"127.0.0.1", "localhost", "::1"})
class GatewayError(ConnectionError):
"""The gateway answered nothing usable; the chain moves to the next rung."""
def gateway_url() -> str:
"""The gateway base URL, read at call time."""
return os.environ.get(URL_ENV) or DEFAULT_URL
def read_key(path: Path | None = None) -> str:
"""The gateway's Bearer key (never printed)."""
try:
return (path or KEY_FILE).read_text(encoding="utf-8").strip()
except OSError as exc:
msg = f"OmniRoute key unreadable: {exc}"
raise GatewayError(msg) from exc
def http_json(
url: str,
payload: dict[str, Any],
timeout: float,
*,
key_file: Path | None = None,
) -> dict[str, Any]:
"""POST ``payload`` with the Bearer key to the local gateway; decode the JSON."""
host = urllib.parse.urlsplit(url).hostname or ""
if not url.startswith("http://") or host not in _LOOPBACK:
msg = f"refusing a non-loopback gateway URL: {url}"
raise ValueError(msg)
req = urllib.request.Request(
url,
data=json.dumps(payload).encode(),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {read_key(key_file)}",
},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
answer: dict[str, Any] = json.loads(resp.read().decode())
return answer
def _content(data: dict[str, Any]) -> str:
"""The first choice's text, or ``""``."""
choices = data.get("choices") or [{}]
message = choices[0].get("message") or {}
return str(message.get("content") or "")
def chat(
messages: list[dict[str, str]],
*,
post: Callable[[str, dict[str, Any], float], dict[str, Any]] = http_json,
clock: Callable[[], float] = time.monotonic,
timeout: float = REQUEST_TIMEOUT_S,
) -> local_backend.LocalReply:
"""Ask ``free-best`` for the next assistant message.
Raises:
ContextOverflowError: the prompt would not fit the combo's limit.
GatewayError: the gateway answered no text.
"""
if local_backend.estimate_tokens(messages) >= CONTEXT_TOKENS:
msg = f"conversation too long for the gateway ({CONTEXT_TOKENS} tokens)"
raise local_backend.ContextOverflowError(msg)
payload = {
"model": MODEL,
"messages": messages,
"stream": False,
"max_tokens": MAX_TOKENS,
"temperature": TEMPERATURE,
}
start = clock()
data = post(f"{gateway_url()}/v1/chat/completions", payload, timeout)
text = local_backend.strip_think(_content(data))
if not text:
msg = f"{MODEL} answered no text"
raise GatewayError(msg)
return local_backend.LocalReply(
text=text,
seconds=clock() - start,
prompt_tokens=int((data.get("usage") or {}).get("prompt_tokens") or 0),
via="omniroute",
model=str(data.get("model") or MODEL),
)

View File

@ -23,7 +23,13 @@ import time
from typing import TYPE_CHECKING, Any, Final
import urllib.error
from leetcode_coach import claude_cli, local_backend, local_cards, local_coach
from leetcode_coach import (
claude_cli,
free_chain,
local_backend,
local_cards,
local_coach,
)
from leetcode_coach.relay.errors import CoachError
if TYPE_CHECKING:
@ -60,9 +66,9 @@ class CoachChat:
def __init__(
self,
ask: Callable[..., dict[str, Any]] = claude_cli.ask,
local_chat: Callable[..., local_backend.LocalReply] = local_backend.chat,
local_chat: Callable[..., local_backend.LocalReply] = free_chain.chat,
) -> None:
"""Bind the claude call and the local model (both injectable)."""
"""Bind the claude call and the free chain (OmniRoute, then Ollama)."""
self._ask = ask
self._local_chat = local_chat
self.monotonic: Callable[[], float] = time.monotonic

View File

@ -16,7 +16,7 @@ import logging
import threading
from typing import TYPE_CHECKING, Any, Final
from leetcode_coach import answer_key, claude_cli, local_backend, toolbox
from leetcode_coach import answer_key, claude_cli, free_chain, local_backend, toolbox
from leetcode_coach.relay import config, grading, protocol, runcode, steps, turns
from leetcode_coach.relay.chat import REQUEST_CAP_S, CoachChat
from leetcode_coach.relay.errors import CoachError
@ -45,7 +45,7 @@ class Deps:
state_dir: Path = field(default_factory=config.state_dir)
ask: Callable[..., dict[str, Any]] = claude_cli.ask
local_chat: Callable[..., local_backend.LocalReply] = local_backend.chat
local_chat: Callable[..., local_backend.LocalReply] = free_chain.chat
fetch: Callable[[str], tuple[str, str] | None] = turns.fetch_statement
probe: AcceptedProbe = field(default_factory=AcceptedProbe)
run_code: Callable[[str, str], dict[str, Any]] = runcode.run

View File

@ -1,9 +1,10 @@
"""Judge kuhy's requirement list, and ambiguous code, on a cheap model.
DOCS-coach-spec.md decision 5: a separate ``claude -p --model haiku`` call (the
coaching session stays on opus), Ollama through `local_backend` when haiku
is out of quota, errors or answers something that is not the JSON asked for,
and when neither answers the gate fails OPEN: ``unverified``, kuhy continues.
coaching session stays on opus), the free chain (`free_chain`: OmniRoute
`free-best`, then Ollama) when haiku is out of quota, errors or answers
something that is not the JSON asked for, and when neither answers the gate
fails OPEN: ``unverified``, kuhy continues.
The checker may only name *missing properties* from the toolbox vocabulary.
That is enforced here, not trusted to the prompt: every ``missing`` item that
@ -25,7 +26,7 @@ import logging
from typing import TYPE_CHECKING, Any
import urllib.error
from leetcode_coach import claude_cli, local_backend
from leetcode_coach import claude_cli, free_chain, local_backend
if TYPE_CHECKING:
from collections.abc import Callable
@ -36,7 +37,8 @@ _LOG = logging.getLogger(__name__)
HAIKU_TIMEOUT_S = 50.0
LOCAL_TIMEOUT_S = 200.0
"""Ollama's share of a check: with haiku's 50 s it fits the relay's 280 s cap."""
"""The free chain's share of a check (both rungs together, ``free_chain``):
with haiku's 50 s it fits the relay's 280 s cap."""
HAIKU_ARGS = [
"--model",
"haiku",
@ -175,7 +177,7 @@ def ask_models[T](
ask: Callable[..., dict[str, Any]] | None,
schema: dict[str, Any] | None = None,
) -> tuple[T, str] | None:
"""The first validated answer and who gave it, then Ollama.
"""The first validated answer and who gave it, then the free chain.
`ask` is the CLI-style ``(args, prompt, **kw)`` (default: haiku) or a
structured ``(system, prompt, schema) -> dict`` model function.
@ -189,7 +191,7 @@ def ask_models[T](
if got is not None:
return got, via
try:
local = local_backend.chat(
local = free_chain.chat(
[
{"role": "system", "content": system},
{"role": "user", "content": prompt},
@ -197,10 +199,10 @@ def ask_models[T](
timeout=LOCAL_TIMEOUT_S,
)
except (urllib.error.URLError, OSError, local_backend.ContextOverflowError) as exc:
_LOG.warning("Ollama could not answer the check either: %s", exc)
_LOG.warning("the free models could not answer the check either: %s", exc)
return None
got = validate(extract_json(local.text))
return None if got is None else (got, "ollama")
return None if got is None else (got, local.via)
def check(

View File

@ -0,0 +1,65 @@
"""A scripted OmniRoute (OpenAI chat API) on a free localhost port.
``POST /v1/chat/completions`` answers the next scripted text as ``free-best``'s
member ``fake/free``; every request's ``Authorization`` header and body are
kept for the test to assert on.
"""
from __future__ import annotations
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import threading
from typing import Self
class _Server(ThreadingHTTPServer):
answers: list[str]
auth: list[str]
bodies: list[bytes]
class _Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
"""The next scripted answer, in the OpenAI shape."""
owner = self.server
assert isinstance(owner, _Server)
length = int(self.headers["Content-Length"])
owner.bodies.append(self.rfile.read(length))
owner.auth.append(self.headers.get("Authorization", ""))
text = owner.answers.pop(0)
body = {"model": "fake/free", "choices": [{"message": {"content": text}}]}
data = json.dumps(body).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *_args: object) -> None:
"""Quiet."""
class FakeOmniRoute:
"""Start with scripted answers; ``url`` goes into ``LEETCODE_OMNIROUTE_URL``."""
def __init__(self, answers: list[str]) -> None:
"""Bind a free port."""
self._server = _Server(("127.0.0.1", 0), _Handler)
self._server.answers = list(answers)
self._server.auth = []
self._server.bodies = []
self.url = f"http://127.0.0.1:{self._server.server_address[1]}"
self.auth = self._server.auth
self.bodies = self._server.bodies
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
def __enter__(self) -> Self:
"""Serve in a thread."""
self._thread.start()
return self
def __exit__(self, *_exc: object) -> None:
"""Stop serving."""
self._server.shutdown()
self._server.server_close()

View File

@ -1,6 +1,7 @@
"""Keep every coach test off the real machine.
No session log under ~/.local, no real `claude` binary, no Ollama on :11434,
no OmniRoute on :20128 (a dead port and a scratch key),
no cluster leaking in from the shell, and the gates (`toolbox.load_safe`) on
the small fixture toolbox, so a reviewed edit of the real `toolbox.json` cannot
flip a leak test. `toolbox.load` (cards, clusters) still reads the real file.
@ -22,6 +23,7 @@ import pytest
from leetcode_coach import (
flagged,
local_backend,
omniroute_backend,
progress,
review_cli,
review_ledger,
@ -62,6 +64,9 @@ def _hermetic_coach(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator
monkeypatch.setenv(session_log.LOG_ENV, "")
monkeypatch.setenv("LEETCODE_CLAUDE_BIN", str(tmp_path / "no-such-claude"))
monkeypatch.setattr(local_backend, "OLLAMA_URL", DEAD_OLLAMA)
monkeypatch.setenv(omniroute_backend.URL_ENV, DEAD_OLLAMA)
monkeypatch.setattr(omniroute_backend, "KEY_FILE", tmp_path / "omniroute-key")
(tmp_path / "omniroute-key").write_text("test-key\n", encoding="utf-8")
real = toolbox.load_safe
def fixture_toolbox(path: Path | None = None) -> toolbox.Toolbox:

View File

@ -166,7 +166,9 @@ def test_ask_models_is_public_and_bounds_the_local_call(
got = req_check.ask_models("sys", "p", lambda o: o, limit)
assert got == ({"ok": 1}, "ollama")
assert seen == [req_check.LOCAL_TIMEOUT_S]
# The free chain's dead gateway rung spent a moment of the shared budget.
assert len(seen) == 1
assert req_check.LOCAL_TIMEOUT_S - 5 < seen[0] <= req_check.LOCAL_TIMEOUT_S
assert req_check.LOCAL_TIMEOUT_S + req_check.HAIKU_TIMEOUT_S < 280

View File

@ -0,0 +1,126 @@
"""The REPL's usage-limit path: OmniRoute ``free-best`` first, Ollama only after.
kuhy 2026-11-27 (part 9005c9b4-2): a Claude usage limit hands the session to
the free models, through the same no-solution gate, so a leaking draft is
rejected and regenerated, never printed.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from leetcode_coach import (
leetcode_repl,
local_backend,
local_session,
omniroute_backend,
)
from leetcode_coach.tests._fake_omniroute import FakeOmniRoute
from leetcode_coach.tests._shared import LEAK, SAFE, STATEMENT, FakeChat
if TYPE_CHECKING:
import pytest
def _statement(monkeypatch: pytest.MonkeyPatch, *, gpu_ok: bool = True) -> list[str]:
asked: list[str] = []
monkeypatch.setattr(local_session, "fetch_statement", lambda _p, _r: STATEMENT)
def confirm() -> bool:
asked.append("gpu")
return gpu_ok
monkeypatch.setattr(local_session, "confirm_gpu", confirm)
return asked
def test_free_run_answers_through_omniroute_without_touching_the_gpu(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
asked = _statement(monkeypatch)
with FakeOmniRoute([SAFE]) as fake:
monkeypatch.setenv(omniroute_backend.URL_ENV, fake.url)
got = local_session.run("two-sum", [], "Start.", lambda: None, free=True)
out = capsys.readouterr().out
assert got == 0
assert out.startswith("[free: free-best via OmniRoute]\n\n...\n")
assert SAFE in out
assert asked == []
def test_a_leaking_free_draft_is_regenerated_and_never_printed(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_statement(monkeypatch)
with FakeOmniRoute([LEAK, SAFE]) as fake:
monkeypatch.setenv(omniroute_backend.URL_ENV, fake.url)
assert local_session.run("two-sum", [], "Start.", lambda: None, free=True) == 0
out = capsys.readouterr().out
assert "seen.set" not in out
assert SAFE in out
assert len(fake.bodies) == 2
def test_a_dead_gateway_falls_through_to_ollama_after_the_gpu_check(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
asked = _statement(monkeypatch)
ollama = FakeChat(SAFE)
monkeypatch.setattr(local_backend, "chat", lambda m, **_k: ollama(m))
assert local_session.run("two-sum", [], "Start.", lambda: None, free=True) == 0
out = capsys.readouterr().out
assert f"[OmniRoute down: local {local_backend.MODEL} via Ollama]" in out
assert SAFE in out
assert asked == ["gpu"]
def test_the_gpu_is_asked_once_per_free_session(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
asked = _statement(monkeypatch)
ollama = FakeChat(SAFE, SAFE)
monkeypatch.setattr(local_backend, "chat", lambda m, **_k: ollama(m))
blocks = iter(["hint", "quit"])
assert (
local_session.run("two-sum", [], "Start.", lambda: next(blocks), free=True) == 0
)
assert asked == ["gpu"]
assert capsys.readouterr().out.count("OmniRoute down") == 1
def test_a_refused_gpu_ends_the_free_session_once_omniroute_is_down(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_statement(monkeypatch, gpu_ok=False)
assert local_session.run("two-sum", [], "Start.", lambda: None, free=True) == 1
out = capsys.readouterr().out
assert "[not loading the local model]" in out
assert "neither OmniRoute nor Ollama answered" in out
def test_the_repl_hands_a_limit_to_the_free_chain(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(leetcode_repl, "ask", lambda *_a: {"api_error_status": 429})
handed: dict[str, Any] = {}
def fake_run(*_a: object, **kw: object) -> int:
handed.update(kw)
return 0
monkeypatch.setattr(local_session, "run", fake_run)
assert leetcode_repl.run_claude("sonnet", ["two-sum"]) == 0
assert handed["free"] is True
def test_local_mode_stays_on_ollama(monkeypatch: pytest.MonkeyPatch) -> None:
"""``leetcode --local`` is the explicit offline choice: no gateway."""
handed: dict[str, Any] = {}
def fake_run(*_a: object, **kw: object) -> int:
handed.update(kw)
return 0
monkeypatch.setattr(local_session, "run", fake_run)
assert leetcode_repl.main(["--local", "two-sum"]) == 0
assert handed.get("free", False) is False

View File

@ -69,7 +69,7 @@ def test_limit_mid_session_falls_back_with_history(
assert capsys.readouterr().out == (
"Restated. What feels unclear?\n\n...\n"
"[You've hit your session limit · resets 8pm (Europe/Warsaw) "
"-- continuing locally]\n"
"-- continuing on the free models]\n"
)
@ -82,7 +82,7 @@ def test_limit_on_the_first_turn_starts_locally(
assert leetcode_repl.run_claude("sonnet", ["two-sum"]) == 0
assert handed["history"] == []
assert "not said" in handed["first"]
assert capsys.readouterr().out == "[usage limit -- switching to local model]\n"
assert capsys.readouterr().out == "[usage limit -- switching to the free models]\n"
def test_session_loop_until_quit_and_missing_session(
@ -179,6 +179,61 @@ def test_launcher_runs_the_package_repl() -> None:
assert proc.stdout.startswith("Usage: leetcode [--local]")
def _fake_free(tmp_path: Path) -> dict[str, str]:
fake = tmp_path / "claude-free"
fake.write_text('#!/bin/bash\nprintf "%s\\n" "$PWD" "$@"\n', encoding="utf-8")
fake.chmod(0o755)
return {**os.environ, "LEETCODE_CLAUDE_FREE_BIN": str(fake)}
def test_launcher_free_starts_claude_free_in_its_tmp_dir(tmp_path: Path) -> None:
"""``leetcode --free two-sum``: claude-free, /leetcode loaded, cwd in /tmp."""
env = {**_fake_free(tmp_path), "LEETCODE_FREE_DIR": str(tmp_path / "free")}
proc = subprocess.run(
[str(LAUNCHER), "--free", "two-sum", "maps"],
capture_output=True,
text=True,
check=False,
env=env,
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.splitlines() == [
str(tmp_path / "free"),
"/leetcode two-sum maps",
]
assert (tmp_path / "free").stat().st_mode & 0o777 == 0o700
def test_launcher_free_defaults_to_tmp() -> None:
"""The shared temp root itself, not $TMPDIR: claude-free's gate allows it only."""
body = LAUNCHER.read_text(encoding="utf-8")
assert "LEETCODE_FREE_DIR:-" + str(Path("/") / "tmp" / "leetcode-free") in body
def test_launcher_free_refuses_a_planted_dir(tmp_path: Path) -> None:
"""A symlink (someone else's dir in shared /tmp) is never entered."""
(tmp_path / "elsewhere").mkdir()
(tmp_path / "free").symlink_to(tmp_path / "elsewhere")
env = {**_fake_free(tmp_path), "LEETCODE_FREE_DIR": str(tmp_path / "free")}
proc = subprocess.run(
[str(LAUNCHER), "--free", "two-sum"],
capture_output=True,
text=True,
check=False,
env=env,
)
assert proc.returncode == 77
assert proc.stdout == ""
def test_launcher_free_needs_a_problem() -> None:
proc = subprocess.run(
[str(LAUNCHER), "--free"], capture_output=True, text=True, check=False
)
assert proc.returncode == 64
assert "Usage: leetcode --free" in proc.stderr
def test_launcher_does_not_leak_pythonpath_into_the_session() -> None:
"""The REPL hands its environment to `claude -p`; the launcher adds nothing."""
body = LAUNCHER.read_text(encoding="utf-8").split("set -euo pipefail", 1)[1]

View File

@ -0,0 +1,153 @@
"""Tests for the OmniRoute transport and the free chain (OmniRoute, then Ollama)."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
import urllib.error
import pytest
from leetcode_coach import free_chain, local_backend, omniroute_backend
from leetcode_coach.tests._fake_omniroute import FakeOmniRoute
if TYPE_CHECKING:
from pathlib import Path
Q = [{"role": "user", "content": "q"}]
def _answer(text: str | None, model: str = "groq/llama") -> dict[str, Any]:
return {"model": model, "choices": [{"message": {"content": text}}]}
def test_chat_asks_free_best_with_a_real_budget() -> None:
sent: list[dict[str, Any]] = []
def post(url: str, payload: dict[str, Any], _t: float) -> dict[str, Any]:
assert url.endswith("/v1/chat/completions")
sent.append(payload)
return _answer("<think>x</think>Hint")
reply = omniroute_backend.chat(Q, post=post, clock=lambda: 2.0)
assert (reply.text, reply.via, reply.model) == ("Hint", "omniroute", "groq/llama")
assert sent[0]["model"] == "free-best"
assert sent[0]["max_tokens"] >= 1000
assert sent[0]["stream"] is False
@pytest.mark.parametrize("body", [_answer(None), _answer(" "), {"choices": []}, {}])
def test_an_empty_answer_is_a_gateway_error(body: dict[str, Any]) -> None:
"""``content: null`` (a reasoning member out of budget) must fall through."""
with pytest.raises(omniroute_backend.GatewayError):
omniroute_backend.chat(Q, post=lambda *_a: body)
def test_a_prompt_over_the_combo_limit_overflows() -> None:
big = [{"role": "user", "content": "x" * (omniroute_backend.CONTEXT_TOKENS * 4)}]
with pytest.raises(local_backend.ContextOverflowError):
omniroute_backend.chat(big, post=lambda *_a: _answer("x"))
def test_http_json_sends_the_bearer_key(tmp_path: Path) -> None:
key = tmp_path / "api_key"
key.write_text("sekrit\n", encoding="utf-8")
with FakeOmniRoute(["Hint"]) as fake:
got = omniroute_backend.http_json(
fake.url + "/v1/chat/completions", {"x": 1}, 5.0, key_file=key
)
assert got["choices"][0]["message"]["content"] == "Hint"
assert fake.auth == ["Bearer sekrit"]
assert json.loads(fake.bodies[0]) == {"x": 1}
def test_http_json_refuses_a_remote_url(tmp_path: Path) -> None:
"""The prompts may only go to the local gateway."""
with pytest.raises(ValueError, match="non-loopback"):
omniroute_backend.http_json("https://example.com/v1", {}, 1.0)
def test_a_missing_key_is_a_gateway_error(tmp_path: Path) -> None:
with pytest.raises(omniroute_backend.GatewayError, match="key"):
omniroute_backend.read_key(tmp_path / "nope")
def test_the_chain_answers_from_omniroute_first() -> None:
def ollama(*_a: object, **_k: object) -> local_backend.LocalReply:
msg = "Ollama must not be asked"
raise AssertionError(msg)
def omni(_m: object, **_k: object) -> local_backend.LocalReply:
return local_backend.LocalReply("Hint", 1.0, 0, via="omniroute")
reply = free_chain.chat(Q, timeout=5.0, rungs=(omni, ollama))
assert reply.via == "omniroute"
@pytest.mark.parametrize(
"error",
[
urllib.error.URLError("refused"),
ConnectionRefusedError(),
omniroute_backend.GatewayError("empty"),
local_backend.ContextOverflowError("big"),
TimeoutError(),
],
)
def test_the_chain_falls_through_to_ollama(error: Exception) -> None:
seen: list[str] = []
def omni(_m: object, **_k: object) -> local_backend.LocalReply:
raise error
def ollama(_m: object, **kw: object) -> local_backend.LocalReply:
seen.append(str(kw.get("timeout")))
return local_backend.LocalReply("Hint", 1.0, 0)
reply = free_chain.chat(
Q, timeout=7.0, rungs=(omni, ollama), on_fallback=seen.append, clock=lambda: 0.0
)
assert reply.via == "ollama"
assert seen[0].startswith("omniroute")
assert seen[1] == "7.0"
def test_the_chain_raises_the_last_error_when_every_rung_fails() -> None:
def down(_m: object, **_k: object) -> local_backend.LocalReply:
raise ConnectionRefusedError
with pytest.raises(ConnectionRefusedError):
free_chain.chat(Q, rungs=(down, down))
def test_the_default_chain_uses_the_gateway_then_ollama() -> None:
"""Hermetic conftest: both are dead ports, so the chain ends in Ollama's error."""
with pytest.raises(urllib.error.URLError, match="refused"):
free_chain.chat(Q, timeout=2.0)
def test_the_live_gateway_url_is_loopback() -> None:
assert omniroute_backend.DEFAULT_URL == "http://127.0.0.1:20128"
assert omniroute_backend.MODEL == "free-best"
def test_the_chain_shares_one_deadline() -> None:
"""A slow first rung leaves the second only what is left of ``timeout``."""
now = [0.0]
budgets: list[float] = []
def slow(_m: object, *, timeout: float) -> local_backend.LocalReply:
budgets.append(timeout)
now[0] += 8.0
raise TimeoutError
def last(_m: object, *, timeout: float) -> local_backend.LocalReply:
budgets.append(timeout)
return local_backend.LocalReply("Hint", 1.0, 0)
free_chain.chat(Q, timeout=10.0, rungs=(slow, last), clock=lambda: now[0])
assert budgets == [10.0, 2.0]
now[0] = 0.0
with pytest.raises(TimeoutError, match="no time left"):
free_chain.chat(Q, timeout=8.5, rungs=(slow, last), clock=lambda: now[0])

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "leetcode-coach"
version = "0.1.6"
version = "0.1.7"
description = "The /leetcode coach as a library: phase gate, leak and stop gates, session log, grading, cards, relay"
requires-python = ">=3.14"
# Everything below loads lazily (rtdb, make_cards, relay.__main__): importing
@ -68,7 +68,9 @@ unfixable = []
# --unsafe-fixes, so without these entries the fixer deletes those prints and
# still exits 0. Their tests assert on stdout.
"leetcode_coach/leetcode_repl.py" = ["T201"]
"leetcode_coach/local_session.py" = ["T201"]
# T201: its prints ARE the session. PLR0913: run() is the REPL's whole hand-over
# (problem, history, first block, reader, gate, free).
"leetcode_coach/local_session.py" = ["T201", "PLR0913"]
"leetcode_coach/make_cards.py" = ["T201"]
"leetcode_coach/fetch_problem.py" = ["S310", "T201"]
"leetcode_coach/history.py" = ["T201"]
@ -97,6 +99,8 @@ unfixable = []
"leetcode_coach/relay/phone.py" = ["PLR0913"]
"leetcode_coach/relay/graders.py" = ["PLR0913"]
"leetcode_coach/local_backend.py" = ["S310"]
# S310: the gateway URL is checked to be loopback http before urlopen.
"leetcode_coach/omniroute_backend.py" = ["S310"]
"leetcode_coach/guard_bridge.py" = ["D101", "D102", "D103"]
"leetcode_coach/shape.py" = ["D103"]
"leetcode_coach/gate_notes.py" = ["D103"]