Files
adamfandClaude Opus 5.5 ccf4e4dd74
Test and publish the site / test (push) Successful in 1m19s
Test and publish the site / publish (push) Successful in 1m31s
Explain concepts on the site, and reuse their code from the CLI
/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]>
2026-10-20 12:58:38 +01:00

152 lines
5.5 KiB
Go

package concept
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
)
func TestRender(t *testing.T) {
r := Result{
Title: "Fenwick tree\n(BIT)",
Summary: "Prefix sums with point updates, both $O(\\log n)$.",
Tags: []string{"Range Query", "prefix-sums", "range-query", ""},
Intuition: "Prefix sums break on updates.",
HowItWorks: "`t[i]` covers `(i - lowbit(i), i]`.",
Walkthrough: []explain.Step{
{Caption: "Build.", SVG: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"></svg>`},
{Caption: "Query.", SVG: "```<svg></svg>"},
},
Complexity: "$O(\\log n)$ each.",
Pitfalls: []string{"It is 1-based.", ""},
Usage: "```cpp\nBIT b(n);\nb.add(3, 5);\n```",
}
got := Render(r, "claude-opus-5-5", time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC))
want := "<!-- concept tags=range-query,prefix-sums -->\n" +
"# Fenwick tree (BIT)\n" +
"\n_Prefix sums with point updates, both $O(\\log n)$._\n" +
"\n_Explained by claude-opus-5-5 on 20 October 2026._\n" +
"\n## Intuition\n\nPrefix sums break on updates.\n" +
"\n## How it works\n\n`t[i]` covers `(i - lowbit(i), i]`.\n" +
"\n## Walkthrough\n\n**Step 1.** Build.\n\n```svg\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"></svg>\n```\n\n" +
"**Step 2.** Query.\n\n```svg\n<svg></svg>\n```\n" +
"\n## Using it\n\n```cpp\nBIT b(n);\nb.add(3, 5);\n```\n" +
"\n## Complexity\n\n$O(\\log n)$ each.\n" +
"\n## Pitfalls\n\n- It is 1-based.\n"
if got != want {
t.Errorf("Render =\n%s\nwant\n%s", got, want)
}
}
func TestSnippet(t *testing.T) {
for _, code := range []string{"struct BIT {};", "```cpp\nstruct BIT {};\n```\n", " struct BIT {};\n\n"} {
if got := Snippet(code, "fenwick-tree"); got != "// concept: fenwick-tree\nstruct BIT {};\n" {
t.Errorf("Snippet(%q) = %q", code, got)
}
}
}
func TestSlug(t *testing.T) {
for _, c := range []struct{ name, title, want string }{
{"fenwick-tree", "", "fenwick-tree"},
{"Fenwick Tree!", "", "fenwick-tree"},
{"../etc", "", "etc"},
{"", "Sparse table (RMQ)", "sparse-table-rmq"},
{"---", "!!", "concept"},
{strings.Repeat("ab-", 30), "", "ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab-ab"},
} {
if got := Slug(c.name, c.title); got != c.want {
t.Errorf("Slug(%q, %q) = %q, want %q", c.name, c.title, got, c.want)
}
}
}
func TestRequestRoundTrip(t *testing.T) {
for _, c := range []struct{ topic, code string }{
{"help explain fenwick trees", ""},
{"how does this work?", "bool canSort(vector<int>& nums, int k) {\n return true;\n}"},
{"raw strings", "auto s = R\"(```)\";"},
} {
topic, code := ParseRequest(Request(c.topic, c.code))
if topic != c.topic || code != c.code {
t.Errorf("round trip of %q / %q = %q / %q", c.topic, c.code, topic, code)
}
}
}
func TestPrompt(t *testing.T) {
p := Prompt(Input{
Topic: " how does this work? ",
Code: "int f() { return 1; }\n\n",
Existing: []Ref{{"fenwick-tree", "Fenwick tree"}},
})
for _, want := range []string{
"<topic>\nhow does this work?\n</topic>",
"<code>\nint f() { return 1; }\n</code>",
"<saved_concepts>\n- fenwick-tree: Fenwick tree\n</saved_concepts>",
"Explain how this code works",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
q := Prompt(Input{Topic: "fenwick trees"})
if strings.Contains(q, "<code>") || strings.Contains(q, "saved_concepts") || !strings.HasSuffix(q, "Explain this concept.") {
t.Errorf("a bare topic should leave the other blocks out:\n%s", q)
}
rw := Prompt(Input{Topic: "fenwick trees", Previous: "# Fenwick tree\n...", Note: "step 2 is wrong"})
for _, want := range []string{"<previous_version>\n# Fenwick tree", "<what_to_change>\nstep 2 is wrong\n</what_to_change>", "Rewrite the explanation"} {
if !strings.Contains(rw, want) {
t.Errorf("rewrite prompt is missing %q:\n%s", want, rw)
}
}
}
// 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{Tags: []string{}, Walkthrough: []explain.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{Slug: "Fenwick Tree", Title: "Fenwick tree"}
return nil
}
func TestGenerate(t *testing.T) {
a := &fakeAsker{}
r, err := Generate(context.Background(), a, Input{Topic: "fenwick trees"})
if err != nil {
t.Fatal(err)
}
if r.Slug != "fenwick-tree" {
t.Errorf("slug = %q, want it cleaned", r.Slug)
}
if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil {
t.Errorf("request not filled in: %+v", a.req)
}
// The page relies on the same math and diagram rules as explanations.
if !strings.Contains(System, explain.MathRules) || !strings.Contains(System, explain.DiagramRules) {
t.Error("System is missing explain's shared rules")
}
}