From eddd1a38f86595c2de0ba2342019d3632b30cd69 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 22 Nov 2026 17:36:33 +0100 Subject: [PATCH] Give the coach kuhy's submission history history.py prints the guard's per-problem mirror (every status, code cut at 1500 chars, newest 12); SKILL.md reads it at the start, for the coach only. Read-only context, never a gate input. Co-Authored-By: Claude Opus 5.5 --- leetcode_coach/leetcode_coach/SKILL.md | 10 +- leetcode_coach/leetcode_coach/history.py | 111 ++++++++++ .../leetcode_coach/tests/test_history.py | 194 ++++++++++++++++++ leetcode_coach/pyproject.toml | 1 + 4 files changed, 311 insertions(+), 5 deletions(-) create mode 100755 leetcode_coach/leetcode_coach/history.py create mode 100644 leetcode_coach/leetcode_coach/tests/test_history.py diff --git a/leetcode_coach/leetcode_coach/SKILL.md b/leetcode_coach/leetcode_coach/SKILL.md index 63a0e98..66feaaa 100644 --- a/leetcode_coach/leetcode_coach/SKILL.md +++ b/leetcode_coach/leetcode_coach/SKILL.md @@ -36,6 +36,8 @@ python3 ~/.claude/skills/leetcode/fetch_problem.py "" never quote it to kuhy unasked. Default starter language is JavaScript (`--lang python3` etc. if kuhy asks). +Then `python3 ~/.claude/skills/leetcode/history.py ""`: his own attempts, +failed and accepted, with code. For you only: never paste it back; ask where it broke. ## 2. Open @@ -214,8 +216,8 @@ the method appeared. ## 5d. Cold re-test `[cold re-test]` in the arguments (`leetcode --retest `, due +3 and -+10 days after a solve) means kuhy solved this before; you have no history, -so do not ask about the old code. In the opening, say plainly: **do NOT ++10 days after a solve) means kuhy solved this before; `history.py` has his old +code, for you only: it is solved cold. In the opening, say plainly: **do NOT submit on LeetCode** -- a resubmission mints a gate credit. Then coach as usual, requirement list first, and judge by running the statement's examples locally with `node` (section 4). The normal exit and post-mortem (5, 5b) @@ -234,12 +236,10 @@ Runs on **sonnet, opus or fable** as written. Haiku went in circles (~30 micro-questions on an Easy, 2026-10-18); `model:` frontmatter is ignored for skills (2026-09-18), so only if you are haiku, the **first line** of your opening message is - > Type `/model sonnet` now — learning sessions are gated to sonnet, opus or > fable; your next message is refused until you do (or send `keep model`). -then continue with the opening. `hooks/leetcode_model_gate_userprompt.sh` -enforces it from the next prompt on. +then continue with the opening (`hooks/leetcode_model_gate_userprompt.sh`). The right client is `leetcode ` (print mode: the Stop hook can still withhold a reply; the TUI has already streamed it). `leetcode --local` runs diff --git a/leetcode_coach/leetcode_coach/history.py b/leetcode_coach/leetcode_coach/history.py new file mode 100755 index 0000000..67341ca --- /dev/null +++ b/leetcode_coach/leetcode_coach/history.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Print kuhy's own submissions on one problem, failed and accepted, with code. + +Usage: history.py + +kuhy, 2026-11-22: a Claude coaching a problem "should also have access to my +history of approaches", including the ones that succeeded. leetcode-guard's +one-minute harvester mirrors every submission (status, time, code) into +``~/.local/share/leetcode_guard/history/.json`` (``_history_store`` in +leetcode-guard documents the shape). This reads that mirror, read-only, and +prints a bounded summary: the newest :data:`SHOWN` submissions, each code +cut at :data:`CODE_CHARS`. The mirror is display-only context and never a +gate input; nothing here writes. + +Exit codes: 0 printed (also "no mirror yet" and "unreadable"), 1 bad input. + +Stdlib only and free of package imports, like ``fetch_problem.py``: SKILL.md +runs it by path. Its stdout IS its interface (T201 exemption in pyproject.toml). +""" + +from __future__ import annotations + +from datetime import UTC, datetime +import json +from pathlib import Path +import re +import sys +from typing import Final + +HISTORY_DIR: Final = Path.home() / ".local" / "share" / "leetcode_guard" / "history" +SHOWN: Final = 12 +"""Newest submissions printed; older ones are counted, not shown.""" +CODE_CHARS: Final = 1500 +"""Code longer than this is cut: one huge paste must not flood the context.""" +_ARGC: Final = 2 +"""argv is the script and one problem.""" + + +def slug_from(arg: str) -> str: + """A full problem URL or a bare slug; anything else raises ``ValueError``.""" + found = re.search(r"leetcode\.(?:com|cn)/problems/([a-z0-9-]+)", arg) + if found: + return found.group(1) + if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", arg): + return arg + msg = f"not a LeetCode slug: {arg!r}" + raise ValueError(msg) + + +def _when(raw: object) -> str: + """Unix seconds as a UTC minute, ``?`` when off.""" + if isinstance(raw, int) and not isinstance(raw, bool): + return datetime.fromtimestamp(raw, tz=UTC).strftime("%Y-%m-%d %H:%M UTC") + return "?" + + +def _row(item: dict[str, object]) -> str: + """One submission: a header line and its code block.""" + stats = ", ".join(str(item.get(key, "?")) for key in ("lang", "runtime", "memory")) + head = f"### {item.get('status', '?')} - {_when(item.get('timestamp'))} - {stats}" + code = item.get("code") + if not isinstance(code, str): + return f"{head}\n(code not mirrored yet)" + cut = "\n[cut]" if len(code) > CODE_CHARS else "" + return f"{head}\n```\n{code[:CODE_CHARS]}{cut}\n```" + + +def render(arg: str) -> str: + """The summary for one problem, as markdown.""" + slug = slug_from(arg) + path = HISTORY_DIR / f"{slug}.json" + if not path.exists(): + return f"No mirrored submissions for {slug} yet." + try: + data = json.loads(path.read_text(encoding="utf-8")) + except OSError, ValueError: + data = None + rows = data.get("submissions") if isinstance(data, dict) else None + if not isinstance(rows, list): + return f"The submission mirror for {slug} is unreadable." + items = [item for item in rows if isinstance(item, dict)] + items.sort(key=lambda item: _stamp(item.get("timestamp")), reverse=True) + accepted = sum(item.get("status") == "Accepted" for item in items) + title = f"{len(items)} submissions ({accepted} accepted)" + parts = [f"# kuhy's submissions on {slug}: {title}"] + parts += [_row(item) for item in items[:SHOWN]] + if len(items) > SHOWN: + parts.append(f"({len(items) - SHOWN} older not shown)") + return "\n\n".join(parts) + + +def _stamp(raw: object) -> int: + """A sort key: the timestamp, 0 when off.""" + return raw if isinstance(raw, int) and not isinstance(raw, bool) else 0 + + +def main() -> int: + """Print the summary for the problem named on argv.""" + if len(sys.argv) != _ARGC: + print("usage: history.py ", file=sys.stderr) + return 1 + try: + print(render(sys.argv[1])) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/leetcode_coach/leetcode_coach/tests/test_history.py b/leetcode_coach/leetcode_coach/tests/test_history.py new file mode 100644 index 0000000..50d91fe --- /dev/null +++ b/leetcode_coach/leetcode_coach/tests/test_history.py @@ -0,0 +1,194 @@ +"""Tests for ``history.py``: kuhy's own attempts on one problem, for the coach. + +The guard's harvester mirrors every submission with its code into +``~/.local/share/leetcode_guard/history/.json`` (phase 2, 2026-11-22). +The coach reads it as context, read-only, bounded. +""" + +from __future__ import annotations + +import json +import runpy +import sys +from typing import TYPE_CHECKING + +import pytest + +from leetcode_coach import history + +if TYPE_CHECKING: + from pathlib import Path + +MIRROR = { + "slug": "two-sum", + "fetched_at": 1795287060, + "complete": True, + "next_offset": 0, + "submissions": [ + { + "id": "3", + "status": "Accepted", + "lang": "python3", + "timestamp": 1795287000, + "runtime": "40 ms", + "memory": "17 MB", + "code": "class Solution:\n def twoSum(self): return seen", + }, + { + "id": "2", + "status": "Wrong Answer", + "lang": "python3", + "timestamp": 1795286000, + "runtime": "N/A", + "memory": "N/A", + "code": "x" * 5000, + }, + { + "id": "1", + "status": "Compile Error", + "lang": "python3", + "timestamp": 1795285000, + "runtime": "N/A", + "memory": "N/A", + }, + ], +} + + +@pytest.fixture(name="mirror_dir") +def _mirror_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A scratch history dir; the real one is never read.""" + folder = tmp_path / "history" + folder.mkdir() + monkeypatch.setattr(history, "HISTORY_DIR", folder) + return folder + + +def write(folder: Path, data: object, slug: str = "two-sum") -> None: + """Put one mirror file down.""" + (folder / f"{slug}.json").write_text(json.dumps(data), encoding="utf-8") + + +def test_every_attempt_is_listed_newest_first_with_code(mirror_dir: Path): + """Failed and accepted alike, each with its status, and code where fetched.""" + write(mirror_dir, MIRROR) + + text = history.render("two-sum") + + assert ( + text.index("Accepted") + < text.index("Wrong Answer") + < text.index("Compile Error") + ) + assert "return seen" in text + assert "(code not mirrored yet)" in text + assert "3 submissions (1 accepted)" in text + + +def test_long_code_is_cut(mirror_dir: Path): + """One huge paste must not flood the coach's context.""" + write(mirror_dir, MIRROR) + + text = history.render("two-sum") + + assert "x" * history.CODE_CHARS in text + assert "x" * (history.CODE_CHARS + 1) not in text + assert "[cut]" in text + + +def test_only_the_newest_submissions_are_shown(mirror_dir: Path): + """A problem with 60 attempts shows the newest few and says how many more.""" + rows = [ + {"id": str(n), "status": "Wrong Answer", "timestamp": 1795280000 + n} + for n in range(60) + ] + write(mirror_dir, {**MIRROR, "submissions": rows}) + + text = history.render("two-sum") + + assert text.count("Wrong Answer") == history.SHOWN + assert f"{60 - history.SHOWN} older not shown" in text + + +def test_no_mirror_says_so(mirror_dir: Path): + """No file yet (never submitted, or the harvester has not reached it).""" + assert mirror_dir.exists() + assert history.render("two-sum") == "No mirrored submissions for two-sum yet." + + +@pytest.mark.parametrize("data", ["{", [], {"submissions": 3}]) +def test_an_unreadable_mirror_is_reported_not_trusted(mirror_dir: Path, data: object): + """Hand-edited or half-written: say it is unreadable, never crash.""" + path = mirror_dir / "two-sum.json" + path.write_text( + data if isinstance(data, str) else json.dumps(data), encoding="utf-8" + ) + + assert ( + history.render("two-sum") == "The submission mirror for two-sum is unreadable." + ) + + +def test_a_bad_slug_is_refused(mirror_dir: Path): + """``../x`` is not a slug and never becomes a path.""" + assert mirror_dir.exists() + with pytest.raises(ValueError, match="not a LeetCode slug"): + history.render("../escape") + + +def test_cli_prints_and_takes_a_url( + mirror_dir: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +): + """Run by path like fetch_problem.py: a URL or a slug, exit 0.""" + write(mirror_dir, MIRROR) + monkeypatch.setattr( + sys, + "argv", + ["history.py", "https://leetcode.com/problems/two-sum/description/"], + ) + + assert history.main() == 0 + assert "Accepted" in capsys.readouterr().out + + +def test_cli_rejects_garbage( + mirror_dir: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +): + """Exit 1 with one stderr line, like fetch_problem.py's bad input.""" + assert mirror_dir.exists() + monkeypatch.setattr(sys, "argv", ["history.py", "../x"]) + + assert history.main() == 1 + assert "not a LeetCode slug" in capsys.readouterr().err + + +def test_runs_as_a_script(monkeypatch: pytest.MonkeyPatch, tmp_path: Path): + """``python3 history.py `` works without the package installed.""" + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setattr(sys, "argv", ["history.py", "two-sum"]) + + with pytest.raises(SystemExit) as stop: + runpy.run_path(history.__file__, run_name="__main__") + + assert stop.value.code == 0 + + +def test_cli_wants_exactly_one_problem( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +): + """No argument: the usage line on stderr, exit 1.""" + monkeypatch.setattr(sys, "argv", ["history.py"]) + + assert history.main() == 1 + assert "usage" in capsys.readouterr().err + + +def test_a_row_without_a_timestamp_still_prints(mirror_dir: Path): + """A hand-edited row missing its time shows ``?``, never crashes.""" + write(mirror_dir, {**MIRROR, "submissions": [{"id": "9", "status": "Accepted"}]}) + + assert "### Accepted - ? - ?, ?, ?" in history.render("two-sum") diff --git a/leetcode_coach/pyproject.toml b/leetcode_coach/pyproject.toml index cb7d1d7..f2edb5f 100644 --- a/leetcode_coach/pyproject.toml +++ b/leetcode_coach/pyproject.toml @@ -71,6 +71,7 @@ unfixable = [] "leetcode_coach/local_session.py" = ["T201"] "leetcode_coach/make_cards.py" = ["T201"] "leetcode_coach/fetch_problem.py" = ["S310", "T201"] +"leetcode_coach/history.py" = ["T201"] "leetcode_coach/eval_local.py" = ["T201"] "leetcode_coach/stop_gate.py" = ["T201"] "leetcode_coach/cluster_cli.py" = ["T201"]