Files
usaco/site/internal/index/index.go
T
adamfandClaude Opus 5.5 63608f130c
Test and publish the site / test (push) Successful in 2m4s
Test and publish the site / publish (push) Successful in 1m44s
Review recorded explanations of a solution on the site
The admin can upload a recording of themselves explaining a problem's
solution out loud (mp3, m4a, wav, webm, ogg or flac, up to 25 MB) and
get interview-style feedback, committed as reviews/<id>.md so every
attempt is kept.

Claude can't take audio, so the recording is transcribed first by an
OpenAI-compatible endpoint (whisper-1 by default; TRANSCRIBE_API_KEY,
with TRANSCRIBE_URL for a self-hosted server). Pace, pauses, filler
words and when complexity first comes up are measured from the word
timestamps and given to Claude with the timestamped transcript, the
statement and optionally the code. The reply covers the verdict, scores
in five areas, the approach and its complexity, missed edge cases,
delivery and what to work on.

Recordings are kept for playback in an S3 bucket (Garage) when the
S3_* settings are given, and are thrown away otherwise. Reviews are
admin-only. The job runs in the background like Explain, and the
statement fetch and save-error handling are now shared between the two.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 01:56:55 +01:00

495 lines
14 KiB
Go

// Package index reads a clone of the usaco repository into memory: every
// problem, its files and tests, and the dates git knows about it.
//
// The layout is the CLI's (README.md at the repo root): solving/, solved/
// and skipped/<name>/, each with a solution (main.cpp, sol.py...), an <io>.in
// 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
// small, so everything, file contents included, is read on each rebuild,
// and a rebuild only happens when the clone changes.
package index
import (
"bufio"
"bytes"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// The three status directories, in the order the CLI searches them.
const (
Solving = "solving"
Solved = "solved"
Skipped = "skipped"
)
var Statuses = []string{Solving, Solved, Skipped}
// 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
// File is a solution file or a test half.
type File struct {
Name string `json:"name"`
Lang string `json:"lang,omitempty"`
Content string `json:"content"`
Truncated bool `json:"truncated,omitempty"`
}
// Test is one saved case. Output is nil when the expected output is missing
// (tests/*.out were gitignored before the site existed).
type Test struct {
Name string `json:"name"`
Input File `json:"input"`
Output *File `json:"output,omitempty"`
}
// Commit is one entry of a problem's history.
type Commit struct {
Hash string `json:"hash"`
Date time.Time `json:"date"`
Subject string `json:"subject"`
}
// Summary is what the list shows.
type Summary struct {
Name string `json:"name"`
Status string `json:"status"`
URL string `json:"url,omitempty"`
Source string `json:"source,omitempty"`
Langs []string `json:"langs"`
Tests int `json:"tests"`
HasNotes bool `json:"hasNotes"`
HasExplanation bool `json:"hasExplanation"`
ReviewCount int `json:"reviewCount"`
FirstSeen *time.Time `json:"firstSeen,omitempty"`
SolvedAt *time.Time `json:"solvedAt,omitempty"`
LastTouched *time.Time `json:"lastTouched,omitempty"`
}
// Problem is everything known about one problem.
type Problem struct {
Summary
IO string `json:"io,omitempty"`
Notes string `json:"notes"`
// Statement is the judge's text, so the handlers send it to the admin
// only: the site should not republish it.
Statement string `json:"statement,omitempty"`
Explanation string `json:"explanation"`
// Reviews are newest first, and admin-only like Statement: they are a
// transcript of the admin talking.
Reviews []Review `json:"reviews"`
Files []File `json:"files"`
Sample *File `json:"sample,omitempty"`
TestSet []Test `json:"testCases"`
History []Commit `json:"history"`
}
// Review is one reviews/<id>.md. The site writes the id as the UTC time of
// the recording, so ids sort by age.
type Review struct {
ID string `json:"id"`
Verdict string `json:"verdict,omitempty"`
// Audio is the recording's key in the audio store; the page only needs
// to know there is one.
Audio string `json:"-"`
HasAudio bool `json:"hasAudio"`
// Content is the markdown without its header comment.
Content string `json:"content"`
}
// Index is one snapshot of the clone.
type Index struct {
Head string
Built time.Time
Problems map[string]*Problem
}
// Build reads dir, a git work tree.
func Build(dir string) (*Index, error) {
idx := &Index{Built: time.Now(), Problems: map[string]*Problem{}}
for _, status := range Statuses {
entries, err := os.ReadDir(filepath.Join(dir, status))
if os.IsNotExist(err) {
continue
}
if err != nil {
return nil, err
}
for _, e := range entries {
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
continue
}
// The CLI never lets one name exist in two status dirs; if a
// hand edit did it anyway, the first in search order wins, as
// in find_problem.
if _, dup := idx.Problems[e.Name()]; dup {
continue
}
p, err := readProblem(filepath.Join(dir, status, e.Name()), status)
if err != nil {
return nil, fmt.Errorf("%s/%s: %w", status, e.Name(), err)
}
idx.Problems[p.Name] = p
}
}
head, err := gitOut(dir, "rev-parse", "HEAD")
if err != nil {
return nil, err
}
idx.Head = strings.TrimSpace(head)
if err := addHistory(dir, idx); err != nil {
return nil, err
}
return idx, nil
}
// solution languages, by extension. Anything else at the top of a problem
// dir (binaries, .bak, the .in/.out) is not a solution.
var langs = map[string]string{
".cpp": "cpp", ".cc": "cpp", ".c": "c", ".h": "cpp", ".hpp": "cpp",
".py": "python", ".java": "java", ".rs": "rust", ".go": "go",
}
func readProblem(pdir, status string) (*Problem, error) {
p := &Problem{Summary: Summary{Name: filepath.Base(pdir), Status: status, Langs: []string{}}, Reviews: []Review{}, Files: []File{}, TestSet: []Test{}, History: []Commit{}}
entries, err := os.ReadDir(pdir)
if err != nil {
return nil, err
}
seenLang := map[string]bool{}
for _, e := range entries {
name := e.Name()
if e.IsDir() {
continue
}
switch {
case name == ".url":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.URL = strings.TrimSpace(string(b))
case name == "notes.md":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.Notes = string(b)
case name == "problem.md":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.Statement = string(b)
case name == "explain.md":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.Explanation = string(b)
case strings.HasSuffix(name, ".in") && p.IO == "":
// The first *.in, as detect_io in lib/common.sh picks it.
p.IO = strings.TrimSuffix(name, ".in")
f, err := readFile(filepath.Join(pdir, name), "")
if err != nil {
return nil, err
}
p.Sample = &f
default:
if lang, ok := langs[filepath.Ext(name)]; ok {
f, err := readFile(filepath.Join(pdir, name), lang)
if err != nil {
return nil, err
}
p.Files = append(p.Files, f)
if !seenLang[lang] {
seenLang[lang] = true
p.Langs = append(p.Langs, lang)
}
}
}
}
// main.cpp / main.rs first: it is the CLI's solution, anything else is
// a side experiment (sol.py) or a helper.
isMain := func(name string) bool { return strings.HasPrefix(name, "main.") }
sort.SliceStable(p.Files, func(i, j int) bool {
return isMain(p.Files[i].Name) && !isMain(p.Files[j].Name)
})
if p.Sample != nil && strings.TrimSpace(p.Sample.Content) == "" {
p.Sample = nil
}
tests, err := readTests(filepath.Join(pdir, "tests"))
if err != nil {
return nil, err
}
p.TestSet = tests
p.Tests = len(tests)
if p.Reviews, err = readReviews(filepath.Join(pdir, "reviews")); err != nil {
return nil, err
}
p.ReviewCount = len(p.Reviews)
p.HasNotes = strings.TrimSpace(p.Notes) != ""
p.HasExplanation = strings.TrimSpace(p.Explanation) != ""
p.Source = Source(p.URL)
return p, nil
}
// readTests pairs tests/N.in with tests/N.out, numerically ordered as
// `usaco test` runs them.
func readTests(tdir string) ([]Test, error) {
entries, err := os.ReadDir(tdir)
if os.IsNotExist(err) {
return []Test{}, nil
}
if err != nil {
return nil, err
}
tests := []Test{}
for _, e := range entries {
base, ok := strings.CutSuffix(e.Name(), ".in")
if !ok || e.IsDir() {
continue
}
in, err := readFile(filepath.Join(tdir, e.Name()), "")
if err != nil {
return nil, err
}
t := Test{Name: base, Input: in}
if out, err := readFile(filepath.Join(tdir, base+".out"), ""); err == nil {
t.Output = &out
}
tests = append(tests, t)
}
sort.Slice(tests, func(i, j int) bool {
a, aerr := strconv.Atoi(tests[i].Name)
b, berr := strconv.Atoi(tests[j].Name)
if aerr == nil && berr == nil {
return a < b
}
return tests[i].Name < tests[j].Name
})
return tests, nil
}
// reviewHead is the comment internal/review writes as a review's first line.
var reviewHead = regexp.MustCompile(`^<!-- review verdict=(\S+)(?: audio=(\S+))? -->\r?\n`)
func readReviews(rdir string) ([]Review, error) {
entries, err := os.ReadDir(rdir)
if os.IsNotExist(err) {
return []Review{}, nil
}
if err != nil {
return nil, err
}
out := []Review{}
for _, e := range entries {
id, ok := strings.CutSuffix(e.Name(), ".md")
if !ok || e.IsDir() {
continue
}
f, err := readFile(filepath.Join(rdir, e.Name()), "")
if err != nil {
return nil, err
}
r := Review{ID: id, Content: f.Content}
if m := reviewHead.FindStringSubmatch(f.Content); m != nil {
r.Verdict, r.Audio, r.HasAudio = m[1], m[2], m[2] != ""
r.Content = f.Content[len(m[0]):]
}
out = append(out, r)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
return out, nil
}
func readFile(path, lang string) (File, error) {
f, err := os.Open(path)
if err != nil {
return File{}, err
}
defer f.Close()
b, err := io.ReadAll(io.LimitReader(f, MaxFileSize+1))
if err != nil {
return File{}, err
}
file := File{Name: filepath.Base(path), Lang: lang}
if len(b) > MaxFileSize {
b = b[:MaxFileSize]
file.Truncated = true
}
file.Content = string(b)
return file, nil
}
// Source names the judge a problem URL points at, for the list's badge.
func Source(raw string) string {
if raw == "" {
return ""
}
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return ""
}
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
known := map[string]string{
"usaco.org": "USACO",
"usaco.guide": "USACO Guide",
"cses.fi": "CSES",
"leetcode.com": "LeetCode",
"codeforces.com": "Codeforces",
"atcoder.jp": "AtCoder",
"kattis.com": "Kattis",
"open.kattis.com": "Kattis",
"hackerrank.com": "HackerRank",
"spoj.com": "SPOJ",
"onlinejudge.org": "UVa",
}
if s, ok := known[host]; ok {
return s
}
return host
}
// addHistory walks the whole log once, oldest first, and gives each problem
// its commits, first and last dates, and solve date.
//
// The solve date is the last time the problem's solved/<name>/ went from
// empty to non-empty: `usaco done` (a move into solved/) and a reopen +
// re-solve both count, adding a test to an already solved problem does not.
// It is taken from git rather than file mtimes (what `usaco stats` uses)
// because a fresh clone has every mtime set to the clone time.
func addHistory(dir string, idx *Index) error {
// --no-renames: a move between status dirs is then a delete plus an
// add, which is exactly what the solved-file counting below wants.
out, err := gitOut(dir, "-c", "core.quotePath=false", "log", "--reverse", "--no-renames",
"--format=%x00%H%x09%aI%x09%s", "--name-status")
if err != nil {
// A repository with no commits yet has no history to add.
if strings.Contains(err.Error(), "does not have any commits") {
return nil
}
return err
}
solvedFiles := map[string]map[string]bool{} // name -> paths under solved/<name>/
var c Commit
touched := map[string]bool{}
becameSolved := map[string]bool{}
flush := func() {
for name := range touched {
p, ok := idx.Problems[name]
if !ok {
continue
}
d := c.Date
if p.FirstSeen == nil {
p.FirstSeen = &d
}
p.LastTouched = &d
p.History = append(p.History, c)
}
for name := range becameSolved {
if p, ok := idx.Problems[name]; ok && len(solvedFiles[name]) > 0 {
d := c.Date
p.SolvedAt = &d
}
}
touched = map[string]bool{}
becameSolved = map[string]bool{}
}
sc := bufio.NewScanner(bytes.NewReader([]byte(out)))
sc.Buffer(make([]byte, 1<<20), 1<<20)
started := false
for sc.Scan() {
line := sc.Text()
if rest, ok := strings.CutPrefix(line, "\x00"); ok {
if started {
flush()
}
started = true
parts := strings.SplitN(rest, "\t", 3)
if len(parts) != 3 {
return fmt.Errorf("unexpected git log line %q", line)
}
date, err := time.Parse(time.RFC3339, parts[1])
if err != nil {
return err
}
c = Commit{Hash: parts[0][:min(len(parts[0]), 12)], Date: date, Subject: parts[2]}
continue
}
if line == "" {
continue
}
fields := strings.Split(line, "\t")
if len(fields) < 2 {
continue
}
kind, path := fields[0], fields[len(fields)-1]
segs := strings.SplitN(path, "/", 3)
if len(segs) < 3 || !isStatus(segs[0]) {
continue
}
name := segs[1]
touched[name] = true
if segs[0] != Solved {
continue
}
set := solvedFiles[name]
if set == nil {
set = map[string]bool{}
solvedFiles[name] = set
}
wasEmpty := len(set) == 0
switch kind[0] {
case 'D':
delete(set, path)
default: // A, M, T (and C if it ever appears)
set[path] = true
}
if wasEmpty && len(set) > 0 {
becameSolved[name] = true
}
}
if started {
flush()
}
if err := sc.Err(); err != nil {
return err
}
for _, p := range idx.Problems {
// Newest first for display.
for i, j := 0, len(p.History)-1; i < j; i, j = i+1, j-1 {
p.History[i], p.History[j] = p.History[j], p.History[i]
}
// A problem that is solved on disk but whose solved/ files never
// showed up in the log (uncommitted, in development) has no date.
if p.Status != Solved {
p.SolvedAt = nil
}
}
return nil
}
func isStatus(s string) bool {
return s == Solving || s == Solved || s == Skipped
}
func gitOut(dir string, args ...string) (string, error) {
cmd := exec.Command("git", args...)
cmd.Dir = dir
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(errb.String()))
}
return out.String(), nil
}