Files
adamfandClaude Opus 5.5 cae5ec8e5a
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s
Keep site jobs across restarts, meter Claude spend, harden admin routes
- internal/jobs replaces explain.Jobs: one registry for every kind of
  background job, with records in DATA_DIR/jobs. A job's draft is written
  before its commit, so a failed commit can be saved again (POST
  /jobs/<kind>/<key>/save) and a restart mid-commit resumes it, without
  paying Claude twice.
- Graceful shutdown: SIGTERM stops new jobs and waits SHUTDOWN_GRACE for
  running ones while still serving the pages that poll them.
- internal/usage records every Claude call's tokens and estimated cost in
  DATA_DIR/usage.jsonl; CLAUDE_MONTHLY_BUDGET refuses new jobs (429) once a
  month reaches it. The stats page shows the admin the spend.
- auth.SameOrigin refuses cross-origin writes to admin routes.
- The LeetCode importer runs the clone's script without the server's
  secrets in its environment.
- A sync that leaves HEAD where it was skips the re-index.
- docs_test.go checks README's route table against the routes, and the CLI
  page against the root README's commands.
- The repo is going private: Gitea links on the site are admin-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:10:01 +01:00

26 KiB

USACO site

The public face of this repo, served at /usaco/ on adam-french.co.uk. It shows the solved problems: each solution, its sample input, saved tests and notes, and its git history, plus a stats page with a solve calendar and a guide to the ./usaco CLI. When the site's admin is logged in, it also shows problems in solving/ and skipped/, and lets them:

  • mark a problem solved, skipped or back in progress
  • set its link
  • save the problem statement (pasted, or fetched from a LeetCode or USACO link)
  • write notes
  • have Claude write an explanation for a problem they are stuck on
  • have Claude explain a technique ("help explain fenwick trees") or a piece of code, saved to a public library of concepts with a C++ snippet to reuse

It is one Go binary that serves a REST API and the built Vue SPA. It runs as one container behind the site's nginx and borrows the site's login, the same arrangement as job-tracker (adamf/job-tracker), which it is modelled on.

Git is the store

There is no database. The CLI's layout is the data model (see the root README.md):

  • solving/, solved/ and skipped/<name>/, each holding the solution files
  • <io>.in for the sample input
  • tests/N.in and N.out
  • .url for the problem link
  • notes.md for notes
  • problem.md for the statement (shown only to the admin, and sent to Claude)
  • explain.md for a Claude-written explanation
  • reviews/<id>.md for feedback on a recording of the admin explaining their solution (admin only)
  • concepts/<slug>/ for a concept: concept.md, snippet.cpp and request.md

The server keeps a clone of adamf/usaco in $DATA_DIR/repo and indexes it into memory.

