Explain concepts on the site, and reuse their code from the CLI
Test and publish the site / test (push) Successful in 1m19s
Test and publish the site / publish (push) Successful in 1m31s

/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/<slug>/: concept.md (tags in a
header comment, then a # title), snippet.cpp (first line
"// concept: <slug>") 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 <[email protected]>
This commit is contained in:
2026-10-20 12:58:38 +01:00
co-authored by Claude Opus 5.5
parent d4849859df
commit ccf4e4dd74
25 changed files with 1750 additions and 33 deletions
+269
View File
@@ -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{})
}
+189
View File
@@ -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<int>& 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, "<topic>\nhelp explain fenwick trees\n</topic>") || !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{"<topic>\nhelp explain fenwick trees", "<previous_version>\n# Fenwick tree", "## Snippet", "<what_to_change>\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, "<saved_concepts>") {
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")
}
}
+13 -1
View File
@@ -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)
}