utils/leetcode_coach/leetcode_coach/fetch_problem.py
Krzysztof kuhy Rudnicki b730cffaf4 Move the /leetcode coach skill into the repo as leetcode_coach/
Phase A of TODO-coach.md (decisions 1-3). The skill code is now a package here
with the same behaviour as before. Nothing new is added. ~/.claude/skills/leetcode
and ~/.local/bin/leetcode become symlinks into the package, created by
scripts/link_leetcode_coach.sh, which install.sh runs.

- Package imports replace the bare sibling imports. To stay under the 250-line
  cap, the Stop-hook detector is split into gate_detector.py and stop_gate.py,
  the card rules move into card_rules.py, and the prompt text moves into
  local_prompt.py.
- local_coach uses gate_detector directly. It no longer loads the hook file
  with importlib.
- make_cards runs on the system python: a genanki pin (pyproject and
  requirements) replaces the `uv run --script` header. The note guid is
  passed to genanki.Note explicitly, so CardNote is no longer subclassed;
  the guid values are unchanged.
- stop_gate also accepts the package path as a skill-load marker, because the
  harness may print the resolved symlink path.
- Every swallowing except now logs a warning. A NullHandler on the package
  logger keeps stdout/stderr the same as before.
- Modules whose prints are their interface (REPL, local session, card builder,
  fetcher, eval, Stop hook) get T201 per-file ignores, and their tests assert
  on stdout.
- hook_shims/ holds the 3-line ~/.claude/hooks shim. It is excluded from
  ruff, mypy, pylint and coverage, and a test runs it end to end.
- Pre-commit: a requirements-sync entry for each package, leetcode_coach and
  genanki added to the pylint hook, and the name-tests-test exclude widened.
  coverage and ruff are bumped to the latest stable releases because the
  dependency-freshness gate requires it.

Verification: 111 coach tests pass with 100% branch coverage. ruff, mypy
strict and pylint are clean (10.00). On the 370 assistant replies in 39 real
/leetcode transcripts, the old hook and stop_gate give the same verdict
(0 mismatches, 20 blocked). fetch_problem output (live two-sum) and
make_cards --dry-run output are byte-identical to the old skill, and so are
the note guids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PjvF5DZG9JduSBYKxqyysi
2026-10-23 15:06:40 +02:00