The repo must stay private on Gitea. The site hides problem.md (the judge's text) and reviews/ (transcripts of the admin talking) from the public, but git holds both, so a public repo would publish them anyway. The server reads it with GIT_TOKEN, so it does not need the repo to be public.

  • Reading. A Gitea push webhook triggers a fetch and hard reset, then a re-index, so a usaco done && usaco sync is live in seconds. A pull every PULL_INTERVAL (10m) catches missed hooks. A sync that leaves HEAD where it was (the interval's pull, or the hook for the site's own push) skips the re-index. The clone is a cache: the remote always wins.

  • Writing. An admin edit runs under one lock:

    1. sync
    2. change the files
    3. commit as GIT_AUTHOR_NAME
    4. push

    The commit subjects match the CLI's: "Solve ", "Skip ", "Reopen " and "Update ". An explanation commits as "Explain ", a review as "Review " and its deletion as "Remove review ". If someone pushed in between and the push is rejected, the edit is replayed once on the new tip. A second rejection returns 409.

  • Dates come from git, not mtimes. A problem's solve date is the commit that moved it into solved/. Its first and last dates are its first and last commits.

The site commits, so the laptop must pull before pushing. usaco sync does pull --rebase --autostash and then push.

Layout

cmd/usacosite/      main: reads the environment, wires everything, registers routes
cmd/usacorunner/    the code runner service (its own image, Dockerfile.runner)
internal/runner/    compile, run, compare and lint, with limits; the site's client for it
internal/auth/      is this request the admin? (asks the site backend; copied from job-tracker)
internal/repo/      the clone: sync, and edit-commit-push with one replay on rejection
internal/index/     reads the clone into memory: problems, files, tests, git dates
internal/handlers/  REST API, Gitea webhook, SPA file server
internal/claude/    the Claude client: streamed call, JSON-schema reply, fixed error messages
internal/explain/   the explanation prompt and schema, explain.md rendering, the job tracker
internal/concept/   the concept prompt and schema, concepts/<slug>/ rendering
internal/transcribe/ OpenAI-compatible speech-to-text client, and pace/pause/filler metrics
internal/review/    the review prompt and schema, reviews/<id>.md rendering
internal/evaluate/  the solve page's evaluation: prompt, schema and the run's verdicts for Claude
internal/audiostore/ optional S3 bucket (Garage) that keeps review recordings for playback
internal/leetcode/  today's daily question or a pasted link, imported by running the clone's lib/leetcode.py
internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page)
web/                Vue 3 + Vite SPA, built for base /usaco/

Routes

Everything is served under BASE_PATH (/usaco). nginx proxies the prefix through unchanged.

Path Auth What
/usaco/, /usaco/p/<name>, /usaco/concepts, /usaco/c/<slug>, /usaco/stats, /usaco/cli none SPA
GET /usaco/api/problems open; the admin also gets unsolved problems the list
GET /usaco/api/problems/<name> open for solved problems; 404 for others unless admin one problem, with files, tests and history
GET /usaco/api/me open {admin}, so the SPA knows whether to show the edit controls
PUT /usaco/api/problems/<name>/meta admin {url?, notes?, statement?}: writes .url, notes.md and problem.md (blank removes the file)
GET /usaco/api/problems/<name>/statement/fetch?url= admin the statement behind url (default: the saved link) as markdown, for review; saves nothing. 422 for a judge it can't read
POST /usaco/api/problems/<name>/explain admin {note?, includeCode?}: starts an explanation and answers 202; 409 if one is running, 503 without CLAUDE_API_KEY
GET /usaco/api/problems/<name>/explain admin the latest job: {state: idle|running|done|error, error?}
POST /usaco/api/problems/<name>/review admin multipart audio (mp3, m4a, wav, webm, ogg, flac; at most 25 MB), note?, includeCode?: starts a review and answers 202; 409 if one is running, 413 if too big, 503 without CLAUDE_API_KEY or TRANSCRIBE_API_KEY
GET /usaco/api/problems/<name>/review admin the latest review job, shaped like the explain one
GET /usaco/api/problems/<name>/reviews/<id>/audio admin the review's recording, with range support; 404 if it was not kept
DELETE /usaco/api/problems/<name>/reviews/<id> admin removes the review and its recording
POST /usaco/api/problems/<name>/status admin {to: solving|solved|skipped}: moves the directory
GET /usaco/api/problems/<name>/code admin the solve page's start: {io, leetcode, languages, default, runner, code: {cpp, python}}, each language's saved source or a starter from template.cpp/template.py
POST /usaco/api/problems/<name>/run admin {lang, source, mode: tests|custom, input?}: compiles once and runs the saved tests (or the custom input) on the runner; answers its verdicts. 503 without RUNNER_URL
POST /usaco/api/problems/<name>/lint admin {lang, source}: the runner's diagnostics (g++ and clang-tidy, or python and ruff)
POST /usaco/api/problems/<name>/evaluate admin {lang, source, note?}: runs the saved tests, then has Claude judge the source; answers 202. 409 if one is running, 503 without CLAUDE_API_KEY
GET /usaco/api/problems/<name>/evaluate admin the latest evaluation job, shaped like the explain one, with the evaluation as result once it is done
PUT /usaco/api/problems/<name>/code admin {lang, source}: commits main.cpp, or main.py (sol.py where that is the existing file), as "Edit "
POST /usaco/api/leetcode/daily admin imports today's LeetCode daily question into solving/ with the CLI's lib/leetcode.py and commits it as "Start ", or finds it if it is already a problem; answers {name, created}. 502 if LeetCode or the import fails
POST /usaco/api/leetcode/import admin {url}: the same for the problem a LeetCode link names (usaco new <leetcode-link>); a bare slug works too. 400 if it is not a LeetCode problem link, 502 if LeetCode or the import fails
GET /usaco/api/concepts open the concept library, newest first, without content or snippets
GET /usaco/api/concepts/<slug> open one concept: {slug, title, summary, tags, content, snippet, updated}
POST /usaco/api/concepts admin {topic, code?}: starts explaining a new concept and answers 202 {id, status}. 503 without CLAUDE_API_KEY
GET /usaco/api/concept-jobs/<id> admin that job, shaped like the explain one, with result: {slug} once it is saved
POST /usaco/api/concepts/<slug>/explain admin {note?}: rewrites the concept in place and answers 202; 409 if a rewrite is running
GET /usaco/api/concepts/<slug>/explain admin the latest rewrite job
DELETE /usaco/api/concepts/<slug> admin removes concepts/<slug>/, committed as "Forget concept "
POST /usaco/api/jobs/<kind>/<key>/save admin commits an unsaved job's answer again (see "Background jobs"); answers 202 and the job, polled at its usual route. 404 if it has nothing unsaved, 409 while it runs
GET /usaco/api/usage admin the Claude spend: {tracked, budget, month, months: [{name, calls, cost}], kinds}
POST /usaco/api/hooks/gitea HMAC (X-Gitea-Signature) queue a pull
GET /usaco/api/health open 200 once the clone is indexed

