From d4849859df93b349c05d75cef144f1b93cad9cd4 Mon Sep 17 00:00:00 2001 From: Adam French Date: Tue, 20 Oct 2026 12:46:53 +0100 Subject: [PATCH] Autocomplete and evaluate solutions on the solve page The editor's completion popup was on but empty for C++, since @codemirror/lang-cpp has no completion source. web/src/completions.js adds one: keywords, the STL, every name in the file (the template's macros show their expansion, typedefs what they alias), members after . and ->, and snippets for the loops and lambdas typed over and over. Python gains the contest standard library and members after ., on top of lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file. Evaluate (POST/GET /problems//evaluate) has Claude judge the editor's code as a strong competitive programmer would before submitting. It runs the saved tests on the runner first, as Submit does, and gives Claude the verdicts and up to three failing cases. The reply is a verdict, correctness, complexity against the constraints, line-anchored issues and a traced counterexample (internal/evaluate). The page shows it in an Evaluation tab of the results panel, marks the issues in the editor beside the lint's for as long as their lines are unchanged, and can load the counterexample as the custom input. It is a background job the page polls, like explanations, but it commits nothing: the code is a draft. explain.Jobs.StartWith keeps a finished job's answer in memory until the next one or a restart. Co-Authored-By: Claude Opus 5.5 --- site/CLAUDE.md | 1 + site/README.md | 9 +- site/internal/evaluate/evaluate.go | 322 +++++++++++++++++++ site/internal/evaluate/evaluate_test.go | 168 ++++++++++ site/internal/explain/jobs.go | 15 +- site/internal/handlers/evaluate.go | 117 +++++++ site/internal/handlers/evaluate_test.go | 146 +++++++++ site/internal/handlers/handlers.go | 12 +- site/internal/handlers/run.go | 30 +- site/web/package-lock.json | 1 + site/web/package.json | 1 + site/web/src/api.js | 5 + site/web/src/completions.js | 258 +++++++++++++++ site/web/src/components/CodeEditor.vue | 29 +- site/web/src/components/EvaluationReport.vue | 280 ++++++++++++++++ site/web/src/components/RunResults.vue | 24 +- site/web/src/format.js | 9 + site/web/src/views/SolvePage.vue | 175 +++++++++- 18 files changed, 1566 insertions(+), 36 deletions(-) create mode 100644 site/internal/evaluate/evaluate.go create mode 100644 site/internal/evaluate/evaluate_test.go create mode 100644 site/internal/handlers/evaluate.go create mode 100644 site/internal/handlers/evaluate_test.go create mode 100644 site/web/src/completions.js create mode 100644 site/web/src/components/EvaluationReport.vue diff --git a/site/CLAUDE.md b/site/CLAUDE.md index 4eff133..7f4d927 100644 --- a/site/CLAUDE.md +++ b/site/CLAUDE.md @@ -19,6 +19,7 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al - **Visibility is decided server-side.** Non-admins see only `solved/`, and an unsolved problem is a 404, not a 403. `auth.Forward` returns false for a request with no cookies without a network call. `problem.md` (the judge's statement) is admin-only even on solved problems. - **Explanations run in the background.** `POST /explain` starts a job in `explain.Jobs` and returns 202; the job calls Claude (`internal/claude`, streamed, JSON schema) and commits `explain.md` through `Mutate`. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network. - **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job in its own `explain.Jobs`: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`) and commit `reviews/.md`. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`. +- **Evaluations are the same shape, but commit nothing.** `POST /evaluate` judges the solve page's draft: it runs the saved tests on the runner, then asks Claude (`internal/evaluate`). It keeps the answer in memory as the job's `Result` (`explain.Jobs.StartWith`), and the page polls for it. - **Code runs in a separate service, never in the site.** The solve page's run/lint handlers (`handlers/run.go`) read the problem from the clone (`Server.Dir`, not the index, which truncates) and post to `cmd/usacorunner` through `runner.Client`; `internal/runner/types.go` is the contract between them. Tests fake it with `handlers.Runner`. The runner's own tests run real g++/python3/clang-tidy/ruff and skip whichever is missing. diff --git a/site/README.md b/site/README.md index 68d7a85..e7673b6 100644 --- a/site/README.md +++ b/site/README.md @@ -51,6 +51,7 @@ internal/claude/ the Claude client: streamed call, JSON-schema reply, fixed e internal/explain/ the explanation prompt and schema, explain.md rendering, the job tracker internal/transcribe/ OpenAI-compatible speech-to-text client, and pace/pause/filler metrics internal/review/ the review prompt and schema, reviews/.md rendering +internal/evaluate/ the solve page's evaluation: prompt, schema and the run's verdicts for Claude internal/audiostore/ optional S3 bucket (Garage) that keeps review recordings for playback internal/leetcode/ today's daily question, imported by running the clone's lib/leetcode.py internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page) @@ -79,6 +80,8 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro | `GET /usaco/api/problems//code` | admin | the solve page's start: `{io, leetcode, languages, default, runner, code: {cpp, python}}`, each language's saved source or a starter from `template.cpp`/`template.py` | | `POST /usaco/api/problems//run` | admin | `{lang, source, mode: tests\|custom, input?}`: compiles once and runs the saved tests (or the custom input) on the runner; answers its verdicts. 503 without `RUNNER_URL` | | `POST /usaco/api/problems//lint` | admin | `{lang, source}`: the runner's diagnostics (g++ and clang-tidy, or python and ruff) | +| `POST /usaco/api/problems//evaluate` | admin | `{lang, source, note?}`: runs the saved tests, then has Claude judge the source; answers 202. 409 if one is running, 503 without `CLAUDE_API_KEY` | +| `GET /usaco/api/problems//evaluate` | admin | the latest evaluation job, shaped like the explain one, with the evaluation as `result` once it is done | | `PUT /usaco/api/problems//code` | admin | `{lang, source}`: commits `main.cpp`, or `main.py` (`sol.py` where that is the existing file), as "Edit " | | `POST /usaco/api/leetcode/daily` | admin | imports today's LeetCode daily question into `solving/` with the CLI's `lib/leetcode.py` and commits it as "Start ", or finds it if it is already a problem; answers `{name, created}`. 502 if LeetCode or the import fails | | `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull | @@ -174,10 +177,12 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex ## Solve page -`/usaco/p//solve` (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through `driver.h`. +`/usaco/p//solve` (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Evaluate (Claude), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through `driver.h`. - **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs code. `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it. - **Runs copy the CLI.** The same g++ flags as `lib/common.sh` (`-DLOCAL`, with the repo root's `debugging.h` and `leetcode.h`, and a LeetCode problem's `driver.h`, sent along), the program runs in a directory holding `.in` with that file also on stdin, `.out` is its output if it wrote one, and outputs compare as `usaco test` does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s. +- **Autocomplete** is in the browser (`web/src/completions.js`), since `@codemirror/lang-cpp` has none. C++ completes keywords, the STL, every name in the file (the template's macros show what they expand to, typedefs what they alias), members after `.` and `->`, and snippets (`for`, `forr`, `foreach`, `lambda`, `dfs`, `sortby`...). Python adds the contest standard library (`heapq`, `bisect`, `collections`...) and members after `.` to lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file; clangd would, but it would need a session per editor next to the runner. +- **Evaluate** has Claude judge the code in the editor, as a strong competitive programmer would before submitting (`internal/evaluate`). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result lives in the server's memory until the next evaluation or a restart. A statement it had to fetch is not saved either. - **Lint.** C++ is g++'s warnings plus clang-tidy with the repo's `.clang-tidy` (bugprone, performance and a few readability checks, tuned so `template.cpp` is clean); the runner embeds a copy, and a test keeps the two equal. Python is `compile()` for syntax errors plus ruff (`E4,E7,E9,F,B`). A missing tool is skipped. The runner image precompiles `bits/stdc++.h` for g++ and clang-tidy (`internal/runner/pch.go`), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22). ## Things that are easy to get wrong @@ -185,6 +190,6 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex - **`BASE_PATH` and Vite's `base` must agree.** The SPA's asset URLs and router base are fixed at build time. - **Edits must decide from disk, not the index.** `repo.Mutate` may run an edit twice, the second time on a newer tip. The handlers re-locate the problem in the clone each time with `findOnDisk`. - **`problem.md` is the judge's text.** `GET /problems/` blanks it for non-admins, so the public site links to the judge instead of republishing it. -- **An explanation or review job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again). +- **An explanation, review or evaluation job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again). - **Uploads are capped at 25 MB**, the OpenAI API's limit. nginx's server-wide `client_max_body_size 50M` is above it; lowering that below 25M would turn big recordings into nginx 413s. - **`tests/*.out` used to be gitignored** by the root `*.out` rule. The root `.gitignore` now re-includes `**/tests/*.out`. A test whose expected output is shown as "Not saved." predates that change or never had one. diff --git a/site/internal/evaluate/evaluate.go b/site/internal/evaluate/evaluate.go new file mode 100644 index 0000000..5bc39ae --- /dev/null +++ b/site/internal/evaluate/evaluate.go @@ -0,0 +1,322 @@ +// Package evaluate has Claude judge the code in the solve page's editor, as +// a strong competitive programmer would before submitting it: is it right, +// is it fast enough for the constraints, which lines are wrong, and is +// there a small input that breaks it. +// +// The code is a draft, so unlike an explanation or a review nothing is +// committed. The answer is kept in memory with the source it judged +// (explain.Jobs.StartWith), and the page anchors each issue to its line in +// the editor. +// +// Claude is given the saved tests' verdicts from the runner along with the +// code, because a test that fails is a fact it should not have to work out, +// and one that passes is evidence it can weigh. +package evaluate + +import ( + "context" + "fmt" + "strings" + "time" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/runner" +) + +// Input is what Claude is told. +type Input struct { + Name string + Statement string + Examples []explain.Example + Lang string // runner.Cpp or runner.Python + Source string + LeetCode bool // the source is a class Solution run through driver.h + Note string // what the admin wants checked: "worried about overflow" + // Run is the saved tests' outcome, nil when they were not run; RunNote + // says why not. + Run *runner.RunResponse + RunNote string +} + +// Issue is one problem in the code, anchored to a line of it. +type Issue struct { + Line int `json:"line"` + Severity string `json:"severity"` + Title string `json:"title"` + Detail string `json:"detail"` +} + +// Counterexample is an input the code gets wrong; all blank when Claude has +// none it is sure of. +type Counterexample struct { + Input string `json:"input"` + Expected string `json:"expected"` + Why string `json:"why"` +} + +// Result is the reply's shape; Schema is the same thing for the API. +type Result struct { + Verdict string `json:"verdict"` + Summary string `json:"summary"` + Correctness string `json:"correctness"` + Complexity string `json:"complexity"` + Issues []Issue `json:"issues"` + Counterexample Counterexample `json:"counterexample"` + Style string `json:"style"` +} + +// Evaluation is what the job keeps and the page shows: the reply, and the +// source it is about, so the page can tell when the editor has moved on. +type Evaluation struct { + Result + Lang string `json:"lang"` + Source string `json:"source"` + Model string `json:"model"` + At time.Time `json:"at"` + // Tests is the run's one-line outcome ("3/4 passed"), or why there was + // none. + Tests string `json:"tests"` +} + +// Verdicts, and how they read on the page. +var Verdicts = map[string]string{ + "correct": "Looks correct", + "edge_cases": "Misses edge cases", + "wrong": "Wrong", + "too_slow": "Too slow", + "incomplete": "Unfinished", +} + +func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} } + +// Schema constrains the reply to Result. Structured outputs need every +// object closed and every property required. +var Schema = map[string]any{ + "type": "object", + "properties": map[string]any{ + "verdict": map[string]any{ + "type": "string", + "enum": []string{"correct", "edge_cases", "wrong", "too_slow", "incomplete"}, + "description": "correct: you expect it to be accepted. edge_cases: the idea is right but some inputs break it (overflow, empty input, an off-by-one at a boundary). " + + "wrong: the approach itself gives wrong answers. too_slow: right answers, but over the time or memory limit at the largest inputs. " + + "incomplete: it does not compile, or is not a full attempt yet. When several apply, pick the first of wrong, too_slow, edge_cases.", + }, + "summary": str("Markdown, one or two sentences: what the code does, as an algorithm, so they can check it was read right."), + "correctness": str("Markdown. Why it is or is not correct. Account for every failing test. If it is wrong, say where the reasoning breaks; if it is right, give the argument briefly, especially for a greedy choice."), + "complexity": str("Markdown. Time and memory as written, against what the constraints allow, with a rough operation count at the largest input."), + "issues": map[string]any{ + "type": "array", + "description": "Specific problems, most serious first: bugs, edge cases, overflow, undefined behaviour, needless slowness. Empty if there are none. Not style nitpicks.", + "items": map[string]any{ + "type": "object", + "properties": map[string]any{ + "line": map[string]any{"type": "integer", "description": "The source line it is on, as numbered in . 0 if it is about the program as a whole."}, + "severity": map[string]any{"type": "string", "enum": []string{"error", "warning", "info"}, "description": "error: gives a wrong answer, crashes or times out on some valid input. warning: risky or fragile, but may be fine on this problem's tests. info: worth knowing, harmless here."}, + "title": str("Plain text, under ten words: shown inline in the editor."), + "detail": str("Markdown. What goes wrong and on what input, and how to fix it. A corrected line or two is fine; never a whole solution."), + }, + "required": []string{"line", "severity", "title", "detail"}, + "additionalProperties": false, + }, + }, + "counterexample": map[string]any{ + "type": "object", + "description": "A small input this code gets wrong, in exactly the problem's input format. All three blank unless you have traced the code on it and are sure.", + "properties": map[string]any{ + "input": str("The input, exactly as the program would read it. Blank for none."), + "expected": str("The correct output for that input, worked out carefully. Blank for none."), + "why": str("Markdown, one or two sentences: what this code outputs instead, and why. Blank for none."), + }, + "required": []string{"input", "expected", "why"}, + "additionalProperties": false, + }, + "style": str("Markdown, two to four sentences: readability and contest habits worth changing, if any. Blank if there is nothing worth saying."), + }, + "required": []string{"verdict", "summary", "correctness", "complexity", "issues", "counterexample", "style"}, + "additionalProperties": false, +} + +// The reply is short; the rest is room for adaptive thinking, which is +// where the tracing happens. +const maxTokens = 24000 + +// System is the same on every call, so it is cached. +const System = `You are a strong competitive programmer reviewing someone's solution before they submit it. You get the problem, their code, and usually the verdicts from running it on their saved tests. Tell them whether it will be accepted and, if not, exactly why. + +How to judge: +- Decide correctness yourself. Trace the code on the examples and on small cases you construct, especially the boundaries: minimum sizes, all-equal values, the largest values, an empty answer. +- The test verdicts are facts. A failing test proves a bug; explain every one. Passing tests are evidence, not proof: samples are small and weak. +- Check the complexity against the constraints in the statement. Assume about 10^8 simple operations per second in C++ and 10^7 in CPython. +- Look hard for what usually breaks accepted-looking code: int overflow where long long is needed, off-by-ones, state not reset between test cases, uninitialised values, out-of-bounds access, wrong output format, recursion depth (in Python especially), comparing floating point exactly, and slow I/O on big input. +- Read the code as written, not as intended. Code that is unfinished or does not compile is incomplete. + +Their setup: +- C++ is built with g++ -std=c++17 -O2 -DLOCAL. LOCAL is defined only on their machine, never on the judge, so the DBG and print macros are no-ops there. Their template defines macros and typedefs such as ll, vi, pii, F(i, L, R) for (int i = L; i < R; i++), FE (<=), FD and FDE (counting down), ALL(c), SZ(c), pb, fi and se, REMAX and REMIN, takeI(n) (declares int n and reads it), takeL, takeV(v, n), whileZ (reads T and loops T times), YESNO(b), and STDIO(name), which reads name.in and writes name.out when run locally or on USACO. Treat these as ordinary code. +- A LeetCode problem's code is the class Solution only; a driver reads the tests and calls it, so judge the method, not I/O. +- Python reads with a tokens() helper over sys.stdin.buffer, and a stdio(name) helper redirects to name.in and name.out when that file exists. + +How to answer: +- The code is shown with line numbers. Every issue names the line it is on, as numbered there, so it can be marked in their editor. +- Point at fixes; do not write their solution. A corrected line or two is fine. +- Give a counterexample only if you have traced the code on it and are sure it fails, and you have worked out the right answer. Keep it small, and in exactly the input format. Otherwise leave it blank. +- Be direct. If the code is right, say so plainly and keep the rest short; do not invent problems. +- Write in plain prose, using markdown for emphasis, lists and inline code, and LaTeX between $...$ for math such as complexities ($O(n \log n)$); the page typesets it with KaTeX.` + +// Prompt is the user message. +func Prompt(in Input) string { + var b strings.Builder + fmt.Fprintf(&b, "\n%s\n\n", in.Name, strings.TrimSpace(in.Statement)) + for i, ex := range in.Examples { + fmt.Fprintf(&b, "\n\n\n%s\n\n", i+1, strings.TrimRight(ex.In, "\n")) + if ex.Out != "" { + fmt.Fprintf(&b, "\n%s\n\n", strings.TrimRight(ex.Out, "\n")) + } + b.WriteString("\n") + } + kind := "" + if in.LeetCode { + kind = " leetcode=\"true\"" + } + fmt.Fprintf(&b, "\n\n%s\n", in.Lang, kind, numbered(in.Source)) + b.WriteString("\n\n" + runText(in.Run, in.RunNote) + "\n") + if note := strings.TrimSpace(in.Note); note != "" { + fmt.Fprintf(&b, "\n\n%s\n\n", note) + } + b.WriteString("\nEvaluate my solution.") + return b.String() +} + +// numbered prefixes each line with its number, right-aligned, as an editor +// gutter would show it. +func numbered(src string) string { + lines := strings.Split(strings.TrimRight(src, "\n"), "\n") + w := len(fmt.Sprint(len(lines))) + var b strings.Builder + for i, line := range lines { + fmt.Fprintf(&b, "%*d| %s\n", w, i+1, line) + } + return b.String() +} + +// Caps on what a run puts in the prompt. A failing test bigger than +// maxCase is a stress test: its verdict is worth stating, its text is not. +const ( + maxCase = 2 << 10 + maxShown = 3 + maxCompiler = 4 << 10 +) + +func runText(r *runner.RunResponse, note string) string { + if r == nil { + return note + "\n" + } + var b strings.Builder + if !r.Compile.OK { + b.WriteString("It did not compile:\n" + capped(r.Compile.Output, maxCompiler) + "\n") + return b.String() + } + if len(r.Results) == 0 { + return "It compiled. There are no saved tests to run.\n" + } + fmt.Fprintf(&b, "%s on the saved tests:\n", Outcome(r)) + for _, t := range r.Results { + fmt.Fprintf(&b, "- test %s: %s in %d ms", t.Name, t.Verdict, t.TimeMs) + if t.Message != "" { + b.WriteString(" (" + t.Message + ")") + } + b.WriteString("\n") + } + shown := 0 + for _, t := range r.Results { + if shown == maxShown { + break + } + if t.Verdict == runner.Accepted || t.Verdict == runner.Unchecked { + continue + } + shown++ + fmt.Fprintf(&b, "\n\n", t.Name, t.Verdict) + if len(t.Input) > maxCase || (t.Expected != nil && len(*t.Expected) > maxCase) { + b.WriteString("(too big to show)\n\n") + continue + } + fmt.Fprintf(&b, "\n%s\n\n", strings.TrimRight(t.Input, "\n")) + if t.Expected != nil { + fmt.Fprintf(&b, "\n%s\n\n", strings.TrimRight(*t.Expected, "\n")) + } + fmt.Fprintf(&b, "\n%s\n\n", capped(strings.TrimRight(t.Output, "\n"), maxCase)) + if t.Stderr != "" { + fmt.Fprintf(&b, "\n%s\n\n", capped(strings.TrimRight(t.Stderr, "\n"), maxCase)) + } + b.WriteString("\n") + } + return b.String() +} + +// Outcome is a run's one-line result: "3/4 passed", or "2 ran" when no +// test had an expected output. +func Outcome(r *runner.RunResponse) string { + if !r.Compile.OK { + return "did not compile" + } + passed, checked := 0, 0 + for _, t := range r.Results { + if t.Verdict != runner.Unchecked { + checked++ + } + if t.Verdict == runner.Accepted { + passed++ + } + } + if checked == 0 { + return fmt.Sprintf("%d ran, unchecked", len(r.Results)) + } + return fmt.Sprintf("%d/%d passed", passed, checked) +} + +func capped(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "\n(cut)" +} + +// Generate asks Claude and returns the evaluation. +func Generate(ctx context.Context, a explain.Asker, in Input, now time.Time) (*Evaluation, error) { + var r Result + err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + if err != nil { + return nil, err + } + tests := in.RunNote + if in.Run != nil { + tests = Outcome(in.Run) + } + return &Evaluation{Result: clean(r, in.Source), Lang: in.Lang, Source: in.Source, Model: a.Model(), At: now, Tests: tests}, nil +} + +// clean keeps the reply inside what the page can show: lines that exist, +// severities it knows, and a counterexample only when it is whole. +func clean(r Result, src string) Result { + lines := strings.Count(strings.TrimRight(src, "\n"), "\n") + 1 + issues := []Issue{} + for _, is := range r.Issues { + if is.Line < 0 || is.Line > lines { + is.Line = 0 + } + switch is.Severity { + case "error", "warning", "info": + default: + is.Severity = "info" + } + if strings.TrimSpace(is.Title) != "" || strings.TrimSpace(is.Detail) != "" { + issues = append(issues, is) + } + } + r.Issues = issues + if strings.TrimSpace(r.Counterexample.Input) == "" || strings.TrimSpace(r.Counterexample.Expected) == "" { + r.Counterexample = Counterexample{} + } + return r +} diff --git a/site/internal/evaluate/evaluate_test.go b/site/internal/evaluate/evaluate_test.go new file mode 100644 index 0000000..309c036 --- /dev/null +++ b/site/internal/evaluate/evaluate_test.go @@ -0,0 +1,168 @@ +package evaluate + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" + "adam-french.co.uk/usaco-site/internal/runner" +) + +func ptr(s string) *string { return &s } + +func TestPrompt(t *testing.T) { + run := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{ + {Name: "1", Verdict: runner.Accepted, TimeMs: 3}, + {Name: "2", Verdict: runner.WrongAnswer, TimeMs: 4, Input: "2\n", Output: "5\n", Expected: ptr("4\n")}, + {Name: "big", Verdict: runner.TimeLimit, TimeMs: 2000, Message: "exceeded 2s", Input: strings.Repeat("9 ", 2000)}, + }} + p := Prompt(Input{ + Name: "moocast", Statement: "# Moocast\n\nCows.", Lang: runner.Cpp, + Source: "int main() {\n return 0;\n}\n", + Examples: []explain.Example{{In: "1\n", Out: "2\n"}}, + Note: " overflow? ", + Run: run, + }) + for _, want := range []string{ + "\n# Moocast\n\nCows.\n", + "\n\n1\n\n\n2\n", + "\n1| int main() {\n2| return 0;\n3| }\n", + "1/3 passed on the saved tests:\n- test 1: AC in 3 ms\n- test 2: WA in 4 ms\n- test big: TLE in 2000 ms (exceeded 2s)\n", + "\n\n2\n\n\n4\n\n\n5\n\n", + "\n(too big to show)\n", + "\noverflow?\n", + } { + if !strings.Contains(p, want) { + t.Errorf("prompt is missing %q:\n%s", want, p) + } + } + + p = Prompt(Input{Name: "two-sum", Statement: "x", Lang: runner.Cpp, LeetCode: true, Source: "class Solution {};", RunNote: "The tests were not run: the code runner is not configured."}) + for _, want := range []string{ + "\n1| class Solution {};\n", + "\nThe tests were not run: the code runner is not configured.\n", + } { + if !strings.Contains(p, want) { + t.Errorf("prompt is missing %q:\n%s", want, p) + } + } + if strings.Contains(p, "") { + t.Errorf("a blank note still made a context block:\n%s", p) + } + + p = Prompt(Input{Name: "x", Lang: runner.Cpp, Source: "int main( {}", Run: &runner.RunResponse{Compile: runner.Compile{Output: "main.cpp:1: error"}}}) + if !strings.Contains(p, "It did not compile:\nmain.cpp:1: error\n") { + t.Errorf("a compile error is not in the prompt:\n%s", p) + } +} + +func TestNumberedPadsToTheWidestLine(t *testing.T) { + got := numbered(strings.Repeat("x\n", 10)) + if !strings.HasPrefix(got, " 1| x\n") || !strings.HasSuffix(got, "10| x\n") { + t.Errorf("numbered = %q", got) + } +} + +func TestOutcome(t *testing.T) { + r := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Verdict: runner.Unchecked}, {Verdict: runner.Unchecked}}} + if got := Outcome(r); got != "2 ran, unchecked" { + t.Errorf("Outcome = %q", got) + } + if got := Outcome(&runner.RunResponse{}); got != "did not compile" { + t.Errorf("Outcome = %q", got) + } +} + +// fakeAsker answers with r. +type fakeAsker struct{ r Result } + +func (fakeAsker) Model() string { return "fake-model" } +func (f fakeAsker) JSON(_ context.Context, _ claude.Request, out any) error { + *out.(*Result) = f.r + return nil +} + +func TestGenerateCleansTheReply(t *testing.T) { + r := Result{ + Verdict: "wrong", + Issues: []Issue{ + {Line: 2, Severity: "error", Title: "Overflow"}, + {Line: 99, Severity: "fatal", Title: "Past the end"}, + {Line: 1, Severity: "info"}, + }, + Counterexample: Counterexample{Input: "3\n", Why: "no expected output"}, + } + now := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC) + run := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Verdict: runner.Accepted}}} + ev, err := Generate(context.Background(), fakeAsker{r}, Input{Lang: runner.Python, Source: "a\nb\n", Run: run}, now) + if err != nil { + t.Fatal(err) + } + want := []Issue{{Line: 2, Severity: "error", Title: "Overflow"}, {Line: 0, Severity: "info", Title: "Past the end"}} + if len(ev.Issues) != 2 || ev.Issues[0] != want[0] || ev.Issues[1] != want[1] { + t.Errorf("issues = %+v, want %+v", ev.Issues, want) + } + if ev.Counterexample != (Counterexample{}) { + t.Errorf("a counterexample with no expected output was kept: %+v", ev.Counterexample) + } + if ev.Lang != runner.Python || ev.Source != "a\nb\n" || ev.Model != "fake-model" || !ev.At.Equal(now) || ev.Tests != "1/1 passed" { + t.Errorf("evaluation = %+v", ev) + } + // The page reads the reply's fields at the top level, beside lang. + b, _ := json.Marshal(ev) + if !strings.Contains(string(b), `"verdict":"wrong"`) || !strings.Contains(string(b), `"lang":"python"`) { + t.Errorf("JSON = %s", b) + } +} + +// Every property must be required and every object closed for structured +// outputs, and the Go struct must read every field the schema asks for. +func TestSchemaMatchesResult(t *testing.T) { + var check func(path string, s map[string]any) + check = func(path string, s map[string]any) { + if s["type"] == "array" { + check(path+"[]", s["items"].(map[string]any)) + return + } + if s["type"] != "object" { + return + } + if s["additionalProperties"] != false { + t.Errorf("%s is not closed", path) + } + props := s["properties"].(map[string]any) + req := map[string]bool{} + for _, r := range s["required"].([]string) { + req[r] = true + } + for k, v := range props { + if !req[k] { + t.Errorf("%s.%s is not required", path, k) + } + check(path+"."+k, v.(map[string]any)) + } + } + check("", Schema) + + b, _ := json.Marshal(Result{Issues: []Issue{{}}}) + var got map[string]any + json.Unmarshal(b, &got) + for k := range Schema["properties"].(map[string]any) { + if _, ok := got[k]; !ok { + t.Errorf("Result has no field for %q", k) + } + } + for v := range Verdicts { + found := false + for _, e := range Schema["properties"].(map[string]any)["verdict"].(map[string]any)["enum"].([]string) { + found = found || e == v + } + if !found { + t.Errorf("verdict %q is labelled but not in the schema", v) + } + } +} diff --git a/site/internal/explain/jobs.go b/site/internal/explain/jobs.go index cb8a3a3..fa4c05c 100644 --- a/site/internal/explain/jobs.go +++ b/site/internal/explain/jobs.go @@ -19,6 +19,8 @@ type Status struct { Error string `json:"error,omitempty"` Started *time.Time `json:"started,omitempty"` Finished *time.Time `json:"finished,omitempty"` + // Result is a finished StartWith job's answer. + Result any `json:"result,omitempty"` } // Jobs runs at most one explanation per problem at a time. An explanation @@ -34,6 +36,13 @@ type Jobs struct { // reports whether it started. fn's error is shown to the admin, so it must // be a message meant for them. func (j *Jobs) Start(name string, fn func() error) bool { + return j.StartWith(name, func() (any, error) { return nil, fn() }) +} + +// StartWith is Start for a job whose answer is kept here rather than +// committed: a done job's Status carries it until the next job for name +// starts, or the server restarts. +func (j *Jobs) StartWith(name string, fn func() (any, error)) bool { j.mu.Lock() defer j.mu.Unlock() if j.m == nil { @@ -45,13 +54,13 @@ func (j *Jobs) Start(name string, fn func() error) bool { now := time.Now() j.m[name] = &Status{State: Running, Started: &now} go func() { - err := fn() + res, err := fn() j.mu.Lock() defer j.mu.Unlock() end := time.Now() - s := &Status{State: Done, Started: &now, Finished: &end} + s := &Status{State: Done, Started: &now, Finished: &end, Result: res} if err != nil { - s.State, s.Error = Failed, err.Error() + s.State, s.Error, s.Result = Failed, err.Error(), nil } j.m[name] = s }() diff --git a/site/internal/handlers/evaluate.go b/site/internal/handlers/evaluate.go new file mode 100644 index 0000000..21e7655 --- /dev/null +++ b/site/internal/handlers/evaluate.go @@ -0,0 +1,117 @@ +package handlers + +import ( + "context" + "errors" + "log" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/evaluate" + "adam-french.co.uk/usaco-site/internal/runner" +) + +// The saved tests run first and Claude takes a minute or two after. +const evaluateTimeout = 10 * time.Minute + +// startEvaluate starts judging the editor's source and answers at once; the +// page polls evaluateStatus, whose result is the evaluation. Nothing is +// committed: the source is a draft, and the answer is about this version of +// it only. +func (s *Server) startEvaluate(ctx *gin.Context) { + if s.Claude == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + return + } + body, p, l, ok := s.readCode(ctx) + if !ok { + return + } + if strings.TrimSpace(body.Source) == "" { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"}) + return + } + if len(body.Note) > maxNote { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"}) + return + } + if strings.TrimSpace(p.Statement) == "" && p.URL == "" { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"}) + return + } + in := evaluate.Input{ + Name: p.Name, Statement: p.Statement, Examples: examples(p), + Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note, + } + link := p.URL + if !s.evalJobs.StartWith(p.Name, func() (any, error) { return s.evaluate(in, link, l) }) { + ctx.JSON(http.StatusConflict, gin.H{"error": "a solution is already being evaluated"}) + return + } + ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name)) +} + +func (s *Server) evaluateStatus(ctx *gin.Context) { + if p, ok := s.lookup(ctx, true); ok { + ctx.JSON(http.StatusOK, s.evalJobs.Get(p.Name)) + } +} + +// evaluate is one job. Its error is shown to the admin, so every path +// returns a message meant for them and logs the detail. +func (s *Server) evaluate(in evaluate.Input, link string, l *layout) (*evaluate.Evaluation, error) { + ctx, cancel := context.WithTimeout(context.Background(), evaluateTimeout) + defer cancel() + name := in.Name + + // A fetched statement is not saved: that would be the only commit an + // evaluation makes. Explain or Edit details keep one. + if _, err := s.ensureStatement(ctx, "evaluate", name, &in.Statement, link); err != nil { + return nil, err + } + + in.Run, in.RunNote = s.evaluationRun(ctx, name, in.Lang, in.Source, l) + + ev, err := evaluate.Generate(ctx, s.Claude, in, time.Now()) + if err != nil { + var f *claude.Failure + if errors.As(err, &f) { + log.Printf("[evaluate] %s: %s: %v", name, f.Msg, f.Err) + return nil, f + } + log.Printf("[evaluate] %s: %v", name, err) + return nil, errors.New("the evaluation could not be written") + } + return ev, nil +} + +// evaluationRun is Submit's run, for Claude to read. A run that cannot +// happen costs the evaluation its test verdicts, not the evaluation: the +// note says why, and goes to Claude in their place. +func (s *Server) evaluationRun(ctx context.Context, name, lang, source string, l *layout) (*runner.RunResponse, string) { + if s.Runner == nil { + return nil, "The tests were not run: the code runner is not configured." + } + tests, err := readRunTests(l) + if err != nil { + log.Printf("[evaluate] %s: reading the tests: %v", name, err) + return nil, "The tests were not run: they could not be read." + } + files, err := s.headers(l, lang) + if err != nil { + log.Printf("[evaluate] %s: reading the headers: %v", name, err) + return nil, "The tests were not run: the headers could not be read." + } + c, cancel := context.WithTimeout(ctx, runTimeout) + defer cancel() + res, err := s.Runner.Run(c, runner.RunRequest{Lang: lang, Source: source, Files: files, IO: l.io, Tests: tests}) + if err != nil { + log.Printf("[evaluate] %s: running the tests: %v", name, err) + return nil, "The tests were not run: the code runner failed." + } + return &res, "" +} diff --git a/site/internal/handlers/evaluate_test.go b/site/internal/handlers/evaluate_test.go new file mode 100644 index 0000000..cbe0b41 --- /dev/null +++ b/site/internal/handlers/evaluate_test.go @@ -0,0 +1,146 @@ +package handlers + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/evaluate" + "adam-french.co.uk/usaco-site/internal/explain" +) + +// fakeEvaluator flags line 1 of whatever it is shown, or fails. +type fakeEvaluator struct { + user string + fail bool +} + +func (f *fakeEvaluator) Model() string { return "fake-model" } +func (f *fakeEvaluator) JSON(_ context.Context, req claude.Request, out any) error { + f.user = req.User + if f.fail { + return &claude.Failure{Msg: "Claude declined to answer"} + } + *out.(*evaluate.Result) = evaluate.Result{ + Verdict: "edge_cases", Summary: "Prints zero.", + Issues: []evaluate.Issue{{Line: 1, Severity: "error", Title: "Never reads n"}}, + } + return nil +} + +type evalStatus struct { + State string `json:"state"` + Error string `json:"error"` + Result *evaluate.Evaluation `json:"result"` +} + +func waitEvaluate(t *testing.T, r *gin.Engine, name string) evalStatus { + t.Helper() + for range 400 { + var s evalStatus + json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/evaluate", "", true).Body.Bytes(), &s) + if s.State != explain.Running { + return s + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("evaluation still running") + return evalStatus{} +} + +const evalBody = `{"lang":"cpp","source":"int main() {}\n","note":"is it fast enough?"}` + +func TestEvaluateRefusals(t *testing.T) { + r, repo, _ := setupRun(t) + if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 503 { + t.Fatalf("no Claude = %d, want 503", rec.Code) + } + repo.srv.Claude = &fakeEvaluator{} + if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, false); rec.Code != 401 { + t.Fatalf("public evaluate = %d, want 401", rec.Code) + } + if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 400 { + t.Fatalf("no statement or link = %d, want 400: %s", rec.Code, rec.Body) + } + withStatement(t, r) + if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"cpp","source":" \n"}`, true); rec.Code != 400 { + t.Fatalf("empty source = %d, want 400", rec.Code) + } + if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"rust","source":"fn main() {}"}`, true); rec.Code != 400 { + t.Fatalf("rust = %d, want 400", rec.Code) + } + if rec := do(r, "POST", "/usaco/api/problems/two-sum/evaluate", `{"lang":"python","source":"x"}`, true); rec.Code != 400 { + t.Fatalf("python on LeetCode = %d, want 400", rec.Code) + } +} + +func TestEvaluateRunsTheTestsAndCommitsNothing(t *testing.T) { + r, repo, fr := setupRun(t) + fc := &fakeEvaluator{} + repo.srv.Claude = fc + withStatement(t, r) + commits := len(repo.msg) + + if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 202 { + t.Fatalf("evaluate = %d %s", rec.Code, rec.Body) + } + s := waitEvaluate(t, r, "moocast") + if s.State != explain.Done || s.Result == nil { + t.Fatalf("job = %+v", s) + } + ev := s.Result + if ev.Verdict != "edge_cases" || ev.Lang != "cpp" || ev.Source != "int main() {}\n" || ev.Model != "fake-model" || ev.Tests != "1/1 passed" { + t.Errorf("evaluation = %+v", ev) + } + if len(ev.Issues) != 1 || ev.Issues[0].Line != 1 { + t.Errorf("issues = %+v", ev.Issues) + } + // Submit's run: the saved tests, with the headers. + if fr.run == nil || len(fr.run.Tests) != 3 || fr.run.IO != "moocast" || fr.run.Files["debugging.h"] == "" { + t.Errorf("run = %+v", fr.run) + } + for _, want := range []string{"walkie-talkies", "\n1| int main() {}\n", "1/1 passed on the saved tests", "is it fast enough?"} { + if !strings.Contains(fc.user, want) { + t.Errorf("prompt is missing %q:\n%s", want, fc.user) + } + } + if len(repo.msg) != commits { + t.Errorf("an evaluation committed: %v", repo.msg[commits:]) + } +} + +func TestEvaluateWithoutARunner(t *testing.T) { + r, repo, fr := setupRun(t) + fc := &fakeEvaluator{} + repo.srv.Claude = fc + withStatement(t, r) + + // A runner that fails costs the verdicts, not the evaluation. + fr.err = errors.New("runner down") + do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true) + if s := waitEvaluate(t, r, "moocast"); s.State != explain.Done || s.Result.Tests != "The tests were not run: the code runner failed." { + t.Fatalf("with a failing runner = %+v", s) + } + + repo.srv.Runner = nil + if c := getCodeReply(t, r, "moocast"); c.Runner { + t.Fatal("runner still reported") + } + do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true) + s := waitEvaluate(t, r, "moocast") + if s.State != explain.Done || !strings.Contains(fc.user, "the code runner is not configured") { + t.Fatalf("with no runner = %+v\n%s", s, fc.user) + } + + fc.fail = true + do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true) + if s := waitEvaluate(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" || s.Result != nil { + t.Fatalf("a failed evaluation = %+v", s) + } +} diff --git a/site/internal/handlers/handlers.go b/site/internal/handlers/handlers.go index 9e078e1..d4058be 100644 --- a/site/internal/handlers/handlers.go +++ b/site/internal/handlers/handlers.go @@ -1,8 +1,8 @@ // Package handlers is the site's REST API: the problem list and pages (public // for solved problems, everything for the admin), the admin's edits, the // Claude explanations (explain.go) and recording reviews (review.go), the -// solve page's code editing and runs (run.go), and the Gitea webhook that -// tells the server to pull. +// solve page's code editing and runs (run.go) and evaluations +// (evaluate.go), and the Gitea webhook that tells the server to pull. package handlers import ( @@ -67,9 +67,9 @@ type Server struct { Runner Runner idx atomic.Pointer[index.Index] - // Separate, so a review and an explanation of one problem can run at - // the same time. - jobs, reviewJobs explain.Jobs + // Separate, so a review, an explanation and an evaluation of one + // problem can run at the same time. + jobs, reviewJobs, evalJobs explain.Jobs } // SetIndex swaps in a freshly built index. repo.Repo calls it (through @@ -111,6 +111,8 @@ func (s *Server) Routes(api *gin.RouterGroup) { admin.PUT("/problems/:name/code", s.saveCode) admin.POST("/problems/:name/run", s.run) admin.POST("/problems/:name/lint", s.lint) + admin.POST("/problems/:name/evaluate", s.startEvaluate) + admin.GET("/problems/:name/evaluate", s.evaluateStatus) admin.POST("/leetcode/daily", s.startDaily) api.POST("/hooks/gitea", s.webhook) } diff --git a/site/internal/handlers/run.go b/site/internal/handlers/run.go index 027ef7d..9c0cd20 100644 --- a/site/internal/handlers/run.go +++ b/site/internal/handlers/run.go @@ -16,6 +16,7 @@ import ( "github.com/gin-gonic/gin" + "adam-french.co.uk/usaco-site/internal/index" "adam-french.co.uk/usaco-site/internal/runner" ) @@ -159,6 +160,7 @@ func (s *Server) getCode(ctx *gin.Context) { "languages": l.languages(), "default": def, "runner": s.Runner != nil, + "claude": s.Claude != nil, "code": code, }) } @@ -248,44 +250,46 @@ type codeBody struct { // Mode and Input are for runs only. Mode string `json:"mode"` Input string `json:"input"` + // Note is for evaluations only. + Note string `json:"note"` } // readCode reads and checks a solve page request against the problem's // layout. It has answered when ok is false. -func (s *Server) readCode(ctx *gin.Context) (body codeBody, l *layout, ok bool) { - p, ok := s.lookup(ctx, true) +func (s *Server) readCode(ctx *gin.Context) (body codeBody, p *index.Problem, l *layout, ok bool) { + p, ok = s.lookup(ctx, true) if !ok { - return body, nil, false + return body, nil, nil, false } ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxRunBody) if err := ctx.ShouldBindJSON(&body); err != nil { var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the request is over 512 KB"}) - return body, nil, false + return body, nil, nil, false } ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"}) - return body, nil, false + return body, nil, nil, false } if len(body.Source) > maxSource { ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the source is over 256 KB"}) - return body, nil, false + return body, nil, nil, false } if body.Lang != runner.Cpp && body.Lang != runner.Python { ctx.JSON(http.StatusBadRequest, gin.H{"error": "lang must be cpp or python"}) - return body, nil, false + return body, nil, nil, false } l, err := s.readLayout(p.Status, p.Name) if err != nil { log.Printf("[code] %s: %v", p.Name, err) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"}) - return body, nil, false + return body, nil, nil, false } if !l.allows(body.Lang) { ctx.JSON(http.StatusBadRequest, gin.H{"error": "a LeetCode problem runs through its C++ driver only"}) - return body, nil, false + return body, nil, nil, false } - return body, l, true + return body, p, l, true } // headers are the files written next to a C++ source; Python needs none. @@ -333,7 +337,7 @@ func (s *Server) run(ctx *gin.Context) { if !s.runnerConfigured(ctx) { return } - body, l, ok := s.readCode(ctx) + body, _, l, ok := s.readCode(ctx) if !ok { return } @@ -472,7 +476,7 @@ func (s *Server) lint(ctx *gin.Context) { if !s.runnerConfigured(ctx) { return } - body, l, ok := s.readCode(ctx) + body, _, l, ok := s.readCode(ctx) if !ok { return } @@ -496,7 +500,7 @@ func (s *Server) lint(ctx *gin.Context) { // saveCode commits the editor's source as the problem's solution. An // unchanged source makes no commit: Mutate skips an empty diff. func (s *Server) saveCode(ctx *gin.Context) { - body, _, ok := s.readCode(ctx) + body, _, _, ok := s.readCode(ctx) if !ok { return } diff --git a/site/web/package-lock.json b/site/web/package-lock.json index cd67972..349ef24 100644 --- a/site/web/package-lock.json +++ b/site/web/package-lock.json @@ -8,6 +8,7 @@ "name": "usaco-site-web", "version": "0.0.0", "dependencies": { + "@codemirror/autocomplete": "^6.20.3", "@codemirror/commands": "^6.11.1", "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-python": "^6.2.1", diff --git a/site/web/package.json b/site/web/package.json index d41b968..56366c1 100644 --- a/site/web/package.json +++ b/site/web/package.json @@ -12,6 +12,7 @@ "preview": "vite preview" }, "dependencies": { + "@codemirror/autocomplete": "^6.20.3", "@codemirror/commands": "^6.11.1", "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-python": "^6.2.1", diff --git a/site/web/src/api.js b/site/web/src/api.js index 004fac4..fd6ea15 100644 --- a/site/web/src/api.js +++ b/site/web/src/api.js @@ -60,6 +60,11 @@ export const runCode = (name, body) => request("POST", `/problems/${encodeURICom export const lintCode = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/lint`, body); // Commits the source as the problem's solution file in that language. export const saveCode = (name, body) => request("PUT", `/problems/${encodeURIComponent(name)}/code`, body); +// body: { lang, source, note? }. Starts Claude judging the source (after a +// run of the saved tests) and answers 202; the status's result is the +// evaluation once it is done. Nothing is committed. +export const startEvaluate = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/evaluate`, body); +export const evaluateStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/evaluate`); // Imports today's LeetCode daily question (or finds it, if it is already a // problem) and answers { name, created }. It takes a few seconds. export const startDaily = () => request("POST", "/leetcode/daily"); diff --git a/site/web/src/completions.js b/site/web/src/completions.js new file mode 100644 index 0000000..d5dda7c --- /dev/null +++ b/site/web/src/completions.js @@ -0,0 +1,258 @@ +/** + * The solve page's autocomplete. CodeMirror's basicSetup already shows + * completions as you type, but @codemirror/lang-cpp offers none, and + * lang-python only keywords, builtins and the names defined in the file. + * + * Both languages get the library a contest solution reaches for, and + * member names after "." (and "->"), which neither language package does. + * Members are the common STL (or list/dict/str) ones plus every member + * already used in the file: without a type checker, that is as close as a + * completion can get to what the object actually has. C++ also gets every + * name in the file, so the template's macros and typedefs (F, takeI, ll) + * come up with what they expand to, and snippets for the loops and lambdas + * that are typed over and over. + * + * A real language server (clangd) would know types, but would have to run + * beside the code runner and hold a session open per editor; this is local + * and instant. + */ +import { completeFromList, ifNotIn, snippetCompletion as snip } from "@codemirror/autocomplete"; +import { syntaxTree } from "@codemirror/language"; +import { cppLanguage } from "@codemirror/lang-cpp"; +import { pythonLanguage } from "@codemirror/lang-python"; + +// "a b c" as completions of one type, with a detail (the header). +const words = (list, type, detail) => list.trim().split(/\s+/).map((label) => ({ label, type, detail })); + +// ---- C++ ---- + +const CPP_KEYWORDS = words( + `auto bool break case catch char class const constexpr continue default delete do double else enum explicit + extern false float for friend goto if inline int long mutable namespace new noexcept nullptr operator private + protected public return short signed sizeof static static_assert static_cast struct switch template this throw + true try typedef typename union unsigned using virtual void volatile while`, + "keyword", +); + +const CPP_LIBRARY = [ + ...words( + "vector string array deque list map multimap set multiset unordered_map unordered_set unordered_multimap stack queue priority_queue bitset pair tuple optional function", + "type", + "std", + ), + ...words("int64_t uint64_t int32_t uint32_t size_t __int128", "type"), + ...words("greater less hash", "class", ""), + ...words("cin cout cerr endl", "variable", ""), + ...words("getline to_string stoi stoll stod freopen printf scanf puts", "function", "/"), + ...words( + `sort stable_sort reverse min max swap minmax lower_bound upper_bound equal_range binary_search unique fill + find find_if count count_if max_element min_element next_permutation prev_permutation nth_element + partial_sort rotate all_of any_of none_of transform copy remove remove_if shuffle`, + "function", + "", + ), + ...words("accumulate iota partial_sum adjacent_difference gcd lcm", "function", ""), + ...words("abs sqrt sqrtl cbrt pow exp log log2 log10 floor ceil round hypot", "function", ""), + ...words("make_pair make_tuple tie get move distance next prev advance begin end", "function", "std"), + ...words("memset memcpy strlen", "function", ""), + ...words( + "__builtin_popcount __builtin_popcountll __builtin_clz __builtin_clzll __builtin_ctz __builtin_ctzll __lg", + "function", + "builtin", + ), + ...words("INT_MAX INT_MIN LLONG_MAX LLONG_MIN UINT_MAX", "constant", ""), + { label: "numeric_limits", type: "class", detail: "" }, + { label: "mt19937", type: "class", detail: "" }, + { label: "chrono", type: "namespace" }, + { label: "std", type: "namespace" }, +]; + +// Nothing knows the object's type, so the members used most come first. +const COMMON_MEMBERS = new Set(["push_back", "size", "begin", "end", "first", "second", "back", "pop_back", "insert", "count"]); +const CPP_MEMBERS = words( + `push_back emplace_back pop_back push_front emplace_front pop_front back front size empty clear begin end + rbegin rend insert emplace erase find count lower_bound upper_bound resize reserve assign at data swap + push pop top first second substr length append c_str compare set reset flip test any none all to_string + to_ullong value has_value`, + "method", +).map((c) => (COMMON_MEMBERS.has(c.label) ? { ...c, boost: 1 } : c)); + +// The template's habits, as snippets. Same-named fields are edited +// together, so typing the loop variable once fills in all three. +const CPP_SNIPPETS = [ + snip("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", { label: "for", detail: "loop", type: "keyword" }), + snip("for (int ${i} = ${n} - 1; ${i} >= 0; ${i}--) {\n\t${}\n}", { label: "forr", detail: "loop down", type: "keyword" }), + snip("for (auto &${x} : ${v}) {\n\t${}\n}", { label: "foreach", detail: "range loop", type: "keyword" }), + snip("while (${}) {\n\t${}\n}", { label: "while", detail: "loop", type: "keyword" }), + snip("if (${}) {\n\t${}\n}", { label: "if", detail: "block", type: "keyword" }), + snip("if (${}) {\n\t${}\n} else {\n\t${}\n}", { label: "ifelse", detail: "block", type: "keyword" }), + snip("struct ${Name} {\n\t${}\n};", { label: "struct", detail: "definition", type: "keyword" }), + snip("auto ${f} = [&](${}) {\n\t${}\n};", { label: "lambda", detail: "[&] lambda", type: "keyword" }), + snip("function ${dfs} = [&](int ${u}) {\n\t${}\n};", { + label: "dfs", + detail: "recursive lambda", + type: "keyword", + }), + snip("sort(${a}.begin(), ${a}.end(), [&](const auto &${x}, const auto &${y}) {\n\treturn ${};\n});", { + label: "sortby", + detail: "sort with a comparator", + type: "keyword", + }), +]; + +// A keyword with a snippet of the same name would hide it behind a plain +// word, so the snippet stands in for it. +const SNIPPED = new Set(CPP_SNIPPETS.map((c) => c.label)); +const CPP_FIXED = [...CPP_KEYWORDS.filter((c) => !SNIPPED.has(c.label)), ...CPP_LIBRARY, ...CPP_SNIPPETS]; +const CPP_FIXED_LABELS = new Set(CPP_FIXED.map((c) => c.label)); + +// Comments, strings and #include <...> get no completions. +const CPP_SKIP = new Set(["LineComment", "BlockComment", "String", "RawString", "CharLiteral", "SystemLibString"]); +const CPP_NAMES = new Set(["Identifier", "TypeIdentifier", "NamespaceIdentifier"]); + +// "#define F(i, L, R) for (...)": a macro, shown with its parameters and +// what it expands to. +const DEFINE = /^[ \t]*#[ \t]*define[ \t]+([A-Za-z_]\w*)(\([^)]*\))?/dgm; +// "typedef long long ll;" and "using vi = vector;" +const ALIAS = /\btypedef\s+([^;]+?)\s+([A-Za-z_]\w*)\s*;|\busing\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g; + +function brief(s) { + s = s.replace(/\s+/g, " ").trim(); + return s.length > 48 ? s.slice(0, 47) + "…" : s; +} + +// A macro's body: the rest of its line, and the next while a line ends in +// a backslash. +function macroBody(text, at) { + let body = ""; + for (;;) { + const end = text.indexOf("\n", at); + const line = text.slice(at, end < 0 ? text.length : end); + if (!line.endsWith("\\") || end < 0) return body + line; + body += line.slice(0, -1) + " "; + at = end + 1; + } +} + +// The file's own names, leaving out the word being typed (at skipFrom): +// otherwise every half-typed name would complete to itself. +function cppFileNames(state, skipFrom) { + const text = state.doc.toString(); + const out = new Map(); + for (const m of text.matchAll(DEFINE)) { + if (m.indices[1][0] === skipFrom) continue; + const body = brief(macroBody(text, m.index + m[0].length)); + // The template defines DBG twice, the #else one empty: keep the one + // that says something. + if (!body && out.has(m[1])) continue; + out.set(m[1], { + label: m[1], + type: m[2] ? "function" : "constant", + detail: m[2] ? m[2].replace(/\s+/g, "") : undefined, + info: body || undefined, + boost: 2, + }); + } + for (const m of text.matchAll(ALIAS)) { + const [name, to] = m[2] ? [m[2], m[1]] : [m[3], m[4]]; + if (!out.has(name)) out.set(name, { label: name, type: "type", detail: brief(to), boost: 2 }); + } + syntaxTree(state).iterate({ + enter(n) { + if (CPP_SKIP.has(n.name)) return false; + if (!CPP_NAMES.has(n.name) || n.from === skipFrom) return; + const name = text.slice(n.from, n.to); + if (name.length < 2 || out.has(name) || CPP_FIXED_LABELS.has(name)) return; + out.set(name, { label: name, type: n.name === "TypeIdentifier" ? "type" : "variable", boost: 1 }); + }, + }); + return [...out.values()]; +} + +// Members already used in the file (x.first, it->second, seg.query). +function fileMembers(state, nodeName, skipFrom, known) { + const out = []; + const seen = new Set(known); + syntaxTree(state).iterate({ + enter(n) { + if (n.name !== nodeName || n.from === skipFrom) return; + const name = state.sliceDoc(n.from, n.to); + if (seen.has(name)) return; + seen.add(name); + out.push({ label: name, type: "property" }); + }, + }); + return out; +} + +const CPP_MEMBER_LABELS = CPP_MEMBERS.map((c) => c.label); + +// Whether the word at from follows a member access: "." but not the one in +// "1." (a number), and in C++ "->" too. +function afterMember(state, from, arrow) { + const text = state.sliceDoc(Math.max(0, from - 32), from); + if (arrow && text.endsWith("->")) return true; + return text.endsWith(".") && !/(^|[^\w])\d+\.$/.test(text); +} + +function cppSource(context) { + const node = syntaxTree(context.state).resolveInner(context.pos, -1); + for (let n = node; n; n = n.parent) if (CPP_SKIP.has(n.name)) return null; + const word = context.matchBefore(/[A-Za-z_]\w*/); + const from = word ? word.from : context.pos; + if (afterMember(context.state, from, true)) { + return { + from, + options: [...CPP_MEMBERS, ...fileMembers(context.state, "FieldIdentifier", from, CPP_MEMBER_LABELS)], + validFor: /^\w*$/, + }; + } + if (!word && !context.explicit) return null; + return { from, options: [...cppFileNames(context.state, from), ...CPP_FIXED], validFor: /^\w*$/ }; +} + +export const cppCompletions = () => cppLanguage.data.of({ autocomplete: cppSource }); + +// ---- Python ---- + +// The standard library a contest solution imports from. lang-python +// already completes builtins and the file's own names, and has its own +// def/for/class snippets. +const PY_LIBRARY = [ + ...words("defaultdict Counter deque OrderedDict", "class", "collections"), + ...words("heappush heappop heapify heappushpop nlargest nsmallest", "function", "heapq"), + ...words("bisect_left bisect_right insort", "function", "bisect"), + ...words("lru_cache cache cmp_to_key reduce", "function", "functools"), + ...words("accumulate permutations combinations combinations_with_replacement product groupby pairwise", "function", "itertools"), + ...words("gcd lcm isqrt comb perm inf sqrt log2 ceil floor", "function", "math"), + ...words("setrecursionlimit stdin stdout", "function", "sys"), + snip("sys.setrecursionlimit(${10 ** 6})", { label: "recursionlimit", detail: "sys", type: "keyword" }), +]; + +const PY_MEMBERS = words( + `append extend insert pop remove clear sort reverse index count copy keys values items get setdefault update + add discard union intersection difference split join strip lstrip rstrip startswith endswith replace find + lower upper isdigit appendleft popleft most_common read readline buffer`, + "method", +); +const PY_MEMBER_LABELS = PY_MEMBERS.map((c) => c.label); + +const pyLibrary = completeFromList(PY_LIBRARY); + +function pySource(context) { + const word = context.matchBefore(/[A-Za-z_]\w*/); + const from = word ? word.from : context.pos; + if (afterMember(context.state, from, false)) { + return { + from, + options: [...PY_MEMBERS, ...fileMembers(context.state, "PropertyName", from, PY_MEMBER_LABELS)], + validFor: /^\w*$/, + }; + } + // lang-python leaves property names alone; everywhere else the library + // joins its builtins. + return pyLibrary(context); +} + +export const pythonCompletions = () => + pythonLanguage.data.of({ autocomplete: ifNotIn(["String", "FormatString", "Comment"], pySource) }); diff --git a/site/web/src/components/CodeEditor.vue b/site/web/src/components/CodeEditor.vue index 013dac9..f18cbc9 100644 --- a/site/web/src/components/CodeEditor.vue +++ b/site/web/src/components/CodeEditor.vue @@ -14,6 +14,9 @@ * is remote and debounced by the page), and are pushed with setDiagnostics * rather than through a linter() source the editor would schedule itself. * CodeMirror maps them through later edits until the next set arrives. + * + * Completions come from basicSetup's autocompletion with sources of our own + * (completions.js), since lang-cpp has none. */ import { onBeforeUnmount, onMounted, ref, watch } from "vue"; import { basicSetup } from "codemirror"; @@ -25,6 +28,7 @@ import { lintGutter, setDiagnostics } from "@codemirror/lint"; import { cpp } from "@codemirror/lang-cpp"; import { python } from "@codemirror/lang-python"; import { tags as t } from "@lezer/highlight"; +import { cppCompletions, pythonCompletions } from "@/completions"; const props = defineProps({ modelValue: { type: String, required: true }, @@ -37,9 +41,9 @@ const emit = defineEmits(["update:modelValue", "run", "submit", "save"]); // The workspace's styles: clang-format's two spaces for C++, PEP 8's four. const LANGS = { - cpp: () => [cpp(), indentUnit.of(" ")], - c: () => [cpp(), indentUnit.of(" ")], - python: () => [python(), indentUnit.of(" ")], + cpp: () => [cpp(), cppCompletions(), indentUnit.of(" ")], + c: () => [cpp(), cppCompletions(), indentUnit.of(" ")], + python: () => [python(), pythonCompletions(), indentUnit.of(" ")], }; const highlight = HighlightStyle.define([ @@ -95,6 +99,14 @@ const theme = EditorView.theme( ".cm-diagnostic-info": { borderLeftColor: "var(--color-ink-faint)" }, ".cm-diagnosticSource": { color: "var(--color-ink-muted)" }, ".cm-panels": { backgroundColor: "var(--color-paper-tint)", color: "var(--color-ink)" }, + ".cm-tooltip.cm-tooltip-autocomplete > ul": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", maxHeight: "16em" }, + ".cm-tooltip.cm-tooltip-autocomplete > ul > li": { padding: "1px 8px 1px 4px" }, + ".cm-tooltip-autocomplete ul li[aria-selected]": { backgroundColor: "#d7e6fb", color: "var(--color-ink)" }, + ".cm-completionMatchedText": { textDecoration: "none", fontWeight: "600" }, + ".cm-completionDetail": { color: "var(--color-ink-muted)", fontStyle: "normal", marginLeft: "1em" }, + ".cm-completionIcon": { opacity: "0.55" }, + ".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" }, + ".cm-snippetField": { backgroundColor: "rgba(0, 0, 0, 0.05)" }, }, { dark: false }, ); @@ -186,7 +198,16 @@ watch( ); watch(() => props.diagnostics, () => view && pushDiagnostics()); -defineExpose({ focus: () => view?.focus() }); +// Puts the cursor at the start of a line's code and shows it. +function goto(line) { + if (!view) return; + const l = view.state.doc.line(Math.min(Math.max(line, 1), view.state.doc.lines)); + const at = l.from + (/^\s*/.exec(l.text)?.[0].length || 0); + view.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) }); + view.focus(); +} + +defineExpose({ focus: () => view?.focus(), goto });