Add an Explain button that has Claude explain a problem
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:
@@ -0,0 +1,191 @@
|
||||
// Package explain turns a problem the admin is stuck on into explain.md: an
|
||||
// intuitive walkthrough of the solution, written by Claude, with SVG
|
||||
// diagrams of the idea running on the sample.
|
||||
//
|
||||
// The reply is a fixed JSON shape (Result) so the page can lay it out as a
|
||||
// ladder the reader climbs only as far as they need: the key observation,
|
||||
// hints that get stronger, then the approach, the walkthrough, and a sketch.
|
||||
// It is stored as markdown, not JSON, so it reads fine on Gitea and can be
|
||||
// edited by hand like notes.md.
|
||||
package explain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/claude"
|
||||
"adam-french.co.uk/usaco-site/internal/index"
|
||||
)
|
||||
|
||||
// Asker is the part of claude.Client used here, so tests can fake it.
|
||||
type Asker interface {
|
||||
JSON(ctx context.Context, req claude.Request, out any) error
|
||||
Model() string
|
||||
}
|
||||
|
||||
// Example is one sample case shown to Claude.
|
||||
type Example struct {
|
||||
In, Out string
|
||||
}
|
||||
|
||||
// Input is what Claude is told about the problem.
|
||||
type Input struct {
|
||||
Name string
|
||||
Statement string
|
||||
Note string // what the admin says they are stuck on
|
||||
Code *index.File // their current attempt, when they chose to send it
|
||||
Examples []Example
|
||||
}
|
||||
|
||||
// Step is one frame of the walkthrough.
|
||||
type Step struct {
|
||||
Caption string `json:"caption"`
|
||||
SVG string `json:"svg"`
|
||||
}
|
||||
|
||||
// Result is the reply's shape; Schema is the same thing for the API.
|
||||
type Result struct {
|
||||
Observation string `json:"observation"`
|
||||
Hints []string `json:"hints"`
|
||||
Approach string `json:"approach"`
|
||||
Walkthrough []Step `json:"walkthrough"`
|
||||
Complexity string `json:"complexity"`
|
||||
Pitfalls []string `json:"pitfalls"`
|
||||
Sketch string `json:"sketch"`
|
||||
}
|
||||
|
||||
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{
|
||||
"observation": str("The single key insight the solution rests on, in one or two sentences of markdown. Name the insight without describing the algorithm."),
|
||||
"hints": strs("Two to four hints in markdown, each a step stronger than the last. The first only nudges; the last leaves the reader one step from the approach."),
|
||||
"approach": str("Markdown. The algorithm explained intuitively: how you would think of it from the problem, why it is correct, and what each piece of state means."),
|
||||
"walkthrough": map[string]any{
|
||||
"type": "array",
|
||||
"description": "Two to six steps tracing the approach on a small example, ideally the sample.",
|
||||
"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 <svg> element showing the state at this step, following the diagram rules."),
|
||||
},
|
||||
"required": []string{"caption", "svg"},
|
||||
"additionalProperties": false,
|
||||
},
|
||||
},
|
||||
"complexity": str("Markdown. Time and memory, with a one-line reason for each."),
|
||||
"pitfalls": strs("Markdown. The mistakes that commonly break this problem: edge cases, overflow, off-by-ones, wrong greedy choices."),
|
||||
"sketch": str("Language-agnostic pseudocode for the core of the solution, without any I/O boilerplate. Plain text, no code fence."),
|
||||
},
|
||||
"required": []string{"observation", "hints", "approach", "walkthrough", "complexity", "pitfalls", "sketch"},
|
||||
"additionalProperties": false,
|
||||
}
|
||||
|
||||
// maxTokens leaves room for adaptive thinking at high effort on top of the
|
||||
// reply, which is a few thousand tokens of prose plus the SVGs.
|
||||
const maxTokens = 32000
|
||||
|
||||
// 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.
|
||||
|
||||
How to explain:
|
||||
- Lead with intuition. Explain how someone could arrive at the idea from the problem's structure: what about the constraints or the question suggests it, and what simpler approach fails and why.
|
||||
- Make every part of the state concrete. When you introduce a DP table, a heap, a union-find or two pointers, say exactly what each entry or pointer means.
|
||||
- Justify correctness informally but convincingly, especially for greedy choices.
|
||||
- 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. Use $...$ only if the problem statement does.
|
||||
|
||||
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 <svg> 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, <foreignObject>, external links, images or CSS @import. Use only basic shapes, paths, lines, text, groups and markers.`
|
||||
|
||||
// Prompt is the user message: the problem and what the admin has given.
|
||||
func Prompt(in Input) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
|
||||
for i, ex := range in.Examples {
|
||||
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
|
||||
if ex.Out != "" {
|
||||
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
|
||||
}
|
||||
b.WriteString("</example>\n")
|
||||
}
|
||||
if in.Code != nil {
|
||||
fmt.Fprintf(&b, "\n<my_attempt file=%q>\n%s\n</my_attempt>\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n"))
|
||||
}
|
||||
if note := strings.TrimSpace(in.Note); note != "" {
|
||||
fmt.Fprintf(&b, "\n<where_i_am_stuck>\n%s\n</where_i_am_stuck>\n", note)
|
||||
}
|
||||
b.WriteString("\nExplain how to solve this problem.")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Generate asks Claude and returns explain.md.
|
||||
func Generate(ctx context.Context, a Asker, in Input, now time.Time) (string, error) {
|
||||
var r Result
|
||||
err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return Render(r, a.Model(), now), nil
|
||||
}
|
||||
|
||||
// Render lays a Result out as markdown. The page folds each "## " section
|
||||
// away; the line above the first one stays visible.
|
||||
func Render(r Result, model string, now time.Time) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "_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("Key observation", r.Observation)
|
||||
for i, h := range r.Hints {
|
||||
section(fmt.Sprintf("Hint %d", i+1), h)
|
||||
}
|
||||
section("Approach", r.Approach)
|
||||
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())
|
||||
section("Complexity", r.Complexity)
|
||||
section("Pitfalls", bullets(r.Pitfalls))
|
||||
if sk := strings.TrimSpace(strings.ReplaceAll(r.Sketch, "```", "")); sk != "" {
|
||||
section("Solution sketch", "```text\n"+sk+"\n```")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package explain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/claude"
|
||||
"adam-french.co.uk/usaco-site/internal/index"
|
||||
)
|
||||
|
||||
func TestRender(t *testing.T) {
|
||||
r := Result{
|
||||
Observation: "The answer is monotone in the effort limit.",
|
||||
Hints: []string{"Fix a limit.", "Binary search it, or run Dijkstra on max-edge."},
|
||||
Approach: "Dijkstra where a path costs its largest step.",
|
||||
Walkthrough: []Step{
|
||||
{Caption: "Start at (0,0).", SVG: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"></svg>`},
|
||||
{Caption: "Relax neighbours.", SVG: "```<svg></svg>"},
|
||||
},
|
||||
Complexity: "O(RC log RC).",
|
||||
Pitfalls: []string{"Effort is the max, not the sum.", ""},
|
||||
Sketch: "dist[0][0] = 0\npop smallest",
|
||||
}
|
||||
got := Render(r, "claude-opus-5-5", time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC))
|
||||
want := "_Explained by claude-opus-5-5 on 19 October 2026._\n" +
|
||||
"\n## Key observation\n\nThe answer is monotone in the effort limit.\n" +
|
||||
"\n## Hint 1\n\nFix a limit.\n" +
|
||||
"\n## Hint 2\n\nBinary search it, or run Dijkstra on max-edge.\n" +
|
||||
"\n## Approach\n\nDijkstra where a path costs its largest step.\n" +
|
||||
"\n## Walkthrough\n\n**Step 1.** Start at (0,0).\n\n```svg\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"></svg>\n```\n\n" +
|
||||
"**Step 2.** Relax neighbours.\n\n```svg\n<svg></svg>\n```\n" +
|
||||
"\n## Complexity\n\nO(RC log RC).\n" +
|
||||
"\n## Pitfalls\n\n- Effort is the max, not the sum.\n" +
|
||||
"\n## Solution sketch\n\n```text\ndist[0][0] = 0\npop smallest\n```\n"
|
||||
if got != want {
|
||||
t.Errorf("Render =\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrompt(t *testing.T) {
|
||||
p := Prompt(Input{
|
||||
Name: "min-effort-path",
|
||||
Statement: "# Path With Minimum Effort\n\nA hiker...",
|
||||
Note: " my BFS is wrong ",
|
||||
Code: &index.File{Name: "main.rs", Content: "fn main() {}\n"},
|
||||
Examples: []Example{{In: "1 2\n", Out: "3\n"}, {In: "5\n"}},
|
||||
})
|
||||
for _, want := range []string{
|
||||
"<problem name=\"min-effort-path\">\n# Path With Minimum Effort",
|
||||
"<example n=\"1\">\n<input>\n1 2\n</input>\n<output>\n3\n</output>",
|
||||
"<example n=\"2\">\n<input>\n5\n</input>\n</example>",
|
||||
"<my_attempt file=\"main.rs\">\nfn main() {}\n</my_attempt>",
|
||||
"<where_i_am_stuck>\nmy BFS is wrong\n</where_i_am_stuck>",
|
||||
} {
|
||||
if !strings.Contains(p, want) {
|
||||
t.Errorf("prompt is missing %q:\n%s", want, p)
|
||||
}
|
||||
}
|
||||
if q := Prompt(Input{Name: "x", Statement: "s"}); strings.Contains(q, "my_attempt") || strings.Contains(q, "stuck") {
|
||||
t.Errorf("empty code and note should leave their blocks out:\n%s", q)
|
||||
}
|
||||
}
|
||||
|
||||
// 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{Hints: []string{}, Walkthrough: []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{Observation: "obs"}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestGenerate(t *testing.T) {
|
||||
a := &fakeAsker{}
|
||||
md, err := Generate(context.Background(), a, Input{Name: "x", Statement: "s"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(md, "_Explained by fake on") || !strings.Contains(md, "## Key observation\n\nobs") {
|
||||
t.Errorf("unexpected markdown:\n%s", md)
|
||||
}
|
||||
if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil {
|
||||
t.Errorf("request not filled in: %+v", a.req)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJobsOneAtATime(t *testing.T) {
|
||||
var j Jobs
|
||||
if s := j.Get("a"); s.State != Idle {
|
||||
t.Fatalf("fresh state = %q, want idle", s.State)
|
||||
}
|
||||
release := make(chan struct{})
|
||||
if !j.Start("a", func() error { <-release; return nil }) {
|
||||
t.Fatal("first start refused")
|
||||
}
|
||||
if j.Start("a", func() error { return nil }) {
|
||||
t.Fatal("second start while running accepted")
|
||||
}
|
||||
if !j.Start("b", func() error { return context.Canceled }) {
|
||||
t.Fatal("another problem's job refused")
|
||||
}
|
||||
close(release)
|
||||
wait := func(name string) Status {
|
||||
for range 200 {
|
||||
if s := j.Get(name); s.State != Running {
|
||||
return s
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%s still running", name)
|
||||
return Status{}
|
||||
}
|
||||
if s := wait("a"); s.State != Done || s.Finished == nil {
|
||||
t.Errorf("a = %+v, want done", s)
|
||||
}
|
||||
if s := wait("b"); s.State != Failed || s.Error != context.Canceled.Error() {
|
||||
t.Errorf("b = %+v, want the error", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package explain
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A job's states. Idle means nothing has run since the server started.
|
||||
const (
|
||||
Idle = "idle"
|
||||
Running = "running"
|
||||
Done = "done"
|
||||
Failed = "error"
|
||||
)
|
||||
|
||||
// Status is what the page polls for.
|
||||
type Status struct {
|
||||
State string `json:"state"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Started *time.Time `json:"started,omitempty"`
|
||||
Finished *time.Time `json:"finished,omitempty"`
|
||||
}
|
||||
|
||||
// Jobs runs at most one explanation per problem at a time. An explanation
|
||||
// takes a minute or more, longer than nginx waits for a response, so the
|
||||
// request only starts it and the page polls. State is in memory: a restart
|
||||
// mid-job loses the job, and nothing is committed until it finishes.
|
||||
type Jobs struct {
|
||||
mu sync.Mutex
|
||||
m map[string]*Status
|
||||
}
|
||||
|
||||
// Start runs fn in the background unless a job for name is running, and
|
||||
// reports whether it started. fn's error is shown to the admin, so it must
|
||||
// be a message meant for them.
|
||||
func (j *Jobs) Start(name string, fn func() error) bool {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
if j.m == nil {
|
||||
j.m = map[string]*Status{}
|
||||
}
|
||||
if s := j.m[name]; s != nil && s.State == Running {
|
||||
return false
|
||||
}
|
||||
now := time.Now()
|
||||
j.m[name] = &Status{State: Running, Started: &now}
|
||||
go func() {
|
||||
err := fn()
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
end := time.Now()
|
||||
s := &Status{State: Done, Started: &now, Finished: &end}
|
||||
if err != nil {
|
||||
s.State, s.Error = Failed, err.Error()
|
||||
}
|
||||
j.m[name] = s
|
||||
}()
|
||||
return true
|
||||
}
|
||||
|
||||
// Get is name's latest job.
|
||||
func (j *Jobs) Get(name string) Status {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
if s := j.m[name]; s != nil {
|
||||
return *s
|
||||
}
|
||||
return Status{State: Idle}
|
||||
}
|
||||
Reference in New Issue
Block a user