From ccf4e4dd74ebdca0d2d483e5310274caf6db492d Mon Sep 17 00:00:00 2001 From: Adam French Date: Tue, 20 Oct 2026 12:58:38 +0100 Subject: [PATCH] Explain concepts on the site, and reuse their code from the CLI /usaco/concepts is a library of techniques Claude explained: the admin asks by topic ("help explain fenwick trees") or pastes code they could not follow, and gets an intuitive explanation with SVG diagrams plus a C++ snippet in contest style. Given code, the walkthrough traces that code and the snippet is a general version of it. Anyone can read the library; generating, rewriting and deleting are admin-only. Each concept is committed as concepts//: concept.md (tags in a header comment, then a # title), snippet.cpp (first line "// concept: ") and request.md (the question, for rewrites). The slug is Claude's to pick, so a new concept's job is keyed by an id and returns {slug} as its result; a taken slug gets -2, -3... rather than overwriting. Rewriting starts from the saved question and version plus a note on what to change. The index reads concepts into Index.Concepts, with their date from git. internal/concept shares explain's math and diagram rules, now split out as explain.MathRules and explain.DiagramRules; the explain prompt is byte-for-byte unchanged. Code fences in explanations are highlighted with the same highlight.js setup as CodeBlock (web/src/highlight.js). `usaco snippet` lists concepts, prints one's snippet, or pastes it into a solution above main (or class Solution), keeping a .bak and refusing a concept the file already has. In interactive mode it pastes into the selection. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 + lib/cmd/interactive.sh | 10 +- lib/cmd/snippet.sh | 43 ++++ lib/common.sh | 21 ++ site/CLAUDE.md | 1 + site/README.md | 22 +- site/internal/concept/concept.go | 310 ++++++++++++++++++++++++ site/internal/concept/concept_test.go | 151 ++++++++++++ site/internal/explain/explain.go | 19 +- site/internal/explain/explain_test.go | 3 + site/internal/handlers/concept.go | 269 ++++++++++++++++++++ site/internal/handlers/concept_test.go | 189 +++++++++++++++ site/internal/handlers/handlers.go | 14 +- site/internal/index/index.go | 117 ++++++++- site/internal/index/index_test.go | 28 +++ site/web/src/App.vue | 1 + site/web/src/api.js | 13 + site/web/src/components/CodeBlock.vue | 23 +- site/web/src/components/Explanation.vue | 21 +- site/web/src/highlight.js | 22 ++ site/web/src/router.js | 2 + site/web/src/views/CliPage.vue | 1 + site/web/src/views/ConceptList.vue | 262 ++++++++++++++++++++ site/web/src/views/ConceptPage.vue | 226 +++++++++++++++++ usaco | 7 +- 25 files changed, 1750 insertions(+), 33 deletions(-) create mode 100644 lib/cmd/snippet.sh create mode 100644 site/internal/concept/concept.go create mode 100644 site/internal/concept/concept_test.go create mode 100644 site/internal/handlers/concept.go create mode 100644 site/internal/handlers/concept_test.go create mode 100644 site/web/src/highlight.js create mode 100644 site/web/src/views/ConceptList.vue create mode 100644 site/web/src/views/ConceptPage.vue diff --git a/README.md b/README.md index 80f37c9..095efad 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ site/ the website (Go server + Vue SPA), deployed as its own containe solving// problems in progress solved// finished problems skipped// problems set aside for later +concepts// techniques the website had Claude explain: concept.md, snippet.cpp, request.md ``` The website's CLI page (`site/web/src/views/CliPage.vue`) is a condensed copy of the Commands section below; keep it in step. @@ -134,6 +135,13 @@ Opens from inside the problem dir, so the `.in`/`.out` files are right there. ``` `copy` auto-detects the clipboard tool: `wl-copy` on Wayland, then `xclip`/`xsel` on X11, and falls back to an OSC52 terminal escape that works even over SSH. +``` +./usaco snippet # list the concepts explained on the website +./usaco snippet fenwick-tree # print its C++ snippet (pipeable; prefixes work) +./usaco snippet fenwick diamond-collector # paste it into the solution above main (alias: sn) +``` +Pasting saves the old solution as `main.cpp.bak` and refuses a concept the solution already has (each snippet starts with a `// concept: ` line). Run `usaco sync` first to pull concepts made on the website. In interactive mode, `snippet ` pastes into the selected problem. + ### Interactive mode ``` ./usaco i # (aliases: interactive, repl) diff --git a/lib/cmd/interactive.sh b/lib/cmd/interactive.sh index b64123d..307743c 100644 --- a/lib/cmd/interactive.sh +++ b/lib/cmd/interactive.sh @@ -12,7 +12,7 @@ WITH_PROBLEM="run build test done undo skip io cat copy edit open path reset" # commands that take no problem NO_PROBLEM="list stats clean sync lang" # REPL-only words (used for completion and for 'help') -REPL_WORDS="s use none push pop stack help quit exit" +REPL_WORDS="s use none push pop stack help quit exit snippet" cur="" [[ -r "$CURRENT_FILE" ]] && cur="$(<"$CURRENT_FILE")" @@ -72,6 +72,8 @@ ${DIM}problem commands${RST} ${DIM}(name optional — omit it to use the selecti ${DIM}other${RST} $NO_PROBLEM, new [io] [--rust|--cpp], new lint [] clippy the selection, or every rust solution + snippet [ []] + list concepts, or paste one's C++ into the selection help [] this, or the dispatcher's usage line for !cmd run a shell command in the problem dir q quit @@ -142,6 +144,12 @@ while :; do if USACO_CREATED="$created" "$ROOT/usaco" new "${args[@]}"; then set_current "$(<"$created")"; fi rm -f "$created" continue ;; + snippet|sn) + # 'snippet ' pastes into the selection; a second word + # names the problem, and none lists the concepts + [[ ${#args[@]} -eq 1 && -n "$cur" ]] && args+=("$cur") + "$ROOT/usaco" snippet "${args[@]+"${args[@]}"}" || true + continue ;; lint) # the one command whose problem name is optional: it lints the # selection if there is one, otherwise every rust solution diff --git a/lib/cmd/snippet.sh b/lib/cmd/snippet.sh new file mode 100644 index 0000000..82ade3d --- /dev/null +++ b/lib/cmd/snippet.sh @@ -0,0 +1,43 @@ +# usaco snippet [ []] +# Concepts are techniques the website had Claude explain, under +# concepts// (pull with 'usaco sync' first). Their snippet.cpp starts +# with a "// concept: " line, which is how a solution that already has +# one is recognised. +if [[ $# -eq 0 ]]; then # list them + shopt -s nullglob + found="" + for d in "$ROOT"/concepts/*/; do + d="${d%/}"; [[ -f "$d/snippet.cpp" ]] || continue + found=1 + title="$(concept_title "$d")" + printf ' %-28s %s\n' "$(basename "$d")" "${title:-}" + done + [[ -n "$found" ]] || echo "No concepts yet: explain one on the website, then 'usaco sync'." + exit 0 +fi +cdir="$(find_concept "$1")" +snip="$cdir/snippet.cpp" +[[ -f "$snip" ]] || { echo "Error: ${cdir#$ROOT/} has no snippet.cpp" >&2; exit 1; } +if [[ $# -eq 1 ]]; then cat "$snip"; exit 0; fi + +dir="$(find_problem "$2")" +main="$(main_file "$dir")" +[[ "$main" == *.cpp ]] || { echo "Error: snippets are C++, and $(basename "$dir") is $(lang_of "$dir")" >&2; exit 1; } +marker="$(head -n 1 "$snip")" +if grep -qxF "$marker" "$main"; then + echo "$(basename "$dir") already has $(basename "$cdir")" >&2; exit 1 +fi +cp "$main" "$main.bak" +# Above main (or LeetCode's class Solution), so the solution can call it; +# at the end if neither is there. +awk -v snip="$snip" ' + !done && /^(int|signed) main\(|^class Solution/ { + while ((getline l < snip) > 0) print l + print "" + done = 1 + } + { print } + END { + if (!done) { print ""; while ((getline l < snip) > 0) print l } + }' "$main.bak" > "$main" +echo "Added $(basename "$cdir") to ${main#$ROOT/} (old one in $(basename "$main").bak)" diff --git a/lib/common.sh b/lib/common.sh index 9cbc7f2..84e868f 100644 --- a/lib/common.sh +++ b/lib/common.sh @@ -60,6 +60,27 @@ find_problem() { # echoes dir of problem in solving/, solved/, or skipped/; uni return 1 } +find_concept() { # echoes dir of concepts/; unique prefix ok + local name="$1" d matches=() + if [[ -d "$ROOT/concepts/$name" ]]; then echo "$ROOT/concepts/$name"; return 0; fi + for d in "$ROOT/concepts/$name"*/; do + [[ -d "$d" ]] && matches+=("${d%/}") + done + if [[ ${#matches[@]} -eq 1 ]]; then echo "${matches[0]}"; return 0; fi + if [[ ${#matches[@]} -gt 1 ]]; then + echo "Error: '$name' is ambiguous:" >&2 + printf ' %s\n' "${matches[@]#$ROOT/}" >&2 + return 1 + fi + echo "Error: concept '$name' not found in concepts/ (try 'usaco sync')" >&2 + return 1 +} + +concept_title() { # $1 = concept dir: echoes the "# " title of its concept.md, if any + [[ -f "$1/concept.md" ]] || return 0 + sed -n 's/^# //p' "$1/concept.md" | head -n 1 +} + # ----- rust project model (for rust-analyzer / clippy) ----- # Problems are bare main.rs files with no manifest, and rust-analyzer only does # real analysis -- type-aware diagnostics, clippy on save -- inside a cargo diff --git a/site/CLAUDE.md b/site/CLAUDE.md index 7f4d927..d2b4c60 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`. +- **Concepts are the same shape, outside the problems.** `POST /concepts` has Claude explain a technique or pasted code (`internal/concept`) and commits `concepts//` (explanation, C++ snippet, the request). The slug is Claude's, so a new concept's job is keyed by an id and returns `{slug}` as its `Result`; rewrites are keyed by slug. The index reads them into `Index.Concepts`, and they are public. - **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 e7673b6..addc447 100644 --- a/site/README.md +++ b/site/README.md @@ -7,6 +7,7 @@ The public face of this repo, served at `/usaco/` on adam-french.co.uk. It shows - save the problem statement (pasted, or fetched from a LeetCode or USACO link) - write notes - have Claude write an explanation for a problem they are stuck on +- have Claude explain a technique ("help explain fenwick trees") or a piece of code, saved to a public library of concepts with a C++ snippet to reuse It is one Go binary that serves a REST API and the built Vue SPA. It runs as one container behind the site's nginx and borrows the site's login, the same arrangement as job-tracker (adamf/job-tracker), which it is modelled on. @@ -22,6 +23,7 @@ There is no database. The CLI's layout is the data model (see the root README.md - `problem.md` for the statement (shown only to the admin, and sent to Claude) - `explain.md` for a Claude-written explanation - `reviews/.md` for feedback on a recording of the admin explaining their solution (admin only) +- `concepts//` for a concept: `concept.md`, `snippet.cpp` and `request.md` The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into memory. @@ -49,6 +51,7 @@ internal/index/ reads the clone into memory: problems, files, tests, git dat internal/handlers/ REST API, Gitea webhook, SPA file server internal/claude/ the Claude client: streamed call, JSON-schema reply, fixed error messages internal/explain/ the explanation prompt and schema, explain.md rendering, the job tracker +internal/concept/ the concept prompt and schema, concepts// rendering 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 @@ -64,7 +67,7 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro | Path | Auth | What | |---|---|---| -| `/usaco/`, `/usaco/p/`, `/usaco/stats`, `/usaco/cli` | none | SPA | +| `/usaco/`, `/usaco/p/`, `/usaco/concepts`, `/usaco/c/`, `/usaco/stats`, `/usaco/cli` | none | SPA | | `GET /usaco/api/problems` | open; the admin also gets unsolved problems | the list | | `GET /usaco/api/problems/` | open for solved problems; 404 for others unless admin | one problem, with files, tests and history | | `GET /usaco/api/me` | open | `{admin}`, so the SPA knows whether to show the edit controls | @@ -84,6 +87,13 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro | `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 | +| `GET /usaco/api/concepts` | open | the concept library, newest first, without content or snippets | +| `GET /usaco/api/concepts/` | open | one concept: `{slug, title, summary, tags, content, snippet, updated}` | +| `POST /usaco/api/concepts` | admin | `{topic, code?}`: starts explaining a new concept and answers 202 `{id, status}`. 503 without `CLAUDE_API_KEY` | +| `GET /usaco/api/concept-jobs/` | admin | that job, shaped like the explain one, with `result: {slug}` once it is saved | +| `POST /usaco/api/concepts//explain` | admin | `{note?}`: rewrites the concept in place and answers 202; 409 if a rewrite is running | +| `GET /usaco/api/concepts//explain` | admin | the latest rewrite job | +| `DELETE /usaco/api/concepts/` | admin | removes `concepts//`, committed as "Forget concept " | | `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull | | `GET /usaco/api/health` | open | 200 once the clone is indexed | @@ -164,6 +174,16 @@ The Explain panel on a problem page (admin only) asks Claude for an intuitive ex - **The call.** `CLAUDE_MODEL` (default `claude-opus-5-5`) at high effort, streamed, with the server-side refusal fallback on. It takes a minute or two and costs roughly $0.10 to $0.60. The request only starts a background job, because nginx gives up after 120 seconds; the page polls. Token usage is logged as `[claude]` lines. - **Statements.** LeetCode and USACO can be fetched. Codeforces sits behind a Cloudflare challenge, and other judges are unknown, so paste those. +## Concepts + +`/usaco/concepts` is a library of techniques Claude explained, each with a C++ snippet to reuse. Anyone can read it; the admin asks for new ones there, by topic ("help explain fenwick trees") or by pasting code they could not follow. + +- **Output.** A JSON-schema reply (`internal/concept` `Schema`): a slug, title, one-line summary and tags, then the intuition, how it works, a walkthrough with SVG diagrams, complexity, when to reach for it, pitfalls, variations, the snippet and a usage example. Given code, the walkthrough traces that code and the snippet is a general version of it. It shares the explanation prompt's math and diagram rules (`explain.MathRules`, `explain.DiagramRules`), so the page renders it with the same `Explanation` component. +- **Storage.** `concepts//concept.md` (first line ``, then a `# ` title), `snippet.cpp` (first line `// concept: `) and `request.md` (the question, so the concept can be rewritten from it). Committed as "Explain concept ". +- **Slugs.** Claude names the concept and is shown the saved ones. A new question never overwrites a saved concept: a taken slug gets `-2`, `-3`… Rewriting one (with a note on what to change) is its own button on the concept's page. +- **Reuse.** The page has a copy button, and `usaco snippet ` pastes the snippet into a solution above `main`. +- **The call.** As for explanations: a background job the page polls, a minute or two, a similar cost. + ## Recording reviews The "Review my explanation" panel (admin only) takes a recording of the admin explaining a solution out loud, as to an interviewer, and commits feedback on it as `reviews/.md`. The id is the UTC time it started (`2026-10-20-153000`), so each attempt is its own file and the page lists them newest first. diff --git a/site/internal/concept/concept.go b/site/internal/concept/concept.go new file mode 100644 index 0000000..4f4630c --- /dev/null +++ b/site/internal/concept/concept.go @@ -0,0 +1,310 @@ +// Package concept turns "help explain fenwick trees", or a piece of code the +// admin could not follow, into a saved concept: concepts//concept.md, +// an intuitive explanation by Claude with SVG diagrams of the idea running, +// and snippet.cpp, a C++ implementation to paste into solutions (`usaco +// snippet` does it from the CLI). +// +// It is the same shape as internal/explain, and shares its math and diagram +// rules, but it teaches a technique rather than coaching a problem, so it +// hands over working code where explain only gives pseudocode. +package concept + +import ( + "context" + "fmt" + "regexp" + "strings" + "time" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" +) + +// Ref is a concept already saved, so Claude names a new one apart from it. +type Ref struct { + Slug, Title string +} + +// Input is what Claude is told. +type Input struct { + Topic string // what the admin asked + Code string // code they want explained, if any + // Previous and Note are set when an existing concept is rewritten: + // what is saved now (explanation and snippet), and what to change. + Previous string + Note string + Existing []Ref +} + +// Result is the reply's shape; Schema is the same thing for the API. +type Result struct { + Slug string `json:"slug"` + Title string `json:"title"` + Summary string `json:"summary"` + Tags []string `json:"tags"` + Intuition string `json:"intuition"` + HowItWorks string `json:"how_it_works"` + Walkthrough []explain.Step `json:"walkthrough"` + Complexity string `json:"complexity"` + WhenToUse string `json:"when_to_use"` + Pitfalls []string `json:"pitfalls"` + Variations string `json:"variations"` + Snippet string `json:"snippet"` + Usage string `json:"usage"` +} + +func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} } + +func strs(desc string) map[string]any { + return map[string]any{"type": "array", "items": 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{ + "slug": str("A short kebab-case name for the concept, such as fenwick-tree or kmp-prefix-function. For code, name the technique it uses. It must not be one of the saved concepts' slugs."), + "title": str("The concept's name as a heading, such as \"Fenwick tree (binary indexed tree)\". Plain text."), + "summary": str("One sentence of plain text: what it does and how fast, for the library's list."), + "tags": strs("Two to five kebab-case tags for finding it again, such as range-query, prefix-sums, graphs, strings, dp."), + "intuition": str("Markdown. The problem it solves, why the obvious approach is too slow or wrong, and the idea that fixes that, so the structure feels inevitable."), + "how_it_works": str("Markdown. The structure and each operation: exactly what every entry, node or pointer means, and why each operation keeps that true."), + "walkthrough": map[string]any{ + "type": "array", + "description": "Three to six steps running the operations on one small example, building the state and then querying or updating it.", + "items": map[string]any{ + "type": "object", + "properties": map[string]any{ + "caption": str("Markdown: what is happening at this step and why."), + "svg": str("One complete element showing the state at this step, following the diagram rules."), + }, + "required": []string{"caption", "svg"}, + "additionalProperties": false, + }, + }, + "complexity": str("Markdown. Time per operation and memory, with a one-line reason for each."), + "when_to_use": str("Markdown. The signals in a problem that call for it, and close alternatives with when to prefer them."), + "pitfalls": strs("Markdown. The mistakes that commonly break it: off-by-ones, 0- versus 1-based indices, overflow, forgetting to reset between test cases."), + "variations": str("Markdown. Common extensions, such as range updates, 2D or other operations, each with the change it needs. Empty if there are none worth knowing."), + "snippet": str("The reusable C++ implementation, following the snippet rules. Plain code, no fence."), + "usage": str("A few lines of C++ calling the snippet the way a solution would. Plain code, no fence."), + }, + "required": []string{"slug", "title", "summary", "tags", "intuition", "how_it_works", "walkthrough", "complexity", "when_to_use", "pitfalls", "variations", "snippet", "usage"}, + "additionalProperties": false, +} + +// maxTokens leaves room for adaptive thinking at high effort on top of the +// reply, which is explain's prose and SVGs plus the code. +const maxTokens = 32000 + +// System is the same on every call, so it is cached. +const System = `You are a patient competitive-programming tutor. Someone wants to understand a technique, data structure or algorithm well enough to use it in contests, or to understand a piece of code they have read. Your explanation goes into their personal library, which they come back to, together with a C++ implementation they paste into solutions. + +How to explain: +- Lead with the problem the technique solves and why the obvious approach is too slow or wrong, so the idea feels inevitable rather than magic. +- Make every part of the structure concrete: say exactly what each array entry, node, pointer or bit means, and why each operation keeps that meaning true. +- Justify correctness and complexity informally but convincingly. +- If they give code, explain that code: what each variable holds, what each loop establishes and why its conditions are the right ones. The walkthrough traces that code on a small input you choose, and the snippet is a clean, general version of it. +- If they give the previous version of the explanation and what to change, rewrite it with that change, keeping what was good. +- Write in plain, direct prose. Use markdown for emphasis, lists and inline code. +` + explain.MathRules + ` + +Snippet rules: +- C++17 that compiles when pasted after #include and using namespace std;, above main. No main, no input or output, no macros. +- One struct or a few functions, named for the concept, with a short comment on each operation saying what it does, its complexity, and whether indices are 0- or 1-based. +- long long wherever sums or products can overflow int. As short as clarity allows: this is contest code, not a library. + +Diagram rules for each walkthrough step's svg: +- Show the actual mechanism on a small concrete example: the array and the tree or table built over it, which cells an operation reads or writes, index bits when they matter, pointers moving. Successive steps should show the state changing. +` + explain.DiagramRules + +// Prompt is the user message. +func Prompt(in Input) string { + var b strings.Builder + fmt.Fprintf(&b, "\n%s\n\n", strings.TrimSpace(in.Topic)) + if code := strings.TrimRight(in.Code, " \t\r\n"); strings.TrimSpace(code) != "" { + fmt.Fprintf(&b, "\n\n%s\n\n", code) + } + if len(in.Existing) > 0 { + b.WriteString("\n\n") + for _, r := range in.Existing { + fmt.Fprintf(&b, "- %s: %s\n", r.Slug, r.Title) + } + b.WriteString("\n") + } + if prev := strings.TrimSpace(in.Previous); prev != "" { + fmt.Fprintf(&b, "\n\n%s\n\n", prev) + if note := strings.TrimSpace(in.Note); note != "" { + fmt.Fprintf(&b, "\n\n%s\n\n", note) + } + b.WriteString("\nRewrite the explanation of this concept.") + return b.String() + } + if strings.TrimSpace(in.Code) != "" { + b.WriteString("\nExplain how this code works and the technique behind it.") + } else { + b.WriteString("\nExplain this concept.") + } + return b.String() +} + +// Generate asks Claude. The slug in the result is cleaned but may already be +// taken; the caller picks the one to save under and passes it to Files. +func Generate(ctx context.Context, a explain.Asker, in Input) (Result, error) { + var r Result + err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r) + if err != nil { + return Result{}, err + } + r.Slug = Slug(r.Slug, r.Title) + return r, nil +} + +var nonSlug = regexp.MustCompile(`[^a-z0-9]+`) + +// Slug cleans name into the CLI's slug shape (handlers.validName), falling +// back to one made from title. +func Slug(name, title string) string { + for _, s := range []string{name, title} { + s = strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(s), "-"), "-") + if len(s) > 60 { + s = strings.TrimRight(s[:60], "-") + } + if s != "" { + return s + } + } + return "concept" +} + +// The files of concepts//. +const ( + MarkdownFile = "concept.md" + SnippetFile = "snippet.cpp" + RequestFile = "request.md" +) + +// Files lays a Result out as the concept's files, by name. +func Files(r Result, in Input, slug, model string, now time.Time) map[string]string { + return map[string]string{ + MarkdownFile: Render(r, model, now), + SnippetFile: Snippet(r.Snippet, slug), + RequestFile: Request(in.Topic, in.Code), + } +} + +// Render lays a Result out as concept.md. The first line is a comment the +// index reads the tags from; the page shows the title itself and folds +// each "## " section away, leaving the summary and byline above them. +func Render(r Result, model string, now time.Time) string { + var b strings.Builder + var tags []string + seen := map[string]bool{} + for _, t := range r.Tags { + if t = Slug(t, ""); t != "concept" && !seen[t] && len(tags) < 6 { + seen[t] = true + tags = append(tags, t) + } + } + fmt.Fprintf(&b, "\n", strings.Join(tags, ",")) + fmt.Fprintf(&b, "# %s\n", oneLine(r.Title)) + if sum := oneLine(r.Summary); sum != "" { + fmt.Fprintf(&b, "\n_%s_\n", sum) + } + fmt.Fprintf(&b, "\n_Explained by %s on %s._\n", model, now.Format("2 January 2006")) + section := func(title, body string) { + if body = strings.TrimSpace(body); body != "" { + fmt.Fprintf(&b, "\n## %s\n\n%s\n", title, body) + } + } + section("Intuition", r.Intuition) + section("How it works", r.HowItWorks) + var walk strings.Builder + for i, s := range r.Walkthrough { + if i > 0 { + walk.WriteString("\n\n") + } + fmt.Fprintf(&walk, "**Step %d.** %s", i+1, strings.TrimSpace(s.Caption)) + // A fence inside the SVG would end the block early; an SVG never + // needs one. + if svg := strings.TrimSpace(strings.ReplaceAll(s.SVG, "```", "")); svg != "" { + fmt.Fprintf(&walk, "\n\n```svg\n%s\n```", svg) + } + } + section("Walkthrough", walk.String()) + if u := unfence(r.Usage); u != "" { + section("Using it", "```cpp\n"+u+"\n```") + } + section("Complexity", r.Complexity) + section("When to reach for it", r.WhenToUse) + section("Pitfalls", bullets(r.Pitfalls)) + section("Variations", r.Variations) + return b.String() +} + +// Marker is snippet.cpp's first line. `usaco snippet` looks for it to +// refuse pasting the same concept into a solution twice. +func Marker(slug string) string { return "// concept: " + slug } + +// Snippet is snippet.cpp: the marker, then the code. +func Snippet(code, slug string) string { + return Marker(slug) + "\n" + unfence(code) + "\n" +} + +// unfence drops a ``` fence Claude put around code despite the schema, so +// the code can be fenced (or saved) once. +func unfence(code string) string { + code = strings.TrimSpace(code) + if rest, ok := strings.CutPrefix(code, "```"); ok { + if nl := strings.IndexByte(rest, '\n'); nl >= 0 { + code = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(rest[nl+1:]), "```")) + } + } + return strings.ReplaceAll(code, "```", "") +} + +// The request's code goes in a tilde fence, which code from a contest will +// not contain, where a backtick one could be closed by a raw string. +const requestFence = "~~~~" + +// Request is request.md: what was asked, kept so the concept can be rewritten +// from the same question. +func Request(topic, code string) string { + s := strings.TrimSpace(topic) + "\n" + if code = strings.TrimRight(code, " \t\r\n"); strings.TrimSpace(code) != "" { + s += "\n" + requestFence + "cpp\n" + code + "\n" + requestFence + "\n" + } + return s +} + +// ParseRequest reads request.md back. +func ParseRequest(s string) (topic, code string) { + s = strings.ReplaceAll(s, "\r\n", "\n") + i := strings.Index(s, "\n"+requestFence) + if i < 0 { + return strings.TrimSpace(s), "" + } + topic, rest := strings.TrimSpace(s[:i]), s[i+1+len(requestFence):] + if nl := strings.IndexByte(rest, '\n'); nl >= 0 { + rest = rest[nl+1:] + } else { + rest = "" + } + if j := strings.LastIndex(rest, requestFence); j >= 0 { + rest = rest[:j] + } + return topic, strings.TrimRight(rest, "\n") +} + +func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") } + +func bullets(items []string) string { + var b strings.Builder + for _, it := range items { + if it = strings.TrimSpace(it); it != "" { + b.WriteString("- " + strings.ReplaceAll(it, "\n", "\n ") + "\n") + } + } + return b.String() +} diff --git a/site/internal/concept/concept_test.go b/site/internal/concept/concept_test.go new file mode 100644 index 0000000..3d79d9b --- /dev/null +++ b/site/internal/concept/concept_test.go @@ -0,0 +1,151 @@ +package concept + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/explain" +) + +func TestRender(t *testing.T) { + r := Result{ + Title: "Fenwick tree\n(BIT)", + Summary: "Prefix sums with point updates, both $O(\\log n)$.", + Tags: []string{"Range Query", "prefix-sums", "range-query", ""}, + Intuition: "Prefix sums break on updates.", + HowItWorks: "`t[i]` covers `(i - lowbit(i), i]`.", + Walkthrough: []explain.Step{ + {Caption: "Build.", SVG: ``}, + {Caption: "Query.", SVG: "```"}, + }, + Complexity: "$O(\\log n)$ each.", + Pitfalls: []string{"It is 1-based.", ""}, + Usage: "```cpp\nBIT b(n);\nb.add(3, 5);\n```", + } + got := Render(r, "claude-opus-5-5", time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC)) + want := "\n" + + "# Fenwick tree (BIT)\n" + + "\n_Prefix sums with point updates, both $O(\\log n)$._\n" + + "\n_Explained by claude-opus-5-5 on 20 October 2026._\n" + + "\n## Intuition\n\nPrefix sums break on updates.\n" + + "\n## How it works\n\n`t[i]` covers `(i - lowbit(i), i]`.\n" + + "\n## Walkthrough\n\n**Step 1.** Build.\n\n```svg\n\n```\n\n" + + "**Step 2.** Query.\n\n```svg\n\n```\n" + + "\n## Using it\n\n```cpp\nBIT b(n);\nb.add(3, 5);\n```\n" + + "\n## Complexity\n\n$O(\\log n)$ each.\n" + + "\n## Pitfalls\n\n- It is 1-based.\n" + if got != want { + t.Errorf("Render =\n%s\nwant\n%s", got, want) + } +} + +func TestSnippet(t *testing.T) { + for _, code := range []string{"struct BIT {};", "```cpp\nstruct BIT {};\n```\n", " struct BIT {};\n\n"} { + if got := Snippet(code, "fenwick-tree"); got != "// concept: fenwick-tree\nstruct BIT {};\n" { + t.Errorf("Snippet(%q) = %q", code, got) + } + } +} + +func TestSlug(t *testing.T) { + for _, c := range []struct{ name, title, want string }{ + {"fenwick-tree", "", "fenwick-tree"}, + {"Fenwick Tree!", "", "fenwick-tree"}, + {"../etc", "", "etc"}, + {"", "Sparse table (RMQ)", "sparse-table-rmq"}, + {"---", "!!", "concept"}, + {strings.Repeat("ab-", 30), "", "ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab"}, + } { + if got := Slug(c.name, c.title); got != c.want { + t.Errorf("Slug(%q, %q) = %q, want %q", c.name, c.title, got, c.want) + } + } +} + +func TestRequestRoundTrip(t *testing.T) { + for _, c := range []struct{ topic, code string }{ + {"help explain fenwick trees", ""}, + {"how does this work?", "bool canSort(vector& nums, int k) {\n return true;\n}"}, + {"raw strings", "auto s = R\"(```)\";"}, + } { + topic, code := ParseRequest(Request(c.topic, c.code)) + if topic != c.topic || code != c.code { + t.Errorf("round trip of %q / %q = %q / %q", c.topic, c.code, topic, code) + } + } +} + +func TestPrompt(t *testing.T) { + p := Prompt(Input{ + Topic: " how does this work? ", + Code: "int f() { return 1; }\n\n", + Existing: []Ref{{"fenwick-tree", "Fenwick tree"}}, + }) + for _, want := range []string{ + "\nhow does this work?\n", + "\nint f() { return 1; }\n", + "\n- fenwick-tree: Fenwick tree\n", + "Explain how this code works", + } { + if !strings.Contains(p, want) { + t.Errorf("prompt is missing %q:\n%s", want, p) + } + } + q := Prompt(Input{Topic: "fenwick trees"}) + if strings.Contains(q, "") || strings.Contains(q, "saved_concepts") || !strings.HasSuffix(q, "Explain this concept.") { + t.Errorf("a bare topic should leave the other blocks out:\n%s", q) + } + rw := Prompt(Input{Topic: "fenwick trees", Previous: "# Fenwick tree\n...", Note: "step 2 is wrong"}) + for _, want := range []string{"\n# Fenwick tree", "\nstep 2 is wrong\n", "Rewrite the explanation"} { + if !strings.Contains(rw, want) { + t.Errorf("rewrite prompt is missing %q:\n%s", want, rw) + } + } +} + +// The schema must describe exactly Result, or the reply would not decode. +func TestSchemaMatchesResult(t *testing.T) { + props := Schema["properties"].(map[string]any) + b, _ := json.Marshal(Result{Tags: []string{}, Walkthrough: []explain.Step{{}}, Pitfalls: []string{}}) + var fields map[string]any + json.Unmarshal(b, &fields) + for f := range fields { + if _, ok := props[f]; !ok { + t.Errorf("Result field %q is not in the schema", f) + } + } + if len(props) != len(fields) || len(Schema["required"].([]string)) != len(fields) { + t.Errorf("schema has %d properties (%d required), Result has %d fields", len(props), len(Schema["required"].([]string)), len(fields)) + } +} + +type fakeAsker struct{ req claude.Request } + +func (f *fakeAsker) Model() string { return "fake" } +func (f *fakeAsker) JSON(_ context.Context, req claude.Request, out any) error { + f.req = req + *out.(*Result) = Result{Slug: "Fenwick Tree", Title: "Fenwick tree"} + return nil +} + +func TestGenerate(t *testing.T) { + a := &fakeAsker{} + r, err := Generate(context.Background(), a, Input{Topic: "fenwick trees"}) + if err != nil { + t.Fatal(err) + } + if r.Slug != "fenwick-tree" { + t.Errorf("slug = %q, want it cleaned", r.Slug) + } + if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil { + t.Errorf("request not filled in: %+v", a.req) + } + // The page relies on the same math and diagram rules as explanations. + if !strings.Contains(System, explain.MathRules) || !strings.Contains(System, explain.DiagramRules) { + t.Error("System is missing explain's shared rules") + } +} diff --git a/site/internal/explain/explain.go b/site/internal/explain/explain.go index cfe3df0..dc9dd00 100644 --- a/site/internal/explain/explain.go +++ b/site/internal/explain/explain.go @@ -95,6 +95,18 @@ var Schema = map[string]any{ // reply, which is a few thousand tokens of prose plus the SVGs. const maxTokens = 32000 +// MathRules tell Claude how to write math for the page's KaTeX. Concepts +// (internal/concept) share them, so both pages typeset the same way. +const MathRules = `- Write math as LaTeX, which the page typesets with KaTeX: $...$ inline, and $$...$$ on lines of its own for a formula worth displaying, such as a recurrence or an identity the approach rests on. That covers formulas, bounds, complexities and indexed sums (write $O(n \log n)$ and $\sum_{i=L}^{R} d_i$, not O(n log n) or Σ_{i=L..R} d[i]). Keep inline code for code: variable names, array accesses and expressions as they would appear in a program.` + +// DiagramRules are what Explanation.vue needs of an SVG to show it in both +// themes and get it past DOMPurify. They follow a bullet that says what the +// diagrams should show, which differs between problems and concepts. +const DiagramRules = `- One self-contained element with xmlns="http://www.w3.org/2000/svg", a viewBox at most 640 wide and 400 tall, and no width or height attributes, so it scales to the page. +- The page has light and dark themes. Draw lines and text with currentColor; fill shapes with none or with these accents only: #3b82f6 (current or active), #22c55e (done or chosen), #f59e0b (being compared or considered), #ef4444 (rejected or invalid). Put text over an accent fill only if it stays readable there. +- Text at least 13px, in font-family="ui-monospace, monospace" for values and sans-serif for labels. Keep labels short; the caption carries the explanation. +- No scripts, event handlers, , external links, images or CSS @import. Use only basic shapes, paths, lines, text, groups and markers.` + // System is the same on every call, so it is cached. const System = `You are a patient competitive-programming coach. Someone is stuck on a problem and wants to understand how to solve it, not just to be handed a solution. Your answer will be shown as a ladder they climb only as far as they need: the key observation, hints of increasing strength, then the full approach, a diagrammed walkthrough, complexity, pitfalls, and a pseudocode sketch. @@ -105,14 +117,11 @@ How to explain: - If they describe what they are stuck on, or include their attempt, address that directly: say what in their attempt is on the right track and where it goes wrong. Do not rewrite their code. - Never give a complete solution in any real programming language. The sketch is short pseudocode for the core idea only. - Write in plain, direct prose. Use markdown for emphasis, lists and inline code. -- Write math as LaTeX, which the page typesets with KaTeX: $...$ inline, and $$...$$ on lines of its own for a formula worth displaying, such as a recurrence or an identity the approach rests on. That covers formulas, bounds, complexities and indexed sums (write $O(n \log n)$ and $\sum_{i=L}^{R} d_i$, not O(n log n) or Σ_{i=L..R} d[i]). Keep inline code for code: variable names, array accesses and expressions as they would appear in a program. +` + MathRules + ` Diagram rules for each walkthrough step's svg: - Show the actual mechanism on a small concrete example (the sample if it is small enough): array cells with index labels and pointer arrows, grid cells with their values and the current frontier, a DP table filling in, a graph with visited nodes and the edge being relaxed, a stack or heap's contents. Successive steps should show the state changing. -- One self-contained element with xmlns="http://www.w3.org/2000/svg", a viewBox at most 640 wide and 400 tall, and no width or height attributes, so it scales to the page. -- The page has light and dark themes. Draw lines and text with currentColor; fill shapes with none or with these accents only: #3b82f6 (current or active), #22c55e (done or chosen), #f59e0b (being compared or considered), #ef4444 (rejected or invalid). Put text over an accent fill only if it stays readable there. -- Text at least 13px, in font-family="ui-monospace, monospace" for values and sans-serif for labels. Keep labels short; the caption carries the explanation. -- No scripts, event handlers, , external links, images or CSS @import. Use only basic shapes, paths, lines, text, groups and markers.` +` + DiagramRules // Prompt is the user message: the problem and what the admin has given. func Prompt(in Input) string { diff --git a/site/internal/explain/explain_test.go b/site/internal/explain/explain_test.go index 445a0d1..5f1ba15 100644 --- a/site/internal/explain/explain_test.go +++ b/site/internal/explain/explain_test.go @@ -101,6 +101,9 @@ func TestGenerate(t *testing.T) { if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil { t.Errorf("request not filled in: %+v", a.req) } + if !strings.Contains(System, MathRules) || !strings.Contains(System, DiagramRules) { + t.Error("System is missing the rules it shares with concepts") + } } func TestJobsOneAtATime(t *testing.T) { diff --git a/site/internal/handlers/concept.go b/site/internal/handlers/concept.go new file mode 100644 index 0000000..0357f21 --- /dev/null +++ b/site/internal/handlers/concept.go @@ -0,0 +1,269 @@ +package handlers + +import ( + "context" + "errors" + "fmt" + "log" + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/concept" + "adam-french.co.uk/usaco-site/internal/index" +) + +// listConcepts is the library, newest first. It leaves out the content and +// snippets, which only a concept's own page needs. +func (s *Server) listConcepts(ctx *gin.Context) { + idx := s.Index() + if idx == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"}) + return + } + out := []index.Concept{} + for _, c := range idx.Concepts { + sum := *c + sum.Content, sum.Snippet = "", nil + out = append(out, sum) + } + sort.Slice(out, func(i, j int) bool { + a, b := out[i].Updated, out[j].Updated + if (a == nil) != (b == nil) { + return a == nil // uncommitted ones are the newest + } + if a != nil && !a.Equal(*b) { + return a.After(*b) + } + return out[i].Slug < out[j].Slug + }) + ctx.JSON(http.StatusOK, gin.H{"admin": s.isAdmin(ctx), "concepts": out}) +} + +func (s *Server) lookupConcept(ctx *gin.Context) (*index.Concept, bool) { + slug := ctx.Param("slug") + idx := s.Index() + if idx == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"}) + return nil, false + } + c, ok := idx.Concepts[slug] + if !validName.MatchString(slug) || !ok { + ctx.JSON(http.StatusNotFound, gin.H{"error": "no such concept"}) + return nil, false + } + return c, true +} + +func (s *Server) getConcept(ctx *gin.Context) { + if c, ok := s.lookupConcept(ctx); ok { + ctx.JSON(http.StatusOK, c) + } +} + +type conceptBody struct { + Topic string `json:"topic"` + Code string `json:"code"` +} + +const maxConceptCode = 32 << 10 + +// startConcept starts explaining a new concept. Its slug is Claude's to +// choose, so the job is keyed by an id of its own, which the page polls +// until the result names the slug to open. +func (s *Server) startConcept(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 + } + idx := s.Index() + if idx == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"}) + return + } + var body conceptBody + if err := ctx.ShouldBindJSON(&body); err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"}) + return + } + switch { + case strings.TrimSpace(body.Topic) == "" && strings.TrimSpace(body.Code) == "": + ctx.JSON(http.StatusBadRequest, gin.H{"error": "say what to explain"}) + return + case len(body.Topic) > maxNote: + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the topic is too long"}) + return + case len(body.Code) > maxConceptCode: + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the code is too long"}) + return + } + topic := strings.TrimSpace(body.Topic) + if topic == "" { + topic = "How does this code work?" + } + in := concept.Input{Topic: topic, Code: body.Code, Existing: conceptRefs(idx, "")} + // Microseconds, so two requests in one second are two jobs. + id := time.Now().UTC().Format("2006-01-02-150405.000000") + if !s.newConceptJobs.StartWith(id, func() (any, error) { return s.writeConcept(in, "") }) { + ctx.JSON(http.StatusConflict, gin.H{"error": "that concept is already being explained"}) + return + } + ctx.JSON(http.StatusAccepted, gin.H{"id": id, "status": s.newConceptJobs.Get(id)}) +} + +func (s *Server) newConceptStatus(ctx *gin.Context) { + ctx.JSON(http.StatusOK, s.newConceptJobs.Get(ctx.Param("id"))) +} + +type rewriteBody struct { + Note string `json:"note"` +} + +// rewriteConcept explains a saved concept again, from the question it was +// asked with, the current version and what the admin wants changed. +func (s *Server) rewriteConcept(ctx *gin.Context) { + c, ok := s.lookupConcept(ctx) + if !ok { + return + } + if s.Claude == nil { + ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) + return + } + var body rewriteBody + if err := ctx.ShouldBindJSON(&body); err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"}) + return + } + if len(body.Note) > maxNote { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"}) + return + } + topic, code := concept.ParseRequest(c.Request) + if topic == "" { + topic = c.Title + } + prev := "# " + c.Title + "\n\n" + c.Content + if c.Snippet != nil { + prev += "\n\n## Snippet\n\n```cpp\n" + c.Snippet.Content + "\n```" + } + in := concept.Input{Topic: topic, Code: code, Previous: prev, Note: body.Note, Existing: conceptRefs(s.Index(), c.Slug)} + slug := c.Slug + if !s.conceptJobs.StartWith(slug, func() (any, error) { return s.writeConcept(in, slug) }) { + ctx.JSON(http.StatusConflict, gin.H{"error": "this concept is already being rewritten"}) + return + } + ctx.JSON(http.StatusAccepted, s.conceptJobs.Get(slug)) +} + +func (s *Server) rewriteStatus(ctx *gin.Context) { + if c, ok := s.lookupConcept(ctx); ok { + ctx.JSON(http.StatusOK, s.conceptJobs.Get(c.Slug)) + } +} + +// conceptRefs are the saved concepts but skip, for Claude to name a new one +// apart from. +func conceptRefs(idx *index.Index, skip string) []concept.Ref { + var refs []concept.Ref + for _, c := range idx.Concepts { + if c.Slug != skip { + refs = append(refs, concept.Ref{Slug: c.Slug, Title: c.Title}) + } + } + sort.Slice(refs, func(i, j int) bool { return refs[i].Slug < refs[j].Slug }) + return refs +} + +// conceptResult is a finished job's answer: where the concept is now. +type conceptResult struct { + Slug string `json:"slug"` +} + +// writeConcept is one job: a new concept when slug is empty, else a rewrite +// of that one. Its error is shown to the admin, so every path returns a +// message meant for them and logs the detail. +func (s *Server) writeConcept(in concept.Input, slug string) (any, error) { + ctx, cancel := context.WithTimeout(context.Background(), explainTimeout) + defer cancel() + + r, err := concept.Generate(ctx, s.Claude, in) + if err != nil { + var f *claude.Failure + if errors.As(err, &f) { + log.Printf("[concept] %s: %s: %v", in.Topic, f.Msg, f.Err) + return nil, f + } + log.Printf("[concept] %s: %v", in.Topic, err) + return nil, errors.New("the explanation could not be written") + } + + rewrite := slug != "" + if !rewrite { + slug = freeSlug(s.Index(), r.Slug) + } + files := concept.Files(r, in, slug, s.Claude.Model(), time.Now()) + err = s.Repo.Mutate(ctx, "Explain concept "+slug, func(dir string) error { + cdir := filepath.Join(dir, index.Concepts, slug) + _, err := os.Stat(cdir) + switch { + case rewrite && os.IsNotExist(err): + return &requestError{http.StatusNotFound, "the concept was deleted while Claude was writing"} + case !rewrite && err == nil: + // Saved since the slug was picked; the next try picks another. + return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; try again", slug)} + } + if err := os.MkdirAll(cdir, 0o755); err != nil { + return err + } + for name, content := range files { + if err := writeOrRemove(filepath.Join(cdir, name), content); err != nil { + return err + } + } + return nil + }) + if err := jobSaveError("concept", slug, "the explanation was written but could not be saved to git", err); err != nil { + return nil, err + } + return conceptResult{Slug: slug}, nil +} + +// freeSlug is want, or want-2, want-3... if a concept already has it. A +// new question never overwrites a saved concept; rewriting one is its own +// request. +func freeSlug(idx *index.Index, want string) string { + slug := want + for n := 2; ; n++ { + if _, taken := idx.Concepts[slug]; !taken { + return slug + } + slug = fmt.Sprintf("%s-%d", want, n) + } +} + +func (s *Server) deleteConcept(ctx *gin.Context) { + c, ok := s.lookupConcept(ctx) + if !ok { + return + } + slug := c.Slug + cctx, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second) + defer cancel() + msg := "Forget concept " + slug + err := s.Repo.Mutate(cctx, msg, func(dir string) error { + // Already gone on a newer tip is what was asked for. + return os.RemoveAll(filepath.Join(dir, index.Concepts, slug)) + }) + if err != nil { + editFailed(ctx, msg, err) + return + } + ctx.JSON(http.StatusOK, gin.H{}) +} diff --git a/site/internal/handlers/concept_test.go b/site/internal/handlers/concept_test.go new file mode 100644 index 0000000..399c23f --- /dev/null +++ b/site/internal/handlers/concept_test.go @@ -0,0 +1,189 @@ +package handlers + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "adam-french.co.uk/usaco-site/internal/claude" + "adam-french.co.uk/usaco-site/internal/concept" + "adam-french.co.uk/usaco-site/internal/explain" +) + +// fakeConceptClaude explains everything as a Fenwick tree. If gate is set, +// it waits for it to close first, so a test can catch a job mid-run. +type fakeConceptClaude struct { + gate chan struct{} + user string +} + +func (f *fakeConceptClaude) Model() string { return "fake-model" } +func (f *fakeConceptClaude) JSON(_ context.Context, req claude.Request, out any) error { + if f.gate != nil { + <-f.gate + } + f.user = req.User + *out.(*concept.Result) = concept.Result{ + Slug: "fenwick-tree", Title: "Fenwick tree", Summary: "Prefix sums with updates.", + Tags: []string{"range-query"}, Intuition: "Lowbits.", Snippet: "struct BIT {};", + } + return nil +} + +func waitStatus(t *testing.T, r *gin.Engine, path string) explain.Status { + t.Helper() + for range 400 { + rec := do(r, "GET", path, "", true) + var s explain.Status + json.Unmarshal(rec.Body.Bytes(), &s) + if s.State != explain.Running { + return s + } + time.Sleep(5 * time.Millisecond) + } + t.Fatalf("%s still running", path) + return explain.Status{} +} + +// newConcept starts a concept and returns the slug its job saved it under. +func newConcept(t *testing.T, r *gin.Engine, body string) string { + t.Helper() + rec := do(r, "POST", "/usaco/api/concepts", body, true) + if rec.Code != 202 { + t.Fatalf("start = %d: %s", rec.Code, rec.Body) + } + var started struct{ ID string } + json.Unmarshal(rec.Body.Bytes(), &started) + s := waitStatus(t, r, "/usaco/api/concept-jobs/"+started.ID) + if s.State != explain.Done { + t.Fatalf("job = %+v, want done", s) + } + res, _ := s.Result.(map[string]any) + slug, _ := res["slug"].(string) + return slug +} + +func TestConceptGuards(t *testing.T) { + r, repo, _ := setup(t) + if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"fenwick"}`, true); rec.Code != 503 { + t.Fatalf("without Claude = %d, want 503", rec.Code) + } + repo.srv.Claude = &fakeConceptClaude{} + if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"fenwick"}`, false); rec.Code != 401 { + t.Fatalf("public start = %d, want 401", rec.Code) + } + if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":" "}`, true); rec.Code != 400 { + t.Fatalf("empty topic = %d, want 400", rec.Code) + } + if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"`+strings.Repeat("a", maxNote+1)+`"}`, true); rec.Code != 400 { + t.Fatalf("long topic = %d, want 400", rec.Code) + } + for _, path := range []string{"/usaco/api/concepts/nope", "/usaco/api/concepts/..", "/usaco/api/concepts/A"} { + if rec := do(r, "GET", path, "", false); rec.Code != 404 { + t.Errorf("GET %s = %d, want 404", path, rec.Code) + } + } +} + +func TestConceptWritesAndCommits(t *testing.T) { + r, repo, _ := setup(t) + fc := &fakeConceptClaude{} + repo.srv.Claude = fc + + code := "bool canSort(vector& nums, int k) {\n return true;\n}" + body, _ := json.Marshal(conceptBody{Topic: "help explain fenwick trees", Code: code}) + if slug := newConcept(t, r, string(body)); slug != "fenwick-tree" { + t.Fatalf("slug = %q", slug) + } + if !strings.Contains(fc.user, "\nhelp explain fenwick trees\n") || !strings.Contains(fc.user, "canSort") { + t.Errorf("prompt is missing the topic or code:\n%s", fc.user) + } + cdir := filepath.Join(repo.dir, "concepts", "fenwick-tree") + snip, _ := os.ReadFile(filepath.Join(cdir, "snippet.cpp")) + if string(snip) != "// concept: fenwick-tree\nstruct BIT {};\n" { + t.Errorf("snippet.cpp = %q", snip) + } + req, _ := os.ReadFile(filepath.Join(cdir, "request.md")) + if topic, got := concept.ParseRequest(string(req)); topic != "help explain fenwick trees" || got != code { + t.Errorf("request.md = %q", req) + } + if got := repo.msg[len(repo.msg)-1]; got != "Explain concept fenwick-tree" { + t.Errorf("commit = %q", got) + } + + // The public sees the library and the page. + rec := do(r, "GET", "/usaco/api/concepts", "", false) + var list struct { + Concepts []map[string]any `json:"concepts"` + } + json.Unmarshal(rec.Body.Bytes(), &list) + if len(list.Concepts) != 1 || list.Concepts[0]["title"] != "Fenwick tree" || list.Concepts[0]["content"] != nil { + t.Fatalf("list = %s", rec.Body) + } + rec = do(r, "GET", "/usaco/api/concepts/fenwick-tree", "", false) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "## Intuition") || !strings.Contains(rec.Body.String(), "struct BIT") { + t.Fatalf("page = %d: %s", rec.Code, rec.Body) + } + + // The same answer to a new question never overwrites the saved one. + if slug := newConcept(t, r, `{"topic":"fenwick again"}`); slug != "fenwick-tree-2" { + t.Fatalf("second slug = %q, want fenwick-tree-2", slug) + } + if !strings.Contains(fc.user, "- fenwick-tree: Fenwick tree") { + t.Errorf("prompt does not list the saved concept:\n%s", fc.user) + } + if req, _ := os.ReadFile(filepath.Join(cdir, "request.md")); !strings.Contains(string(req), "canSort") { + t.Error("the first concept was overwritten") + } + + // Public visitors cannot delete; the admin can. + if rec := do(r, "DELETE", "/usaco/api/concepts/fenwick-tree-2", "", false); rec.Code != 401 { + t.Fatalf("public delete = %d, want 401", rec.Code) + } + if rec := do(r, "DELETE", "/usaco/api/concepts/fenwick-tree-2", "", true); rec.Code != 200 { + t.Fatalf("delete = %d: %s", rec.Code, rec.Body) + } + if _, err := os.Stat(filepath.Join(repo.dir, "concepts", "fenwick-tree-2")); !os.IsNotExist(err) { + t.Error("the concept's directory is still there") + } + if got := repo.msg[len(repo.msg)-1]; got != "Forget concept fenwick-tree-2" { + t.Errorf("commit = %q", got) + } +} + +func TestConceptRewrite(t *testing.T) { + r, repo, _ := setup(t) + repo.srv.Claude = &fakeConceptClaude{} + newConcept(t, r, `{"topic":"help explain fenwick trees"}`) + + fc := &fakeConceptClaude{gate: make(chan struct{})} + repo.srv.Claude = fc + path := "/usaco/api/concepts/fenwick-tree/explain" + if rec := do(r, "POST", path, `{"note":"step 2 is wrong"}`, true); rec.Code != 202 { + t.Fatalf("rewrite = %d: %s", rec.Code, rec.Body) + } + if rec := do(r, "POST", path, `{}`, true); rec.Code != 409 { + t.Fatalf("second rewrite while running = %d, want 409", rec.Code) + } + close(fc.gate) + if s := waitStatus(t, r, path); s.State != explain.Done { + t.Fatalf("rewrite job = %+v", s) + } + for _, want := range []string{"\nhelp explain fenwick trees", "\n# Fenwick tree", "## Snippet", "\nstep 2 is wrong"} { + if !strings.Contains(fc.user, want) { + t.Errorf("rewrite prompt is missing %q:\n%s", want, fc.user) + } + } + if strings.Contains(fc.user, "") { + t.Error("a rewrite should not list the concept as taken") + } + if _, err := os.Stat(filepath.Join(repo.dir, "concepts", "fenwick-tree-2")); !os.IsNotExist(err) { + t.Error("a rewrite saved a new concept instead of replacing its own") + } +} diff --git a/site/internal/handlers/handlers.go b/site/internal/handlers/handlers.go index d4058be..26cc89a 100644 --- a/site/internal/handlers/handlers.go +++ b/site/internal/handlers/handlers.go @@ -2,7 +2,8 @@ // 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 evaluations -// (evaluate.go), and the Gitea webhook that tells the server to pull. +// (evaluate.go), the library of concepts Claude explained (concept.go), and +// the Gitea webhook that tells the server to pull. package handlers import ( @@ -70,6 +71,9 @@ type Server struct { // Separate, so a review, an explanation and an evaluation of one // problem can run at the same time. jobs, reviewJobs, evalJobs explain.Jobs + // New concepts are keyed by a job id (the slug is Claude's to pick), + // rewrites by slug. + newConceptJobs, conceptJobs explain.Jobs } // SetIndex swaps in a freshly built index. repo.Repo calls it (through @@ -114,6 +118,14 @@ func (s *Server) Routes(api *gin.RouterGroup) { admin.POST("/problems/:name/evaluate", s.startEvaluate) admin.GET("/problems/:name/evaluate", s.evaluateStatus) admin.POST("/leetcode/daily", s.startDaily) + api.GET("/concepts", s.listConcepts) + api.GET("/concepts/:slug", s.getConcept) + admin.POST("/concepts", s.startConcept) + // Not under /concepts/, where "jobs" would be a slug. + admin.GET("/concept-jobs/:id", s.newConceptStatus) + admin.POST("/concepts/:slug/explain", s.rewriteConcept) + admin.GET("/concepts/:slug/explain", s.rewriteStatus) + admin.DELETE("/concepts/:slug", s.deleteConcept) api.POST("/hooks/gitea", s.webhook) } diff --git a/site/internal/index/index.go b/site/internal/index/index.go index 1cbfd0f..df937f1 100644 --- a/site/internal/index/index.go +++ b/site/internal/index/index.go @@ -6,7 +6,9 @@ // the CLI wires up, tests/N.in + N.out, and optionally a .url, notes.md, // problem.md (the statement, pasted or fetched from the judge by the site), // explain.md (an explanation the site had Claude write) and reviews/.md -// (feedback on a recording of the admin explaining it). The repo is +// (feedback on a recording of the admin explaining it). Beside them, +// concepts// holds a technique the site had Claude explain +// (internal/concept): concept.md, snippet.cpp and request.md. The repo is // small, so everything, file contents included, is read on each rebuild, // and a rebuild only happens when the clone changes. package index @@ -36,6 +38,9 @@ const ( var Statuses = []string{Solving, Solved, Skipped} +// Concepts is the directory of saved concepts, which are not problems. +const Concepts = "concepts" + // MaxFileSize caps what is held for one file. Test inputs can be large and // nobody reads a megabyte in a browser; the rest is cut and marked. const MaxFileSize = 64 << 10 @@ -110,16 +115,33 @@ type Review struct { Content string `json:"content"` } +// Concept is one concepts//. Unlike a problem, it is public whatever +// its state: nothing in it is the judge's or the admin's own words. +type Concept struct { + Slug string `json:"slug"` + Title string `json:"title"` + Summary string `json:"summary,omitempty"` + Tags []string `json:"tags"` + // Content is concept.md without its header comment and title, which the + // page shows itself. + Content string `json:"content,omitempty"` + Snippet *File `json:"snippet,omitempty"` + // Request is request.md, what was asked, for rewriting the concept. + Request string `json:"-"` + Updated *time.Time `json:"updated,omitempty"` +} + // Index is one snapshot of the clone. type Index struct { Head string Built time.Time Problems map[string]*Problem + Concepts map[string]*Concept } // Build reads dir, a git work tree. func Build(dir string) (*Index, error) { - idx := &Index{Built: time.Now(), Problems: map[string]*Problem{}} + idx := &Index{Built: time.Now(), Problems: map[string]*Problem{}, Concepts: map[string]*Concept{}} for _, status := range Statuses { entries, err := os.ReadDir(filepath.Join(dir, status)) if os.IsNotExist(err) { @@ -145,6 +167,9 @@ func Build(dir string) (*Index, error) { idx.Problems[p.Name] = p } } + if err := readConcepts(filepath.Join(dir, Concepts), idx); err != nil { + return nil, err + } head, err := gitOut(dir, "rev-parse", "HEAD") if err != nil { return nil, err @@ -306,6 +331,82 @@ func readReviews(rdir string) ([]Review, error) { return out, nil } +func readConcepts(cdir string, idx *Index) error { + entries, err := os.ReadDir(cdir) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + for _, e := range entries { + if !e.IsDir() || strings.HasPrefix(e.Name(), ".") { + continue + } + c, err := readConcept(filepath.Join(cdir, e.Name())) + if err != nil { + return fmt.Errorf("%s/%s: %w", Concepts, e.Name(), err) + } + if c != nil { + idx.Concepts[c.Slug] = c + } + } + return nil +} + +// conceptHead is the comment internal/concept writes as concept.md's first +// line. +var conceptHead = regexp.MustCompile(`^\r?\n`) + +// readConcept returns nil for a directory with neither an explanation nor a +// snippet: there is nothing to show. +func readConcept(cdir string) (*Concept, error) { + c := &Concept{Slug: filepath.Base(cdir), Title: filepath.Base(cdir), Tags: []string{}} + md, mdErr := os.ReadFile(filepath.Join(cdir, "concept.md")) + if mdErr != nil && !os.IsNotExist(mdErr) { + return nil, mdErr + } + if snip, err := readFile(filepath.Join(cdir, "snippet.cpp"), "cpp"); err == nil { + c.Snippet = &snip + } else if !os.IsNotExist(err) { + return nil, err + } + if mdErr != nil && c.Snippet == nil { + return nil, nil + } + if b, err := os.ReadFile(filepath.Join(cdir, "request.md")); err == nil { + c.Request = string(b) + } + + content := string(md) + if m := conceptHead.FindStringSubmatch(content); m != nil { + for _, t := range strings.Split(m[1], ",") { + if t != "" { + c.Tags = append(c.Tags, t) + } + } + content = content[len(m[0]):] + } + // The title is the first line if it is a heading, and the summary the + // first italic line under it that is not the byline. + if first, rest, _ := strings.Cut(content, "\n"); strings.HasPrefix(first, "# ") { + c.Title = strings.TrimSpace(first[2:]) + content = rest + } + for _, line := range strings.Split(content, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "## ") { + break + } + if len(line) > 2 && line[0] == '_' && line[len(line)-1] == '_' && !strings.HasPrefix(line, "_Explained by ") { + c.Summary = line[1 : len(line)-1] + break + } + } + c.Content = strings.TrimLeft(content, "\r\n") + return c, nil +} + func readFile(path, lang string) (File, error) { f, err := os.Open(path) if err != nil { @@ -378,6 +479,7 @@ func addHistory(dir string, idx *Index) error { solvedFiles := map[string]map[string]bool{} // name -> paths under solved// var c Commit touched := map[string]bool{} + touchedConcepts := map[string]bool{} becameSolved := map[string]bool{} flush := func() { @@ -393,6 +495,12 @@ func addHistory(dir string, idx *Index) error { p.LastTouched = &d p.History = append(p.History, c) } + for slug := range touchedConcepts { + if cn, ok := idx.Concepts[slug]; ok { + d := c.Date + cn.Updated = &d + } + } for name := range becameSolved { if p, ok := idx.Problems[name]; ok && len(solvedFiles[name]) > 0 { d := c.Date @@ -400,6 +508,7 @@ func addHistory(dir string, idx *Index) error { } } touched = map[string]bool{} + touchedConcepts = map[string]bool{} becameSolved = map[string]bool{} } @@ -433,6 +542,10 @@ func addHistory(dir string, idx *Index) error { } kind, path := fields[0], fields[len(fields)-1] segs := strings.SplitN(path, "/", 3) + if len(segs) == 3 && segs[0] == Concepts { + touchedConcepts[segs[1]] = true + continue + } if len(segs) < 3 || !isStatus(segs[0]) { continue } diff --git a/site/internal/index/index_test.go b/site/internal/index/index_test.go index 0da8ef1..fa99745 100644 --- a/site/internal/index/index_test.go +++ b/site/internal/index/index_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "testing" "time" ) @@ -76,6 +77,13 @@ func fixture(t *testing.T) string { write("solved/moocast/reviews/2026-09-04-100000.md", "\n_Reviewed by m._\n") write("solved/moocast/reviews/notes.md", "hand-written\n") commit(4, "Add a test") + + write("concepts/fenwick-tree/concept.md", "\n# Fenwick tree\n\n_Prefix sums with updates in O(log n)._\n\n_Explained by m on 5 September 2026._\n\n## Intuition\n\nLowbits.\n") + write("concepts/fenwick-tree/snippet.cpp", "// concept: fenwick-tree\nstruct BIT {};\n") + write("concepts/fenwick-tree/request.md", "help explain fenwick trees\n") + write("concepts/hand-made/snippet.cpp", "int f();\n") + write("concepts/empty/notes.txt", "nothing to show\n") + commit(5, "Explain concept fenwick-tree") return dir } @@ -139,6 +147,26 @@ func TestBuild(t *testing.T) { t.Fatalf("moocast history = %+v, want 3 commits newest first", m.History) } + if len(m.History) != 3 { + t.Fatalf("a concept's commit touched moocast: %+v", m.History) + } + if len(idx.Concepts) != 2 { + t.Fatalf("concepts = %v, want fenwick-tree and hand-made (empty has nothing to show)", idx.Concepts) + } + f := idx.Concepts["fenwick-tree"] + if f.Title != "Fenwick tree" || f.Summary != "Prefix sums with updates in O(log n)." || len(f.Tags) != 2 || f.Tags[1] != "prefix-sums" { + t.Fatalf("fenwick-tree = %+v", f) + } + if !strings.HasPrefix(f.Content, "_Prefix sums") || strings.Contains(f.Content, "# Fenwick") || strings.Contains(f.Content, "