Every job status (GET …/explain, …/review, …/evaluate, /concept-jobs/<id>, /concepts/<slug>/explain) is {kind, key, state: idle|running|done|error, error?, unsaved?, result?}. Every route that starts a Claude job also answers 429 once this month's budget is spent (CLAUDE_MONTHLY_BUDGET), and 503 while the server is shutting down.

Auth works as in job-tracker:

  • internal/auth forwards the browser's cookies to the site backend's /auth/validate-admin.
  • A "yes" is cached for 30 seconds.
  • A refused admin action sends the browser to /admin/login?redirect=….
  • An admin route that changes something also refuses (403) a request the browser says came from another origin (auth.SameOrigin, by Sec-Fetch-Site, else Origin). The cookies are SameSite=Lax, which already keeps them off other sites' requests; this covers the rest of adam-french.co.uk.

Development

make check          # go vet + go test, and a vite build
make dev            # docker compose up --build: this checkout's problems, no login

Then open http://localhost:8080/usaco/.

make dev. The dev compose clones the repo root, mounted read-only, and sets GIT_PUSH=false. Edits made in the browser become commits in the container's clone and nowhere else. Only committed work shows up.

Hot reload. Run the server with make dev, then run cd web && npm run dev. Vite proxies /usaco/api to localhost:8080.

Without Docker:

go build -o /tmp/usacosite ./cmd/usacosite && (cd web && npx vite build)
DEV_MODE=true AUTH_MODE=dev GIT_PUSH=false GIT_REMOTE_URL=file://$PWD/.. \
  DATA_DIR=/tmp/usaco-data STATIC_DIR=$PWD/web/dist /tmp/usacosite

Every variable is listed and explained in .env.example.

Running inside web_server

The site's docker-compose.yml runs the published image as service usaco, with an explicit environment: list. The site's nginx routes /usaco/ to it. ./usaco-data is mounted at /data and holds the clone (repo/), the background jobs' records (jobs/) and the Claude spend ledger (usage.jsonl). Deleting it is safe: the next start re-clones. It costs any answer not yet committed, the last evaluations and the spend history. The container runs as uid 1000, so run chown 1000 usaco-data on the host.

