/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]>
311 lines
13 KiB
Go
311 lines
13 KiB
Go
// Package concept turns "help explain fenwick trees", or a piece of code the
|
|
// admin could not follow, into a saved concept: concepts/<slug>/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 <svg> 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 <bits/stdc++.h> 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, "<topic>\n%s\n</topic>\n", strings.TrimSpace(in.Topic))
|
|
if code := strings.TrimRight(in.Code, " \t\r\n"); strings.TrimSpace(code) != "" {
|
|
fmt.Fprintf(&b, "\n<code>\n%s\n</code>\n", code)
|
|
}
|
|
if len(in.Existing) > 0 {
|
|
b.WriteString("\n<saved_concepts>\n")
|
|
for _, r := range in.Existing {
|
|
fmt.Fprintf(&b, "- %s: %s\n", r.Slug, r.Title)
|
|
}
|
|
b.WriteString("</saved_concepts>\n")
|
|
}
|
|
if prev := strings.TrimSpace(in.Previous); prev != "" {
|
|
fmt.Fprintf(&b, "\n<previous_version>\n%s\n</previous_version>\n", prev)
|
|
if note := strings.TrimSpace(in.Note); note != "" {
|
|
fmt.Fprintf(&b, "\n<what_to_change>\n%s\n</what_to_change>\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/<slug>/.
|
|
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, "<!-- concept tags=%s -->\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()
|
|
}
|