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
+310
View File
@@ -0,0 +1,310 @@
// 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()
}
+151
View File
@@ -0,0 +1,151 @@
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")
}
}
+14 -5
View File
@@ -95,6 +95,18 @@ var Schema = map[string]any{
// 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 <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.`
// 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.
@@ -105,14 +117,11 @@ How to explain:
- 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.
- 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.
` + 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.
- 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.`
` + DiagramRules
// Prompt is the user message: the problem and what the admin has given.
func Prompt(in Input) string {
+3
View File
@@ -101,6 +101,9 @@ func TestGenerate(t *testing.T) {
if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil {
t.Errorf("request not filled in: %+v", a.req)
}
if !strings.Contains(System, MathRules) || !strings.Contains(System, DiagramRules) {
t.Error("System is missing the rules it shares with concepts")
}
}
func TestJobsOneAtATime(t *testing.T) {
+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)
}
+115 -2
View File
@@ -6,7 +6,9 @@
// the CLI wires up, tests/N.in + N.out, and optionally a .url, notes.md,
// problem.md (the statement, pasted or fetched from the judge by the site),
// explain.md (an explanation the site had Claude write) and reviews/<id>.md
// (feedback on a recording of the admin explaining it). The repo is
// (feedback on a recording of the admin explaining it). Beside them,
// concepts/<slug>/ holds a technique the site had Claude explain
// (internal/concept): concept.md, snippet.cpp and request.md. The repo is
// small, so everything, file contents included, is read on each rebuild,
// and a rebuild only happens when the clone changes.
package index
@@ -36,6 +38,9 @@ const (
var Statuses = []string{Solving, Solved, Skipped}
// Concepts is the directory of saved concepts, which are not problems.
const Concepts = "concepts"
// MaxFileSize caps what is held for one file. Test inputs can be large and
// nobody reads a megabyte in a browser; the rest is cut and marked.
const MaxFileSize = 64 << 10
@@ -110,16 +115,33 @@ type Review struct {
Content string `json:"content"`
}
// Concept is one concepts/<slug>/. Unlike a problem, it is public whatever
// its state: nothing in it is the judge's or the admin's own words.
type Concept struct {
Slug string `json:"slug"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Tags []string `json:"tags"`
// Content is concept.md without its header comment and title, which the
// page shows itself.
Content string `json:"content,omitempty"`
Snippet *File `json:"snippet,omitempty"`
// Request is request.md, what was asked, for rewriting the concept.
Request string `json:"-"`
Updated *time.Time `json:"updated,omitempty"`
}
// Index is one snapshot of the clone.
type Index struct {
Head string
Built time.Time
Problems map[string]*Problem
Concepts map[string]*Concept
}
// Build reads dir, a git work tree.
func Build(dir string) (*Index, error) {
idx := &Index{Built: time.Now(), Problems: map[string]*Problem{}}
idx := &Index{Built: time.Now(), Problems: map[string]*Problem{}, Concepts: map[string]*Concept{}}
for _, status := range Statuses {
entries, err := os.ReadDir(filepath.Join(dir, status))
if os.IsNotExist(err) {
@@ -145,6 +167,9 @@ func Build(dir string) (*Index, error) {
idx.Problems[p.Name] = p
}
}
if err := readConcepts(filepath.Join(dir, Concepts), idx); err != nil {
return nil, err
}
head, err := gitOut(dir, "rev-parse", "HEAD")
if err != nil {
return nil, err
@@ -306,6 +331,82 @@ func readReviews(rdir string) ([]Review, error) {
return out, nil
}
func readConcepts(cdir string, idx *Index) error {
entries, err := os.ReadDir(cdir)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
for _, e := range entries {
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
continue
}
c, err := readConcept(filepath.Join(cdir, e.Name()))
if err != nil {
return fmt.Errorf("%s/%s: %w", Concepts, e.Name(), err)
}
if c != nil {
idx.Concepts[c.Slug] = c
}
}
return nil
}
// conceptHead is the comment internal/concept writes as concept.md's first
// line.
var conceptHead = regexp.MustCompile(`^<!-- concept(?: tags=(\S*))? -->\r?\n`)
// readConcept returns nil for a directory with neither an explanation nor a
// snippet: there is nothing to show.
func readConcept(cdir string) (*Concept, error) {
c := &Concept{Slug: filepath.Base(cdir), Title: filepath.Base(cdir), Tags: []string{}}
md, mdErr := os.ReadFile(filepath.Join(cdir, "concept.md"))
if mdErr != nil && !os.IsNotExist(mdErr) {
return nil, mdErr
}
if snip, err := readFile(filepath.Join(cdir, "snippet.cpp"), "cpp"); err == nil {
c.Snippet = &snip
} else if !os.IsNotExist(err) {
return nil, err
}
if mdErr != nil && c.Snippet == nil {
return nil, nil
}
if b, err := os.ReadFile(filepath.Join(cdir, "request.md")); err == nil {
c.Request = string(b)
}
content := string(md)
if m := conceptHead.FindStringSubmatch(content); m != nil {
for _, t := range strings.Split(m[1], ",") {
if t != "" {
c.Tags = append(c.Tags, t)
}
}
content = content[len(m[0]):]
}
// The title is the first line if it is a heading, and the summary the
// first italic line under it that is not the byline.
if first, rest, _ := strings.Cut(content, "\n"); strings.HasPrefix(first, "# ") {
c.Title = strings.TrimSpace(first[2:])
content = rest
}
for _, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "## ") {
break
}
if len(line) > 2 && line[0] == '_' && line[len(line)-1] == '_' && !strings.HasPrefix(line, "_Explained by ") {
c.Summary = line[1 : len(line)-1]
break
}
}
c.Content = strings.TrimLeft(content, "\r\n")
return c, nil
}
func readFile(path, lang string) (File, error) {
f, err := os.Open(path)
if err != nil {
@@ -378,6 +479,7 @@ func addHistory(dir string, idx *Index) error {
solvedFiles := map[string]map[string]bool{} // name -> paths under solved/<name>/
var c Commit
touched := map[string]bool{}
touchedConcepts := map[string]bool{}
becameSolved := map[string]bool{}
flush := func() {
@@ -393,6 +495,12 @@ func addHistory(dir string, idx *Index) error {
p.LastTouched = &d
p.History = append(p.History, c)
}
for slug := range touchedConcepts {
if cn, ok := idx.Concepts[slug]; ok {
d := c.Date
cn.Updated = &d
}
}
for name := range becameSolved {
if p, ok := idx.Problems[name]; ok && len(solvedFiles[name]) > 0 {
d := c.Date
@@ -400,6 +508,7 @@ func addHistory(dir string, idx *Index) error {
}
}
touched = map[string]bool{}
touchedConcepts = map[string]bool{}
becameSolved = map[string]bool{}
}
@@ -433,6 +542,10 @@ func addHistory(dir string, idx *Index) error {
}
kind, path := fields[0], fields[len(fields)-1]
segs := strings.SplitN(path, "/", 3)
if len(segs) == 3 && segs[0] == Concepts {
touchedConcepts[segs[1]] = true
continue
}
if len(segs) < 3 || !isStatus(segs[0]) {
continue
}
+28
View File
@@ -4,6 +4,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
@@ -76,6 +77,13 @@ func fixture(t *testing.T) string {
write("solved/moocast/reviews/2026-09-04-100000.md", "<!-- review verdict=correct audio=moocast/2026-09-04-100000.mp3 -->\n_Reviewed by m._\n")
write("solved/moocast/reviews/notes.md", "hand-written\n")
commit(4, "Add a test")
write("concepts/fenwick-tree/concept.md", "<!-- concept tags=range-query,prefix-sums -->\n# Fenwick tree\n\n_Prefix sums with updates in O(log n)._\n\n_Explained by m on 5 September 2026._\n\n## Intuition\n\nLowbits.\n")
write("concepts/fenwick-tree/snippet.cpp", "// concept: fenwick-tree\nstruct BIT {};\n")
write("concepts/fenwick-tree/request.md", "help explain fenwick trees\n")
write("concepts/hand-made/snippet.cpp", "int f();\n")
write("concepts/empty/notes.txt", "nothing to show\n")
commit(5, "Explain concept fenwick-tree")
return dir
}
@@ -139,6 +147,26 @@ func TestBuild(t *testing.T) {
t.Fatalf("moocast history = %+v, want 3 commits newest first", m.History)
}
if len(m.History) != 3 {
t.Fatalf("a concept's commit touched moocast: %+v", m.History)
}
if len(idx.Concepts) != 2 {
t.Fatalf("concepts = %v, want fenwick-tree and hand-made (empty has nothing to show)", idx.Concepts)
}
f := idx.Concepts["fenwick-tree"]
if f.Title != "Fenwick tree" || f.Summary != "Prefix sums with updates in O(log n)." || len(f.Tags) != 2 || f.Tags[1] != "prefix-sums" {
t.Fatalf("fenwick-tree = %+v", f)
}
if !strings.HasPrefix(f.Content, "_Prefix sums") || strings.Contains(f.Content, "# Fenwick") || strings.Contains(f.Content, "<!--") {
t.Fatalf("fenwick-tree content keeps its header or title: %q", f.Content)
}
if f.Snippet == nil || f.Snippet.Lang != "cpp" || f.Request != "help explain fenwick trees\n" || f.Updated == nil || !f.Updated.Equal(day(5)) {
t.Fatalf("fenwick-tree snippet/request/updated = %+v / %q / %v", f.Snippet, f.Request, f.Updated)
}
if h := idx.Concepts["hand-made"]; h.Title != "hand-made" || h.Content != "" || h.Snippet == nil || len(h.Tags) != 0 {
t.Fatalf("hand-made = %+v, want the slug as title and only a snippet", h)
}
w := idx.Problems["watermelon"]
if w.Status != Skipped || w.SolvedAt != nil || w.Sample != nil {
t.Fatalf("watermelon = %+v, want skipped, unsolved, no sample (empty .in)", w.Summary)