// 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 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 // 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. 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. ` + 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. ` + DiagramRules // 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, "\n%s\n\n", in.Name, strings.TrimSpace(in.Statement)) for i, ex := range in.Examples { fmt.Fprintf(&b, "\n\n\n%s\n\n", i+1, strings.TrimRight(ex.In, "\n")) if ex.Out != "" { fmt.Fprintf(&b, "\n%s\n\n", strings.TrimRight(ex.Out, "\n")) } b.WriteString("\n") } if in.Code != nil { fmt.Fprintf(&b, "\n\n%s\n\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n")) } if note := strings.TrimSpace(in.Note); note != "" { fmt.Fprintf(&b, "\n\n%s\n\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{Tag: "explain", 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() }