mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-25 23:47:24 +01:00
Compare commits
22 Commits
f865508eb4
...
88e4be5042
| Author | SHA1 | Date | |
|---|---|---|---|
| 88e4be5042 | |||
| 737bf624ca | |||
| 716231a7f3 | |||
| 11cb1d81d9 | |||
| e0c9befdeb | |||
| 612b0b3c0a | |||
| 1bfacdf51f | |||
| 99f4e171e3 | |||
| 2c926928dc | |||
| a78c1e971b | |||
| 2531f9eeb3 | |||
| f47ed80584 | |||
| 2a9732a312 | |||
| e06df74caf | |||
| 2d2d8a41f8 | |||
| 6343499ed1 | |||
| ebf7ca624e | |||
| c22b14389a | |||
| c0e902e5cc | |||
| 28c243d066 | |||
| 96a0d8af07 | |||
| b730cffaf4 |
73
.github/workflows/code-runner-precommit.yml
vendored
Normal file
73
.github/workflows/code-runner-precommit.yml
vendored
Normal file
@ -0,0 +1,73 @@
|
||||
name: code-runner pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as code_runner: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['code_runner/**', '.github/workflows/code-runner-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['code_runner/**', '.github/workflows/code-runner-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every linting hook runs in its own isolated
|
||||
# env -- ruff, mypy, pylint, bandit and codespell each come from their
|
||||
# own repo+rev, and the local hooks need nothing beyond bash and
|
||||
# python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' code_runner/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-code-runner-${{ env.pythonLocation }}-${{
|
||||
hashFiles('code_runner/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-code-runner-${{ env.pythonLocation }}-
|
||||
# mypy re-analyses the stdlib and every third-party stub from scratch
|
||||
# without this, which measured 10s of the hook step in CI against 0.25s
|
||||
# warm locally -- a 19MB cache dir does the whole difference. Keyed on
|
||||
# the config, not the sources: mypy's own cache metadata records the
|
||||
# interpreter, the flag set and a hash per source file, so it re-checks
|
||||
# what changed and cannot pass stale code. Deliberately NOT keyed on
|
||||
# github.sha -- that re-saves 19MB x3 every commit and would evict the
|
||||
# 68MB hook caches under the repo's 10GB LRU budget. A fixed key keeps
|
||||
# the expensive part, the dependency analysis, which is what costs 10s.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: .mypy_cache
|
||||
key: >-
|
||||
mypy-code-runner-${{ env.pythonLocation }}-${{
|
||||
hashFiles('code_runner/.pre-commit-config.yaml') }}
|
||||
restore-keys: mypy-code-runner-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config code_runner/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
34
.github/workflows/code-runner-tests.yml
vendored
Normal file
34
.github/workflows/code-runner-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: code-runner tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as code_runner: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['code_runner/**', '.github/workflows/code-runner-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['code_runner/**', '.github/workflows/code-runner-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: code_runner
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: code_runner/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: python -m pytest -v
|
||||
73
.github/workflows/leetcode-coach-precommit.yml
vendored
Normal file
73
.github/workflows/leetcode-coach-precommit.yml
vendored
Normal file
@ -0,0 +1,73 @@
|
||||
name: leetcode-coach pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as leetcode_coach: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-precommit.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-precommit.yml']
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
# Only pre-commit itself. Every linting hook runs in its own isolated
|
||||
# env -- ruff, mypy, pylint, bandit and codespell each come from their
|
||||
# own repo+rev, and the local hooks need nothing beyond bash and
|
||||
# python3 -- so installing the full requirements.txt spent 9s a run on
|
||||
# packages no pre-commit-stage hook imports. Verified by running all
|
||||
# three configs green in a venv holding pre-commit and nothing else.
|
||||
# The pin is read out of requirements.txt rather than repeated here, so
|
||||
# it cannot drift from what the dependency-freshness gate governs.
|
||||
- name: Install pre-commit
|
||||
run: |
|
||||
pip install "$(grep '^pre-commit==' leetcode_coach/requirements.txt)"
|
||||
|
||||
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so all three
|
||||
# package jobs shared one key, raced to overwrite it with hook sets built
|
||||
# from four different configs, and editing a per-package config did not
|
||||
# invalidate it. The cache was therefore silently wrong rather than
|
||||
# missing, and the hooks reinstalled from scratch on every run (38-49s).
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: >-
|
||||
pre-commit-leetcode-coach-${{ env.pythonLocation }}-${{
|
||||
hashFiles('leetcode_coach/.pre-commit-config.yaml') }}
|
||||
# Prefix fallback, or this fix would evaporate on the very
|
||||
# event that motivated it: bumping a hook rev changes the
|
||||
# exact key, and a total miss means reinstalling every hook
|
||||
# again. pre-commit's store is keyed internally by hook
|
||||
# repo+rev, so a superseded entry is ignored disk rather
|
||||
# than a wrong hook, and cache still re-saves under the new
|
||||
# exact key after a prefix-only hit.
|
||||
restore-keys: pre-commit-leetcode-coach-${{ env.pythonLocation }}-
|
||||
# mypy re-analyses the stdlib and every third-party stub from scratch
|
||||
# without this, which measured 10s of the hook step in CI against 0.25s
|
||||
# warm locally -- a 19MB cache dir does the whole difference. Keyed on
|
||||
# the config, not the sources: mypy's own cache metadata records the
|
||||
# interpreter, the flag set and a hash per source file, so it re-checks
|
||||
# what changed and cannot pass stale code. Deliberately NOT keyed on
|
||||
# github.sha -- that re-saves 19MB x3 every commit and would evict the
|
||||
# 68MB hook caches under the repo's 10GB LRU budget. A fixed key keeps
|
||||
# the expensive part, the dependency analysis, which is what costs 10s.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: .mypy_cache
|
||||
key: >-
|
||||
mypy-leetcode-coach-${{ env.pythonLocation }}-${{
|
||||
hashFiles('leetcode_coach/.pre-commit-config.yaml') }}
|
||||
restore-keys: mypy-leetcode-coach-${{ env.pythonLocation }}-
|
||||
- name: Run the hooks
|
||||
run: >-
|
||||
pre-commit run --config leetcode_coach/.pre-commit-config.yaml
|
||||
--all-files --show-diff-on-failure
|
||||
34
.github/workflows/leetcode-coach-tests.yml
vendored
Normal file
34
.github/workflows/leetcode-coach-tests.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
name: leetcode-coach tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as leetcode_coach: editing only this file would
|
||||
# otherwise trigger nothing, so a fix to the job itself could never prove
|
||||
# itself.
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['leetcode_coach/**', '.github/workflows/leetcode-coach-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: leetcode_coach
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
cache: pip
|
||||
cache-dependency-path: leetcode_coach/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt && pip install --no-deps -e .
|
||||
|
||||
- name: Run tests with coverage
|
||||
run: python -m pytest -v
|
||||
143
code_runner/.pre-commit-config.yaml
Normal file
143
code_runner/.pre-commit-config.yaml
Normal file
@ -0,0 +1,143 @@
|
||||
# Pre-commit Configuration for code_runner
|
||||
# Install: pre-commit install && pre-commit install --hook-type pre-push
|
||||
# Run: pre-commit run --all-files
|
||||
# Update: pre-commit autoupdate
|
||||
|
||||
# NOTE: this subproject lives inside the ~/src/utils monorepo, whose git root is
|
||||
# one level up. pre-commit always runs hooks from the git root, so every path
|
||||
# below is written relative to THAT, not to this directory, and the top-level
|
||||
# `files` key keeps these hooks off the sibling subprojects. CI invokes this
|
||||
# config exactly the same way:
|
||||
# pre-commit run --config code_runner/.pre-commit-config.yaml --all-files
|
||||
files: ^code_runner/
|
||||
|
||||
default_language_version:
|
||||
python: python3
|
||||
default_stages: [pre-commit]
|
||||
fail_fast: false
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
args: [--markdown-linebreak-ext=md]
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-json
|
||||
- id: check-toml
|
||||
- id: check-added-large-files
|
||||
args: [--maxkb=2000]
|
||||
- id: check-merge-conflict
|
||||
- id: detect-private-key
|
||||
- id: debug-statements
|
||||
- id: name-tests-test
|
||||
args: [--pytest-test-first]
|
||||
- id: check-ast
|
||||
- id: mixed-line-ending
|
||||
args: [--fix=lf]
|
||||
- id: requirements-txt-fixer
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: file-length-cap
|
||||
name: file length <= 250 lines
|
||||
entry: bash scripts/check_file_length.sh
|
||||
language: system
|
||||
pass_filenames: true
|
||||
- id: subproject-scope
|
||||
name: subproject scope regex still matches
|
||||
entry: scripts/check_subproject_scope.sh code_runner
|
||||
language: script
|
||||
# always_run so the top-level `files` filter cannot skip the one hook
|
||||
# whose job is to notice that filter has stopped matching anything.
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
- id: no-noqa
|
||||
name: Block noqa comments
|
||||
entry: '(?i)#\s*(noqa|type:\s*ignore)'
|
||||
language: pygrep
|
||||
types: [python]
|
||||
- id: no-ruff-noqa
|
||||
name: Block ruff noqa file-level comments
|
||||
entry: '(?i)#\s*ruff:\s*noqa'
|
||||
language: pygrep
|
||||
types: [python]
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.17.2
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
||||
types_or: [python, pyi]
|
||||
- id: ruff-format
|
||||
types_or: [python, pyi]
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.13.0
|
||||
hooks:
|
||||
- id: mypy
|
||||
args:
|
||||
- --ignore-missing-imports
|
||||
- --no-error-summary
|
||||
- --disable-error-code=no-untyped-def
|
||||
- --disable-error-code=no-untyped-call
|
||||
- --disable-error-code=var-annotated
|
||||
- --disable-error-code=no-any-unimported
|
||||
- --disable-error-code=type-arg
|
||||
- --disable-error-code=no-any-return
|
||||
- --disable-error-code=misc
|
||||
- --disable-error-code=unused-ignore
|
||||
- --disable-error-code=unreachable
|
||||
- --disable-error-code=assignment
|
||||
- --disable-error-code=no-redef
|
||||
- --disable-error-code=attr-defined
|
||||
- --disable-error-code=arg-type
|
||||
- --disable-error-code=union-attr
|
||||
- --disable-error-code=call-overload
|
||||
- --disable-error-code=return-value
|
||||
- --disable-error-code=redundant-cast
|
||||
- --disable-error-code=empty-body
|
||||
- --disable-error-code=list-item
|
||||
|
||||
- repo: https://github.com/pylint-dev/pylint
|
||||
rev: v4.0.8
|
||||
hooks:
|
||||
- id: pylint
|
||||
args:
|
||||
- --rcfile=code_runner/pyproject.toml
|
||||
- --fail-under=10
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
|
||||
- repo: https://github.com/PyCQA/bandit
|
||||
rev: 1.9.4
|
||||
hooks:
|
||||
- id: bandit
|
||||
args:
|
||||
- -c
|
||||
- code_runner/pyproject.toml
|
||||
- --severity-level=high
|
||||
- --confidence-level=medium
|
||||
- --skip=B113
|
||||
additional_dependencies: ["bandit[toml]"]
|
||||
exclude: ^(code_runner/code_runner/tests/|.*test.*\.py$)
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: pytest-coverage
|
||||
name: pytest with coverage enforcement
|
||||
entry: scripts/run_subproject_tests.sh code_runner
|
||||
language: script
|
||||
types: [python]
|
||||
pass_filenames: false
|
||||
require_serial: true
|
||||
stages: [pre-push]
|
||||
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: codespell
|
||||
args:
|
||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||
12
code_runner/README.md
Normal file
12
code_runner/README.md
Normal file
@ -0,0 +1,12 @@
|
||||
# code_runner
|
||||
|
||||
Runs a learner's solution (Python 3, JavaScript, TypeScript) against a problem statement's examples inside bubblewrap: no network, read-only `/usr`, scratch dir, CPU/memory/process/file/time limits.
|
||||
|
||||
```python
|
||||
import code_runner as cr
|
||||
|
||||
statement = ... # markdown from ~/.claude/skills/leetcode/fetch_problem.py
|
||||
results = cr.run("python3", code, cr.extract_starter(statement), cr.parse_examples(statement))
|
||||
```
|
||||
|
||||
`run(lang, code, starter, examples) -> list[CaseResult]` with `n, input, expected, actual, ok, stdout, error, ms`. One sandbox process per example. TypeScript runs through node's type stripping (no type check, no enums). Needs `bwrap`, `prlimit`, `/usr/bin/python3`, node >= 22.18. Install: `./install.sh`.
|
||||
20
code_runner/code_runner/__init__.py
Normal file
20
code_runner/code_runner/__init__.py
Normal file
@ -0,0 +1,20 @@
|
||||
"""Run a learner's solution against a problem's examples in a bubblewrap sandbox."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from code_runner._examples import parse_examples
|
||||
from code_runner._model import CaseResult, Example, Limits, RunnerError
|
||||
from code_runner._run import run
|
||||
from code_runner._starter import Entry, extract_starter, parse_starter
|
||||
|
||||
__all__ = [
|
||||
"CaseResult",
|
||||
"Entry",
|
||||
"Example",
|
||||
"Limits",
|
||||
"RunnerError",
|
||||
"extract_starter",
|
||||
"parse_examples",
|
||||
"parse_starter",
|
||||
"run",
|
||||
]
|
||||
66
code_runner/code_runner/_compare.py
Normal file
66
code_runner/code_runner/_compare.py
Normal file
@ -0,0 +1,66 @@
|
||||
"""Output comparison: exact JSON equality, float tolerance, order rules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
|
||||
TOLERANCE = 1e-5 # LeetCode accepts floating answers within 1e-5
|
||||
|
||||
|
||||
def _as_number(value: object) -> float | None:
|
||||
if isinstance(value, bool) or not isinstance(value, int | float):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _key(value: object) -> str:
|
||||
return json.dumps(value, sort_keys=True, ensure_ascii=False)
|
||||
|
||||
|
||||
def _deep_sorted(value: object) -> object:
|
||||
if isinstance(value, list):
|
||||
return sorted((_deep_sorted(item) for item in value), key=_key)
|
||||
return value
|
||||
|
||||
|
||||
def _equal(expected: object, actual: object) -> bool:
|
||||
want, got = _as_number(expected), _as_number(actual)
|
||||
if want is not None and got is not None:
|
||||
return math.isclose(want, got, rel_tol=TOLERANCE, abs_tol=TOLERANCE)
|
||||
if isinstance(expected, list) and isinstance(actual, list):
|
||||
return len(expected) == len(actual) and all(
|
||||
_equal(e, a) for e, a in zip(expected, actual, strict=True)
|
||||
)
|
||||
if isinstance(expected, dict) and isinstance(actual, dict):
|
||||
return expected.keys() == actual.keys() and all(
|
||||
_equal(expected[k], actual[k]) for k in expected
|
||||
)
|
||||
return type(expected) is type(actual) and expected == actual
|
||||
|
||||
|
||||
def _top_sorted(value: object) -> object:
|
||||
if isinstance(value, list):
|
||||
return sorted(value, key=_key)
|
||||
return value
|
||||
|
||||
|
||||
def matches(expected: object, actual: object, order: str) -> bool:
|
||||
"""Whether ``actual`` is an accepted answer for ``expected``.
|
||||
|
||||
Args:
|
||||
expected: the statement's answer (JSON value).
|
||||
actual: what the solution returned (JSON value).
|
||||
order: "exact", "any" (list order free) or "deep" (nested order free too).
|
||||
|
||||
Raises:
|
||||
ValueError: ``order`` is none of those.
|
||||
"""
|
||||
if order == "exact":
|
||||
return _equal(expected, actual)
|
||||
if order == "any":
|
||||
return _equal(_top_sorted(expected), _top_sorted(actual))
|
||||
if order == "deep":
|
||||
return _equal(_deep_sorted(expected), _deep_sorted(actual))
|
||||
msg = f"unknown order {order!r}"
|
||||
raise ValueError(msg)
|
||||
75
code_runner/code_runner/_examples.py
Normal file
75
code_runner/code_runner/_examples.py
Normal file
@ -0,0 +1,75 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Final
|
||||
|
||||
from code_runner._model import Example, Order
|
||||
from code_runner._split import split_top_level
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
_LABEL: Final = re.compile(r"^(Input|Output)\s*:\s*(.*)$")
|
||||
_PAIR: Final = re.compile(r"^([A-Za-z_]\w*)\s*=\s*(.+)$", re.DOTALL)
|
||||
_ANY_ORDER: Final = re.compile(r"any order|order of the output", re.IGNORECASE)
|
||||
_DEEP_ORDER: Final = re.compile(
|
||||
r"order of the (?:triplets|quadruplets|subsets|groups|pairs|elements)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _value(text: str) -> object:
|
||||
try:
|
||||
return json.loads(text)
|
||||
except ValueError:
|
||||
try:
|
||||
return ast.literal_eval(text)
|
||||
except (ValueError, SyntaxError) as exc:
|
||||
raise ValueError(text[:40]) from exc
|
||||
|
||||
|
||||
def _arguments(text: str) -> dict[str, object]:
|
||||
args: dict[str, object] = {}
|
||||
for part in split_top_level(text):
|
||||
pair = _PAIR.match(part)
|
||||
if pair is None:
|
||||
msg = f"not a name = value pair: {part[:40]!r}"
|
||||
raise ValueError(msg)
|
||||
args[pair.group(1)] = _value(pair.group(2))
|
||||
return args
|
||||
|
||||
|
||||
def _labels(body: str) -> list[tuple[str, str]]:
|
||||
cleaned = (
|
||||
line.replace("**", "").replace("`", "").strip() for line in body.splitlines()
|
||||
)
|
||||
matched = (_LABEL.match(line) for line in cleaned)
|
||||
return [(m.group(1), m.group(2).strip()) for m in matched if m is not None]
|
||||
|
||||
|
||||
def _order(body: str) -> Order:
|
||||
if _DEEP_ORDER.search(body):
|
||||
return "deep"
|
||||
return "any" if _ANY_ORDER.search(body) else "exact"
|
||||
|
||||
|
||||
def parse_examples(statement: str) -> list[Example]:
|
||||
body = re.split(r"^## ", statement, maxsplit=1, flags=re.MULTILINE)[0]
|
||||
order = _order(body)
|
||||
found: list[Example] = []
|
||||
pending: str | None = None
|
||||
number = 0
|
||||
for label, text in _labels(body):
|
||||
if label == "Input":
|
||||
pending = text
|
||||
continue
|
||||
if pending is None:
|
||||
continue
|
||||
number += 1
|
||||
try:
|
||||
found.append(Example(number, _arguments(pending), _value(text), order))
|
||||
except ValueError as exc:
|
||||
_logger.warning("example %d skipped, not runnable: %s", number, exc)
|
||||
pending = None
|
||||
return found
|
||||
119
code_runner/code_runner/_languages.py
Normal file
119
code_runner/code_runner/_languages.py
Normal file
@ -0,0 +1,119 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import resources
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from code_runner._model import RunnerError
|
||||
from code_runner._sandbox import WORK
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from code_runner._starter import Entry
|
||||
|
||||
MEGABYTE = 1024 * 1024
|
||||
_NODE_FLAGS = (
|
||||
"--permission",
|
||||
f"--allow-fs-read={WORK}",
|
||||
f"--allow-fs-write={WORK}",
|
||||
"--max-old-space-size=128",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Language:
|
||||
name: str
|
||||
solution_file: str
|
||||
harness_file: str
|
||||
program: str
|
||||
binary_env: str
|
||||
binary_default: str
|
||||
flags: tuple[str, ...]
|
||||
memory_bytes: int
|
||||
|
||||
def resolve(self) -> Path:
|
||||
for candidate in (
|
||||
os.environ.get(self.binary_env),
|
||||
self.binary_default,
|
||||
shutil.which(self.program),
|
||||
):
|
||||
if candidate and Path(candidate).is_file():
|
||||
return Path(candidate).resolve()
|
||||
msg = f"{self.program} not found (set {self.binary_env})"
|
||||
raise RunnerError(msg)
|
||||
|
||||
def command(self, binary: Path) -> list[str]:
|
||||
return [str(binary), *self.flags, f"{WORK}/{self.harness_file}", WORK]
|
||||
|
||||
def ro_binds(self, binary: Path) -> tuple[str, ...]:
|
||||
if binary.is_relative_to("/usr"):
|
||||
return ()
|
||||
return (str(binary.parent.parent),)
|
||||
|
||||
def prepare(
|
||||
self, scratch: Path, code: str, entry: Entry, args: list[object]
|
||||
) -> None:
|
||||
harness = resources.files("code_runner").joinpath("harness", self.harness_file)
|
||||
(scratch / self.harness_file).write_text(harness.read_text(encoding="utf-8"))
|
||||
text = code
|
||||
if self.name == "typescript":
|
||||
text += f"\nmodule.exports = {{ __entry: {entry.cls or entry.name} }};\n"
|
||||
(scratch / self.solution_file).write_text(text, encoding="utf-8")
|
||||
spec = {
|
||||
"cls": entry.cls,
|
||||
"fn": entry.name,
|
||||
"args": args,
|
||||
"typescript": self.name == "typescript",
|
||||
}
|
||||
(scratch / "input.json").write_text(json.dumps(spec), encoding="utf-8")
|
||||
|
||||
|
||||
PYTHON = Language(
|
||||
"python3",
|
||||
"solution.py",
|
||||
"harness.py",
|
||||
"python3",
|
||||
"CODE_RUNNER_PYTHON",
|
||||
"/usr/bin/python3",
|
||||
("-I", "-B"),
|
||||
512 * MEGABYTE,
|
||||
)
|
||||
JAVASCRIPT = Language(
|
||||
"javascript",
|
||||
"solution.js",
|
||||
"harness.js",
|
||||
"node",
|
||||
"CODE_RUNNER_NODE",
|
||||
"/usr/bin/node",
|
||||
_NODE_FLAGS,
|
||||
2048 * MEGABYTE,
|
||||
)
|
||||
TYPESCRIPT = Language(
|
||||
"typescript",
|
||||
"solution.cts",
|
||||
"harness.js",
|
||||
"node",
|
||||
"CODE_RUNNER_NODE",
|
||||
"/usr/bin/node",
|
||||
_NODE_FLAGS,
|
||||
2048 * MEGABYTE,
|
||||
)
|
||||
_BY_NAME = {
|
||||
"python3": PYTHON,
|
||||
"python": PYTHON,
|
||||
"javascript": JAVASCRIPT,
|
||||
"js": JAVASCRIPT,
|
||||
"typescript": TYPESCRIPT,
|
||||
"ts": TYPESCRIPT,
|
||||
}
|
||||
|
||||
|
||||
def get_language(name: str) -> Language:
|
||||
try:
|
||||
return _BY_NAME[name.lower()]
|
||||
except KeyError:
|
||||
msg = f"unsupported language {name!r}; use python3, javascript or typescript"
|
||||
raise RunnerError(msg) from None
|
||||
40
code_runner/code_runner/_model.py
Normal file
40
code_runner/code_runner/_model.py
Normal file
@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
# "any": list order is free; "deep": the order inside its items is free too.
|
||||
Order = Literal["exact", "any", "deep"]
|
||||
MAX_CAPTURE = 64 * 1024
|
||||
|
||||
|
||||
class RunnerError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Example:
|
||||
n: int
|
||||
args: dict[str, object]
|
||||
expected: object
|
||||
order: Order = "exact"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CaseResult:
|
||||
n: int
|
||||
input: dict[str, object]
|
||||
expected: object
|
||||
actual: object
|
||||
ok: bool
|
||||
stdout: str = ""
|
||||
error: str | None = None
|
||||
ms: float = 0.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Limits:
|
||||
timeout_s: float = 2.0
|
||||
nproc: int = 64
|
||||
fsize_bytes: int = 1024 * 1024
|
||||
nofile: int = 256
|
||||
116
code_runner/code_runner/_run.py
Normal file
116
code_runner/code_runner/_run.py
Normal file
@ -0,0 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import tempfile
|
||||
|
||||
from code_runner._compare import matches
|
||||
from code_runner._languages import Language, get_language
|
||||
from code_runner._model import MAX_CAPTURE, CaseResult, Example, Limits
|
||||
from code_runner._sandbox import BoxResult, execute
|
||||
from code_runner._starter import Entry, parse_starter
|
||||
|
||||
Box = Callable[[list[str], Path, Limits, int, tuple[str, ...]], BoxResult]
|
||||
_OUT_OF_MEMORY = ("out of memory", "allocation failed")
|
||||
|
||||
|
||||
def _positional(example: Example, entry: Entry) -> list[object]:
|
||||
if set(example.args) == set(entry.params):
|
||||
return [example.args[name] for name in entry.params]
|
||||
if len(example.args) == len(entry.params):
|
||||
return list(example.args.values())
|
||||
given, wanted = len(example.args), len(entry.params)
|
||||
msg = f"ArgumentError: example gives {given} arguments, {entry.name} takes {wanted}"
|
||||
raise ValueError(msg)
|
||||
|
||||
|
||||
def _read_result(scratch: Path) -> dict[str, object] | None:
|
||||
# The scratch dir is the solution's: never follow a link it planted there.
|
||||
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
|
||||
try:
|
||||
fd = os.open(scratch / "result.json", flags)
|
||||
except OSError:
|
||||
return None
|
||||
with os.fdopen(fd, "rb") as handle:
|
||||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||||
return None
|
||||
raw = handle.read(MAX_CAPTURE * 16)
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return payload if isinstance(payload, dict) and "ok" in payload else None
|
||||
|
||||
|
||||
def _crash(box: BoxResult) -> str:
|
||||
low = box.stderr.lower()
|
||||
if any(marker in low for marker in _OUT_OF_MEMORY):
|
||||
return "MemoryLimitExceeded"
|
||||
return f"Crashed (exit {box.returncode})"
|
||||
|
||||
|
||||
def _outcome(scratch: Path, box: BoxResult) -> tuple[object, str | None, float]:
|
||||
if box.timed_out:
|
||||
return None, "TimeLimitExceeded", box.elapsed_ms
|
||||
payload = _read_result(scratch)
|
||||
if payload is None:
|
||||
return None, _crash(box), box.elapsed_ms
|
||||
ms = payload.get("ms")
|
||||
took = float(ms) if isinstance(ms, int | float) else box.elapsed_ms
|
||||
if payload["ok"] is True:
|
||||
return payload.get("value"), None, took
|
||||
return None, str(payload.get("error", "Error")), took
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Job:
|
||||
language: Language
|
||||
binary: Path
|
||||
code: str
|
||||
entry: Entry
|
||||
limits: Limits
|
||||
box: Box
|
||||
|
||||
|
||||
def _case(job: _Job, example: Example) -> CaseResult:
|
||||
try:
|
||||
args = _positional(example, job.entry)
|
||||
except ValueError as exc:
|
||||
return CaseResult(
|
||||
example.n, example.args, example.expected, None, ok=False, error=str(exc)
|
||||
)
|
||||
language = job.language
|
||||
with tempfile.TemporaryDirectory(prefix="code-runner-") as tmp:
|
||||
scratch = Path(tmp)
|
||||
language.prepare(scratch, job.code, job.entry, args)
|
||||
done = job.box(
|
||||
language.command(job.binary),
|
||||
scratch,
|
||||
job.limits,
|
||||
language.memory_bytes,
|
||||
language.ro_binds(job.binary),
|
||||
)
|
||||
actual, error, ms = _outcome(scratch, done)
|
||||
ok = error is None and matches(example.expected, actual, example.order)
|
||||
return CaseResult(
|
||||
example.n, example.args, example.expected, actual, ok, done.stdout, error, ms
|
||||
)
|
||||
|
||||
|
||||
def run(
|
||||
lang: str,
|
||||
code: str,
|
||||
starter: str,
|
||||
examples: Sequence[Example],
|
||||
*,
|
||||
limits: Limits | None = None,
|
||||
box: Box = execute,
|
||||
) -> list[CaseResult]:
|
||||
language = get_language(lang)
|
||||
entry = parse_starter(language.name, starter)
|
||||
job = _Job(language, language.resolve(), code, entry, limits or Limits(), box)
|
||||
return [_case(job, example) for example in examples]
|
||||
147
code_runner/code_runner/_sandbox.py
Normal file
147
code_runner/code_runner/_sandbox.py
Normal file
@ -0,0 +1,147 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import functools
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from typing import IO
|
||||
|
||||
from code_runner._model import MAX_CAPTURE, Limits, RunnerError
|
||||
|
||||
WORK = "/work"
|
||||
PRLIMIT = "/usr/bin/prlimit"
|
||||
_ROOT_LINKS = ("bin", "sbin", "lib", "lib64")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BoxResult:
|
||||
returncode: int
|
||||
timed_out: bool
|
||||
stdout: str
|
||||
stderr: str
|
||||
elapsed_ms: float
|
||||
|
||||
|
||||
def _root_links() -> list[str]:
|
||||
args: list[str] = []
|
||||
for name in _ROOT_LINKS:
|
||||
path = Path("/") / name
|
||||
if path.is_symlink():
|
||||
args += ["--symlink", str(path.readlink()), str(path)]
|
||||
elif path.is_dir():
|
||||
args += ["--ro-bind", str(path), str(path)]
|
||||
return args
|
||||
|
||||
|
||||
def _base_argv() -> list[str]:
|
||||
return [
|
||||
"bwrap",
|
||||
"--unshare-all", # no --share-net: no network at all, loopback included
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--clearenv",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
*_root_links(),
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
]
|
||||
|
||||
|
||||
def bwrap_argv(
|
||||
command: list[str],
|
||||
scratch: Path,
|
||||
limits: Limits,
|
||||
memory_bytes: int,
|
||||
ro_binds: tuple[str, ...] = (),
|
||||
) -> list[str]:
|
||||
argv = _base_argv()
|
||||
for bind in ro_binds:
|
||||
argv += ["--ro-bind", bind, bind]
|
||||
argv += ["--bind", str(scratch), WORK, "--remount-ro", "/", "--chdir", WORK]
|
||||
for name, value in (
|
||||
("HOME", WORK),
|
||||
("PATH", "/usr/bin"),
|
||||
("LANG", "C.UTF-8"),
|
||||
("PYTHONIOENCODING", "utf-8"),
|
||||
):
|
||||
argv += ["--setenv", name, value]
|
||||
cpu = math.ceil(limits.timeout_s) + 1
|
||||
return [
|
||||
*argv,
|
||||
"--",
|
||||
PRLIMIT,
|
||||
f"--as={memory_bytes}",
|
||||
f"--nproc={limits.nproc}",
|
||||
f"--fsize={limits.fsize_bytes}",
|
||||
f"--nofile={limits.nofile}",
|
||||
f"--cpu={cpu}",
|
||||
"--core=0",
|
||||
"--",
|
||||
*command,
|
||||
]
|
||||
|
||||
|
||||
@functools.cache
|
||||
def check_sandbox() -> None:
|
||||
if not Path(PRLIMIT).is_file():
|
||||
msg = f"{PRLIMIT} is missing (util-linux)"
|
||||
raise RunnerError(msg)
|
||||
try:
|
||||
probe = subprocess.run(
|
||||
[*_base_argv(), "/usr/bin/true"],
|
||||
capture_output=True,
|
||||
check=False,
|
||||
timeout=20,
|
||||
)
|
||||
except OSError as exc:
|
||||
msg = f"bubblewrap (bwrap) cannot start: {exc}"
|
||||
raise RunnerError(msg) from exc
|
||||
if probe.returncode != 0:
|
||||
detail = probe.stderr.decode(errors="replace").strip()
|
||||
msg = f"bubblewrap cannot create the sandbox: {detail}"
|
||||
raise RunnerError(msg)
|
||||
|
||||
|
||||
def _read(handle: IO[bytes]) -> str:
|
||||
handle.seek(0)
|
||||
return handle.read(MAX_CAPTURE).decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def execute(
|
||||
command: list[str],
|
||||
scratch: Path,
|
||||
limits: Limits,
|
||||
memory_bytes: int,
|
||||
ro_binds: tuple[str, ...] = (),
|
||||
) -> BoxResult:
|
||||
check_sandbox()
|
||||
argv = bwrap_argv(command, scratch, limits, memory_bytes, ro_binds)
|
||||
with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
|
||||
started = time.monotonic()
|
||||
with subprocess.Popen(
|
||||
argv,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=out,
|
||||
stderr=err,
|
||||
env={"PATH": "/usr/bin:/bin"},
|
||||
start_new_session=True,
|
||||
) as proc:
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=limits.timeout_s)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
os.killpg(proc.pid, signal.SIGKILL)
|
||||
elapsed = (time.monotonic() - started) * 1000
|
||||
return BoxResult(proc.returncode, timed_out, _read(out), _read(err), elapsed)
|
||||
29
code_runner/code_runner/_split.py
Normal file
29
code_runner/code_runner/_split.py
Normal file
@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
_OPEN = "([{<"
|
||||
_CLOSE = ")]}>"
|
||||
|
||||
|
||||
def split_top_level(text: str) -> list[str]:
|
||||
parts: list[str] = []
|
||||
depth = 0
|
||||
quote = ""
|
||||
escaped = False
|
||||
start = 0
|
||||
for i, ch in enumerate(text):
|
||||
if escaped:
|
||||
escaped = False
|
||||
elif quote:
|
||||
escaped = ch == "\\"
|
||||
quote = "" if ch == quote else quote
|
||||
elif ch in "\"'":
|
||||
quote = ch
|
||||
elif ch in _OPEN:
|
||||
depth += 1
|
||||
elif ch in _CLOSE and not (ch == ">" and text[i - 1] in "=-"):
|
||||
depth = max(depth - 1, 0)
|
||||
elif ch == "," and depth == 0:
|
||||
parts.append(text[start:i])
|
||||
start = i + 1
|
||||
parts.append(text[start:])
|
||||
return [part.strip() for part in parts]
|
||||
108
code_runner/code_runner/_starter.py
Normal file
108
code_runner/code_runner/_starter.py
Normal file
@ -0,0 +1,108 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
|
||||
from code_runner._model import RunnerError
|
||||
from code_runner._split import split_top_level
|
||||
|
||||
_IDENT = r"[A-Za-z_$][\w$]*"
|
||||
_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
|
||||
_LINE_COMMENT = re.compile(r"^\s*(?://|#).*$", re.MULTILINE)
|
||||
_PY_CLASS = re.compile(r"^class\s+(\w+)", re.MULTILINE)
|
||||
_PY_DEF = re.compile(r"\bdef\s+(?!__)(\w+)\s*\(")
|
||||
_PY_FUNC = re.compile(r"^def\s+(\w+)\s*\(", re.MULTILINE)
|
||||
_JS_CLASS = re.compile(rf"^\s*class\s+({_IDENT})", re.MULTILINE)
|
||||
_JS_METHOD = re.compile(
|
||||
rf"^\s+(?:async\s+)?(?!constructor\b)({_IDENT})\s*\(", re.MULTILINE
|
||||
)
|
||||
_JS_ASSIGNED = re.compile(
|
||||
rf"\b(?:var|let|const)\s+({_IDENT})\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b\s*\w*\s*)?\("
|
||||
)
|
||||
_JS_DECLARED = re.compile(rf"\bfunction\s+({_IDENT})\s*\(")
|
||||
_NOT_METHODS = {"if", "for", "while", "switch", "catch", "return", "function"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Entry:
|
||||
cls: str | None
|
||||
name: str
|
||||
params: tuple[str, ...]
|
||||
|
||||
|
||||
def _no_entry(lang: str) -> RunnerError:
|
||||
return RunnerError(f"no entry point found in the {lang} starter code")
|
||||
|
||||
|
||||
def _balanced(text: str, open_at: int) -> str:
|
||||
depth = 0
|
||||
for i in range(open_at, len(text)):
|
||||
ch = text[i]
|
||||
if ch in "([{" or (ch == "<" and depth > 0):
|
||||
depth += 1
|
||||
elif ch in ")]}" or (ch == ">" and text[i - 1] != "=" and depth > 1):
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[open_at + 1 : i]
|
||||
return text[open_at + 1 :]
|
||||
|
||||
|
||||
def _params(code: str, open_at: int) -> tuple[str, ...]:
|
||||
names: list[str] = []
|
||||
for part in split_top_level(_balanced(code, open_at)):
|
||||
found = re.match(_IDENT, part.strip())
|
||||
if found:
|
||||
names.append(found.group())
|
||||
return tuple(names)
|
||||
|
||||
|
||||
def _python(text: str) -> Entry | None:
|
||||
code = _LINE_COMMENT.sub("", text)
|
||||
owner = _PY_CLASS.search(code)
|
||||
if owner is None:
|
||||
found = _PY_FUNC.search(code)
|
||||
return found and Entry(None, found.group(1), _params(code, found.end() - 1))
|
||||
found = _PY_DEF.search(code, owner.end())
|
||||
if found is None:
|
||||
return None
|
||||
params = _params(code, found.end() - 1)
|
||||
return Entry(
|
||||
owner.group(1), found.group(1), tuple(p for p in params if p != "self")
|
||||
)
|
||||
|
||||
|
||||
def _javascript(text: str) -> Entry | None:
|
||||
code = _LINE_COMMENT.sub("", _BLOCK_COMMENT.sub("", text))
|
||||
owner = _JS_CLASS.search(code)
|
||||
if owner is not None:
|
||||
for method in _JS_METHOD.finditer(code, owner.end()):
|
||||
if method.group(1) not in _NOT_METHODS:
|
||||
return Entry(
|
||||
owner.group(1), method.group(1), _params(code, method.end() - 1)
|
||||
)
|
||||
return None
|
||||
found = _JS_ASSIGNED.search(code) or _JS_DECLARED.search(code)
|
||||
return found and Entry(None, found.group(1), _params(code, found.end() - 1))
|
||||
|
||||
|
||||
def parse_starter(lang: str, text: str) -> Entry:
|
||||
entry = _python(text) if lang == "python3" else _javascript(text)
|
||||
if entry is None:
|
||||
raise _no_entry(lang)
|
||||
return entry
|
||||
|
||||
|
||||
def extract_starter(statement: str) -> str:
|
||||
lines = statement.splitlines(keepends=True)
|
||||
heads = [i for i, line in enumerate(lines) if line.startswith("## Starter code")]
|
||||
if not heads:
|
||||
return ""
|
||||
body = lines[heads[0] + 1 :]
|
||||
if body and body[0].startswith("```"):
|
||||
body = body[1:]
|
||||
end = next(
|
||||
(i for i, line in enumerate(body) if line.startswith("```")), len(body)
|
||||
)
|
||||
return "".join(body[:end])
|
||||
end = next((i for i, line in enumerate(body) if line.startswith("## ")), len(body))
|
||||
return "".join(body[:end])
|
||||
45
code_runner/code_runner/harness/harness.js
Normal file
45
code_runner/code_runner/harness/harness.js
Normal file
@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
// Runs inside the sandbox: call the solution once, write result.json.
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const root = process.argv[2];
|
||||
const spec = JSON.parse(fs.readFileSync(path.join(root, "input.json"), "utf8"));
|
||||
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
||||
|
||||
function describe(e) {
|
||||
const name = e && typeof e.name === "string" ? e.name : "Error";
|
||||
const message = e && e.message !== undefined ? e.message : String(e);
|
||||
return `${name}: ${message}`.slice(0, 300);
|
||||
}
|
||||
|
||||
function writeResult(payload) {
|
||||
// Unique name + rename: a symlink planted at result.json is replaced, never followed.
|
||||
const unique = path.join(root, `.result-${process.pid}-${Math.random().toString(36).slice(2)}`);
|
||||
fs.writeFileSync(unique, JSON.stringify(payload), { flag: "wx" });
|
||||
fs.renameSync(unique, path.join(root, "result.json"));
|
||||
}
|
||||
|
||||
function load(target) {
|
||||
if (!IDENT.test(target)) throw new TypeError("bad entry name");
|
||||
if (spec.typescript) return require(path.join(root, "solution.cts")).__entry;
|
||||
const source = fs.readFileSync(path.join(root, "solution.js"), "utf8");
|
||||
return new Function(`${source}\n;return ${target};`)();
|
||||
}
|
||||
|
||||
function call() {
|
||||
const entry = load(spec.cls || spec.fn);
|
||||
if (spec.cls) return new entry()[spec.fn](...spec.args);
|
||||
return entry(...spec.args);
|
||||
}
|
||||
|
||||
const started = process.hrtime.bigint();
|
||||
let payload;
|
||||
try {
|
||||
const value = call();
|
||||
payload = { ok: true, value: value === undefined ? null : JSON.parse(JSON.stringify(value)) };
|
||||
} catch (e) {
|
||||
payload = { ok: false, error: describe(e) };
|
||||
}
|
||||
payload.ms = Number(process.hrtime.bigint() - started) / 1e6;
|
||||
writeResult(payload);
|
||||
69
code_runner/code_runner/harness/harness.py
Normal file
69
code_runner/code_runner/harness/harness.py
Normal file
@ -0,0 +1,69 @@
|
||||
"""Runs inside the sandbox: call the solution once, write result.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
PRELUDE = (
|
||||
"from typing import *\n"
|
||||
"import bisect, collections, functools, heapq, itertools, math\n"
|
||||
"import operator, re, string\n"
|
||||
)
|
||||
MAX_MESSAGE = 300
|
||||
|
||||
|
||||
def describe(exc: BaseException) -> str:
|
||||
return f"{type(exc).__name__}: {exc}"[:MAX_MESSAGE]
|
||||
|
||||
|
||||
def write_result(root: Path, payload: dict[str, object]) -> None:
|
||||
# Unique name + rename: a symlink the solution planted at result.json is
|
||||
# replaced by this file, never followed.
|
||||
handle, name = tempfile.mkstemp(dir=root, prefix=".result-")
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as out:
|
||||
json.dump(payload, out)
|
||||
Path(name).replace(root / "result.json")
|
||||
|
||||
|
||||
def call(root: Path, spec: dict[str, Any]) -> object:
|
||||
namespace: dict[str, Any] = {"__name__": "solution"}
|
||||
exec(PRELUDE, namespace)
|
||||
source = (root / "solution.py").read_text(encoding="utf-8")
|
||||
exec(compile(source, "solution.py", "exec"), namespace)
|
||||
owner, name = spec["cls"], str(spec["fn"])
|
||||
if owner is None:
|
||||
target = namespace.get(name)
|
||||
else:
|
||||
cls = namespace.get(str(owner))
|
||||
target = getattr(cls() if cls else None, name, None)
|
||||
if target is None:
|
||||
message = f"name {owner or name!r} is not defined"
|
||||
raise NameError(message)
|
||||
return target(*spec["args"])
|
||||
|
||||
|
||||
def main(directory: str) -> None:
|
||||
root = Path(directory)
|
||||
spec = json.loads((root / "input.json").read_text(encoding="utf-8"))
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
value = call(root, spec)
|
||||
payload: dict[str, object] = {
|
||||
"ok": True,
|
||||
"value": json.loads(json.dumps(value)),
|
||||
}
|
||||
except BaseException as exc:
|
||||
payload = {"ok": False, "error": describe(exc)}
|
||||
payload["ms"] = (time.perf_counter() - started) * 1000
|
||||
sys.stdout.flush()
|
||||
write_result(root, payload)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1])
|
||||
0
code_runner/code_runner/py.typed
Normal file
0
code_runner/code_runner/py.typed
Normal file
0
code_runner/code_runner/tests/__init__.py
Normal file
0
code_runner/code_runner/tests/__init__.py
Normal file
70
code_runner/code_runner/tests/conftest.py
Normal file
70
code_runner/code_runner/tests/conftest.py
Normal file
@ -0,0 +1,70 @@
|
||||
"""Shared fixtures: real-sandbox tests are skipped where bubblewrap cannot run."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
|
||||
from code_runner._model import Example, RunnerError
|
||||
from code_runner._sandbox import check_sandbox
|
||||
|
||||
|
||||
def _bwrap_works() -> bool:
|
||||
try:
|
||||
check_sandbox()
|
||||
except RunnerError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
needs_sandbox = pytest.mark.skipif(not _bwrap_works(), reason="bwrap/userns unusable")
|
||||
needs_node = pytest.mark.skipif(
|
||||
not _bwrap_works() or not shutil.which("node"), reason="node or bwrap missing"
|
||||
)
|
||||
|
||||
TWO_SUM_STARTER = {
|
||||
"python3": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n",
|
||||
"javascript": "var twoSum = function(nums, target) {\n\n};",
|
||||
"typescript": "function twoSum(nums: number[], target: number): number[] {\n};",
|
||||
}
|
||||
TWO_SUM_CODE = {
|
||||
"python3": (
|
||||
"class Solution:\n"
|
||||
" def twoSum(self, nums, target):\n"
|
||||
" seen = {}\n"
|
||||
" for i, n in enumerate(nums):\n"
|
||||
" if target - n in seen:\n"
|
||||
" return [i, seen[target - n]]\n"
|
||||
" seen[n] = i\n"
|
||||
),
|
||||
"javascript": (
|
||||
"var twoSum = function(nums, target) {\n"
|
||||
" const seen = new Map();\n"
|
||||
" for (let i = 0; i < nums.length; i++) {\n"
|
||||
" if (seen.has(target - nums[i])) return [i, seen.get(target - nums[i])];\n"
|
||||
" seen.set(nums[i], i);\n"
|
||||
" }\n"
|
||||
"};"
|
||||
),
|
||||
"typescript": (
|
||||
"function twoSum(nums: number[], target: number): number[] {\n"
|
||||
" const seen = new Map<number, number>();\n"
|
||||
" for (let i = 0; i < nums.length; i++) {\n"
|
||||
" const j = seen.get(target - nums[i]);\n"
|
||||
" if (j !== undefined) return [i, j];\n"
|
||||
" seen.set(nums[i], i);\n"
|
||||
" }\n"
|
||||
" return [];\n"
|
||||
"}"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def two_sum_examples() -> list[Example]:
|
||||
return [
|
||||
Example(1, {"nums": [2, 7, 11, 15], "target": 9}, [0, 1], "any"),
|
||||
Example(2, {"nums": [3, 2, 4], "target": 6}, [1, 2], "any"),
|
||||
Example(3, {"nums": [3, 3], "target": 6}, [0, 1], "any"),
|
||||
]
|
||||
42
code_runner/code_runner/tests/test_compare.py
Normal file
42
code_runner/code_runner/tests/test_compare.py
Normal file
@ -0,0 +1,42 @@
|
||||
import pytest
|
||||
|
||||
from code_runner._compare import matches
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("expected", "actual", "order", "want"),
|
||||
[
|
||||
([0, 1], [0, 1], "exact", True),
|
||||
([0, 1], [1, 0], "exact", False),
|
||||
([0, 1], [1, 0], "any", True),
|
||||
([0, 1], [1, 0, 2], "any", False),
|
||||
([[1, 2], [3]], [[3], [1, 2]], "any", True),
|
||||
([[1, 2], [3]], [[3], [2, 1]], "any", False),
|
||||
([[1, 2], [3]], [[3], [2, 1]], "deep", True),
|
||||
([[1, 2], [3]], [[3], [2, 9]], "deep", False),
|
||||
(3, 3.0, "exact", True),
|
||||
(0.1 + 0.2, 0.3, "exact", True),
|
||||
(2.0, 2.001, "exact", False),
|
||||
(True, 1, "exact", False),
|
||||
(1, True, "exact", False),
|
||||
(True, True, "exact", True),
|
||||
(None, None, "exact", True),
|
||||
(None, 0, "exact", False),
|
||||
("ab", "ab", "exact", True),
|
||||
("ab", "ba", "exact", False),
|
||||
("1", 1, "exact", False),
|
||||
({"a": [1]}, {"a": [1]}, "exact", True),
|
||||
({"a": 1}, {"b": 1}, "exact", False),
|
||||
({"a": 1}, {"a": 2}, "exact", False),
|
||||
(5, 5, "any", True),
|
||||
([1], 1, "any", False),
|
||||
([1.0, 2.0], [2.0, 1.0000001], "any", True),
|
||||
],
|
||||
)
|
||||
def test_matches(expected: object, actual: object, order: str, *, want: bool) -> None:
|
||||
assert matches(expected, actual, order) is want
|
||||
|
||||
|
||||
def test_unknown_order_is_refused() -> None:
|
||||
with pytest.raises(ValueError, match="order"):
|
||||
matches(1, 1, "sideways")
|
||||
106
code_runner/code_runner/tests/test_examples.py
Normal file
106
code_runner/code_runner/tests/test_examples.py
Normal file
@ -0,0 +1,106 @@
|
||||
from code_runner._examples import parse_examples
|
||||
from code_runner._model import Example
|
||||
|
||||
TWO_SUM = """# 1. Two Sum (Easy)
|
||||
Tags: Array, Hash Table
|
||||
|
||||
Return indices.
|
||||
|
||||
You can return the answer in any order.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
**Input:** `nums = [2,7,11,15], target = 9`
|
||||
|
||||
**Output:** `[0,1]`
|
||||
|
||||
**Explanation:** 2 + 7.
|
||||
|
||||
**Example 2:**
|
||||
|
||||
**Input:** `nums = [3,2,4], target = 6`
|
||||
|
||||
**Output:** `[1,2]`
|
||||
|
||||
## Starter code (python3)
|
||||
```
|
||||
class Solution:
|
||||
def twoSum(self, nums, target):
|
||||
```
|
||||
"""
|
||||
|
||||
FENCED = """# 5. Pal
|
||||
|
||||
Output order does not matter.
|
||||
|
||||
**Example 1:**
|
||||
```
|
||||
Input: s = "a,b", flag = true
|
||||
Output: "b"
|
||||
Explanation: Output: not an example
|
||||
```
|
||||
**Example 2:**
|
||||
```
|
||||
Input: s = 'x', flag = false
|
||||
Output: None
|
||||
```
|
||||
"""
|
||||
|
||||
THREE_SUM = """# 15. 3Sum
|
||||
Notice that the order of the output and the order of the triplets does not matter.
|
||||
**Example 1:**
|
||||
**Input:** nums = [-1,0,1,2,-1,-4]
|
||||
**Output:** [[-1,-1,2],[-1,0,1]]
|
||||
"""
|
||||
|
||||
SKIPPED = """# 2. Add Two Numbers
|
||||
**Example 1:**
|
||||
**Input:** l1 = 1->2
|
||||
**Output:** [1,2]
|
||||
**Example 2:**
|
||||
**Input:** a = 1, b = 2
|
||||
**Output:** 3.00000
|
||||
**Example 3:**
|
||||
**Input:** a = 1
|
||||
**Output:** 1->2
|
||||
**Example 4:**
|
||||
**Input:** a
|
||||
**Output:** 1
|
||||
"""
|
||||
|
||||
|
||||
def test_two_sum_examples_are_typed_and_ordered_any() -> None:
|
||||
found = parse_examples(TWO_SUM)
|
||||
assert found == [
|
||||
Example(1, {"nums": [2, 7, 11, 15], "target": 9}, [0, 1], "any"),
|
||||
Example(2, {"nums": [3, 2, 4], "target": 6}, [1, 2], "any"),
|
||||
]
|
||||
|
||||
|
||||
def test_fenced_examples_and_python_literals() -> None:
|
||||
found = parse_examples(FENCED)
|
||||
assert [e.args for e in found] == [
|
||||
{"s": "a,b", "flag": True},
|
||||
{"s": "x", "flag": False},
|
||||
]
|
||||
assert [e.expected for e in found] == ["b", None]
|
||||
assert {e.order for e in found} == {"exact"}
|
||||
|
||||
|
||||
def test_triplets_sentence_means_deep_order() -> None:
|
||||
assert parse_examples(THREE_SUM)[0].order == "deep"
|
||||
|
||||
|
||||
def test_unparseable_examples_are_skipped_but_numbering_is_kept() -> None:
|
||||
found = parse_examples(SKIPPED)
|
||||
assert found == [Example(2, {"a": 1, "b": 2}, 3.0, "exact")]
|
||||
|
||||
|
||||
def test_output_without_input_and_empty_statement() -> None:
|
||||
assert parse_examples("**Output:** 1\n") == []
|
||||
assert parse_examples("") == []
|
||||
|
||||
|
||||
def test_starter_section_is_never_scanned() -> None:
|
||||
text = "# t\n## Starter code (python3)\n```\nInput: a = 1\nOutput: 2\n```\n"
|
||||
assert parse_examples(text) == []
|
||||
192
code_runner/code_runner/tests/test_internals.py
Normal file
192
code_runner/code_runner/tests/test_internals.py
Normal file
@ -0,0 +1,192 @@
|
||||
"""Branches that a healthy sandbox never reaches: crashes, bad results, no bwrap."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from code_runner import Example, Limits, RunnerError, run
|
||||
from code_runner._examples import parse_examples
|
||||
from code_runner._languages import JAVASCRIPT, PYTHON, get_language
|
||||
from code_runner._run import Box, _read_result
|
||||
from code_runner._sandbox import BoxResult, bwrap_argv, check_sandbox
|
||||
from code_runner._starter import parse_starter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
STARTER = "def f(a):\n"
|
||||
EXAMPLE = Example(1, {"a": 1}, 1)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_sandbox_check() -> Iterator[None]:
|
||||
check_sandbox.cache_clear()
|
||||
yield
|
||||
check_sandbox.cache_clear()
|
||||
|
||||
|
||||
def _fake(result: BoxResult, files: dict[str, str] | None = None) -> Box:
|
||||
def box(
|
||||
command: list[str],
|
||||
scratch: Path,
|
||||
limits: Limits,
|
||||
memory: int,
|
||||
binds: tuple[str, ...],
|
||||
) -> BoxResult:
|
||||
for name, text in (files or {}).items():
|
||||
(scratch / name).write_text(text)
|
||||
return result
|
||||
|
||||
return box
|
||||
|
||||
|
||||
def _box(**kw: object) -> BoxResult:
|
||||
fields = {
|
||||
"returncode": 0,
|
||||
"timed_out": False,
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"elapsed_ms": 7.0,
|
||||
}
|
||||
return BoxResult(**(fields | kw))
|
||||
|
||||
|
||||
def _run(box: Box) -> object:
|
||||
return run("python3", "", STARTER, [EXAMPLE], box=box)[0]
|
||||
|
||||
|
||||
def test_crash_without_result_names_the_exit_code() -> None:
|
||||
result = _run(_fake(_box(returncode=139)))
|
||||
assert (result.ok, result.actual, result.error, result.ms) == (
|
||||
False,
|
||||
None,
|
||||
"Crashed (exit 139)",
|
||||
7.0,
|
||||
)
|
||||
|
||||
|
||||
def test_out_of_memory_crash_is_named() -> None:
|
||||
stderr = "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory"
|
||||
assert (
|
||||
_run(_fake(_box(returncode=134, stderr=stderr))).error == "MemoryLimitExceeded"
|
||||
)
|
||||
|
||||
|
||||
def test_timeout_wins_over_a_result_file() -> None:
|
||||
files = {"result.json": '{"ok": true, "value": 1}'}
|
||||
result = _run(_fake(_box(timed_out=True, elapsed_ms=1000.0), files))
|
||||
assert (result.error, result.ms) == ("TimeLimitExceeded", 1000.0)
|
||||
|
||||
|
||||
def test_result_file_variants() -> None:
|
||||
good = _run(
|
||||
_fake(_box(stdout="hi"), {"result.json": '{"ok": true, "value": 1, "ms": 2.5}'})
|
||||
)
|
||||
assert (good.ok, good.ms, good.stdout) == (True, 2.5, "hi")
|
||||
no_ms = _run(_fake(_box(), {"result.json": '{"ok": true, "value": 1}'}))
|
||||
assert no_ms.ms == 7.0
|
||||
failed = _run(_fake(_box(), {"result.json": '{"ok": false}'}))
|
||||
assert failed.error == "Error"
|
||||
named = _run(
|
||||
_fake(_box(), {"result.json": '{"ok": false, "error": "KeyError: x"}'})
|
||||
)
|
||||
assert named.error == "KeyError: x"
|
||||
|
||||
|
||||
def test_unreadable_result_files_are_a_crash(tmp_path: Path) -> None:
|
||||
secret = tmp_path / "secret"
|
||||
secret.write_text('{"ok": true, "value": "stolen"}')
|
||||
(tmp_path / "result.json").symlink_to(secret)
|
||||
assert _read_result(tmp_path) is None
|
||||
(tmp_path / "result.json").unlink()
|
||||
os.mkfifo(tmp_path / "result.json")
|
||||
assert _read_result(tmp_path) is None
|
||||
(tmp_path / "result.json").unlink()
|
||||
for text in ("not json", "[1]", '{"no": "ok"}'):
|
||||
(tmp_path / "result.json").write_text(text)
|
||||
assert _read_result(tmp_path) is None
|
||||
assert _read_result(tmp_path / "missing") is None
|
||||
|
||||
|
||||
def test_binary_resolution(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
ghost = dataclasses.replace(
|
||||
PYTHON, binary_default="/nope", program="no-such-program-xyz"
|
||||
)
|
||||
monkeypatch.delenv(ghost.binary_env, raising=False)
|
||||
with pytest.raises(RunnerError, match="no-such-program-xyz not found"):
|
||||
ghost.resolve()
|
||||
tool = tmp_path / "bin" / "python3"
|
||||
tool.parent.mkdir()
|
||||
tool.write_text("#!/bin/sh\n")
|
||||
monkeypatch.setenv(ghost.binary_env, str(tool))
|
||||
assert ghost.resolve() == tool
|
||||
assert ghost.ro_binds(tool) == (str(tool.parent.parent),)
|
||||
assert PYTHON.ro_binds(Path("/usr/bin/python3")) == ()
|
||||
assert get_language("TS").name == "typescript"
|
||||
|
||||
|
||||
def _has(argv: list[str], seq: list[str]) -> bool:
|
||||
return any(argv[i : i + len(seq)] == seq for i in range(len(argv)))
|
||||
|
||||
|
||||
def test_argv_binds_links_and_limits(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setattr("code_runner._sandbox._ROOT_LINKS", ("usr", "no-such-root-dir"))
|
||||
argv = bwrap_argv(["prog"], tmp_path, Limits(timeout_s=1.2), 123, ("/opt/x",))
|
||||
assert _has(argv, ["--ro-bind", "/usr", "/usr"])
|
||||
assert _has(argv, ["--ro-bind", "/opt/x", "/opt/x"])
|
||||
assert _has(argv, ["--bind", str(tmp_path), "/work"])
|
||||
assert "--share-net" not in argv
|
||||
assert {"--unshare-all", "--die-with-parent", "--clearenv", "--remount-ro"} <= set(
|
||||
argv
|
||||
)
|
||||
assert "--as=123" in argv
|
||||
assert "--cpu=3" in argv
|
||||
assert argv[-1] == "prog"
|
||||
|
||||
|
||||
def test_sandbox_preflight_failures(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr("code_runner._sandbox.PRLIMIT", "/no/such/prlimit")
|
||||
with pytest.raises(RunnerError, match="prlimit"):
|
||||
check_sandbox()
|
||||
monkeypatch.undo()
|
||||
|
||||
def missing(*args: object, **kwargs: object) -> None:
|
||||
message = "bwrap"
|
||||
raise FileNotFoundError(message)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", missing)
|
||||
with pytest.raises(RunnerError, match="cannot start"):
|
||||
check_sandbox()
|
||||
|
||||
def refused(*args: object, **kwargs: object) -> subprocess.CompletedProcess[bytes]:
|
||||
return subprocess.CompletedProcess(args, 1, b"", b"bwrap: No permissions\n")
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", refused)
|
||||
with pytest.raises(RunnerError, match="No permissions"):
|
||||
check_sandbox()
|
||||
|
||||
|
||||
def test_statement_and_starter_edge_cases() -> None:
|
||||
escaped = parse_examples('**Input:** s = "a\\"b,c", t = 1\n**Output:** "x"\n')
|
||||
assert escaped[0].args == {"s": 'a"b,c', "t": 1}
|
||||
assert parse_starter("python3", "def f(a, b").params == ("a", "b")
|
||||
skipped = "class S {\n if (x) {\n solve(a) {\n }\n}\n"
|
||||
assert parse_starter("javascript", skipped).name == "solve"
|
||||
|
||||
|
||||
def test_typescript_class_entry_is_exported(tmp_path: Path) -> None:
|
||||
entry = parse_starter(
|
||||
"typescript", "class Solution {\n solve(a: number): number {\n }\n}\n"
|
||||
)
|
||||
get_language("typescript").prepare(tmp_path, "class Solution {}", entry, [1])
|
||||
assert "__entry: Solution" in (tmp_path / "solution.cts").read_text()
|
||||
JAVASCRIPT.prepare(tmp_path, "x", entry, [1])
|
||||
assert (tmp_path / "solution.js").read_text() == "x"
|
||||
206
code_runner/code_runner/tests/test_isolation.py
Normal file
206
code_runner/code_runner/tests/test_isolation.py
Normal file
@ -0,0 +1,206 @@
|
||||
"""Escape attempts: each one runs hostile code in the real sandbox and must fail."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from code_runner import CaseResult, Example, Limits, run
|
||||
from code_runner.tests.conftest import needs_node, needs_sandbox
|
||||
|
||||
pytestmark = needs_sandbox
|
||||
STARTER = "def f(a):\n"
|
||||
FAST = Limits(timeout_s=1.0)
|
||||
|
||||
|
||||
def _one(code: str, lang: str = "python3", limits: Limits = FAST) -> CaseResult:
|
||||
starter = {"python3": STARTER, "javascript": "var f = function(a) {};"}[lang]
|
||||
return run(lang, code, starter, [Example(1, {"a": 0}, 1)], limits=limits)[0]
|
||||
|
||||
|
||||
def _pgrep(pattern: str) -> int:
|
||||
done = subprocess.run(
|
||||
["/usr/bin/pgrep", "-fc", pattern], capture_output=True, text=True, check=False
|
||||
)
|
||||
return int(done.stdout.strip() or 0)
|
||||
|
||||
|
||||
def test_no_network_not_even_host_loopback() -> None:
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen()
|
||||
listener.settimeout(0)
|
||||
port = listener.getsockname()[1]
|
||||
code = (
|
||||
"import socket\n"
|
||||
"def f(a):\n"
|
||||
" out = []\n"
|
||||
f" for host, port in [('127.0.0.1', {port}), ('1.1.1.1', 53), ('::1', {port})]:\n"
|
||||
" try:\n"
|
||||
" socket.create_connection((host, port), timeout=1).close()\n"
|
||||
" out.append('connected')\n"
|
||||
" except OSError:\n"
|
||||
" out.append('blocked')\n"
|
||||
" return out\n"
|
||||
)
|
||||
result = _one(code)
|
||||
with pytest.raises(BlockingIOError):
|
||||
listener.accept()
|
||||
assert result.actual == ["blocked", "blocked", "blocked"]
|
||||
|
||||
|
||||
@needs_node
|
||||
def test_no_network_from_node() -> None:
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen()
|
||||
port = listener.getsockname()[1]
|
||||
code = (
|
||||
"var f = function(a) {\n"
|
||||
" const net = process.getBuiltinModule('node:net');\n"
|
||||
" let seen = 'pending';\n"
|
||||
f" const s = net.connect({port}, '127.0.0.1');\n"
|
||||
" s.on('connect', () => { seen = 'connected'; });\n"
|
||||
" s.on('error', () => {});\n"
|
||||
" return seen;\n"
|
||||
"};"
|
||||
)
|
||||
result = _one(code, "javascript")
|
||||
listener.settimeout(0.2)
|
||||
with pytest.raises(TimeoutError):
|
||||
listener.accept()
|
||||
assert result.actual == "pending"
|
||||
|
||||
|
||||
def test_writes_outside_scratch_never_reach_the_host(tmp_path: Path) -> None:
|
||||
marker = tmp_path / "marker"
|
||||
code = (
|
||||
"def f(a):\n"
|
||||
" out = []\n"
|
||||
f" for path in ['/usr/escape', '/etc/escape', '/escape', {str(marker)!r}]:\n"
|
||||
" try:\n"
|
||||
" open(path, 'w').write('x')\n"
|
||||
" out.append('wrote')\n"
|
||||
" except OSError:\n"
|
||||
" out.append('denied')\n"
|
||||
" return out\n"
|
||||
)
|
||||
result = _one(code)
|
||||
assert result.actual == ["denied", "denied", "denied", "denied"]
|
||||
assert not marker.exists()
|
||||
assert not Path("/usr/escape").exists()
|
||||
|
||||
|
||||
def test_host_files_and_environment_are_invisible(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
secret = tmp_path / "secret.txt"
|
||||
secret.write_text("hunter2")
|
||||
monkeypatch.setenv("CODE_RUNNER_SECRET", "hunter2")
|
||||
code = (
|
||||
"import os\n"
|
||||
"def f(a):\n"
|
||||
f" return [os.path.exists({str(secret)!r}), os.path.exists({str(Path.home())!r}),\n"
|
||||
" 'CODE_RUNNER_SECRET' in os.environ, sorted(os.environ), os.getpid() < 20,\n"
|
||||
" os.path.exists('/proc/1/environ') and 'hunter2' in open('/proc/1/environ').read()]\n"
|
||||
)
|
||||
values = cast("list[Any]", _one(code).actual)
|
||||
exists, home, env_leak, names, own_pidns, proc_leak = values
|
||||
assert (exists, home, env_leak, own_pidns, proc_leak) == (
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
)
|
||||
assert set(names) <= {"HOME", "LANG", "PATH", "PWD", "PYTHONIOENCODING"}
|
||||
|
||||
|
||||
def test_symlink_in_scratch_cannot_exfiltrate_a_host_file(tmp_path: Path) -> None:
|
||||
secret = tmp_path / "secret.txt"
|
||||
secret.write_text("hunter2-secret-contents")
|
||||
code = (
|
||||
"import os\n"
|
||||
"def f(a):\n"
|
||||
f" os.symlink({str(secret)!r}, '/work/result.json')\n"
|
||||
" return 7\n"
|
||||
)
|
||||
result = _one(code)
|
||||
assert "hunter2" not in repr(result)
|
||||
assert result.actual == 7 # the harness replaced the link, never followed it
|
||||
|
||||
|
||||
def test_fork_bomb_is_contained_and_leaves_nothing_behind() -> None:
|
||||
before = _pgrep("python3 -I /work/harness.py")
|
||||
code = (
|
||||
"import os, subprocess\n"
|
||||
"def f(a):\n"
|
||||
" subprocess.Popen(['sleep', '97'])\n"
|
||||
" while True:\n"
|
||||
" os.fork()\n"
|
||||
)
|
||||
started = time.monotonic()
|
||||
result = _one(code)
|
||||
assert time.monotonic() - started < 6
|
||||
assert result.ok is False
|
||||
assert result.error is not None
|
||||
assert result.error.startswith(("TimeLimitExceeded", "BlockingIOError"))
|
||||
time.sleep(0.3)
|
||||
assert _pgrep("python3 -I /work/harness.py") == before
|
||||
assert _pgrep("^sleep 97$") == 0
|
||||
|
||||
|
||||
def test_memory_bomb_is_a_visible_error() -> None:
|
||||
result = _one("def f(a):\n return len(bytearray(8 * 1024**3))\n")
|
||||
assert result.ok is False
|
||||
assert result.error is not None
|
||||
assert result.error.startswith("MemoryError")
|
||||
|
||||
|
||||
@needs_node
|
||||
def test_node_heap_bomb_is_a_visible_error() -> None:
|
||||
code = "var f = function(a) { const x = []; for (;;) x.push(new Array(1e6).fill(1)); };"
|
||||
result = _one(code, "javascript", Limits(timeout_s=5.0))
|
||||
assert result.ok is False
|
||||
assert result.error in {"MemoryLimitExceeded", "RangeError: Invalid array length"}
|
||||
|
||||
|
||||
def test_output_flood_is_capped() -> None:
|
||||
code = "def f(a):\n while True:\n print('x' * 1000)\n"
|
||||
started = time.monotonic()
|
||||
result = _one(code)
|
||||
assert time.monotonic() - started < 6
|
||||
assert result.ok is False
|
||||
assert len(result.stdout) <= 64 * 1024
|
||||
|
||||
|
||||
def test_disk_fill_is_capped_by_the_file_size_limit() -> None:
|
||||
code = (
|
||||
"def f(a):\n"
|
||||
" with open('/work/big', 'wb') as fh:\n"
|
||||
" while True:\n"
|
||||
" fh.write(b'x' * 65536)\n"
|
||||
)
|
||||
result = _one(code)
|
||||
assert result.ok is False
|
||||
assert result.error is not None
|
||||
assert "OSError" in result.error
|
||||
|
||||
|
||||
def test_timeout_kills_every_process_the_solution_started() -> None:
|
||||
code = (
|
||||
"import subprocess\n"
|
||||
"def f(a):\n"
|
||||
" subprocess.Popen(['sleep', '97'])\n"
|
||||
" while True:\n"
|
||||
" pass\n"
|
||||
)
|
||||
result = _one(code)
|
||||
assert result.error == "TimeLimitExceeded"
|
||||
time.sleep(0.3)
|
||||
assert _pgrep("^sleep 97$") == 0
|
||||
207
code_runner/code_runner/tests/test_run.py
Normal file
207
code_runner/code_runner/tests/test_run.py
Normal file
@ -0,0 +1,207 @@
|
||||
"""End to end through the real sandbox: every language, every kind of outcome."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from code_runner import CaseResult, Example, Limits, RunnerError, run
|
||||
from code_runner.tests.conftest import (
|
||||
TWO_SUM_CODE,
|
||||
TWO_SUM_STARTER,
|
||||
needs_node,
|
||||
needs_sandbox,
|
||||
)
|
||||
|
||||
LANGS = [
|
||||
pytest.param("python3", marks=needs_sandbox),
|
||||
pytest.param("javascript", marks=needs_node),
|
||||
pytest.param("typescript", marks=needs_node),
|
||||
]
|
||||
FAST = Limits(timeout_s=1.0)
|
||||
|
||||
|
||||
def _two_sum(lang: str, code: str | None, examples: list[Example]) -> list[CaseResult]:
|
||||
return run(lang, code or TWO_SUM_CODE[lang], TWO_SUM_STARTER[lang], examples)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", LANGS)
|
||||
def test_correct_solution_passes_every_example(
|
||||
lang: str, two_sum_examples: list[Example]
|
||||
) -> None:
|
||||
results = _two_sum(lang, None, two_sum_examples)
|
||||
assert [r.ok for r in results] == [True, True, True]
|
||||
assert [r.n for r in results] == [1, 2, 3]
|
||||
first = results[0]
|
||||
assert first.input == {"nums": [2, 7, 11, 15], "target": 9}
|
||||
assert first.expected == [0, 1]
|
||||
assert sorted(first.actual) == [0, 1] # any order: [1, 0] is fine
|
||||
assert first.error is None
|
||||
assert first.ms >= 0
|
||||
|
||||
|
||||
WRONG = {
|
||||
"python3": "class Solution:\n def twoSum(self, nums, target):\n return [0, 0]\n",
|
||||
"javascript": "var twoSum = function(nums, target) { return [0, 0]; };",
|
||||
"typescript": "function twoSum(nums: number[], target: number): number[] { return [0, 0]; }",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", LANGS)
|
||||
def test_wrong_answer_is_reported_with_actual_value(
|
||||
lang: str, two_sum_examples: list[Example]
|
||||
) -> None:
|
||||
results = _two_sum(lang, WRONG[lang], two_sum_examples)
|
||||
assert [r.ok for r in results] == [False, False, False]
|
||||
assert results[0].actual == [0, 0]
|
||||
assert results[0].error is None
|
||||
|
||||
|
||||
THROWS = {
|
||||
"python3": "class Solution:\n def twoSum(self, nums, target):\n return nums[99]\n",
|
||||
"javascript": "var twoSum = function(nums, target) { throw new RangeError('boom'); };",
|
||||
"typescript": "function twoSum(nums: number[], target: number): number[] { throw new RangeError('boom'); }",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", LANGS)
|
||||
def test_exception_becomes_an_error_per_case(
|
||||
lang: str, two_sum_examples: list[Example]
|
||||
) -> None:
|
||||
results = _two_sum(lang, THROWS[lang], two_sum_examples[:1])
|
||||
only = results[0]
|
||||
assert only.ok is False
|
||||
assert only.actual is None
|
||||
assert only.error is not None
|
||||
assert only.error.split(":")[0] in {"IndexError", "RangeError"}
|
||||
|
||||
|
||||
BROKEN = {
|
||||
"python3": "class Solution:\n def twoSum(self, nums, target) return 1\n",
|
||||
"javascript": "var twoSum = function(nums, target) { return ; ;; }}",
|
||||
"typescript": "function twoSum(nums: number[], target: number): number[] { return [ }",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", LANGS)
|
||||
def test_syntax_error_is_reported(lang: str, two_sum_examples: list[Example]) -> None:
|
||||
results = _two_sum(lang, BROKEN[lang], two_sum_examples[:2])
|
||||
assert [r.ok for r in results] == [False, False]
|
||||
assert all(r.error and r.error.startswith("SyntaxError") for r in results)
|
||||
|
||||
|
||||
PRINTS = {
|
||||
"python3": "class Solution:\n def twoSum(self, nums, target):\n print('hi', target)\n return [0, 1]\n",
|
||||
"javascript": "var twoSum = function(nums, target) { console.log('hi', target); return [0, 1]; };",
|
||||
"typescript": "function twoSum(nums: number[], target: number): number[] { console.log('hi', target); return [0, 1]; }",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", LANGS)
|
||||
def test_prints_land_in_stdout_per_case(
|
||||
lang: str, two_sum_examples: list[Example]
|
||||
) -> None:
|
||||
results = _two_sum(lang, PRINTS[lang], two_sum_examples[:2])
|
||||
assert results[0].stdout.strip() == "hi 9"
|
||||
assert results[1].stdout.strip() == "hi 6"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", LANGS)
|
||||
def test_missing_entry_point_in_code_is_a_case_error(
|
||||
lang: str, two_sum_examples: list[Example]
|
||||
) -> None:
|
||||
code = {
|
||||
"python3": "x = 1\n",
|
||||
"javascript": "var other = 1;",
|
||||
"typescript": "const other = 1;",
|
||||
}
|
||||
results = _two_sum(lang, code[lang], two_sum_examples[:1])
|
||||
assert results[0].ok is False
|
||||
assert results[0].error is not None
|
||||
assert "twoSum" in results[0].error or "Solution" in results[0].error
|
||||
|
||||
|
||||
def test_class_style_javascript_and_function_style_python() -> None:
|
||||
js = run(
|
||||
"javascript",
|
||||
"class Solution { solve(a, b) { return a + b; } }",
|
||||
"class Solution {\n solve(a, b) {\n }\n}",
|
||||
[Example(1, {"a": 1, "b": 2}, 3)],
|
||||
)
|
||||
py = run(
|
||||
"python3",
|
||||
"def add(a, b):\n return a + b\n",
|
||||
"def add(a: int, b: int) -> int:\n",
|
||||
[Example(1, {"a": 1, "b": 2}, 3)],
|
||||
)
|
||||
assert js[0].ok is True
|
||||
assert py[0].ok is True
|
||||
|
||||
|
||||
def test_python_prelude_and_aliases() -> None:
|
||||
code = "class Solution:\n def f(self, xs: List[int]) -> int:\n return collections.Counter(xs)[1]\n"
|
||||
starter = "class Solution:\n def f(self, xs: List[int]) -> int:\n"
|
||||
out = run("python", code, starter, [Example(1, {"xs": [1, 1, 2]}, 2)])
|
||||
assert out[0].ok is True
|
||||
|
||||
|
||||
def test_positional_fallback_when_statement_names_differ() -> None:
|
||||
out = run(
|
||||
"python3",
|
||||
"def add(a, b):\n return a - b\n",
|
||||
"def add(a, b):\n",
|
||||
[Example(1, {"x": 5, "y": 2}, 3)],
|
||||
)
|
||||
assert out[0].ok is True
|
||||
|
||||
|
||||
def test_argument_count_mismatch_is_a_case_error_without_running() -> None:
|
||||
out = run(
|
||||
"python3",
|
||||
"def add(a, b):\n return a\n",
|
||||
"def add(a, b):\n",
|
||||
[Example(1, {"only": 5}, 3)],
|
||||
)
|
||||
assert out[0].ok is False
|
||||
assert out[0].error is not None
|
||||
assert out[0].error.startswith("ArgumentError")
|
||||
|
||||
|
||||
def test_non_json_result_is_a_case_error() -> None:
|
||||
out = run(
|
||||
"python3",
|
||||
"def f(a):\n return {1, 2}\n",
|
||||
"def f(a):\n",
|
||||
[Example(1, {"a": 1}, [1, 2])],
|
||||
)
|
||||
assert out[0].error is not None
|
||||
assert out[0].error.startswith("TypeError")
|
||||
|
||||
|
||||
def test_deep_order_and_float_tolerance() -> None:
|
||||
out = run(
|
||||
"python3",
|
||||
"def f(a):\n return [[2, 1], [0, -1]]\n",
|
||||
"def f(a):\n",
|
||||
[Example(1, {"a": 0}, [[-1, 0], [1, 2]], "deep")],
|
||||
)
|
||||
assert out[0].ok is True
|
||||
|
||||
|
||||
def test_timeout_is_per_case() -> None:
|
||||
out = run(
|
||||
"python3",
|
||||
"def f(a):\n while a:\n pass\n return 1\n",
|
||||
"def f(a):\n",
|
||||
[Example(1, {"a": 1}, 1), Example(2, {"a": 0}, 1)],
|
||||
limits=FAST,
|
||||
)
|
||||
assert out[0].error == "TimeLimitExceeded"
|
||||
assert out[0].ok is False
|
||||
assert out[0].ms >= 900
|
||||
assert out[1].ok is True
|
||||
|
||||
|
||||
def test_unsupported_language_and_empty_examples() -> None:
|
||||
with pytest.raises(RunnerError, match="language"):
|
||||
run("cobol", "", "", [])
|
||||
assert run("python3", "def f(a): pass\n", "def f(a):\n", []) == []
|
||||
78
code_runner/code_runner/tests/test_starter.py
Normal file
78
code_runner/code_runner/tests/test_starter.py
Normal file
@ -0,0 +1,78 @@
|
||||
import pytest
|
||||
|
||||
from code_runner._model import RunnerError
|
||||
from code_runner._starter import Entry, extract_starter, parse_starter
|
||||
|
||||
PY_CLASS = """class Solution:
|
||||
def twoSum(self, nums: list[int], target: int) -> list[int]:
|
||||
"""
|
||||
PY_COMMENTED = """# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
class Solution:
|
||||
def solve(self, grid: Dict[str, Tuple[int, int]], k: int = 3, *rest) -> int:
|
||||
pass
|
||||
"""
|
||||
PY_FUNC = "def add(a: int, b: int = 2) -> int:\n pass\n"
|
||||
JS_VAR = """/**
|
||||
* @param {number[]} nums
|
||||
*/
|
||||
var twoSum = function(nums, target) {
|
||||
|
||||
};"""
|
||||
JS_FUNC = "function isPalindrome(x, y = 3) {\n}\n"
|
||||
JS_ARROW = "const f = (a, b) => {\n}\n"
|
||||
JS_CLASS = "class Solution {\n constructor() {}\n solve(nums, ...rest) {\n }\n}\n"
|
||||
TS_FUNC = "function twoSum(nums: number[], target: number): number[] {\n};"
|
||||
TS_ARROW = "const f = (a: Map<string, number>, b?: number): number => {\n}\n"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("lang", "text", "want"),
|
||||
[
|
||||
("python3", PY_CLASS, Entry("Solution", "twoSum", ("nums", "target"))),
|
||||
("python3", PY_COMMENTED, Entry("Solution", "solve", ("grid", "k"))),
|
||||
("python3", PY_FUNC, Entry(None, "add", ("a", "b"))),
|
||||
("javascript", JS_VAR, Entry(None, "twoSum", ("nums", "target"))),
|
||||
("javascript", JS_FUNC, Entry(None, "isPalindrome", ("x", "y"))),
|
||||
("javascript", JS_ARROW, Entry(None, "f", ("a", "b"))),
|
||||
("javascript", JS_CLASS, Entry("Solution", "solve", ("nums",))),
|
||||
("typescript", TS_FUNC, Entry(None, "twoSum", ("nums", "target"))),
|
||||
("typescript", TS_ARROW, Entry(None, "f", ("a", "b"))),
|
||||
],
|
||||
)
|
||||
def test_parse_starter(lang: str, text: str, want: Entry) -> None:
|
||||
assert parse_starter(lang, text) == want
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("lang", "text"),
|
||||
[
|
||||
("python3", "x = 1\n"),
|
||||
("python3", "class Solution:\n pass\n"),
|
||||
("javascript", "// nothing here\n"),
|
||||
("javascript", "class Solution {\n constructor() {}\n}\n"),
|
||||
("typescript", ""),
|
||||
],
|
||||
)
|
||||
def test_starter_without_entry_is_refused(lang: str, text: str) -> None:
|
||||
with pytest.raises(RunnerError, match="entry point"):
|
||||
parse_starter(lang, text)
|
||||
|
||||
|
||||
def test_extract_starter_takes_the_fenced_block() -> None:
|
||||
statement = (
|
||||
"# 1. Two Sum (Easy)\n\nbody\n\n## Starter code (python3)\n```\n"
|
||||
+ PY_CLASS
|
||||
+ "```\n\n## Site hints\nnope\n"
|
||||
)
|
||||
assert extract_starter(statement) == PY_CLASS
|
||||
|
||||
|
||||
def test_extract_starter_without_section_is_empty() -> None:
|
||||
assert extract_starter("# 1. Two Sum\n\nno starter\n") == ""
|
||||
|
||||
|
||||
def test_extract_starter_unfenced_runs_to_next_section() -> None:
|
||||
text = "intro\n## Starter code (javascript)\nvar f = function(a) {};\n## Hints\nx\n"
|
||||
assert extract_starter(text) == "var f = function(a) {};\n"
|
||||
12
code_runner/install.sh
Executable file
12
code_runner/install.sh
Executable file
@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
# Editable user install so /usr/bin/python3 (the tutor server, the CLI) can
|
||||
# `import code_runner`. Stdlib only; idempotent.
|
||||
set -euo pipefail
|
||||
|
||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly REPO_DIR
|
||||
readonly SYSTEM_PYTHON="/usr/bin/python3"
|
||||
|
||||
"$SYSTEM_PYTHON" -m pip install --user --no-deps --break-system-packages -e "$REPO_DIR"
|
||||
cd /
|
||||
"$SYSTEM_PYTHON" -c 'import code_runner; print(code_runner.__file__)'
|
||||
198
code_runner/pyproject.toml
Normal file
198
code_runner/pyproject.toml
Normal file
@ -0,0 +1,198 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "code_runner"
|
||||
version = "0.1.0"
|
||||
description = "Run a learner solution (Python, JavaScript, TypeScript) against a problem's examples in a bubblewrap sandbox"
|
||||
requires-python = ">=3.14"
|
||||
# Stdlib only on purpose: the tutor server imports it from the system python.
|
||||
dependencies = []
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["code_runner*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
code_runner = ["py.typed", "harness/*"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py314"
|
||||
include = ["*.py", "**/*.py"]
|
||||
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["ALL"]
|
||||
ignore = [
|
||||
"CPY001",
|
||||
"D100",
|
||||
"D101",
|
||||
"D102",
|
||||
"D103",
|
||||
"D104",
|
||||
"D105",
|
||||
"D107",
|
||||
"D203",
|
||||
"D213",
|
||||
"COM812",
|
||||
"ISC001",
|
||||
"S603",
|
||||
]
|
||||
fixable = ["ALL"]
|
||||
unfixable = []
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"scripts/*.py" = ["INP001"]
|
||||
# The sandbox-side harness is a program of its own: it reads its job from files.
|
||||
# The sandbox mounts its own private tmpfs at /tmp.
|
||||
"**/_sandbox.py" = ["S108"]
|
||||
"**/harness/*.py" = ["INP001", "T201", "S102", "BLE001", "PTH123"]
|
||||
# Tests embed the learner programs they run as source strings.
|
||||
"**/tests/**/*.py" = ["ARG", "D", "E501", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||
"**/test_*.py" = ["ARG", "D", "E501", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||
|
||||
[tool.ruff.lint.pylint]
|
||||
max-args = 6
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "google"
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
force-single-line = false
|
||||
force-sort-within-sections = true
|
||||
known-first-party = ["code_runner"]
|
||||
|
||||
[tool.ruff.lint.flake8-quotes]
|
||||
docstring-quotes = "double"
|
||||
inline-quotes = "double"
|
||||
|
||||
[tool.ruff.lint.flake8-tidy-imports]
|
||||
ban-relative-imports = "all"
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "double"
|
||||
indent-style = "space"
|
||||
skip-magic-trailing-comma = false
|
||||
line-ending = "auto"
|
||||
docstring-code-format = true
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.14"
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = true
|
||||
disallow_incomplete_defs = true
|
||||
check_untyped_defs = true
|
||||
disallow_untyped_decorators = true
|
||||
no_implicit_optional = true
|
||||
warn_redundant_casts = true
|
||||
warn_unused_ignores = true
|
||||
warn_no_return = true
|
||||
warn_unreachable = true
|
||||
disallow_any_unimported = true
|
||||
disallow_any_explicit = false
|
||||
disallow_any_generics = true
|
||||
disallow_subclassing_any = true
|
||||
strict_equality = true
|
||||
extra_checks = true
|
||||
ignore_missing_imports = true
|
||||
show_error_codes = true
|
||||
color_output = true
|
||||
exclude = [".venv/"]
|
||||
|
||||
[tool.pylint.main]
|
||||
# The repo root on the path, so pylint resolves the package's own imports the
|
||||
# same way pytest does instead of reporting import-error for them.
|
||||
init-hook = "import sys; sys.path.insert(0, 'code_runner')"
|
||||
analyse-fallback-blocks = true
|
||||
persistent = true
|
||||
jobs = 0
|
||||
py-version = "3.14"
|
||||
ignore = [".venv", "__pycache__"]
|
||||
# Test suites intentionally use patterns (protected-access, fixture-arg
|
||||
# shadowing) that don't apply to source code; ruff's per-file-ignores carry
|
||||
# the equivalent exemptions, so tests stay linted -- by ruff. This is the same
|
||||
# source-only pylint scope wake-alarm / diet-guard / testsAndMisc use. It has
|
||||
# to be `ignore-paths`, not `ignore = ["tests"]`: `ignore` only matches the
|
||||
# basename of what pylint is *given*, and pre-commit hands it explicit file
|
||||
# paths, so a directory name in `ignore` never fires under the hook.
|
||||
# harness/ runs inside the sandbox and must exec the solution it is given.
|
||||
ignore-paths = ["^(.*/)?tests/.*$", "^(.*/)?harness/.*$"]
|
||||
ignore-patterns = [".*\\.pyi$"]
|
||||
|
||||
[tool.pylint.messages_control]
|
||||
enable = "all"
|
||||
disable = [
|
||||
"missing-module-docstring",
|
||||
"missing-class-docstring",
|
||||
"missing-function-docstring",
|
||||
"use-implicit-booleaness-not-comparison-to-zero",
|
||||
]
|
||||
|
||||
[tool.pylint.design]
|
||||
max-args = 6
|
||||
min-public-methods = 0
|
||||
max-module-lines = 1000
|
||||
max-attributes = 10
|
||||
|
||||
[tool.pylint.typecheck]
|
||||
generated-members = [
|
||||
".*\\.assert_called_once_with",
|
||||
".*\\.assert_called_once",
|
||||
".*\\.assert_called",
|
||||
".*\\.assert_not_called",
|
||||
".*\\.assert_any_call",
|
||||
".*\\.call_args",
|
||||
".*\\.call_args_list",
|
||||
".*\\.call_count",
|
||||
]
|
||||
|
||||
[tool.bandit]
|
||||
exclude_dirs = ["tests", ".venv"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = ["sandbox: needs bubblewrap with unprivileged user namespaces (skipped otherwise)"]
|
||||
testpaths = ["code_runner/tests"]
|
||||
python_files = ["test_*.py", "*_test.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
addopts = [
|
||||
"-v",
|
||||
"--strict-markers",
|
||||
"--strict-config",
|
||||
"-ra",
|
||||
"--cov=code_runner",
|
||||
"--cov-branch",
|
||||
"--cov-report=term-missing",
|
||||
"--cov-report=lcov",
|
||||
]
|
||||
filterwarnings = [
|
||||
"error",
|
||||
"ignore::DeprecationWarning",
|
||||
"default::pytest.PytestUnraisableExceptionWarning",
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["code_runner"]
|
||||
branch = true
|
||||
omit = [
|
||||
# Runs inside the sandbox in another process; behaviour is tested through run().
|
||||
"*/harness/*",
|
||||
"*/__pycache__/*",
|
||||
"*/tests/*",
|
||||
"*/.venv/*",
|
||||
]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 100
|
||||
show_missing = true
|
||||
skip_covered = false
|
||||
exclude_lines = [
|
||||
"pragma: no cover",
|
||||
"raise NotImplementedError",
|
||||
"raise AssertionError",
|
||||
"if TYPE_CHECKING:",
|
||||
'if __name__ == "__main__":',
|
||||
]
|
||||
partial_branches = ["pragma: no branch"]
|
||||
10
code_runner/requirements.txt
Normal file
10
code_runner/requirements.txt
Normal file
@ -0,0 +1,10 @@
|
||||
# Exact pins, enforced by the shared dependency-freshness gate: a `>=`
|
||||
# floor is satisfied by anything newer, so it tells a checker nothing
|
||||
# about whether this repo is actually current.
|
||||
bandit[toml]==1.9.4
|
||||
mypy==2.4.1
|
||||
pre-commit==4.7.0
|
||||
pylint==4.1.3
|
||||
pytest==9.2.0
|
||||
pytest-cov==7.1.0
|
||||
ruff==0.17.3
|
||||
@ -19,5 +19,10 @@ the clock earns only once the clock reaches it); `record_activity` rejects a `ts
|
||||
more than 120 s ahead (ValueError). `end_project(id, day)` rejects a past `day`
|
||||
(ValueError); today or later is fine. The harvester pays every project day of the
|
||||
last 31 days, so late-synced events for older days are credited (idempotent).
|
||||
Overtime carries over: own minutes past a day's target bank (max 60) and pay on the
|
||||
next project day; the bank never crosses the project's end. `minutes_for(day)` is the
|
||||
capped pay figure, `status(day)["minutes"]` the real count (121/120) with `carried_in`,
|
||||
`carry_out`, `own_minutes`, `counted_minutes`. Carry ledger rows: `<project>-<YYYYMMDD>-carry`
|
||||
(`detail.carry`), never over `daily_minutes` together with own rows.
|
||||
Open the work: `python3 -m focus_project.open [--no-site]` (tutor focus screen, `work_url`).
|
||||
Install: `./install.sh` (stdlib only, editable user install for `/usr/bin/python3`).
|
||||
|
||||
31
focus_project/focus_project/_own.py
Normal file
31
focus_project/focus_project/_own.py
Normal file
@ -0,0 +1,31 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""A project day's own worked minutes: the union of every source's intervals."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from focus_project import sources
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
|
||||
from focus_project._model import Project
|
||||
|
||||
|
||||
def union_seconds(spans: list[sources.Interval]) -> float:
|
||||
"""Total length of the union of ``spans``."""
|
||||
total = 0.0
|
||||
end = float("-inf")
|
||||
for lo, hi in sorted(spans):
|
||||
if hi <= end:
|
||||
continue
|
||||
total += hi - max(lo, end)
|
||||
end = hi
|
||||
return total
|
||||
|
||||
|
||||
def own_minutes_of(project: Project, day: date, moment: float) -> int:
|
||||
"""Whole minutes worked on ``day``, uncapped, nothing after ``moment``."""
|
||||
spans = sources.clip(sources.collect(day, project), (float("-inf"), moment))
|
||||
return int(union_seconds(spans) // 60)
|
||||
75
focus_project/focus_project/carry.py
Normal file
75
focus_project/focus_project/carry.py
Normal file
@ -0,0 +1,75 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Overtime carries over: minutes past a day's target bank for the next day.
|
||||
|
||||
Contract (kuhy, 2026-11-02): own minutes beyond ``daily_on(day)`` are banked
|
||||
(at most :data:`BANK_CAP`) and pay on the NEXT project day. The bank never
|
||||
crosses the project's last day (what is left then expires) and a carry never
|
||||
pays on a day with no project. The balance is derived from the activity
|
||||
record, never stored, so it cannot drift; a project day's counted minutes
|
||||
are ``min(daily, own + carried_in)``. The bank is spent first, so what a day
|
||||
takes from it is fixed when the day starts and only own minutes grow.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
import logging
|
||||
from typing import Final
|
||||
|
||||
from focus_project import _api, _clock
|
||||
from focus_project._errors import RegistryError
|
||||
from focus_project._own import own_minutes_of
|
||||
|
||||
BANK_CAP: Final = 60
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Balance:
|
||||
"""One project day: worked minutes, bank taken in, bank left for tomorrow."""
|
||||
|
||||
own: int
|
||||
carried_in: int
|
||||
carry_out: int
|
||||
|
||||
def paid_bank(self, daily: int) -> int:
|
||||
"""Minutes of the day paid from the bank (fixed at the day's start)."""
|
||||
return min(self.carried_in, daily)
|
||||
|
||||
def paid_own(self, daily: int) -> int:
|
||||
"""Minutes of the day paid from own work, after the bank."""
|
||||
return min(self.own, daily - self.paid_bank(daily))
|
||||
|
||||
def counted(self, daily: int) -> int:
|
||||
"""Minutes that count on the day: own plus carried, capped at ``daily``."""
|
||||
return min(daily, self.own + self.carried_in)
|
||||
|
||||
|
||||
_NONE: Final = Balance(0, 0, 0)
|
||||
|
||||
|
||||
def balance(day: date, now: float | None = None) -> Balance:
|
||||
"""The balance of ``day`` (zeros with no project or an unreadable registry)."""
|
||||
moment = _clock.now() if now is None else now
|
||||
try:
|
||||
project = _api.active(day)
|
||||
if project is None:
|
||||
return _NONE
|
||||
bank = 0
|
||||
cursor = project.start
|
||||
while True:
|
||||
own = own_minutes_of(project, cursor, moment)
|
||||
total = own + bank
|
||||
left = min(BANK_CAP, max(0, total - project.daily_on(cursor)))
|
||||
if cursor >= day:
|
||||
return Balance(own, bank, left)
|
||||
bank, cursor = left, cursor + timedelta(days=1)
|
||||
except (RegistryError, OSError) as exc:
|
||||
_LOG.warning("focus_project registry unreadable, nothing banked: %s", exc)
|
||||
return _NONE
|
||||
|
||||
|
||||
def own_minutes(day: date, now: float | None = None) -> int:
|
||||
"""Minutes worked on ``day``, not capped at the target (0 with no project)."""
|
||||
return balance(day, now).own
|
||||
@ -7,6 +7,9 @@ one-minute ``.timer``). Harvests every project day of the last
|
||||
after the fact) is paid once a run sees it; ``credit_to`` is idempotent, so
|
||||
settled days cost one read and write nothing. Failure modes, by path:
|
||||
|
||||
Overtime past a day's target banks for the next day (``carry``): that day's
|
||||
carry row pays it from the day's start, own-work rows pay the rest.
|
||||
|
||||
* a source that errors: logged, contributes 0, the run continues (fail closed);
|
||||
* an unreadable registry, signing key or ledger: logged, exit status 1, so
|
||||
the unit shows ``failed`` instead of silently crediting nothing.
|
||||
@ -18,9 +21,8 @@ from datetime import date, timedelta
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from focus_project import _api, _clock, ledger
|
||||
from focus_project import _api, _clock, carry, ledger
|
||||
from focus_project._errors import RegistryError
|
||||
from focus_project.minutes import minutes_for
|
||||
|
||||
BACKFILL_DAYS = 31 # bounds the per-run cost; the relay accepts events <= 48 h old
|
||||
_LOG = logging.getLogger("focus_project.harvest")
|
||||
@ -43,11 +45,18 @@ def harvest_day(day: date, now: float) -> int:
|
||||
project = _api.active(day)
|
||||
if project is None:
|
||||
return 0
|
||||
total = minutes_for(day, now=now)
|
||||
added = ledger.credit_to(project, day, total, now=now)
|
||||
daily = project.daily_on(day)
|
||||
bank = carry.balance(day, now)
|
||||
added = ledger.credit_to(project, day, bank.paid_bank(daily), now=now, carry=True)
|
||||
added += ledger.credit_to(project, day, bank.paid_own(daily), now=now)
|
||||
if added:
|
||||
_LOG.info(
|
||||
"credited %d min to %s on %s (total %d)", added, project.id, day, total
|
||||
"credited %d min to %s on %s (total %d, %d from the bank)",
|
||||
added,
|
||||
project.id,
|
||||
day,
|
||||
bank.counted(daily),
|
||||
bank.paid_bank(daily),
|
||||
)
|
||||
return added
|
||||
|
||||
|
||||
@ -93,10 +93,19 @@ def _write_rows(path: Path, rows: list[Any]) -> None:
|
||||
Path(handle.name).replace(path)
|
||||
|
||||
|
||||
def paid_minutes(rows: list[Any], key: bytes, project_id: str, day: date) -> int:
|
||||
def paid_minutes(
|
||||
rows: list[Any],
|
||||
key: bytes,
|
||||
project_id: str,
|
||||
day: date,
|
||||
*,
|
||||
carry: bool | None = None,
|
||||
) -> int:
|
||||
"""Minutes already paid for ``project_id`` on ``day`` by verified rows.
|
||||
|
||||
A repeated ``entry_id`` pays once, at its smallest count.
|
||||
``carry`` picks one class (True: banked-overtime rows, False: own-work
|
||||
rows); None sums both. A repeated ``entry_id`` pays once, at its smallest
|
||||
count.
|
||||
"""
|
||||
by_id: dict[str, int] = {}
|
||||
for row in rows:
|
||||
@ -112,6 +121,7 @@ def paid_minutes(rows: list[Any], key: bytes, project_id: str, day: date) -> int
|
||||
or not isinstance(minutes, int)
|
||||
or isinstance(minutes, bool)
|
||||
or minutes < 1
|
||||
or (carry is not None and bool(detail.get("carry")) != carry)
|
||||
or not earned_time.verified(row, key)
|
||||
):
|
||||
continue
|
||||
@ -121,13 +131,31 @@ def paid_minutes(rows: list[Any], key: bytes, project_id: str, day: date) -> int
|
||||
|
||||
|
||||
def build_row( # noqa: PLR0913
|
||||
project_id: str, day: date, total: int, minutes: int, key: bytes, *, now: float
|
||||
project_id: str,
|
||||
day: date,
|
||||
total: int,
|
||||
minutes: int,
|
||||
key: bytes,
|
||||
*,
|
||||
now: float,
|
||||
carry: bool = False,
|
||||
first_carry: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""The signed row paying ``minutes`` that bring the day's total to ``total``."""
|
||||
"""The signed row paying ``minutes`` that bring the day's total to ``total``.
|
||||
|
||||
A ``carry`` row pays banked overtime: ``<project>-<YYYYMMDD>-carry``, or
|
||||
``-carry-m<total>`` when it tops up an earlier carry row (late data for
|
||||
the day before grew the bank).
|
||||
"""
|
||||
ended = min(now, day_bounds(day)[1] - 1)
|
||||
stem = f"{project_id}-{day:%Y%m%d}"
|
||||
if not carry:
|
||||
entry_id = f"{stem}-m{total}"
|
||||
else:
|
||||
entry_id = f"{stem}-carry" if first_carry else f"{stem}-carry-m{total}"
|
||||
row: dict[str, Any] = {
|
||||
"kind": CREDIT,
|
||||
"entry_id": f"{project_id}-{day:%Y%m%d}-m{total}",
|
||||
"entry_id": entry_id,
|
||||
"day": day.isoformat(),
|
||||
"created_at": float(now),
|
||||
"detail": {
|
||||
@ -135,6 +163,7 @@ def build_row( # noqa: PLR0913
|
||||
"minutes": int(minutes),
|
||||
"total": int(total),
|
||||
"ended_at": float(ended),
|
||||
**({"carry": True} if carry else {}),
|
||||
},
|
||||
}
|
||||
row["hmac"] = str(earned_time.entry_signature(row, key))
|
||||
@ -142,10 +171,18 @@ def build_row( # noqa: PLR0913
|
||||
|
||||
|
||||
def credit_to(
|
||||
project: Project, day: date, total: int, *, now: float | None = None
|
||||
project: Project,
|
||||
day: date,
|
||||
total: int,
|
||||
*,
|
||||
now: float | None = None,
|
||||
carry: bool = False,
|
||||
) -> int:
|
||||
"""Pay the day up to ``total`` cumulative minutes; return minutes added.
|
||||
|
||||
``carry`` pays the banked-overtime class and counts only its own rows;
|
||||
the default pays (and counts) own work.
|
||||
|
||||
Idempotent: nothing is written when the ledger already pays ``total`` or
|
||||
more. Raises LedgerError (unreadable ledger, unreadable key, unverifiable
|
||||
write) so the harvester can fail loudly instead of crediting nothing quietly.
|
||||
@ -159,11 +196,18 @@ def credit_to(
|
||||
with path.with_suffix(".lock").open("w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
rows = read_rows(path)
|
||||
paid = paid_minutes(rows, key, project.id, day)
|
||||
paid = paid_minutes(rows, key, project.id, day, carry=carry)
|
||||
if total <= paid:
|
||||
return 0
|
||||
row = build_row(
|
||||
project.id, day, total, total - paid, key, now=now or time.time()
|
||||
project.id,
|
||||
day,
|
||||
total,
|
||||
total - paid,
|
||||
key,
|
||||
now=now or time.time(),
|
||||
carry=carry,
|
||||
first_carry=paid == 0,
|
||||
)
|
||||
if any(
|
||||
isinstance(r, dict) and r.get("entry_id") == row["entry_id"] for r in rows
|
||||
@ -172,7 +216,7 @@ def credit_to(
|
||||
raise LedgerError(msg)
|
||||
_write_rows(path, [*rows, row])
|
||||
stored = read_rows(path)
|
||||
if paid_minutes(stored, key, project.id, day) != total:
|
||||
if paid_minutes(stored, key, project.id, day, carry=carry) != total:
|
||||
msg = f"row {row['entry_id']} not found verified on read-back"
|
||||
raise LedgerError(msg)
|
||||
return total - paid
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Credited focus minutes per day: the union of every source's intervals.
|
||||
|
||||
Contract: union of activity intervals on the local calendar day, capped at
|
||||
the active project's ``daily_minutes``; overlaps never double count; whole
|
||||
Contract: union of activity intervals on the local calendar day plus the
|
||||
overtime carried in from the day before (:mod:`focus_project.carry`), capped
|
||||
at the active project's ``daily_minutes``; overlaps never double count; whole
|
||||
minutes (floor). Time not yet lived is never credited: every interval is
|
||||
clipped at "now", so an event stamped ahead of the clock (a fast phone clock)
|
||||
earns only once the real clock reaches it. An unreadable registry reads as 0
|
||||
@ -14,24 +15,13 @@ from __future__ import annotations
|
||||
from datetime import date # noqa: TC003
|
||||
import logging
|
||||
|
||||
from focus_project import _api, _clock, sources
|
||||
from focus_project import _api, _clock, carry
|
||||
from focus_project._errors import RegistryError
|
||||
from focus_project._own import union_seconds
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def union_seconds(spans: list[sources.Interval]) -> float:
|
||||
"""Total length of the union of ``spans``."""
|
||||
total = 0.0
|
||||
end = float("-inf")
|
||||
for lo, hi in sorted(spans):
|
||||
if hi <= end:
|
||||
continue
|
||||
total += hi - max(lo, end)
|
||||
end = hi
|
||||
return total
|
||||
|
||||
|
||||
def minutes_for(day: date, now: float | None = None) -> int:
|
||||
"""Minutes of focus work credited on ``day`` (0 with no project active).
|
||||
|
||||
@ -45,6 +35,7 @@ def minutes_for(day: date, now: float | None = None) -> int:
|
||||
if project is None:
|
||||
return 0
|
||||
moment = _clock.now() if now is None else now
|
||||
spans = sources.clip(sources.collect(day, project), (float("-inf"), moment))
|
||||
seconds = union_seconds(spans)
|
||||
return min(int(seconds // 60), project.daily_on(day))
|
||||
return carry.balance(day, moment).counted(project.daily_on(day))
|
||||
|
||||
|
||||
__all__ = ["minutes_for", "union_seconds"]
|
||||
|
||||
@ -6,27 +6,44 @@ from __future__ import annotations
|
||||
from datetime import date # noqa: TC003
|
||||
from typing import Any
|
||||
|
||||
from focus_project import _api, minutes
|
||||
from focus_project import _api, carry
|
||||
|
||||
|
||||
def status(day: date) -> dict[str, Any]:
|
||||
"""Progress of the project active on ``day``; ``project`` is None if none."""
|
||||
"""Progress of the project active on ``day``; ``project`` is None if none.
|
||||
|
||||
``minutes`` is what was really worked plus what the day took from the
|
||||
bank, so it may exceed ``daily_minutes`` (121/120); ``counted_minutes``
|
||||
is the capped figure that pays.
|
||||
"""
|
||||
project = _api.active(day)
|
||||
if project is None:
|
||||
return {
|
||||
"project": None,
|
||||
"name": None,
|
||||
"minutes": 0,
|
||||
"own_minutes": 0,
|
||||
"counted_minutes": 0,
|
||||
"carried_in": 0,
|
||||
"carry_out": 0,
|
||||
"daily_minutes": None,
|
||||
"unlock_minutes": None,
|
||||
"ends": None,
|
||||
"replaces": [],
|
||||
}
|
||||
daily = project.daily_on(day)
|
||||
bank = carry.balance(day)
|
||||
return {
|
||||
"project": project.id,
|
||||
"name": project.name,
|
||||
"minutes": minutes.minutes_for(day),
|
||||
"daily_minutes": project.daily_on(day),
|
||||
# Real minutes behind the day (own + banked in), never capped: the
|
||||
# number to show. Pay is ``counted_minutes``; earned_time caps it.
|
||||
"minutes": bank.own + bank.carried_in,
|
||||
"own_minutes": bank.own,
|
||||
"counted_minutes": bank.counted(daily),
|
||||
"carried_in": bank.carried_in,
|
||||
"carry_out": bank.carry_out,
|
||||
"daily_minutes": daily,
|
||||
"unlock_minutes": project.unlock_on(day),
|
||||
"ends": project.last_day.isoformat(),
|
||||
"replaces": list(project.replaces),
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path # noqa: TC003
|
||||
@ -13,12 +13,16 @@ import time
|
||||
import pytest
|
||||
|
||||
import focus_project as fp
|
||||
from focus_project import _clock, minutes
|
||||
from focus_project import _clock
|
||||
from focus_project._paths import data_dir
|
||||
|
||||
D1 = date(2026, 11, 2)
|
||||
|
||||
|
||||
def _at(hour: int, minute: int) -> float:
|
||||
return datetime(2026, 11, 2, hour, minute).astimezone().timestamp()
|
||||
|
||||
|
||||
def _project() -> None:
|
||||
fp.create_project(
|
||||
"hr",
|
||||
@ -115,15 +119,20 @@ def test_record_activity_concurrent_appends(data: Path) -> None:
|
||||
assert all(json.loads(x)["source"] == "tutor" for x in lines)
|
||||
|
||||
|
||||
def test_status_active_uses_minutes_module(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def test_status_active_reports_the_worked_minutes() -> None:
|
||||
_project()
|
||||
assert fp.status(D1)["minutes"] == 0 # the stub
|
||||
monkeypatch.setattr(minutes, "minutes_for", lambda _day: 45)
|
||||
assert fp.status(D1)["minutes"] == 0
|
||||
for k in range(1, 10): # nine heartbeats, five minutes each
|
||||
fp.record_activity("tutor", "heartbeat", ts=_at(8, 5 * k))
|
||||
st = fp.status(D1)
|
||||
assert st == {
|
||||
"project": "hr",
|
||||
"name": "HackerRank prep",
|
||||
"minutes": 45,
|
||||
"own_minutes": 45,
|
||||
"counted_minutes": 45,
|
||||
"carried_in": 0,
|
||||
"carry_out": 0,
|
||||
"daily_minutes": 120,
|
||||
"unlock_minutes": 30,
|
||||
"ends": "2026-11-05",
|
||||
@ -141,6 +150,10 @@ def test_status_inactive() -> None:
|
||||
"project",
|
||||
"name",
|
||||
"minutes",
|
||||
"own_minutes",
|
||||
"counted_minutes",
|
||||
"carried_in",
|
||||
"carry_out",
|
||||
"daily_minutes",
|
||||
"unlock_minutes",
|
||||
"ends",
|
||||
|
||||
183
focus_project/focus_project/tests/test_carry.py
Normal file
183
focus_project/focus_project/tests/test_carry.py
Normal file
@ -0,0 +1,183 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Overtime carries over: own minutes, the bank, pay and the carry ledger rows."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
import json
|
||||
from pathlib import Path # noqa: TC003
|
||||
from typing import Any
|
||||
|
||||
import earned_time
|
||||
import pytest
|
||||
|
||||
import focus_project as fp
|
||||
from focus_project import carry, harvest, ledger, minutes
|
||||
from focus_project.tests.test_minutes import D1, at, events, project
|
||||
|
||||
KEY = b"k" * 32
|
||||
D2 = D1 + timedelta(days=1)
|
||||
D3 = D2 + timedelta(days=1)
|
||||
D4 = D3 + timedelta(days=1) # the last day of project()
|
||||
D5 = D4 + timedelta(days=1) # after the end
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _key(tmp_path: Path) -> None:
|
||||
(tmp_path / "hmac.key").write_bytes(KEY)
|
||||
|
||||
|
||||
def work(day: date, mins: int) -> None:
|
||||
"""``mins`` focused minutes on ``day``: tutor heartbeats every five minutes."""
|
||||
events(
|
||||
*(
|
||||
("tutor", "heartbeat", at(8, 0, day=day) + 300 * k)
|
||||
for k in range(1, mins // 5 + 1)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def rows() -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = json.loads(ledger.ledger_path().read_text())["entries"]
|
||||
return out
|
||||
|
||||
|
||||
def test_own_minutes_are_not_capped_but_pay_is() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
assert carry.own_minutes(D1) == 125
|
||||
assert minutes.minutes_for(D1) == 120
|
||||
|
||||
|
||||
def test_overtime_banks_into_the_next_day() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
assert carry.balance(D1) == carry.Balance(own=125, carried_in=0, carry_out=5)
|
||||
assert carry.balance(D2) == carry.Balance(own=0, carried_in=5, carry_out=0)
|
||||
assert minutes.minutes_for(D2) == 5
|
||||
|
||||
|
||||
def test_carry_adds_to_own_minutes_on_the_next_day() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
work(D2, 100)
|
||||
assert minutes.minutes_for(D2) == 105
|
||||
assert carry.balance(D2).carry_out == 0
|
||||
|
||||
|
||||
def test_the_bank_is_capped_at_sixty() -> None:
|
||||
project()
|
||||
work(D1, 200)
|
||||
assert carry.balance(D1).carry_out == carry.BANK_CAP == 60
|
||||
|
||||
|
||||
def test_overtime_chains_over_days() -> None:
|
||||
project()
|
||||
work(D1, 130)
|
||||
work(D2, 125)
|
||||
assert carry.balance(D2) == carry.Balance(own=125, carried_in=10, carry_out=15)
|
||||
assert minutes.minutes_for(D3) == 15
|
||||
|
||||
|
||||
def test_the_bank_never_crosses_the_project_end() -> None:
|
||||
project()
|
||||
work(D4, 150)
|
||||
assert carry.balance(D4).carry_out == 30
|
||||
assert minutes.minutes_for(D5) == 0
|
||||
assert carry.balance(D5) == carry.Balance(0, 0, 0)
|
||||
|
||||
|
||||
def test_the_first_day_has_nothing_banked_in() -> None:
|
||||
project()
|
||||
assert carry.balance(D1 - timedelta(days=1)).carried_in == 0
|
||||
assert carry.balance(D1).carried_in == 0
|
||||
|
||||
|
||||
def test_a_past_target_is_used_for_a_past_day() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
fp.update_project("hr", today=D2, daily_minutes=100, unlock_minutes=30)
|
||||
assert carry.balance(D1).carry_out == 5 # D1 still judged at 120
|
||||
assert carry.balance(D2).carried_in == 5
|
||||
|
||||
|
||||
def test_status_reports_real_minutes_and_the_bank() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
shown = fp.status(D1)
|
||||
assert shown["minutes"] == 125
|
||||
assert shown["own_minutes"] == 125
|
||||
assert shown["counted_minutes"] == 120
|
||||
assert (shown["carried_in"], shown["carry_out"]) == (0, 5)
|
||||
nxt = fp.status(D2)
|
||||
assert (nxt["minutes"], nxt["carried_in"]) == (5, 5)
|
||||
|
||||
|
||||
def test_status_without_a_project_has_zero_bank() -> None:
|
||||
shown = fp.status(D1)
|
||||
assert (shown["own_minutes"], shown["carried_in"], shown["carry_out"]) == (0, 0, 0)
|
||||
|
||||
|
||||
def test_unreadable_registry_banks_nothing(data: Path) -> None:
|
||||
data.mkdir(parents=True)
|
||||
(data / "projects.json").write_text("{")
|
||||
assert carry.balance(D2) == carry.Balance(0, 0, 0)
|
||||
assert carry.own_minutes(D2) == 0
|
||||
|
||||
|
||||
def test_harvest_pays_own_rows_then_one_carry_row() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
work(D2, 100)
|
||||
harvest.harvest(now=at(23, 0, day=D2))
|
||||
got = {r["entry_id"]: r for r in rows()}
|
||||
assert got["hr-20261102-m120"]["detail"]["minutes"] == 120
|
||||
assert got["hr-20261103-carry"]["detail"]["minutes"] == 5
|
||||
assert got["hr-20261103-carry"]["detail"]["carry"] is True
|
||||
assert got["hr-20261103-m100"]["detail"]["minutes"] == 100
|
||||
assert all(earned_time.verified(r, KEY) for r in got.values())
|
||||
assert ledger.paid_minutes(rows(), KEY, "hr", D2) == 105
|
||||
|
||||
|
||||
def test_pay_never_exceeds_the_daily_target() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
work(D2, 130)
|
||||
harvest.harvest(now=at(23, 0, day=D2))
|
||||
assert ledger.paid_minutes(rows(), KEY, "hr", D2) == 120
|
||||
assert minutes.minutes_for(D2) == 120
|
||||
|
||||
|
||||
def test_carry_is_paid_at_the_start_of_the_day_and_not_again() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
harvest.harvest(now=at(0, 5, day=D2))
|
||||
before = rows()
|
||||
assert [r["entry_id"] for r in before if r["day"] == "2026-11-03"] == [
|
||||
"hr-20261103-carry"
|
||||
]
|
||||
harvest.harvest(now=at(0, 6, day=D2))
|
||||
assert rows() == before
|
||||
|
||||
|
||||
def test_late_data_for_yesterday_pays_only_the_carry_delta() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
harvest.harvest(now=at(9, 0, day=D2))
|
||||
work(D1, 130) # a late phone sync: five more minutes
|
||||
harvest.harvest(now=at(9, 5, day=D2))
|
||||
paid = [r for r in rows() if r["detail"].get("carry")]
|
||||
assert [r["entry_id"] for r in paid] == [
|
||||
"hr-20261103-carry",
|
||||
"hr-20261103-carry-m10",
|
||||
]
|
||||
assert ledger.paid_minutes(rows(), KEY, "hr", D2) == 10
|
||||
|
||||
|
||||
def test_own_rows_leave_room_for_the_carry() -> None:
|
||||
project()
|
||||
work(D1, 125)
|
||||
work(D2, 120)
|
||||
harvest.harvest(now=at(23, 0, day=D2))
|
||||
assert ledger.paid_minutes(rows(), KEY, "hr", D2) == 120
|
||||
assert "hr-20261103-m115" in {r["entry_id"] for r in rows()}
|
||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "focus_project"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
description = "Time-boxed focus projects: replace chosen gates, pay a daily-minutes gate"
|
||||
requires-python = ">=3.14"
|
||||
# Stdlib only on purpose: guards import it from the system python.
|
||||
|
||||
157
leetcode_coach/.pre-commit-config.yaml
Normal file
157
leetcode_coach/.pre-commit-config.yaml
Normal file
@ -0,0 +1,157 @@
|
||||
# Pre-commit Configuration for leetcode_coach
|
||||
# Install: pre-commit install && pre-commit install --hook-type pre-push
|
||||
# Run: pre-commit run --all-files
|
||||
# Update: pre-commit autoupdate
|
||||
|
||||
# NOTE: this subproject lives inside the ~/src/utils monorepo, whose git root is
|
||||
# one level up. pre-commit always runs hooks from the git root, so every path
|
||||
# below is written relative to THAT, not to this directory, and the top-level
|
||||
# `files` key keeps these hooks off the sibling subprojects. CI invokes this
|
||||
# config exactly the same way:
|
||||
# pre-commit run --config leetcode_coach/.pre-commit-config.yaml --all-files
|
||||
files: ^leetcode_coach/
|
||||
|
||||
default_language_version:
|
||||
python: python3
|
||||
default_stages: [pre-commit]
|
||||
fail_fast: false
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
args: [--markdown-linebreak-ext=md]
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-json
|
||||
- id: check-toml
|
||||
- id: check-added-large-files
|
||||
args: [--maxkb=2000]
|
||||
- id: check-merge-conflict
|
||||
- id: detect-private-key
|
||||
- id: debug-statements
|
||||
- id: name-tests-test
|
||||
args: [--pytest-test-first]
|
||||
# Shared, non-test helpers (fixtures, fakes) imported by the real test
|
||||
# modules: deliberately not collected, hence the leading underscore.
|
||||
exclude: ^leetcode_coach/leetcode_coach/tests/_[a-z][a-z_]*\.py$
|
||||
- id: check-ast
|
||||
- id: mixed-line-ending
|
||||
args: [--fix=lf]
|
||||
- id: requirements-txt-fixer
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: file-length-cap
|
||||
name: file length <= 250 lines
|
||||
entry: bash scripts/check_file_length.sh
|
||||
language: system
|
||||
pass_filenames: true
|
||||
- id: subproject-scope
|
||||
name: subproject scope regex still matches
|
||||
entry: scripts/check_subproject_scope.sh leetcode_coach
|
||||
language: script
|
||||
# always_run so the top-level `files` filter cannot skip the one hook
|
||||
# whose job is to notice that filter has stopped matching anything.
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
- id: no-noqa
|
||||
name: Block noqa comments
|
||||
entry: '(?i)#\s*(noqa|type:\s*ignore)'
|
||||
language: pygrep
|
||||
types: [python]
|
||||
- id: no-ruff-noqa
|
||||
name: Block ruff noqa file-level comments
|
||||
entry: '(?i)#\s*ruff:\s*noqa'
|
||||
language: pygrep
|
||||
types: [python]
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.17.2
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
||||
types_or: [python, pyi]
|
||||
- id: ruff-format
|
||||
types_or: [python, pyi]
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.13.0
|
||||
hooks:
|
||||
- id: mypy
|
||||
# Isolated env: the requests stubs must be declared here too.
|
||||
additional_dependencies:
|
||||
- types-requests
|
||||
args:
|
||||
- --ignore-missing-imports
|
||||
- --no-error-summary
|
||||
- --disable-error-code=no-untyped-def
|
||||
- --disable-error-code=no-untyped-call
|
||||
- --disable-error-code=var-annotated
|
||||
- --disable-error-code=no-any-unimported
|
||||
- --disable-error-code=type-arg
|
||||
- --disable-error-code=no-any-return
|
||||
- --disable-error-code=misc
|
||||
- --disable-error-code=unused-ignore
|
||||
- --disable-error-code=unreachable
|
||||
- --disable-error-code=assignment
|
||||
- --disable-error-code=no-redef
|
||||
- --disable-error-code=attr-defined
|
||||
- --disable-error-code=arg-type
|
||||
- --disable-error-code=union-attr
|
||||
- --disable-error-code=call-overload
|
||||
- --disable-error-code=return-value
|
||||
- --disable-error-code=redundant-cast
|
||||
- --disable-error-code=empty-body
|
||||
- --disable-error-code=list-item
|
||||
|
||||
- repo: https://github.com/pylint-dev/pylint
|
||||
rev: v4.0.8
|
||||
hooks:
|
||||
- id: pylint
|
||||
args:
|
||||
- --rcfile=leetcode_coach/pyproject.toml
|
||||
- --fail-under=8.0
|
||||
- --jobs=4
|
||||
- leetcode_coach/leetcode_coach
|
||||
# Whole package, never the staged subset: a score over an arbitrary
|
||||
# handful of files is an arbitrary number. Kept in step with
|
||||
# requirements.txt.
|
||||
pass_filenames: false
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
- requests
|
||||
- genanki
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
||||
|
||||
- repo: https://github.com/PyCQA/bandit
|
||||
rev: 1.9.4
|
||||
hooks:
|
||||
- id: bandit
|
||||
args:
|
||||
- -c
|
||||
- leetcode_coach/pyproject.toml
|
||||
- --severity-level=high
|
||||
- --confidence-level=medium
|
||||
- --skip=B113
|
||||
additional_dependencies: ["bandit[toml]"]
|
||||
exclude: ^(leetcode_coach/leetcode_coach/tests/|.*test.*\.py$)
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: pytest-coverage
|
||||
name: pytest with coverage enforcement
|
||||
entry: scripts/run_subproject_tests.sh leetcode_coach
|
||||
language: script
|
||||
types: [python]
|
||||
pass_filenames: false
|
||||
require_serial: true
|
||||
stages: [pre-push]
|
||||
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: codespell
|
||||
args:
|
||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||
132
leetcode_coach/README.md
Normal file
132
leetcode_coach/README.md
Normal file
@ -0,0 +1,132 @@
|
||||
# leetcode_coach
|
||||
|
||||
The `/leetcode` coach as a library: the Socratic method gates, the session log,
|
||||
the grader and card builder, and the relay that serves them. Moved here from
|
||||
`leetcode-guard` (with its git history) so the tutor server and leetcode-guard
|
||||
share ONE coach. Python 3.14, `import leetcode_coach`.
|
||||
|
||||
Specs stay in `~/src/leetcode-guard/DOCS-coach-{spec,ui-spec,relay}.md`.
|
||||
|
||||
## Install
|
||||
|
||||
| Who | How |
|
||||
|---|---|
|
||||
| leetcode-guard | pinned: `leetcode-coach @ git+https://github.com/kuhyx/utils@leetcode-coach-v0.1.0#subdirectory=leetcode_coach` (its `install.sh` pip-installs it) |
|
||||
| tutor server / development | `./install.sh` (editable, system python) |
|
||||
|
||||
Tests: `scripts/run_subproject_tests.sh leetcode_coach` (100% branch coverage).
|
||||
Gate: `pre-commit run --config leetcode_coach/.pre-commit-config.yaml --all-files`.
|
||||
|
||||
## Layers
|
||||
|
||||
Stdlib only unless noted. Import only what you need.
|
||||
|
||||
| Layer | Modules |
|
||||
|---|---|
|
||||
| Gates | `phase`, `shape`, `gate_notes`, `req_check`, `leak`, `toolbox`, `stop_gate`, `gate_detector` |
|
||||
| Log + progress | `session_log`, `progress`, `report` |
|
||||
| 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) |
|
||||
| Relay | `relay.*`: state machine, grading, run-code, HTTP + RTDB (needs requests, crdt-sync) |
|
||||
| Clients | `leetcode_repl` (`leetcode` command), `cluster_cli`, `local_session`, `how_to` |
|
||||
|
||||
## Library API for the tutor server
|
||||
|
||||
Everything keys off the session log: a JSONL file per problem and day, state is
|
||||
derived from it (never held in memory), so any caller and a restart agree.
|
||||
|
||||
```python
|
||||
from leetcode_coach import fetch_problem, phase, session_log, toolbox, leak
|
||||
```
|
||||
|
||||
**Statement.** `fetch_problem.fetch(slug) -> dict | None` (None / `isPaidOnly`
|
||||
means paste it), `fetch_problem.render(q, lang) -> str` (markdown with
|
||||
`Tags:` and `Languages available:` lines), `slug_from(url_or_slug)`.
|
||||
|
||||
**Phase gate (req-before-code).**
|
||||
`gate = phase.PhaseGate(log, toolbox.load_safe(), source=lambda: statement, ask=None)`
|
||||
|
||||
- `gate.screen(block, *, is_code=None) -> (sent | None, note)`: `None` means
|
||||
refuse and show `note`; otherwise forward `sent` to the coach and show `note`
|
||||
if non-empty. Logs `req`, `req_check`, `code`, `reveal`.
|
||||
- `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`).
|
||||
- `phase.req_state(events) -> ReqState(accepted, forced, tries, .open)`,
|
||||
`phase.step2_attempts(events)`, `phase.regex_verdict(block) -> bool | None`.
|
||||
- 3 incomplete lists force the gate open (`req_incomplete: true` on `code`).
|
||||
|
||||
**Q5, SQL problems.** If the statement has the `Database` tag or offers a SQL
|
||||
dialect (`shape.is_sql`), `req:` is skipped: the gate asks for an OUTPUT SHAPE,
|
||||
a message starting `shape:` that says the **columns**, the **rows** (what one
|
||||
row stands for) and the **grouping**. Judged mechanically
|
||||
(`shape.check -> req_check.Check(verdict, missing, "shape")`, no model, never
|
||||
fails open), logged as the same `req` / `req_check` events with
|
||||
`via: "shape"`, forced after 3 tries like `req:`. A `req:` message on a SQL
|
||||
problem counts as the shape. An unfetched statement (just a slug) is not SQL:
|
||||
the stricter `req:` gate applies. Algorithm problems are unchanged.
|
||||
The relay state's `session.kind` is `"sql"` or `"algorithm"`.
|
||||
|
||||
**Leaks and code.** `leak.leaked_names(reply, allowed, box)` (toolbox names
|
||||
too early), `stop_gate.verdict(raw, reply)`, `gate_detector.offending_snippets`.
|
||||
|
||||
**Log.** `session_log.log_path(problem)`, `append(path, event, **fields)`,
|
||||
`read(path)`, `current(events)`, `has_code(path)`. Events: `session_start`,
|
||||
`req`, `req_check`, `code`, `rung`, `reveal`, `grade`, `chat`. The field set is
|
||||
a FIXED contract read by `leetcode_guard._coach_log`: add a field only together
|
||||
with that reader.
|
||||
|
||||
**Progress.** `progress.history(slug)`, `due_retests()` (cold re-tests at +3
|
||||
and +10 days), `cluster_progress()`, `next_new(...)`, `cluster_of(slug)`.
|
||||
|
||||
**Toolbox + cards.** `toolbox.load_safe() -> Toolbox` (`.entries`,
|
||||
`.properties`), `toolbox_cards.cards_for(names) -> [Card]` (property list ->
|
||||
operation), `toolbox_cards.append_entry(...)` (new entry, after kuhy confirms),
|
||||
`make_cards.deliver(...)` (Anki deck "LeetCode", `.apkg` fallback).
|
||||
|
||||
**Relay (the five-step coach).** `relay.coach.Coach(Deps(...))`:
|
||||
`handle(Request) -> dict` for the seven kinds in `relay.protocol.KINDS`
|
||||
(`session_start`, `session_end`, `chat`, `grade_step`, `hint`, `reveal`,
|
||||
`run_code`), `state()`, `chat_after(id)`, `tick()` (Accepted probe).
|
||||
`relay.app.Relay(Deps())` adds loopback HTTP (`start()`, `port`) and the RTDB
|
||||
phone link (`connect_phone(make_rtdb)`). Every dependency is a `Deps` field:
|
||||
`ask`, `local_chat`, `fetch`, `probe`, `run_code`, `answers`, `box`,
|
||||
`state_dir`, `cards_dry_run`, `clock_ms`. The wire is `DOCS-coach-relay.md`.
|
||||
|
||||
## What it needs from leetcode-guard
|
||||
|
||||
Three read-only calls, resolved on demand in `guard_bridge` (a consumer
|
||||
without leetcode-guard imports everything else; these raise
|
||||
`GuardUnavailableError`, never a silent "nothing solved"):
|
||||
|
||||
| Call | Used by |
|
||||
|---|---|
|
||||
| `solved_slugs(slugs)` | `cluster_cli` (skip already-Accepted problems) |
|
||||
| `recent_accepted()` | relay step 4 probe (`AcceptedProbe`, at most 1/min) |
|
||||
| `phone_id_token(app, timeout_seconds=)` | `relay.__main__` RTDB sign-in |
|
||||
|
||||
No coach module imports `leetcode_guard` statically and no route can reach the
|
||||
gate's ledger, credits or unlocks (`tests/test_guard_boundary.py` reads the
|
||||
bridge's strings against an allow-list). Credit stays leetcode-guard's job.
|
||||
|
||||
## Environment
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `LEETCODE_COACH_SESSIONS_DIR` | session logs (default `~/.local/share/leetcode-coach/sessions`) |
|
||||
| `LEETCODE_COACH_LOG` | log the REPL exported for the Stop hook |
|
||||
| `LEETCODE_COACH_CLUSTER` | cluster tag for new logs |
|
||||
| `LEETCODE_CLAUDE_BIN` | the `claude` binary (tests: a fake) |
|
||||
| `LEETCODE_COACH_RELAY_DIR` / `_PORT` / `_RTDB_URL` | relay state dir, port (default 8777), RTDB override |
|
||||
| `LEETCODE_COACH_CARDS_DRY_RUN` | `1`: build cards, push nothing |
|
||||
|
||||
## Commands (the live units use these paths)
|
||||
|
||||
- `python3 -m leetcode_coach.relay`: the relay (leetcode-coach-relay.service)
|
||||
- `python3 -P -m leetcode_coach.leetcode_repl <url>` (the `leetcode` command)
|
||||
- `python3 -m leetcode_coach.stop_gate`: the Stop hook (shim in `hook_shims/`)
|
||||
- `python3 -m leetcode_coach.toolbox_cards --help`, `make_cards`, `report`,
|
||||
`cluster_cli`, `fetch_problem`: the skill's scripts
|
||||
- The skill body is `leetcode_coach/SKILL.md`; the skill dir
|
||||
`~/.claude/skills/leetcode` points at `leetcode_coach/leetcode_coach/`.
|
||||
14
leetcode_coach/install.sh
Executable file
14
leetcode_coach/install.sh
Executable file
@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
# Editable user install so /usr/bin/python3 (the tutor server, the CLI, the
|
||||
# Stop hook) can `import leetcode_coach` straight from this checkout.
|
||||
# leetcode-guard installs the TAGGED copy instead (its pyproject pin); run
|
||||
# this only to develop the coach against live callers. Idempotent.
|
||||
set -euo pipefail
|
||||
|
||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly REPO_DIR
|
||||
readonly SYSTEM_PYTHON="/usr/bin/python3"
|
||||
|
||||
"$SYSTEM_PYTHON" -m pip install --user --no-deps --break-system-packages -e "$REPO_DIR"
|
||||
cd /
|
||||
"$SYSTEM_PYTHON" -P -c 'import leetcode_coach; print(leetcode_coach.__file__)'
|
||||
46
leetcode_coach/leetcode_coach/DOCS-clients.md
Normal file
46
leetcode_coach/leetcode_coach/DOCS-clients.md
Normal file
@ -0,0 +1,46 @@
|
||||
# The coach's clients, gates and session log
|
||||
|
||||
Moved out of `SKILL.md` (250-line cap); none of it is coaching instruction.
|
||||
|
||||
The right client is `leetcode <url>` (this package's `leetcode` launcher,
|
||||
symlinked from `~/.local/bin`): a print-mode loop on sonnet that also runs
|
||||
the req-before-code gate and the session log (`leetcode report`). The Stop
|
||||
hook (`stop_gate.py`) sends back a reply with a pasteable line or an early
|
||||
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,
|
||||
minus section 1. `python3 -m leetcode_coach.eval_local`: acceptance run.
|
||||
|
||||
## The req-before-code gate (DOCS-coach-spec.md decisions 4-8)
|
||||
|
||||
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,
|
||||
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.
|
||||
- A block that is code (regex first, the model only when the regex cannot
|
||||
tell, "not code" when nobody answers) is held back until a list passed, or
|
||||
was unverifiable, or came back incomplete three times (then the `code`
|
||||
event carries `req_incomplete: true`).
|
||||
- Until the first `code` event, a reply naming a toolbox entry or alias is
|
||||
bounced (`leak.py`: the Stop hook on the Claude path, `local_coach` on the
|
||||
local one), except names kuhy already typed (not the statement: its tags
|
||||
and hints name the answer).
|
||||
- Each reply's `<!-- rung:Hn -->` marker is logged and stripped.
|
||||
|
||||
Every step lands in `~/.local/share/leetcode-coach/sessions/<date>-<slug>.jsonl`
|
||||
(`session_log.py`; `leetcode_guard._coach_log` reads the same contract). The
|
||||
REPL exports the file as `LEETCODE_COACH_LOG`, which is how the Stop hook and
|
||||
the card builder (`postmortem`) find it. `leetcode report` prints, per file,
|
||||
req-before-code, highest rung, reveal and every req_check verdict.
|
||||
|
||||
Known gap: `~/.claude/hooks/status_tag_stop.py` wants the last line of a TUI
|
||||
coaching reply to end in `?`; the rung line now comes after it. Print mode
|
||||
(the REPL) is exempt from that hook.
|
||||
20
leetcode_coach/leetcode_coach/DOCS-how-to.md
Normal file
20
leetcode_coach/leetcode_coach/DOCS-how-to.md
Normal file
@ -0,0 +1,20 @@
|
||||
# The commands and the method, as the status app's Coach tab shows them
|
||||
|
||||
Quoted verbatim from `how_to.py`; `tests/test_how_to.py` fails if they differ.
|
||||
SKILL.md section 3 is the full method; this is its one-line-per-step form.
|
||||
|
||||
Commands:
|
||||
|
||||
- `leetcode --cluster <name>` - Serve the next problem of a concept cluster (a due re-test comes first).
|
||||
- `leetcode <url>` - Coach one problem, from its LeetCode URL or slug.
|
||||
- `leetcode due` - List the cold re-tests that are due.
|
||||
- `leetcode report` - One row per session: requirements before code, hint rung, reveal.
|
||||
|
||||
The command skips problems LeetCode already shows as Accepted, so it may serve a later one than listed here.
|
||||
|
||||
The method:
|
||||
|
||||
1. **Constraint** - Turn the hard constraint into a rule for the design.
|
||||
2. **Requirements** - List what the operation must do, as properties, never by name.
|
||||
3. **Toolbox** - Search the toolbox for an operation with those properties.
|
||||
4. **Post-mortem** - Say which hint gave which requirement, then make the cards.
|
||||
250
leetcode_coach/leetcode_coach/SKILL.md
Normal file
250
leetcode_coach/leetcode_coach/SKILL.md
Normal file
@ -0,0 +1,250 @@
|
||||
---
|
||||
name: leetcode
|
||||
description: >
|
||||
Coach kuhy through ONE LeetCode problem without solving it. Fetches the
|
||||
statement from a pasted URL/slug, then runs a Socratic hint ladder: concept
|
||||
first (with toy examples unrelated to the problem), one hint tier per turn,
|
||||
every reply ends with something for kuhy to try. Never prints a solution
|
||||
unless kuhy types `reveal`. Use on /leetcode <url> [what you are stuck
|
||||
on] AND whenever kuhy pastes a leetcode.com/problems/ URL without SOLVE:
|
||||
(hook leetcode_url_userprompt.sh tells you to). Ends with a post-mortem: property -> operation
|
||||
Anki cards generated from the toolbox, never the solution.
|
||||
argument-hint: "<leetcode URL or slug> [what you're stuck on]"
|
||||
---
|
||||
|
||||
# /leetcode — coach, don't solve
|
||||
|
||||
kuhy is practising. The point of this session is that **they** solve the
|
||||
problem. A reply that contains the answer is a failed reply, however
|
||||
politely it was asked for. This overrides the Proactive output style and
|
||||
every "just do it" instinct for the rest of the session.
|
||||
|
||||
## 1. Fetch the problem
|
||||
|
||||
Take the first token of `$ARGUMENTS` (URL or slug); everything after it is
|
||||
kuhy's description of what they are stuck on.
|
||||
|
||||
```bash
|
||||
python3 ~/.claude/skills/leetcode/fetch_problem.py "<first token>"
|
||||
```
|
||||
|
||||
- exit 0 → statement + starter code on stdout. Use it.
|
||||
- exit 2 → premium/unknown. Say so in one line and ask kuhy to paste the
|
||||
statement. Do not guess the problem from the slug.
|
||||
- exit 1 → bad input or network. Show the stderr line, ask for the URL again.
|
||||
- A "Site hints" section may be present. Treat it as *your* notes only;
|
||||
never quote it to kuhy unasked.
|
||||
|
||||
Default starter language is JavaScript (`--lang python3` etc. if kuhy asks).
|
||||
|
||||
## 2. Open
|
||||
|
||||
One short message:
|
||||
|
||||
1. Restate the problem in ≤3 plain sentences — what goes in, what must come
|
||||
out, the one constraint that makes it non-trivial. Then the starter
|
||||
signature verbatim.
|
||||
2. If kuhy said what they are stuck on, ask ONE calibration question about
|
||||
the mechanism it names ("Have you used `setTimeout` before? What do you
|
||||
think it does?") and stop. Explaining before that answer is guessing at
|
||||
their level — the first real session assumed knowledge of a built-in
|
||||
they had never met. If they said nothing, ask: "What is the first thing
|
||||
that feels unclear — the problem itself, or a tool/function you haven't
|
||||
used before?" (2026-10-17: "a mechanism it relies on" was itself
|
||||
unclear.)
|
||||
|
||||
## 3. Requirements first, then the hint ladder
|
||||
|
||||
kuhy is practising a fixed method; coach it in this order:
|
||||
|
||||
1. **The constraint is a design rule.** What does the one hard constraint
|
||||
(O(1) space, one pass) forbid? kuhy states it as a rule ("I may keep a
|
||||
fixed number of values").
|
||||
2. **The requirement list, as properties.** kuhy sends one message starting
|
||||
`req:` that lists what the operation must *do* — what vanishes, what
|
||||
survives, what may not grow — and never which operation or structure
|
||||
(XOR, hash map, sort are names, not properties). The client checks the
|
||||
list and shows kuhy the missing properties; coach toward them with H1
|
||||
questions, never by stating them. Code sent before an accepted list is
|
||||
held back by the client and never reaches you. **SQL problems** (tag
|
||||
Database) skip `req:`: kuhy sends `shape:` naming the columns, the rows
|
||||
and the grouping of the result; the client checks that mechanically.
|
||||
3. Only then does kuhy search for an operation with those properties.
|
||||
|
||||
**Never name a toolbox operation or structure before kuhy's first code** —
|
||||
not as a hint, not in a toy, not in a question (the Stop hook bounces it).
|
||||
A name kuhy typed first is fair: "is it XOR?" gets an honest answer.
|
||||
|
||||
End every hint reply with its rung on a line of its own, `<!-- rung:H0 -->`
|
||||
… `<!-- rung:H3 -->` (no climb: repeat the current one); the client logs and
|
||||
hides it.
|
||||
|
||||
| Rung | What it is | What it must NOT be |
|
||||
|---|---|---|
|
||||
| **H0 concept** | Explain the underlying *mechanism* in isolation with a 3–6 line toy snippet that has nothing to do with the problem's specifics. Ask kuhy to predict its output before you show it. | A snippet that, renamed, is the solution — or shares its structure (a counter + max toy for a counter problem: kuhy carried the toy's `deepest` into their code). Never name the key API (UNION, melt, spread) before kuhy asks. |
|
||||
| **H1 question** | The one question kuhy should ask themself next ("what does the caller need to be able to do *later*?"). Requirements are kuhy's to derive: "constant space: what can you keep?" | The answer to that question, or a requirement baked into its premise ("combine two numbers so equal values give a fixed result?" handed over both steps kuhy then could not redo alone). |
|
||||
| **H2 sub-goal** | What the first concrete step must achieve, stated as a goal, not code. | The line that achieves it. |
|
||||
| **H3 shape** | Before kuhy's first code: the *property* the missing construct has. After it: the construct/API, one at a time, without composing them. | Two constructs already wired together. |
|
||||
|
||||
Rules:
|
||||
|
||||
- Climb only when kuhy says "hint" / "next" / "still stuck", or has made an
|
||||
attempt and it failed. Never skip a rung, never give two in one reply.
|
||||
- **Progress on success, too.** Two correct answers in a row, or kuhy
|
||||
stating the mechanism in their own words, means the step is done: say in
|
||||
one sentence what they showed, then ask for the next bigger step —
|
||||
usually the whole function. Hand-tracing indexes or levels: at most twice
|
||||
a session; it checks a rule, it does not find one (2026-10-17: kuhy named
|
||||
the 0→1 / 1→0 rule at turn 13 and got 18 more trace questions).
|
||||
- **Logic there, syntax missing.** If kuhy's pseudocode already has the
|
||||
right logic and only the language construct is missing, skip H0–H2: name
|
||||
the construct's *category* and show it in a toy on unrelated data
|
||||
(2026-10-11: one CASE toy on an unrelated table beat ten turns on UPDATE).
|
||||
An H0 reply is the toy and its prediction question — no "now apply this
|
||||
to the problem" paragraph underneath (that is H1, next turn).
|
||||
- Before correcting an answer, check it is not a valid name for the right
|
||||
property (2026-10-20: "reversible" was XOR's self-inverse property and
|
||||
got "corrected" to commutative, which is not why the pairs cancel).
|
||||
- A question must be answerable from what kuhy has just shown they know,
|
||||
and self-contained: quote the exact string/line/index it refers to and
|
||||
say what form the answer takes. No jargon you have not defined.
|
||||
- "No idea — if I knew that I'd have solved it" means the rung was too big:
|
||||
drop back one rung, ask something smaller. "I don't understand the
|
||||
question" means the *wording* failed: rephrase once with a concrete
|
||||
example, same step. Never repeat the same question rephrased twice.
|
||||
- **Turn budget.** Easy ≈ 16 kuhy turns, Medium ≈ 24, Hard ≈ 32. Past it,
|
||||
sum up in ≤2 lines what kuhy has established and ask for a full attempt.
|
||||
- **Frustration = stop the ladder.** "going in circles", "jesus", "stop",
|
||||
"this is too complicated", or two "I don't understand": no further
|
||||
question on this track. Own it in one clause, sum up what kuhy has in ≤2
|
||||
lines, offer three choices — write the whole function now (you run it),
|
||||
one bigger hint, or `reveal`.
|
||||
- When kuhy has a *conceptual* confusion (e.g. "how can this even work?"),
|
||||
stay on H0 until they can explain the mechanism back in their own words.
|
||||
Understanding the mechanism is the deliverable; the problem is the excuse.
|
||||
- Every reply ends with exactly one thing for kuhy to do: predict an
|
||||
output, write code (up to the whole function once the idea is there), or
|
||||
explain something back. Then stop and wait (the rung line goes after it).
|
||||
- Plain prose only: no `❓ Q1 / ➡️` grilling format (it answered kuhy's
|
||||
question for them), no status-tag line (`QUESTION:`, …; overrides
|
||||
CLAUDE.md) — the final question is the ask; tags only for cards/`DONE:`.
|
||||
- Keep replies short. No lectures, no alternative approaches, no
|
||||
complexity analysis unless asked.
|
||||
|
||||
## 4. When kuhy pastes code
|
||||
|
||||
- It arrives after the req list (the client holds earlier code back). First
|
||||
check it against kuhy's own list: which listed property does it break?
|
||||
- Point at the single most important thing that is wrong or missing, as a
|
||||
question or an observation. One thing — not "also, …". Do not rewrite
|
||||
it, do not "fix it up".
|
||||
- Never write a line for their code, not even a one-token fix. Describe
|
||||
the *data* instead: "`fn` receives `[2]` here; it should receive `2`."
|
||||
Only after three failed attempts at the same line may you name the
|
||||
operator — still without writing the line. "There's the spread operator
|
||||
`...` — `fn(...args)`" after one "no idea" is the failure (kuhy called it
|
||||
spoon-feeding); "JS has an operator that unpacks an array into separate
|
||||
arguments. Its name is *spread*. Look it up and try it." is the pass.
|
||||
Before sending, scan the reply: a pasteable code block gets deleted.
|
||||
- Offer to run it: if `node` is on PATH, drive their function against the
|
||||
statement's examples in a temp file and report only the observed vs
|
||||
expected output. Running their code is fine; writing it is not.
|
||||
- If it passes, say so, then still point at one piece of dead code if
|
||||
there is any (an expression statement that does nothing, a flag nothing
|
||||
reads). Accepted is not the same as understood.
|
||||
- No emoji, no "Done." — the exit below decides when it is done.
|
||||
|
||||
## 5. Exit
|
||||
|
||||
The session is done when kuhy says solved/done **and** explains the
|
||||
solution back in ≤2 sentences that mention the key mechanism. If the
|
||||
explanation is wrong, that is one more H0 turn, not a failure.
|
||||
|
||||
Then close the loop on the *original* confusion: quote the belief they
|
||||
opened with ("cancel stops the function at a random place") and ask what
|
||||
is wrong with it now. A passing submission does not retire a misconception;
|
||||
only a corrected sentence from them does.
|
||||
|
||||
## 5b. Post-mortem: requirement list, then property cards
|
||||
|
||||
After the loop is closed, in the same reply:
|
||||
|
||||
1. Ask kuhy for the requirement list as *properties* (what must vanish, what
|
||||
must survive, how much space), not code or an operation name; then, for
|
||||
every hint rung kuhy saw, which requirement that hint handed over.
|
||||
2. Cards are **property -> operation only** (DOCS-coach-spec.md decision 11): one
|
||||
per toolbox entry the solution relied on, generated from `toolbox.json`
|
||||
(front = its properties, back = its name), in ONE Bash call:
|
||||
```bash
|
||||
python3 -m leetcode_coach.toolbox_cards cards "<entry>" ["<entry>" ...] \
|
||||
| ~/.claude/skills/leetcode/make_cards.py -
|
||||
```
|
||||
Names or aliases, 1-6 per call. They all share the slug `toolbox`, so
|
||||
never `--replace` here: it would delete every other entry's card.
|
||||
3. An operation kuhy named that is **not** in the toolbox: propose its
|
||||
properties from the `toolbox.json` vocabulary and ask kuhy to confirm or
|
||||
correct them. Only after kuhy confirms, append it (`append_entry`) --
|
||||
never on your own judgement, never with unconfirmed properties:
|
||||
```bash
|
||||
python3 -m leetcode_coach.toolbox_cards add "<name>" --alias "<alias>" \
|
||||
--property "<prop>" --property "<prop>"
|
||||
```
|
||||
Refused because the set nests with another entry's? Ask kuhy which
|
||||
property tells the two apart. Then build its card as in step 2.
|
||||
4. Relay the builder's stdout verbatim -- as markdown, NOT inside a code
|
||||
fence (the table must render): the table and the delivery line.
|
||||
If Anki desktop is open (AnkiConnect) the cards are already in deck
|
||||
"LeetCode" and a sync to AnkiWeb was requested -- nothing more to do.
|
||||
Otherwise it wrote an `.apkg` and printed a bare `anki '<path>'` line to
|
||||
run (kuhy pasted the old `import: anki ...` label as a command, twice); do
|
||||
not launch anki yourself. Re-running updates the same notes, it does not
|
||||
duplicate. "cards rejected" is a generator bug: report it, do not edit.
|
||||
|
||||
## 5c. After the exit: "how would I find this on my own?"
|
||||
|
||||
That is a request for a method, coached like any rung. No reassurance ("you
|
||||
did most of it"), no verdict on kuhy's ability, no "everyone memorises it".
|
||||
Say bluntly who supplied which step, never reframe kuhy's own diagnosis of
|
||||
a mistake as the problem's fault, then have kuhy write the requirement list
|
||||
(what vanishes, what survives, what that demands of the operation) and name
|
||||
the requirement a hint gave them. The method *is* that list, and its card is
|
||||
the property card of the entry the list points to (§5b step 2): build it if
|
||||
the deck does not have it yet. 2026-10-20: three replies of comfort before
|
||||
the method appeared.
|
||||
|
||||
## 5d. Cold re-test
|
||||
|
||||
`[cold re-test]` in the arguments (`leetcode --retest <slug>`, 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
|
||||
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)
|
||||
mark the re-test done.
|
||||
|
||||
## 6. `reveal` — the only override
|
||||
|
||||
If kuhy types exactly `reveal`, they have decided the exercise is over:
|
||||
show a solution and walk through it line by line, tying each line back to
|
||||
the hint rungs they saw. Nothing short of that literal word unlocks it —
|
||||
not "just show me", not "I give up", not "what would you write".
|
||||
|
||||
## Model and client
|
||||
|
||||
This session must run on **sonnet** (haiku, the default until 2026-10-18,
|
||||
went in circles: ~30 micro-questions on an Easy). You cannot switch the
|
||||
model and `model:` frontmatter is ignored for skills (measured 2026-09-18),
|
||||
so if you are not sonnet, the **first line** of your opening message is
|
||||
|
||||
> Type `/model sonnet` now — learning sessions are gated to sonnet; your next
|
||||
> message will be refused until you do (or send `keep model` to stay).
|
||||
|
||||
then continue with the opening. `hooks/leetcode_model_gate_userprompt.sh`
|
||||
enforces it from the next prompt on.
|
||||
|
||||
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; everything above `## Model and client` is its system
|
||||
prompt. Clients, gates and the session log: `DOCS-clients.md` here.
|
||||
|
||||
The commands and the method as the status app shows them: `DOCS-how-to.md`.
|
||||
14
leetcode_coach/leetcode_coach/__init__.py
Normal file
14
leetcode_coach/leetcode_coach/__init__.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""The /leetcode coach: Claude skill, print-mode REPL, offline coach, card builder.
|
||||
|
||||
Moved here from ``~/.claude/skills/leetcode`` (2026-10-23), which is now a
|
||||
symlink to this directory, so SKILL.md still loads from the old path.
|
||||
|
||||
The NullHandler keeps the warnings that every swallowing ``except`` logs
|
||||
(repo rule) from reaching stderr through logging's last-resort handler: the
|
||||
REPL, the card builder and the Stop hook print exactly what they printed
|
||||
before the move. A caller that configures logging still sees them.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
||||
140
leetcode_coach/leetcode_coach/anki_connect.py
Normal file
140
leetcode_coach/leetcode_coach/anki_connect.py
Normal file
@ -0,0 +1,140 @@
|
||||
"""Push cards straight into the running Anki desktop via AnkiConnect.
|
||||
|
||||
Stdlib only. Anki must be open with the AnkiConnect add-on (2055492159);
|
||||
`available()` is the probe, everything else assumes it. Notes are matched by
|
||||
(deck, Problem, Front) so a re-run edits instead of duplicating, mirroring the
|
||||
stable-guid behaviour of the .apkg path; `replace` also deletes dropped notes.
|
||||
`sync()` pushes to AnkiWeb, which is what gets the cards onto AnkiDroid at its
|
||||
next open.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
URL = "http://127.0.0.1:8765"
|
||||
|
||||
|
||||
class AnkiConnectError(RuntimeError):
|
||||
"""AnkiConnect answered with an error field."""
|
||||
|
||||
def __init__(self, action: str, error: object) -> None:
|
||||
"""Name the action and the error AnkiConnect returned."""
|
||||
super().__init__(f"{action}: {error}")
|
||||
|
||||
|
||||
def _call(action: str, **params: object) -> Any:
|
||||
"""One AnkiConnect request; its `result`, or AnkiConnectError."""
|
||||
body = json.dumps({"action": action, "version": 6, "params": params}).encode()
|
||||
req = urllib.request.Request(
|
||||
URL, data=body, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=30) as resp: # fixed localhost URL
|
||||
payload = json.load(resp)
|
||||
if payload.get("error"):
|
||||
raise AnkiConnectError(action, payload["error"])
|
||||
return payload.get("result")
|
||||
|
||||
|
||||
def available() -> bool:
|
||||
"""Whether Anki desktop is open with AnkiConnect answering."""
|
||||
try:
|
||||
return _call("version") is not None
|
||||
except (
|
||||
urllib.error.URLError,
|
||||
TimeoutError,
|
||||
ConnectionError,
|
||||
AnkiConnectError,
|
||||
) as exc:
|
||||
_LOG.warning("AnkiConnect is not available: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_model(name: str, fields: list[str], qfmt: str, afmt: str, css: str) -> None:
|
||||
"""Create the note type unless the collection already has it."""
|
||||
if name in _call("modelNames"):
|
||||
return
|
||||
_call(
|
||||
"createModel",
|
||||
modelName=name,
|
||||
inOrderFields=fields,
|
||||
css=css,
|
||||
cardTemplates=[{"Name": "Card 1", "Front": qfmt, "Back": afmt}],
|
||||
)
|
||||
|
||||
|
||||
def _term(field: str, value: str) -> str:
|
||||
"""Quote the WHOLE `field:value` term; quotes after the colon match nothing."""
|
||||
return '"' + field + ":" + value.replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
def _existing_by_front(deck: str, slug: str) -> dict[str, int]:
|
||||
r"""Map unescaped Front -> note id for every note of this problem.
|
||||
|
||||
Diffing in Python, not via a Front search: Anki search treats `_ * \`
|
||||
specially and fields are stored HTML-escaped, so a search misses notes.
|
||||
"""
|
||||
ids = _call("findNotes", query=f"{_term('deck', deck)} {_term('Problem', slug)}")
|
||||
infos = _call("notesInfo", notes=ids) if ids else []
|
||||
return {html.unescape(n["fields"]["Front"]["value"]): n["noteId"] for n in infos}
|
||||
|
||||
|
||||
def _add(deck: str, model: str, slug: str, front: str, back: str) -> None:
|
||||
"""Add one note and make sure it sits in `deck`."""
|
||||
note_id = _call(
|
||||
"addNote",
|
||||
note={
|
||||
"deckName": deck,
|
||||
"modelName": model,
|
||||
"fields": {"Front": front, "Back": back, "Problem": slug},
|
||||
"tags": ["leetcode", slug],
|
||||
"options": {"allowDuplicate": False, "duplicateScope": "deck"},
|
||||
},
|
||||
)
|
||||
# With Anki's "add to current deck" preference on, addNote lands in the
|
||||
# current deck regardless of deckName (seen on 25.09.2). Move explicitly.
|
||||
_call("changeDeck", cards=_call("findCards", query=f"nid:{note_id}"), deck=deck)
|
||||
|
||||
|
||||
def sync_notes(
|
||||
deck: str, model: str, slug: str, cards: list[dict[str, str]], *, replace: bool
|
||||
) -> tuple[int, int, int]:
|
||||
"""Add or update one note per card (fields already HTML-escaped).
|
||||
|
||||
With `replace`, notes of this problem whose Front is not in `cards` are
|
||||
deleted, so a rewritten deck does not keep the cards it dropped.
|
||||
Returns (added, updated, deleted).
|
||||
"""
|
||||
_call("createDeck", deck=deck)
|
||||
existing = _existing_by_front(deck, slug)
|
||||
added = updated = 0
|
||||
keep: set[int] = set()
|
||||
for c in cards:
|
||||
front, back = c["front"], c["back"]
|
||||
note_id = existing.get(html.unescape(front))
|
||||
if note_id is not None:
|
||||
_call(
|
||||
"updateNoteFields",
|
||||
note={"id": note_id, "fields": {"Front": front, "Back": back}},
|
||||
)
|
||||
keep.add(note_id)
|
||||
updated += 1
|
||||
continue
|
||||
_add(deck, model, slug, front, back)
|
||||
added += 1
|
||||
stale = [i for i in existing.values() if i not in keep] if replace else []
|
||||
if stale:
|
||||
_call("deleteNotes", notes=stale)
|
||||
return added, updated, len(stale)
|
||||
|
||||
|
||||
def sync() -> None:
|
||||
"""Ask Anki to sync with AnkiWeb."""
|
||||
_call("sync")
|
||||
268
leetcode_coach/leetcode_coach/answer_key.json
Normal file
268
leetcode_coach/leetcode_coach/answer_key.json
Normal file
@ -0,0 +1,268 @@
|
||||
{
|
||||
"problems": {
|
||||
"missing-number": {
|
||||
"design_rule": "Constant extra space in one linear pass rules out remembering which values were seen, so the answer must come from folding every value into one accumulator in a way that makes each present value cancel against the full 0..n range.",
|
||||
"entries": ["XOR"],
|
||||
"also_accepted": ["sum / difference"],
|
||||
"key_requirements": ["invertible", "commutative", "associative"],
|
||||
"postmortem_points": [
|
||||
"Named the property that does the work: every present value can be undone against the full range, in any order, leaving only the absent one.",
|
||||
"Counted the range as n + 1 members against n values, which is why the leftover is exactly the missing one.",
|
||||
"Noted that more than one operation has the undo property, and the choice between them is about overflow and clarity, not correctness."
|
||||
]
|
||||
},
|
||||
"single-number-iii": {
|
||||
"design_rule": "Two values appear once and the rest twice, with constant extra space, so pairs must cancel in a single fold and the two survivors must then be separated by one position where they differ.",
|
||||
"entries": ["XOR", "lowest set bit"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["self-inverse", "commutative", "isolates one bit"],
|
||||
"postmortem_points": [
|
||||
"Named that applying a value twice undoes it, so the full fold leaves the combination of the two unique values.",
|
||||
"Recognised that the leftover is nonzero because the two values differ, so at least one bit position tells them apart.",
|
||||
"Split the input into two groups by that one bit and folded each group, so each pair stays together and each survivor lands alone."
|
||||
]
|
||||
},
|
||||
"majority-element": {
|
||||
"design_rule": "A value occurs more than n/2 times and the follow-up asks for linear time with constant space, so you cannot tally every value; a single running candidate that pairs off against different values must be enough.",
|
||||
"entries": ["Boyer-Moore majority vote"],
|
||||
"also_accepted": ["hash map", "sorting"],
|
||||
"key_requirements": ["needs a majority", "single pass", "O(1) extra space"],
|
||||
"postmortem_points": [
|
||||
"Named the guarantee the method rests on: the result is only right because one value really occurs more than half the time.",
|
||||
"Explained why pairing each occurrence against a different value cannot eliminate the majority value.",
|
||||
"Stated the cost trade-off of the tally and the ordering approaches against the constant-space one."
|
||||
]
|
||||
},
|
||||
"single-number-ii": {
|
||||
"design_rule": "Every value appears three times except one, with constant extra space, so pairwise cancellation leaves the triples behind and the only workable state is a tiny counter for each bit position.",
|
||||
"entries": ["per-bit counts mod k"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["cancels any k-fold repeat", "works per bit", "O(1) extra space"],
|
||||
"postmortem_points": [
|
||||
"Named why undoing by pairs fails here: a value seen three times does not cancel, so the repeat count must be part of the rule.",
|
||||
"Treated each bit position independently, counting its occurrences modulo three, so the triples vanish and the single value remains.",
|
||||
"Noted that the counter per bit is a fixed number of variables, which is what satisfies the space limit, and that k = 3 can be swapped for any repeat count."
|
||||
]
|
||||
},
|
||||
"two-sum-ii-input-array-is-sorted": {
|
||||
"design_rule": "The input is already ordered and only constant extra space is allowed, so the order itself must tell you which end to move after each comparison instead of remembering complements.",
|
||||
"entries": ["two pointers"],
|
||||
"also_accepted": ["binary search"],
|
||||
"key_requirements": ["two moving indexes", "from both ends", "O(1) extra space"],
|
||||
"postmortem_points": [
|
||||
"Named the property of the input that makes a decision safe: a too-small total can only be fixed by raising the lower end, a too-large one by lowering the upper end.",
|
||||
"Argued that each step discards a position that can no longer be part of an answer, so the scan is linear.",
|
||||
"Noted that the memory-based approach is excluded by the space limit, not by correctness."
|
||||
]
|
||||
},
|
||||
"3sum": {
|
||||
"design_rule": "Finding all distinct triples is cubic if unordered, so fix one value, order the rest so a pair search is linear, and skip repeated values to avoid duplicate triples.",
|
||||
"entries": ["sorting", "two pointers"],
|
||||
"also_accepted": ["hash set"],
|
||||
"key_requirements": ["makes equal values adjacent", "two moving indexes", "from both ends"],
|
||||
"postmortem_points": [
|
||||
"Reduced the problem to a pair search for each fixed first value, with total cost n log n for the ordering plus n squared for the searches.",
|
||||
"Used the ordering twice: to drive the pair search from both ends and to skip equal neighbours so no triple repeats.",
|
||||
"Handled the duplicate skips at both the fixed value and after a hit, and said why each is needed."
|
||||
]
|
||||
},
|
||||
"container-with-most-water": {
|
||||
"design_rule": "The width only shrinks as the walls close in, so a better container needs a taller shorter wall, which means always giving up the shorter wall and never the taller one.",
|
||||
"entries": ["two pointers"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["two moving indexes", "from both ends"],
|
||||
"postmortem_points": [
|
||||
"Started from the widest pair and argued why moving the taller wall can never help while moving the shorter one might.",
|
||||
"Stated the invariant: every pair that was skipped is no better than a pair already measured.",
|
||||
"Kept the best area seen so far as the only state, one linear scan with constant space."
|
||||
]
|
||||
},
|
||||
"trapping-rain-water": {
|
||||
"design_rule": "Water above a bar is set by the lower of the tallest bars on its two sides, so you need those side maxima without storing them for every position, which a scan from both ends can supply.",
|
||||
"entries": ["two pointers", "min / max"],
|
||||
"also_accepted": ["monotonic stack"],
|
||||
"key_requirements": ["two moving indexes", "from both ends", "associative"],
|
||||
"postmortem_points": [
|
||||
"Named the per-position rule: the level is the lower of the best bar to the left and the best bar to the right, minus the bar itself.",
|
||||
"Explained why the side with the smaller best-so-far is already decided, so only that side moves.",
|
||||
"Compared the stored-per-position version with the two-ended scan on memory."
|
||||
]
|
||||
},
|
||||
"longest-substring-without-repeating-characters": {
|
||||
"design_rule": "The answer is a longest contiguous range with no repeat, and a range that contains a repeat stays invalid as it grows, so both ends can only move right and the range can be repaired by moving the left end.",
|
||||
"entries": ["sliding window", "hash set"],
|
||||
"also_accepted": ["hash map", "counting array"],
|
||||
"key_requirements": ["window moves right", "monotone condition", "O(1) lookup"],
|
||||
"postmortem_points": [
|
||||
"Named why validity changes only once as the range grows: once a repeat is inside, extending it cannot fix it.",
|
||||
"Used the constant-time membership test to know when to move the left end.",
|
||||
"Argued the linear cost: each position enters and leaves the range at most once."
|
||||
]
|
||||
},
|
||||
"longest-repeating-character-replacement": {
|
||||
"design_rule": "A range is fixable when its length minus its most frequent letter fits the replacement budget, and that stays true for any smaller range inside it, so a range that only moves right can track the best length with per-letter counts.",
|
||||
"entries": ["sliding window", "counting array"],
|
||||
"also_accepted": ["hash map"],
|
||||
"key_requirements": ["window moves right", "monotone condition", "stores a value per key"],
|
||||
"postmortem_points": [
|
||||
"Turned the budget into a property of the range: length minus the highest count must not exceed the allowance.",
|
||||
"Explained why the highest count never needs lowering: a stale high count can only stop the range from growing, never make an answer wrong, because a longer answer needs a higher count first.",
|
||||
"Kept per-letter counts over a small fixed alphabet and updated them as each end moves."
|
||||
]
|
||||
},
|
||||
"permutation-in-string": {
|
||||
"design_rule": "A rearrangement of a pattern is a range of the same length with the same per-letter counts, so a fixed-length range that slides right can be compared incrementally instead of rebuilt.",
|
||||
"entries": ["sliding window", "counting array"],
|
||||
"also_accepted": ["hash map"],
|
||||
"key_requirements": ["window moves right", "stores a value per key"],
|
||||
"postmortem_points": [
|
||||
"Reduced the order-free match to equality of per-letter counts.",
|
||||
"Moved the range one step at a time, adding the new letter and removing the old one, so each step costs constant work.",
|
||||
"Kept a count of letters currently matching, or compared a small fixed-size table, instead of recomparing everything."
|
||||
]
|
||||
},
|
||||
"minimum-window-substring": {
|
||||
"design_rule": "The shortest range covering all required letters stays covering as it grows, so grow the right end until it covers, then shrink the left end while it still does, tracking the required counts per letter.",
|
||||
"entries": ["sliding window", "hash map"],
|
||||
"also_accepted": ["counting array"],
|
||||
"key_requirements": ["window moves right", "monotone condition", "stores a value per key"],
|
||||
"postmortem_points": [
|
||||
"Named that being covered is a property that only gets easier as the range grows, which is what makes shrinking safe.",
|
||||
"Tracked how many required letters are still short instead of recomparing all counts at every step.",
|
||||
"Recorded the best range only at the moment the shrinking loop stops being valid, and handled repeated required letters with counts."
|
||||
]
|
||||
},
|
||||
"subarray-sum-equals-k": {
|
||||
"design_rule": "Values can be negative, so a range that only moves right cannot be repaired by its total; instead the sum of any range is a difference of two running totals, so count how often each earlier total was seen.",
|
||||
"entries": ["prefix sum + hash map"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["needs an inverse", "handles negatives", "single pass", "O(1) lookup"],
|
||||
"postmortem_points": [
|
||||
"Named why growing and shrinking by the total fails here: negatives break the single change of validity.",
|
||||
"Expressed a range sum as the later total minus the earlier total, so the question becomes whether total minus the target was seen before.",
|
||||
"Counted each earlier total rather than only marking it, and recorded the empty start so ranges beginning at the first element are found."
|
||||
]
|
||||
},
|
||||
"continuous-subarray-sum": {
|
||||
"design_rule": "Being a multiple of k is not monotone as a range grows, so a moving range cannot work; two running totals with the same remainder bound a range whose sum is a multiple of k, and the length-two minimum needs the earliest position of each remainder.",
|
||||
"entries": ["prefix sum + hash map"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["needs an inverse", "single pass", "O(1) lookup"],
|
||||
"postmortem_points": [
|
||||
"Turned divisibility into equality of remainders between two running totals.",
|
||||
"Stored the first position of each remainder and never overwrote it, so the length condition can be checked.",
|
||||
"Seeded the empty start at position minus one, and handled two adjacent zero values as the edge case."
|
||||
]
|
||||
},
|
||||
"subarray-sums-divisible-by-k": {
|
||||
"design_rule": "A range sum divisible by k means two running totals share a remainder, and values can be negative so remainders must be normalised, so count the occurrences of each remainder as the scan proceeds.",
|
||||
"entries": ["prefix sum + hash map"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["needs an inverse", "handles negatives", "O(1) lookup"],
|
||||
"postmortem_points": [
|
||||
"Reduced the question to counting pairs of running totals with equal remainders.",
|
||||
"Normalised negative remainders into the range 0 to k minus 1, and said why the language remainder operator needs that fix.",
|
||||
"Counted pairs as each new total arrives, by adding the number of earlier equal remainders, and seeded the empty start."
|
||||
]
|
||||
},
|
||||
"contiguous-array": {
|
||||
"design_rule": "Equal numbers of zeros and ones is not a count that a moving range can steer, but relabelling zero as minus one turns it into a range summing to zero, so the earliest position of each running total gives the longest range.",
|
||||
"entries": ["prefix sum + hash map"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["needs an inverse", "handles negatives", "O(1) lookup"],
|
||||
"postmortem_points": [
|
||||
"Relabelled one value so that balanced becomes a total of zero, and noted that this introduces negatives.",
|
||||
"Stored only the first position of each running total because the longest range wants the earliest match.",
|
||||
"Seeded the empty start so a balanced range from the beginning counts."
|
||||
]
|
||||
},
|
||||
"daily-temperatures": {
|
||||
"design_rule": "For each day you need the nearest later day that is warmer, and answering all days in one linear pass means holding the still-unanswered days in an order where the most recent is resolved first.",
|
||||
"entries": ["monotonic stack"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["next-greater lookup", "last-in-first-out", "amortized O(n)"],
|
||||
"postmortem_points": [
|
||||
"Framed the task as a nearest-later-larger lookup for every position.",
|
||||
"Kept the unresolved days with their values decreasing, so a warmer day resolves exactly the most recent ones it beats.",
|
||||
"Argued the linear total: each day is added once and removed once, and stored positions rather than values to get distances."
|
||||
]
|
||||
},
|
||||
"next-greater-element-i": {
|
||||
"design_rule": "Every query value is looked up in a second list, and the nearest later larger element is needed for all of them, so compute it once per element of the big list in one pass and answer the queries by key.",
|
||||
"entries": ["monotonic stack", "hash map"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["next-greater lookup", "last-in-first-out", "stores a value per key"],
|
||||
"postmortem_points": [
|
||||
"Separated the two jobs: finding the nearest later larger value for every element, and answering the queries by value.",
|
||||
"Used distinct values as keys to store each answer, and defaulted to minus one for elements never resolved.",
|
||||
"Argued the linear cost of the pass: each element enters and leaves once."
|
||||
]
|
||||
},
|
||||
"next-greater-element-ii": {
|
||||
"design_rule": "The array is circular, so the nearest larger element may lie before the position, and since one pass over the list cannot see it, the same pass must cover every position twice while still resolving the most recent unresolved ones first.",
|
||||
"entries": ["monotonic stack"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["next-greater lookup", "last-in-first-out", "amortized O(n)"],
|
||||
"postmortem_points": [
|
||||
"Handled the wrap-around by visiting each position a second time through the remainder of the index, instead of copying the list.",
|
||||
"Recorded answers only on the first visit, since an element resolved earlier is already settled.",
|
||||
"Argued the cost is still linear: at most two additions and removals per element."
|
||||
]
|
||||
},
|
||||
"largest-rectangle-in-histogram": {
|
||||
"design_rule": "Each bar's best rectangle extends to the nearest strictly lower bar on each side, so a single pass must find both limits for every bar, which means resolving the most recent taller bars as soon as a lower one arrives.",
|
||||
"entries": ["monotonic stack"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["next-greater lookup", "last-in-first-out", "amortized O(n)"],
|
||||
"postmortem_points": [
|
||||
"Reframed it as a nearest-lower lookup on both sides for every bar, the mirror of a nearest-larger lookup.",
|
||||
"Computed the width from the new limit and the limit stored below the removed bar, and flushed the remaining bars with a sentinel at the end.",
|
||||
"Argued the linear total: each bar is added once and removed once, and equal heights need no special case if the comparison is chosen consistently."
|
||||
]
|
||||
},
|
||||
"merge-intervals": {
|
||||
"design_rule": "Overlapping ranges can be scattered anywhere in the input, so order them by start; then everything that overlaps the current group follows right after it and one pass can extend or close the group.",
|
||||
"entries": ["sort by start + merge"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["overlaps become adjacent", "needs sorted input", "single pass"],
|
||||
"postmortem_points": [
|
||||
"Named why the ordering by start makes the single comparison with the last group enough.",
|
||||
"Treated touching ranges deliberately (whether a shared endpoint counts as overlap) and extended the end with the larger of the two ends.",
|
||||
"Stated the cost: n log n for the ordering dominates the linear merge."
|
||||
]
|
||||
},
|
||||
"insert-interval": {
|
||||
"design_rule": "The existing ranges are already ordered by start and disjoint, so no reordering is needed: those entirely before the new one stay, those overlapping it are absorbed into one, and the rest follow.",
|
||||
"entries": ["sort by start + merge"],
|
||||
"also_accepted": ["binary search"],
|
||||
"key_requirements": ["overlaps become adjacent", "needs sorted input", "single pass"],
|
||||
"postmortem_points": [
|
||||
"Used the given order instead of reordering, so the work is one linear pass in three phases: before, overlapping, after.",
|
||||
"Merged the overlapping run by taking the smallest start and the largest end among it and the new range.",
|
||||
"Handled the edge cases: the new range at either extreme, touching endpoints, and an empty input list."
|
||||
]
|
||||
},
|
||||
"non-overlapping-intervals": {
|
||||
"design_rule": "Removing the fewest ranges means keeping the most that do not overlap, and the range that finishes first always leaves the most room for the rest, so a locally best choice is never regretted.",
|
||||
"entries": ["sort by end + greedy pick"],
|
||||
"also_accepted": [],
|
||||
"key_requirements": ["earliest end first", "greedy", "needs sorted input"],
|
||||
"postmortem_points": [
|
||||
"Flipped the question: the answer is the total minus the largest set of mutually compatible ranges.",
|
||||
"Gave the exchange argument for why taking the earliest finish is never worse than any other first choice.",
|
||||
"Counted a range as compatible only if it starts at or after the last kept end, and decided that touching counts as compatible."
|
||||
]
|
||||
},
|
||||
"minimum-number-of-arrows-to-burst-balloons": {
|
||||
"design_rule": "One arrow serves every range that contains its position, so the fewest arrows come from sweeping ranges by their right end and placing each arrow at the earliest end that still covers everything not yet served.",
|
||||
"entries": ["sort by end + greedy pick"],
|
||||
"also_accepted": ["sort by start + merge"],
|
||||
"key_requirements": ["earliest end first", "greedy", "needs sorted input"],
|
||||
"postmortem_points": [
|
||||
"Recognised this as the same structure as keeping the most compatible ranges: a group of ranges sharing a point costs one arrow.",
|
||||
"Placed the arrow at the earliest end and counted a new arrow only when the next range starts strictly after it.",
|
||||
"Ordered by comparing rather than subtracting, since the coordinates can be negative and reach the integer limits."
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
81
leetcode_coach/leetcode_coach/answer_key.py
Normal file
81
leetcode_coach/leetcode_coach/answer_key.py
Normal file
@ -0,0 +1,81 @@
|
||||
"""The grader's answer key (DOCS-coach-ui-spec.md decision 5), from ``answer_key.json``.
|
||||
|
||||
Schema: ``{"problems": {"<slug>": {"design_rule", "entries", "also_accepted",
|
||||
"key_requirements", "postmortem_points"}}}``, one entry per cluster problem.
|
||||
|
||||
* ``design_rule``: what the binding constraint forces, in one sentence.
|
||||
* ``entries``: toolbox entry names (``toolbox.json``) that solve it, 1-3. Where
|
||||
the entry is a combination ("prefix sum + hash map"), naming both of its
|
||||
parts is as good as naming it.
|
||||
* ``also_accepted``: further toolbox entries that are correct but not the
|
||||
intended one (sum instead of XOR for Missing Number).
|
||||
* ``key_requirements``: 2-5 vocabulary properties the requirement list must
|
||||
contain. Each is a property of the ``entries``, so the intended entries
|
||||
cover all of them.
|
||||
* ``postmortem_points``: 2-4 properties and method steps a good post-mortem
|
||||
names, never code.
|
||||
|
||||
The file is never shown to kuhy. The design rule and the points still name no
|
||||
toolbox entry, because the grader's feedback is built from them and goes
|
||||
through the same leak check as coach replies (``leak.leaked_names``); a test
|
||||
holds that line. kuhy reviews the JSON itself, like the toolbox.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
ANSWER_KEY_PATH = Path(__file__).with_name("answer_key.json")
|
||||
|
||||
|
||||
def load(path: Path | None = None) -> dict[str, Any]:
|
||||
"""The parsed answer key; ``path`` defaults to the shipped file at call time."""
|
||||
source = ANSWER_KEY_PATH if path is None else path
|
||||
data: dict[str, Any] = json.loads(source.read_text(encoding="utf-8"))
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Answer:
|
||||
"""What a correct run of one problem looks like."""
|
||||
|
||||
design_rule: str
|
||||
entries: tuple[str, ...]
|
||||
also_accepted: tuple[str, ...]
|
||||
key_requirements: tuple[str, ...]
|
||||
postmortem_points: tuple[str, ...]
|
||||
|
||||
|
||||
def _strings(
|
||||
raw: dict[str, Any], key: str, *, optional: bool = False
|
||||
) -> tuple[str, ...]:
|
||||
value = raw.get(key, [] if optional else None)
|
||||
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
||||
msg = f"{key} must be a list of strings"
|
||||
raise TypeError(msg)
|
||||
return tuple(value)
|
||||
|
||||
|
||||
def _answer(raw: object) -> Answer:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("design_rule"), str):
|
||||
msg = "every answer needs an object with a string design_rule"
|
||||
raise TypeError(msg)
|
||||
return Answer(
|
||||
design_rule=raw["design_rule"],
|
||||
entries=_strings(raw, "entries"),
|
||||
also_accepted=_strings(raw, "also_accepted", optional=True),
|
||||
key_requirements=_strings(raw, "key_requirements"),
|
||||
postmortem_points=_strings(raw, "postmortem_points"),
|
||||
)
|
||||
|
||||
|
||||
def load_answers(path: Path | None = None) -> dict[str, Answer]:
|
||||
"""The typed key, ``{slug: Answer}``; a malformed file raises `TypeError`."""
|
||||
problems = load(path)["problems"]
|
||||
if not isinstance(problems, dict):
|
||||
msg = "problems must map each slug to its answer"
|
||||
raise TypeError(msg)
|
||||
return {slug: _answer(raw) for slug, raw in problems.items()}
|
||||
92
leetcode_coach/leetcode_coach/card_rules.py
Normal file
92
leetcode_coach/leetcode_coach/card_rules.py
Normal file
@ -0,0 +1,92 @@
|
||||
"""The shape rules every /leetcode post-mortem card must pass.
|
||||
|
||||
Short by construction: a back longer than BACK_MAX_WORDS words or a front
|
||||
longer than FRONT_MAX_WORDS fails the run and names the offender, so the model
|
||||
has to shorten instead of shipping a paragraph. Shape is gated the same way: a
|
||||
yes/no or either/or question is a coin flip, two questions on one front split
|
||||
the recall, and a `{ ... }` back is a placeholder, not an answer.
|
||||
|
||||
Split out of `make_cards.py` (which keeps the delivery side) for the
|
||||
250-line cap; the rules are unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
|
||||
FRONT_MAX_WORDS = 20
|
||||
BACK_MAX_WORDS = 8
|
||||
MIN_CARDS, MAX_CARDS = 1, 6
|
||||
YES_NO = re.compile(
|
||||
r"(is|are|does|do|did|can|could|should|will|would|has|have|was|were)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
EITHER_OR = re.compile(r"\bor\b", re.IGNORECASE)
|
||||
PLACEHOLDER = re.compile(r"\{\s*(\.\.\.|…)\s*\}|…")
|
||||
|
||||
Card = dict[str, str]
|
||||
|
||||
|
||||
def shape_errors(i: int, front: str, back: str) -> list[str]:
|
||||
"""Coin-flip and placeholder cards: a pass on them proves no recall."""
|
||||
errors: list[str] = []
|
||||
if front.count("?") > 1:
|
||||
errors.append(f"card {i}: two questions on one front; split it")
|
||||
question = re.split(r"[:—]|\.\s", front)[-1].strip()
|
||||
if question.endswith("?"):
|
||||
if YES_NO.match(question):
|
||||
errors.append(f"card {i}: yes/no front; ask for the thing itself")
|
||||
elif EITHER_OR.search(question):
|
||||
errors.append(f"card {i}: either/or front; the back is a coin flip")
|
||||
if PLACEHOLDER.search(back):
|
||||
errors.append(f"card {i}: placeholder in back; write the real code")
|
||||
return errors
|
||||
|
||||
|
||||
def validate(slug: str, cards: list[Card]) -> list[str]:
|
||||
"""Return every rule violation as a human-readable line (empty = ok)."""
|
||||
errors: list[str] = []
|
||||
if not MIN_CARDS <= len(cards) <= MAX_CARDS:
|
||||
errors.append(f"{len(cards)} cards; want {MIN_CARDS}-{MAX_CARDS}")
|
||||
for i, c in enumerate(cards, 1):
|
||||
front, back = str(c.get("front", "")).strip(), str(c.get("back", "")).strip()
|
||||
if not front or not back:
|
||||
errors.append(f"card {i}: empty front or back")
|
||||
continue
|
||||
if "\n" in front or "\n" in back:
|
||||
errors.append(f"card {i}: newlines are not allowed")
|
||||
if len(front.split()) > FRONT_MAX_WORDS:
|
||||
errors.append(
|
||||
f"card {i}: front is {len(front.split())} words (max {FRONT_MAX_WORDS})"
|
||||
)
|
||||
if (n := len(back.split())) > BACK_MAX_WORDS:
|
||||
errors.append(
|
||||
f"card {i}: back is {n} words (max {BACK_MAX_WORDS}): {back!r}"
|
||||
)
|
||||
errors += shape_errors(i, front, back)
|
||||
if not slug:
|
||||
errors.append("missing slug")
|
||||
return errors
|
||||
|
||||
|
||||
def _cell(text: str) -> str:
|
||||
"""Markdown table cell: a bare pipe would split it in two."""
|
||||
return text.strip().replace("|", "\\|")
|
||||
|
||||
|
||||
def _esc(text: str) -> str:
|
||||
"""HTML-escape one field (quotes are left alone)."""
|
||||
return html.escape(text.strip(), quote=False)
|
||||
|
||||
|
||||
def table(cards: list[Card]) -> str:
|
||||
"""Markdown table for the chat reply, so the model relays instead of retyping."""
|
||||
rows = ["| Front | Back |", "|---|---|"]
|
||||
rows += [f"| {_cell(c['front'])} | {_cell(c['back'])} |" for c in cards]
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
def escaped(cards: list[Card]) -> list[Card]:
|
||||
"""Anki fields are HTML: escape so `a<b` or `&` survive rendering."""
|
||||
return [{"front": _esc(c["front"]), "back": _esc(c["back"])} for c in cards]
|
||||
85
leetcode_coach/leetcode_coach/claude_cli.py
Normal file
85
leetcode_coach/leetcode_coach/claude_cli.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""The one `claude -p` call, shared by the coaching REPL and the req checker.
|
||||
|
||||
The binary is looked up per call (``LEETCODE_CLAUDE_BIN``, else PATH), so the
|
||||
E2E tests can point a running REPL at a fake. A binary that cannot start or
|
||||
hangs past `timeout` comes back as an error reply, never an exception: the
|
||||
checker treats it as "haiku did not answer" and falls back.
|
||||
|
||||
The signal for a spent plan is the synthetic reply "You've hit your session
|
||||
limit · resets 3pm (Europe/Warsaw)" (error rate_limit, HTTP 429), as recorded
|
||||
in real transcripts on 2026-09-26.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
LIMIT_RE = re.compile(r"hit your (?:\w+ )?limit|usage limit reached", re.IGNORECASE)
|
||||
RATE_LIMIT_STATUS = 429
|
||||
|
||||
|
||||
def claude_bin() -> str:
|
||||
"""``LEETCODE_CLAUDE_BIN``, else ``claude`` from PATH.
|
||||
|
||||
PATH lookup, not a fixed path: claude lives in ~/.local/bin here, and the
|
||||
old /usr/bin/claude default made every REPL turn crash (2026-10-20).
|
||||
"""
|
||||
return os.environ.get("LEETCODE_CLAUDE_BIN") or shutil.which("claude") or "claude"
|
||||
|
||||
|
||||
def ask(
|
||||
args: list[str],
|
||||
prompt: str,
|
||||
*,
|
||||
timeout: float | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""One `claude -p` turn; the JSON result, or a stand-in carrying stderr.
|
||||
|
||||
`env` is merged over this process's environment for the child only: the
|
||||
relay hands each session its own ``LEETCODE_COACH_LOG`` this way, never
|
||||
through ``os.environ`` (one process serves many sessions).
|
||||
"""
|
||||
child_env = {**os.environ, "CLAUDE_TTY_FIX_OFF": "1", **(env or {})}
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[claude_bin(), "-p", *args, "--output-format", "json", prompt],
|
||||
capture_output=True,
|
||||
stdin=subprocess.DEVNULL, # claude -p would otherwise drain REPL input
|
||||
text=True,
|
||||
env=child_env,
|
||||
check=False,
|
||||
cwd=Path.home(),
|
||||
timeout=timeout,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
_LOG.warning("claude -p could not run: %s", exc)
|
||||
return {"result": f"[claude could not run: {exc}]", "_stderr": str(exc)}
|
||||
reply: object
|
||||
try:
|
||||
reply = json.loads(proc.stdout, strict=False) if proc.stdout.strip() else {}
|
||||
except json.JSONDecodeError as exc:
|
||||
_LOG.warning("claude -p printed something that is not JSON: %s", exc)
|
||||
reply = {}
|
||||
result: dict[str, Any] = reply if isinstance(reply, dict) else {}
|
||||
result["_stderr"] = proc.stderr.strip()
|
||||
if proc.returncode != 0 and "result" not in result:
|
||||
result["result"] = f"[claude exited {proc.returncode}]\n{proc.stderr.strip()}"
|
||||
return result
|
||||
|
||||
|
||||
def is_limit_hit(reply: dict[str, Any]) -> bool:
|
||||
"""Whether Claude refused this turn because the plan's usage limit is spent."""
|
||||
if reply.get("api_error_status") == RATE_LIMIT_STATUS:
|
||||
return True
|
||||
text = f"{reply.get('result', '')}\n{reply.get('_stderr', '')}"
|
||||
return bool(LIMIT_RE.search(text))
|
||||
148
leetcode_coach/leetcode_coach/cluster_cli.py
Normal file
148
leetcode_coach/leetcode_coach/cluster_cli.py
Normal file
@ -0,0 +1,148 @@
|
||||
"""`leetcode due`, `leetcode --cluster <name>` and `leetcode --retest <slug>`.
|
||||
|
||||
DOCS-coach-spec.md decisions 10 and 12, on top of `progress` (which derives
|
||||
everything from the session logs):
|
||||
|
||||
* ``due`` lists the cold re-tests that are due (+3 and +10 days after a solve).
|
||||
* ``--cluster <name>`` serves that cluster's due re-test first, else its next
|
||||
problem with no ``code`` event, skipping problems LeetCode already reports
|
||||
Accepted. The live check fails OPEN: if LeetCode cannot be asked, the
|
||||
problem is served rather than skipped.
|
||||
* ``--retest <slug>`` starts a cold session: a fresh ``claude -p`` session
|
||||
with no history, whose opening tells the coach it is a re-test judged in
|
||||
``node`` and that kuhy must NOT submit -- a resubmission is a new
|
||||
submission id, and the harvester mints a gate credit for every one.
|
||||
A ``retest`` event is logged only if the session reached a post-mortem, so
|
||||
quitting early does not burn the re-test.
|
||||
|
||||
``--dry-run`` says what would be served without starting a session. The
|
||||
cluster name reaches the session writer through ``$LEETCODE_COACH_CLUSTER``.
|
||||
Its prints are its interface (T201 exemption in pyproject.toml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from leetcode_coach import guard_bridge, how_to, progress
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
COMMANDS = frozenset({"due", "--cluster", "--retest"})
|
||||
USAGE = (
|
||||
"usage: leetcode due | --cluster <name> [--dry-run] | --retest <slug> [--dry-run]"
|
||||
)
|
||||
STAGES = len(progress.RETEST_OFFSETS)
|
||||
COLD_RETEST_TAG = "[cold re-test]"
|
||||
COLD_RETEST = (
|
||||
f"{COLD_RETEST_TAG} kuhy solved this problem before. This is a cold "
|
||||
"re-test: fresh session, no hints or code from last time, requirement "
|
||||
"list first as usual. Judge the solution by running the statement's "
|
||||
"examples locally with node, not on LeetCode. Tell kuhy: do NOT submit "
|
||||
"on LeetCode, a resubmission mints a gate credit."
|
||||
)
|
||||
|
||||
Start = Callable[[list[str]], int]
|
||||
|
||||
|
||||
def accepted_on_leetcode(slug: str) -> bool:
|
||||
"""Whether LeetCode confirms an Accepted submission; False if it cannot say."""
|
||||
try:
|
||||
solved = guard_bridge.solved_slugs([slug])
|
||||
except Exception: # pylint: disable=broad-exception-caught
|
||||
_logger.exception("live solved-check for %s raised; serving it", slug)
|
||||
return False
|
||||
return slug in solved
|
||||
|
||||
|
||||
def _due() -> int:
|
||||
rows = progress.due_retests()
|
||||
if not rows:
|
||||
print("no re-tests due")
|
||||
return 0
|
||||
for row in rows:
|
||||
command = how_to.retest_command(row["slug"])
|
||||
print(
|
||||
f"{row['due']} {row['slug']} re-test {row['stage']}/{STAGES} "
|
||||
f"({row['cluster'] or 'no cluster'}) -> {command}"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def _retest(slug: str, start: Start, *, dry: bool) -> int:
|
||||
past = progress.history(slug)
|
||||
if past.solved is None:
|
||||
print(
|
||||
f"{slug} is not solved yet (no code + post-mortem logged)", file=sys.stderr
|
||||
)
|
||||
return 1
|
||||
if past.retests >= STAGES:
|
||||
print(f"both re-tests of {slug} are done; practise it with `leetcode {slug}`")
|
||||
return 0
|
||||
stage = past.retests + 1
|
||||
print(f"cold re-test {stage}/{STAGES}: {slug} (solved {past.solved})")
|
||||
if dry:
|
||||
return 0
|
||||
cluster = progress.cluster_of(slug)
|
||||
if cluster is None:
|
||||
os.environ.pop(progress.CLUSTER_ENV, None)
|
||||
else:
|
||||
os.environ[progress.CLUSTER_ENV] = cluster
|
||||
before = progress.count_events(slug, "postmortem")
|
||||
code = start([slug, COLD_RETEST])
|
||||
if progress.count_events(slug, "postmortem") > before:
|
||||
event = {"event": "retest", "stage": stage, "cluster": cluster}
|
||||
progress.append_event(slug, event)
|
||||
print(f"re-test {stage}/{STAGES} logged for {slug}")
|
||||
else:
|
||||
print(
|
||||
f"re-test not logged: the session ended without a post-mortem; "
|
||||
f"rerun `leetcode --retest {slug}`"
|
||||
)
|
||||
return code
|
||||
|
||||
|
||||
def _cluster(
|
||||
name: str, start: Start, accepted: Callable[[str], bool], *, dry: bool
|
||||
) -> int:
|
||||
clusters = progress.load_clusters()
|
||||
if name not in clusters:
|
||||
known = ", ".join(clusters)
|
||||
print(f"unknown cluster {name!r}; known: {known}", file=sys.stderr)
|
||||
return 1
|
||||
due = [row for row in progress.due_retests() if row["cluster"] == name]
|
||||
if due:
|
||||
print(f"re-test due: {due[0]['slug']} (due {due[0]['due']})")
|
||||
return _retest(due[0]["slug"], start, dry=dry)
|
||||
slug = progress.next_new(name, None, accepted)
|
||||
if slug is None:
|
||||
print(f"{name}: every problem is started or accepted on LeetCode")
|
||||
return 0
|
||||
number = next(p["id"] for p in clusters[name] if p["slug"] == slug)
|
||||
print(f"next in {name}: {slug} (#{number})")
|
||||
if dry:
|
||||
return 0
|
||||
os.environ[progress.CLUSTER_ENV] = name
|
||||
return start([slug])
|
||||
|
||||
|
||||
def main(
|
||||
argv: list[str], start: Start, accepted: Callable[[str], bool] | None = None
|
||||
) -> int:
|
||||
"""Dispatch `due`, `--cluster <name>` and `--retest <slug>`."""
|
||||
dry = "--dry-run" in argv
|
||||
args = [a for a in argv if a != "--dry-run"]
|
||||
match args:
|
||||
case ["due"]:
|
||||
return _due()
|
||||
case ["--cluster", name]:
|
||||
check = accepted_on_leetcode if accepted is None else accepted
|
||||
return _cluster(name, start, check, dry=dry)
|
||||
case ["--retest", slug]:
|
||||
return _retest(slug, start, dry=dry)
|
||||
case _:
|
||||
print(USAGE, file=sys.stderr)
|
||||
return 1
|
||||
40
leetcode_coach/leetcode_coach/clusters.json
Normal file
40
leetcode_coach/leetcode_coach/clusters.json
Normal file
@ -0,0 +1,40 @@
|
||||
{
|
||||
"clusters": {
|
||||
"bit-cancellation": [
|
||||
{"id": 268, "slug": "missing-number", "title": "Missing Number"},
|
||||
{"id": 260, "slug": "single-number-iii", "title": "Single Number III"},
|
||||
{"id": 169, "slug": "majority-element", "title": "Majority Element"},
|
||||
{"id": 137, "slug": "single-number-ii", "title": "Single Number II"}
|
||||
],
|
||||
"two-pointers": [
|
||||
{"id": 167, "slug": "two-sum-ii-input-array-is-sorted", "title": "Two Sum II - Input Array Is Sorted"},
|
||||
{"id": 15, "slug": "3sum", "title": "3Sum"},
|
||||
{"id": 11, "slug": "container-with-most-water", "title": "Container With Most Water"},
|
||||
{"id": 42, "slug": "trapping-rain-water", "title": "Trapping Rain Water"}
|
||||
],
|
||||
"sliding-window": [
|
||||
{"id": 3, "slug": "longest-substring-without-repeating-characters", "title": "Longest Substring Without Repeating Characters"},
|
||||
{"id": 424, "slug": "longest-repeating-character-replacement", "title": "Longest Repeating Character Replacement"},
|
||||
{"id": 567, "slug": "permutation-in-string", "title": "Permutation in String"},
|
||||
{"id": 76, "slug": "minimum-window-substring", "title": "Minimum Window Substring"}
|
||||
],
|
||||
"prefix-sum-hash": [
|
||||
{"id": 560, "slug": "subarray-sum-equals-k", "title": "Subarray Sum Equals K"},
|
||||
{"id": 523, "slug": "continuous-subarray-sum", "title": "Continuous Subarray Sum"},
|
||||
{"id": 974, "slug": "subarray-sums-divisible-by-k", "title": "Subarray Sums Divisible by K"},
|
||||
{"id": 525, "slug": "contiguous-array", "title": "Contiguous Array"}
|
||||
],
|
||||
"monotonic-stack": [
|
||||
{"id": 739, "slug": "daily-temperatures", "title": "Daily Temperatures"},
|
||||
{"id": 496, "slug": "next-greater-element-i", "title": "Next Greater Element I"},
|
||||
{"id": 503, "slug": "next-greater-element-ii", "title": "Next Greater Element II"},
|
||||
{"id": 84, "slug": "largest-rectangle-in-histogram", "title": "Largest Rectangle in Histogram"}
|
||||
],
|
||||
"intervals": [
|
||||
{"id": 56, "slug": "merge-intervals", "title": "Merge Intervals"},
|
||||
{"id": 57, "slug": "insert-interval", "title": "Insert Interval"},
|
||||
{"id": 435, "slug": "non-overlapping-intervals", "title": "Non-overlapping Intervals"},
|
||||
{"id": 452, "slug": "minimum-number-of-arrows-to-burst-balloons", "title": "Minimum Number of Arrows to Burst Balloons"}
|
||||
]
|
||||
}
|
||||
}
|
||||
105
leetcode_coach/leetcode_coach/eval_local.py
Executable file
105
leetcode_coach/leetcode_coach/eval_local.py
Executable file
@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scripted acceptance run of the local coach on two-sum (no human needed).
|
||||
|
||||
Six canned student turns, including a demand for the code, a buggy paste and a
|
||||
give-up. PASS only if every criterion holds on every reply:
|
||||
|
||||
no-code the no-solution gate finds nothing pasteable in the shown reply
|
||||
one-task the reply ends with exactly one thing to do (one question, or an
|
||||
imperative last line)
|
||||
fast the reply (including gate regenerations) took < MAX_SECONDS
|
||||
|
||||
The model load is timed separately by a warm-up call and excluded: it happens
|
||||
once per session, and the criterion is about the conversation's pace.
|
||||
Writes the transcript to ~/data/claude-scratch/leetcode-local/. Its printed
|
||||
table IS the verdict (T201 exemption in pyproject.toml).
|
||||
|
||||
python3 -m leetcode_coach.eval_local
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from leetcode_coach import local_backend, local_cards, local_coach, local_prompt
|
||||
from leetcode_coach.local_session import opening_message
|
||||
|
||||
MAX_SECONDS = 15.0
|
||||
OUT_DIR = Path.home() / "data" / "claude-scratch" / "leetcode-local"
|
||||
BUGGY = """var twoSum = function(nums, target) {
|
||||
const seen = {};
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
seen[nums[i]] = i;
|
||||
if (seen[target - nums[i]] !== undefined) return [seen[target - nums[i]], i];
|
||||
}
|
||||
};"""
|
||||
TURNS = [
|
||||
opening_message(["how", "to", "beat", "checking", "every", "pair"]),
|
||||
"I'd do two loops and check every pair. That's slow though, right?",
|
||||
"just give me the code",
|
||||
"hint",
|
||||
BUGGY,
|
||||
"I give up, what would you write?",
|
||||
]
|
||||
Row = tuple[int, float, int, bool, bool, bool, bool]
|
||||
|
||||
|
||||
def _print_table(rows: list[Row]) -> None:
|
||||
"""One line per turn: timing, tries and the three criteria."""
|
||||
print("turn secs tries withheld no-code one-task fast")
|
||||
for n, secs, tries, withheld, ok_code, ok_task, ok_fast in rows:
|
||||
print(
|
||||
f"{n:>4} {secs:5.1f} {tries:>5} {withheld!s:>8} {ok_code!s:>7} "
|
||||
f"{ok_task!s:>8} {ok_fast!s:>5}"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Run the six turns, print a per-criterion table, exit 0 only on PASS."""
|
||||
statement = subprocess.run(
|
||||
[sys.executable, str(Path(__file__).with_name("fetch_problem.py")), "two-sum"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout
|
||||
start = time.monotonic()
|
||||
local_backend.chat([{"role": "user", "content": "Say ok."}])
|
||||
print(f"model load + warm-up: {time.monotonic() - start:.1f}s")
|
||||
coach = local_coach.LocalCoach.start(statement)
|
||||
rows: list[Row] = []
|
||||
log: list[str] = []
|
||||
for n, said in enumerate(TURNS, 1):
|
||||
turn = coach.respond(said)
|
||||
shown, _ = local_cards.split_cards(turn.text)
|
||||
leaks = local_coach.gate_findings(shown, statement, coach.user_texts())
|
||||
rows.append(
|
||||
(
|
||||
n,
|
||||
turn.seconds,
|
||||
turn.attempts,
|
||||
turn.withheld,
|
||||
not leaks,
|
||||
local_prompt.ends_with_one_task(shown),
|
||||
turn.seconds < MAX_SECONDS,
|
||||
)
|
||||
)
|
||||
log.append(
|
||||
f"## Turn {n}\n\n**kuhy:** {said}\n\n**coach** "
|
||||
f"({turn.seconds:.1f}s, attempts {turn.attempts}):\n\n{shown}\n"
|
||||
)
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
stamp = dt.datetime.now(tz=dt.UTC).astimezone()
|
||||
out = OUT_DIR / f"eval-{stamp:%Y%m%d-%H%M%S}.md"
|
||||
out.write_text("\n".join(log), encoding="utf-8")
|
||||
_print_table(rows)
|
||||
passed = all(all(r[4:]) for r in rows)
|
||||
print(f"{'PASS' if passed else 'FAIL'} transcript: {out}")
|
||||
return 0 if passed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
179
leetcode_coach/leetcode_coach/fetch_problem.py
Executable file
179
leetcode_coach/leetcode_coach/fetch_problem.py
Executable file
@ -0,0 +1,179 @@
|
||||
#!/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())
|
||||
176
leetcode_coach/leetcode_coach/gate_detector.py
Normal file
176
leetcode_coach/leetcode_coach/gate_detector.py
Normal file
@ -0,0 +1,176 @@
|
||||
"""Transcript parsing and pasteable-snippet detection for the no-solution gate.
|
||||
|
||||
Shared by the Stop hook (`stop_gate.py`) and the offline coach
|
||||
(`local_coach.py`), so both paths judge a reply with one detector. A snippet
|
||||
is pasteable when a code span or fenced block uses an identifier from the
|
||||
problem's starter signature together with a call/spread/assignment -- unless
|
||||
that exact snippet already appears in kuhy's own messages or the fetched
|
||||
problem (quoting their code back is fine).
|
||||
|
||||
Moved verbatim from ``~/.claude/hooks/leetcode_no_solution_stop.py``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
KEYWORDS = {
|
||||
"function",
|
||||
"return",
|
||||
"const",
|
||||
"let",
|
||||
"var",
|
||||
"self",
|
||||
"def",
|
||||
"class",
|
||||
"this",
|
||||
"new",
|
||||
"true",
|
||||
"false",
|
||||
"null",
|
||||
"None",
|
||||
"int",
|
||||
"str",
|
||||
"list",
|
||||
"number",
|
||||
"string",
|
||||
"void",
|
||||
}
|
||||
CODE_RE = re.compile(r"```.*?```|`[^`\n]+`", re.DOTALL)
|
||||
SIG_RE = re.compile(
|
||||
r"(?:function\s*(\w*)|def\s+(\w+)|(\w+)\s*=\s*(?:function)?)\s*\(([^)]*)\)"
|
||||
)
|
||||
# User-role messages that are not kuhy: the injected skill body and the hook's
|
||||
# own block reason (which quotes the offending snippet and must not whitelist it).
|
||||
NOT_KUHY = ("Base directory for this skill", "Stop hook feedback:")
|
||||
MIN_IDENT_LEN = 2 # single letters (`t`) are too common in prose and toy code
|
||||
LANG_PREFIXES = ("javascript", "js", "python", "typescript")
|
||||
|
||||
Entry = dict[str, Any]
|
||||
|
||||
|
||||
def _parse(line: str) -> object:
|
||||
"""One JSONL line, or None when it is not JSON (e.g. a half-written tail)."""
|
||||
try:
|
||||
return json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
_LOG.warning("skipping a transcript line that is not JSON: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def transcript_lines(raw: str) -> list[Entry]:
|
||||
"""Every JSON object in a JSONL transcript, in order."""
|
||||
return [d for d in map(_parse, raw.splitlines()) if isinstance(d, dict)]
|
||||
|
||||
|
||||
def _content(msg: Entry) -> str | list[Entry]:
|
||||
"""The `message.content` field: a string or a list of content blocks."""
|
||||
content: str | list[Entry] = msg.get("message", {}).get("content", "")
|
||||
return content
|
||||
|
||||
|
||||
def text_of(msg: Entry) -> str:
|
||||
"""All text in an entry, tool results included."""
|
||||
content = _content(msg)
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
parts = []
|
||||
for c in content:
|
||||
if c.get("type") == "text":
|
||||
parts.append(c.get("text", ""))
|
||||
elif c.get("type") == "tool_result":
|
||||
inner = c.get("content", "")
|
||||
parts.append(
|
||||
inner
|
||||
if isinstance(inner, str)
|
||||
else " ".join(x.get("text", "") for x in inner)
|
||||
)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def kuhy_text(msg: Entry) -> str:
|
||||
"""Only what kuhy typed: no tool results, no skill body, no echoed hook reason."""
|
||||
content = _content(msg)
|
||||
texts = (
|
||||
[content]
|
||||
if isinstance(content, str)
|
||||
else [c.get("text", "") for c in content if c.get("type") == "text"]
|
||||
)
|
||||
return "\n".join(t for t in texts if not t.startswith(NOT_KUHY))
|
||||
|
||||
|
||||
def _signature_names(code: str) -> set[str]:
|
||||
"""Function and parameter names of every signature in `code`."""
|
||||
names: set[str] = set()
|
||||
for sig in SIG_RE.finditer(code):
|
||||
names.update(n for n in sig.groups()[:3] if n)
|
||||
for raw in sig.group(4).split(","):
|
||||
param = raw.strip().split(":")[0].split("=")[0].strip().lstrip("*")
|
||||
if param:
|
||||
names.add(param)
|
||||
return names
|
||||
|
||||
|
||||
def starter_identifiers(entries: list[Entry]) -> set[str]:
|
||||
"""Function name + parameter names from the fetched '## Starter code' block."""
|
||||
for e in entries:
|
||||
if e.get("type") != "user":
|
||||
continue
|
||||
txt = text_of(e)
|
||||
if "## Starter code" not in txt:
|
||||
continue
|
||||
block = txt.split("## Starter code", 1)[1]
|
||||
m = re.search(r"```\n?(.*?)```", block, re.DOTALL)
|
||||
code = m.group(1) if m else block
|
||||
# LeetCode starters carry the test harness in a block comment; drop
|
||||
# comments so its helpers (`log`, `...argsArr`) are not taken as symbols.
|
||||
code = re.sub(r"/\*.*?\*/|//[^\n]*|#[^\n]*", "", code, flags=re.DOTALL)
|
||||
names = _signature_names(code)
|
||||
return {n for n in names if len(n) >= MIN_IDENT_LEN and n not in KEYWORDS}
|
||||
return set()
|
||||
|
||||
|
||||
def _squash(text: str) -> str:
|
||||
"""Collapse every whitespace run to one space."""
|
||||
return re.sub(r"\s+", " ", text).strip()
|
||||
|
||||
|
||||
def allowed_text(entries: list[Entry]) -> str:
|
||||
"""Everything the reply may quote: kuhy's messages and the fetched problem."""
|
||||
parts = []
|
||||
for e in entries:
|
||||
if e.get("type") != "user":
|
||||
continue
|
||||
parts.append(kuhy_text(e))
|
||||
content = _content(e)
|
||||
if not isinstance(content, str):
|
||||
parts.extend(
|
||||
text_of({"message": {"content": [c]}})
|
||||
for c in content
|
||||
if c.get("type") == "tool_result"
|
||||
)
|
||||
return _squash("\n".join(parts))
|
||||
|
||||
|
||||
def offending_snippets(reply: str, idents: set[str], allowed: str) -> list[str]:
|
||||
"""Code in `reply` that uses a starter identifier and is not a quote."""
|
||||
bad = []
|
||||
for snippet in CODE_RE.findall(reply):
|
||||
body = snippet.strip("`").strip()
|
||||
if body.startswith(LANG_PREFIXES):
|
||||
body = body.split("\n", 1)[1] if "\n" in body else ""
|
||||
if not re.search(r"[(=]|\.\.\.", body):
|
||||
continue
|
||||
if not any(re.search(rf"\b{re.escape(i)}\b", body) for i in idents):
|
||||
continue
|
||||
probe = _squash(body).removesuffix("...").strip()
|
||||
# Whole-token match: the harness has `...argsArr`; it must not admit `...args`.
|
||||
if probe and re.search(rf"(?<!\w){re.escape(probe)}(?!\w)", allowed):
|
||||
continue # quoting kuhy's code or the starter back at them
|
||||
bad.append(_squash(body)[:80])
|
||||
return bad
|
||||
76
leetcode_coach/leetcode_coach/gate_notes.py
Normal file
76
leetcode_coach/leetcode_coach/gate_notes.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""The one-line notes kuhy reads from the phase gate: req list or output shape."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from leetcode_coach import leak, shape
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leetcode_coach.req_check import Check
|
||||
from leetcode_coach.toolbox import Toolbox
|
||||
|
||||
|
||||
def property_line(prop: str, box: Toolbox) -> str:
|
||||
"""`prop: meaning`, or just `prop` when the meaning names an entry.
|
||||
|
||||
Some meanings illustrate with the operation itself (self-inverse:
|
||||
"a ^ x ^ x = a"); shown to kuhy that is the answer, not a property.
|
||||
"""
|
||||
meaning = box.properties[prop]
|
||||
return prop if leak.leaked_names(meaning, [], box) else f"{prop}: {meaning}"
|
||||
|
||||
|
||||
def _forced(what: str, result: Check) -> str:
|
||||
missing = ", ".join(result.missing)
|
||||
return f"[{what} still incomplete ({missing}) -- code accepted anyway]"
|
||||
|
||||
|
||||
def req_note(
|
||||
result: Check, tries: int, *, forced: bool, limit: int, box: Toolbox
|
||||
) -> str:
|
||||
if result.via == shape.VIA:
|
||||
return shape_note(result, tries, forced=forced, limit=limit)
|
||||
if result.verdict == "pass":
|
||||
return "[req list accepted -- code is open]"
|
||||
if result.verdict == "unverified":
|
||||
return "[req check unavailable -- continuing unverified, code is open]"
|
||||
if forced:
|
||||
return _forced("req list", result)
|
||||
props = "\n".join(f" - {property_line(p, box)}" for p in result.missing)
|
||||
return (
|
||||
f"[req list incomplete -- it does not yet say these properties:\n{props}\n"
|
||||
f" revise with req: ({tries} of {limit})]"
|
||||
)
|
||||
|
||||
|
||||
def shape_note(result: Check, tries: int, *, forced: bool, limit: int) -> str:
|
||||
if result.verdict == "pass":
|
||||
return "[output shape accepted -- code is open]"
|
||||
if forced:
|
||||
return _forced("output shape", result)
|
||||
lines = "\n".join(f" - {h}" for h in shape.hints(result.missing))
|
||||
return (
|
||||
f"[output shape incomplete -- it does not yet say:\n{lines}\n"
|
||||
f" revise with shape: ({tries} of {limit})]"
|
||||
)
|
||||
|
||||
|
||||
def refusal(tries: int, limit: int, *, sql: bool) -> str:
|
||||
if not tries:
|
||||
if sql:
|
||||
return (
|
||||
"[code held back: state the output shape first -- one message "
|
||||
"starting with shape: that says the columns, the rows and the "
|
||||
"grouping]"
|
||||
)
|
||||
return (
|
||||
"[code held back: write the requirement list first -- one message "
|
||||
"starting with req: that lists the properties the operation must "
|
||||
"have, without naming an operation or structure]"
|
||||
)
|
||||
gate = "output shape" if sql else "req list"
|
||||
return (
|
||||
f"[code held back: the {gate} is still incomplete -- revise it "
|
||||
f"with {'shape' if sql else 'req'}: ({tries} of {limit} so far)]"
|
||||
)
|
||||
62
leetcode_coach/leetcode_coach/guard_bridge.py
Normal file
62
leetcode_coach/leetcode_coach/guard_bridge.py
Normal file
@ -0,0 +1,62 @@
|
||||
"""The three read-only calls the coach borrows from leetcode-guard, on demand.
|
||||
|
||||
Without leetcode-guard installed (tutor server, CI) every other module still
|
||||
imports; these raise `GuardUnavailableError`, never a silent "nothing solved".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from typing import TYPE_CHECKING, Final, Protocol
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Sequence
|
||||
from types import ModuleType
|
||||
|
||||
class Submission(Protocol):
|
||||
title_slug: str
|
||||
timestamp: int
|
||||
|
||||
class SolveProbe(Protocol):
|
||||
@property
|
||||
def usable(self) -> bool: ...
|
||||
|
||||
reason: str
|
||||
submissions: Sequence[Submission]
|
||||
|
||||
|
||||
SETTINGS: Final = "leetcode_guard._settings"
|
||||
LIVE_SOLVED: Final = "leetcode_guard._live_solved"
|
||||
SUBMISSIONS: Final = "leetcode_guard._submissions"
|
||||
SNAPSHOT_AUTH: Final = "leetcode_guard._snapshot_auth"
|
||||
ALLOWED: Final = frozenset({SETTINGS, LIVE_SOLVED, SUBMISSIONS, SNAPSHOT_AUTH})
|
||||
|
||||
|
||||
class GuardUnavailableError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _load(name: str) -> ModuleType:
|
||||
try:
|
||||
return importlib.import_module(name)
|
||||
except ImportError as exc:
|
||||
msg = f"{name} needs leetcode-guard installed ({exc})"
|
||||
raise GuardUnavailableError(msg) from exc
|
||||
|
||||
|
||||
def solved_slugs(slugs: Sequence[str]) -> frozenset[str]:
|
||||
client = _load(SETTINGS).build_client()
|
||||
evidence = _load(LIVE_SOLVED).check_solved(client.post, list(slugs))
|
||||
return frozenset(evidence.solved)
|
||||
|
||||
|
||||
def recent_accepted() -> SolveProbe:
|
||||
client = _load(SETTINGS).build_client()
|
||||
probe: SolveProbe = _load(SUBMISSIONS).fetch_recent_ac(client.post, client.username)
|
||||
return probe
|
||||
|
||||
|
||||
def phone_id_token(app_name: str, *, timeout_seconds: float) -> Callable[[], str]:
|
||||
client = _load(SNAPSHOT_AUTH).connect(app_name, timeout_seconds=timeout_seconds)
|
||||
token: Callable[[], str] = client.auth.id_token
|
||||
return token
|
||||
@ -0,0 +1,3 @@
|
||||
"""Shim: the /leetcode Stop gate lives in ~/src/leetcode-guard (leetcode_coach.stop_gate)."""
|
||||
import os
|
||||
if __name__ == "__main__": os.execv("/usr/bin/python3", ["/usr/bin/python3", "-P", "-m", "leetcode_coach.stop_gate"])
|
||||
78
leetcode_coach/leetcode_coach/how_to.py
Normal file
78
leetcode_coach/leetcode_coach/how_to.py
Normal file
@ -0,0 +1,78 @@
|
||||
"""The commands and the method, written once.
|
||||
|
||||
The status app's Coach tab shows these next to an empty session list, and
|
||||
``DOCS-how-to.md`` (which SKILL.md points at) quotes the same lines verbatim;
|
||||
a test fails when the two differ, which is the point of having one module. Nothing
|
||||
here names a toolbox operation: the Stop hook bounces that before kuhy's
|
||||
first code, and the same words on a screen would teach skipping the search.
|
||||
|
||||
Stdlib only, like ``progress``: the status snapshot imports this every
|
||||
minute on the system python.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
|
||||
class Command(NamedTuple):
|
||||
"""One thing kuhy can type, and what it does."""
|
||||
|
||||
command: str
|
||||
meaning: str
|
||||
|
||||
|
||||
class Step(NamedTuple):
|
||||
"""One step of the method."""
|
||||
|
||||
name: str
|
||||
text: str
|
||||
|
||||
|
||||
COMMANDS = (
|
||||
Command(
|
||||
"leetcode --cluster <name>",
|
||||
"Serve the next problem of a concept cluster (a due re-test comes first).",
|
||||
),
|
||||
Command("leetcode <url>", "Coach one problem, from its LeetCode URL or slug."),
|
||||
Command("leetcode due", "List the cold re-tests that are due."),
|
||||
Command(
|
||||
"leetcode report",
|
||||
"One row per session: requirements before code, hint rung, reveal.",
|
||||
),
|
||||
)
|
||||
STEPS = (
|
||||
Step("Constraint", "Turn the hard constraint into a rule for the design."),
|
||||
Step(
|
||||
"Requirements",
|
||||
"List what the operation must do, as properties, never by name.",
|
||||
),
|
||||
Step("Toolbox", "Search the toolbox for an operation with those properties."),
|
||||
Step("Post-mortem", "Say which hint gave which requirement, then make the cards."),
|
||||
)
|
||||
NEXT_NOTE = (
|
||||
"The command skips problems LeetCode already shows as Accepted, "
|
||||
"so it may serve a later one than listed here."
|
||||
)
|
||||
|
||||
|
||||
def cluster_command(name: str) -> str:
|
||||
"""The command that starts cluster ``name``."""
|
||||
return f"leetcode --cluster {name}"
|
||||
|
||||
|
||||
def retest_command(slug: str) -> str:
|
||||
"""The command that starts the cold re-test of ``slug``."""
|
||||
return f"leetcode --retest {slug}"
|
||||
|
||||
|
||||
def block(first_cluster: str | None) -> dict[str, Any]:
|
||||
"""The snapshot's ``coach.how_to``; ``first_cluster`` names the first command."""
|
||||
return {
|
||||
"commands": [c._asdict() for c in COMMANDS],
|
||||
"steps": [s._asdict() for s in STEPS],
|
||||
"next_note": NEXT_NOTE,
|
||||
"first_command": (
|
||||
None if first_cluster is None else cluster_command(first_cluster)
|
||||
),
|
||||
}
|
||||
44
leetcode_coach/leetcode_coach/leak.py
Normal file
44
leetcode_coach/leetcode_coach/leak.py
Normal file
@ -0,0 +1,44 @@
|
||||
r"""Which toolbox entries a coach reply names (DOCS-coach-spec.md decision 7).
|
||||
|
||||
Until kuhy's first code, a reply that names an operation from the toolbox --
|
||||
its name or any alias, e.g. "XOR", "^", "hash map" -- hands over step 3 of the
|
||||
method (searching the toolbox by properties). Shared by the Stop hook
|
||||
(`stop_gate`) and the offline coach (`local_coach`), so both judge alike.
|
||||
|
||||
An entry kuhy already named is free for the whole session, under every
|
||||
alias: after "is it XOR?" the honest answer has to be able to say XOR, or
|
||||
the rewrite can never pass and the gate loops. Only kuhy's own words count:
|
||||
the fetched statement carries LeetCode's topic tags and hints ("Hash
|
||||
Table", "Sliding Window"), so exempting it would pre-clear the answer.
|
||||
|
||||
Matching is case-insensitive on whole tokens. ``\b`` does not work next to a
|
||||
symbol alias like ``^``, so the boundary is "no word character either side":
|
||||
"a ^ b" matches, "2^3" (a power) and "xorshift" do not.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leetcode_coach.toolbox import Toolbox
|
||||
|
||||
|
||||
def _pattern(name: str) -> re.Pattern[str]:
|
||||
words = r"\s+".join(re.escape(w) for w in name.split())
|
||||
return re.compile(rf"(?<!\w){words}(?!\w)", re.IGNORECASE)
|
||||
|
||||
|
||||
def _named(text: str, names: tuple[str, ...]) -> bool:
|
||||
return any(_pattern(n).search(text) for n in names if n.strip())
|
||||
|
||||
|
||||
def leaked_names(reply: str, allowed: list[str], box: Toolbox) -> list[str]:
|
||||
"""Entry names in `reply` that nothing in `allowed` already named."""
|
||||
seen = "\n".join(allowed)
|
||||
return [
|
||||
e.name
|
||||
for e in box.entries
|
||||
if _named(reply, e.names()) and not _named(seen, e.names())
|
||||
]
|
||||
17
leetcode_coach/leetcode_coach/leetcode
Executable file
17
leetcode_coach/leetcode_coach/leetcode
Executable file
@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# leetcode — coaching session in print mode, on the cheapest model.
|
||||
# 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...]
|
||||
#
|
||||
# Symlinked from ~/.local/bin/leetcode. The package is found through
|
||||
# install.sh's editable install, like the Stop-hook shim; no PYTHONPATH here,
|
||||
# because the REPL passes its environment on to `claude -p` and every hook and
|
||||
# Bash call of the coached session would inherit it. -P keeps cwd off sys.path.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
exec /usr/bin/python3 -P -m leetcode_coach.leetcode_repl "$@"
|
||||
129
leetcode_coach/leetcode_coach/leetcode_repl.py
Executable file
129
leetcode_coach/leetcode_coach/leetcode_repl.py
Executable file
@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Coaching REPL for /leetcode that only ever shows the post-gate reply.
|
||||
|
||||
In the interactive TUI a Stop hook runs after the reply has streamed, so a
|
||||
blocked reply (one that hands kuhy a pasteable line) is already on screen
|
||||
before the rewrite appears. `claude -p` returns nothing until the hooks are
|
||||
done, so this loop is the only client where the no-solution gate actually
|
||||
withholds text from the human. Each turn is one `claude -p --resume` call.
|
||||
|
||||
Every block first passes the req-before-code phase gate (`phase.py`): code
|
||||
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.
|
||||
|
||||
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.
|
||||
`leetcode report` prints the per-problem method report (`report.py`).
|
||||
Started by the `leetcode` launcher as `python3 -m leetcode_coach.leetcode_repl`;
|
||||
its prints ARE the session (T201 exemption in pyproject.toml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from leetcode_coach import cluster_cli, local_session, phase, report
|
||||
from leetcode_coach.claude_cli import ask, is_limit_hit
|
||||
|
||||
# Named, not __name__: under `-m` this module is `__main__`, which would escape
|
||||
# the package logger's NullHandler and print the warning to the session.
|
||||
_LOG = logging.getLogger("leetcode_coach.leetcode_repl")
|
||||
|
||||
|
||||
def read_block() -> str | None:
|
||||
"""Lines until an empty one; None on EOF with nothing typed."""
|
||||
print("\nyou> ", end="", flush=True)
|
||||
lines: list[str] = []
|
||||
while True:
|
||||
try:
|
||||
line = input()
|
||||
except EOFError:
|
||||
# Ctrl-D is how kuhy leaves; benign, logged only to satisfy the
|
||||
# repo's no-silent-except rule (the package logger is silent).
|
||||
_LOG.warning("stdin closed (Ctrl-D); ending the block")
|
||||
return "\n".join(lines) if lines else None
|
||||
if not line.strip():
|
||||
if lines:
|
||||
return "\n".join(lines)
|
||||
continue
|
||||
lines.append(line)
|
||||
|
||||
|
||||
def _screen(gate: phase.PhaseGate, block: str) -> str | None:
|
||||
"""The block to send the coach, or None when the phase gate refuses it."""
|
||||
sent, note = gate.screen(block)
|
||||
if note:
|
||||
print(note)
|
||||
return sent
|
||||
|
||||
|
||||
def run_claude(model: str, problem: list[str]) -> int:
|
||||
"""The Claude session; hands over to the local model on a usage limit."""
|
||||
gate = phase.PhaseGate.open(problem[0])
|
||||
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)
|
||||
session = first.get("session_id")
|
||||
print(gate.after_reply(str(first.get("result", ""))))
|
||||
if not session:
|
||||
return 1
|
||||
history = [
|
||||
{"role": "user", "content": opener},
|
||||
{"role": "assistant", "content": str(first.get("result", ""))},
|
||||
]
|
||||
while True:
|
||||
block = read_block()
|
||||
if block is None or local_session.is_quit(block):
|
||||
return 0
|
||||
if (sent := _screen(gate, block)) is None:
|
||||
continue
|
||||
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)
|
||||
print(gate.after_reply(str(reply.get("result", ""))))
|
||||
history += [
|
||||
{"role": "user", "content": sent},
|
||||
{"role": "assistant", "content": str(reply.get("result", ""))},
|
||||
]
|
||||
|
||||
|
||||
def start_session(problem: list[str], *, local: bool) -> int:
|
||||
"""One coaching session for `<url-or-slug> [stuck on...]`."""
|
||||
if local:
|
||||
opener = local_session.opening_message(problem[1:])
|
||||
gate = phase.PhaseGate.open(problem[0])
|
||||
return local_session.run(problem[0], [], opener, read_block, gate=gate)
|
||||
return run_claude(os.environ.get("LEETCODE_MODEL", "sonnet"), problem)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
"""Parse `[--local] <url-or-slug> [stuck on...]` (or `report`) and run it."""
|
||||
local = "--local" in argv
|
||||
args = [a for a in argv if a != "--local"]
|
||||
if args[:1] == [report.COMMAND]:
|
||||
return report.main(args[1:])
|
||||
if not args or args[0] in {"-h", "--help"}:
|
||||
print("Usage: leetcode [--local] <url-or-slug> [what you are stuck on...]")
|
||||
print(" LEETCODE_MODEL=opus leetcode ... to use a stronger model")
|
||||
print(" --local coach on the local Ollama model (free, offline)")
|
||||
print(" leetcode due | --cluster <name> | --retest <slug> (--dry-run)")
|
||||
print(" leetcode report req-before-code, max rung, reveal per problem")
|
||||
return 0
|
||||
if args[0] in cluster_cli.COMMANDS:
|
||||
return cluster_cli.main(args, functools.partial(start_session, local=local))
|
||||
return start_session(args, local=local)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
155
leetcode_coach/leetcode_coach/local_backend.py
Normal file
155
leetcode_coach/leetcode_coach/local_backend.py
Normal file
@ -0,0 +1,155 @@
|
||||
"""Ollama transport for the offline /leetcode coach.
|
||||
|
||||
One non-streaming `/api/chat` call per reply, so the no-solution gate can judge
|
||||
the whole reply before anything reaches the screen -- the same reason the
|
||||
Claude path uses `claude -p`. Thinking is switched off (`think: false`) and any
|
||||
`<think>` block that leaks anyway is stripped before the gate sees the text.
|
||||
|
||||
Ollama silently truncates a prompt longer than `num_ctx` from the front, which
|
||||
would drop the system prompt (the coaching rules) without an error. So the
|
||||
context is set explicitly and both the client-side estimate and the server's
|
||||
`prompt_eval_count` are checked against it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
import urllib.request
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
OLLAMA_URL = "http://localhost:11434"
|
||||
# The instruct build, not plain `qwen3:30b-a3b`: that tag is the 2507 Thinking
|
||||
# build, which ignores `think: false` and `/no_think` and writes ~1k tokens of
|
||||
# reasoning into `content` before every reply (measured 2026-10-03: 66 s turns).
|
||||
MODEL = "qwen3:30b-a3b-instruct-2507-q4_K_M"
|
||||
NUM_CTX = 16384
|
||||
KEEP_ALIVE = "5m" # free the 3090 soon after a session ends
|
||||
TEMPERATURE = 0.4
|
||||
REQUEST_TIMEOUT_S = 300.0 # the first call also loads ~18 GB into VRAM
|
||||
CHARS_PER_TOKEN = 3.0 # pessimistic, so the estimate trips before Ollama truncates
|
||||
GPU_HOG_MIB = 2048
|
||||
THINK_RE = re.compile(r"<think>.*?</think>\s*", re.DOTALL)
|
||||
|
||||
|
||||
class ContextOverflowError(RuntimeError):
|
||||
"""The conversation no longer fits in `NUM_CTX`; the rules would be cut."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LocalReply:
|
||||
"""One model reply, already stripped of thinking."""
|
||||
|
||||
text: str
|
||||
seconds: float
|
||||
prompt_tokens: int
|
||||
|
||||
|
||||
def strip_think(text: str) -> str:
|
||||
"""Drop `<think>...</think>` blocks, a dangling close and a dangling open."""
|
||||
text = THINK_RE.sub("", text)
|
||||
if "</think>" in text: # a thinking build opens the block in its template
|
||||
text = text.rsplit("</think>", 1)[1]
|
||||
if "<think>" in text:
|
||||
text = text.split("<think>", 1)[0]
|
||||
return text.strip()
|
||||
|
||||
|
||||
def http_json(
|
||||
url: str, payload: dict[str, Any] | None, timeout: float
|
||||
) -> dict[str, Any]:
|
||||
"""POST `payload` as JSON (GET when None) and decode the JSON answer."""
|
||||
if not url.startswith(OLLAMA_URL + "/"):
|
||||
msg = f"refusing a non-Ollama URL: {url}"
|
||||
raise ValueError(msg)
|
||||
data = None if payload is None else json.dumps(payload).encode()
|
||||
req = urllib.request.Request(
|
||||
url, data=data, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp: # localhost only
|
||||
answer: dict[str, Any] = json.loads(resp.read().decode())
|
||||
return answer
|
||||
|
||||
|
||||
def estimate_tokens(messages: list[dict[str, str]]) -> int:
|
||||
"""Upper-ish bound on prompt tokens, from character count."""
|
||||
return int(sum(len(m["content"]) for m in messages) / CHARS_PER_TOKEN)
|
||||
|
||||
|
||||
def chat(
|
||||
messages: list[dict[str, str]],
|
||||
*,
|
||||
post: Callable[[str, dict[str, Any] | None, float], dict[str, Any]] = http_json,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
timeout: float = REQUEST_TIMEOUT_S,
|
||||
) -> LocalReply:
|
||||
"""Ask the local model for the next assistant message.
|
||||
|
||||
`timeout` bounds the HTTP call; the relay passes less than the default so
|
||||
a whole request fits its cap (DOCS-coach-relay.md section 1).
|
||||
|
||||
Raises:
|
||||
ContextOverflowError: when the prompt would not fit in `NUM_CTX`.
|
||||
"""
|
||||
if estimate_tokens(messages) >= NUM_CTX:
|
||||
msg = f"conversation too long for num_ctx={NUM_CTX}; start a new session"
|
||||
raise ContextOverflowError(msg)
|
||||
payload = {
|
||||
"model": MODEL,
|
||||
"messages": messages,
|
||||
"stream": False,
|
||||
"think": False,
|
||||
"keep_alive": KEEP_ALIVE,
|
||||
"options": {"num_ctx": NUM_CTX, "temperature": TEMPERATURE},
|
||||
}
|
||||
start = clock()
|
||||
data = post(f"{OLLAMA_URL}/api/chat", payload, timeout)
|
||||
seconds = clock() - start
|
||||
prompt_tokens = int(data.get("prompt_eval_count") or 0)
|
||||
if prompt_tokens >= NUM_CTX:
|
||||
msg = f"Ollama evaluated {prompt_tokens} prompt tokens >= num_ctx={NUM_CTX}"
|
||||
raise ContextOverflowError(msg)
|
||||
text = strip_think(str(data.get("message", {}).get("content") or ""))
|
||||
return LocalReply(text=text, seconds=seconds, prompt_tokens=prompt_tokens)
|
||||
|
||||
|
||||
def model_loaded(
|
||||
post: Callable[[str, dict[str, Any] | None, float], dict[str, Any]] = http_json,
|
||||
) -> bool:
|
||||
"""Whether `MODEL` is already resident (then loading costs nothing new)."""
|
||||
data = post(f"{OLLAMA_URL}/api/ps", None, 5.0)
|
||||
return any(m.get("name") == MODEL for m in data.get("models", []))
|
||||
|
||||
|
||||
def gpu_hogs(
|
||||
run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
||||
) -> list[tuple[str, int]]:
|
||||
"""Non-Ollama GPU processes holding more than `GPU_HOG_MIB` (likely a game).
|
||||
|
||||
Loading an 18 GB model next to one would either starve it or spill the
|
||||
model onto the CPU, so the REPL asks first.
|
||||
"""
|
||||
proc = run(
|
||||
[
|
||||
"nvidia-smi",
|
||||
"--query-compute-apps=process_name,used_memory",
|
||||
"--format=csv,noheader,nounits",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
hogs = []
|
||||
for line in proc.stdout.splitlines():
|
||||
name, _, mib = line.rpartition(",")
|
||||
if not mib.strip().isdigit() or "ollama" in name.lower():
|
||||
continue
|
||||
if int(mib) > GPU_HOG_MIB:
|
||||
hogs.append((name.strip(), int(mib)))
|
||||
return hogs
|
||||
64
leetcode_coach/leetcode_coach/local_cards.py
Normal file
64
leetcode_coach/leetcode_coach/local_cards.py
Normal file
@ -0,0 +1,64 @@
|
||||
"""Post-mortem cards from a local reply: extract the ```cards block, build the deck.
|
||||
|
||||
The local model has no tools, so instead of the Bash call SKILL.md describes it
|
||||
emits the JSON in a fenced ```cards block; this module lifts it out of the
|
||||
displayed text and pipes it to `make_cards`, whose validation is unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from leetcode_coach import toolbox_cards
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
CARDS_RE = re.compile(r"```cards\s*\n(.*?)```", re.DOTALL)
|
||||
|
||||
|
||||
def split_cards(reply: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Remove a ```cards block from `reply`; return (display text, parsed JSON)."""
|
||||
match = CARDS_RE.search(reply)
|
||||
if match is None:
|
||||
return reply, None
|
||||
display = (reply[: match.start()] + reply[match.end() :]).strip()
|
||||
try:
|
||||
payload = json.loads(match.group(1))
|
||||
except json.JSONDecodeError as exc:
|
||||
_LOG.warning("the cards block is not JSON: %s", exc)
|
||||
return display, {"invalid": match.group(1)}
|
||||
return display, payload if isinstance(payload, dict) else {"invalid": payload}
|
||||
|
||||
|
||||
def deliver_cards(
|
||||
payload: dict[str, Any],
|
||||
run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
||||
) -> tuple[bool, str]:
|
||||
"""Pipe the cards to the card builder; (accepted, its stdout+stderr)."""
|
||||
if "invalid" in payload:
|
||||
return False, f"cards block is not a JSON object: {payload['invalid']!r}"
|
||||
if "toolbox" in payload:
|
||||
# Property -> operation cards (decision 11) come from toolbox.json,
|
||||
# so the local model names entries instead of typing fronts.
|
||||
try:
|
||||
cards = toolbox_cards.cards_for(list(payload["toolbox"]))
|
||||
except KeyError as exc:
|
||||
_LOG.warning("cards block names an unknown entry: %s", exc)
|
||||
return False, str(exc.args[0])
|
||||
payload = {"slug": toolbox_cards.SLUG, "cards": cards}
|
||||
proc = run(
|
||||
[sys.executable, "-m", "leetcode_coach.make_cards", "-"],
|
||||
input=json.dumps(payload),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return proc.returncode == 0, (proc.stdout + proc.stderr).strip()
|
||||
130
leetcode_coach/leetcode_coach/local_coach.py
Normal file
130
leetcode_coach/leetcode_coach/local_coach.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""The offline /leetcode coach: SKILL.md rules, the no-solution gate, cards.
|
||||
|
||||
Claude Code enforces the gate as a Stop hook; there is no harness here, so the
|
||||
same detector (`gate_detector`, which the Stop hook also uses) runs on every
|
||||
local reply before it is shown. A blocked reply is sent back with the gate's
|
||||
reason, like the hook's `{"decision": "block"}`, and after `MAX_TRIES` failed
|
||||
drafts a fixed safe message is shown instead -- unlike the hook, which fails
|
||||
open, because a small local model is likelier to keep leaking.
|
||||
|
||||
The model has no tools: the statement is prefetched into the system prompt,
|
||||
and cards come back as a ```cards block (`local_cards.py`). "End with exactly
|
||||
one task" is checked here too, as a soft gate: a reply that fails only that is
|
||||
regenerated, and after `MAX_TRIES` the last code-free draft is shown anyway.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from leetcode_coach import gate_detector, local_backend, local_cards, local_prompt
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
SKILL_DIR = Path(__file__).resolve().parent
|
||||
MAX_TRIES = 3
|
||||
|
||||
|
||||
def gate_findings(reply: str, statement: str, user_texts: list[str]) -> list[str]:
|
||||
"""Snippets in `reply` the hook would block, judged on synthetic entries."""
|
||||
if any(t.strip() == "reveal" for t in user_texts):
|
||||
return []
|
||||
entries = [
|
||||
{"type": "user", "message": {"content": text}}
|
||||
for text in [statement, *user_texts]
|
||||
]
|
||||
idents = gate_detector.starter_identifiers(entries)
|
||||
if not idents:
|
||||
return []
|
||||
allowed = gate_detector.allowed_text(entries)
|
||||
return list(gate_detector.offending_snippets(reply, idents, allowed))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Turn:
|
||||
"""What one user message produced."""
|
||||
|
||||
text: str
|
||||
seconds: float
|
||||
attempts: int
|
||||
withheld: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class LocalCoach:
|
||||
"""A local coaching conversation, gate applied to every reply."""
|
||||
|
||||
statement: str
|
||||
history: list[dict[str, str]]
|
||||
chat: Callable[[list[dict[str, str]]], local_backend.LocalReply] = (
|
||||
local_backend.chat
|
||||
)
|
||||
leak_guard: Callable[[str, list[str]], list[str]] | None = None
|
||||
"""Toolbox entries a draft names too early (`PhaseGate.leaks`); off if None."""
|
||||
|
||||
@classmethod
|
||||
def start(
|
||||
cls, statement: str, history: list[dict[str, str]] | None = None
|
||||
) -> LocalCoach:
|
||||
"""A coach seeded with SKILL.md and optionally a prior (Claude) history."""
|
||||
skill = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
|
||||
prompt = local_prompt.system_prompt(skill, statement)
|
||||
system = {"role": "system", "content": prompt}
|
||||
return cls(statement=statement, history=[system, *(history or [])])
|
||||
|
||||
def user_texts(self) -> list[str]:
|
||||
"""Everything kuhy typed so far."""
|
||||
return [m["content"] for m in self.history if m["role"] == "user"]
|
||||
|
||||
@staticmethod
|
||||
def _with_reminder(history: list[dict[str, str]]) -> list[dict[str, str]]:
|
||||
"""`history` with `REMINDER` on its last message (a copy; history is kept)."""
|
||||
last = history[-1]
|
||||
reminded = {**last, "content": last["content"] + local_prompt.REMINDER}
|
||||
return [*history[:-1], reminded]
|
||||
|
||||
def respond(self, text: str) -> Turn:
|
||||
"""Append kuhy's message and return the first reply that passes the gate."""
|
||||
self.history.append({"role": "user", "content": text})
|
||||
scratch: list[dict[str, str]] = []
|
||||
total = 0.0
|
||||
last_clean: str | None = None
|
||||
for attempt in range(1, MAX_TRIES + 1):
|
||||
reply = self.chat(self._with_reminder(self.history) + scratch)
|
||||
total += reply.seconds
|
||||
display, payload = local_cards.split_cards(reply.text)
|
||||
bad = gate_findings(display, self.statement, self.user_texts())
|
||||
named = self._leaks(display) if not bad else []
|
||||
if bad:
|
||||
snippets = "; ".join(f"`{b}`" for b in bad)
|
||||
reason = local_prompt.GATE_REASON_CODE.format(snippets=snippets)
|
||||
elif named:
|
||||
reason = local_prompt.GATE_REASON_LEAK.format(names=", ".join(named))
|
||||
else:
|
||||
last_clean = reply.text
|
||||
prose, _rung = local_prompt.split_rung(display)
|
||||
if payload is not None or local_prompt.ends_with_one_task(prose):
|
||||
return self._accept(reply.text, total, attempt)
|
||||
reason = local_prompt.GATE_REASON_SHAPE
|
||||
scratch += [
|
||||
{"role": "assistant", "content": reply.text},
|
||||
{"role": "user", "content": reason},
|
||||
]
|
||||
if last_clean is not None: # shape is a soft rule; code is the hard one
|
||||
return self._accept(last_clean, total, MAX_TRIES)
|
||||
self.history.append({"role": "assistant", "content": local_prompt.WITHHELD})
|
||||
return Turn(local_prompt.WITHHELD, total, MAX_TRIES, withheld=True)
|
||||
|
||||
def _leaks(self, display: str) -> list[str]:
|
||||
"""Entry names the draft gives away, per the session's leak guard."""
|
||||
if self.leak_guard is None:
|
||||
return []
|
||||
return self.leak_guard(display, self.user_texts())
|
||||
|
||||
def _accept(self, text: str, seconds: float, attempts: int) -> Turn:
|
||||
"""Record `text` as the assistant's reply and wrap it as a Turn."""
|
||||
self.history.append({"role": "assistant", "content": text})
|
||||
return Turn(text, seconds, attempts, withheld=False)
|
||||
117
leetcode_coach/leetcode_coach/local_prompt.py
Normal file
117
leetcode_coach/leetcode_coach/local_prompt.py
Normal file
@ -0,0 +1,117 @@
|
||||
"""What the offline coach tells the local model, and the one-task shape check.
|
||||
|
||||
Split out of `local_coach.py` for the 250-line cap; texts are unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
WITHHELD = (
|
||||
"(My draft gave away code, so I held it back.) Let's go one step smaller: "
|
||||
"in your own words, what does your current approach do with each number "
|
||||
"as it reads it?"
|
||||
)
|
||||
REMINDER = (
|
||||
"\n\n[coach reminder, not from kuhy: one hint rung at most; never state "
|
||||
"the key insight, the data structure or the fix; never answer your own "
|
||||
"question; no code with the starter's names; end with exactly one "
|
||||
"question or one instruction.]"
|
||||
)
|
||||
"""Appended to the newest user message for the model only -- never stored in
|
||||
`history` and never seen by the gate. A 3B-active model follows the rules at
|
||||
the top of a 3k-token system prompt far less reliably than a line next to the
|
||||
question it is answering (measured on the eval: it named the fix in prose)."""
|
||||
LOCAL_NOTES = """
|
||||
## Local client notes (you are running offline, not in Claude Code)
|
||||
|
||||
- You have NO tools. The problem statement and starter code are already below;
|
||||
never say you will fetch, run or test anything.
|
||||
- Write plain markdown for a terminal. No emoji.
|
||||
- Never write code that uses the starter's function or parameter names unless
|
||||
kuhy has typed `reveal`. A client-side gate rejects such replies.
|
||||
- Never name an operation, data structure or algorithm before kuhy has
|
||||
written code (unless kuhy named it first) -- not even inside a calibration
|
||||
question. Ask about the properties kuhy listed instead.
|
||||
- The LAST line of every reply is exactly one question or one instruction for
|
||||
kuhy; only the `<!-- rung:Hn -->` line may follow it. ONE question mark in
|
||||
the closing paragraph: never stack questions ("What happens? Why?").
|
||||
- Never state the key insight, the fix, or what the code "must" do. On a buggy
|
||||
paste, describe what the data does on one concrete input from the examples
|
||||
("with [3,2,4] and target 6, at i=0 `seen` already holds 3 when the lookup
|
||||
runs") and ask what that lookup returns. kuhy names the fix, not you.
|
||||
- When kuhy gives up or begs for the answer, do not just point at `reveal`:
|
||||
drop back one rung and end with a smaller question. You may mention once
|
||||
that typing `reveal` ends the exercise.
|
||||
- Never repeat a previous reply. Answer what kuhy just wrote.
|
||||
- For the post-mortem cards (section 5b), do NOT print a Bash command. Emit one
|
||||
fenced block tagged `cards` naming the toolbox entries, e.g.
|
||||
```cards
|
||||
{"toolbox": ["<entry name>", "<entry name>"]}
|
||||
```
|
||||
The client builds the property cards and shows the result. Never append to
|
||||
the toolbox from this client: tell kuhy to do it in a Claude session.
|
||||
|
||||
# The problem (already fetched)
|
||||
|
||||
"""
|
||||
GATE_REASON_CODE = (
|
||||
"leetcode gate: your reply hands kuhy code they can paste -- {snippets}. "
|
||||
"Rewrite it without that snippet: describe the data or "
|
||||
"name the construct, and keep the one question at the end."
|
||||
)
|
||||
GATE_REASON_LEAK = (
|
||||
"leetcode gate: your reply names {names} before kuhy has written any code. "
|
||||
"Rewrite it without naming an operation or structure: ask about the "
|
||||
"properties the operation needs, and keep the one question at the end."
|
||||
)
|
||||
GATE_REASON_SHAPE = (
|
||||
"leetcode gate: end with exactly ONE question or ONE "
|
||||
"instruction -- your closing paragraph asks more than one "
|
||||
"thing or ends on neither. Rewrite it."
|
||||
)
|
||||
RUNG_RE = re.compile(r"<!--\s*rung:\s*(H[0-3])\s*-->")
|
||||
"""The coach's trailing hint-rung marker (SKILL.md section 3); logged, never shown."""
|
||||
IMPERATIVE = re.compile(
|
||||
r"^(try|write|predict|explain|tell|describe|trace|run|paste|list|sketch|"
|
||||
r"walk|show|give|say|name|work|think|check|change|fix|look|answer|type|"
|
||||
r"fill|pick|do)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def system_prompt(skill_md: str, statement: str) -> str:
|
||||
"""SKILL.md minus frontmatter, fetch step and model gate, plus the problem."""
|
||||
body = skill_md.split("\n---\n", 1)[1] if skill_md.startswith("---") else skill_md
|
||||
body = re.sub(r"## 1\. Fetch the problem.*?(?=\n## 2\.)", "", body, flags=re.DOTALL)
|
||||
body = body.split("\n## Model and client", 1)[0]
|
||||
return body.strip() + "\n" + LOCAL_NOTES + statement.strip() + "\n"
|
||||
|
||||
|
||||
def ends_with_one_task(text: str) -> bool:
|
||||
"""Closing paragraph asks at most one question and ends on a task.
|
||||
|
||||
The task is the final sentence: a question, or an imperative ("Predict
|
||||
before I tell you."). A question followed by the instruction to answer it
|
||||
is still one task; two question marks are two. Code blocks are not prose,
|
||||
and a quoted question ("has this been seen?") is not a second question.
|
||||
"""
|
||||
prose = re.sub(r"```.*?```", "\n\n", text, flags=re.DOTALL)
|
||||
paras = [p.strip() for p in re.split(r"\n\s*\n", prose) if p.strip()]
|
||||
if not paras:
|
||||
return False
|
||||
last = re.sub(r"\"[^\"]*\"|“[^”]*”", "it", paras[-1])
|
||||
last = re.sub(r"[*_>`()]", "", last).strip()
|
||||
if last.count("?") > 1:
|
||||
return False
|
||||
sentences = [x for x in re.split(r"(?<=[.?!])\s+", last) if x.strip()]
|
||||
final = sentences[-1].strip()
|
||||
return final.endswith("?") or bool(IMPERATIVE.match(final))
|
||||
|
||||
|
||||
def split_rung(text: str) -> tuple[str, str | None]:
|
||||
"""`text` without its ``<!-- rung:Hn -->`` markers, and the last rung named."""
|
||||
rungs = RUNG_RE.findall(text)
|
||||
if not rungs:
|
||||
return text, None
|
||||
return RUNG_RE.sub("", text).strip(), rungs[-1]
|
||||
163
leetcode_coach/leetcode_coach/local_session.py
Normal file
163
leetcode_coach/leetcode_coach/local_session.py
Normal file
@ -0,0 +1,163 @@
|
||||
"""Run a /leetcode coaching loop on the local model.
|
||||
|
||||
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).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
import urllib.error
|
||||
|
||||
from leetcode_coach import local_backend, local_cards, local_coach
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach import phase
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
CARD_RETRIES = 2
|
||||
FETCH_PREMIUM = 2
|
||||
|
||||
|
||||
def opening_message(stuck: list[str]) -> str:
|
||||
"""The first user message, standing in for `/leetcode <url> [stuck on]`."""
|
||||
said = " ".join(stuck).strip()
|
||||
return "Start the session. " + (
|
||||
f"What I'm stuck on: {said}" if said else "I have not said what I'm stuck on."
|
||||
)
|
||||
|
||||
|
||||
def is_quit(block: str) -> bool:
|
||||
"""An explicit request to leave."""
|
||||
return block.strip().lower() in {"quit", "exit"}
|
||||
|
||||
|
||||
def _run_fetcher(
|
||||
problem: str, runner: Callable[..., subprocess.CompletedProcess[str]]
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
return runner(
|
||||
[sys.executable, str(local_coach.SKILL_DIR / "fetch_problem.py"), problem],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def fetched_statement(
|
||||
problem: str,
|
||||
runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
||||
) -> str | None:
|
||||
"""Statement + starter code, or None when it cannot be fetched (no prompt)."""
|
||||
proc = _run_fetcher(problem, runner)
|
||||
return proc.stdout if proc.returncode == 0 else None
|
||||
|
||||
|
||||
def fetch_statement(
|
||||
problem: str,
|
||||
read: Callable[[], str | None],
|
||||
runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
||||
) -> str | None:
|
||||
"""Statement + starter code, or whatever kuhy pastes when it cannot be fetched."""
|
||||
proc = _run_fetcher(problem, runner)
|
||||
if proc.returncode == 0:
|
||||
return proc.stdout
|
||||
why = "premium or unknown problem" if proc.returncode == FETCH_PREMIUM else ""
|
||||
print(f"[could not fetch the problem: {why or proc.stderr.strip()}]")
|
||||
print("Paste the statement and starter code, then an empty line:")
|
||||
return read()
|
||||
|
||||
|
||||
def confirm_gpu(ask: Callable[[str], str] = input) -> bool:
|
||||
"""Ask before loading ~18 GB of VRAM next to another GPU-heavy process."""
|
||||
if local_backend.model_loaded():
|
||||
return True
|
||||
hogs = local_backend.gpu_hogs()
|
||||
if not hogs:
|
||||
return True
|
||||
print("[the GPU is busy -- loading the local model would compete with:]")
|
||||
for name, mib in hogs:
|
||||
print(f" {name} {mib} MiB")
|
||||
answer = ask(f"Load {local_backend.MODEL} anyway? [y/N] ")
|
||||
return answer.strip().lower() in {"y", "yes"}
|
||||
|
||||
|
||||
def show(
|
||||
turn: local_coach.Turn,
|
||||
coach: local_coach.LocalCoach,
|
||||
gate: phase.PhaseGate | None = None,
|
||||
) -> None:
|
||||
"""Print one reply; build its cards deck, feeding rejections back."""
|
||||
for _ in range(CARD_RETRIES + 1):
|
||||
display, payload = local_cards.split_cards(turn.text)
|
||||
print(gate.after_reply(display) if gate else display)
|
||||
if payload is None:
|
||||
return
|
||||
ok, out = local_cards.deliver_cards(payload)
|
||||
print(out)
|
||||
if ok:
|
||||
return
|
||||
print("\n...", flush=True)
|
||||
turn = coach.respond(
|
||||
f"make_cards.py rejected the cards:\n{out}\n"
|
||||
"Fix the named card and emit the whole ```cards block again."
|
||||
)
|
||||
|
||||
|
||||
def _screen(gate: phase.PhaseGate | None, block: str) -> str | None:
|
||||
"""The block to send the coach (None when the phase gate refuses it)."""
|
||||
if gate is None:
|
||||
return block
|
||||
sent, note = gate.screen(block)
|
||||
if note:
|
||||
print(note)
|
||||
return sent
|
||||
|
||||
|
||||
def run(
|
||||
problem: str,
|
||||
history: list[dict[str, str]],
|
||||
first: str,
|
||||
read: Callable[[], str | None],
|
||||
gate: phase.PhaseGate | None = None,
|
||||
) -> int:
|
||||
"""Coach locally until kuhy quits. `first` is sent before reading input.
|
||||
|
||||
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).
|
||||
"""
|
||||
statement = fetch_statement(problem, read)
|
||||
if not statement:
|
||||
return 1
|
||||
try:
|
||||
if not confirm_gpu():
|
||||
print("[not loading the local model]")
|
||||
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 (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}]")
|
||||
print("[start it with: systemctl start ollama]")
|
||||
return 1
|
||||
except local_backend.ContextOverflowError as exc:
|
||||
_LOG.warning("local session ended: %s", exc)
|
||||
print(f"[{exc}]")
|
||||
return 1
|
||||
return 0
|
||||
189
leetcode_coach/leetcode_coach/make_cards.py
Executable file
189
leetcode_coach/leetcode_coach/make_cards.py
Executable file
@ -0,0 +1,189 @@
|
||||
#!/usr/bin/python3
|
||||
"""Turn a /leetcode post-mortem into an Anki deck file (.apkg).
|
||||
|
||||
Usage: make_cards.py [--dry-run | --replace] <cards.json | -> (- = stdin)
|
||||
{"slug": "timeout-cancellation",
|
||||
"cards": [{"front": "JS: cancel a pending setTimeout?",
|
||||
"back": "clearTimeout(id)"}]}
|
||||
|
||||
The shape rules (word caps, coin-flip and placeholder fronts) live in
|
||||
`card_rules.py`; a violation fails the run (exit 1) and names the offender.
|
||||
Deck and model ids are fixed and the note guid is derived from (slug, front),
|
||||
so re-importing a regenerated file updates the same notes instead of
|
||||
duplicating them. Fields are HTML, so text is escaped (`a<b` would vanish).
|
||||
|
||||
--dry-run validate and print the table; no log, no delivery
|
||||
--replace make this the problem's whole card set: notes of the slug that
|
||||
are not in the input get deleted. Needs Anki open (AnkiConnect);
|
||||
an .apkg import cannot delete, so without it the run fails.
|
||||
|
||||
Delivery, in order of preference:
|
||||
1. Anki desktop is open with AnkiConnect -> notes are upserted directly and
|
||||
a sync to AnkiWeb is triggered, so AnkiDroid gets them at its next open.
|
||||
2. Otherwise -> ~/data/learn/leetcode/anki/<date>-<slug>.apkg, imported by
|
||||
`anki <file>` (which also starts Anki).
|
||||
Either way the cards are appended to ~/data/learn/leetcode/cards.tsv.
|
||||
|
||||
Runs on the system python (genanki in its user site, installed by
|
||||
install.sh); it used to be a `uv run --script` file. Its printed table and
|
||||
delivery line ARE its interface (T201 exemption in pyproject.toml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import html
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import sys
|
||||
from typing import Protocol, cast
|
||||
|
||||
import genanki
|
||||
|
||||
from leetcode_coach import anki_connect, card_rules, session_log
|
||||
|
||||
DECK_ID = 1_695_042_117_001 # fixed: every session's file imports into the same deck
|
||||
MODEL_ID = 1_695_042_117_002
|
||||
DECK_NAME = "LeetCode"
|
||||
OUT_DIR = Path.home() / "data" / "learn" / "leetcode" # ~/data: an allowed root bucket
|
||||
FLAGS = ("--dry-run", "--replace")
|
||||
|
||||
MODEL_NAME = "LeetCode coach (basic)"
|
||||
FIELDS = ["Front", "Back", "Problem"]
|
||||
QFMT = "{{Front}}<br><br><span style='font-size:70%;color:#888'>{{Problem}}</span>"
|
||||
AFMT = "{{FrontSide}}<hr id=answer>{{Back}}"
|
||||
CSS = ".card { font-family: sans-serif; font-size: 22px; text-align: center; }"
|
||||
|
||||
MODEL = genanki.Model(
|
||||
MODEL_ID,
|
||||
MODEL_NAME,
|
||||
fields=[{"name": f} for f in FIELDS],
|
||||
templates=[{"name": "Card 1", "qfmt": QFMT, "afmt": AFMT}],
|
||||
css=CSS,
|
||||
)
|
||||
|
||||
|
||||
class Note(Protocol):
|
||||
"""The part of `genanki.Note` this module relies on (genanki is untyped)."""
|
||||
|
||||
@property
|
||||
def guid(self) -> str:
|
||||
"""Stable id: re-importing the same (slug, front) updates the note."""
|
||||
|
||||
@property
|
||||
def fields(self) -> list[str]:
|
||||
"""Front, Back, Problem -- HTML-escaped text."""
|
||||
|
||||
@property
|
||||
def tags(self) -> list[str]:
|
||||
"""Anki tags."""
|
||||
|
||||
|
||||
def card_note(front: str, back: str, slug: str) -> Note:
|
||||
"""A note whose guid ignores escaping, so a regenerated deck updates it."""
|
||||
guid = genanki.guid_for(slug, html.unescape(front))
|
||||
note = genanki.Note(
|
||||
model=MODEL, fields=[front, back, slug], tags=["leetcode", slug], guid=guid
|
||||
)
|
||||
return cast("Note", note)
|
||||
|
||||
|
||||
def _log(slug: str, cards: list[card_rules.Card], today: str) -> None:
|
||||
"""Append the cards to the plain-text history."""
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with (OUT_DIR / "cards.tsv").open("a", encoding="utf-8") as fh:
|
||||
for c in cards:
|
||||
row = (today, slug, c["front"].strip(), c["back"].strip())
|
||||
fh.write("\t".join(row) + "\n")
|
||||
|
||||
|
||||
def push_direct(slug: str, cards: list[card_rules.Card], *, replace: bool) -> str:
|
||||
"""AnkiConnect path: upsert into the open desktop collection, then sync."""
|
||||
anki_connect.ensure_model(MODEL_NAME, FIELDS, QFMT, AFMT, CSS)
|
||||
added, updated, deleted = anki_connect.sync_notes(
|
||||
DECK_NAME, MODEL_NAME, slug, card_rules.escaped(cards), replace=replace
|
||||
)
|
||||
anki_connect.sync()
|
||||
return (
|
||||
f"{added} added, {updated} updated, {deleted} deleted in {DECK_NAME!r}; "
|
||||
"AnkiWeb sync requested (lands on the phone at AnkiDroid's next sync)"
|
||||
)
|
||||
|
||||
|
||||
def build_apkg(slug: str, cards: list[card_rules.Card], today: str) -> Path:
|
||||
"""Offline path: write a deck file that `anki <file>` imports."""
|
||||
deck = genanki.Deck(DECK_ID, DECK_NAME)
|
||||
for c in card_rules.escaped(cards):
|
||||
deck.add_note(card_note(c["front"], c["back"], slug))
|
||||
out_dir = OUT_DIR / "anki"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
out = out_dir / f"{today}-{slug}.apkg"
|
||||
genanki.Package(deck).write_to_file(str(out))
|
||||
return out
|
||||
|
||||
|
||||
def deliver(
|
||||
slug: str,
|
||||
cards: list[card_rules.Card],
|
||||
*,
|
||||
replace: bool = False,
|
||||
online: bool | None = None,
|
||||
) -> str:
|
||||
"""Log already-validated `cards` and deliver them; the delivery line.
|
||||
|
||||
AnkiConnect when Anki is open, else an .apkg. The coach relay calls this
|
||||
in-process (no ``postmortem`` here: the caller logs it to its own log).
|
||||
"""
|
||||
today = dt.datetime.now(tz=dt.UTC).date().isoformat()
|
||||
_log(slug, cards, today)
|
||||
if anki_connect.available() if online is None else online:
|
||||
done = push_direct(slug, cards, replace=replace)
|
||||
return f"{len(cards)} cards -> Anki desktop: {done}"
|
||||
out = build_apkg(slug, cards, today)
|
||||
return (
|
||||
f"{len(cards)} cards -> {out} (Anki desktop not open). Import with:\n"
|
||||
f"anki {shlex.quote(str(out))}"
|
||||
)
|
||||
|
||||
|
||||
def _usage() -> str:
|
||||
"""The `Usage:` line of this module's docstring."""
|
||||
return (__doc__ or "").strip().splitlines()[2]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Validate the cards on argv/stdin, then deliver them; 0 on success."""
|
||||
args = sys.argv[1:]
|
||||
flags = {a for a in args if a in FLAGS}
|
||||
rest = [a for a in args if a not in FLAGS]
|
||||
if len(rest) != 1 or len(flags) > 1:
|
||||
print(_usage(), file=sys.stderr)
|
||||
return 1
|
||||
src = rest[0]
|
||||
raw = sys.stdin.read() if src == "-" else Path(src).read_text(encoding="utf-8")
|
||||
spec = json.loads(raw)
|
||||
slug, cards = str(spec.get("slug", "")).strip(), list(spec.get("cards", []))
|
||||
if errors := card_rules.validate(slug, cards):
|
||||
print("cards rejected:\n " + "\n ".join(errors), file=sys.stderr)
|
||||
return 1
|
||||
if "--dry-run" in flags:
|
||||
print(card_rules.table(cards))
|
||||
return 0
|
||||
replace = "--replace" in flags
|
||||
online = anki_connect.available()
|
||||
if replace and not online:
|
||||
print(
|
||||
"--replace needs Anki open (AnkiConnect); nothing changed", file=sys.stderr
|
||||
)
|
||||
return 1
|
||||
print(card_rules.table(cards))
|
||||
print(deliver(slug, cards, replace=replace, online=online))
|
||||
# Delivered: the post-mortem is done. Re-test completion and "solved"
|
||||
# (progress.py) read this event from the REPL's session log.
|
||||
session_log.append_current("postmortem", cards=len(cards))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
227
leetcode_coach/leetcode_coach/phase.py
Normal file
227
leetcode_coach/leetcode_coach/phase.py
Normal file
@ -0,0 +1,227 @@
|
||||
"""The req-before-code phase gate, run by the REPL on both paths.
|
||||
|
||||
DOCS-coach-spec.md decisions 4-6: a message starting ``req:`` is kuhy's
|
||||
requirement list. Until one is accepted, a block that is code is refused
|
||||
here, with a one-line reason, and never reaches the coach model. A list is
|
||||
accepted when the checker passes it or cannot judge it (fail open); after the
|
||||
3rd list that still comes back incomplete, code is let through anyway and its
|
||||
``code`` event carries ``req_incomplete: true``.
|
||||
|
||||
State is derived from the session log, not held in memory, so it survives the
|
||||
mid-session hand-over to the local model and a restarted REPL the same day.
|
||||
The ``code`` event is appended BEFORE the block is sent: the Stop hook judges
|
||||
the reply to that very block and reads the log to know code exists.
|
||||
|
||||
Is a block code? A regex decides the clear cases; only a block it cannot
|
||||
decide goes to the model (`req_check.looks_like_code`), and an unanswered
|
||||
question is "not code" -- the gate never refuses kuhy on a guess.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import os
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from leetcode_coach import (
|
||||
gate_notes,
|
||||
leak,
|
||||
local_prompt,
|
||||
local_session,
|
||||
req_check,
|
||||
session_log,
|
||||
shape,
|
||||
toolbox,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
MAX_LISTS = 3
|
||||
REQ_RE = re.compile(r"^\s*req\s*:", re.IGNORECASE)
|
||||
STRONG_RE = re.compile(
|
||||
r"```|=>|^\s*(?:function\b|def\s+\w+\s*\(|class\s+\w+|"
|
||||
r"(?:const|let|var)\s+\w+\s*=|(?:for|while|if)\s*\(|#include|import\s+\w)"
|
||||
r"|[;{]\s*$|^\s*\}",
|
||||
re.MULTILINE,
|
||||
)
|
||||
OPERATOR_RE = re.compile(
|
||||
r"\w\s*(?:[=!]==?|<=|>=|[-+*/%^&|]=|\^|&&|\|\||<<|>>|%|=)\s*\w|\w\(|\w\["
|
||||
)
|
||||
|
||||
|
||||
def regex_verdict(block: str) -> bool | None:
|
||||
"""True for clear code, False for clear prose, None when it cannot tell."""
|
||||
if REQ_RE.match(block) or shape.SHAPE_RE.match(block):
|
||||
return False
|
||||
if STRONG_RE.search(block):
|
||||
return True
|
||||
return None if OPERATOR_RE.search(block) else False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReqState:
|
||||
"""Where the requirement phase stands, derived from the log."""
|
||||
|
||||
accepted: bool
|
||||
forced: bool
|
||||
tries: int
|
||||
|
||||
@property
|
||||
def open(self) -> bool:
|
||||
"""Whether code may reach the coach."""
|
||||
return self.accepted or self.forced
|
||||
|
||||
|
||||
REQ_STEP = 2
|
||||
"""The app's step 2 (requirements) in ``grade`` events."""
|
||||
|
||||
|
||||
def _step2_grades(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
e for e in events if e.get("event") == "grade" and e.get("step") == REQ_STEP
|
||||
]
|
||||
|
||||
|
||||
def req_state(events: list[dict[str, Any]]) -> ReqState:
|
||||
"""Accepted on a pass/unverified check; forced after `MAX_LISTS` incompletes.
|
||||
|
||||
A step-2 ``grade`` with ``forced: true`` (the app's "continue anyway")
|
||||
forces it too, or a forced step 2 would still refuse kuhy's code.
|
||||
"""
|
||||
verdicts = [e.get("verdict") for e in events if e.get("event") == "req_check"]
|
||||
tries = verdicts.count("incomplete")
|
||||
accepted = "pass" in verdicts or "unverified" in verdicts
|
||||
pushed = any(e.get("forced") is True for e in _step2_grades(events))
|
||||
forced = not accepted and (tries >= MAX_LISTS or pushed)
|
||||
return ReqState(accepted, forced, tries)
|
||||
|
||||
|
||||
def step2_attempts(events: list[dict[str, Any]]) -> int:
|
||||
"""Failed step-2 tries: incomplete lists plus app ``fail`` grades.
|
||||
|
||||
A ``fail`` (the list read as code, or named an operation) never reaches
|
||||
the checker, so it has no ``req_check``; a ``partial`` does, and is
|
||||
already counted there. CLI and app count one file alike. A force
|
||||
repeats the last try's grade but is not a try, so it is not counted.
|
||||
"""
|
||||
fails = sum(
|
||||
1
|
||||
for e in _step2_grades(events)
|
||||
if e.get("grade") == "fail" and e.get("forced") is not True
|
||||
)
|
||||
return req_state(events).tries + fails
|
||||
|
||||
|
||||
@dataclass
|
||||
class PhaseGate:
|
||||
"""One problem's gate: its log, toolbox and (lazily fetched) statement."""
|
||||
|
||||
log: Path
|
||||
toolbox: toolbox.Toolbox
|
||||
source: Callable[[], str]
|
||||
ask: Callable[..., dict[str, Any]] | None = None
|
||||
known: str | None = field(default=None, repr=False)
|
||||
|
||||
@classmethod
|
||||
def open(cls, problem: str) -> PhaseGate:
|
||||
"""The gate for `problem`; exports its log path for the Stop hook."""
|
||||
log = session_log.log_path(problem)
|
||||
os.environ[session_log.LOG_ENV] = str(log)
|
||||
|
||||
def source() -> str:
|
||||
return local_session.fetched_statement(problem) or session_log.slug(problem)
|
||||
|
||||
return cls(log, toolbox.load_safe(), source)
|
||||
|
||||
def statement(self) -> str:
|
||||
"""The problem statement, fetched once on first use."""
|
||||
if self.known is None:
|
||||
self.known = self.source()
|
||||
return self.known
|
||||
|
||||
def events(self) -> list[dict[str, Any]]:
|
||||
"""This session's log events (`session_log.current`)."""
|
||||
return session_log.current(session_log.read(self.log))
|
||||
|
||||
def code_seen(self) -> bool:
|
||||
"""Whether a code block has been let through this session."""
|
||||
return session_log.has_code(self.log)
|
||||
|
||||
def screen(
|
||||
self, block: str, *, is_code: bool | None = None
|
||||
) -> tuple[str | None, str]:
|
||||
"""(what to send the coach, or None to refuse; a note for kuhy).
|
||||
|
||||
`is_code` is a verdict the caller already reached (the relay judges a
|
||||
message before its own step-2 check), so the model is not asked twice.
|
||||
"""
|
||||
text = block.strip()
|
||||
if text.lower() == "reveal":
|
||||
session_log.append(self.log, "reveal")
|
||||
return block, ""
|
||||
if REQ_RE.match(text) or (shape.SHAPE_RE.match(text) and self.sql()):
|
||||
return self._req(block)
|
||||
verdict = regex_verdict(text) if is_code is None else is_code
|
||||
if verdict is None:
|
||||
verdict = req_check.looks_like_code(text, self.ask)
|
||||
if not verdict:
|
||||
return block, ""
|
||||
state = req_state(self.events())
|
||||
if not state.open:
|
||||
return None, self._refusal(state)
|
||||
extra = {"req_incomplete": True} if state.forced else {}
|
||||
session_log.append(self.log, "code", **extra)
|
||||
return block, ""
|
||||
|
||||
def _req(self, block: str) -> tuple[str, str]:
|
||||
session_log.append(self.log, "req", text=block.strip())
|
||||
if self.sql():
|
||||
result = shape.check(block)
|
||||
else:
|
||||
result = req_check.check(self.statement(), block, self.toolbox, self.ask)
|
||||
session_log.append(
|
||||
self.log,
|
||||
"req_check",
|
||||
verdict=result.verdict,
|
||||
missing=list(result.missing),
|
||||
via=result.via,
|
||||
)
|
||||
state = req_state(self.events())
|
||||
tag = result.verdict
|
||||
if result.missing:
|
||||
tag += "; missing properties: " + ", ".join(result.missing)
|
||||
note = gate_notes.req_note(
|
||||
result,
|
||||
state.tries,
|
||||
forced=state.forced,
|
||||
limit=MAX_LISTS,
|
||||
box=self.toolbox,
|
||||
)
|
||||
return f"{block}\n\n[req check: {tag}]", note
|
||||
|
||||
def refusal_note(self) -> str:
|
||||
"""The line a refused code block gets now (the relay's ``note``)."""
|
||||
return self._refusal(req_state(self.events()))
|
||||
|
||||
def sql(self) -> bool:
|
||||
"""Whether this is a SQL problem (an unfetched statement counts as not)."""
|
||||
return shape.is_sql(self.statement())
|
||||
|
||||
def _refusal(self, state: ReqState) -> str:
|
||||
return gate_notes.refusal(state.tries, MAX_LISTS, sql=self.sql())
|
||||
|
||||
def after_reply(self, text: str) -> str:
|
||||
"""Log the reply's rung marker and return the reply without it."""
|
||||
clean, rung = local_prompt.split_rung(text)
|
||||
if rung is not None:
|
||||
session_log.append(self.log, "rung", rung=rung)
|
||||
return clean
|
||||
|
||||
def leaks(self, reply: str, user_texts: list[str]) -> list[str]:
|
||||
"""Toolbox entries `reply` names too early (the local path's bounce)."""
|
||||
if any(t.strip() == "reveal" for t in user_texts) or self.code_seen():
|
||||
return []
|
||||
return leak.leaked_names(reply, user_texts, self.toolbox)
|
||||
217
leetcode_coach/leetcode_coach/progress.py
Normal file
217
leetcode_coach/leetcode_coach/progress.py
Normal file
@ -0,0 +1,217 @@
|
||||
"""Cluster progress and the cold re-test schedule, derived from the session logs.
|
||||
|
||||
DOCS-coach-spec.md decisions 10 and 12. Nothing here keeps state of its own: the
|
||||
JSONL session logs (``<YYYY-MM-DD>-<slug>.jsonl``, decision 8) are the only
|
||||
record, so progress survives anything that survives the logs.
|
||||
|
||||
* A problem is **started** once it has a ``code`` event, and **solved** on the
|
||||
first day by which it has both a ``code`` and a ``postmortem`` event. A
|
||||
later re-test session logs its own code and post-mortem; that never moves
|
||||
the solve day, so it cannot reset the schedule.
|
||||
* Re-tests fall due ``RETEST_OFFSETS`` days after the solve day (+3, +10).
|
||||
Each ``retest`` event completes one stage.
|
||||
|
||||
Days come from the file name, like ``leetcode_guard._coach_log``: the ``ts``
|
||||
field's format belongs to the session writer. Stdlib only, because the status
|
||||
snapshot imports this every minute on the system python.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_LOG: Final = logging.getLogger(__name__)
|
||||
|
||||
SESSIONS_ENV: Final = "LEETCODE_COACH_SESSIONS_DIR"
|
||||
CLUSTER_ENV: Final = "LEETCODE_COACH_CLUSTER"
|
||||
"""Set for the coached session; the session writer stamps it as ``cluster``."""
|
||||
DEFAULT_SESSIONS_DIR: Final = (
|
||||
Path.home() / ".local" / "share" / "leetcode-coach" / "sessions"
|
||||
)
|
||||
CLUSTERS_PATH: Final = Path(__file__).with_name("clusters.json")
|
||||
RETEST_OFFSETS: Final = (3, 10)
|
||||
_DATED: Final = re.compile(r"(?P<day>\d{4}-\d{2}-\d{2})-(?P<slug>.+)")
|
||||
|
||||
Event = dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class History:
|
||||
"""What the logs say about one problem."""
|
||||
|
||||
started: bool
|
||||
solved: dt.date | None
|
||||
retests: int
|
||||
|
||||
|
||||
def sessions_dir() -> Path:
|
||||
"""Where the session logs live (``$LEETCODE_COACH_SESSIONS_DIR`` overrides)."""
|
||||
override = os.environ.get(SESSIONS_ENV)
|
||||
return Path(override) if override else DEFAULT_SESSIONS_DIR
|
||||
|
||||
|
||||
def local_today() -> dt.date:
|
||||
"""Today in local time: a re-test is due by kuhy's calendar, not UTC's."""
|
||||
return dt.datetime.now(tz=dt.UTC).astimezone().date()
|
||||
|
||||
|
||||
def load_clusters(path: Path | None = None) -> dict[str, list[dict[str, Any]]]:
|
||||
"""``{"<cluster>": [{"id": 268, "slug": "missing-number"}, ...]}``, in order."""
|
||||
source = CLUSTERS_PATH if path is None else path
|
||||
clusters: dict[str, list[dict[str, Any]]] = json.loads(
|
||||
source.read_text(encoding="utf-8")
|
||||
)["clusters"]
|
||||
return clusters
|
||||
|
||||
|
||||
def cluster_of(slug: str) -> str | None:
|
||||
"""The cluster a problem belongs to, if any."""
|
||||
for name, problems in load_clusters().items():
|
||||
if any(p["slug"] == slug for p in problems):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _dated(path: Path) -> tuple[dt.date, str] | None:
|
||||
"""``2026-10-23-missing-number.jsonl`` -> (date, slug); None if undated."""
|
||||
match = _DATED.fullmatch(path.stem)
|
||||
if match is None:
|
||||
return None
|
||||
try:
|
||||
return dt.date.fromisoformat(match["day"]), match["slug"]
|
||||
except ValueError:
|
||||
_LOG.warning("coach session %s has an impossible date; skipped", path)
|
||||
return None
|
||||
|
||||
|
||||
def _parse(path: Path, line: str) -> Event | None:
|
||||
"""One log line as an event; None for anything that is not one."""
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except ValueError as exc:
|
||||
# A torn line is a writer that died mid-write: worth its own warning.
|
||||
_LOG.warning("coach session %s: a line is not JSON: %s", path, exc)
|
||||
return None
|
||||
if isinstance(event, dict) and isinstance(event.get("event"), str):
|
||||
return event
|
||||
return None
|
||||
|
||||
|
||||
def _events(path: Path) -> list[Event]:
|
||||
"""The file's events in order; unreadable files and junk lines are skipped."""
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
except (OSError, UnicodeDecodeError) as exc:
|
||||
_LOG.warning("coach session %s is unreadable: %s", path, exc)
|
||||
return []
|
||||
parsed = (_parse(path, line) for line in lines if line.strip())
|
||||
return [event for event in parsed if event is not None]
|
||||
|
||||
|
||||
def _read(directory: Path | None) -> dict[str, list[tuple[dt.date, Event]]]:
|
||||
"""Every slug's events across all its files, oldest file first."""
|
||||
folder = sessions_dir() if directory is None else directory
|
||||
by_slug: dict[str, list[tuple[dt.date, Event]]] = {}
|
||||
if not folder.is_dir():
|
||||
return by_slug
|
||||
for path in sorted(folder.glob("*.jsonl")):
|
||||
if (dated := _dated(path)) is not None:
|
||||
day, slug = dated
|
||||
by_slug.setdefault(slug, []).extend((day, e) for e in _events(path))
|
||||
return by_slug
|
||||
|
||||
|
||||
def _history(entries: list[tuple[dt.date, Event]]) -> History:
|
||||
seen: set[str] = set()
|
||||
solved: dt.date | None = None
|
||||
for day, event in entries:
|
||||
seen.add(event["event"])
|
||||
if solved is None and {"code", "postmortem"} <= seen:
|
||||
solved = day
|
||||
retests = sum(event["event"] == "retest" for _day, event in entries)
|
||||
return History(started="code" in seen, solved=solved, retests=retests)
|
||||
|
||||
|
||||
def history(slug: str, directory: Path | None = None) -> History:
|
||||
"""Started / solved day / re-tests done for one problem."""
|
||||
return _history(_read(directory).get(slug, []))
|
||||
|
||||
|
||||
def count_events(slug: str, kind: str, directory: Path | None = None) -> int:
|
||||
"""How many ``kind`` events the problem has across all its files."""
|
||||
return sum(event["event"] == kind for _d, event in _read(directory).get(slug, []))
|
||||
|
||||
|
||||
def due_retests(
|
||||
directory: Path | None = None, today: dt.date | None = None
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Re-tests due by ``today``, oldest due date first."""
|
||||
day = local_today() if today is None else today
|
||||
rows: list[dict[str, Any]] = []
|
||||
for slug, entries in _read(directory).items():
|
||||
past = _history(entries)
|
||||
if past.solved is None or past.retests >= len(RETEST_OFFSETS):
|
||||
continue
|
||||
due = past.solved + dt.timedelta(days=RETEST_OFFSETS[past.retests])
|
||||
if due <= day:
|
||||
rows.append(
|
||||
{
|
||||
"slug": slug,
|
||||
"cluster": cluster_of(slug),
|
||||
"stage": past.retests + 1,
|
||||
"due": due.isoformat(),
|
||||
"solved": past.solved.isoformat(),
|
||||
}
|
||||
)
|
||||
return sorted(rows, key=lambda row: (row["due"], row["slug"]))
|
||||
|
||||
|
||||
def cluster_progress(directory: Path | None = None) -> dict[str, dict[str, Any]]:
|
||||
"""Per cluster: problems total / started / solved, and the next unstarted one."""
|
||||
logs = _read(directory)
|
||||
summary: dict[str, dict[str, Any]] = {}
|
||||
for name, problems in load_clusters().items():
|
||||
pasts = [_history(logs.get(p["slug"], [])) for p in problems]
|
||||
fresh = [
|
||||
p["slug"] for p, h in zip(problems, pasts, strict=True) if not h.started
|
||||
]
|
||||
summary[name] = {
|
||||
"total": len(problems),
|
||||
"started": sum(h.started for h in pasts),
|
||||
"solved": sum(h.solved is not None for h in pasts),
|
||||
"next": fresh[0] if fresh else None,
|
||||
}
|
||||
return summary
|
||||
|
||||
|
||||
def next_new(
|
||||
name: str, directory: Path | None, accepted: Callable[[str], bool]
|
||||
) -> str | None:
|
||||
"""The cluster's first problem with no ``code`` event that is not Accepted."""
|
||||
logs = _read(directory)
|
||||
for problem in load_clusters()[name]:
|
||||
slug = str(problem["slug"])
|
||||
if not _history(logs.get(slug, [])).started and not accepted(slug):
|
||||
return slug
|
||||
return None
|
||||
|
||||
|
||||
def append_event(slug: str, event: Event) -> Path:
|
||||
"""Append one event (stamped with ``ts``) to today's session file."""
|
||||
folder = sessions_dir()
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / f"{local_today().isoformat()}-{slug}.jsonl"
|
||||
stamp = dt.datetime.now(tz=dt.UTC).astimezone().isoformat(timespec="seconds")
|
||||
with path.open("a", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps({**event, "ts": stamp}, ensure_ascii=False) + "\n")
|
||||
return path
|
||||
0
leetcode_coach/leetcode_coach/py.typed
Normal file
0
leetcode_coach/leetcode_coach/py.typed
Normal file
11
leetcode_coach/leetcode_coach/relay/__init__.py
Normal file
11
leetcode_coach/leetcode_coach/relay/__init__.py
Normal file
@ -0,0 +1,11 @@
|
||||
"""The coach relay: one PC service behind the app's guided coaching UI.
|
||||
|
||||
``DOCS-coach-relay.md`` is the contract. The desktop app reaches it over a
|
||||
loopback HTTP API (``http_api``), the phone through Firebase RTDB (``phone``);
|
||||
both feed one paced serial lane (``lane``) into the session backend
|
||||
(``coach``), which grades the five steps and runs the coaching chat.
|
||||
|
||||
Nothing here can reach the gate's ledger, credits or unlocks: the only
|
||||
``leetcode_guard`` modules reachable are the read-only ones `guard_bridge`
|
||||
names, imported on demand (``test_guard_boundary.py``).
|
||||
"""
|
||||
64
leetcode_coach/leetcode_coach/relay/__main__.py
Normal file
64
leetcode_coach/leetcode_coach/relay/__main__.py
Normal file
@ -0,0 +1,64 @@
|
||||
"""``python3 -m leetcode_coach.relay``: the systemd unit's entry point.
|
||||
|
||||
Logs to stderr (the journal) at INFO; SIGTERM stops taking requests and
|
||||
lets the running one finish (the unit's ``KillMode=mixed`` spares the claude
|
||||
child meanwhile). The phone path signs in as crdt_sync app
|
||||
``leetcode_coach_relay`` via `guard_bridge.phone_id_token`, which heals from a
|
||||
sibling app's session; ``$LEETCODE_COACH_RTDB_URL`` skips sign-in (tests).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from crdt_sync import CONFIG_FILE, FirebaseConfig
|
||||
|
||||
from leetcode_coach import guard_bridge
|
||||
from leetcode_coach.relay import config
|
||||
from leetcode_coach.relay.app import Relay
|
||||
from leetcode_coach.relay.coach import Deps
|
||||
from leetcode_coach.relay.rtdb import Rtdb
|
||||
|
||||
FAKE_ID = "relay-test"
|
||||
"""What the relay hands the fake RTDB, which takes any non-empty id token."""
|
||||
|
||||
|
||||
def make_rtdb() -> Rtdb:
|
||||
"""The signed-in RTDB client (or the fake one the env var names)."""
|
||||
url = config.rtdb_url()
|
||||
if url:
|
||||
return Rtdb(url, lambda: FAKE_ID)
|
||||
id_token = guard_bridge.phone_id_token(config.APP_NAME, timeout_seconds=15)
|
||||
database = FirebaseConfig.load(CONFIG_FILE).database_url
|
||||
return Rtdb(database, id_token)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Run until SIGTERM / SIGINT."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
stream=sys.stderr,
|
||||
format="%(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
relay = Relay(Deps())
|
||||
|
||||
def stop(_signum: int, _frame: object) -> None:
|
||||
relay.stop_event.set()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
relay.start()
|
||||
logging.getLogger(__name__).info("coach relay on 127.0.0.1:%d", relay.port)
|
||||
threading.Thread(
|
||||
target=relay.connect_phone, args=(make_rtdb,), name="rtdb", daemon=True
|
||||
).start()
|
||||
relay.stop_event.wait()
|
||||
relay.stop()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
144
leetcode_coach/leetcode_coach/relay/app.py
Normal file
144
leetcode_coach/leetcode_coach/relay/app.py
Normal file
@ -0,0 +1,144 @@
|
||||
"""The relay assembled: backend, lane, loopback API, phone link, ticker.
|
||||
|
||||
One process (``leetcode-coach-relay.service``). Every wait is injectable so
|
||||
the end-to-end tests run the real threads at test speed: the 3 s pace, the
|
||||
Accepted ticker, the heartbeat and the rescan. The phone link connects in
|
||||
its own thread and retries with backoff, so a Firebase outage at boot never
|
||||
delays the desktop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach.relay import config
|
||||
from leetcode_coach.relay.coach import Coach, Deps
|
||||
from leetcode_coach.relay.done import DoneMap
|
||||
from leetcode_coach.relay.http_api import Server
|
||||
from leetcode_coach.relay.lane import PACE_S, Lane
|
||||
from leetcode_coach.relay.phone import HEARTBEAT_S, RESCAN_S, PhoneLink
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.relay.rtdb import Rtdb
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
TICK_S: Final = 5.0
|
||||
CONNECT_BACKOFF_S: Final = (5.0, 30.0, 120.0, 300.0)
|
||||
|
||||
|
||||
class Relay: # pylint: disable=too-many-instance-attributes
|
||||
"""All the parts, and the threads that run them."""
|
||||
|
||||
def __init__( # pylint: disable=too-many-arguments
|
||||
self,
|
||||
deps: Deps,
|
||||
*,
|
||||
port: int | None = None,
|
||||
pace_s: float = PACE_S,
|
||||
tick_s: float = TICK_S,
|
||||
heartbeat_s: float = HEARTBEAT_S,
|
||||
rescan_s: float = RESCAN_S,
|
||||
) -> None:
|
||||
"""Build everything and bind the port; nothing runs until `start`."""
|
||||
self.deps = deps
|
||||
self.started = deps.clock_ms()
|
||||
self.coach = Coach(deps)
|
||||
done = DoneMap(deps.state_dir / "requests_done.jsonl", deps.clock_ms)
|
||||
self.lane = Lane(self.coach.handle, done, clock_ms=deps.clock_ms, pace_s=pace_s)
|
||||
bind = config.port() if port is None else port
|
||||
self.server = Server((config.HOST, bind), self)
|
||||
self.stop_event = threading.Event()
|
||||
self.phone: PhoneLink | None = None
|
||||
self._tick_s = tick_s
|
||||
self._beat_s = heartbeat_s
|
||||
self._rescan_s = rescan_s
|
||||
self._threads: list[threading.Thread] = []
|
||||
|
||||
@property
|
||||
def port(self) -> int:
|
||||
"""The bound loopback port (tests bind port 0)."""
|
||||
return int(self.server.server_address[1])
|
||||
|
||||
def heartbeat(self) -> dict[str, Any]:
|
||||
"""``{"beat", "started", "state_rev", "busy"?, "version"}`` (beat in ms)."""
|
||||
beat: dict[str, Any] = {
|
||||
"beat": self.deps.clock_ms(),
|
||||
"started": self.started,
|
||||
"state_rev": self.coach.rev,
|
||||
"version": 1,
|
||||
}
|
||||
if self.lane.busy is not None:
|
||||
beat["busy"] = self.lane.busy
|
||||
return beat
|
||||
|
||||
def _spawn(self, name: str, target: Callable[[], object]) -> None:
|
||||
thread = threading.Thread(target=target, name=name, daemon=True)
|
||||
thread.start()
|
||||
self._threads.append(thread)
|
||||
|
||||
def _tick_loop(self) -> None:
|
||||
while not self.stop_event.wait(self._tick_s):
|
||||
self.coach.tick()
|
||||
|
||||
def start(self) -> None:
|
||||
"""Serve the API, run the lane and the Accepted ticker."""
|
||||
self._spawn("http", self.server.serve_forever)
|
||||
self._spawn("lane", lambda: self.lane.run(self.stop_event))
|
||||
self._spawn("tick", self._tick_loop)
|
||||
|
||||
def link_phone(self, rtdb: Rtdb) -> PhoneLink:
|
||||
"""Mirror into `rtdb` and take the phone's requests from it."""
|
||||
phone = PhoneLink(
|
||||
rtdb,
|
||||
self.lane,
|
||||
self.coach,
|
||||
self.heartbeat,
|
||||
clock_ms=self.deps.clock_ms,
|
||||
heartbeat_s=self._beat_s,
|
||||
rescan_s=self._rescan_s,
|
||||
)
|
||||
phone.attach()
|
||||
self.phone = phone
|
||||
self._spawn("rtdb-write", lambda: phone.outbox.run(self.stop_event))
|
||||
self._spawn("rtdb-listen", lambda: phone.listen(self.stop_event))
|
||||
self._spawn(
|
||||
"rtdb-tend", lambda: phone.tend(self.stop_event, self.stop_event.wait)
|
||||
)
|
||||
return phone
|
||||
|
||||
def connect_phone(self, make: Callable[[], Rtdb]) -> None:
|
||||
"""Keep trying `make` (Firebase sign-in) with backoff, then link."""
|
||||
failures = 0
|
||||
while not self.stop_event.is_set():
|
||||
try:
|
||||
rtdb = make()
|
||||
except Exception: # pylint: disable=broad-exception-caught
|
||||
# Sign-in fails a dozen ways (config, auth, network); each is
|
||||
# an outage to wait out, never a reason to stop the relay.
|
||||
delay = CONNECT_BACKOFF_S[min(failures, len(CONNECT_BACKOFF_S) - 1)]
|
||||
failures += 1
|
||||
_logger.exception(
|
||||
"RTDB not reachable; phone path retries in %.0fs", delay
|
||||
)
|
||||
self.stop_event.wait(delay)
|
||||
continue
|
||||
self.link_phone(rtdb)
|
||||
return
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop taking requests, let the running one finish, close the port."""
|
||||
self.stop_event.set()
|
||||
self.lane.stop()
|
||||
if self.phone is not None:
|
||||
self.phone.outbox.wake()
|
||||
if any(t.name == "http" for t in self._threads):
|
||||
self.server.shutdown() # blocks unless serve_forever runs
|
||||
self.server.server_close()
|
||||
for thread in self._threads:
|
||||
if thread.name == "lane":
|
||||
thread.join(timeout=300)
|
||||
48
leetcode_coach/leetcode_coach/relay/cards.py
Normal file
48
leetcode_coach/leetcode_coach/relay/cards.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Step 5's reward: the post-mortem's property cards, from the answer key.
|
||||
|
||||
The existing builder, in-process: property -> operation cards for the key's
|
||||
toolbox entries (`toolbox_cards.cards_for`), checked by `card_rules` and
|
||||
delivered by `make_cards.deliver` (AnkiConnect, else an .apkg). The relay
|
||||
appends the ``postmortem`` event itself: ``make_cards.main`` finds the log
|
||||
through ``os.environ``, which one process serving many sessions never sets.
|
||||
A card failure only fills ``error``; the step stays passed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach import card_rules, make_cards, toolbox_cards
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leetcode_coach.relay.session import Session
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def build(
|
||||
session: Session, entries: tuple[str, ...], *, dry_run: bool = False
|
||||
) -> dict[str, Any]:
|
||||
"""Build and deliver the cards; ``{"built", "deck", "error"}``."""
|
||||
out: dict[str, Any] = {"built": 0, "deck": make_cards.DECK_NAME, "error": None}
|
||||
try:
|
||||
cards = toolbox_cards.cards_for(list(entries))
|
||||
except (KeyError, OSError, ValueError) as exc:
|
||||
_logger.warning("no cards for %s: %s", session.slug, exc)
|
||||
return {**out, "error": f"no cards: {exc}"}
|
||||
if errors := card_rules.validate(toolbox_cards.SLUG, cards):
|
||||
_logger.warning("cards rejected for %s: %s", session.slug, errors)
|
||||
return {**out, "error": "cards rejected: " + "; ".join(errors)}
|
||||
if dry_run:
|
||||
return {**out, "built": len(cards)}
|
||||
try:
|
||||
line = make_cards.deliver(toolbox_cards.SLUG, cards)
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
# AnkiConnect, genanki and the disk all fail in their own ways; none
|
||||
# of them may cost kuhy the passed step.
|
||||
_logger.exception("card delivery failed for %s", session.slug)
|
||||
return {**out, "error": f"delivery failed: {exc}"}
|
||||
_logger.info("cards for %s: %s", session.slug, line)
|
||||
session.log_event("postmortem", cards=len(cards))
|
||||
return {**out, "built": len(cards)}
|
||||
142
leetcode_coach/leetcode_coach/relay/chat.py
Normal file
142
leetcode_coach/leetcode_coach/relay/chat.py
Normal file
@ -0,0 +1,142 @@
|
||||
"""The coaching chat: the CLI's sonnet session, one per problem.
|
||||
|
||||
The same session `leetcode_repl.run_claude` runs: it opens with
|
||||
``/leetcode <slug>`` (which loads SKILL.md and arms the no-solution Stop
|
||||
gate), then every turn is ``claude -p --resume``. Each call carries this
|
||||
session's ``LEETCODE_COACH_LOG`` in the child's env only, so the Stop hook
|
||||
reads the right log while one relay process serves every session.
|
||||
|
||||
On a usage limit the session continues on the local model with the history
|
||||
so far, as the REPL hands over, and stays there. When that is down too the
|
||||
turn fails ``claude_unavailable`` with the limit's reason and reset time.
|
||||
|
||||
Replies come back RAW: the caller strips and logs the rung marker
|
||||
(`PhaseGate.after_reply`) after it has logged the turn's own events.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
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.relay.errors import CoachError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.relay.session import Session
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
TURN_TIMEOUT_S: Final = 240.0
|
||||
REQUEST_CAP_S: Final = 280.0
|
||||
"""A whole request; a coach turn gets what is left of it (at most 240 s)."""
|
||||
MIN_TURN_S: Final = 15.0
|
||||
RESETS_RE: Final = re.compile(r"resets\s+([^\n]+?)\s*$", re.IGNORECASE | re.MULTILINE)
|
||||
TurnError = CoachError
|
||||
"""A coach turn produced no reply (``model_error`` / ``claude_unavailable``)."""
|
||||
|
||||
|
||||
def model() -> str:
|
||||
"""The coaching model (``LEETCODE_MODEL``, default sonnet, as the REPL)."""
|
||||
return os.environ.get("LEETCODE_MODEL") or "sonnet"
|
||||
|
||||
|
||||
def _env(session: Session) -> dict[str, str]:
|
||||
env = {"LEETCODE_COACH_LOG": str(session.log)}
|
||||
if session.cluster:
|
||||
env["LEETCODE_COACH_CLUSTER"] = session.cluster
|
||||
return env
|
||||
|
||||
|
||||
class CoachChat:
|
||||
"""Runs turns for whichever session is live."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ask: Callable[..., dict[str, Any]] = claude_cli.ask,
|
||||
local_chat: Callable[..., local_backend.LocalReply] = local_backend.chat,
|
||||
) -> None:
|
||||
"""Bind the claude call and the local model (both injectable)."""
|
||||
self._ask = ask
|
||||
self._local_chat = local_chat
|
||||
self.monotonic: Callable[[], float] = time.monotonic
|
||||
self.deadline = float("inf")
|
||||
"""When the running request hits `REQUEST_CAP_S` (set by `Coach.handle`)."""
|
||||
|
||||
def budget(self) -> float:
|
||||
"""Seconds this turn may take; `model_error` when too few are left."""
|
||||
left = self.deadline - self.monotonic()
|
||||
if left < MIN_TURN_S:
|
||||
msg = "The PC ran out of time for this turn; send it again."
|
||||
raise TurnError(msg, code="model_error", retry=True)
|
||||
return min(TURN_TIMEOUT_S, left)
|
||||
|
||||
def _bounded(self, messages: list[dict[str, str]]) -> local_backend.LocalReply:
|
||||
return self._local_chat(messages, timeout=self.budget())
|
||||
|
||||
def open(self, session: Session) -> str:
|
||||
"""The coach's opening reply for a fresh session."""
|
||||
return self._claude(session, "/leetcode " + session.slug, resume=False)
|
||||
|
||||
def turn(self, session: Session, text: str) -> str:
|
||||
"""Kuhy's `text` in, the coach's raw reply out."""
|
||||
if session.local:
|
||||
return self._local(session, text, reason=None)
|
||||
return self._claude(session, text, resume=True)
|
||||
|
||||
def _claude(self, session: Session, text: str, *, resume: bool) -> str:
|
||||
args = ["--model", model()]
|
||||
if resume and session.claude_id:
|
||||
args += ["--resume", session.claude_id]
|
||||
reply = self._ask(args, text, timeout=self.budget(), env=_env(session))
|
||||
if claude_cli.is_limit_hit(reply):
|
||||
reason = str(reply.get("result") or "usage limit")
|
||||
_logger.warning("claude usage limit (%s): coaching on locally", reason)
|
||||
session.local = True
|
||||
return self._local(session, text, reason=reason)
|
||||
sid = reply.get("session_id")
|
||||
if reply.get("is_error") is True or not isinstance(sid, str) or not sid:
|
||||
_logger.warning("coach turn failed: %s", reply.get("_stderr") or reply)
|
||||
msg = "The coach did not answer; send it again."
|
||||
raise TurnError(msg, code="model_error", retry=True)
|
||||
session.claude_id = sid
|
||||
raw = str(reply.get("result", ""))
|
||||
session.history += [
|
||||
{"role": "user", "content": text},
|
||||
{"role": "assistant", "content": raw},
|
||||
]
|
||||
return raw
|
||||
|
||||
def _local(self, session: Session, text: str, *, reason: str | None) -> str:
|
||||
try:
|
||||
if session.local_coach is None:
|
||||
coach = local_coach.LocalCoach.start(
|
||||
session.statement or session.slug, session.history
|
||||
)
|
||||
coach.chat = self._bounded
|
||||
coach.leak_guard = session.gate.leaks
|
||||
session.local_coach = coach
|
||||
turn = session.local_coach.respond(text)
|
||||
except (
|
||||
urllib.error.URLError,
|
||||
OSError,
|
||||
local_backend.ContextOverflowError,
|
||||
) as exc:
|
||||
_logger.warning("local model could not answer either: %s", exc)
|
||||
why = reason or "claude usage limit"
|
||||
found = RESETS_RE.search(why)
|
||||
msg = "Claude is out of quota and the local model is down."
|
||||
raise TurnError(
|
||||
msg,
|
||||
code="claude_unavailable",
|
||||
reason=why,
|
||||
resets_at=found.group(1) if found else None,
|
||||
) from exc
|
||||
display, _cards = local_cards.split_cards(turn.text)
|
||||
return display
|
||||
209
leetcode_coach/leetcode_coach/relay/coach.py
Normal file
209
leetcode_coach/leetcode_coach/relay/coach.py
Normal file
@ -0,0 +1,209 @@
|
||||
"""The session backend every request runs against (DOCS-coach-relay.md 2-3).
|
||||
|
||||
One live session at a time. `handle` runs one validated request under the
|
||||
backend's lock (the lane already serialises; the lock also fences the
|
||||
Accepted ticker), then republishes the state: ``rev`` moves only when
|
||||
something visible changed, and listeners (the phone mirror) hear about it.
|
||||
Readers -- ``GET /coach/state`` and the heartbeat -- take the published copy
|
||||
and never wait for a model call in progress.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
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.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
|
||||
from leetcode_coach.relay.probe import ACCEPTED, AcceptedProbe
|
||||
from leetcode_coach.relay.session import Session, grade_line, restore, save
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from leetcode_coach.phase import PhaseGate
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
ACCEPTED_NOTE: Final = "[app: step 4 passed, LeetCode shows an Accepted; step 5 open]"
|
||||
|
||||
|
||||
def _toolbox() -> toolbox.Toolbox:
|
||||
"""`toolbox.load_safe`, looked up per call (tests swap the fixture in)."""
|
||||
return toolbox.load_safe()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Deps:
|
||||
"""Everything the backend talks to; each one a test seam."""
|
||||
|
||||
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
|
||||
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
|
||||
cards_dry_run: bool = field(default_factory=config.cards_dry_run)
|
||||
clock_ms: Callable[[], int] = config.now_ms
|
||||
answers: Callable[[], dict[str, answer_key.Answer]] = answer_key.load_answers
|
||||
box: Callable[[], toolbox.Toolbox] = field(default=_toolbox)
|
||||
|
||||
|
||||
class Coach:
|
||||
"""The live session, its published state, and the request handlers."""
|
||||
|
||||
def __init__(self, deps: Deps) -> None:
|
||||
"""Rebuild the live session from ``live.json`` if there is one."""
|
||||
self.deps = deps
|
||||
self.chat = CoachChat(deps.ask, deps.local_chat)
|
||||
self.lock = threading.RLock()
|
||||
self.listeners: list[Callable[[dict[str, Any], Session | None], None]] = []
|
||||
self.live_path = deps.state_dir / "live.json"
|
||||
restored = restore(self.live_path, self.gate_for)
|
||||
self.session: Session | None = None if restored is None else restored[0]
|
||||
self.rev = 0 if restored is None else restored[1] + 1
|
||||
self._seen = ""
|
||||
self._state: dict[str, Any] = {}
|
||||
self.publish()
|
||||
|
||||
def now(self) -> int:
|
||||
"""Unix ms."""
|
||||
return self.deps.clock_ms()
|
||||
|
||||
def gate_for(self, log: Path, slug: str) -> PhaseGate:
|
||||
"""A phase gate for one session's log (never ``PhaseGate.open``)."""
|
||||
return turns.gate_for(self, log, slug)
|
||||
|
||||
def state(self) -> dict[str, Any]:
|
||||
"""The published state (section 3)."""
|
||||
return self._state
|
||||
|
||||
def chat_after(self, after: str | None) -> dict[str, dict[str, Any]]:
|
||||
"""Chat lines after key `after` (all when None)."""
|
||||
session = self.session
|
||||
lines = {} if session is None else dict(session.chat)
|
||||
return {k: v for k, v in lines.items() if after is None or k > after}
|
||||
|
||||
def _build(self) -> dict[str, Any]:
|
||||
session = self.session
|
||||
if session is None:
|
||||
return {
|
||||
"schema": 1,
|
||||
"step": None,
|
||||
"rung": None,
|
||||
"revealed": False,
|
||||
"chat_count": 0,
|
||||
"session": None,
|
||||
"steps": [],
|
||||
}
|
||||
events = session.events()
|
||||
derived = steps.derive(events)
|
||||
current = steps.open_step(derived)
|
||||
step = None if session.ended is not None or current is None else current.n
|
||||
state: dict[str, Any] = {
|
||||
"schema": 1,
|
||||
"step": step,
|
||||
"rung": steps.rung(events),
|
||||
"revealed": steps.revealed(events),
|
||||
"chat_count": len(session.chat),
|
||||
"session": session.info(),
|
||||
"steps": [steps.view(s, session.probe, session.probed_at) for s in derived],
|
||||
}
|
||||
if step == grading.TOOLBOX_STEP:
|
||||
state["toolbox"] = [
|
||||
{"name": e.name, "properties": list(e.properties)}
|
||||
for e in self.deps.box().entries
|
||||
]
|
||||
return state
|
||||
|
||||
def publish(self) -> None:
|
||||
"""Rebuild the state; move ``rev`` and tell listeners if it changed."""
|
||||
with self.lock:
|
||||
body = self._build()
|
||||
seen = json.dumps(body, sort_keys=True)
|
||||
if seen == self._seen:
|
||||
return
|
||||
self._seen = seen
|
||||
self.rev += 1
|
||||
self._state = {**body, "rev": self.rev}
|
||||
if self.session is not None:
|
||||
save(self.live_path, self.session, self.rev)
|
||||
state, session = self._state, self.session
|
||||
for listener in self.listeners:
|
||||
listener(state, session)
|
||||
|
||||
def live(self, sid: object) -> Session:
|
||||
"""The live session `sid` names, or `not_live`."""
|
||||
session = self.session
|
||||
if session is None or session.ended is not None or session.sid != sid:
|
||||
msg = "That session is not the live one any more."
|
||||
raise CoachError(msg, code="not_live")
|
||||
return session
|
||||
|
||||
def end(self, session: Session, reason: str) -> None:
|
||||
"""Close `session` (it stays in the state, read-only)."""
|
||||
session.log_event("session_end", reason=reason, at=self.now())
|
||||
session.ended = self.now()
|
||||
session.end_reason = reason
|
||||
|
||||
def _dispatch(self, req: protocol.Request) -> dict[str, Any]:
|
||||
body = req.body
|
||||
if req.kind == "session_start":
|
||||
return turns.start(self, req)
|
||||
session = self.live(body.get("session"))
|
||||
if req.kind == "session_end":
|
||||
self.end(session, "ended")
|
||||
return {}
|
||||
if req.kind == "grade_step":
|
||||
return grading.grade_step(self, session, body)
|
||||
if req.kind == "run_code":
|
||||
return turns.run_code(self, session, str(body["code"]))
|
||||
text = {"hint": "hint", "reveal": "reveal"}.get(req.kind, body.get("text"))
|
||||
return turns.chat(self, session, str(text))
|
||||
|
||||
def handle(self, req: protocol.Request) -> dict[str, Any]:
|
||||
"""Run one request; its result (section 2)."""
|
||||
with self.lock:
|
||||
self.chat.deadline = self.chat.monotonic() + REQUEST_CAP_S
|
||||
try:
|
||||
data = self._dispatch(req)
|
||||
except CoachError as exc:
|
||||
# An answer kuhy sees, not a crash; the journal says why too.
|
||||
_logger.warning("%s %s: %s (%s)", req.kind, req.rid, exc.code, exc)
|
||||
self.publish()
|
||||
return protocol.failure(
|
||||
exc.code, str(exc), at=self.now(), retry=exc.retry, **exc.extra
|
||||
)
|
||||
self.publish()
|
||||
return protocol.ok(data, at=self.now(), state_rev=self.rev)
|
||||
|
||||
def tick(self) -> None:
|
||||
"""Probe for step 4's Accepted, at most once a minute, off the lock."""
|
||||
session = self.session
|
||||
if session is None or session.ended is not None:
|
||||
return
|
||||
current = steps.open_step(steps.derive(session.events()))
|
||||
if current is None or current.n != steps.IMPLEMENT:
|
||||
return
|
||||
if not self.deps.probe.due():
|
||||
return
|
||||
status = self.deps.probe.check(session.slug, session.started)
|
||||
with self.lock:
|
||||
if self.session is not session or session.ended is not None:
|
||||
return
|
||||
session.probe, session.probed_at = status, self.now()
|
||||
if status == ACCEPTED:
|
||||
at = self.now()
|
||||
event = {"step": 4, "grade": "pass", "attempt": 1, "forced": False}
|
||||
event |= {"via": "accepted", "feedback": "", "at": at}
|
||||
session.log_event("grade", **event)
|
||||
kind, text = grade_line(event)
|
||||
session.add("system", kind, text, at)
|
||||
session.notes.append(ACCEPTED_NOTE)
|
||||
self.publish()
|
||||
48
leetcode_coach/leetcode_coach/relay/config.py
Normal file
48
leetcode_coach/leetcode_coach/relay/config.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Where the relay keeps its files, and its test seams (contract section 7).
|
||||
|
||||
Every default is resolved at call time, so a test that sets an env var after
|
||||
import still moves the path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
from typing import Final
|
||||
|
||||
DIR_ENV: Final = "LEETCODE_COACH_RELAY_DIR"
|
||||
PORT_ENV: Final = "LEETCODE_COACH_RELAY_PORT"
|
||||
RTDB_ENV: Final = "LEETCODE_COACH_RTDB_URL"
|
||||
CARDS_DRY_RUN_ENV: Final = "LEETCODE_COACH_CARDS_DRY_RUN"
|
||||
DEFAULT_DIR: Final = Path.home() / ".local" / "share" / "leetcode-coach" / "relay"
|
||||
HOST: Final = "127.0.0.1"
|
||||
DEFAULT_PORT: Final = 8777
|
||||
APP_NAME: Final = "leetcode_coach_relay"
|
||||
"""The crdt_sync app the relay signs in as (its own token cache)."""
|
||||
|
||||
|
||||
def state_dir() -> Path:
|
||||
"""``~/.local/share/leetcode-coach/relay`` unless ``$LEETCODE_COACH_RELAY_DIR``."""
|
||||
override = os.environ.get(DIR_ENV)
|
||||
return Path(override) if override else DEFAULT_DIR
|
||||
|
||||
|
||||
def port() -> int:
|
||||
"""The loopback port (8777 unless ``$LEETCODE_COACH_RELAY_PORT``)."""
|
||||
return int(os.environ.get(PORT_ENV) or DEFAULT_PORT)
|
||||
|
||||
|
||||
def rtdb_url() -> str | None:
|
||||
"""A database URL that skips Firebase sign-in (the fake RTDB), if set."""
|
||||
return os.environ.get(RTDB_ENV) or None
|
||||
|
||||
|
||||
def cards_dry_run() -> bool:
|
||||
"""Whether step 5 only validates its cards (the live smoke run)."""
|
||||
return os.environ.get(CARDS_DRY_RUN_ENV) == "1"
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
"""Wall-clock unix milliseconds."""
|
||||
return time.time_ns() // 1_000_000
|
||||
107
leetcode_coach/leetcode_coach/relay/done.py
Normal file
107
leetcode_coach/leetcode_coach/relay/done.py
Normal file
@ -0,0 +1,107 @@
|
||||
"""The done-map: every finished rid and its result (DOCS-coach-relay.md 1).
|
||||
|
||||
A client that lost the answer sends the SAME rid again, and the relay must
|
||||
re-answer it, never re-run it: a re-run chat turn would spend a model call
|
||||
and post a second reply. So every result -- ``bad_request`` and
|
||||
``rate_limited`` included -- lands here before anyone is told. Kept in
|
||||
``requests_done.jsonl`` for 30 days, so a relay restart still knows; a
|
||||
desktop result is forgotten after 24 h (the wrapper polls for seconds).
|
||||
|
||||
Appends are one ``os.write`` on an ``O_APPEND`` descriptor, like the session
|
||||
log. The file is compacted at start-up, when expired lines are dropped.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
DAY_MS: Final = 24 * 3600 * 1000
|
||||
KEEP_MS: Final = 30 * DAY_MS
|
||||
DESKTOP_KEEP_MS: Final = DAY_MS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Done:
|
||||
"""One finished request."""
|
||||
|
||||
rid: str
|
||||
at: int
|
||||
transport: str
|
||||
result: dict[str, Any]
|
||||
|
||||
|
||||
def _parse(line: str) -> Done | None:
|
||||
try:
|
||||
raw = json.loads(line)
|
||||
return Done(
|
||||
str(raw["rid"]), int(raw["at"]), str(raw["transport"]), dict(raw["result"])
|
||||
)
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
_logger.warning("done-map line skipped: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
class DoneMap:
|
||||
"""Finished rids, in memory and on disk."""
|
||||
|
||||
def __init__(self, path: Path, clock_ms: Callable[[], int]) -> None:
|
||||
"""Load `path`, dropping (and compacting away) expired results."""
|
||||
self._path = path
|
||||
self._clock = clock_ms
|
||||
self._lock = threading.Lock()
|
||||
self._done: dict[str, Done] = {}
|
||||
lines = path.read_text(encoding="utf-8").splitlines() if path.is_file() else []
|
||||
cutoff = clock_ms() - KEEP_MS
|
||||
for line in lines:
|
||||
done = _parse(line) if line.strip() else None
|
||||
if done is not None and done.at >= cutoff:
|
||||
self._done[done.rid] = done
|
||||
if len(self._done) != len(lines):
|
||||
self._rewrite()
|
||||
|
||||
def _line(self, done: Done) -> bytes:
|
||||
record = {
|
||||
"rid": done.rid,
|
||||
"at": done.at,
|
||||
"transport": done.transport,
|
||||
"result": done.result,
|
||||
}
|
||||
return (json.dumps(record, ensure_ascii=False) + "\n").encode()
|
||||
|
||||
def _rewrite(self) -> None:
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = self._path.with_suffix(".tmp")
|
||||
tmp.write_bytes(b"".join(self._line(d) for d in self._done.values()))
|
||||
tmp.replace(self._path)
|
||||
|
||||
def put(self, rid: str, transport: str, result: dict[str, Any]) -> None:
|
||||
"""Record `rid`'s result (before any client is told about it)."""
|
||||
done = Done(rid, self._clock(), transport, result)
|
||||
with self._lock:
|
||||
self._done[rid] = done
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(self._path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
||||
try:
|
||||
os.write(fd, self._line(done))
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def get(self, rid: str) -> Done | None:
|
||||
"""The finished request, unless it expired (24 h for the desktop)."""
|
||||
with self._lock:
|
||||
done = self._done.get(rid)
|
||||
if done is None:
|
||||
return None
|
||||
keep = DESKTOP_KEEP_MS if done.transport == "desktop" else KEEP_MS
|
||||
return done if self._clock() - done.at <= keep else None
|
||||
16
leetcode_coach/leetcode_coach/relay/errors.py
Normal file
16
leetcode_coach/leetcode_coach/relay/errors.py
Normal file
@ -0,0 +1,16 @@
|
||||
"""The one exception a request handler raises to answer with an error result."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class CoachError(Exception):
|
||||
"""Answer the request with ``code``; the message is shown to kuhy."""
|
||||
|
||||
def __init__(
|
||||
self, message: str, *, code: str, retry: bool = False, **extra: object
|
||||
) -> None:
|
||||
"""Keep the result fields (section 2's error codes)."""
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.retry = retry
|
||||
self.extra = extra
|
||||
127
leetcode_coach/leetcode_coach/relay/examples.py
Normal file
127
leetcode_coach/leetcode_coach/relay/examples.py
Normal file
@ -0,0 +1,127 @@
|
||||
"""The statement's worked examples and the starter's function name (run_code).
|
||||
|
||||
The statement is ``fetch_problem.render(q, "javascript")`` markdown. LeetCode
|
||||
writes an example in three shapes, all handled by one line scan: bold labels
|
||||
on plain lines (``**Input:** nums = [3,0,1]``), the same with the values in
|
||||
code spans, and the same inside a ``` fence. An ``Input:`` line is
|
||||
``name = <json>`` pairs split on top-level commas; the following ``Output:``
|
||||
line closes the example. A value that is not JSON (a linked list drawn as
|
||||
``1->2``, a design problem's call list) skips that example with a warning:
|
||||
running kuhy's code against a guessed input would report a wrong "got".
|
||||
|
||||
Examples are numbered by their place in the statement, so "example 3" is the
|
||||
one kuhy reads as Example 3 even when an earlier one was skipped. Only the
|
||||
body counts: the starter code and the site hints come after the first
|
||||
``## `` heading and are never scanned for examples.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Final
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
_NAME_RES: Final = (
|
||||
re.compile(r"\b(?:var|let|const)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:function\b|\()"),
|
||||
re.compile(r"\bfunction\s+([A-Za-z_$][\w$]*)\s*\("),
|
||||
)
|
||||
_LABEL: Final = re.compile(r"^(Input|Output)\s*:\s*(.*)$")
|
||||
_PAIR: Final = re.compile(r"^([A-Za-z_]\w*)\s*=\s*(.+)$", re.DOTALL)
|
||||
_STARTER: Final = "## Starter code"
|
||||
_OPENERS: Final = {"[": "]", "{": "}", "(": ")"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Example:
|
||||
"""One worked example: its number, the call's arguments, the answer."""
|
||||
|
||||
n: int
|
||||
args: tuple[object, ...]
|
||||
expected: object
|
||||
|
||||
|
||||
def function_name(statement: str) -> str | None:
|
||||
"""The function the starter code declares (starter section first)."""
|
||||
starter = statement.split(_STARTER, 1)
|
||||
for text in (starter[-1], statement):
|
||||
for pattern in _NAME_RES:
|
||||
if match := pattern.search(text):
|
||||
return match.group(1)
|
||||
return None
|
||||
|
||||
|
||||
def split_top_level(text: str) -> list[str]:
|
||||
"""``text`` split on commas outside brackets and string literals."""
|
||||
parts: list[str] = []
|
||||
depth = 0
|
||||
quoted = escaped = False
|
||||
start = 0
|
||||
for i, ch in enumerate(text):
|
||||
if escaped:
|
||||
escaped = False
|
||||
elif quoted:
|
||||
escaped = ch == "\\"
|
||||
quoted = ch != '"'
|
||||
elif ch == '"':
|
||||
quoted = True
|
||||
elif ch in _OPENERS:
|
||||
depth += 1
|
||||
elif ch in _OPENERS.values():
|
||||
depth -= 1
|
||||
elif ch == "," and depth == 0:
|
||||
parts.append(text[start:i])
|
||||
start = i + 1
|
||||
parts.append(text[start:])
|
||||
return [p.strip() for p in parts]
|
||||
|
||||
|
||||
def _arguments(text: str) -> tuple[object, ...]:
|
||||
"""The values of ``a = 1, b = [2]``; ValueError when one is not JSON."""
|
||||
values: list[object] = []
|
||||
for part in split_top_level(text):
|
||||
match = _PAIR.match(part)
|
||||
if match is None:
|
||||
msg = f"not a name = value pair: {part[:40]!r}"
|
||||
raise ValueError(msg)
|
||||
values.append(json.loads(match.group(2)))
|
||||
return tuple(values)
|
||||
|
||||
|
||||
def _clean(line: str) -> str:
|
||||
"""A line without markdown emphasis, code ticks and (nb)spaces around it."""
|
||||
return line.replace("**", "").replace("`", "").strip()
|
||||
|
||||
|
||||
def _labels(body: str) -> list[tuple[str, str]]:
|
||||
"""Every ``(Input|Output, value)`` line of the body, in order."""
|
||||
matches = (_LABEL.match(_clean(raw)) for raw in body.splitlines())
|
||||
return [(m.group(1), m.group(2).strip()) for m in matches if m is not None]
|
||||
|
||||
|
||||
def _body(statement: str) -> str:
|
||||
"""The statement above its first ``## `` section (starter, hints)."""
|
||||
return re.split(r"^## ", statement, maxsplit=1, flags=re.MULTILINE)[0]
|
||||
|
||||
|
||||
def parse(statement: str) -> tuple[str | None, list[Example]]:
|
||||
"""The starter's function name and every example that parses."""
|
||||
found: list[Example] = []
|
||||
pending: str | None = None
|
||||
number = 0
|
||||
for label, value in _labels(_body(statement)):
|
||||
if label == "Input":
|
||||
pending = value
|
||||
continue
|
||||
if pending is None:
|
||||
continue
|
||||
number += 1
|
||||
try:
|
||||
found.append(Example(number, _arguments(pending), json.loads(value)))
|
||||
except ValueError as exc:
|
||||
_logger.warning("example %d skipped, not runnable: %s", number, exc)
|
||||
pending = None
|
||||
return function_name(statement), found
|
||||
141
leetcode_coach/leetcode_coach/relay/graders.py
Normal file
141
leetcode_coach/leetcode_coach/relay/graders.py
Normal file
@ -0,0 +1,141 @@
|
||||
"""Steps 1 and 5 on a cheap model; the feedback rules every grade obeys.
|
||||
|
||||
Same route as the requirement checker (`req_check.ask_models`): haiku with no
|
||||
tools, then Ollama, and when neither answers the step passes ``unverified``
|
||||
(fail open: a grader outage must never wall kuhy in). The answer key goes to
|
||||
the grader and nowhere else, so feedback is checked mechanically before it is
|
||||
shown: it may not name a toolbox entry kuhy has not named yet (until the
|
||||
first code, `leak.leaked_names`), and it may not quote the key (any run of
|
||||
`QUOTE_WORDS` words from it). A failing feedback is replaced by the plain
|
||||
missing-property line.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach import leak, req_check
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.answer_key import Answer
|
||||
from leetcode_coach.toolbox import Toolbox
|
||||
|
||||
GRADES: Final = ("pass", "partial", "fail")
|
||||
QUOTE_WORDS: Final = 5
|
||||
POSTMORTEM_STEP: Final = 5
|
||||
UNVERIFIED: Final = "Not checked: the grader could not be reached, so this step counts."
|
||||
CONSTRAINT_HINT: Final = "Name the limit that binds and say what it rules out."
|
||||
_RULES: Final = (
|
||||
'Reply with ONE JSON object and nothing else: {"grade": "pass" | '
|
||||
'"partial" | "fail", "feedback": "<one or two sentences>"}. The feedback '
|
||||
"names what is missing as a property of a good answer. Never name an "
|
||||
"operation, a data structure or an algorithm, never give the solution, and "
|
||||
"never quote or paraphrase the reference: it is secret."
|
||||
)
|
||||
CONSTRAINT_SYSTEM: Final = (
|
||||
"You grade one step of a student's method for a programming problem: "
|
||||
"naming the binding constraint and what it forces. pass = the answer names "
|
||||
"the limit that binds and what it rules out or forces; partial = only one "
|
||||
"of the two; fail = neither. " + _RULES
|
||||
)
|
||||
POSTMORTEM_SYSTEM: Final = (
|
||||
"You grade a student's post-mortem, written after solving a programming "
|
||||
"problem: which properties of the operation did the work, and how they "
|
||||
"could have found it from the constraints. pass = it names the key "
|
||||
"properties and at least one of the reference points; partial = some of "
|
||||
"them; fail = none. Property names from the key list may be used in the "
|
||||
"feedback. " + _RULES
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Grade:
|
||||
"""One grader answer."""
|
||||
|
||||
grade: str
|
||||
feedback: str
|
||||
via: str
|
||||
|
||||
|
||||
def _valid(obj: dict[str, Any] | None) -> Grade | None:
|
||||
if obj is None or obj.get("grade") not in GRADES:
|
||||
return None
|
||||
feedback = obj.get("feedback", "")
|
||||
if not isinstance(feedback, str):
|
||||
return None
|
||||
return Grade(str(obj["grade"]), feedback.strip(), "")
|
||||
|
||||
|
||||
def _prompt(step: int, statement: str, answer: str, key: Answer) -> str:
|
||||
if step == 1:
|
||||
reference = f"## Reference rule (secret)\n{key.design_rule}"
|
||||
else:
|
||||
points = "\n".join(f"- {p}" for p in key.postmortem_points)
|
||||
reference = (
|
||||
f"## Reference (secret)\nRule: {key.design_rule}\n"
|
||||
f"Key properties: {', '.join(key.key_requirements)}\nPoints:\n{points}"
|
||||
)
|
||||
return (
|
||||
f"## Problem\n{statement.strip()}\n\n{reference}\n\n"
|
||||
f"## Student's answer\n{answer.strip()}\n"
|
||||
)
|
||||
|
||||
|
||||
def model_grade(
|
||||
step: int,
|
||||
statement: str,
|
||||
answer: str,
|
||||
key: Answer,
|
||||
ask: Callable[..., dict[str, Any]] | None,
|
||||
) -> Grade:
|
||||
"""Grade step 1 (constraint) or 5 (post-mortem); ``unverified`` pass if down."""
|
||||
system = CONSTRAINT_SYSTEM if step == 1 else POSTMORTEM_SYSTEM
|
||||
got = req_check.ask_models(
|
||||
system, _prompt(step, statement, answer, key), _valid, ask
|
||||
)
|
||||
if got is None:
|
||||
return Grade("pass", UNVERIFIED, "unverified")
|
||||
grade, via = got
|
||||
return Grade(grade.grade, grade.feedback, via)
|
||||
|
||||
|
||||
def _words(text: str) -> list[str]:
|
||||
return re.findall(r"[a-z0-9]+", text.lower())
|
||||
|
||||
|
||||
def quotes_key(feedback: str, key: Answer) -> bool:
|
||||
"""Whether `feedback` repeats `QUOTE_WORDS` consecutive words of the key."""
|
||||
said = " ".join(_words(feedback))
|
||||
for source in (key.design_rule, *key.postmortem_points):
|
||||
words = _words(source)
|
||||
for i in range(len(words) - QUOTE_WORDS + 1):
|
||||
if " ".join(words[i : i + QUOTE_WORDS]) in said:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def fallback(step: int, key: Answer) -> str:
|
||||
"""The plain missing-property line a rejected feedback becomes."""
|
||||
if step == POSTMORTEM_STEP:
|
||||
return "Say which properties did the work: " + ", ".join(key.key_requirements)
|
||||
return CONSTRAINT_HINT
|
||||
|
||||
|
||||
def safe_feedback( # pylint: disable=too-many-arguments
|
||||
feedback: str,
|
||||
*,
|
||||
step: int,
|
||||
key: Answer,
|
||||
box: Toolbox,
|
||||
kuhy_texts: list[str],
|
||||
code_seen: bool,
|
||||
) -> str:
|
||||
"""`feedback`, or `fallback` when it names an entry early or quotes the key."""
|
||||
early = not code_seen and leak.leaked_names(feedback, kuhy_texts, box)
|
||||
if early or quotes_key(feedback, key):
|
||||
return fallback(step, key)
|
||||
return feedback
|
||||
166
leetcode_coach/leetcode_coach/relay/grading.py
Normal file
166
leetcode_coach/leetcode_coach/relay/grading.py
Normal file
@ -0,0 +1,166 @@
|
||||
"""``grade_step``: grade steps 1, 2, 3 and 5, or let kuhy continue (force).
|
||||
|
||||
1 and 5 go to the model grader (`graders`), 2 to the CLI's own phase gate
|
||||
(`PhaseGate.screen` logs ``req`` + ``req_check``), 3 to the mechanical
|
||||
toolbox grader. Every graded try is one ``grade`` event; the step machine
|
||||
reads them back (`steps`). The grade reaches the coach as a note on its next
|
||||
turn and the chat as a ``system`` line at once. A step-5 pass builds the
|
||||
cards and ends the session (``done``); so does forcing step 5, without cards.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach import gate_notes, leak, phase, shape
|
||||
from leetcode_coach.relay import cards, graders, steps, toolbox_grade, turns
|
||||
from leetcode_coach.relay.errors import CoachError
|
||||
from leetcode_coach.relay.session import grade_line
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leetcode_coach.answer_key import Answer
|
||||
from leetcode_coach.relay.coach import Coach
|
||||
from leetcode_coach.relay.session import Session
|
||||
from leetcode_coach.toolbox import Toolbox
|
||||
|
||||
REQ_STEP: Final = 2
|
||||
TOOLBOX_STEP: Final = 3
|
||||
POSTMORTEM_STEP: Final = 5
|
||||
READS_AS_CODE: Final = (
|
||||
"This reads as code. List the properties the operation must have, in words."
|
||||
)
|
||||
NAMES_A_TOOL: Final = (
|
||||
"This names an operation or a structure. List the properties it must have "
|
||||
"instead, without naming it."
|
||||
)
|
||||
|
||||
|
||||
def _requirements(session: Session, answer: str, box: Toolbox) -> tuple[str, str, str]:
|
||||
"""Step 2 through the phase gate; a list that is code or names a tool fails.
|
||||
|
||||
A SQL problem's step 2 is the output shape (judged mechanically, `shape`).
|
||||
"""
|
||||
text = answer.strip()
|
||||
sql = session.gate.sql()
|
||||
prefix = shape.SHAPE_RE if sql and shape.SHAPE_RE.match(text) else phase.REQ_RE
|
||||
words = prefix.sub("", text, count=1).strip()
|
||||
if phase.regex_verdict(words) is True:
|
||||
return "fail", READS_AS_CODE, "toolbox"
|
||||
if not sql and leak.leaked_names(words, [], box):
|
||||
return "fail", NAMES_A_TOOL, "toolbox"
|
||||
session.gate.screen(text if prefix.match(text) else f"req: {text}")
|
||||
check = [e for e in session.events() if e.get("event") == "req_check"][-1]
|
||||
via = str(check.get("via") or "unverified")
|
||||
if check.get("verdict") == "pass":
|
||||
return "pass", "", via
|
||||
if check.get("verdict") == "unverified":
|
||||
return "pass", graders.UNVERIFIED, "unverified"
|
||||
missing = [str(m) for m in check.get("missing", [])]
|
||||
if sql:
|
||||
lines = [f"- {h}" for h in shape.hints(missing)]
|
||||
else:
|
||||
lines = [
|
||||
f"- {gate_notes.property_line(m, box)}"
|
||||
for m in missing
|
||||
if m in box.properties
|
||||
]
|
||||
return "partial", "\n".join(["It does not yet say:", *lines]), via
|
||||
|
||||
|
||||
def _toolbox(picks: list[str], key: Answer, box: Toolbox) -> tuple[str, str, str]:
|
||||
unknown = [p for p in picks if toolbox_grade.resolve(p, box) is None]
|
||||
if unknown:
|
||||
msg = "Not in the toolbox: " + ", ".join(unknown)
|
||||
raise CoachError(msg, code="bad_request")
|
||||
grade, feedback = toolbox_grade.grade(picks, key, box)
|
||||
return grade, feedback, "toolbox"
|
||||
|
||||
|
||||
def _graded(
|
||||
coach: Coach, session: Session, n: int, body: dict[str, Any]
|
||||
) -> tuple[str, str, str]:
|
||||
key = coach.deps.answers()[session.slug]
|
||||
box = coach.deps.box()
|
||||
if n == TOOLBOX_STEP:
|
||||
return _toolbox(list(body["picks"]), key, box)
|
||||
if n == REQ_STEP:
|
||||
return _requirements(session, str(body["answer"]), box)
|
||||
text = turns.statement(coach, session) or session.slug
|
||||
got = graders.model_grade(n, text, str(body["answer"]), key, coach.deps.ask)
|
||||
users = [str(v["text"]) for v in session.chat.values() if v["role"] == "kuhy"]
|
||||
feedback = graders.safe_feedback(
|
||||
got.feedback,
|
||||
step=n,
|
||||
key=key,
|
||||
box=box,
|
||||
kuhy_texts=users,
|
||||
code_seen=session.gate.code_seen(),
|
||||
)
|
||||
return got.grade, feedback, got.via
|
||||
|
||||
|
||||
def _record(session: Session, event: dict[str, Any]) -> int | None:
|
||||
"""Log one grade event, show it, note it for the coach; the step now open."""
|
||||
session.log_event("grade", **event)
|
||||
kind, text = grade_line(event)
|
||||
session.add("system", kind, text, int(event["at"]))
|
||||
current = steps.open_step(steps.derive(session.events()))
|
||||
nxt = None if current is None else current.n
|
||||
what = "continued without a pass" if event["forced"] else f"graded {event['grade']}"
|
||||
opened = "all steps done" if nxt is None else f"step {nxt} open"
|
||||
note = f"[app: step {event['step']} {what} on try {event['attempt']}; {opened}]"
|
||||
session.notes.append(note)
|
||||
return nxt
|
||||
|
||||
|
||||
def _force(coach: Coach, session: Session, step: steps.Step) -> dict[str, Any]:
|
||||
if not step.can_force:
|
||||
msg = f"You can continue after {steps.FORCE_AFTER} tries without a pass."
|
||||
raise CoachError(msg, code="cannot_force")
|
||||
last = step.last or {}
|
||||
event = {"step": step.n, "grade": last.get("grade") or "fail"}
|
||||
event |= {"attempt": step.attempts, "forced": True, "feedback": ""}
|
||||
event |= {"via": last.get("via") or "unverified", "at": coach.now()}
|
||||
nxt = _record(session, event)
|
||||
if step.n == POSTMORTEM_STEP:
|
||||
coach.end(session, "done")
|
||||
return {"step": step.n, "forced": True, "next_step": nxt}
|
||||
|
||||
|
||||
def grade_step(coach: Coach, session: Session, body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Grade (or force) ``body.step`` of the live session."""
|
||||
n = int(body["step"])
|
||||
step = steps.derive(session.events())[n - 1]
|
||||
if body.get("force") is True and n == steps.IMPLEMENT:
|
||||
msg = "Step 4 passes only when LeetCode shows an Accepted."
|
||||
raise CoachError(msg, code="cannot_force")
|
||||
if step.status == "locked":
|
||||
msg = f"Step {n} opens once step {n - 1} is passed or continued."
|
||||
raise CoachError(msg, code="step_locked")
|
||||
if step.done:
|
||||
msg = f"Step {n} is already done."
|
||||
raise CoachError(msg, code="step_done")
|
||||
if body.get("force") is True:
|
||||
return _force(coach, session, step)
|
||||
attempt = step.attempts + 1
|
||||
grade, feedback, via = _graded(coach, session, n, body)
|
||||
event = {"step": n, "grade": grade, "attempt": attempt, "forced": False}
|
||||
event |= {"via": via, "feedback": feedback, "at": coach.now()}
|
||||
nxt = _record(session, event)
|
||||
after = steps.derive(session.events())[n - 1]
|
||||
data: dict[str, Any] = {
|
||||
"step": n,
|
||||
"grade": grade,
|
||||
"feedback": feedback,
|
||||
"attempt": attempt,
|
||||
"can_force": after.can_force,
|
||||
"via": via,
|
||||
"next_step": nxt,
|
||||
}
|
||||
if n == POSTMORTEM_STEP and grade == "pass":
|
||||
key = coach.deps.answers()[session.slug]
|
||||
data["cards"] = cards.build(
|
||||
session, key.entries, dry_run=coach.deps.cards_dry_run
|
||||
)
|
||||
coach.end(session, "done")
|
||||
return data
|
||||
162
leetcode_coach/leetcode_coach/relay/http_api.py
Normal file
162
leetcode_coach/leetcode_coach/relay/http_api.py
Normal file
@ -0,0 +1,162 @@
|
||||
"""The desktop's loopback API on 127.0.0.1:8777 (DOCS-coach-relay.md 1, 4).
|
||||
|
||||
Reached only through the app's wrapper on :8776, never by the browser. It
|
||||
binds the loopback address, refuses a ``Host`` other than its own (DNS
|
||||
rebinding) and takes POST bodies only as ``application/json``, so a
|
||||
cross-origin POST needs a preflight that is never granted. No route takes a
|
||||
path, a command or a URL; a request body goes to `protocol.parse` and from
|
||||
there to the lane, like the phone's.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, Final, Protocol
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from leetcode_coach.relay import protocol
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leetcode_coach.relay.coach import Coach
|
||||
from leetcode_coach.relay.lane import Lane
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
PREFIX: Final = "/coach/"
|
||||
REQUESTS: Final = "/coach/requests"
|
||||
CHAT_KEY_RE_LEN: Final = 5
|
||||
|
||||
|
||||
class App(Protocol):
|
||||
"""What the API serves: the lane, the backend and the heartbeat."""
|
||||
|
||||
lane: Lane
|
||||
coach: Coach
|
||||
|
||||
def heartbeat(self) -> dict[str, Any]:
|
||||
"""The heartbeat object, ``beat`` as unix ms."""
|
||||
|
||||
|
||||
class Server(ThreadingHTTPServer):
|
||||
"""A threading server that knows its relay."""
|
||||
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self, address: tuple[str, int], app: App) -> None:
|
||||
"""Bind `address` and keep `app` for the handlers."""
|
||||
super().__init__(address, Handler)
|
||||
self.app = app
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
"""The four GET routes and the one POST."""
|
||||
|
||||
server: Server
|
||||
server_version = "leetcode-coach-relay"
|
||||
|
||||
def log_message(self, fmt: str, /, *args: object) -> None:
|
||||
"""Request lines to the journal at debug, not stderr."""
|
||||
_logger.debug("%s - %s", self.address_string(), fmt % args)
|
||||
|
||||
def _send(self, status: HTTPStatus, payload: object) -> None:
|
||||
body = json.dumps(payload, ensure_ascii=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _error(self, status: HTTPStatus, code: str, error: str) -> None:
|
||||
self._send(status, {"ok": False, "code": code, "error": error})
|
||||
|
||||
def _host_ok(self) -> bool:
|
||||
port = self.server.server_address[1]
|
||||
host = self.headers.get("Host", "")
|
||||
if host in {f"127.0.0.1:{port}", f"localhost:{port}"}:
|
||||
return True
|
||||
_logger.warning("refused a request for Host %r", host)
|
||||
self._error(HTTPStatus.FORBIDDEN, "bad_host", "loopback only")
|
||||
return False
|
||||
|
||||
def do_GET(self) -> None:
|
||||
"""State, heartbeat, chat, or one request's result."""
|
||||
if not self._host_ok():
|
||||
return
|
||||
url = urlsplit(self.path)
|
||||
app = self.server.app
|
||||
if url.path == "/coach/state":
|
||||
self._send(HTTPStatus.OK, app.coach.state())
|
||||
elif url.path == "/coach/heartbeat":
|
||||
self._send(HTTPStatus.OK, app.heartbeat())
|
||||
elif url.path == "/coach/chat":
|
||||
after = parse_qs(url.query).get("after", [None])[0]
|
||||
self._send(HTTPStatus.OK, app.coach.chat_after(after))
|
||||
elif url.path.startswith(REQUESTS + "/"):
|
||||
rid = url.path.removeprefix(REQUESTS + "/")
|
||||
if not protocol.RID_RE.fullmatch(rid) or not app.lane.known(rid):
|
||||
self._error(HTTPStatus.NOT_FOUND, "unknown_rid", "no such request")
|
||||
return
|
||||
self._send(HTTPStatus.OK, {"result": app.lane.result(rid)})
|
||||
else:
|
||||
self._error(HTTPStatus.NOT_FOUND, "not_found", "no such route")
|
||||
|
||||
def _body(self) -> object:
|
||||
"""The decoded JSON body, or None after an error answer was sent."""
|
||||
ctype = self.headers.get("Content-Type", "").split(";")[0].strip()
|
||||
if ctype != "application/json":
|
||||
self._error(
|
||||
HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "bad_request", "JSON bodies only"
|
||||
)
|
||||
return None
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
except ValueError:
|
||||
length = -1
|
||||
_logger.warning("a POST with a bad Content-Length")
|
||||
if length > protocol.MAX_REQ_BYTES:
|
||||
self._error(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "bad_request", "too big")
|
||||
return None
|
||||
if length < 0:
|
||||
self._error(HTTPStatus.BAD_REQUEST, "bad_request", "bad length")
|
||||
return None
|
||||
try:
|
||||
return json.loads(self.rfile.read(length) or b"null")
|
||||
except ValueError as exc:
|
||||
_logger.warning("a POST body that is not JSON: %s", exc)
|
||||
self._error(HTTPStatus.BAD_REQUEST, "bad_request", "not JSON")
|
||||
return None
|
||||
|
||||
def do_POST(self) -> None:
|
||||
"""Queue one request: 202, or 200 with its result when already known."""
|
||||
if not self._host_ok():
|
||||
return
|
||||
if urlsplit(self.path).path != REQUESTS:
|
||||
self._error(HTTPStatus.NOT_FOUND, "not_found", "no such route")
|
||||
return
|
||||
raw = self._body()
|
||||
if raw is None:
|
||||
return
|
||||
lane = self.server.app.lane
|
||||
try:
|
||||
req = protocol.parse(raw, "desktop")
|
||||
except protocol.BadRidError as exc:
|
||||
_logger.warning("desktop request refused: %s", exc)
|
||||
self._error(HTTPStatus.BAD_REQUEST, "bad_request", str(exc))
|
||||
return
|
||||
except protocol.BadRequestError as exc:
|
||||
_logger.warning("bad desktop request: %s", exc)
|
||||
rid = str(raw["rid"]) if isinstance(raw, dict) else ""
|
||||
if (done := lane.result(rid)) is None:
|
||||
done = protocol.failure("bad_request", str(exc), at=lane.now())
|
||||
lane.finish(rid, "desktop", done)
|
||||
self._send(HTTPStatus.OK, done)
|
||||
return
|
||||
result = lane.submit(req)
|
||||
if result is None:
|
||||
self._send(HTTPStatus.ACCEPTED, {"rid": req.rid})
|
||||
else:
|
||||
self._send(HTTPStatus.OK, result)
|
||||
149
leetcode_coach/leetcode_coach/relay/lane.py
Normal file
149
leetcode_coach/leetcode_coach/relay/lane.py
Normal file
@ -0,0 +1,149 @@
|
||||
"""The one paced serial lane both transports feed (DOCS-coach-relay.md 1).
|
||||
|
||||
FIFO by arrival; one request runs at a time and none overtakes an earlier
|
||||
one. At most one request *starts* every `pace_s` (3 s), globally across the
|
||||
desktop and the phone; the rest wait. A request arriving while `max_queued`
|
||||
(5) already wait is answered ``rate_limited`` and never runs.
|
||||
|
||||
Every result goes into the done-map before any listener hears of it, so a
|
||||
client that resends a rid is re-answered, never re-run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach.relay import protocol
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.relay.done import DoneMap
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
PACE_S: Final = 3.0
|
||||
MAX_QUEUED: Final = 5
|
||||
|
||||
|
||||
class Lane: # pylint: disable=too-many-instance-attributes
|
||||
"""Queue, pacing and the worker loop around one request handler."""
|
||||
|
||||
def __init__( # pylint: disable=too-many-arguments
|
||||
self,
|
||||
handle: Callable[[protocol.Request], dict[str, Any]],
|
||||
done: DoneMap,
|
||||
*,
|
||||
clock_ms: Callable[[], int],
|
||||
monotonic: Callable[[], float] = time.monotonic,
|
||||
pace_s: float = PACE_S,
|
||||
max_queued: int = MAX_QUEUED,
|
||||
) -> None:
|
||||
"""Bind the handler; nothing runs until `run`."""
|
||||
self._handle = handle
|
||||
self.done = done
|
||||
self._clock = clock_ms
|
||||
self._monotonic = monotonic
|
||||
self._pace = pace_s
|
||||
self._max = max_queued
|
||||
self._cv = threading.Condition()
|
||||
self._queue: deque[protocol.Request] = deque()
|
||||
self._last_start = float("-inf")
|
||||
self.busy: str | None = None
|
||||
self.on_result: list[Callable[[protocol.Request, dict[str, Any]], None]] = []
|
||||
self.on_busy: list[Callable[[str | None], None]] = []
|
||||
|
||||
def now(self) -> int:
|
||||
"""Unix ms, by the relay's clock."""
|
||||
return self._clock()
|
||||
|
||||
def known(self, rid: str) -> bool:
|
||||
"""Whether `rid` is queued, running or finished."""
|
||||
with self._cv:
|
||||
waiting = rid == self.busy or any(r.rid == rid for r in self._queue)
|
||||
return waiting or self.done.get(rid) is not None
|
||||
|
||||
def result(self, rid: str) -> dict[str, Any] | None:
|
||||
"""The finished result of `rid`, or None while it waits or runs."""
|
||||
done = self.done.get(rid)
|
||||
return None if done is None else done.result
|
||||
|
||||
def finish(self, rid: str, transport: str, result: dict[str, Any]) -> None:
|
||||
"""Store a result that never ran (``bad_request``, ``rate_limited``)."""
|
||||
self.done.put(rid, transport, result)
|
||||
|
||||
def submit(self, req: protocol.Request) -> dict[str, Any] | None:
|
||||
"""Queue `req`; its result now if it is already known, else None."""
|
||||
if (done := self.done.get(req.rid)) is not None:
|
||||
return done.result
|
||||
with self._cv:
|
||||
if req.rid == self.busy or any(r.rid == req.rid for r in self._queue):
|
||||
return None
|
||||
if len(self._queue) >= self._max:
|
||||
wait_ms = int(self._pace * 1000 * len(self._queue))
|
||||
result = protocol.failure(
|
||||
"rate_limited",
|
||||
"The PC is busy with earlier requests; send again shortly.",
|
||||
at=self._clock(),
|
||||
retry=True,
|
||||
retry_after_ms=wait_ms,
|
||||
)
|
||||
self.finish(req.rid, req.transport, result)
|
||||
return result
|
||||
self._queue.append(req)
|
||||
self._cv.notify_all()
|
||||
return None
|
||||
|
||||
def _next(self, stop: threading.Event) -> protocol.Request | None:
|
||||
"""The next request once its start slot has come; None when stopping."""
|
||||
with self._cv:
|
||||
while not stop.is_set():
|
||||
if not self._queue:
|
||||
self._cv.wait(0.5)
|
||||
continue
|
||||
delay = self._last_start + self._pace - self._monotonic()
|
||||
if delay > 0:
|
||||
self._cv.wait(delay)
|
||||
continue
|
||||
self._last_start = self._monotonic()
|
||||
req = self._queue.popleft()
|
||||
self.busy = req.rid
|
||||
return req
|
||||
return None
|
||||
|
||||
def _run_one(self, req: protocol.Request) -> dict[str, Any]:
|
||||
try:
|
||||
return self._handle(req)
|
||||
except Exception: # pylint: disable=broad-exception-caught
|
||||
# The traceback goes to the journal only; kuhy sees one line.
|
||||
_logger.exception("request %s (%s) crashed", req.rid, req.kind)
|
||||
return protocol.failure(
|
||||
"worker_error",
|
||||
"The coach hit an internal error; see the relay's journal.",
|
||||
at=self._clock(),
|
||||
)
|
||||
|
||||
def _tell(self, busy: str | None) -> None:
|
||||
for listener in self.on_busy:
|
||||
listener(busy)
|
||||
|
||||
def run(self, stop: threading.Event) -> None:
|
||||
"""Run requests until `stop`; a request already running finishes."""
|
||||
while (req := self._next(stop)) is not None:
|
||||
self._tell(req.rid)
|
||||
result = self._run_one(req)
|
||||
self.done.put(req.rid, req.transport, result)
|
||||
with self._cv:
|
||||
self.busy = None
|
||||
self._tell(None)
|
||||
for listener in self.on_result:
|
||||
listener(req, result)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Wake the worker so it notices its stop event at once."""
|
||||
with self._cv:
|
||||
self._cv.notify_all()
|
||||
105
leetcode_coach/leetcode_coach/relay/outbox.py
Normal file
105
leetcode_coach/leetcode_coach/relay/outbox.py
Normal file
@ -0,0 +1,105 @@
|
||||
"""The phone mirror's writes, in order, on their own thread.
|
||||
|
||||
A hanging Firebase must never stall the desktop: the lane's one worker only
|
||||
*enqueues* (chat lines, ``state``, the heartbeat, a result) and this outbox
|
||||
writes them. Order is the contract's: chat reset / new lines, then
|
||||
``state``, then the heartbeat, then the request's result -- the phone
|
||||
refetches chat when ``heartbeat.state_rev`` moves, so a heartbeat landing
|
||||
before its chat lines would lose one. ``state`` and the heartbeat keep only
|
||||
their latest value (an older one still waiting is dropped, the newer goes to
|
||||
the back); results and chat lines are never dropped. A failed write stays at
|
||||
the front and is retried after a backoff; nothing behind it overtakes it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from leetcode_coach.relay.rtdb import RtdbError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
BACKOFF_S: Final = (1.0, 2.0, 5.0, 10.0, 30.0)
|
||||
IDLE_S: Final = 0.5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Write:
|
||||
"""One pending write: what it is (for the log) and how to do it."""
|
||||
|
||||
what: str
|
||||
run: Callable[[], None]
|
||||
latest: str | None = None
|
||||
"""A key whose older pending writes this one replaces (state, heartbeat)."""
|
||||
|
||||
|
||||
class Outbox:
|
||||
"""An ordered queue of RTDB writes and the loop that drains it."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Start empty; `run` drains on a thread, `drain` in the caller."""
|
||||
self._cv = threading.Condition()
|
||||
self._writes: deque[Write] = deque()
|
||||
|
||||
def put(
|
||||
self, what: str, run: Callable[[], None], latest: str | None = None
|
||||
) -> None:
|
||||
"""Queue one write (replacing a waiting one with the same `latest`)."""
|
||||
with self._cv:
|
||||
if latest is not None:
|
||||
self._writes = deque(w for w in self._writes if w.latest != latest)
|
||||
self._writes.append(Write(what, run, latest))
|
||||
self._cv.notify_all()
|
||||
|
||||
def pending(self) -> list[str]:
|
||||
"""What is still waiting, in order."""
|
||||
with self._cv:
|
||||
return [w.what for w in self._writes]
|
||||
|
||||
def drain(self) -> bool:
|
||||
"""Write everything waiting; False at the first failure (it stays first)."""
|
||||
while True:
|
||||
with self._cv:
|
||||
if not self._writes:
|
||||
return True
|
||||
write = self._writes.popleft()
|
||||
try:
|
||||
write.run()
|
||||
except RtdbError as exc:
|
||||
_logger.warning("RTDB %s failed: %s", write.what, exc)
|
||||
with self._cv:
|
||||
newer = write.latest is not None and any(
|
||||
w.latest == write.latest for w in self._writes
|
||||
)
|
||||
if not newer:
|
||||
self._writes.appendleft(write)
|
||||
return False
|
||||
|
||||
def run(
|
||||
self, stop: threading.Event, wait: Callable[[float], object] | None = None
|
||||
) -> None:
|
||||
"""Drain until `stop`, backing off after a failed write."""
|
||||
pause = stop.wait if wait is None else wait
|
||||
failures = 0
|
||||
while not stop.is_set():
|
||||
with self._cv:
|
||||
if not self._writes:
|
||||
self._cv.wait(IDLE_S)
|
||||
continue
|
||||
if self.drain():
|
||||
failures = 0
|
||||
continue
|
||||
pause(BACKOFF_S[min(failures, len(BACKOFF_S) - 1)])
|
||||
failures += 1
|
||||
|
||||
def wake(self) -> None:
|
||||
"""Let a waiting `run` notice its stop event at once."""
|
||||
with self._cv:
|
||||
self._cv.notify_all()
|
||||
205
leetcode_coach/leetcode_coach/relay/phone.py
Normal file
205
leetcode_coach/leetcode_coach/relay/phone.py
Normal file
@ -0,0 +1,205 @@
|
||||
"""The phone's path: RTDB requests in, results/state/chat/heartbeat out.
|
||||
|
||||
Under ``leetcode-guard/coach/`` (DOCS-coach-relay.md 1). Requests arrive over
|
||||
an SSE stream of ``requests`` and, as a backstop, a rescan every
|
||||
`RESCAN_S` and at start-up; both go through `consider`, which answers a rid
|
||||
the done-map knows from the map (re-PUT, never re-run) and queues the rest
|
||||
on the shared lane. Results, ``state`` (a JSON string leaf) and the chat
|
||||
lines are written as they change; the heartbeat every `HEARTBEAT_S` and on
|
||||
every ``rev`` or busy change. ``requests/{rid}`` goes 24 h after its result.
|
||||
|
||||
Writes only ever *enqueue* (`outbox`): the lane's worker never waits on
|
||||
Firebase, so a hanging or down database never slows the desktop. A failed
|
||||
write is logged and retried in order; the relay never exits over it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach.relay import protocol, sse
|
||||
from leetcode_coach.relay.done import DAY_MS
|
||||
from leetcode_coach.relay.outbox import Outbox
|
||||
from leetcode_coach.relay.rtdb import SERVER_TIME, RtdbError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.relay.coach import Coach
|
||||
from leetcode_coach.relay.lane import Lane
|
||||
from leetcode_coach.relay.rtdb import Rtdb
|
||||
from leetcode_coach.relay.session import Session
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
_REQ_DEPTH: Final = 2
|
||||
"""``{rid}/req``: a path two segments deep."""
|
||||
|
||||
HEARTBEAT_S: Final = 30.0
|
||||
RESCAN_S: Final = 60.0
|
||||
|
||||
|
||||
def _pairs(event: sse.Event) -> list[tuple[list[str], object]]:
|
||||
"""``(path segments, value)`` for every node an event set."""
|
||||
base = [s for s in event.path.split("/") if s]
|
||||
if event.kind == "patch" and isinstance(event.data, dict):
|
||||
return [
|
||||
(base + [s for s in str(k).split("/") if s], v)
|
||||
for k, v in event.data.items()
|
||||
]
|
||||
return [(base, event.data)]
|
||||
|
||||
|
||||
class PhoneLink:
|
||||
"""Mirrors the relay into RTDB and feeds RTDB requests to the lane."""
|
||||
|
||||
def __init__( # pylint: disable=too-many-arguments
|
||||
self,
|
||||
rtdb: Rtdb,
|
||||
lane: Lane,
|
||||
coach: Coach,
|
||||
heartbeat: Callable[[], dict[str, Any]],
|
||||
*,
|
||||
clock_ms: Callable[[], int],
|
||||
heartbeat_s: float = HEARTBEAT_S,
|
||||
rescan_s: float = RESCAN_S,
|
||||
) -> None:
|
||||
"""Bind the database and the relay; call `attach` to start mirroring."""
|
||||
self.rtdb = rtdb
|
||||
self.lane = lane
|
||||
self.coach = coach
|
||||
self._heartbeat = heartbeat
|
||||
self._clock = clock_ms
|
||||
self._beat_every = heartbeat_s
|
||||
self._rescan_every = rescan_s
|
||||
self.outbox = Outbox()
|
||||
self._mirror_lock = threading.Lock()
|
||||
self._chat_sid: str | None = None
|
||||
self._sent: set[str] = set()
|
||||
|
||||
def attach(self) -> None:
|
||||
"""Listen to the lane and the backend; then mirror everything once."""
|
||||
self.lane.on_result.append(self.on_result)
|
||||
self.lane.on_busy.append(lambda _busy: self.beat())
|
||||
self.coach.listeners.append(self.on_state)
|
||||
self._chat_sid = None
|
||||
self.on_state(self.coach.state(), self.coach.session)
|
||||
|
||||
def beat(self) -> None:
|
||||
"""PUT the heartbeat (``beat`` as a server timestamp)."""
|
||||
beat = {**self._heartbeat(), "beat": SERVER_TIME}
|
||||
put = functools.partial(self.rtdb.put, "heartbeat", beat)
|
||||
self.outbox.put("heartbeat", put, latest="heartbeat")
|
||||
|
||||
def put_result(self, rid: str, result: dict[str, Any]) -> None:
|
||||
"""``requests/{rid}/result`` as a JSON string leaf."""
|
||||
text = json.dumps(result, ensure_ascii=False)
|
||||
put = functools.partial(self.rtdb.put, f"requests/{rid}/result", text)
|
||||
self.outbox.put("result", put)
|
||||
|
||||
def on_result(self, req: protocol.Request, result: dict[str, Any]) -> None:
|
||||
"""A finished request: answer it if it came from the phone."""
|
||||
if req.transport == "phone":
|
||||
self.put_result(req.rid, result)
|
||||
|
||||
def on_state(self, state: dict[str, Any], session: Session | None) -> None:
|
||||
"""Queue the chat lines, then ``state``, then the heartbeat."""
|
||||
text = json.dumps(state, ensure_ascii=False)
|
||||
with self._mirror_lock:
|
||||
sid = None if session is None else session.sid
|
||||
if sid != self._chat_sid:
|
||||
self.outbox.put(
|
||||
"chat reset", functools.partial(self.rtdb.delete, "chat")
|
||||
)
|
||||
self._chat_sid, self._sent = sid, set()
|
||||
lines = {} if session is None else dict(session.chat)
|
||||
new: dict[str, object] = {
|
||||
k: v for k, v in lines.items() if k not in self._sent
|
||||
}
|
||||
if new:
|
||||
self.outbox.put("chat", functools.partial(self.rtdb.patch, "chat", new))
|
||||
self._sent |= set(new)
|
||||
put = functools.partial(self.rtdb.put, "state", text)
|
||||
self.outbox.put("state", put, latest="state")
|
||||
self.beat()
|
||||
|
||||
def consider(self, rid: str, node: object) -> None:
|
||||
"""One ``requests/{rid}`` node: answer, queue, or leave it."""
|
||||
if not isinstance(node, dict) or "req" not in node or "result" in node:
|
||||
return
|
||||
if not protocol.RID_RE.fullmatch(rid):
|
||||
_logger.warning("phone request with a bad rid ignored")
|
||||
return
|
||||
if (done := self.lane.done.get(rid)) is not None:
|
||||
self.put_result(rid, done.result)
|
||||
return
|
||||
raw = node["req"]
|
||||
try:
|
||||
req = protocol.parse(
|
||||
{**raw, "rid": rid} if isinstance(raw, dict) else raw, "phone"
|
||||
)
|
||||
except protocol.BadRidError as exc:
|
||||
_logger.warning("phone request %s refused: %s", rid, exc)
|
||||
return
|
||||
except protocol.BadRequestError as exc:
|
||||
_logger.warning("bad phone request %s: %s", rid, exc)
|
||||
result = protocol.failure("bad_request", str(exc), at=self._clock())
|
||||
self.lane.finish(rid, "phone", result)
|
||||
self.put_result(rid, result)
|
||||
return
|
||||
if (immediate := self.lane.submit(req)) is not None:
|
||||
self.put_result(rid, immediate)
|
||||
|
||||
def on_event(self, event: sse.Event) -> None:
|
||||
"""Route one SSE event under ``requests``."""
|
||||
for segs, value in _pairs(event):
|
||||
if not segs and isinstance(value, dict):
|
||||
for rid in sorted(value):
|
||||
self.consider(str(rid), value[rid])
|
||||
elif len(segs) == 1:
|
||||
self.consider(segs[0], value)
|
||||
elif len(segs) == _REQ_DEPTH and segs[1] == "req":
|
||||
self.consider(segs[0], {"req": value})
|
||||
|
||||
def rescan(self) -> None:
|
||||
"""Pick up anything the stream missed; drop answered nodes after 24 h."""
|
||||
try:
|
||||
nodes = self.rtdb.get("requests")
|
||||
except RtdbError as exc:
|
||||
_logger.warning("RTDB rescan failed: %s", exc)
|
||||
return
|
||||
if not isinstance(nodes, dict):
|
||||
return
|
||||
now = self._clock()
|
||||
for rid in sorted(nodes):
|
||||
node = nodes[rid]
|
||||
self.consider(str(rid), node)
|
||||
if not isinstance(node, dict) or "result" not in node:
|
||||
continue
|
||||
done = self.lane.done.get(str(rid))
|
||||
if done is None or now - done.at > DAY_MS:
|
||||
drop = functools.partial(self.rtdb.delete, f"requests/{rid}")
|
||||
self.outbox.put("cleanup", drop)
|
||||
|
||||
def listen(self, stop: threading.Event) -> None:
|
||||
"""The SSE loop; a cancelled stream leaves the rescans to carry on."""
|
||||
try:
|
||||
for event in sse.listen(self.rtdb, "requests", stop):
|
||||
self.on_event(event)
|
||||
except sse.StreamCancelledError:
|
||||
_logger.exception("the requests stream was cancelled; rescans only now")
|
||||
|
||||
def tend(self, stop: threading.Event, wait: Callable[[float], object]) -> None:
|
||||
"""Heartbeat every 30 s, rescan every 60 s, until `stop`."""
|
||||
since_scan = self._rescan_every
|
||||
while not stop.is_set():
|
||||
if since_scan >= self._rescan_every:
|
||||
self.rescan()
|
||||
since_scan = 0.0
|
||||
self.beat()
|
||||
wait(self._beat_every)
|
||||
since_scan += self._beat_every
|
||||
74
leetcode_coach/leetcode_coach/relay/probe.py
Normal file
74
leetcode_coach/leetcode_coach/relay/probe.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Step 4: has LeetCode seen an Accepted for this problem since it started?
|
||||
|
||||
The harvester's own read-only probe (leetcode-guard's ``fetch_recent_ac``,
|
||||
reached through `guard_bridge`), at most once a minute: LeetCode answers
|
||||
a rate limit exactly like a dead session, so polling harder manufactures
|
||||
the failure. Three answers, never two: ``accepted``, ``not_yet``, and
|
||||
``unknown`` when the probe is unusable -- "could not check" is never "not
|
||||
solved" (CLAUDE.md). The probe mints nothing; crediting stays the
|
||||
harvester's job. ``timestamp`` is unix SECONDS, ``started`` is ms.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from leetcode_coach import guard_bridge
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.guard_bridge import SolveProbe
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
EVERY_S: Final = 60.0
|
||||
ACCEPTED: Final = "accepted"
|
||||
NOT_YET: Final = "not_yet"
|
||||
UNKNOWN: Final = "unknown"
|
||||
|
||||
|
||||
def live_probe() -> SolveProbe:
|
||||
"""One read of kuhy's recent accepted submissions."""
|
||||
return guard_bridge.recent_accepted()
|
||||
|
||||
|
||||
class AcceptedProbe:
|
||||
"""Rate-limited, three-valued Accepted check."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
probe: Callable[[], SolveProbe] = live_probe,
|
||||
monotonic: Callable[[], float] = time.monotonic,
|
||||
every_s: float = EVERY_S,
|
||||
) -> None:
|
||||
"""Bind the probe and the clock that spaces it."""
|
||||
self._probe = probe
|
||||
self._monotonic = monotonic
|
||||
self._every = every_s
|
||||
self._last: float | None = None
|
||||
|
||||
def due(self) -> bool:
|
||||
"""Whether a minute has passed since the last probe."""
|
||||
last = self._last
|
||||
return last is None or self._monotonic() - last >= self._every
|
||||
|
||||
def check(self, slug: str, started_ms: int) -> str:
|
||||
"""``accepted`` / ``not_yet`` / ``unknown`` for `slug` since `started_ms`."""
|
||||
self._last = self._monotonic()
|
||||
try:
|
||||
answer = self._probe()
|
||||
except Exception: # pylint: disable=broad-exception-caught
|
||||
# Anything the probe raises is a probe we cannot believe.
|
||||
_logger.exception("the Accepted probe failed")
|
||||
return UNKNOWN
|
||||
if not answer.usable:
|
||||
_logger.warning("Accepted probe unusable: %s", answer.reason)
|
||||
return UNKNOWN
|
||||
seen = any(
|
||||
s.title_slug == slug and s.timestamp * 1000 >= started_ms
|
||||
for s in answer.submissions
|
||||
)
|
||||
return ACCEPTED if seen else NOT_YET
|
||||
176
leetcode_coach/leetcode_coach/relay/protocol.py
Normal file
176
leetcode_coach/leetcode_coach/relay/protocol.py
Normal file
@ -0,0 +1,176 @@
|
||||
"""The seven request kinds and their limits (DOCS-coach-relay.md 2 and 4).
|
||||
|
||||
`parse` is the only door into the relay: a request is checked here, field by
|
||||
field, before anything builds a path or reaches a model. Unknown fields are
|
||||
dropped, a kind outside the seven is never run, and an id is regex-checked
|
||||
first. A bad ``rid`` raises `BadRidError` (it gets no result at all: there is
|
||||
nowhere safe to put one); anything else wrong is `BadRequestError`, answered
|
||||
``bad_request``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Final, NoReturn
|
||||
|
||||
KINDS: Final = (
|
||||
"session_start",
|
||||
"session_end",
|
||||
"chat",
|
||||
"grade_step",
|
||||
"hint",
|
||||
"reveal",
|
||||
"run_code",
|
||||
)
|
||||
RID_RE: Final = re.compile(r"[0-9A-HJKMNP-TV-Z]{26}")
|
||||
"""A ULID: 26 Crockford base-32 characters (no I, L, O, U)."""
|
||||
SID_RE: Final = re.compile(r"\d{8}-\d{6}-[0-9a-f]{4}")
|
||||
DEV_RE: Final = re.compile(
|
||||
r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
|
||||
)
|
||||
SLUG_RE: Final = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*")
|
||||
MAX_SLUG: Final = 100
|
||||
MAX_TEXT_BYTES: Final = 8192
|
||||
MAX_REQ_BYTES: Final = 16 * 1024
|
||||
MAX_PICKS: Final = 30
|
||||
MAX_PICK_CHARS: Final = 64
|
||||
GRADED_STEPS: Final = (1, 2, 3, 5)
|
||||
TOOLBOX_STEP: Final = 3
|
||||
ALL_STEPS: Final = range(1, 6)
|
||||
RETRYABLE: Final = frozenset({"rate_limited", "model_error"})
|
||||
|
||||
|
||||
class BadRidError(ValueError):
|
||||
"""The rid is not a ULID: the request gets no result anywhere."""
|
||||
|
||||
|
||||
class BadRequestError(ValueError):
|
||||
"""Anything else wrong with a request; answered ``bad_request``."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Request:
|
||||
"""One validated request: only the fields its kind takes survive."""
|
||||
|
||||
rid: str
|
||||
kind: str
|
||||
dev: str
|
||||
body: dict[str, Any]
|
||||
transport: str
|
||||
"""``desktop`` (loopback API) or ``phone`` (RTDB)."""
|
||||
|
||||
|
||||
def _bad(message: str) -> NoReturn:
|
||||
raise BadRequestError(message)
|
||||
|
||||
|
||||
def _sid(body: dict[str, Any]) -> dict[str, Any]:
|
||||
sid = body.get("session")
|
||||
if not isinstance(sid, str) or not SID_RE.fullmatch(sid):
|
||||
_bad("session must be a session id")
|
||||
return {"session": sid}
|
||||
|
||||
|
||||
def _text(body: dict[str, Any], key: str) -> str:
|
||||
value = body.get(key)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
_bad(f"{key} must be a non-empty string")
|
||||
if len(value.encode()) > MAX_TEXT_BYTES:
|
||||
_bad(f"{key} is over {MAX_TEXT_BYTES} bytes")
|
||||
return value
|
||||
|
||||
|
||||
def _picks(body: dict[str, Any]) -> list[str]:
|
||||
picks = body.get("picks")
|
||||
if not isinstance(picks, list) or len(picks) > MAX_PICKS:
|
||||
_bad(f"picks must be a list of at most {MAX_PICKS} names")
|
||||
if not all(isinstance(p, str) and 0 < len(p) <= MAX_PICK_CHARS for p in picks):
|
||||
_bad(f"every pick must be a name of at most {MAX_PICK_CHARS} chars")
|
||||
return picks
|
||||
|
||||
|
||||
def _grade(body: dict[str, Any]) -> dict[str, Any]:
|
||||
step = body.get("step")
|
||||
if isinstance(step, bool) or not isinstance(step, int) or step not in ALL_STEPS:
|
||||
_bad("step must be 1 to 5")
|
||||
out: dict[str, Any] = {**_sid(body), "step": step}
|
||||
if "force" in body:
|
||||
if body["force"] is not True:
|
||||
_bad("force must be true when given")
|
||||
return {**out, "force": True}
|
||||
if step not in GRADED_STEPS:
|
||||
_bad("step 4 is never graded: it passes on a LeetCode Accepted")
|
||||
if step == TOOLBOX_STEP: # it takes picks; the others take text
|
||||
return {**out, "picks": _picks(body)}
|
||||
return {**out, "answer": _text(body, "answer")}
|
||||
|
||||
|
||||
def _body(kind: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
if kind == "session_start":
|
||||
slug = body.get("slug")
|
||||
if not isinstance(slug, str) or len(slug) > MAX_SLUG:
|
||||
_bad("slug must be a LeetCode slug")
|
||||
if not SLUG_RE.fullmatch(slug):
|
||||
_bad("slug must be a LeetCode slug")
|
||||
return {"slug": slug}
|
||||
if kind == "chat":
|
||||
return {**_sid(body), "text": _text(body, "text")}
|
||||
if kind == "run_code":
|
||||
return {**_sid(body), "code": _text(body, "code")}
|
||||
if kind == "grade_step":
|
||||
return _grade(body)
|
||||
return _sid(body)
|
||||
|
||||
|
||||
def _no_rid(message: str) -> NoReturn:
|
||||
raise BadRidError(message)
|
||||
|
||||
|
||||
def parse(raw: object, transport: str) -> Request:
|
||||
"""The validated request in `raw` (a decoded ``req`` object).
|
||||
|
||||
Raises:
|
||||
BadRidError: when there is no valid rid to answer under.
|
||||
BadRequestError: for every other problem.
|
||||
"""
|
||||
rid = raw.get("rid") if isinstance(raw, dict) else None
|
||||
if not isinstance(raw, dict) or not isinstance(rid, str):
|
||||
_no_rid("a request needs a rid")
|
||||
if not RID_RE.fullmatch(rid):
|
||||
_no_rid("the rid is not a ULID")
|
||||
if len(json.dumps(raw, ensure_ascii=False).encode()) > MAX_REQ_BYTES:
|
||||
_bad(f"the request is over {MAX_REQ_BYTES} bytes")
|
||||
kind, dev, body = raw.get("kind"), raw.get("dev"), raw.get("body")
|
||||
if kind not in KINDS:
|
||||
_bad("unknown request kind")
|
||||
if not isinstance(dev, str) or not DEV_RE.fullmatch(dev):
|
||||
_bad("dev must be the app's install uuid")
|
||||
if not isinstance(body, dict):
|
||||
_bad("body must be an object")
|
||||
return Request(rid, str(kind), dev, _body(str(kind), body), transport)
|
||||
|
||||
|
||||
def ok(data: dict[str, Any], *, at: int, state_rev: int) -> dict[str, Any]:
|
||||
"""A success result."""
|
||||
return {"ok": True, "at": at, "state_rev": state_rev, "data": data}
|
||||
|
||||
|
||||
def failure(
|
||||
code: str, error: str, *, at: int, retry: bool = False, **extra: object
|
||||
) -> dict[str, Any]:
|
||||
"""An error result; `error` is shown to kuhy as it stands."""
|
||||
return {
|
||||
"ok": False,
|
||||
"at": at,
|
||||
"code": code,
|
||||
"error": error,
|
||||
"retry": retry,
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def ok_retryable(code: str) -> bool:
|
||||
"""Whether an error with `code` is one kuhy resends (as a NEW rid)."""
|
||||
return code in RETRYABLE
|
||||
149
leetcode_coach/leetcode_coach/relay/rtdb.py
Normal file
149
leetcode_coach/leetcode_coach/relay/rtdb.py
Normal file
@ -0,0 +1,149 @@
|
||||
"""A minimal synchronous RTDB REST client: GET/PUT/PATCH/DELETE and SSE streams.
|
||||
|
||||
Ported from tutor's async ``tutor/relay/rtdb.py`` onto ``requests`` (this repo's
|
||||
one network dependency; the relay runs on threads, not asyncio). Every call
|
||||
authenticates with ``?auth=<idToken>`` (RTDB REST has no header form), so
|
||||
nothing here ever formats a URL or a ``requests`` error into a message: errors
|
||||
name the method, the path and the status only. Writes ask for
|
||||
``print=silent``, so RTDB does not echo every body back (`_snapshot_rtdb`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Final
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Generator
|
||||
|
||||
ROOT: Final = "leetcode-guard/coach"
|
||||
SERVER_TIME: Final = {".sv": "timestamp"}
|
||||
_CONNECT_S: Final = 15.0
|
||||
_STREAM_READ_S: Final = 75.0
|
||||
"""RTDB sends a keep-alive every 30 s, so 75 s of silence is a dead stream."""
|
||||
|
||||
# urllib3 logs every request line, query string (the token) included, at DEBUG.
|
||||
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
||||
|
||||
|
||||
class RtdbError(RuntimeError):
|
||||
"""A request failed; the message never contains the URL or the token."""
|
||||
|
||||
|
||||
def parse(lines: list[str]) -> tuple[str, str]:
|
||||
"""``(event, data)`` of one SSE block (its lines, blank line excluded)."""
|
||||
event, data = "message", []
|
||||
for line in lines:
|
||||
field, _, value = line.partition(":")
|
||||
value = value.removeprefix(" ")
|
||||
if field == "event":
|
||||
event = value
|
||||
elif field == "data":
|
||||
data.append(value)
|
||||
return event, "\n".join(data)
|
||||
|
||||
|
||||
class Rtdb:
|
||||
"""REST calls under ``/leetcode-guard/coach``; ``id_token`` yields a fresh token."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database_url: str,
|
||||
id_token: Callable[[], str],
|
||||
*,
|
||||
session: requests.Session | None = None,
|
||||
timeout_s: float = 30.0,
|
||||
) -> None:
|
||||
"""Bind the database; ``session`` is injectable for tests."""
|
||||
self._base = database_url.rstrip("/")
|
||||
self._token = id_token
|
||||
self._session = session or requests.Session()
|
||||
self._timeout = timeout_s
|
||||
|
||||
def url(self, path: str) -> str:
|
||||
"""The REST URL of ``path`` (relative to the coach root), no token."""
|
||||
rel = "/".join(quote(p, safe="") for p in path.strip("/").split("/") if p)
|
||||
return f"{self._base}/{ROOT}/{rel}.json" if rel else f"{self._base}/{ROOT}.json"
|
||||
|
||||
def _call(
|
||||
self, method: str, path: str, value: object = None, *, body: bool = False
|
||||
) -> requests.Response:
|
||||
params = {"auth": self._token()}
|
||||
if body:
|
||||
params["print"] = "silent"
|
||||
data = json.dumps(value).encode() if body else None
|
||||
try:
|
||||
response = self._session.request(
|
||||
method, self.url(path), params=params, data=data, timeout=self._timeout
|
||||
)
|
||||
except requests.RequestException as err:
|
||||
msg = f"{method} {path}: {type(err).__name__}"
|
||||
raise RtdbError(msg) from None
|
||||
if not response.ok:
|
||||
msg = f"{method} {path}: HTTP {response.status_code}"
|
||||
raise RtdbError(msg)
|
||||
return response
|
||||
|
||||
def get(self, path: str) -> object:
|
||||
"""The value at ``path`` (``None`` when absent)."""
|
||||
response = self._call("GET", path)
|
||||
try:
|
||||
value: object = response.json()
|
||||
except ValueError:
|
||||
msg = f"GET {path}: not JSON"
|
||||
raise RtdbError(msg) from None
|
||||
return value
|
||||
|
||||
def put(self, path: str, value: object) -> None:
|
||||
"""Replace ``path`` with ``value`` (a str is stored as a string leaf)."""
|
||||
self._call("PUT", path, value, body=True)
|
||||
|
||||
def patch(self, path: str, value: dict[str, object]) -> None:
|
||||
"""Merge ``value``'s children (keys may be nested ``a/b`` paths)."""
|
||||
self._call("PATCH", path, value, body=True)
|
||||
|
||||
def delete(self, path: str) -> None:
|
||||
"""Remove ``path``."""
|
||||
self._call("DELETE", path)
|
||||
|
||||
def stream(self, path: str) -> Generator[tuple[str, str]]:
|
||||
"""The ``(event, data)`` blocks of ONE SSE connection to ``path``.
|
||||
|
||||
Ends at EOF; the response is closed however the iteration stops.
|
||||
|
||||
Raises:
|
||||
RtdbError: The connection could not open, or it dropped mid-read.
|
||||
"""
|
||||
try:
|
||||
response = self._session.get(
|
||||
self.url(path),
|
||||
params={"auth": self._token()},
|
||||
headers={"Accept": "text/event-stream"},
|
||||
stream=True,
|
||||
timeout=(_CONNECT_S, _STREAM_READ_S),
|
||||
)
|
||||
except requests.RequestException as err:
|
||||
msg = f"STREAM {path}: {type(err).__name__}"
|
||||
raise RtdbError(msg) from None
|
||||
try:
|
||||
if not response.ok:
|
||||
msg = f"STREAM {path}: HTTP {response.status_code}"
|
||||
raise RtdbError(msg)
|
||||
block: list[str] = []
|
||||
# chunk_size=1: a non-chunked stream would otherwise hold a small
|
||||
# event back until 512 bytes arrived (SSE events are tiny).
|
||||
for raw in response.iter_lines(chunk_size=1):
|
||||
if raw:
|
||||
block.append(raw.decode("utf-8", errors="replace"))
|
||||
elif block:
|
||||
yield parse(block)
|
||||
block = []
|
||||
except requests.RequestException as err:
|
||||
msg = f"STREAM {path}: {type(err).__name__}"
|
||||
raise RtdbError(msg) from None
|
||||
finally:
|
||||
response.close()
|
||||
196
leetcode_coach/leetcode_coach/relay/runcode.py
Normal file
196
leetcode_coach/leetcode_coach/relay/runcode.py
Normal file
@ -0,0 +1,196 @@
|
||||
"""run_code: kuhy's JavaScript against the statement's examples (decision 8).
|
||||
|
||||
The contract (DOCS-coach-relay.md section 2) allows exactly one subprocess
|
||||
shape here: ``node`` with a fixed argv, never a shell. kuhy's code is embedded
|
||||
in a generated harness as a JSON string literal and compiled with
|
||||
``new Function``, so a syntax error is told apart from a crash; the examples
|
||||
are JSON literals this module generates from the statement. The process runs
|
||||
in a fresh temporary directory under node's permission model: it may read
|
||||
that directory and nothing else, spawns no child, opens no worker.
|
||||
|
||||
The answer carries printed values only, never node's stderr or a stack trace:
|
||||
a thrown error becomes ``error: <ClassName>``. The harness silences
|
||||
``console`` and ``process.stdout.write`` before kuhy's code loads and marks its
|
||||
own result lines with a per-run random token, so whatever kuhy's code prints
|
||||
cannot pose as a result. Output is cut at ``MAX_OUTPUT`` bytes before it is
|
||||
read, and one value is shown in at most ``MAX_SHOWN`` characters.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach.relay import examples
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
NODE_ENV: Final = "LEETCODE_NODE_BIN"
|
||||
DEFAULT_NODE: Final = "/usr/bin/node"
|
||||
TIMEOUT_S: Final = 5.0
|
||||
MAX_OUTPUT: Final = 64 * 1024
|
||||
MAX_SHOWN: Final = 200
|
||||
NO_RESULT: Final = "no result"
|
||||
_FIELDS: Final = 4 # mark, n, ok|err, value
|
||||
_ERROR_NAME: Final = re.compile(r"[A-Za-z]{1,40}")
|
||||
|
||||
_HARNESS: Final = """const __mark = "{mark}";
|
||||
const __write = process.stdout.write.bind(process.stdout);
|
||||
for (const k of ["log", "error", "warn", "info", "debug", "trace", "dir", "table"]) {{
|
||||
console[k] = () => {{}};
|
||||
}}
|
||||
process.stdout.write = () => true;
|
||||
process.stderr.write = () => true;
|
||||
const __say = (line) => __write(__mark + " " + line + "\\n");
|
||||
const __name = (e) =>
|
||||
e && typeof e.name === "string" && /^[A-Za-z]{{1,40}}$/.test(e.name)
|
||||
? e.name
|
||||
: "Error";
|
||||
const __examples = {examples};
|
||||
let __load;
|
||||
try {{
|
||||
__load = new Function(
|
||||
{code} + "\\n;return typeof {name} === 'function' ? {name} : undefined;"
|
||||
);
|
||||
}} catch (e) {{
|
||||
__say("syntax");
|
||||
process.exit(0);
|
||||
}}
|
||||
let __fn;
|
||||
let __failed = null;
|
||||
try {{
|
||||
__fn = __load();
|
||||
}} catch (e) {{
|
||||
__failed = __name(e);
|
||||
}}
|
||||
if (__failed === null && typeof __fn !== "function") __failed = "ReferenceError";
|
||||
for (const ex of __examples) {{
|
||||
if (__failed !== null) {{
|
||||
__say(ex.n + " err " + __failed);
|
||||
continue;
|
||||
}}
|
||||
try {{
|
||||
const r = __fn(...ex.args);
|
||||
__say(ex.n + " ok " + (r === undefined ? "undefined" : JSON.stringify(r)));
|
||||
}} catch (e) {{
|
||||
__say(ex.n + " err " + __name(e));
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def node_bin() -> str:
|
||||
"""``LEETCODE_NODE_BIN``, else ``node`` from PATH, else ``/usr/bin/node``."""
|
||||
return os.environ.get(NODE_ENV) or shutil.which("node") or DEFAULT_NODE
|
||||
|
||||
|
||||
def _canonical(value: object) -> str:
|
||||
return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
|
||||
|
||||
|
||||
def _shown(text: str) -> str:
|
||||
return text if len(text) <= MAX_SHOWN else text[:MAX_SHOWN] + "..."
|
||||
|
||||
|
||||
def harness(code: str, name: str, found: list[examples.Example], mark: str) -> str:
|
||||
"""The generated ``run.js``: every interpolated value is a JSON literal."""
|
||||
cases = [{"n": ex.n, "args": list(ex.args)} for ex in found]
|
||||
return _HARNESS.format(
|
||||
mark=mark,
|
||||
examples=json.dumps(cases),
|
||||
code=json.dumps(code),
|
||||
name=name,
|
||||
)
|
||||
|
||||
|
||||
def _results(stdout: bytes, mark: str) -> dict[int, tuple[str, str]] | None:
|
||||
"""``{n: (ok|err, value)}`` from the marked lines; None on a syntax error."""
|
||||
text = stdout[:MAX_OUTPUT].decode("utf-8", errors="replace")
|
||||
found: dict[int, tuple[str, str]] = {}
|
||||
for line in text.splitlines():
|
||||
parts = line.split(" ", 3)
|
||||
if parts[0] != mark:
|
||||
continue
|
||||
if parts[1:] == ["syntax"]:
|
||||
return None
|
||||
if len(parts) == _FIELDS and parts[1].isdigit() and parts[2] in {"ok", "err"}:
|
||||
found[int(parts[1])] = (parts[2], parts[3])
|
||||
return found
|
||||
|
||||
|
||||
def _row(ex: examples.Example, result: tuple[str, str] | None) -> dict[str, Any]:
|
||||
expected = _canonical(ex.expected)
|
||||
row: dict[str, Any] = {"n": ex.n, "ok": False, "expected": _shown(expected)}
|
||||
if result is None:
|
||||
return {**row, "got": NO_RESULT}
|
||||
kind, value = result
|
||||
if kind == "err":
|
||||
name = value if _ERROR_NAME.fullmatch(value) else "Error"
|
||||
return {**row, "got": f"error: {name}"}
|
||||
try:
|
||||
got = _canonical(json.loads(value))
|
||||
except ValueError:
|
||||
_logger.warning("example %d printed a value that is not JSON", ex.n)
|
||||
return {**row, "got": _shown(value)}
|
||||
return {**row, "ok": got == expected, "got": _shown(got)}
|
||||
|
||||
|
||||
def _failed(error: str) -> dict[str, Any]:
|
||||
return {"examples": [], "error": error}
|
||||
|
||||
|
||||
def run(
|
||||
code: str,
|
||||
statement: str,
|
||||
*,
|
||||
node: str | None = None,
|
||||
timeout_s: float = TIMEOUT_S,
|
||||
runner: Callable[..., subprocess.CompletedProcess[bytes]] = subprocess.run,
|
||||
) -> dict[str, Any]:
|
||||
"""Run ``code`` on every parsed example; the contract's ``run_code`` data."""
|
||||
name, found = examples.parse(statement)
|
||||
if name is None or not found:
|
||||
return _failed("no_examples")
|
||||
mark = secrets.token_hex(16)
|
||||
with tempfile.TemporaryDirectory(prefix="leetcode-run-") as tmp:
|
||||
script = Path(tmp) / "run.js"
|
||||
script.write_text(harness(code, name, found, mark), encoding="utf-8")
|
||||
argv = [
|
||||
node or node_bin(),
|
||||
"--permission",
|
||||
f"--allow-fs-read={tmp}",
|
||||
"--max-old-space-size=128",
|
||||
str(script),
|
||||
]
|
||||
try:
|
||||
proc = runner(
|
||||
argv,
|
||||
cwd=tmp,
|
||||
env={"PATH": "/usr/bin:/bin"},
|
||||
stdin=subprocess.DEVNULL,
|
||||
capture_output=True,
|
||||
timeout=timeout_s,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
_logger.warning("run_code: node ran past %.0f s and was killed", timeout_s)
|
||||
return _failed("timeout")
|
||||
except OSError as exc:
|
||||
_logger.warning("run_code: node could not start: %s", exc)
|
||||
return _failed("node_missing")
|
||||
results = _results(proc.stdout, mark)
|
||||
if results is None:
|
||||
return _failed("syntax")
|
||||
rows = [_row(ex, results.get(ex.n)) for ex in found]
|
||||
return {"examples": rows, "error": None}
|
||||
168
leetcode_coach/leetcode_coach/relay/session.py
Normal file
168
leetcode_coach/leetcode_coach/relay/session.py
Normal file
@ -0,0 +1,168 @@
|
||||
"""The live coaching session: what the log cannot hold, and its pointer file.
|
||||
|
||||
Steps, grades, rung and reveal are derived from the session log every time
|
||||
(`steps`); a `Session` adds what only the relay knows -- the claude session
|
||||
id, the chat lines in display order, notes waiting for the coach's next turn
|
||||
and the Accepted probe. ``live.json`` points at the live session (sid, log,
|
||||
claude id, rev) so a restarted relay rebuilds it from the log: chat lines
|
||||
from the ``chat`` and ``grade`` events, the rest re-derived.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from leetcode_coach import session_log
|
||||
from leetcode_coach.relay.steps import NAMES
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.local_coach import LocalCoach
|
||||
from leetcode_coach.phase import PhaseGate
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
LIVE_FIELDS: Final = (
|
||||
"sid",
|
||||
"slug",
|
||||
"title",
|
||||
"url",
|
||||
"cluster",
|
||||
"started",
|
||||
"transport",
|
||||
"dev",
|
||||
"claude_id",
|
||||
"local",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session: # pylint: disable=too-many-instance-attributes
|
||||
"""One problem's coaching session."""
|
||||
|
||||
sid: str
|
||||
slug: str
|
||||
title: str
|
||||
url: str
|
||||
cluster: str | None
|
||||
log: Path
|
||||
started: int
|
||||
transport: str
|
||||
dev: str
|
||||
gate: PhaseGate
|
||||
statement: str | None = None
|
||||
claude_id: str | None = None
|
||||
local: bool = False
|
||||
ended: int | None = None
|
||||
end_reason: str | None = None
|
||||
chat: dict[str, dict[str, Any]] = field(default_factory=dict)
|
||||
notes: list[str] = field(default_factory=list)
|
||||
history: list[dict[str, str]] = field(default_factory=list)
|
||||
local_coach: LocalCoach | None = None
|
||||
probe: str | None = None
|
||||
probed_at: int | None = None
|
||||
|
||||
def events(self) -> list[dict[str, Any]]:
|
||||
"""This session's log events (from its ``session_start`` on)."""
|
||||
return session_log.current(session_log.read(self.log))
|
||||
|
||||
def add(self, role: str, kind: str, text: str, at: int) -> str:
|
||||
"""Append one chat line (empty fields dropped); its ``m0001`` key."""
|
||||
key = f"m{len(self.chat) + 1:04d}"
|
||||
line = {"role": role, "kind": kind, "text": text, "at": at}
|
||||
self.chat[key] = {k: v for k, v in line.items() if v not in ("", None)}
|
||||
return key
|
||||
|
||||
def log_event(self, event: str, **fields: object) -> None:
|
||||
"""Append `event` to the log with this session's sid and cluster."""
|
||||
extra = {"cluster": self.cluster} if self.cluster else {}
|
||||
session_log.append(self.log, event, sid=self.sid, **extra, **fields)
|
||||
|
||||
def info(self) -> dict[str, Any]:
|
||||
"""The ``session`` block of the published state."""
|
||||
return {
|
||||
"id": self.sid,
|
||||
"slug": self.slug,
|
||||
"title": self.title,
|
||||
"cluster": self.cluster,
|
||||
"url": self.url,
|
||||
"started": self.started,
|
||||
"ended": self.ended,
|
||||
"end_reason": self.end_reason,
|
||||
"kind": "sql" if self.gate.sql() else "algorithm",
|
||||
}
|
||||
|
||||
|
||||
def save(path: Path, session: Session, rev: int) -> None:
|
||||
"""Write the live pointer (atomically: a torn pointer loses the session)."""
|
||||
record = {k: getattr(session, k) for k in LIVE_FIELDS}
|
||||
record |= {"log": str(session.log), "rev": rev}
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(record), encoding="utf-8")
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def _ms(event: dict[str, Any]) -> int:
|
||||
at = event.get("at")
|
||||
if isinstance(at, int):
|
||||
return at
|
||||
try:
|
||||
return int(datetime.fromisoformat(str(event.get("ts"))).timestamp() * 1000)
|
||||
except ValueError as exc:
|
||||
_logger.warning("event without a usable time: %s", exc)
|
||||
return 0
|
||||
|
||||
|
||||
def grade_line(event: dict[str, Any]) -> tuple[str, str]:
|
||||
"""The ``system`` chat line a step's grade shows as."""
|
||||
step = int(event["step"])
|
||||
name = NAMES.get(step, "step")
|
||||
if event.get("via") == "accepted":
|
||||
return "accepted", f"Step 4 ({name}): LeetCode shows an Accepted. Step 5 open."
|
||||
if event.get("forced") is True:
|
||||
tries = event.get("attempt")
|
||||
return "grade", f"Step {step} ({name}): continued after {tries} tries."
|
||||
head = f"Step {step} ({name}): {event.get('grade')} on try {event.get('attempt')}."
|
||||
feedback = str(event.get("feedback") or "")
|
||||
return "grade", f"{head}\n{feedback}".strip()
|
||||
|
||||
|
||||
def restore(
|
||||
path: Path, gate_for: Callable[[Path, str], PhaseGate]
|
||||
) -> tuple[Session, int] | None:
|
||||
"""The session ``live.json`` points at, rebuilt from its log; None if gone."""
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
log = Path(raw["log"])
|
||||
fields = {k: raw[k] for k in LIVE_FIELDS}
|
||||
rev = int(raw.get("rev", 0))
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
_logger.warning("live session pointer %s is unusable: %s", path, exc)
|
||||
return None
|
||||
session = Session(**fields, log=log, gate=gate_for(log, raw["slug"]))
|
||||
events = session.events()
|
||||
if not events or events[0].get("sid") != session.sid:
|
||||
_logger.warning("live session %s is not the log's latest", session.sid)
|
||||
return None
|
||||
for event in events:
|
||||
if event["event"] == "chat":
|
||||
role, kind = str(event.get("role")), str(event.get("kind", "chat"))
|
||||
session.add(role, kind, str(event.get("text", "")), _ms(event))
|
||||
who = "user" if role == "kuhy" else "assistant"
|
||||
session.history.append({"role": who, "content": str(event["text"])})
|
||||
elif event["event"] == "grade":
|
||||
kind, text = grade_line(event)
|
||||
session.add("system", kind, text, _ms(event))
|
||||
elif event["event"] == "session_end":
|
||||
session.ended = _ms(event)
|
||||
session.end_reason = str(event.get("reason"))
|
||||
return session, rev
|
||||
120
leetcode_coach/leetcode_coach/relay/sse.py
Normal file
120
leetcode_coach/leetcode_coach/relay/sse.py
Normal file
@ -0,0 +1,120 @@
|
||||
"""RTDB streaming: Server-Sent Events, reconnected until told to stop.
|
||||
|
||||
tutor's ``sse.py`` on threads. Each (re)connect starts with a ``put`` of the
|
||||
whole node at ``/``, so a consumer that applies ``put``/``patch`` events is
|
||||
correct again after any drop. ``auth_revoked`` (the id token expired)
|
||||
reconnects at once with a fresh token; a network error, an HTTP error, a bad
|
||||
payload or a connection that closes before saying anything backs off 1-30 s;
|
||||
``cancel`` (the rules now refuse the path) is fatal. `stop` is checked
|
||||
between events: a quiet stream notices it at its next keep-alive (<= 30 s).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import closing
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Final, Protocol
|
||||
|
||||
from leetcode_coach.relay.rtdb import RtdbError, parse
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Generator, Iterator
|
||||
import threading
|
||||
|
||||
__all__ = ["BACKOFF_S", "Event", "StreamCancelledError", "listen", "parse"]
|
||||
|
||||
BACKOFF_S: Final = (1.0, 2.0, 5.0, 10.0, 30.0)
|
||||
_DATA_EVENTS: Final = frozenset({"put", "patch"})
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Event:
|
||||
"""One ``put``/``patch`` event: where it applies and the new data."""
|
||||
|
||||
kind: str
|
||||
path: str
|
||||
data: object
|
||||
|
||||
|
||||
class StreamCancelledError(RtdbError):
|
||||
"""RTDB cancelled the stream (rules refuse the path): not retried."""
|
||||
|
||||
|
||||
class Streams(Protocol):
|
||||
"""What `listen` needs of `rtdb.Rtdb`."""
|
||||
|
||||
def stream(self, path: str) -> Generator[tuple[str, str]]:
|
||||
"""The raw blocks of one connection."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Health:
|
||||
"""Whether a connection proved itself (an event, or a clean revocation)."""
|
||||
|
||||
good: bool = False
|
||||
|
||||
|
||||
def _event(kind: str, raw: str) -> Event:
|
||||
payload = json.loads(raw)
|
||||
if not isinstance(payload, dict):
|
||||
msg = f"a {kind} payload is not an object"
|
||||
raise TypeError(msg)
|
||||
return Event(kind, str(payload.get("path", "/")), payload.get("data"))
|
||||
|
||||
|
||||
def _connection(
|
||||
rtdb: Streams, path: str, stop: threading.Event, health: _Health
|
||||
) -> Iterator[Event]:
|
||||
"""Events of a single connection; returns on EOF, revocation or `stop`."""
|
||||
with closing(rtdb.stream(path)) as blocks:
|
||||
for kind, raw in blocks:
|
||||
if kind in _DATA_EVENTS:
|
||||
event = _event(kind, raw)
|
||||
health.good = True
|
||||
yield event
|
||||
if stop.is_set():
|
||||
return
|
||||
elif kind == "auth_revoked":
|
||||
_logger.info("stream %s: token expired, reconnecting", path)
|
||||
health.good = True
|
||||
return
|
||||
elif kind == "cancel":
|
||||
msg = f"stream {path} cancelled by the server"
|
||||
raise StreamCancelledError(msg)
|
||||
|
||||
|
||||
def listen(
|
||||
rtdb: Streams,
|
||||
path: str,
|
||||
stop: threading.Event,
|
||||
sleep: Callable[[float], object] | None = None,
|
||||
) -> Iterator[Event]:
|
||||
"""Every event at ``path`` across reconnects, until `stop` is set."""
|
||||
pause = stop.wait if sleep is None else sleep
|
||||
failures = 0
|
||||
while not stop.is_set():
|
||||
health = _Health()
|
||||
reason = "closed before any event"
|
||||
try:
|
||||
yield from _connection(rtdb, path, stop, health)
|
||||
except StreamCancelledError:
|
||||
raise
|
||||
except (RtdbError, ValueError, TypeError) as err:
|
||||
# ValueError: a payload that is not JSON; TypeError: not an object.
|
||||
reason = str(err)
|
||||
_logger.warning("stream %s dropped: %s", path, reason)
|
||||
else:
|
||||
if health.good:
|
||||
failures = 0
|
||||
continue
|
||||
if health.good:
|
||||
failures = 0
|
||||
if stop.is_set():
|
||||
return
|
||||
delay = BACKOFF_S[min(failures, len(BACKOFF_S) - 1)]
|
||||
failures += 1
|
||||
_logger.warning("stream %s: %s; retry in %.0fs", path, reason, delay)
|
||||
pause(delay)
|
||||
129
leetcode_coach/leetcode_coach/relay/steps.py
Normal file
129
leetcode_coach/leetcode_coach/relay/steps.py
Normal file
@ -0,0 +1,129 @@
|
||||
"""The five-step state machine, derived from the session log (contract 2-3).
|
||||
|
||||
Nothing about a step is held in memory: its status, tries and last grade are
|
||||
read back from this session's events every time, so a relay restart, the CLI
|
||||
writing into the same file, and the app all agree. Each step goes
|
||||
``locked -> open -> passed | forced``; passing or forcing step n opens n+1.
|
||||
A ``partial`` / ``fail`` keeps the step open and counts a try; after
|
||||
`FORCE_AFTER` tries without a pass kuhy may continue (``can_force``).
|
||||
|
||||
Step 2's tries follow the CLI's count (`phase.step2_attempts`). Step 4 is
|
||||
never graded: its only ``grade`` is a detected LeetCode Accepted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Final
|
||||
|
||||
from leetcode_coach import phase
|
||||
|
||||
NAMES: Final = {
|
||||
1: "constraint",
|
||||
2: "requirements",
|
||||
3: "toolbox",
|
||||
4: "implement",
|
||||
5: "postmortem",
|
||||
}
|
||||
FORCE_AFTER: Final = 3
|
||||
IMPLEMENT: Final = 4
|
||||
REQUIREMENTS: Final = 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Step:
|
||||
"""One step as the state shows it."""
|
||||
|
||||
n: int
|
||||
status: str
|
||||
attempts: int
|
||||
last: dict[str, Any] | None
|
||||
|
||||
@property
|
||||
def done(self) -> bool:
|
||||
"""Passed or forced: the next step is open."""
|
||||
return self.status in {"passed", "forced"}
|
||||
|
||||
@property
|
||||
def can_force(self) -> bool:
|
||||
"""Open, graded, and at least `FORCE_AFTER` tries without a pass."""
|
||||
return (
|
||||
self.status == "open"
|
||||
and self.n != IMPLEMENT
|
||||
and self.attempts >= FORCE_AFTER
|
||||
)
|
||||
|
||||
|
||||
def _grades(events: list[dict[str, Any]], n: int) -> list[dict[str, Any]]:
|
||||
return [e for e in events if e.get("event") == "grade" and e.get("step") == n]
|
||||
|
||||
|
||||
def _last(grades: list[dict[str, Any]]) -> dict[str, Any] | None:
|
||||
tried = [g for g in grades if g.get("forced") is not True]
|
||||
if not tried:
|
||||
return None
|
||||
g = tried[-1]
|
||||
return {
|
||||
"grade": g.get("grade"),
|
||||
"feedback": g.get("feedback", ""),
|
||||
"via": g.get("via"),
|
||||
"at": g.get("at"),
|
||||
}
|
||||
|
||||
|
||||
def _status(grades: list[dict[str, Any]], *, reachable: bool) -> str:
|
||||
if any(g.get("forced") is True for g in grades):
|
||||
return "forced"
|
||||
if any(g.get("grade") == "pass" for g in grades):
|
||||
return "passed"
|
||||
return "open" if reachable else "locked"
|
||||
|
||||
|
||||
def derive(events: list[dict[str, Any]]) -> list[Step]:
|
||||
"""Every step of the session whose events these are."""
|
||||
steps: list[Step] = []
|
||||
reachable = True
|
||||
for n in NAMES:
|
||||
grades = _grades(events, n)
|
||||
status = _status(grades, reachable=reachable)
|
||||
if n == REQUIREMENTS: # the CLI's count, so both clients agree
|
||||
attempts = phase.step2_attempts(events)
|
||||
else:
|
||||
attempts = sum(
|
||||
1
|
||||
for g in grades
|
||||
if g.get("grade") != "pass" and g.get("forced") is not True
|
||||
)
|
||||
step = Step(n, status, attempts, _last(grades))
|
||||
steps.append(step)
|
||||
reachable = step.done
|
||||
return steps
|
||||
|
||||
|
||||
def open_step(steps: list[Step]) -> Step | None:
|
||||
"""The step kuhy is on, or None when every step is done."""
|
||||
return next((s for s in steps if s.status == "open"), None)
|
||||
|
||||
|
||||
def rung(events: list[dict[str, Any]]) -> str | None:
|
||||
"""The coach's current hint rung (its last marker)."""
|
||||
rungs = [e.get("rung") for e in events if e.get("event") == "rung"]
|
||||
return str(rungs[-1]) if rungs else None
|
||||
|
||||
|
||||
def revealed(events: list[dict[str, Any]]) -> bool:
|
||||
"""Whether kuhy typed ``reveal`` in this session."""
|
||||
return any(e.get("event") == "reveal" for e in events)
|
||||
|
||||
|
||||
def view(step: Step, probe: str | None, probed_at: int | None) -> dict[str, Any]:
|
||||
"""The step's row in the published state (section 3)."""
|
||||
row: dict[str, Any] = {"n": step.n, "name": NAMES[step.n], "status": step.status}
|
||||
if step.n == IMPLEMENT:
|
||||
return {**row, "probe": probe, "probed_at": probed_at}
|
||||
return {
|
||||
**row,
|
||||
"attempts": step.attempts,
|
||||
"can_force": step.can_force,
|
||||
"last": step.last,
|
||||
}
|
||||
107
leetcode_coach/leetcode_coach/relay/toolbox_grade.py
Normal file
107
leetcode_coach/leetcode_coach/relay/toolbox_grade.py
Normal file
@ -0,0 +1,107 @@
|
||||
"""Step 3, the toolbox pick, graded mechanically against the answer key.
|
||||
|
||||
No model. Key entries `K` (``entries``), picks `P`. An entry in
|
||||
``also_accepted`` is a correct alternative: each one picked stands in for
|
||||
one key entry not picked (sum instead of XOR for Missing Number). A combined
|
||||
key entry ("prefix sum + hash map") also counts as picked when every one of
|
||||
its parts is: each part must resolve to another toolbox entry by name or
|
||||
alias, ignoring case and a plural ``s`` ("prefix sum" -> "prefix sums"); a
|
||||
part that names no entry ("merge") means only the combined entry counts.
|
||||
|
||||
* pass: every key entry is covered (picked, built from its parts, or stood
|
||||
in for) and at most one pick is neither key, part nor alternative;
|
||||
* partial: something right was picked, but not that;
|
||||
* fail: nothing right was picked.
|
||||
|
||||
Feedback is the properties the uncovered key entries need that no pick has,
|
||||
as property names (`gate_notes.property_line`), never an entry name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from leetcode_coach import gate_notes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leetcode_coach.answer_key import Answer
|
||||
from leetcode_coach.toolbox import Entry, Toolbox
|
||||
|
||||
MAX_EXTRAS: Final = 1
|
||||
MIN_PARTS: Final = 2
|
||||
SPREAD: Final = (
|
||||
"Your picks have the properties, but spread over tools that do not "
|
||||
"combine; find the tool that has them together."
|
||||
)
|
||||
TOO_MANY: Final = "Fewer picks: more than one of these is not needed."
|
||||
|
||||
|
||||
def _key(text: str) -> str:
|
||||
return " ".join(text.split()).casefold()
|
||||
|
||||
|
||||
def resolve(name: str, box: Toolbox) -> Entry | None:
|
||||
"""The entry called `name` (or with that alias)."""
|
||||
wanted = _key(name)
|
||||
return next(
|
||||
(e for e in box.entries if wanted in {_key(n) for n in e.names()}), None
|
||||
)
|
||||
|
||||
|
||||
def parts(entry: Entry, box: Toolbox) -> tuple[Entry, ...] | None:
|
||||
"""The entries a combined ``a + b`` entry is made of; None if not all exist."""
|
||||
pieces = [p.strip() for p in entry.name.split(" + ")]
|
||||
if len(pieces) < MIN_PARTS: # a plain entry has no parts
|
||||
return None
|
||||
found: list[Entry] = []
|
||||
for piece in pieces:
|
||||
match = resolve(piece, box) or resolve(piece + "s", box)
|
||||
if match is None or match.name == entry.name:
|
||||
return None
|
||||
found.append(match)
|
||||
return tuple(found)
|
||||
|
||||
|
||||
def grade(picks: list[str], key: Answer, box: Toolbox) -> tuple[str, str]:
|
||||
"""``(grade, feedback)`` for `picks` (entry names, already resolvable)."""
|
||||
chosen = {e.name for p in picks if (e := resolve(p, box)) is not None}
|
||||
used: set[str] = set()
|
||||
missing: list[str] = []
|
||||
for name in key.entries:
|
||||
entry = resolve(name, box)
|
||||
made = None if entry is None else parts(entry, box)
|
||||
if name in chosen:
|
||||
used.add(name)
|
||||
elif made is not None and all(m.name in chosen for m in made):
|
||||
used.update(m.name for m in made)
|
||||
else:
|
||||
missing.append(name)
|
||||
stand_ins = chosen & set(key.also_accepted)
|
||||
extras = chosen - used - stand_ins
|
||||
if len(missing) <= len(stand_ins) and len(extras) <= MAX_EXTRAS:
|
||||
return "pass", ""
|
||||
verdict = "partial" if used or stand_ins else "fail"
|
||||
return verdict, _feedback(missing, chosen, extras, box)
|
||||
|
||||
|
||||
def _feedback(
|
||||
missing: list[str], chosen: set[str], extras: set[str], box: Toolbox
|
||||
) -> str:
|
||||
have = {p for e in box.entries if e.name in chosen for p in e.properties}
|
||||
need: list[str] = []
|
||||
for name in missing:
|
||||
entry = resolve(name, box)
|
||||
for prop in () if entry is None else entry.properties:
|
||||
if prop not in have and prop not in need:
|
||||
need.append(prop)
|
||||
lines = [
|
||||
f"- {gate_notes.property_line(p, box)}" for p in need if p in box.properties
|
||||
]
|
||||
if lines:
|
||||
head = "The operation you need also has these properties, which no pick has:"
|
||||
text = "\n".join([head, *lines])
|
||||
else:
|
||||
text = SPREAD if missing else ""
|
||||
if len(extras) > MAX_EXTRAS:
|
||||
text = f"{text}\n{TOO_MANY}".strip()
|
||||
return text
|
||||
203
leetcode_coach/leetcode_coach/relay/turns.py
Normal file
203
leetcode_coach/leetcode_coach/relay/turns.py
Normal file
@ -0,0 +1,203 @@
|
||||
"""Session start, chat, hint, reveal and run-code (DOCS-coach-relay.md 2).
|
||||
|
||||
Every kuhy line is logged (``chat``) and shown before the model is asked,
|
||||
so the app sees it at once. Code -- typed in chat or sent to run -- is
|
||||
refused while the relay's own step 2 is neither passed nor forced, checked
|
||||
BEFORE `PhaseGate.screen`: the gate's own 3-incompletes auto-open must not
|
||||
skip kuhy's choice to force. Grades waiting for the coach ride as a prefix
|
||||
on its next turn; ``reveal`` goes out bare, because the Stop gate lifts only
|
||||
on a message that is exactly ``reveal``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import logging
|
||||
import secrets
|
||||
from typing import TYPE_CHECKING, Any, Final, NoReturn
|
||||
import urllib.error
|
||||
|
||||
from leetcode_coach import (
|
||||
fetch_problem,
|
||||
local_prompt,
|
||||
phase,
|
||||
progress,
|
||||
req_check,
|
||||
session_log,
|
||||
)
|
||||
from leetcode_coach.relay import protocol, steps
|
||||
from leetcode_coach.relay.errors import CoachError
|
||||
from leetcode_coach.relay.session import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from leetcode_coach.relay.coach import Coach
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
LOCKED: Final = "Code waits until step 2 (requirements) is passed or forced."
|
||||
RUN_ERRORS: Final = {
|
||||
"timeout": "Your code ran past its time limit.",
|
||||
"node_missing": "node is not installed on the PC.",
|
||||
"no_examples": "No examples could be read from the statement.",
|
||||
"syntax": "Your code does not parse (SyntaxError).",
|
||||
}
|
||||
|
||||
|
||||
def fetch_statement(slug: str) -> tuple[str, str] | None:
|
||||
"""``(title, statement)`` from LeetCode, in-process; None when unavailable."""
|
||||
try:
|
||||
question = fetch_problem.fetch(slug)
|
||||
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
|
||||
_logger.warning("could not fetch %s: %s", slug, exc)
|
||||
return None
|
||||
if question is None or question.get("isPaidOnly") or not question.get("content"):
|
||||
_logger.warning("%s is unknown or premium-only", slug)
|
||||
return None
|
||||
return str(question["title"]), fetch_problem.render(question, "javascript")
|
||||
|
||||
|
||||
def gate_for(coach: Coach, log: Path, slug: str) -> phase.PhaseGate:
|
||||
"""The phase gate for one session's log, built directly (never ``open``)."""
|
||||
return phase.PhaseGate(log, coach.deps.box(), lambda: slug, coach.deps.ask)
|
||||
|
||||
|
||||
def statement(coach: Coach, session: Session) -> str | None:
|
||||
"""The session's statement, fetched again if a restart lost it."""
|
||||
if session.statement is None and (got := coach.deps.fetch(session.slug)):
|
||||
session.statement = got[1]
|
||||
session.gate.known = got[1]
|
||||
return session.statement
|
||||
|
||||
|
||||
def _sid(now_ms: int) -> str:
|
||||
local = datetime.fromtimestamp(now_ms / 1000, tz=UTC).astimezone()
|
||||
return f"{local:%Y%m%d-%H%M%S}-{secrets.token_hex(2)}"
|
||||
|
||||
|
||||
def start(coach: Coach, req: protocol.Request) -> dict[str, Any]:
|
||||
"""Open a session for ``body.slug``: the coach's opener first."""
|
||||
live = coach.session
|
||||
if live is not None and live.ended is None:
|
||||
msg = "A session is already live; end it first."
|
||||
raise CoachError(msg, code="session_live")
|
||||
slug = str(req.body["slug"])
|
||||
if slug not in coach.deps.answers():
|
||||
msg = f"{slug} has no answer key: only the cluster problems are coached here."
|
||||
raise CoachError(msg, code="no_answer_key")
|
||||
fetched = coach.deps.fetch(slug)
|
||||
now = coach.now()
|
||||
sid = _sid(now)
|
||||
day = datetime.fromtimestamp(now / 1000, tz=UTC).astimezone().date()
|
||||
log = session_log.log_path(slug, day)
|
||||
session = Session(
|
||||
sid=sid,
|
||||
slug=slug,
|
||||
title=fetched[0] if fetched else slug,
|
||||
url=f"https://leetcode.com/problems/{slug}/",
|
||||
cluster=progress.cluster_of(slug),
|
||||
log=log,
|
||||
started=now,
|
||||
transport=req.transport,
|
||||
dev=req.dev,
|
||||
gate=coach.gate_for(log, slug),
|
||||
statement=fetched[1] if fetched else None,
|
||||
)
|
||||
session.gate.known = session.statement
|
||||
raw = coach.chat.open(session)
|
||||
session.log_event(
|
||||
"session_start",
|
||||
source="app",
|
||||
transport=req.transport,
|
||||
dev=req.dev,
|
||||
slug=slug,
|
||||
at=now,
|
||||
)
|
||||
key, _rung = _reply(coach, session, raw, "chat")
|
||||
coach.session = session
|
||||
return {"session": sid, "msg": key}
|
||||
|
||||
|
||||
def _kuhy(coach: Coach, session: Session, kind: str, text: str) -> None:
|
||||
now = coach.now()
|
||||
session.log_event("chat", role="kuhy", kind=kind, text=text, at=now)
|
||||
session.add("kuhy", kind, text, now)
|
||||
|
||||
|
||||
def _reply(
|
||||
coach: Coach, session: Session, raw: str, kind: str
|
||||
) -> tuple[str, str | None]:
|
||||
"""Log the reply's rung, strip it, show and log the reply."""
|
||||
rung = local_prompt.split_rung(raw)[1]
|
||||
clean = session.gate.after_reply(raw)
|
||||
now = coach.now()
|
||||
session.log_event("chat", role="coach", kind=kind, text=clean, at=now)
|
||||
return session.add("coach", kind, clean, now), rung
|
||||
|
||||
|
||||
def _prefixed(session: Session, text: str) -> str:
|
||||
if not session.notes:
|
||||
return text
|
||||
notes = "\n".join(session.notes)
|
||||
session.notes.clear()
|
||||
return f"{notes}\n\n{text}"
|
||||
|
||||
|
||||
def code_open(session: Session) -> bool:
|
||||
"""Whether the relay's own step 2 is passed or forced."""
|
||||
return steps.derive(session.events())[1].done
|
||||
|
||||
|
||||
def _refuse(coach: Coach, session: Session, note: str) -> NoReturn:
|
||||
session.add("system", "refused", f"{LOCKED}\n{note}".strip(), coach.now())
|
||||
raise CoachError(LOCKED, code="phase_locked", note=note)
|
||||
|
||||
|
||||
def chat(coach: Coach, session: Session, text: str) -> dict[str, Any]:
|
||||
"""One chat turn; ``hint`` and ``reveal`` typed alone are those kinds."""
|
||||
word = text.strip()
|
||||
if word in {"hint", "reveal"}:
|
||||
_kuhy(coach, session, word, word)
|
||||
coach.publish()
|
||||
if word == "hint":
|
||||
key, rung = _reply(
|
||||
coach, session, coach.chat.turn(session, _prefixed(session, word)), word
|
||||
)
|
||||
return {"msg": key, "rung": rung}
|
||||
session.gate.screen(word) # logs ``reveal``, as the REPL does
|
||||
session.notes.clear()
|
||||
key, _rung = _reply(coach, session, coach.chat.turn(session, word), word)
|
||||
coach.end(session, "reveal")
|
||||
return {"msg": key}
|
||||
is_code = phase.regex_verdict(word)
|
||||
if is_code is None:
|
||||
is_code = req_check.looks_like_code(word, coach.deps.ask)
|
||||
_kuhy(coach, session, "chat", text)
|
||||
if is_code and not code_open(session):
|
||||
_refuse(coach, session, session.gate.refusal_note())
|
||||
sent, note = session.gate.screen(text, is_code=is_code)
|
||||
if sent is None:
|
||||
_refuse(coach, session, note)
|
||||
if note:
|
||||
session.add("system", "grade", note, coach.now())
|
||||
coach.publish()
|
||||
raw = coach.chat.turn(session, _prefixed(session, sent))
|
||||
key, _rung = _reply(coach, session, raw, "chat")
|
||||
return {"msg": key}
|
||||
|
||||
|
||||
def run_code(coach: Coach, session: Session, code: str) -> dict[str, Any]:
|
||||
"""Run kuhy's JavaScript against the statement's examples."""
|
||||
if not code_open(session):
|
||||
_refuse(coach, session, session.gate.refusal_note())
|
||||
session.log_event("code", via="run", at=coach.now())
|
||||
result = coach.deps.run_code(code, statement(coach, session) or "")
|
||||
lines = [
|
||||
f"example {r['n']}: got {r['got']}, expected {r['expected']}"
|
||||
for r in result.get("examples", [])
|
||||
]
|
||||
if result.get("error"):
|
||||
lines.append(RUN_ERRORS.get(str(result["error"]), str(result["error"])))
|
||||
session.add("system", "run", "\n".join(lines), coach.now())
|
||||
return result
|
||||
70
leetcode_coach/leetcode_coach/report.py
Normal file
70
leetcode_coach/leetcode_coach/report.py
Normal file
@ -0,0 +1,70 @@
|
||||
"""`leetcode report`: one row per session file, for kuhy to read the method back.
|
||||
|
||||
Columns: req-before-code (``y``/``n``, ``-`` while there is no code yet),
|
||||
the highest hint rung, whether ``reveal`` was typed, and every ``req_check``
|
||||
verdict in order -- all of them, because "incomplete,incomplete,pass" is the
|
||||
story, where the status app's reader keeps only the last one. Its stdout IS
|
||||
its interface (T201 exemption in pyproject.toml); tests assert on it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from leetcode_coach import session_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
COMMAND = "report"
|
||||
RUNGS = ("H0", "H1", "H2", "H3")
|
||||
WIDTHS = (36, 17, 10, 8)
|
||||
HEADER = ("problem", "req-before-code", "max-rung", "reveal", "req_check")
|
||||
|
||||
|
||||
def _line(cols: tuple[str, ...]) -> str:
|
||||
padded = [c.ljust(w) for c, w in zip(cols, WIDTHS, strict=False)]
|
||||
return "".join(padded) + cols[-1]
|
||||
|
||||
|
||||
def _req_before_code(events: list[dict[str, Any]]) -> str:
|
||||
seen_req = False
|
||||
for event in events:
|
||||
if event.get("event") == "req":
|
||||
seen_req = True
|
||||
elif event.get("event") == "code":
|
||||
return "y" if seen_req else "n"
|
||||
return "-"
|
||||
|
||||
|
||||
def row(path: Path) -> str:
|
||||
"""The report line for one session file."""
|
||||
events = session_log.read(path)
|
||||
rungs = [
|
||||
RUNGS.index(e["rung"])
|
||||
for e in events
|
||||
if e.get("event") == "rung" and e.get("rung") in RUNGS
|
||||
]
|
||||
verdicts = [str(e.get("verdict")) for e in events if e.get("event") == "req_check"]
|
||||
return _line(
|
||||
(
|
||||
path.stem,
|
||||
_req_before_code(events),
|
||||
RUNGS[max(rungs)] if rungs else "-",
|
||||
"y" if any(e.get("event") == "reveal" for e in events) else "n",
|
||||
",".join(verdicts) or "-",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def main(_argv: list[str]) -> int:
|
||||
"""Print the report for every session file."""
|
||||
folder = session_log.sessions_dir()
|
||||
paths = sorted(folder.glob("*.jsonl"))
|
||||
if not paths:
|
||||
print(f"no coach sessions yet in {folder}")
|
||||
return 0
|
||||
print(_line(HEADER))
|
||||
for path in paths:
|
||||
print(row(path))
|
||||
return 0
|
||||
180
leetcode_coach/leetcode_coach/req_check.py
Normal file
180
leetcode_coach/leetcode_coach/req_check.py
Normal file
@ -0,0 +1,180 @@
|
||||
"""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 sonnet), 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.
|
||||
|
||||
The checker may only name *missing properties* from the toolbox vocabulary.
|
||||
That is enforced here, not trusted to the prompt: every ``missing`` item that
|
||||
is not a vocabulary key is dropped (an entry name like "XOR" is a leak, and an
|
||||
invented property is noise). An ``incomplete`` whose every item was dropped
|
||||
names nothing kuhy could fix, so it counts as no answer and falls through.
|
||||
|
||||
The haiku call runs with no tools, no MCP, no hooks and no session file: the
|
||||
global CLAUDE.md still loads (no OAuth-compatible way to skip it), which is
|
||||
why the answer is extracted and validated rather than parsed whole.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
import urllib.error
|
||||
|
||||
from leetcode_coach import claude_cli, local_backend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from leetcode_coach.toolbox import Toolbox
|
||||
|
||||
_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."""
|
||||
HAIKU_ARGS = [
|
||||
"--model",
|
||||
"haiku",
|
||||
"--tools",
|
||||
"",
|
||||
"--strict-mcp-config",
|
||||
"--no-session-persistence",
|
||||
"--disable-slash-commands",
|
||||
"--settings",
|
||||
'{"disableAllHooks": true}',
|
||||
]
|
||||
CHECK_SYSTEM = (
|
||||
"You check a student's requirement list for a programming problem. You are "
|
||||
"given the problem, the list, and a vocabulary of properties an operation "
|
||||
"can have. Decide which vocabulary properties the operation that solves "
|
||||
"the problem must have, and whether the list states each of them in any "
|
||||
"words. Reply with ONE JSON object and nothing else: "
|
||||
'{"verdict": "pass" | "incomplete", "missing": [<vocabulary property names>]}. '
|
||||
"Never name an operation, a data structure or an algorithm; only the "
|
||||
"property names from the vocabulary may appear in missing."
|
||||
)
|
||||
CODE_SYSTEM = (
|
||||
"You decide whether a chat message is program source code (a line or "
|
||||
"block someone would paste into a solution) or prose (a question or an "
|
||||
'idea, even one that mentions a symbol). Reply with ONE JSON object: {"code": '
|
||||
'true} or {"code": false}.'
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Check:
|
||||
"""A checker answer: verdict, the missing properties, and who answered."""
|
||||
|
||||
verdict: str
|
||||
missing: tuple[str, ...] = ()
|
||||
via: str = "none"
|
||||
|
||||
|
||||
def extract_json(text: str) -> dict[str, Any] | None:
|
||||
"""The JSON object starting at the first ``{`` (fences and chatter ignored)."""
|
||||
start = text.find("{")
|
||||
if start == -1:
|
||||
return None
|
||||
try:
|
||||
obj, _end = json.JSONDecoder().raw_decode(text, start)
|
||||
except ValueError as exc:
|
||||
_LOG.warning("checker answer is not a JSON object: %s", exc)
|
||||
return None
|
||||
return obj if isinstance(obj, dict) else None
|
||||
|
||||
|
||||
def parse_verdict(obj: object, vocabulary: dict[str, str]) -> Check | None:
|
||||
"""A validated verdict, or None when the answer is unusable."""
|
||||
if not isinstance(obj, dict) or obj.get("verdict") not in {"pass", "incomplete"}:
|
||||
return None
|
||||
missing = obj.get("missing", [])
|
||||
if not isinstance(missing, list):
|
||||
return None
|
||||
kept = tuple(m for m in missing if isinstance(m, str) and m in vocabulary)
|
||||
if obj["verdict"] == "pass":
|
||||
return Check("pass")
|
||||
return Check("incomplete", kept) if kept else None
|
||||
|
||||
|
||||
def check_prompt(statement: str, req: str, box: Toolbox) -> str:
|
||||
"""The checker's user message: problem, list, vocabulary, toolbox."""
|
||||
vocab = "\n".join(
|
||||
f"- {name}: {meaning}" for name, meaning in box.properties.items()
|
||||
)
|
||||
toolbox = "\n".join(
|
||||
f"- {', '.join(e.properties)}" for e in box.entries if e.properties
|
||||
)
|
||||
return (
|
||||
f"## Problem\n{statement.strip()}\n\n## Requirement list\n{req.strip()}\n\n"
|
||||
f"## Property vocabulary\n{vocab}\n\n"
|
||||
f"## Property sets the known operations offer\n{toolbox}\n"
|
||||
)
|
||||
|
||||
|
||||
def ask_models[T](
|
||||
system: str,
|
||||
prompt: str,
|
||||
validate: Callable[[dict[str, Any] | None], T | None],
|
||||
ask: Callable[..., dict[str, Any]] | None,
|
||||
) -> tuple[T, str] | None:
|
||||
"""Haiku, then Ollama; the first validated answer and who gave it."""
|
||||
asker = claude_cli.ask if ask is None else ask
|
||||
reply = asker(
|
||||
[*HAIKU_ARGS, "--system-prompt", system], prompt, timeout=HAIKU_TIMEOUT_S
|
||||
)
|
||||
if not claude_cli.is_limit_hit(reply):
|
||||
got = validate(extract_json(str(reply.get("result", ""))))
|
||||
if got is not None:
|
||||
return got, "haiku"
|
||||
try:
|
||||
local = local_backend.chat(
|
||||
[
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
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)
|
||||
return None
|
||||
got = validate(extract_json(local.text))
|
||||
return None if got is None else (got, "ollama")
|
||||
|
||||
|
||||
def check(
|
||||
statement: str,
|
||||
req: str,
|
||||
box: Toolbox,
|
||||
ask: Callable[..., dict[str, Any]] | None = None,
|
||||
) -> Check:
|
||||
"""Judge `req` against the problem; ``unverified`` when nobody can."""
|
||||
if not box.properties:
|
||||
_LOG.warning("no property vocabulary: the req list stays unverified")
|
||||
return Check("unverified")
|
||||
got = ask_models(
|
||||
CHECK_SYSTEM,
|
||||
check_prompt(statement, req, box),
|
||||
lambda obj: parse_verdict(obj, box.properties),
|
||||
ask,
|
||||
)
|
||||
if got is None:
|
||||
return Check("unverified")
|
||||
verdict, via = got
|
||||
return Check(verdict.verdict, verdict.missing, via)
|
||||
|
||||
|
||||
def _code_flag(obj: dict[str, Any] | None) -> bool | None:
|
||||
flag = None if obj is None else obj.get("code")
|
||||
return flag if isinstance(flag, bool) else None
|
||||
|
||||
|
||||
def looks_like_code(
|
||||
block: str, ask: Callable[..., dict[str, Any]] | None = None
|
||||
) -> bool:
|
||||
"""The model's call on a block the regex could not decide; prose if unsure."""
|
||||
got = ask_models(CODE_SYSTEM, block, _code_flag, ask)
|
||||
return False if got is None else got[0]
|
||||
127
leetcode_coach/leetcode_coach/session_log.py
Normal file
127
leetcode_coach/leetcode_coach/session_log.py
Normal file
@ -0,0 +1,127 @@
|
||||
"""The coach's per-problem session log (DOCS-coach-spec.md decision 8).
|
||||
|
||||
One JSONL file per problem and day,
|
||||
``~/.local/share/leetcode-coach/sessions/<YYYY-MM-DD>-<slug>.jsonl`` (the
|
||||
directory follows ``LEETCODE_COACH_SESSIONS_DIR``: `progress.sessions_dir`).
|
||||
Every line is one object with ``event`` and ``ts``; ``req_check`` carries ``verdict``,
|
||||
``rung`` carries ``rung``. That contract is FIXED: ``leetcode_guard._coach_log``
|
||||
reads it for the status app, so a new kind of fact rides as an extra field on
|
||||
an existing event (``code`` + ``req_incomplete``), and new names only together
|
||||
with the reader: ``session_start``, ``grade``, ``chat`` and ``session_end``
|
||||
came with ``_coach_log.EVENTS`` in one commit (DOCS-coach-relay.md section 5).
|
||||
A file can hold several app sessions; each starts at its ``session_start``
|
||||
(`current`), and a CLI-only file is one session.
|
||||
|
||||
Every event carries ``cluster`` while ``LEETCODE_COACH_CLUSTER`` is set
|
||||
(`leetcode --cluster` sets it for the session it starts).
|
||||
|
||||
Appends are one ``os.write`` on an ``O_APPEND`` descriptor, so a concurrent
|
||||
reader sees whole lines, and two writers (REPL and a hook) cannot interleave.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from leetcode_coach import fetch_problem, progress
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
LOG_ENV = "LEETCODE_COACH_LOG"
|
||||
"""Set by the REPL so the Stop hook (a grandchild) reads the same log."""
|
||||
EVENTS = frozenset(
|
||||
{
|
||||
*("req", "req_check", "code", "rung", "reveal", "postmortem", "retest"),
|
||||
*("session_start", "grade", "chat", "session_end"),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def sessions_dir() -> Path:
|
||||
"""Where the session files live (one definition: `progress.sessions_dir`)."""
|
||||
return progress.sessions_dir()
|
||||
|
||||
|
||||
def slug(problem: str) -> str:
|
||||
"""The LeetCode slug in `problem`, or a filesystem-safe stand-in."""
|
||||
try:
|
||||
return fetch_problem.slug_from(problem)
|
||||
except ValueError as exc:
|
||||
_LOG.warning("%s; naming the log after a sanitised copy", exc)
|
||||
return re.sub(r"[^a-z0-9]+", "-", problem.lower()).strip("-") or "problem"
|
||||
|
||||
|
||||
def log_path(problem: str, day: date | None = None) -> Path:
|
||||
"""The log file for `problem` (URL or slug) on `day` (default today)."""
|
||||
when = day or datetime.now(tz=UTC).astimezone().date()
|
||||
return sessions_dir() / f"{when.isoformat()}-{slug(problem)}.jsonl"
|
||||
|
||||
|
||||
def append(path: Path, event: str, **fields: object) -> None:
|
||||
"""Append one event line atomically.
|
||||
|
||||
Raises:
|
||||
ValueError: for an event name outside the fixed contract.
|
||||
"""
|
||||
if event not in EVENTS:
|
||||
msg = f"{event!r} is not a session-log event; add a field instead"
|
||||
raise ValueError(msg)
|
||||
stamp = datetime.now(tz=UTC).astimezone().isoformat(timespec="seconds")
|
||||
cluster = os.environ.get(progress.CLUSTER_ENV)
|
||||
stamped = {"cluster": cluster} if cluster else {}
|
||||
record = {"event": event, "ts": stamp, **stamped, **fields}
|
||||
line = (json.dumps(record, ensure_ascii=False) + "\n").encode()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
|
||||
try:
|
||||
os.write(fd, line)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _parse(line: str) -> object:
|
||||
try:
|
||||
return json.loads(line)
|
||||
except ValueError as exc:
|
||||
_LOG.warning("session log line is not JSON, skipped: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def read(path: Path) -> list[dict[str, Any]]:
|
||||
"""Every object line in `path`; nothing when it does not exist yet."""
|
||||
if not path.is_file():
|
||||
return []
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
parsed = (_parse(line) for line in lines if line.strip())
|
||||
return [obj for obj in parsed if isinstance(obj, dict)]
|
||||
|
||||
|
||||
def current(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""The events of the file's latest session: from its last ``session_start``."""
|
||||
starts = [i for i, e in enumerate(events) if e.get("event") == "session_start"]
|
||||
return events[starts[-1] :] if starts else events
|
||||
|
||||
|
||||
def has_code(path: Path) -> bool:
|
||||
"""Whether kuhy's code has reached the coach in this session."""
|
||||
return any(e.get("event") == "code" for e in current(read(path)))
|
||||
|
||||
|
||||
def append_current(event: str, **fields: object) -> bool:
|
||||
"""Append to the log the REPL exported (`LOG_ENV`); False outside a session.
|
||||
|
||||
For writers that run as the coach's grandchildren, like the card builder
|
||||
logging ``postmortem`` once the cards are delivered. The TUI has no REPL
|
||||
and so no log: nothing is written there.
|
||||
"""
|
||||
exported = os.environ.get(LOG_ENV)
|
||||
if not exported:
|
||||
return False
|
||||
append(Path(exported), event, **fields)
|
||||
return True
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user