Add an Explain button that has Claude explain a problem
Test and publish the site / publish (push) Successful in 8m15s
Test and publish the site / test (push) Successful in 5m51s

When stuck, the admin can ask Claude for an intuitive explanation of a
problem. It is committed as explain.md and shown as folded sections, so
the reader opens only as much as they need: the key observation, hints
that get stronger, the approach, a walkthrough with an SVG diagram per
step, complexity, pitfalls and a pseudocode sketch.

- internal/claude: streamed call with a JSON-schema reply, high effort,
  the server-side refusal fallback, fixed error messages and logged
  token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5);
  without a key only this feature is off.
- internal/explain: the prompt, the schema, rendering to markdown, and
  a per-problem job tracker. The request starts a job and the page polls,
  since a call outlasts nginx's 120s timeout.
- internal/statement: fetches statements from LeetCode's GraphQL API and
  USACO's problem pages. Others (Codeforces is behind Cloudflare) are
  pasted.
- problem.md holds the statement, editable from the meta editor and
  shown only to the admin. Diagrams are sanitized with DOMPurify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-19 20:38:15 +01:00
co-authored by Claude Opus 5.5
parent f0e10d2a58
commit 995b44a57a
27 changed files with 2144 additions and 67 deletions
+219
View File
@@ -0,0 +1,219 @@
package handlers
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/repo"
"adam-french.co.uk/usaco-site/internal/statement"
)
// Fetcher is the part of statement.Fetcher the handlers use, so tests can
// fake the judges.
type Fetcher interface {
Fetch(ctx context.Context, link string) (string, error)
}
func (s *Server) fetcher() Fetcher {
if s.Statements != nil {
return s.Statements
}
return &statement.Fetcher{}
}
// fetchStatement returns the statement behind ?url= (or the saved link) for
// the admin to review in the editor. It saves nothing.
func (s *Server) fetchStatement(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
link := strings.TrimSpace(ctx.Query("url"))
if link == "" {
link = p.URL
}
if u, err := url.Parse(link); link == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "give the problem an http(s) link first"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), 20*time.Second)
defer cancel()
md, err := s.fetcher().Fetch(c, link)
switch {
case errors.Is(err, statement.ErrUnsupported):
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
case err != nil:
log.Printf("[statement] %s: %v", link, err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
default:
ctx.JSON(http.StatusOK, gin.H{"statement": md})
}
}
type explainBody struct {
Note string `json:"note"`
IncludeCode bool `json:"includeCode"`
}
const maxNote = 4 << 10
// Claude can take a few minutes at high effort; this also bounds the
// commit that follows.
const explainTimeout = 10 * time.Minute
// startExplain starts writing explain.md and answers at once; the page polls
// explainStatus. Everything Claude sees is taken from the index now, so a
// sync during the call changes nothing but where the result is committed.
func (s *Server) startExplain(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
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 explainBody
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
}
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 := explain.Input{Name: p.Name, Statement: p.Statement, Note: body.Note, Examples: examples(p)}
if body.IncludeCode {
in.Code = mainFile(p)
}
link := p.URL
if !s.jobs.Start(p.Name, func() error { return s.explain(in, link) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "an explanation is already being written"})
return
}
ctx.JSON(http.StatusAccepted, s.jobs.Get(p.Name))
}
func (s *Server) explainStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.jobs.Get(p.Name))
}
}
// explain 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) explain(in explain.Input, link string) error {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
// No statement saved: fetch it, and save it alongside the explanation
// so the next one does not need the judge.
fetched := ""
if strings.TrimSpace(in.Statement) == "" {
md, err := s.fetcher().Fetch(ctx, link)
if err != nil {
log.Printf("[explain] %s: fetching %s: %v", in.Name, link, err)
return fmt.Errorf("could not fetch the statement (%v); paste it into the editor", err)
}
in.Statement, fetched = md, md
}
md, err := explain.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err)
return f
}
log.Printf("[explain] %s: %v", in.Name, err)
return errors.New("the explanation could not be written")
}
name := in.Name
err = s.Repo.Mutate(ctx, "Explain "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if fetched != "" {
// Only if it is still missing: the admin may have pasted one
// while Claude was working.
if _, err := os.Stat(filepath.Join(pdir, "problem.md")); os.IsNotExist(err) {
if err := writeOrRemove(filepath.Join(pdir, "problem.md"), fetched); err != nil {
return err
}
}
}
return writeOrRemove(filepath.Join(pdir, "explain.md"), md)
})
var re *requestError
switch {
case err == nil:
return nil
case errors.As(err, &re):
return errors.New(re.msg)
case errors.Is(err, repo.ErrRejected):
return errors.New("the repository changed while saving; try again")
default:
log.Printf("[explain] %s: saving: %v", name, err)
return errors.New("the explanation was written but could not be saved to git")
}
}
// mainFile is the CLI's solution (main.cpp, main.rs...), else the first
// solution file.
func mainFile(p *index.Problem) *index.File {
for i := range p.Files {
if strings.HasPrefix(p.Files[i].Name, "main.") {
return &p.Files[i]
}
}
if len(p.Files) > 0 {
return &p.Files[0]
}
return nil
}
// A case bigger than this is a stress test, not something to trace by hand,
// and a truncated one would mislead.
const maxExample = 2 << 10
// examples are the saved tests that have an expected output, then the
// sample input if no test has the same input. Three is plenty to trace.
func examples(p *index.Problem) []explain.Example {
var out []explain.Example
seen := map[string]bool{}
for _, t := range p.TestSet {
if len(out) == 3 {
return out
}
if t.Output == nil || t.Input.Truncated || len(t.Input.Content) > maxExample || len(t.Output.Content) > maxExample {
continue
}
out = append(out, explain.Example{In: t.Input.Content, Out: t.Output.Content})
seen[strings.TrimSpace(t.Input.Content)] = true
}
if sm := p.Sample; sm != nil && len(out) < 3 && len(sm.Content) <= maxExample && !seen[strings.TrimSpace(sm.Content)] {
out = append(out, explain.Example{In: sm.Content})
}
return out
}
+161
View File
@@ -0,0 +1,161 @@
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/explain"
"adam-french.co.uk/usaco-site/internal/statement"
)
// fakeClaude answers every request with one observation. If gate is set,
// it waits for it to close first, so a test can catch a job mid-run.
type fakeClaude struct {
gate chan struct{}
user string
}
func (f *fakeClaude) Model() string { return "fake-model" }
func (f *fakeClaude) JSON(_ context.Context, req claude.Request, out any) error {
if f.gate != nil {
<-f.gate
}
f.user = req.User
*out.(*explain.Result) = explain.Result{Observation: "Think in reverse."}
return nil
}
// fakeJudge knows one link.
type fakeJudge struct{}
func (fakeJudge) Fetch(_ context.Context, link string) (string, error) {
if link == "https://usaco.org/moocast" {
return "# Moocast\n\nCows with walkie-talkies.", nil
}
return "", statement.ErrUnsupported
}
func waitJob(t *testing.T, r *gin.Engine, name string) explain.Status {
t.Helper()
for range 400 {
rec := do(r, "GET", "/usaco/api/problems/"+name+"/explain", "", true)
var s explain.Status
json.Unmarshal(rec.Body.Bytes(), &s)
if s.State != explain.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job still running")
return explain.Status{}
}
func TestExplainNeedsClaudeAndAStatement(t *testing.T) {
r, repo, _ := setup(t)
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true); rec.Code != 503 {
t.Fatalf("no Claude = %d, want 503", rec.Code)
}
repo.srv.Claude = &fakeClaude{}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true); rec.Code != 400 {
t.Fatalf("no statement or link = %d, want 400: %s", rec.Code, rec.Body)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, false); rec.Code != 401 {
t.Fatalf("public explain = %d, want 401", rec.Code)
}
}
func TestExplainWritesAndCommits(t *testing.T) {
r, repo, _ := setup(t)
fc := &fakeClaude{gate: make(chan struct{})}
repo.srv.Claude = fc
if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast\nsecret statement"}`, true); rec.Code != 200 {
t.Fatalf("saving a statement = %d: %s", rec.Code, rec.Body)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{"note":"stuck on order","includeCode":true}`, true); rec.Code != 202 {
t.Fatalf("start = %d: %s", rec.Code, rec.Body)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true); rec.Code != 409 {
t.Fatalf("second start while running = %d, want 409", rec.Code)
}
close(fc.gate)
if s := waitJob(t, r, "moocast"); s.State != explain.Done {
t.Fatalf("job = %+v, want done", s)
}
for _, want := range []string{"secret statement", "stuck on order", "<my_attempt file=\"main.cpp\">"} {
if !strings.Contains(fc.user, want) {
t.Errorf("prompt is missing %q:\n%s", want, fc.user)
}
}
b, err := os.ReadFile(filepath.Join(repo.dir, "solved/moocast/explain.md"))
if err != nil || !strings.Contains(string(b), "## Key observation\n\nThink in reverse.") {
t.Fatalf("explain.md = %q, %v", b, err)
}
if last := repo.msg[len(repo.msg)-1]; last != "Explain moocast" {
t.Errorf("commit subject = %q", last)
}
// The public sees the explanation of a solved problem, not the statement.
var pub struct{ Statement, Explanation string }
json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", false).Body.Bytes(), &pub)
if pub.Statement != "" || !strings.Contains(pub.Explanation, "Think in reverse.") {
t.Errorf("public view = %+v", pub)
}
var adm struct{ Statement string }
json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", true).Body.Bytes(), &adm)
if !strings.Contains(adm.Statement, "secret statement") {
t.Errorf("admin should see the statement, got %q", adm.Statement)
}
}
func TestExplainFetchesAMissingStatement(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.Claude = &fakeClaude{}
repo.srv.Statements = fakeJudge{}
do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://cses.fi/x"}`, true)
do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true)
if s := waitJob(t, r, "watermelon"); s.State != explain.Failed || !strings.Contains(s.Error, "paste it") {
t.Fatalf("unfetchable statement: job = %+v, want an error asking to paste it", s)
}
do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://usaco.org/moocast"}`, true)
do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true)
if s := waitJob(t, r, "watermelon"); s.State != explain.Done {
t.Fatalf("job = %+v, want done", s)
}
if b, _ := os.ReadFile(filepath.Join(repo.dir, "solving/watermelon/problem.md")); !strings.Contains(string(b), "walkie-talkies") {
t.Errorf("fetched statement not saved: %q", b)
}
}
func TestFetchStatement(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.Statements = fakeJudge{}
if rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch", "", true); rec.Code != 400 {
t.Fatalf("no link = %d, want 400", rec.Code)
}
if rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch?url=https://cses.fi/x", "", true); rec.Code != 422 {
t.Fatalf("unsupported judge = %d, want 422", rec.Code)
}
rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch?url=https://usaco.org/moocast", "", true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "walkie-talkies") {
t.Fatalf("fetch = %d %s", rec.Code, rec.Body)
}
if _, err := os.Stat(filepath.Join(repo.dir, "solved/moocast/problem.md")); !os.IsNotExist(err) {
t.Error("fetching must not save anything")
}
if rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch?url=https://usaco.org/moocast", "", false); rec.Code != 401 {
t.Fatalf("public fetch = %d, want 401", rec.Code)
}
}
+40 -7
View File
@@ -1,6 +1,7 @@
// 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, and the
// Gitea webhook that tells the server to pull.
// for solved problems, everything for the admin), the admin's edits, the
// Claude explanations (explain.go), and the Gitea webhook that tells the
// server to pull.
package handlers
import (
@@ -24,6 +25,7 @@ import (
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/auth"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/repo"
)
@@ -41,8 +43,15 @@ type Server struct {
// Pull asks for a sync. It must not block: the webhook answers at once
// and the sync runs in the background.
Pull func()
// Claude writes the explanations; nil when CLAUDE_API_KEY is not set,
// which turns only that feature off.
Claude explain.Asker
// Statements reads a statement from the problem's judge; nil means the
// real judges.
Statements Fetcher
idx atomic.Pointer[index.Index]
idx atomic.Pointer[index.Index]
jobs explain.Jobs
}
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
@@ -73,6 +82,9 @@ func (s *Server) Routes(api *gin.RouterGroup) {
api.GET("/problems/:name", s.get)
admin.PUT("/problems/:name/meta", s.updateMeta)
admin.POST("/problems/:name/status", s.setStatus)
admin.GET("/problems/:name/statement/fetch", s.fetchStatement)
admin.POST("/problems/:name/explain", s.startExplain)
admin.GET("/problems/:name/explain", s.explainStatus)
api.POST("/hooks/gitea", s.webhook)
}
@@ -144,9 +156,20 @@ func (s *Server) lookup(ctx *gin.Context, admin bool) (*index.Problem, bool) {
}
func (s *Server) get(ctx *gin.Context) {
if p, ok := s.lookup(ctx, s.isAdmin(ctx)); ok {
ctx.JSON(http.StatusOK, p)
admin := s.isAdmin(ctx)
p, ok := s.lookup(ctx, admin)
if !ok {
return
}
// The statement is the judge's text, kept for the admin and for Claude;
// the public page links to the judge instead. The index is shared, so
// this blanks a copy.
if !admin && p.Statement != "" {
c := *p
c.Statement = ""
p = &c
}
ctx.JSON(http.StatusOK, p)
}
// requestError is an edit that cannot be made, with the status to send.
@@ -194,8 +217,9 @@ func findOnDisk(dir, name string) (status string, err error) {
}
type metaBody struct {
URL *string `json:"url"`
Notes *string `json:"notes"`
URL *string `json:"url"`
Notes *string `json:"notes"`
Statement *string `json:"statement"`
}
const maxNotes = 64 << 10
@@ -225,6 +249,10 @@ func (s *Server) updateMeta(ctx *gin.Context) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "notes are too long"})
return
}
if body.Statement != nil && len(*body.Statement) > maxNotes {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the statement is too long"})
return
}
name := p.Name
s.mutate(ctx, name, "Update "+name, func(dir string) error {
@@ -244,6 +272,11 @@ func (s *Server) updateMeta(ctx *gin.Context) {
return err
}
}
if body.Statement != nil {
if err := writeOrRemove(filepath.Join(pdir, "problem.md"), *body.Statement); err != nil {
return err
}
}
return nil
})
}