180 lines
6.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Fetch a LeetCode problem statement + starter code as markdown.
Usage: fetch_problem.py <url-or-slug> [--lang javascript]
Uses LeetCode's public GraphQL endpoint (no login). Exit codes:
0 printed the problem
1 bad input / network error
2 problem not available without login (premium) or unknown slug
Stdlib only and free of package imports on purpose: SKILL.md runs it by path
(`python3 ~/.claude/skills/leetcode/fetch_problem.py`), which works without
any install. Its stdout IS its interface (T201 exemption in pyproject.toml).
"""
from __future__ import annotations
import argparse
from html.parser import HTMLParser
import json
import logging
import re
import sys
from typing import Any
import urllib.error
import urllib.request
# A fixed name, and its own NullHandler: run by path this module is
# `__main__` and the package __init__ (which silences the package logger)
# never loads, so without both the warning below would print a second copy of
# the "fetch failed" line through logging's last-resort handler.
_LOG = logging.getLogger("leetcode_coach.fetch_problem")
_LOG.addHandler(logging.NullHandler())
GRAPHQL = "https://leetcode.com/graphql"
QUERY = """
query q($s: String!) {
question(titleSlug: $s) {
questionFrontendId title difficulty content isPaidOnly
codeSnippets { langSlug code }
topicTags { name }
hints
}
}
"""
EXIT_FAILED, EXIT_UNAVAILABLE = 1, 2
_OPEN = {"p": "\n", "div": "\n", "ul": "\n", "ol": "\n", "li": "\n- ", "br": "\n"}
_CLOSE = {"p": "\n", "div": "\n"}
_BOTH = {"strong": "**", "b": "**", "em": "_", "i": "_"}
class _HtmlToText(HTMLParser):
"""Minimal HTML -> markdown-ish text; keeps <pre>/<code> verbatim."""
def __init__(self) -> None:
super().__init__()
self.out: list[str] = []
self.in_pre = False
self.in_code = False
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
"""Open a fence, an inline code span or a markdown marker."""
del attrs # no attribute matters for the text
if tag == "pre":
self.in_pre = True
self.out.append("\n```\n")
elif tag == "code" and not self.in_pre:
self.in_code = True
self.out.append("`")
elif tag in _OPEN or tag in _BOTH:
self.out.append(_OPEN.get(tag) or _BOTH[tag])
def handle_endtag(self, tag: str) -> None:
"""Close what `handle_starttag` opened."""
if tag == "pre":
self.in_pre = False
self.out.append("\n```\n")
elif tag == "code" and self.in_code:
self.in_code = False
self.out.append("`")
elif tag in _CLOSE or tag in _BOTH:
self.out.append(_CLOSE.get(tag) or _BOTH[tag])
def handle_data(self, data: str) -> None:
"""Text: verbatim inside <pre>, whitespace-collapsed elsewhere."""
self.out.append(data if self.in_pre else re.sub(r"\s+", " ", data))
def text(self) -> str:
"""Everything fed so far, with runs of blank lines squeezed."""
return re.sub(r"\n{3,}", "\n\n", "".join(self.out)).strip()
def slug_from(arg: str) -> str:
"""Accept a full URL (with /description/, /submissions/, ?query) or a bare slug."""
m = re.search(r"leetcode\.(?:com|cn)/problems/([a-z0-9-]+)", arg)
if m:
return m.group(1)
if re.fullmatch(r"[a-z0-9-]+", arg):
return arg
msg = f"not a LeetCode problem URL or slug: {arg!r}"
raise ValueError(msg)
def fetch(slug: str) -> dict[str, Any] | None:
"""The GraphQL `question` object for `slug`, or None when LeetCode has none."""
body = json.dumps({"query": QUERY, "variables": {"s": slug}}).encode()
req = urllib.request.Request(
GRAPHQL,
data=body,
headers={
"Content-Type": "application/json",
"Referer": f"https://leetcode.com/problems/{slug}/",
"User-Agent": "Mozilla/5.0 (leetcode-coach skill)",
},
)
with urllib.request.urlopen(req, timeout=20) as resp: # fixed https URL
payload = json.load(resp)
question: dict[str, Any] | None = payload.get("data", {}).get("question")
return question
def render(q: dict[str, Any], lang: str) -> str:
"""Markdown: title, tags, statement, starter code, then the hidden hints."""
parser = _HtmlToText()
parser.feed(q["content"] or "")
tags = ", ".join(t["name"] for t in q["topicTags"]) or "none"
snippets = {s["langSlug"]: s["code"] for s in q["codeSnippets"]}
chosen = lang if lang in snippets else next(iter(snippets), None)
lines = [
f"# {q['questionFrontendId']}. {q['title']} ({q['difficulty']})",
f"Tags: {tags}",
f"Languages available: {', '.join(snippets) or 'none'}",
"",
parser.text(),
"",
]
if chosen:
lines += [
f"## Starter code ({chosen})",
"```",
snippets[chosen].rstrip(),
"```",
]
if q["hints"]:
lines += ["", "## Site hints (do NOT show to the user unasked)"]
lines += [f"- {h}" for h in q["hints"]]
return "\n".join(lines)
def main() -> int:
"""Print the problem named on argv; see the module docstring for exit codes."""
ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
ap.add_argument("problem", help="LeetCode problem URL or title slug")
ap.add_argument("--lang", default="javascript", help="starter-code language slug")
args = ap.parse_args()
try:
slug = slug_from(args.problem)
q = fetch(slug)
except (
ValueError,
urllib.error.URLError,
TimeoutError,
json.JSONDecodeError,
) as exc:
_LOG.warning("fetch failed: %s", exc)
print(f"fetch failed: {exc}", file=sys.stderr)
return EXIT_FAILED
if q is None or q.get("isPaidOnly") or not q.get("content"):
print(
f"problem {slug!r} is unknown or premium-only (no statement without login)",
file=sys.stderr,
)
return EXIT_UNAVAILABLE
print(render(q, args.lang))
return 0
if __name__ == "__main__":
sys.exit(main())