Deploying

A push to main that touches site/ or .gitea/workflows/ runs .gitea/workflows/ci.yaml at the repo root. It does the following:

  1. Tests.
  2. Builds both images from site/, smoke-tests the runner, and pushes them as adam-french.co.uk/adamf/usaco:<sha> and adam-french.co.uk/adamf/usaco-runner:<sha>, each also as :latest.
  3. Rolls usaco-runner and then the site onto the new images, waiting for each healthcheck.

Problem commits don't match the path filter, so they never rebuild the image. The webhook brings them in.

By hand on the host:

cd ~/deploy/web_server && docker compose pull usaco && docker compose up -d --no-deps usaco

To pin a version, set USACO_IMAGE_TAG=<sha> in the site's .env.

One-off setup

The registry setup is shared with job-tracker (see its README, "One-off: registry setup"). The host is already logged in, and the same REGISTRY_USER and REGISTRY_TOKEN work here.

  1. CI secrets. In this repo's Settings → Actions → Secrets, add REGISTRY_USER and REGISTRY_TOKEN. Use the same values as job-tracker.

  2. A git token for the server. In Gitea, go to Settings → Applications and create a token with repository: read and write. Put it in the site's .env as USACO_GIT_TOKEN.

  3. The data directory. On the host, in ~/deploy/web_server, run mkdir usaco-data && sudo chown 1000:1000 usaco-data.

  4. A webhook secret. Generate one, for example with openssl rand -hex 32, and put it in the site's .env as USACO_WEBHOOK_SECRET.

  5. Deploy web_server with the usaco service and the /usaco/ route. Then push this repo, so CI publishes the first image.

  6. The webhook. In this repo's Settings → Webhooks → Add webhook → Gitea, set:

    • Target URL: http://usaco:8080/usaco/api/hooks/gitea
    • Method: POST
    • Content type: application/json
    • Secret: the value of USACO_WEBHOOK_SECRET
    • Trigger: push events

    Gitea only delivers to Docker-network hosts that are on [webhook] ALLOWED_HOST_LIST. web_server's compose sets that to external,usaco. Use "Test delivery": the response should be 202, and docker logs usaco should show a new [index] line.

Explanations

The Explain panel on a problem page (admin only) asks Claude for an intuitive explanation and commits it as explain.md.

  • Input. The statement (problem.md; when it is missing, it is fetched from the link and saved too), up to three saved tests with outputs or the sample input, optionally the main solution file, and the admin's "where I'm stuck" note.
  • Output. A JSON-schema reply (internal/explain Schema): the key observation, 2 to 4 hints, the approach, a walkthrough whose steps each carry an SVG diagram, complexity, pitfalls and a pseudocode sketch. It is stored as markdown with one ## section each, and the page shows every section folded so the reader opens only as much as they need. Diagrams are ```svg fences, sanitized with DOMPurify before they are inserted.
  • The call. CLAUDE_MODEL (default claude-opus-5-5) at high effort, streamed, with the server-side refusal fallback on. It takes a minute or two and costs roughly $0.10 to $0.60. The request only starts a background job (see "Background jobs"), because nginx gives up after 120 seconds; the page polls. Token usage is logged as [claude] lines and kept in the spend ledger (see "Claude spend").
  • Statements. LeetCode and USACO can be fetched. Codeforces sits behind a Cloudflare challenge, and other judges are unknown, so paste those.

Concepts

/usaco/concepts is a library of techniques Claude explained, each with a C++ snippet to reuse. Anyone can read it; the admin asks for new ones there, by topic ("help explain fenwick trees") or by pasting code they could not follow.

  • Output. A JSON-schema reply (internal/concept Schema): a slug, title, one-line summary and tags, then the intuition, how it works, a walkthrough with SVG diagrams, complexity, when to reach for it, pitfalls, variations, the snippet and a usage example. Given code, the walkthrough traces that code and the snippet is a general version of it. It shares the explanation prompt's math and diagram rules (explain.MathRules, explain.DiagramRules), so the page renders it with the same Explanation component.
  • Storage. concepts/<slug>/concept.md (first line <!-- concept tags=… -->, then a # title), snippet.cpp (first line // concept: <slug>) and request.md (the question, so the concept can be rewritten from it). Committed as "Explain concept ".
  • Slugs. Claude names the concept and is shown the saved ones. A new question never overwrites a saved concept: a taken slug gets -2, -3… Rewriting one (with a note on what to change) is its own button on the concept's page.
  • Reuse. The page has a copy button, and usaco snippet <slug> <problem> pastes the snippet into a solution above main.
  • The call. As for explanations: a background job the page polls, a minute or two, a similar cost.

Recording reviews

The "Review my explanation" panel (admin only) takes a recording of the admin explaining a solution out loud, as to an interviewer, and commits feedback on it as reviews/<id>.md. The id is the UTC time it started (2026-10-20-153000), so each attempt is its own file and the page lists them newest first.

  • Recording in the browser. Besides a file picker, the panel records from the microphone (AudioRecorder.vue, MediaRecorder at 32 kbps): webm/Opus in Chrome and Firefox, m4a in Safari, named with that extension because the server picks the format by it. A take stops itself just short of 25 MB (over an hour), and either kind of recording gets a player to check before sending. The microphone needs a secure context, so it works on the deployed HTTPS site and on localhost, not over plain HTTP on a LAN address.
  • Transcription. Claude cannot take audio, so the recording goes first to an OpenAI-compatible /v1/audio/transcriptions endpoint: TRANSCRIBE_URL (default the OpenAI API) with TRANSCRIBE_MODEL (default whisper-1, about $0.006 a minute). It asks for word and segment timestamps, and for a verbatim transcript, because Whisper otherwise drops the fillers. A self-hosted faster-whisper server works by changing the URL.
  • Metrics. Pace (words per minute), pauses of 2 seconds or more, filler-word counts and when complexity was first mentioned are measured from the timestamps (transcribe.Metrics), since Claude never hears the recording. It is told so, and judges delivery from the words and these numbers only, not tone.
  • Review. The statement, examples, optionally the main solution file, the admin's note, the metrics and the timestamped transcript go to Claude with a JSON schema (internal/review Schema): a verdict (correct, partly correct, incorrect, incomplete), a restatement, an assessment of the approach and complexities, missed edge cases, delivery feedback quoting [mm:ss], 1 to 5 scores in five areas, strengths and things to work on. The markdown ends with the metrics and the full transcript. Its first line is a <!-- review verdict=… audio=… --> comment the index reads.
  • The recording. It is too big for git. With all five S3_* variables set it is kept in that bucket as <name>/<id>.<ext> and the page gets a player; otherwise it is thrown away once transcribed. In web_server that is a private Garage bucket, never the public uploads one. A recording whose review could not be written is deleted again. One whose review was written but not committed stays with the unsaved review, until it is saved or a new recording replaces it.
  • Privacy. A review is a transcript of the admin talking, so reviews and their count are blanked for everyone else, even on solved problems.

Solve page

/usaco/p/<name>/solve (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Evaluate (Claude), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through driver.h.

  • The runner is its own service. The site holds the Claude, Gitea and S3 secrets and shares app-network with the database, so it never runs solutions. The one script it runs is the clone's lib/leetcode.py (the LeetCode import), with an environment holding none of those secrets (leetcode.scriptEnv). cmd/usacorunner does, in a container with no environment, on an internal network that only the site joins, read-only apart from an exec-able /tmp tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (runner.Client, RUNNER_URL); the browser never sees it.
  • Runs copy the CLI. The same g++ flags as lib/common.sh (-DLOCAL, with the repo root's debugging.h and leetcode.h, and a LeetCode problem's driver.h, sent along), the program runs in a directory holding <io>.in with that file also on stdin, <io>.out is its output if it wrote one, and outputs compare as usaco test does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s.
  • Autocomplete is in the browser (web/src/completions.js), since @codemirror/lang-cpp has none. C++ completes keywords, the STL, every name in the file (the template's macros show what they expand to, typedefs what they alias), members after . and ->, and snippets (for, forr, foreach, lambda, dfs, sortby...). Python adds the contest standard library (heapq, bisect, collections...) and members after . to lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file; clangd would, but it would need a session per editor next to the runner.
  • Vim keys are a checkbox in the toolbar (@replit/codemirror-vim), off by default and remembered in the browser. A status line under the editor shows the mode and the command being typed, and :w saves as Save does. Run and Submit keep their Ctrl+Enter keys in every mode.
  • Evaluate has Claude judge the code in the editor, as a strong competitive programmer would before submitting (internal/evaluate). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result is the job's, kept until the next evaluation of the problem. A statement it had to fetch is not saved either.
  • Lint. C++ is g++'s warnings plus clang-tidy with the repo's .clang-tidy (bugprone, performance and a few readability checks, tuned so template.cpp is clean); the runner embeds a copy, and a test keeps the two equal. Python is compile() for syntax errors plus ruff (E4,E7,E9,F,B). A missing tool is skipped. The runner image precompiles bits/stdc++.h for g++ and clang-tidy (internal/runner/pch.go), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22).

Background jobs

Explanations, concepts, reviews and evaluations take minutes, so each is a job (internal/jobs) that the page polls. One job runs per kind and key at a time: per problem, per concept slug, or per new-concept id.

  • Work, then save. A job that commits runs in two steps. The work (statement fetch, transcription, Claude) produces a draft, and the draft is written to $DATA_DIR/jobs/<kind>/<key>.json before the commit. If the commit fails (the push was rejected twice, or Gitea is down), the job ends as an error with unsaved: true, and the page offers Save again, which commits the same draft without asking Claude again.
  • Restarts. Records survive a restart, so a finished job's status and an evaluation's result are still there afterwards. On SIGTERM the server stops taking new jobs (503) and waits up to SHUTDOWN_GRACE (5m) for running ones, still answering the pages that poll them. web_server's stop_grace_period for usaco must be longer. A job cut off anyway is settled on the next start. Mid-commit, its draft is saved again once the first sync is done. Still at its work, it is marked as interrupted, and must be started again.
  • Records are pruned a week after they finish, unless they hold an unsaved draft.

Claude spend

Every Claude call is appended to $DATA_DIR/usage.jsonl (internal/usage) with its tokens and an estimated cost. The estimate uses the answering model's list price, which can be a fallback model. A refused or cut-off call is billed too, so it is recorded too. The stats page shows the admin this month's total, the months before it, and the split by feature. Transcription is not counted; it costs about $0.006 a minute.

CLAUDE_MONTHLY_BUDGET (dollars, unset for none) caps a calendar month (UTC). Once the month's estimate reaches it, new jobs are refused with 429 until the 1st. A job already running is never stopped, so a month can end slightly over.

Things that are easy to get wrong

  • BASE_PATH and Vite's base must agree. The SPA's asset URLs and router base are fixed at build time.
  • Edits must decide from disk, not the index. repo.Mutate may run an edit twice, the second time on a newer tip. The handlers re-locate the problem in the clone each time with findOnDisk.
  • problem.md is the judge's text. GET /problems/<name> blanks it for non-admins, so the public site links to the judge instead of republishing it.
  • A save func may run twice for one draft. A restart after the push but before the job's record says so resumes the save. Explanations and reviews rewrite the same file, so the second run commits nothing. A new concept looks for itself first (newConceptSlug).
  • Uploads are capped at 25 MB, the OpenAI API's limit. nginx's server-wide client_max_body_size 50M is above it; lowering that below 25M would turn big recordings into nginx 413s.
  • tests/*.out used to be gitignored by the root *.out rule. The root .gitignore now re-includes **/tests/*.out. A test whose expected output is shown as "Not saved." predates that change or never had one.