Compare commits

...
20 Commits
Author SHA1 Message Date
adamfandClaude Opus 5.5 7157c6649e CI: scratch directories per run, not per commit
Test and publish the site / test (push) Successful in 18s
Test and publish the site / publish (push) Successful in 8s
Test and publish the site / deploy (push) Successful in 1s
The build runner takes two jobs at once, so the same commit pushed to
two branches (main and a feature branch) ran its test job twice in
parallel against one src-<sha> directory, and each run's clean-up
deleted the other's source mid-test. Suffix the scratch directories
(and activity-tracker's throwaway Postgres and network) with the run id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:14:45 +00:00
adamfandClaude Opus 5.5 1ec6fb4f5a CI: test and publish on the build VM, deploy on stpvm
Test and publish the site / test (push) Successful in 5m28s
Test and publish the site / publish (push) Successful in 3m28s
Test and publish the site / deploy (push) Successful in 27s
test and publish (build, smoke test, push) move to stpbuild's runner
(label `build`); the two roll-out steps become a deploy job on stpvm
(`self-hosted`). The fetch is over HTTP with the job's own GITEA_TOKEN.

Also fix the roll-out's working directory: /home/adamf/deploy/web_server
no longer exists on stpvm; the stack lives in /home/adamf/deploy/stpweb.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:00:13 +00:00
adamfandClaude Opus 5.5 5ed1e0b89d CI: fetch from git.adam-french.co.uk instead of localhost
Test and publish the site / test (push) Successful in 1m40s
Test and publish the site / publish (push) Successful in 2m41s
Gitea runs on its own LXC, and stpvm's localhost:2222 forwarder to it is
being removed. stpvm pins git.adam-french.co.uk to the LXC's LAN IP in
/etc/hosts, so the self-hosted job reaches it directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:26:35 +00:00
adamf 89d604e076 wonderful strings 2026-10-29 22:51:38 +00:00
usaco site 88b634d82d Start palindromic-path-queries-in-a-tree 2026-10-29 12:46:22 +00:00
adamfandClaude Opus 5.5 cae5ec8e5a Keep site jobs across restarts, meter Claude spend, harden admin routes
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s
- 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
adamf 7638d88570 Refresh paper UI styling
Test and publish the site / test (push) Successful in 51s
Test and publish the site / publish (push) Successful in 1m39s
2026-10-23 20:00:46 +01:00
usaco site 19300d9b10 Start minimum-operations-to-sort-a-string 2026-10-21 11:14:19 +00:00
usaco site 1fd2bd7517 Explain concept lexicographic-greedy-construction 2026-10-20 18:21:40 +00:00
usaco site 5772093741 Explain concept complexity-budget-estimation 2026-10-20 13:58:35 +00:00
adamf a1a95c8963 Solved 2026-10-20 14:03:30 +01:00
adamfandClaude Opus 5.5 2ea9980d58 Add vim keys to the solve page's editor
Test and publish the site / test (push) Successful in 51s
Test and publish the site / publish (push) Successful in 1m16s
A Vim checkbox in the toolbar turns on @replit/codemirror-vim, off by
default and remembered in this browser like the split. A status line
under the editor shows the mode and the command being typed, and :w
saves as Save does. Run, Submit and Save keep their Ctrl keys in every
mode, since the page's keymap is at the highest precedence.

The vim extension sits in a Compartment, so turning it on or off keeps
the text and its history; the states kept for the other languages are
brought up to date when they are swapped back in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 14:00:29 +01:00
usaco site 20d2e05798 Explain count-vowel-substrings-of-a-string 2026-10-20 12:47:46 +00:00
usaco site f52fdfca0b Start count-vowel-substrings-of-a-string 2026-10-20 12:05:40 +00:00
adamfandClaude Opus 5.5 3a8f651a6f Import LeetCode problems from a pasted link on the site
Test and publish the site / test (push) Successful in 1m9s
Test and publish the site / publish (push) Successful in 1m31s
The problem list's admin row gains a link box beside "Today's LeetCode":
POST /leetcode/import takes {url} and does what `usaco new
<leetcode-link>` does, through the same lib/leetcode.py run and "Start
<slug>" commit as the daily question, then opens the solve page. A
problem already in the repo is only opened.

leetcode.Slug reads the link as slug_of in lib/leetcode.py does: full
links with /description/ and query strings, www., no scheme, or a bare
slug. Anything else is a 400.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 13:02:11 +01:00
adamfandClaude Opus 5.5 ccf4e4dd74 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]>
2026-10-20 12:58:38 +01:00
adamfandClaude Opus 5.5 d4849859df Autocomplete and evaluate solutions on the solve page
Test and publish the site / test (push) Successful in 1m25s
Test and publish the site / publish (push) Successful in 1m51s
The editor's completion popup was on but empty for C++, since
@codemirror/lang-cpp has no completion source. web/src/completions.js
adds one: keywords, the STL, every name in the file (the template's
macros show their expansion, typedefs what they alias), members after
. and ->, and snippets for the loops and lambdas typed over and over.
Python gains the contest standard library and members after ., on top
of lang-python's builtins and local names. Nothing knows types, so
members are the common ones plus those already used in the file.

Evaluate (POST/GET /problems/<name>/evaluate) has Claude judge the
editor's code as a strong competitive programmer would before
submitting. It runs the saved tests on the runner first, as Submit
does, and gives Claude the verdicts and up to three failing cases. The
reply is a verdict, correctness, complexity against the constraints,
line-anchored issues and a traced counterexample (internal/evaluate).
The page shows it in an Evaluation tab of the results panel, marks the
issues in the editor beside the lint's for as long as their lines are
unchanged, and can load the counterexample as the custom input.

It is a background job the page polls, like explanations, but it
commits nothing: the code is a draft. explain.Jobs.StartWith keeps a
finished job's answer in memory until the next one or a restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 12:46:54 +01:00
usaco site 34552f2d81 Explain sum-of-sortable-integers 2026-10-20 11:04:15 +00:00
usaco site 1e03936ad8 Edit sum-of-sortable-integers 2026-10-20 10:58:47 +00:00
usaco site f15ba26bda Start sum-of-sortable-integers 2026-10-20 10:58:27 +00:00
130 changed files with 7307 additions and 333 deletions
+41 -24
View File
@@ -1,10 +1,12 @@
# =============================================================================
# ci.yaml — test the site (site/) on every push that changes it; publish an
# image for such pushes to main that pass. Copied from job-tracker's ci.yaml,
# with the same runner and constraints: a self-hosted act_runner on the web_server
# host (stpvm) in HOST mode, with git and docker and no other toolchain. So Go and Node run
# in `docker run` containers, and the source is fetched with plain git rather
# than actions/checkout (which needs Node on the host).
# image for such pushes to main that pass. Copied from job-tracker's ci.yaml.
# test and publish run on the build VM's act_runner (stpbuild, label
# `build`); deploy runs on the stpweb host's (stpvm, `self-hosted`), the only
# one with the stack. Both are in HOST mode, with git and docker and no other
# toolchain. So Go and Node run in `docker run` containers, and the source is
# fetched with plain git rather than actions/checkout (which needs Node on
# the host).
#
# PATHS
# Most pushes here are problems ("Solve moocast", from the CLI or from the
@@ -12,16 +14,18 @@
# up through the Gitea webhook. Only changes to site/ or this workflow run
# it.
#
# TWO JOBS
# THREE JOBS
# test go vet + go test, and a vite build of site/web. The same checks
# as `make check` in site/.
# publish main only, after test: builds the two images, the site
# (Dockerfile) and its code runner (Dockerfile.runner), pushes
# each to this Gitea's container registry as :<sha> and :latest,
# then pulls them into the web_server stack (services
# `usaco-runner`, then `usaco`) and waits for each to be healthy —
# see "Deploying" in site/README.md. The runner goes first, so the
# new site never starts against an old runner.
# (Dockerfile) and its code runner (Dockerfile.runner),
# smoke-tests the runner image, and pushes each to this Gitea's
# container registry as :<sha> and :latest. It reuses test's git
# cache, so both must run on the same runner.
# deploy after publish, on stpvm: pulls them into the stpweb stack
# (services `usaco-runner`, then `usaco`) and waits for each to
# be healthy — see "Deploying" in site/README.md. The runner goes
# first, so the new site never starts against an old runner.
#
# SECRETS (repo settings -> Actions -> Secrets)
# REGISTRY_USER a Gitea user that can write packages for adamf
@@ -41,14 +45,18 @@ env:
jobs:
test:
runs-on: self-hosted
runs-on: build
env:
SHA: ${{ github.sha }}
REF: ${{ github.ref }}
REMOTE: ssh://git@localhost:2222/adamf/usaco.git
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
# Over HTTP with the job's own token (read access to this repo while
# the job runs), so the runner needs no SSH key or Gitea user.
REMOTE: http://git.adam-french.co.uk:3000/adamf/usaco.git
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
CACHE: /home/adamf/.cache/usaco-ci/repo.git
SRC: /home/adamf/.cache/usaco-ci/src-${{ github.sha }}
# Per run, not just per commit: the build runner takes two jobs at
# once, and the same commit pushed to two branches runs twice.
SRC: /home/adamf/.cache/usaco-ci/src-${{ github.sha }}-${{ github.run_id }}
steps:
- name: Export the pushed commit's site/ to a scratch directory
shell: bash
@@ -56,14 +64,19 @@ jobs:
set -eu
mkdir -p "$(dirname "$CACHE")"
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
# The job's token as a Basic auth header, passed via env rather
# than -c so it never shows in the process list.
auth=$(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)
GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: Basic $auth" \
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
rm -rf "$SRC"
mkdir -p "$SRC"
git --git-dir="$CACHE" archive --format=tar "$SHA" site | tar -x -C "$SRC"
test -f "$SRC/site/go.mod"
# Read-only source, and named volumes for the module and build
# caches, for the reasons given in web_server's deploy.yaml. git
# caches, for the reasons given in stpweb's deploy.yaml. git
# is installed because internal/repo and internal/index test
# against real repositories. internal/runner's tests compile and
# run C++ and Python with the image's g++ and python3 (it runs as
@@ -102,11 +115,11 @@ jobs:
publish:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: self-hosted
runs-on: build
env:
SHA: ${{ github.sha }}
CACHE: /home/adamf/.cache/usaco-ci/repo.git
SRC: /home/adamf/.cache/usaco-ci/publish-${{ github.sha }}
SRC: /home/adamf/.cache/usaco-ci/publish-${{ github.sha }}-${{ github.run_id }}
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
# The Dockerfile's `RUN --mount=type=cache` lines need BuildKit.
@@ -137,7 +150,7 @@ jobs:
shell: bash
run: |
set -eu
name="usaco-runner-ci-$SHA"
name="usaco-runner-ci-$SHA-${{ github.run_id }}"
docker run -d --name "$name" --read-only --tmpfs /tmp:size=256m,exec \
--memory 1g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges \
"$RUNNER_IMAGE:$SHA" >/dev/null
@@ -171,11 +184,15 @@ jobs:
shell: bash
run: rm -rf "$SRC"
deploy:
needs: publish
runs-on: self-hosted
steps:
# The runner first, the same way as the site below, so the new
# site never talks to an old runner. Pinning
# USACO_RUNNER_IMAGE_TAG in the site's .env makes this a no-op.
- name: Roll the runner onto the new image
working-directory: /home/adamf/deploy/web_server
working-directory: /home/adamf/deploy/stpweb
shell: bash
run: |
set -eu
@@ -192,11 +209,11 @@ jobs:
# Put the new image live, exactly as job-tracker's workflow does
# for `jobs`: pull + up of the one service, under .compose.lock, which
# web_server's deploy.yaml and maintenance.yaml hold, then wait for the
# stpweb's deploy.yaml and maintenance.yaml hold, then wait for the
# image's HEALTHCHECK (process up, repository cloned and indexed).
# Pinning USACO_IMAGE_TAG in the site's .env makes this a no-op.
- name: Roll the site onto the new image
working-directory: /home/adamf/deploy/web_server
working-directory: /home/adamf/deploy/stpweb
shell: bash
run: |
set -eu
+8
View File
@@ -13,6 +13,7 @@ site/ the website (Go server + Vue SPA), deployed as its own containe
solving/<name>/ problems in progress
solved/<name>/ finished problems
skipped/<name>/ problems set aside for later
concepts/<slug>/ techniques the website had Claude explain: concept.md, snippet.cpp, request.md
```
The website's CLI page (`site/web/src/views/CliPage.vue`) is a condensed copy of the Commands section below; keep it in step.
@@ -134,6 +135,13 @@ Opens from inside the problem dir, so the `.in`/`.out` files are right there.
```
`copy` auto-detects the clipboard tool: `wl-copy` on Wayland, then `xclip`/`xsel` on X11, and falls back to an OSC52 terminal escape that works even over SSH.
```
./usaco snippet # list the concepts explained on the website
./usaco snippet fenwick-tree # print its C++ snippet (pipeable; prefixes work)
./usaco snippet fenwick diamond-collector # paste it into the solution above main (alias: sn)
```
Pasting saves the old solution as `main.cpp.bak` and refuses a concept the solution already has (each snippet starts with a `// concept: <slug>` line). Run `usaco sync` first to pull concepts made on the website. In interactive mode, `snippet <concept>` pastes into the selected problem.
### Interactive mode
```
./usaco i # (aliases: interactive, repl)
@@ -0,0 +1,164 @@
<!-- concept tags=complexity,constraints,time-limit,contest-strategy -->
# Estimating TLE from constraints (operations budget)
_Predict TLE before coding: plug the maximum input sizes into your algorithm's complexity and compare with a budget of about 10^8 simple C++ operations per second; checking takes O(1) time._
_Explained by claude-opus-5-5 on 20 October 2026._
## Intuition
**The problem.** You have an idea for a solution. You want to know *before* coding it whether it will run inside the time limit. Otherwise you get **TLE** (Time Limit Exceeded), meaning the judge killed your program because it was too slow.
**Why "just try it" is wrong.** The sample tests are tiny, so any algorithm passes them instantly. The judge's hidden tests use the *maximum* sizes from the statement. An $O(n^2)$ loop on $n = 10^3$ is instant. The same loop on $n = 2\cdot 10^5$ needs about $4 \cdot 10^{10}$ steps, which takes minutes.
**The idea that fixes it.** Treat time as a budget of operations. A modern judge runs compiled C++ at roughly $10^8$–$10^9$ simple operations per second. The low end is safe, and the high end is only reached by very tight loops. So:
$$\text{ops}(n_{\max}) \le 10^8 \times \text{TL in seconds} \quad\Rightarrow\quad \text{safe}$$
Plug the **largest** allowed input into your algorithm's complexity, ignoring constants, and compare the result with the budget.
This works in reverse too. Problem setters choose the constraints so that the intended complexity just fits. **So the constraints tell you which algorithm they want.** For example, $n \le 20$ suggests something over all subsets, and $n \le 5000$ suggests $O(n^2)$.
## How it works
### The procedure, every time
1. **Find the worst case** from the constraints: the largest $n$, $m$, $q$, values and number of tests. Note any guarantee such as "sum of $n$ over all tests $\le 2\cdot 10^5$".
2. **Write your algorithm's cost as a formula** in those quantities, for example $q \log^2 n$ or $n \cdot m$. Count the work of every loop and every data-structure call.
3. **Plug in the numbers and compare with the budget** $B = 10^8 \times \text{TL}$:
- $\le B$: **safe**. Write it without worrying.
- between $B$ and $10 B$: **risky**. It passes only with simple loops, contiguous arrays and few `%` or divisions. It fails with `map`, `set`, recursion or heavy objects.
- $> 10 B$: **TLE**. Find a better algorithm.
### The reverse table: from $n$ to the complexity they expect
This table is the same rule solved for $n$. It assumes 1 second.
| max $n$ | intended complexity | operations at max |
|---|---|---|
| $\le 10$–$11$ | $O(n!)$, $O(n \cdot n!)$ | $\approx 4\cdot 10^7$ |
| $\le 20$ | $O(2^n \cdot n)$ bitmask DP | $\approx 2\cdot 10^7$ |
| $\le 40$ | $O(2^{n/2})$ meet in the middle | $\approx 10^6$ per half |
| $\le 100$ | $O(n^4)$ | $10^8$ |
| $\le 500$ | $O(n^3)$ | $1.25\cdot 10^8$ |
| $\le 5000$ | $O(n^2)$ | $2.5\cdot 10^7$ |
| $\le 10^5$ | $O(n\sqrt n)$, $O(n \log^2 n)$ | $3\cdot 10^7$ |
| $\le 10^6$ | $O(n \log n)$ | $2\cdot 10^7$ |
| $\le 10^7$–$10^8$ | $O(n)$, often with a tiny constant | $10^7$–$10^8$ |
| $\le 10^{12}$ and up | $O(\sqrt n)$, $O(\log n)$, $O(1)$ | small |
Read it in both directions:
- "$n \le 5000$" almost shouts $O(n^2)$.
- "$n \le 20$" shouts subsets.
- "$n \le 10^{18}$" means you may not even loop to $n$.
### What counts as one "operation"
An operation is one cheap step: an addition, a comparison, an array read in cache.
- **Costly steps, each worth several operations:** `%` and `/` on `long long`, which are 20–40 cycles. Also cache misses from random memory access, and allocation inside loops.
- **Each call is $\log n$ operations with a big constant:** `set`, `map`, `priority_queue`, `lower_bound`.
- **Each call is $O(1)$ on average with a large constant:** `unordered_map`.
That is why the safe line is $10^8$, not the $10^9$ cycles a CPU actually runs.
### Measuring instead of guessing
If your estimate is in the risky zone, generate a maximum-size, worst-shaped test and time it. The `Timer` struct below does this. Leave yourself a 2× margin, because judges can be slower than your machine.
## Walkthrough
**Step 1.** **Read the constraints.** Suppose $n \le 2\cdot 10^5$, the time limit is 1 s, and there are up to $t = 10^4$ tests with $\sum n \le 2\cdot 10^5$.
The axis is logarithmic, so each tick is $100\times$ the previous one.
- The green dashed line is the safe budget, $10^8$.
- The red dashed line, $10^9$, is where even tight loops fail.
The blue bar is $n$ itself. Reading the input once is free.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 2.** **Try the brute force, $O(n^2)$.** Plugging in $n = 2\cdot 10^5$ gives $n^2 = 4 \cdot 10^{10}$. That is $400\times$ the safe budget, which means minutes of running time. Reject it before writing a line.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 3.** **Try sorting plus binary search, $O(n \log n)$.** Since $\log_2(2\cdot 10^5) \approx 18$, the cost is about $3.6\cdot 10^6$ operations. That is far under the budget, so even `set` or `map` constants are fine. This is very likely the intended complexity for $n = 2\cdot 10^5$.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><text x="110" y="187" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n log n</text><rect x="120" y="170" width="262" height="24" fill="#22c55e"/><text x="388" y="187" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">3.6e6</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 4.** **Try sqrt decomposition, $O(n\sqrt n)$.** Since $\sqrt{2\cdot 10^5} \approx 447$, the cost is about $9\cdot 10^7$, right at the safe line. It passes with plain arrays and tight loops, but can fail with heavy constants. This is the **risky zone**: measure a max test with `Timer` before submitting.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><text x="110" y="187" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n log n</text><rect x="120" y="170" width="262" height="24" fill="#22c55e"/><text x="388" y="187" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">3.6e6</text><text x="110" y="232" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n√n</text><rect x="120" y="215" width="318" height="24" fill="#f59e0b"/><text x="492" y="232" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">9e7</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 5.** **The multi-test trap.** The $O(n \log n)$ solution is correct, but suppose it calls `memset(cnt, 0, sizeof cnt)` on a 200 000-element array in every test. That costs $t \cdot 2\cdot 10^5 = 2\cdot 10^9$, which is TLE even though $\sum n$ is small.
Always add up the cost of anything that does not scale with that test's own $n$. Here the fix is to clear only the first $n$ entries.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">t = 1e4 tests, Σn = 2·10^5</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><text x="110" y="187" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n log n</text><rect x="120" y="170" width="262" height="24" fill="#22c55e"/><text x="388" y="187" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">3.6e6</text><text x="110" y="232" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n√n</text><rect x="120" y="215" width="318" height="24" fill="#f59e0b"/><text x="492" y="232" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">9e7</text><text x="110" y="277" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">t·memset</text><rect x="120" y="260" width="372" height="24" fill="#ef4444"/><text x="498" y="277" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e9</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
## Using it
```cpp
TimeBudget tb(1.0); // 1 second time limit
double n = 2e5, q = 2e5;
int a = tb.verdict(n * q); // 2 -> O(n*q) = 4e10, TLE
int b = tb.verdict(TimeBudget::nLogN(n)); // 0 -> 3.5e6, safe
int c = tb.verdict(TimeBudget::nSqrtN(n)); // 0 -> 8.9e7, safe but tight
int d = tb.verdict(TimeBudget::subsets(20));// 0 -> 2e7, bitmask DP fine
Timer t;
// solve(maxTest); // run on a generated worst-case input
cerr << t.ms() << " ms\n";
// Heuristic search that stops safely before a 2 s limit:
// while (t.ms() < 1800) { improve(); }
```
## Complexity
Reading the constraints and doing the arithmetic costs $O(1)$. It is a few multiplications that save you from writing the wrong solution.
- **`verdict` and the cost models:** $O(1)$ time and $O(1)$ memory. Each one is a formula.
- **`Timer`:** $O(1)$ per call. `steady_clock` reads are cheap, but in a tight search loop check the clock every ~1000 iterations rather than on every iteration.
- **Memory has its own budget, so check it too.** One `int` is 4 bytes and one `long long` is 8 bytes. A 256 MB limit holds about $6 \cdot 10^7$ ints or $3 \cdot 10^7$ long longs. So a $5000 \times 5000$ `long long` DP (200 MB) fits only barely, and a $10^4 \times 10^4$ one does not fit at all.
## When to reach for it
**Always, before coding.** It takes ten seconds and is the most useful habit in contests. Use it especially when:
- You have a working brute force and wonder whether it is enough. Many easy problems have $n \le 2000$, where $O(n^2)$ is fine, so it often is.
- You are stuck. Look at the constraints and read the intended complexity off the table. Then ask which known technique has that complexity:
- $O(n \log n)$ suggests sorting, segment trees or binary search.
- $O(2^n)$ suggests subsets or bitmask DP.
- $O(n^3)$ suggests interval DP or Floyd–Warshall.
- Two ideas compete. Pick the simplest one that fits the budget, not the asymptotically best one.
**Close alternatives:**
- **Measuring** with `Timer` on a generated max test. Prefer it when the estimate is in the risky zone ($10^8$–$10^9$) or when constants are unclear, such as hashing, recursion or heavy STL.
- **Thinking about memory** in the same way. Use it when the arrays are 2D or the DP tables are large.
- **Interpreted languages** like Python are about 30–100× slower. Divide the budget accordingly, to roughly $10^6$–$10^7$ per second.
## Pitfalls
- **Multiple test cases.** If $t \le 10^4$ and each $n \le 2\cdot 10^5$, check whether the statement guarantees $\sum n \le 2\cdot 10^5$. Without that guarantee even $O(n)$ per test is $2\cdot 10^9$. With it, anything that depends only on $n$ is fine.
- **Hidden per-test costs.** Even when $\sum n$ is bounded, `memset`, `vector(MAXN)` or a sieve redone inside each test costs $t \cdot \text{MAXN}$. Clear only the first $n$ entries, or build shared tables once before reading the tests.
- **Forgetting a factor.** $q$ queries each doing an $O(\log n)$ `set` operation inside an $O(\log n)$ binary search costs $q \log^2 n$, not $q \log n$. Multiply every nested level, including the cost of the library calls.
- **Several variables.** With an $n \times m$ grid and $q$ queries, the cost may be $n m$ (fine at $10^3 \times 10^3$) or $q \cdot n m$ (TLE). Plug in the maximum of each variable simultaneously, unless the statement says something like $n \cdot m \le 10^6$.
- **Constraints on values, not sizes.** $a_i \le 10^9$ forbids a counting array of size $\max a$, even when $n$ is small. Use sorting, coordinate compression or hashing instead.
- **Big constants.** `map`, `set`, `unordered_map`, recursion, `long long %` and `endl` (it flushes) can make a 'safe' $5\cdot 10^7$ run in 2 s.
- **Slow I/O.** Reading $10^6$ numbers with plain `cin` is slow. Add `ios::sync_with_stdio(false); cin.tie(nullptr);` and print `'\n'` instead of `endl`.
- **Average versus worst case.** Hash tables, naive quicksort and pivot-based tricks can be hacked with adversarial tests. Estimate with the worst case unless the randomness is your own.
- **Integer overflow in the estimate itself.** `n*n` with `int n = 2e5` overflows. Compute estimates in `double` or `long long`.
## Variations
- **Different time limits:** scale the budget linearly. With a 3 s limit you get about $3 \cdot 10^8$. A 0.5 s limit halves it, which often signals "no $\log$ factor, or a very light one".
- **Amortized costs:** add up the total work over the whole run, not the worst single step. For example, a two-pointer loop is $O(n)$ in total even though one step can move far, and DSU is close to $O(1)$ per operation.
- **Bitset speedup:** a `bitset<N>` operation processes 64 bits per machine word. That turns $O(n^2)$ or $O(n^3)$ into the same cost divided by 64, which is how $n = 2000$ cubic or $n = 5\cdot 10^4$ quadratic solutions pass.
- **Offline or sqrt tricks:** when $O(n \log n)$ is hard to find and $n \le 10^5$, the table says $O(n \sqrt n) \approx 3 \cdot 10^7$ is allowed. That is the budget behind Mo's algorithm and sqrt decomposition.
- **Recursion depth:** depth $10^6$ in DFS can overflow the stack. This is a memory limit rather than a time limit, but it is estimated the same way. Switch to an iterative version when the depth can reach $n \approx 10^5$–$10^6$.
- **Time-guarded heuristics:** in optimization or interactive problems, use `Timer` to search until about 90% of the time limit and then print the best answer found so far.
@@ -0,0 +1 @@
I woud like to know the TLE of a problem given its input array size (or any other kind of input)
@@ -0,0 +1,31 @@
// concept: complexity-budget-estimation
// Rough operations budget for C++: <= 1e8 simple ops per second is safe,
// up to ~1e9/s only for very tight loops, beyond that expect TLE.
struct TimeBudget {
double seconds; // time limit of the problem
explicit TimeBudget(double s = 1.0) : seconds(s) {}
// 0 = safe, 1 = risky (needs small constant), 2 = TLE. O(1).
int verdict(double ops) const {
if (ops <= 1e8 * seconds) return 0;
if (ops <= 1e9 * seconds) return 1;
return 2;
}
// Cost models for common complexities; n is a size (count), not an index. O(1) each.
static double lg(double n) { return max(1.0, log2(n)); }
static double nLogN(double n) { return n * lg(n); }
static double nSqrtN(double n) { return n * sqrt(n); }
static double subsets(double n) { return pow(2.0, n) * n; } // 2^n * n bitmask DP
static double perms(int n) { double f = 1; for (int i = 2; i <= n; i++) f *= i; return f * n; } // n! * n
};
// Wall-clock timer: time a max-size test locally, or stop a search before the limit.
struct Timer {
chrono::steady_clock::time_point st = chrono::steady_clock::now();
// Milliseconds since construction or last reset(). O(1).
double ms() const {
return chrono::duration<double, milli>(chrono::steady_clock::now() - st).count();
}
void reset() { st = chrono::steady_clock::now(); }
};
@@ -0,0 +1,207 @@
<!-- concept tags=greedy,strings,monotonic-stack,lexicographic -->
# Lexicographically largest answers: greedy construction
_Build the lexicographically largest answer position by position, at each step taking the largest choice that can still be completed. The classic instance is a monotonic stack that finds the largest length-k subsequence in O(n)._
_Explained by claude-opus-5-5 on 20 October 2026._
## Intuition
### The one fact everything rests on
Lexicographic order compares two sequences at their **first differing position**, and nothing after that position matters. So making position 1 as large as possible beats any improvement you could make later. Once position 1 is fixed, the same holds for position 2, and so on.
Every "lexicographically largest answer" problem therefore reduces to one rule:
$$\text{answer}_j = \max\{\, c : \text{the prefix } \text{answer}_1 \dots \text{answer}_{j-1}\, c \text{ can still be completed to a valid answer} \,\}$$
In words: decide positions left to right. At each one, take the largest choice that still leaves *some* way to finish.
### Why the obvious approaches fail
- **Enumerating all valid answers and taking the max** is exponential.
- **Greedy without a feasibility check**, meaning "just take the biggest thing now", walks into dead ends. For a length-$k$ subsequence of `cabde` with $k=3$, grabbing `e` first leaves nothing to fill the other two slots.
- **Sorting by a naive key** is also wrong. To build the largest number from the strings {9, 34, 3}, plain descending order gives `9343`, but the right answer is `9334`.
### What the real work is
The skill is building a **fast feasibility check**, and then often replacing "try every candidate per position" with a structure that finds the best feasible candidate directly. For subsequences that structure is a monotonic stack: one pass, $O(n)$ total.
### The edge case to watch
When lengths can differ, a proper prefix is *smaller*: `ab` < `abc`. So when length is free, "largest" also means "longer is better on ties", and "smallest" means "shorter is better".
## How it works
### The general recipe
1. **Pin down the order.** Decide whether the answer length is fixed or free, and whether you compare characters, integers or something else.
2. **Write a feasibility check.** `feasible(prefix)` answers whether some valid full answer starts with this prefix. It is usually a counting argument, such as "enough elements remain" or "enough copies of each letter remain". Sometimes it is a matching or a flow.
3. **Build the answer greedily.**
- For each position, try candidates from largest to smallest.
- Keep the first candidate that leaves the prefix feasible.
- Trying in that order guarantees the first one that works is the best one.
4. **Speed it up.**
- The naive cost is $O(L \cdot |\Sigma| \cdot T_{check})$.
- The usual fix is a structure that answers "largest feasible candidate" directly: a monotonic stack, a suffix maximum, a heap, or a segment tree over a window.
### The canonical case: the largest subsequence of length exactly $k$
**The window view.** For pick $j$ (0-based), the element must come from index $\text{last}+1$ up to $n-k+j$, where $\text{last}$ is the index of the previous pick. Going further right would leave too few elements for the remaining picks. Inside that window, take the maximum, choosing the leftmost copy if there are ties. This is correct but costs $O(nk)$.
**The stack view** does the same work in $O(n)$:
- `st` holds the current best prefix of the answer, built from `s[0..i-1]`, that can still be extended to length `k`.
- Before pushing `s[i]`, pop while all three hold:
- `!st.empty()` and `st.back() < s[i]`. Putting `s[i]` in the top's slot makes the answer larger at an *earlier* position, and that beats anything that happens later.
- `st.size()-1 + (n-i) >= k`.
- `st.size()-1` is how many elements would stay kept after the pop.
- `n-i` is how many elements remain to choose from, counting `s[i]` itself.
- If their sum drops below `k`, popping would make a length-`k` answer impossible. The top is then *forced* and must stay.
- Then push `s[i]` only if `st.size() < k`. If the stack is full, every pop was blocked by `st.back() >= s[i]`. Since `n-i >= 1`, the counting condition holds whenever the stack is full, so it cannot be what blocked the pop. Skipping `s[i]` therefore loses nothing.
**Why the stack is correct (exchange argument).**
- Suppose the final answer keeps `x` at some slot, and a later element `c > x` could have taken that slot with enough elements left over.
- Then the answer with `c` in that slot is strictly larger, which contradicts optimality.
- The stack makes exactly that swap whenever it is legal, and only when it is legal.
### Other shapes of the same rule
- **Largest number from concatenating strings:** sort with the comparator `a+b > b+a`. Putting `a` before `b` is better exactly when that concatenation wins at the first difference.
- **Largest topological order:** run Kahn's algorithm with a max-heap, always taking the largest available vertex.
- **Largest permutation with at most $k$ swaps:** walk left to right and swap the largest remaining value into the current position.
## Walkthrough
**Step 1.** **The greedy rule, by windows.**
- The task: the largest subsequence of length $k=3$ of `s = cabde`, with $n=5$.
- Pick 1 must leave 2 elements after it, so it comes from indices $[0, n-k] = [0,2]$. The maximum there is `c`.
- Pick 2 comes from $[1,3]$, giving `d`. Pick 3 comes from $[4,4]$, giving `e`.
- The answer is `cde`.
This is correct but costs $O(nk)$. The stack in the next steps reaches the same answer in one pass.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#f59e0b' fill-opacity='0.35' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#f59e0b' fill-opacity='0.35' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M60 110 v8 h184 v-8' fill='none' stroke='#f59e0b' stroke-width='2'/><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='160'>pick 1: window [0,2] → max c at 0</text><text x='20' y='188'>pick 2: window [1,3] → max d at 3</text><text x='20' y='216'>pick 3: window [4,4] → e</text><text x='20' y='256'>answer = cde (k = 3, n = 5)</text></g></svg>
```
**Step 2.** **Stack pass, i = 0 and i = 1.**
- At $i=0$ the stack is empty, so `c` is pushed.
- At $i=1$ the top is `c` and the current element is `a`. Since `c` ≥ `a`, the condition `st.back() < s[i]` fails and nothing is popped.
- The stack has room ($2 < k$), so `a` is pushed.
The stack is now `[c, a]`. It is the best prefix of the answer so far that can still be completed.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M152 112 l-7 12 h14 z' fill='#3b82f6'/><text x='152' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='none' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>a</text></g><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>i=0: push c</text><text x='20' y='306'>i=1: top c ≥ a → no pop, push a</text></g></svg>
```
**Step 3.** **i = 2, current `b`.**
- The top `a` is smaller than `b`.
- Counting check: `st.size()-1 + (n-i)` = $1 + 3 = 4 \ge 3$, so enough elements remain without `a`. Pop `a`.
- The new top is `c`, and `c` ≥ `b`, so popping stops.
- Push `b`. The stack is `[c, b]`.
Slot 2 got upgraded from `a` to `b`, and that beats anything later positions could do.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='none' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M216 112 l-7 12 h14 z' fill='#3b82f6'/><text x='216' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='none' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='400' y='200' width='56' height='44' fill='none' stroke='#ef4444' stroke-width='2' stroke-dasharray='5 3'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>b</text><text x='428' y='229'>a</text></g><text x='470' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>popped</text><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>a &lt; b and 1 + 3 = 4 ≥ 3 → pop a</text><text x='20' y='306'>c ≥ b → stop, push b</text></g></svg>
```
**Step 4.** **i = 3, current `d`.**
- The top `b` < `d`, and $1 + 2 = 3 \ge 3$, so pop `b`.
- Now the top `c` < `d` too, but the check gives $0 + 2 = 2 < 3$.
- Dropping `c` would leave only `d` and `e`, too few for length 3.
- So `c` is **forced** and stays. This is exactly why the greedy cannot simply start with `d`.
- Push `d`. The stack is `[c, d]`.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='none' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M280 112 l-7 12 h14 z' fill='#3b82f6'/><text x='280' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='#f59e0b' fill-opacity='0.35' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><rect x='400' y='200' width='56' height='44' fill='none' stroke='#ef4444' stroke-width='2' stroke-dasharray='5 3'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>d</text><text x='428' y='229'>b</text></g><text x='470' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>popped</text><text x='100' y='190' font-family='sans-serif' font-size='13' fill='currentColor'>forced</text><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>b &lt; d and 1 + 2 = 3 ≥ 3 → pop b</text><text x='20' y='306'>c &lt; d but 0 + 2 = 2 &lt; 3 → blocked, push d</text></g></svg>
```
**Step 5.** **i = 4, current `e`.**
- The top `d` < `e`, but the check gives $1 + 1 = 2 < 3$, so the pop is blocked.
- Push `e`. The stack is `[c, d, e]`.
- That matches the window greedy's answer, `cde`.
Every element was pushed once and popped at most once, so the pass is $O(n)$.
```svg
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 320'><text x='20' y='68' font-family='sans-serif' font-size='14' fill='currentColor'>s</text><rect x='60' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='124' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='188' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='252' y='40' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='316' y='40' width='56' height='44' fill='#3b82f6' fill-opacity='0.4' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='88' y='69'>c</text><text x='152' y='69'>a</text><text x='216' y='69'>b</text><text x='280' y='69'>d</text><text x='344' y='69'>e</text></g><g font-family='ui-monospace, monospace' font-size='13' fill='currentColor' text-anchor='middle'><text x='88' y='102'>0</text><text x='152' y='102'>1</text><text x='216' y='102'>2</text><text x='280' y='102'>3</text><text x='344' y='102'>4</text></g><path d='M344 112 l-7 12 h14 z' fill='#3b82f6'/><text x='344' y='142' font-family='ui-monospace, monospace' font-size='14' fill='currentColor' text-anchor='middle'>i</text><text x='20' y='228' font-family='sans-serif' font-size='14' fill='currentColor'>stack</text><rect x='100' y='200' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='164' y='200' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><rect x='228' y='200' width='56' height='44' fill='#22c55e' fill-opacity='0.45' stroke='currentColor'/><g font-family='ui-monospace, monospace' font-size='20' fill='currentColor' text-anchor='middle'><text x='128' y='229'>c</text><text x='192' y='229'>d</text><text x='256' y='229'>e</text></g><g font-family='sans-serif' font-size='14' fill='currentColor'><text x='20' y='282'>d &lt; e but 1 + 1 = 2 &lt; 3 → blocked, push e</text><text x='20' y='306'>result = cde</text></g></svg>
```
## Using it
```cpp
string s = "cabde";
string best = largestSubseq(s, 3); // "cde"
vector<int> a = {3, 9, 5, 9, 1};
vector<int> b = largestSubseq(a, 2); // {9, 9}
string num = largestConcat({"9", "34", "30", "5", "3"}); // "9534330"
// smallest subsequence of length k: reuse with negated values,
// or copy largestSubseq and flip < to >
```
## Complexity
- **Monotonic stack, `largestSubseq`:** $O(n)$ time. Each element is pushed at most once and popped at most once, so the inner `while` runs at most $n$ times in total. Memory is $O(n)$ for the stack, and at most $k$ elements are kept.
- **Generic position-by-position greedy:** $O(L \cdot |\Sigma| \cdot T_{check})$ time, where $L$ is the answer length, $|\Sigma|$ is the number of candidates per position and $T_{check}$ is the cost of one feasibility check. Use [complexity-budget-estimation] to decide whether it fits or needs a faster check.
- **Window-max version:** $O(k \log n)$ time with a segment tree or sparse table, or $O(n)$ with a monotonic deque.
- **`largestConcat`:** $O(n \log n \cdot \ell)$ time, where $\ell$ is the string length, because each comparison builds two concatenations.
## When to reach for it
### Signals in the statement
- "Lexicographically largest/smallest", "maximum number you can form", "print the answer that comes first in dictionary order", or "if there are multiple answers, print the lexicographically smallest".
- The answer is a sequence built under constraints: pick a subsequence, delete some characters, order some items, or assign values position by position.
### The decision process
1. Can you check "is this prefix completable?" quickly? If so, the position-by-position greedy works.
2. Is it a subsequence with a length or count constraint? Use the **monotonic stack**.
3. Is it an ordering of pieces? Use a **sort with a pairwise comparator**, such as `a+b > b+a`.
4. Is it an ordering with precedence constraints? Use **Kahn's algorithm with a heap**.
5. Is the choice per position a range maximum over a sliding window? Use a **sparse table, segment tree or deque**.
### Close alternatives
- **DP plus reconstruction.** When feasibility itself needs DP, as in the lexicographically smallest LCS or path, first compute `can[i][state]` or `best[i]` from the back. Then walk forward and pick the smallest or largest option whose DP value is still optimal.
- **Suffix arrays or hashing.** When you must compare long candidate substrings quickly rather than build an answer, as in the largest rotation or the largest substring.
- **Binary search on the answer.** Usable only when the objective is a number. Lexicographic order on sequences is not a single numeric threshold.
## Pitfalls
- **Ignoring the prefix rule.** `"ab" < "abc"`. If the answer length is free, a largest answer should keep tied elements, so pop only on strict `<`. A smallest answer, by contrast, prefers stopping early.
- **Comparing numbers as strings or strings as numbers.** `"9" > "10"` as strings, while `9 < 10` as ints. Know which order the problem means, and use `vector<int>` for integer sequences.
- **Off-by-one in the counting check.** `n-i` must count `s[i]` itself, and `st.size()-1` is the count *after* the pop. Writing `n-i-1` or `st.size()` either blocks valid pops or allows answers shorter than `k`.
- **Forgetting the push cap `st.size() < k`.** Without it the stack returns more than `k` elements.
- **Greedy with no feasibility check.** Taking the biggest element now can make the rest of the answer impossible. Always ask: can I still finish?
- **Non-strict comparator in `sort`.** Using `a+b >= b+a` breaks strict weak ordering, which is undefined behaviour and can crash. Use a strict `>`.
- **Topological-order trap.** A max-heap Kahn gives the lexicographically largest *sequence*. "Give the smallest labels to the earliest positions" is a different objective: reverse the graph, use a max-heap, and reverse the result.
- **Tie-breaking in the window greedy.** When the maximum appears several times in a window, take the **leftmost** copy. That leaves the most room for the later picks.
- **Multi-test reset.** Clear the stack, count arrays and `inStack` flags between test cases.
## Variations
- **Smallest instead of largest:** flip the comparison in the pop condition to `st.back() > s[i]`. This is "Remove K Digits": keep $n-k$ digits, then strip leading zeros if the problem asks.
- **Length is free:** drop the counting check and the push cap. Pop while `st.back() < s[i]`, then always push. The result is the non-increasing chain of suffix maxima, with ties kept because longer wins on ties.
- **Each distinct letter exactly once** (largest or smallest such subsequence):
- Precompute `last[c]`, the last index of each letter, and keep an `inStack[c]` flag.
- Skip a letter if it is already in the stack.
- Pop the top only if it is beaten and `last[top] > i`, meaning it appears again later.
- **Elements from two arrays, keeping each one's internal order** ("Create Maximum Number"):
- For each split $k = k_1 + k_2$, take `largestSubseq` of both arrays.
- Merge them greedily, at each step taking from whichever *remaining suffix* is lexicographically larger.
- **General per-position constraint:** use the window form. Each pick is a range-maximum query over the allowed indices, so a sparse table or segment tree gives $O(k \log n)$. A monotonic deque works when the window only slides right.
- **Largest permutation or topological order:** use a max-heap of currently available elements, as in Kahn's algorithm. For "largest with at most $k$ swaps", keep a position map so you can swap the largest remaining value forward.
- **Expensive feasibility:** if feasibility is monotone in the candidate, binary search the largest feasible value for each position instead of trying every candidate.
@@ -0,0 +1 @@
What do I need to know about questions that include finding the lexicographically largest answer
@@ -0,0 +1,21 @@
// concept: lexicographic-greedy-construction
// Lexicographically largest subsequence of exactly k elements (k <= n). O(n). 0-based.
// Works for string or vector<T>. For the smallest, flip `<` to `>`.
template<class S> S largestSubseq(const S& s, int k) {
S st; int n = s.size();
for (int i = 0; i < n; i++) {
// pop if top is smaller and we can still reach length k without it
while (!st.empty() && st.back() < s[i] && (int)st.size() - 1 + (n - i) >= k)
st.pop_back();
if ((int)st.size() < k) st.push_back(s[i]);
}
return st;
}
// Largest string obtainable by concatenating all pieces in some order. O(n log n * len).
string largestConcat(vector<string> v) {
sort(v.begin(), v.end(), [](const string& a, const string& b) { return a + b > b + a; });
string r;
for (auto& x : v) r += x;
return r;
}
+9 -1
View File
@@ -12,7 +12,7 @@ WITH_PROBLEM="run build test done undo skip io cat copy edit open path reset"
# commands that take no problem
NO_PROBLEM="list stats clean sync lang"
# REPL-only words (used for completion and for 'help')
REPL_WORDS="s use none push pop stack help quit exit"
REPL_WORDS="s use none push pop stack help quit exit snippet"
cur=""
[[ -r "$CURRENT_FILE" ]] && cur="$(<"$CURRENT_FILE")"
@@ -72,6 +72,8 @@ ${DIM}problem commands${RST} ${DIM}(name optional — omit it to use the selecti
${DIM}other${RST}
$NO_PROBLEM, new <name> [io] [--rust|--cpp], new <leetcode-url|daily>
lint [<name>] clippy the selection, or every rust solution
snippet [<concept> [<name>]]
list concepts, or paste one's C++ into the selection
help [<cmd>] this, or the dispatcher's usage line for <cmd>
!cmd run a shell command in the problem dir
q quit
@@ -142,6 +144,12 @@ while :; do
if USACO_CREATED="$created" "$ROOT/usaco" new "${args[@]}"; then set_current "$(<"$created")"; fi
rm -f "$created"
continue ;;
snippet|sn)
# 'snippet <concept>' pastes into the selection; a second word
# names the problem, and none lists the concepts
[[ ${#args[@]} -eq 1 && -n "$cur" ]] && args+=("$cur")
"$ROOT/usaco" snippet "${args[@]+"${args[@]}"}" || true
continue ;;
lint)
# the one command whose problem name is optional: it lints the
# selection if there is one, otherwise every rust solution
+43
View File
@@ -0,0 +1,43 @@
# usaco snippet [<concept> [<problem>]]
# Concepts are techniques the website had Claude explain, under
# concepts/<slug>/ (pull with 'usaco sync' first). Their snippet.cpp starts
# with a "// concept: <slug>" line, which is how a solution that already has
# one is recognised.
if [[ $# -eq 0 ]]; then # list them
shopt -s nullglob
found=""
for d in "$ROOT"/concepts/*/; do
d="${d%/}"; [[ -f "$d/snippet.cpp" ]] || continue
found=1
title="$(concept_title "$d")"
printf ' %-28s %s\n' "$(basename "$d")" "${title:-}"
done
[[ -n "$found" ]] || echo "No concepts yet: explain one on the website, then 'usaco sync'."
exit 0
fi
cdir="$(find_concept "$1")"
snip="$cdir/snippet.cpp"
[[ -f "$snip" ]] || { echo "Error: ${cdir#$ROOT/} has no snippet.cpp" >&2; exit 1; }
if [[ $# -eq 1 ]]; then cat "$snip"; exit 0; fi
dir="$(find_problem "$2")"
main="$(main_file "$dir")"
[[ "$main" == *.cpp ]] || { echo "Error: snippets are C++, and $(basename "$dir") is $(lang_of "$dir")" >&2; exit 1; }
marker="$(head -n 1 "$snip")"
if grep -qxF "$marker" "$main"; then
echo "$(basename "$dir") already has $(basename "$cdir")" >&2; exit 1
fi
cp "$main" "$main.bak"
# Above main (or LeetCode's class Solution), so the solution can call it;
# at the end if neither is there.
awk -v snip="$snip" '
!done && /^(int|signed) main\(|^class Solution/ {
while ((getline l < snip) > 0) print l
print ""
done = 1
}
{ print }
END {
if (!done) { print ""; while ((getline l < snip) > 0) print l }
}' "$main.bak" > "$main"
echo "Added $(basename "$cdir") to ${main#$ROOT/} (old one in $(basename "$main").bak)"
+21
View File
@@ -60,6 +60,27 @@ find_problem() { # echoes dir of problem in solving/, solved/, or skipped/; uni
return 1
}
find_concept() { # echoes dir of concepts/<slug>; unique prefix ok
local name="$1" d matches=()
if [[ -d "$ROOT/concepts/$name" ]]; then echo "$ROOT/concepts/$name"; return 0; fi
for d in "$ROOT/concepts/$name"*/; do
[[ -d "$d" ]] && matches+=("${d%/}")
done
if [[ ${#matches[@]} -eq 1 ]]; then echo "${matches[0]}"; return 0; fi
if [[ ${#matches[@]} -gt 1 ]]; then
echo "Error: '$name' is ambiguous:" >&2
printf ' %s\n' "${matches[@]#$ROOT/}" >&2
return 1
fi
echo "Error: concept '$name' not found in concepts/ (try 'usaco sync')" >&2
return 1
}
concept_title() { # $1 = concept dir: echoes the "# " title of its concept.md, if any
[[ -f "$1/concept.md" ]] || return 0
sed -n 's/^# //p' "$1/concept.md" | head -n 1
}
# ----- rust project model (for rust-analyzer / clippy) -----
# Problems are bare main.rs files with no manifest, and rust-analyzer only does
# real analysis -- type-aware diagnostics, clippy on save -- inside a cargo
+9 -1
View File
@@ -5,12 +5,16 @@
# --- Core -------------------------------------------------------------------
# URL prefix everything is served under. The SPA is built for /usaco.
BASE_PATH=
# The clone lives in $DATA_DIR/repo (default /data).
# The clone lives in $DATA_DIR/repo (default /data), beside the job records
# ($DATA_DIR/jobs) and the Claude spend ledger ($DATA_DIR/usage.jsonl).
DATA_DIR=
# Listen port (default 8080).
PORT=
# "true" enables gin debug logging, and is required for AUTH_MODE=dev.
DEV_MODE=
# How long a SIGTERM waits for running jobs before the server exits, a Go
# duration. Default 5m; the container's stop_grace_period must be longer.
SHUTDOWN_GRACE=
# --- Git --------------------------------------------------------------------
# What to clone. Production: http://gitea:3000/adamf/usaco.git (Gitea on the
@@ -47,6 +51,10 @@ AUTH_VALIDATE_URL=
CLAUDE_API_KEY=
# Model for explanations (default claude-opus-5-5).
CLAUDE_MODEL=
# Monthly cap on the estimated Claude spend, in dollars (e.g. 20). Once a
# calendar month (UTC) reaches it, new Claude jobs are refused until the 1st.
# Blank: no cap; spend is still recorded and shown on the stats page.
CLAUDE_MONTHLY_BUDGET=
# --- Recording reviews ------------------------------------------------------
# A review needs CLAUDE_API_KEY and a transcriber: anything that speaks
+9 -3
View File
@@ -14,11 +14,16 @@ cd web && npm run dev # SPA hot reload; proxies /usaco/api to localhost:8080
One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, all under `/usaco`. It is deployed as one container inside the `web_server` stack, behind its nginx. It has the same shape as `../job-tracker`, from which `internal/auth` and `handlers.SPA` were copied.
- **Git is the only store.** `internal/repo` owns the clone and serializes every git command. A sync is fetch + hard reset (the remote wins). `Mutate` does sync, edit, commit and push, and replays the edit once if the push is rejected. Its `onChange` callback (`Server.Reload`) rebuilds the index under the same lock.
- **Git is the only store** for content. `internal/repo` owns the clone and serializes every git command. A sync is fetch + hard reset (the remote wins). `Mutate` does sync, edit, commit and push, and replays the edit once if the push is rejected. Its `onChange` callback (`Server.Reload`) rebuilds the index under the same lock, when HEAD moved. Beside the clone, `DATA_DIR` holds only operational state: job records (`jobs/`) and the Claude spend ledger (`usage.jsonl`).
- **The index is an immutable snapshot**, swapped in through an `atomic.Pointer`. Handlers read `s.Index()` once per request.
- **Visibility is decided server-side.** Non-admins see only `solved/`, and an unsolved problem is a 404, not a 403. `auth.Forward` returns false for a request with no cookies without a network call. `problem.md` (the judge's statement) is admin-only even on solved problems.
- **Explanations run in the background.** `POST /explain` starts a job in `explain.Jobs` and returns 202; the job calls Claude (`internal/claude`, streamed, JSON schema) and commits `explain.md` through `Mutate`. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network.
- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job in its own `explain.Jobs`: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`) and commit `reviews/<id>.md`. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`.
- **Explanations run in the background.** `POST /explain` starts a job (`internal/jobs`, kind "explain", keyed by problem) and returns 202. The job's work calls Claude (`internal/claude`, streamed, JSON schema) and returns a draft; the kind's save func (`saveExplain`) commits `explain.md` through `Mutate`. The draft is on disk before the commit, so a failed commit is retried (`POST /jobs/<kind>/<key>/save`) and one a restart cut off is resumed (`Server.ResumeJobs`) without calling Claude again. Save funcs may therefore run twice for one draft. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network.
- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job of its own kind: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`), then `saveReview` commits `reviews/<id>.md`. An unsaved draft keeps its recording; `discardReview` deletes it when a new review replaces the draft. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`.
- **Concepts are the same shape, outside the problems.** `POST /concepts` has Claude explain a technique or pasted code (`internal/concept`) and commits `concepts/<slug>/` (explanation, C++ snippet, the request). The slug is Claude's, so a new concept's job is keyed by an id and returns `{slug}` as its `Result`; rewrites are keyed by slug. The index reads them into `Index.Concepts`, and they are public.
- **Evaluations are the same shape, but commit nothing.** `POST /evaluate` judges the solve page's draft: it runs the saved tests on the runner, then asks Claude (`internal/evaluate`). Its kind has no save func: the answer is the job's `Result`, kept in the job's record, and the page polls for it.
- **Claude calls are metered.** `claude.Client` records every call's tokens in `usage.Ledger`; `Server.claudeReady` refuses a new Claude job with 429 once `CLAUDE_MONTHLY_BUDGET` is spent. A nil ledger tracks nothing, which the tests use.
- **Admin writes are same-origin only.** `auth.SameOrigin` runs before `auth.Require` on the admin group and refuses a cross-origin browser request (403).
- **Code runs in a separate service, never in the site.** The solve page's run/lint handlers (`handlers/run.go`) read the problem from the clone (`Server.Dir`, not the index, which truncates) and post to `cmd/usacorunner` through `runner.Client`; `internal/runner/types.go` is the contract between them. Tests fake it with `handlers.Runner`. The runner's own tests run real g++/python3/clang-tidy/ruff and skip whichever is missing.
@@ -28,3 +33,4 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al
- **Edits look at the disk.** An edit func passed to `Mutate` may run twice, so it must locate the problem with `findOnDisk`, never from the index.
- **Commit subjects match the CLI's** (`lib/cmd/done.sh`): "Solve <name>" and so on.
- **The problem layout belongs to the CLI** in the repo root (`lib/`). When the CLI's layout changes, update `internal/index`.
- **Docs are tested.** `docs_test.go` fails when README.md's route table and `Routes` disagree, or when a `./usaco` command in the root README is missing from `CliPage.vue` (skipped in CI, which only has `site/`).
+57 -9
View File
@@ -7,6 +7,7 @@ The public face of this repo, served at `/usaco/` on adam-french.co.uk. It shows
- 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.
@@ -22,10 +23,13 @@ There is no database. The CLI's layout is the data model (see the root README.md
- `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.
- **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. The clone is a cache: the remote always wins.
**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
@@ -49,10 +53,12 @@ internal/index/ reads the clone into memory: problems, files, tests, git dat
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, imported by running the clone's lib/leetcode.py
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/
```
@@ -63,7 +69,7 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
| Path | Auth | What |
|---|---|---|
| `/usaco/`, `/usaco/p/<name>`, `/usaco/stats`, `/usaco/cli` | none | SPA |
| `/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 |
@@ -79,16 +85,31 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
| `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 <name>" |
| `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 <slug>", 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 <slug>" |
| `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
@@ -114,7 +135,7 @@ 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 only the clone, so deleting it is safe: the next start re-clones. The container runs as uid 1000, so run `chown 1000 usaco-data` on the host.
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
@@ -158,9 +179,19 @@ The Explain panel on a problem page (admin only) asks Claude for an intuitive ex
- **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, because nginx gives up after 120 seconds; the page polls. Token usage is logged as `[claude]` lines.
- **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 <slug>".
- **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.
@@ -169,22 +200,39 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex
- **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 fails is deleted again.
- **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), 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`.
`/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 code. `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.
- **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.
- **An explanation or review job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again).
- **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.
+66 -4
View File
@@ -14,10 +14,16 @@ package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/gin-gonic/gin"
@@ -26,9 +32,11 @@ import (
"adam-french.co.uk/usaco-site/internal/auth"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/handlers"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/repo"
"adam-french.co.uk/usaco-site/internal/runner"
"adam-french.co.uk/usaco-site/internal/transcribe"
"adam-french.co.uk/usaco-site/internal/usage"
)
func main() {
@@ -67,6 +75,7 @@ func main() {
log.Fatal("GIT_REMOTE_URL is not set")
}
var err error
srv := &handlers.Server{Checker: checker, WebhookSecret: os.Getenv("WEBHOOK_SECRET")}
if srv.WebhookSecret == "" {
log.Println("[webhook] WEBHOOK_SECRET is not set: the push hook is off, pulls happen on the interval only")
@@ -75,13 +84,33 @@ func main() {
// CLAUDE
// Optional: without a key the site runs as before and the Explain
// button answers 503.
// Every call's cost goes in a ledger beside the clone, and
// CLAUDE_MONTHLY_BUDGET (dollars) stops new jobs once a month has spent
// it.
budget := 0.0
if v := os.Getenv("CLAUDE_MONTHLY_BUDGET"); v != "" {
if budget, err = strconv.ParseFloat(v, 64); err != nil || budget < 0 {
log.Fatalf("CLAUDE_MONTHLY_BUDGET=%q is not a dollar amount", v)
}
}
ledger, err := usage.Open(filepath.Join(dataDir, "usage.jsonl"), budget)
if err != nil {
log.Fatal(err)
}
srv.Usage = ledger
if c, err := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL")); err == nil {
c.Ledger = ledger
srv.Claude = c
log.Printf("[claude] explanations use %s", c.Model())
log.Printf("[claude] explanations use %s; monthly budget %s", c.Model(), dollars(budget))
} else {
log.Printf("[claude] %v: explanations are off", err)
}
// JOBS
// Their records (and the drafts of answers not yet committed) are kept
// beside the clone, so a restart loses neither.
srv.Jobs = jobs.New(filepath.Join(dataDir, "jobs"))
// REVIEWS
// A recording needs a transcriber as well as Claude. OPENAI_API_KEY is
// accepted too, as the key most people already have under that name.
@@ -164,10 +193,41 @@ func main() {
r.NoRoute(handlers.SPA(staticDir, basePath))
addr := ":" + getenv("PORT", "8080")
log.Printf("listening on %s%s/", addr, basePath)
if err := r.Run(addr); err != nil {
log.Fatal(err)
hs := &http.Server{Addr: addr, Handler: r}
go func() {
log.Printf("listening on %s%s/", addr, basePath)
if err := hs.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
// SHUTDOWN
// A deploy stops the container with SIGTERM. Without a handler the
// process (PID 1, which has no default one) ignored it until Docker's
// SIGKILL, mid-job. Now the running jobs get SHUTDOWN_GRACE to finish,
// while the server keeps answering the pages that poll them and turns
// new jobs away; the compose file's stop_grace_period must be longer.
// A job cut off anyway is settled by the next start (internal/jobs).
stop, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer cancel()
<-stop.Done()
grace := duration("SHUTDOWN_GRACE", 5*time.Minute)
log.Printf("[shutdown] waiting up to %s for running jobs", grace)
drain, undrain := context.WithTimeout(context.Background(), grace)
defer undrain()
if !srv.Jobs.Drain(drain.Done()) {
log.Println("[shutdown] jobs still running; they are settled on the next start")
}
ctx, done := context.WithTimeout(context.Background(), 10*time.Second)
defer done()
hs.Shutdown(ctx)
}
func dollars(budget float64) string {
if budget == 0 {
return "none"
}
return fmt.Sprintf("$%.2f", budget)
}
func syncLoop(rp *repo.Repo, srv *handlers.Server, trigger <-chan struct{}, interval time.Duration) {
@@ -183,6 +243,8 @@ func syncLoop(rp *repo.Repo, srv *handlers.Server, trigger <-chan struct{}, inte
for !pull() {
time.Sleep(30 * time.Second)
}
// Commits a restart interrupted need the clone, so they wait for it.
srv.ResumeJobs()
tick := time.NewTicker(interval)
defer tick.Stop()
for {
+86
View File
@@ -0,0 +1,86 @@
// Package docs_test checks the hand-written documentation against what it
// describes, so the two cannot drift apart unnoticed.
package docs_test
import (
"os"
"regexp"
"sort"
"strings"
"testing"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/handlers"
)
// README.md's route table lists every API route, and nothing else.
func TestReadmeRoutes(t *testing.T) {
b, err := os.ReadFile("README.md")
if err != nil {
t.Fatal(err)
}
row := regexp.MustCompile("(?m)^\\| `(GET|POST|PUT|DELETE) /usaco/api([^`?]*)")
param := regexp.MustCompile(`<([a-z]+)>`)
documented := map[string]bool{}
for _, m := range row.FindAllStringSubmatch(string(b), -1) {
documented[m[1]+" "+param.ReplaceAllString(m[2], ":$1")] = true
}
gin.SetMode(gin.TestMode)
r := gin.New()
(&handlers.Server{}).Routes(r.Group("/usaco/api"))
served := map[string]bool{}
for _, rt := range r.Routes() {
served[rt.Method+" "+strings.TrimPrefix(rt.Path, "/usaco/api")] = true
}
for _, missing := range diff(served, documented) {
t.Errorf("README.md's route table is missing %s", missing)
}
for _, stale := range diff(documented, served) {
t.Errorf("README.md documents %s, which is not served", stale)
}
}
// The CLI page (web/src/views/CliPage.vue) is a condensed copy of the root
// README's commands, since the image's build context cannot reach the
// README. Every command there must be on the page. CI exports only site/,
// so there this is skipped; `make check` in a full checkout runs it.
func TestCliPageCoversTheCommands(t *testing.T) {
readme, err := os.ReadFile("../README.md")
if os.IsNotExist(err) {
t.Skip("no root README (CI builds site/ alone)")
}
if err != nil {
t.Fatal(err)
}
page, err := os.ReadFile("web/src/views/CliPage.vue")
if err != nil {
t.Fatal(err)
}
// Commands the page gives as another one's alias.
aliases := map[string]string{"vim": "(also vim, edit)"}
for _, m := range regexp.MustCompile(`(?m)^\./usaco ([a-z]+)`).FindAllStringSubmatch(string(readme), -1) {
cmd := m[1]
want := "usaco " + cmd
if a, ok := aliases[cmd]; ok {
want = a
}
if !strings.Contains(string(page), want) {
t.Errorf("CliPage.vue does not mention %q (README.md has ./usaco %s)", want, cmd)
}
}
}
// diff is the keys of a that are not in b, sorted.
func diff(a, b map[string]bool) []string {
var out []string
for k := range a {
if !b[k] {
out = append(out, k)
}
}
sort.Strings(out)
return out
}
+57
View File
@@ -0,0 +1,57 @@
package auth
import (
"net/http"
"net/url"
"github.com/gin-gonic/gin"
)
// SameOrigin refuses a state-changing request that a browser made from
// another origin: cross-site request forgery.
//
// The admin is recognized by cookies alone, and the site's cookies are
// SameSite=Lax, which keeps them off another site's POST. That is the main
// defence; this is the second. Lax still sends them from any other origin of
// the same site (another subdomain of adam-french.co.uk), and the JSON
// handlers would decode a text/plain form body too, so the browser's own
// word on where a request came from is checked as well.
//
// Sec-Fetch-Site is set by every current browser and cannot be set by a
// page. An older browser sends Origin on a cross-origin POST instead, which
// must name this host (nginx passes the browser's Host through). A request
// with neither is not from a browser (curl, the tests), and so carries no
// one's cookies but its sender's.
//
// Same-origin pages are not told apart: Gitea, at /gitea/ on the same host,
// is trusted like this site's own pages.
func SameOrigin() gin.HandlerFunc {
return func(ctx *gin.Context) {
r := ctx.Request
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
ctx.Next()
return
}
if site := r.Header.Get("Sec-Fetch-Site"); site != "" {
// "none" is a request the user made themselves (the address
// bar), which a page cannot forge.
if site != "same-origin" && site != "none" {
refuse(ctx)
return
}
} else if origin := r.Header.Get("Origin"); origin != "" {
if u, err := url.Parse(origin); err != nil || u.Host != r.Host {
refuse(ctx)
return
}
}
ctx.Next()
}
}
// refuse is a 403, not the 401 that sends the page to the login: logging in
// would not help.
func refuse(ctx *gin.Context) {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin request refused"})
}
+43
View File
@@ -0,0 +1,43 @@
package auth
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestSameOrigin(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(SameOrigin())
r.Any("/x", func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
cases := []struct {
name, method string
headers map[string]string
want int
}{
{"same-origin fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-origin"}, 200},
{"typed in", "POST", map[string]string{"Sec-Fetch-Site": "none"}, 200},
{"sibling subdomain", "POST", map[string]string{"Sec-Fetch-Site": "same-site"}, 403},
{"another site", "PUT", map[string]string{"Sec-Fetch-Site": "cross-site", "Origin": "https://example.com"}, 403},
{"cross-site GET", "GET", map[string]string{"Sec-Fetch-Site": "cross-site"}, 200},
{"old browser, same host", "POST", map[string]string{"Origin": "https://adam-french.co.uk"}, 200},
{"old browser, other host", "DELETE", map[string]string{"Origin": "https://evil.adam-french.co.uk"}, 403},
{"not a browser", "POST", nil, 200},
}
for _, tc := range cases {
req := httptest.NewRequest(tc.method, "/x", nil)
req.Host = "adam-french.co.uk"
for k, v := range tc.headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Errorf("%s: %d, want %d", tc.name, rec.Code, tc.want)
}
}
}
+28
View File
@@ -16,10 +16,13 @@ import (
"errors"
"fmt"
"log"
"time"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/anthropics/anthropic-sdk-go/shared/constant"
"adam-french.co.uk/usaco-site/internal/usage"
)
// DefaultModel is used when CLAUDE_MODEL is blank.
@@ -40,6 +43,9 @@ func (f *Failure) Unwrap() error { return f.Err }
// Request is one call.
type Request struct {
// Tag names the feature making the call ("explain", "review"...) in
// the usage ledger.
Tag string
System string
User string
Schema map[string]any
@@ -50,6 +56,8 @@ type Request struct {
type Client struct {
api anthropic.Client
model string
// Ledger records what each call cost; nil records nothing.
Ledger *usage.Ledger
}
// New builds a client, or returns ErrNotConfigured for a blank key. opts
@@ -102,12 +110,20 @@ func (c *Client) JSON(ctx context.Context, req Request, out any) error {
}
}
if err := stream.Err(); err != nil {
// A stream that broke off partway was still billed for what it
// produced.
if msg.Usage.OutputTokens > 0 {
c.record(req.Tag, msg)
}
return apiFailure(err)
}
u := msg.Usage
log.Printf("[claude] %s: %d in (%d cached, %d written), %d out, stop %s",
msg.Model, u.InputTokens, u.CacheReadInputTokens, u.CacheCreationInputTokens, u.OutputTokens, msg.StopReason)
// Recorded before the stop reason is looked at: a refusal or a reply
// cut off at the length limit is billed all the same.
c.record(req.Tag, msg)
switch msg.StopReason {
case anthropic.BetaStopReasonRefusal:
@@ -128,6 +144,18 @@ func (c *Client) JSON(ctx context.Context, req Request, out any) error {
return &Failure{"Claude's reply was empty", errors.New("no text block")}
}
func (c *Client) record(tag string, msg anthropic.BetaMessage) {
u := msg.Usage
model := string(msg.Model)
if model == "" {
model = c.model
}
c.Ledger.Record(usage.Entry{
Time: time.Now(), Kind: tag, Model: model,
In: u.InputTokens, CacheRead: u.CacheReadInputTokens, CacheWrite: u.CacheCreationInputTokens, Out: u.OutputTokens,
})
}
func apiFailure(err error) error {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return &Failure{"Claude took too long", err}
+22
View File
@@ -8,10 +8,14 @@ import (
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/anthropics/anthropic-sdk-go/option"
"adam-french.co.uk/usaco-site/internal/usage"
)
// sse is a minimal streamed reply: one text block holding text.
@@ -111,3 +115,21 @@ func TestFailures(t *testing.T) {
}
}
}
// Every answered call is in the ledger, a refusal included: it is billed.
func TestLedger(t *testing.T) {
l, err := usage.Open(filepath.Join(t.TempDir(), "usage.jsonl"), 0)
if err != nil {
t.Fatal(err)
}
for _, stop := range []string{"end_turn", "refusal"} {
c := fake(t, 200, sse(`{"a":"hi"}`, stop), nil, nil)
c.Ledger = l
var out map[string]any
c.JSON(context.Background(), Request{Tag: "explain", System: "s", User: "u", Schema: map[string]any{}, MaxTokens: 10}, &out)
}
s := l.Summarize(time.Now())
if len(s.Kinds) != 1 || s.Kinds[0].Name != "explain" || s.Kinds[0].Calls != 2 || s.Month <= 0 {
t.Fatalf("summary = %+v", s)
}
}
+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{Tag: "concept", 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")
}
}
+322
View File
@@ -0,0 +1,322 @@
// Package evaluate has Claude judge the code in the solve page's editor, as
// a strong competitive programmer would before submitting it: is it right,
// is it fast enough for the constraints, which lines are wrong, and is
// there a small input that breaks it.
//
// The code is a draft, so unlike an explanation or a review nothing is
// committed. The answer is kept as the job's result with the source it judged
// (a jobs.Kind with no save), and the page anchors each issue to its line in
// the editor.
//
// Claude is given the saved tests' verdicts from the runner along with the
// code, because a test that fails is a fact it should not have to work out,
// and one that passes is evidence it can weigh.
package evaluate
import (
"context"
"fmt"
"strings"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/runner"
)
// Input is what Claude is told.
type Input struct {
Name string
Statement string
Examples []explain.Example
Lang string // runner.Cpp or runner.Python
Source string
LeetCode bool // the source is a class Solution run through driver.h
Note string // what the admin wants checked: "worried about overflow"
// Run is the saved tests' outcome, nil when they were not run; RunNote
// says why not.
Run *runner.RunResponse
RunNote string
}
// Issue is one problem in the code, anchored to a line of it.
type Issue struct {
Line int `json:"line"`
Severity string `json:"severity"`
Title string `json:"title"`
Detail string `json:"detail"`
}
// Counterexample is an input the code gets wrong; all blank when Claude has
// none it is sure of.
type Counterexample struct {
Input string `json:"input"`
Expected string `json:"expected"`
Why string `json:"why"`
}
// Result is the reply's shape; Schema is the same thing for the API.
type Result struct {
Verdict string `json:"verdict"`
Summary string `json:"summary"`
Correctness string `json:"correctness"`
Complexity string `json:"complexity"`
Issues []Issue `json:"issues"`
Counterexample Counterexample `json:"counterexample"`
Style string `json:"style"`
}
// Evaluation is what the job keeps and the page shows: the reply, and the
// source it is about, so the page can tell when the editor has moved on.
type Evaluation struct {
Result
Lang string `json:"lang"`
Source string `json:"source"`
Model string `json:"model"`
At time.Time `json:"at"`
// Tests is the run's one-line outcome ("3/4 passed"), or why there was
// none.
Tests string `json:"tests"`
}
// Verdicts, and how they read on the page.
var Verdicts = map[string]string{
"correct": "Looks correct",
"edge_cases": "Misses edge cases",
"wrong": "Wrong",
"too_slow": "Too slow",
"incomplete": "Unfinished",
}
func str(desc string) map[string]any { return 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{
"verdict": map[string]any{
"type": "string",
"enum": []string{"correct", "edge_cases", "wrong", "too_slow", "incomplete"},
"description": "correct: you expect it to be accepted. edge_cases: the idea is right but some inputs break it (overflow, empty input, an off-by-one at a boundary). " +
"wrong: the approach itself gives wrong answers. too_slow: right answers, but over the time or memory limit at the largest inputs. " +
"incomplete: it does not compile, or is not a full attempt yet. When several apply, pick the first of wrong, too_slow, edge_cases.",
},
"summary": str("Markdown, one or two sentences: what the code does, as an algorithm, so they can check it was read right."),
"correctness": str("Markdown. Why it is or is not correct. Account for every failing test. If it is wrong, say where the reasoning breaks; if it is right, give the argument briefly, especially for a greedy choice."),
"complexity": str("Markdown. Time and memory as written, against what the constraints allow, with a rough operation count at the largest input."),
"issues": map[string]any{
"type": "array",
"description": "Specific problems, most serious first: bugs, edge cases, overflow, undefined behaviour, needless slowness. Empty if there are none. Not style nitpicks.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"line": map[string]any{"type": "integer", "description": "The source line it is on, as numbered in <code>. 0 if it is about the program as a whole."},
"severity": map[string]any{"type": "string", "enum": []string{"error", "warning", "info"}, "description": "error: gives a wrong answer, crashes or times out on some valid input. warning: risky or fragile, but may be fine on this problem's tests. info: worth knowing, harmless here."},
"title": str("Plain text, under ten words: shown inline in the editor."),
"detail": str("Markdown. What goes wrong and on what input, and how to fix it. A corrected line or two is fine; never a whole solution."),
},
"required": []string{"line", "severity", "title", "detail"},
"additionalProperties": false,
},
},
"counterexample": map[string]any{
"type": "object",
"description": "A small input this code gets wrong, in exactly the problem's input format. All three blank unless you have traced the code on it and are sure.",
"properties": map[string]any{
"input": str("The input, exactly as the program would read it. Blank for none."),
"expected": str("The correct output for that input, worked out carefully. Blank for none."),
"why": str("Markdown, one or two sentences: what this code outputs instead, and why. Blank for none."),
},
"required": []string{"input", "expected", "why"},
"additionalProperties": false,
},
"style": str("Markdown, two to four sentences: readability and contest habits worth changing, if any. Blank if there is nothing worth saying."),
},
"required": []string{"verdict", "summary", "correctness", "complexity", "issues", "counterexample", "style"},
"additionalProperties": false,
}
// The reply is short; the rest is room for adaptive thinking, which is
// where the tracing happens.
const maxTokens = 24000
// System is the same on every call, so it is cached.
const System = `You are a strong competitive programmer reviewing someone's solution before they submit it. You get the problem, their code, and usually the verdicts from running it on their saved tests. Tell them whether it will be accepted and, if not, exactly why.
How to judge:
- Decide correctness yourself. Trace the code on the examples and on small cases you construct, especially the boundaries: minimum sizes, all-equal values, the largest values, an empty answer.
- The test verdicts are facts. A failing test proves a bug; explain every one. Passing tests are evidence, not proof: samples are small and weak.
- Check the complexity against the constraints in the statement. Assume about 10^8 simple operations per second in C++ and 10^7 in CPython.
- Look hard for what usually breaks accepted-looking code: int overflow where long long is needed, off-by-ones, state not reset between test cases, uninitialised values, out-of-bounds access, wrong output format, recursion depth (in Python especially), comparing floating point exactly, and slow I/O on big input.
- Read the code as written, not as intended. Code that is unfinished or does not compile is incomplete.
Their setup:
- C++ is built with g++ -std=c++17 -O2 -DLOCAL. LOCAL is defined only on their machine, never on the judge, so the DBG and print macros are no-ops there. Their template defines macros and typedefs such as ll, vi, pii, F(i, L, R) for (int i = L; i < R; i++), FE (<=), FD and FDE (counting down), ALL(c), SZ(c), pb, fi and se, REMAX and REMIN, takeI(n) (declares int n and reads it), takeL, takeV(v, n), whileZ (reads T and loops T times), YESNO(b), and STDIO(name), which reads name.in and writes name.out when run locally or on USACO. Treat these as ordinary code.
- A LeetCode problem's code is the class Solution only; a driver reads the tests and calls it, so judge the method, not I/O.
- Python reads with a tokens() helper over sys.stdin.buffer, and a stdio(name) helper redirects to name.in and name.out when that file exists.
How to answer:
- The code is shown with line numbers. Every issue names the line it is on, as numbered there, so it can be marked in their editor.
- Point at fixes; do not write their solution. A corrected line or two is fine.
- Give a counterexample only if you have traced the code on it and are sure it fails, and you have worked out the right answer. Keep it small, and in exactly the input format. Otherwise leave it blank.
- Be direct. If the code is right, say so plainly and keep the rest short; do not invent problems.
- Write in plain prose, using markdown for emphasis, lists and inline code, and LaTeX between $...$ for math such as complexities ($O(n \log n)$); the page typesets it with KaTeX.`
// Prompt is the user message.
func Prompt(in Input) string {
var b strings.Builder
fmt.Fprintf(&b, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
for i, ex := range in.Examples {
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
if ex.Out != "" {
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
}
b.WriteString("</example>\n")
}
kind := ""
if in.LeetCode {
kind = " leetcode=\"true\""
}
fmt.Fprintf(&b, "\n<code lang=%q%s>\n%s</code>\n", in.Lang, kind, numbered(in.Source))
b.WriteString("\n<test_run>\n" + runText(in.Run, in.RunNote) + "</test_run>\n")
if note := strings.TrimSpace(in.Note); note != "" {
fmt.Fprintf(&b, "\n<context>\n%s\n</context>\n", note)
}
b.WriteString("\nEvaluate my solution.")
return b.String()
}
// numbered prefixes each line with its number, right-aligned, as an editor
// gutter would show it.
func numbered(src string) string {
lines := strings.Split(strings.TrimRight(src, "\n"), "\n")
w := len(fmt.Sprint(len(lines)))
var b strings.Builder
for i, line := range lines {
fmt.Fprintf(&b, "%*d| %s\n", w, i+1, line)
}
return b.String()
}
// Caps on what a run puts in the prompt. A failing test bigger than
// maxCase is a stress test: its verdict is worth stating, its text is not.
const (
maxCase = 2 << 10
maxShown = 3
maxCompiler = 4 << 10
)
func runText(r *runner.RunResponse, note string) string {
if r == nil {
return note + "\n"
}
var b strings.Builder
if !r.Compile.OK {
b.WriteString("It did not compile:\n" + capped(r.Compile.Output, maxCompiler) + "\n")
return b.String()
}
if len(r.Results) == 0 {
return "It compiled. There are no saved tests to run.\n"
}
fmt.Fprintf(&b, "%s on the saved tests:\n", Outcome(r))
for _, t := range r.Results {
fmt.Fprintf(&b, "- test %s: %s in %d ms", t.Name, t.Verdict, t.TimeMs)
if t.Message != "" {
b.WriteString(" (" + t.Message + ")")
}
b.WriteString("\n")
}
shown := 0
for _, t := range r.Results {
if shown == maxShown {
break
}
if t.Verdict == runner.Accepted || t.Verdict == runner.Unchecked {
continue
}
shown++
fmt.Fprintf(&b, "\n<failed_test name=%q verdict=%q>\n", t.Name, t.Verdict)
if len(t.Input) > maxCase || (t.Expected != nil && len(*t.Expected) > maxCase) {
b.WriteString("(too big to show)\n</failed_test>\n")
continue
}
fmt.Fprintf(&b, "<input>\n%s\n</input>\n", strings.TrimRight(t.Input, "\n"))
if t.Expected != nil {
fmt.Fprintf(&b, "<expected>\n%s\n</expected>\n", strings.TrimRight(*t.Expected, "\n"))
}
fmt.Fprintf(&b, "<got>\n%s\n</got>\n", capped(strings.TrimRight(t.Output, "\n"), maxCase))
if t.Stderr != "" {
fmt.Fprintf(&b, "<stderr>\n%s\n</stderr>\n", capped(strings.TrimRight(t.Stderr, "\n"), maxCase))
}
b.WriteString("</failed_test>\n")
}
return b.String()
}
// Outcome is a run's one-line result: "3/4 passed", or "2 ran" when no
// test had an expected output.
func Outcome(r *runner.RunResponse) string {
if !r.Compile.OK {
return "did not compile"
}
passed, checked := 0, 0
for _, t := range r.Results {
if t.Verdict != runner.Unchecked {
checked++
}
if t.Verdict == runner.Accepted {
passed++
}
}
if checked == 0 {
return fmt.Sprintf("%d ran, unchecked", len(r.Results))
}
return fmt.Sprintf("%d/%d passed", passed, checked)
}
func capped(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "\n(cut)"
}
// Generate asks Claude and returns the evaluation.
func Generate(ctx context.Context, a explain.Asker, in Input, now time.Time) (*Evaluation, error) {
var r Result
err := a.JSON(ctx, claude.Request{Tag: "evaluate", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
if err != nil {
return nil, err
}
tests := in.RunNote
if in.Run != nil {
tests = Outcome(in.Run)
}
return &Evaluation{Result: clean(r, in.Source), Lang: in.Lang, Source: in.Source, Model: a.Model(), At: now, Tests: tests}, nil
}
// clean keeps the reply inside what the page can show: lines that exist,
// severities it knows, and a counterexample only when it is whole.
func clean(r Result, src string) Result {
lines := strings.Count(strings.TrimRight(src, "\n"), "\n") + 1
issues := []Issue{}
for _, is := range r.Issues {
if is.Line < 0 || is.Line > lines {
is.Line = 0
}
switch is.Severity {
case "error", "warning", "info":
default:
is.Severity = "info"
}
if strings.TrimSpace(is.Title) != "" || strings.TrimSpace(is.Detail) != "" {
issues = append(issues, is)
}
}
r.Issues = issues
if strings.TrimSpace(r.Counterexample.Input) == "" || strings.TrimSpace(r.Counterexample.Expected) == "" {
r.Counterexample = Counterexample{}
}
return r
}
+168
View File
@@ -0,0 +1,168 @@
package evaluate
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/runner"
)
func ptr(s string) *string { return &s }
func TestPrompt(t *testing.T) {
run := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{
{Name: "1", Verdict: runner.Accepted, TimeMs: 3},
{Name: "2", Verdict: runner.WrongAnswer, TimeMs: 4, Input: "2\n", Output: "5\n", Expected: ptr("4\n")},
{Name: "big", Verdict: runner.TimeLimit, TimeMs: 2000, Message: "exceeded 2s", Input: strings.Repeat("9 ", 2000)},
}}
p := Prompt(Input{
Name: "moocast", Statement: "# Moocast\n\nCows.", Lang: runner.Cpp,
Source: "int main() {\n return 0;\n}\n",
Examples: []explain.Example{{In: "1\n", Out: "2\n"}},
Note: " overflow? ",
Run: run,
})
for _, want := range []string{
"<problem name=\"moocast\">\n# Moocast\n\nCows.\n</problem>",
"<example n=\"1\">\n<input>\n1\n</input>\n<output>\n2\n</output>",
"<code lang=\"cpp\">\n1| int main() {\n2| return 0;\n3| }\n</code>",
"1/3 passed on the saved tests:\n- test 1: AC in 3 ms\n- test 2: WA in 4 ms\n- test big: TLE in 2000 ms (exceeded 2s)\n",
"<failed_test name=\"2\" verdict=\"WA\">\n<input>\n2\n</input>\n<expected>\n4\n</expected>\n<got>\n5\n</got>\n</failed_test>",
"<failed_test name=\"big\" verdict=\"TLE\">\n(too big to show)\n</failed_test>",
"<context>\noverflow?\n</context>",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
p = Prompt(Input{Name: "two-sum", Statement: "x", Lang: runner.Cpp, LeetCode: true, Source: "class Solution {};", RunNote: "The tests were not run: the code runner is not configured."})
for _, want := range []string{
"<code lang=\"cpp\" leetcode=\"true\">\n1| class Solution {};\n</code>",
"<test_run>\nThe tests were not run: the code runner is not configured.\n</test_run>",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
if strings.Contains(p, "<context>") {
t.Errorf("a blank note still made a context block:\n%s", p)
}
p = Prompt(Input{Name: "x", Lang: runner.Cpp, Source: "int main( {}", Run: &runner.RunResponse{Compile: runner.Compile{Output: "main.cpp:1: error"}}})
if !strings.Contains(p, "It did not compile:\nmain.cpp:1: error\n") {
t.Errorf("a compile error is not in the prompt:\n%s", p)
}
}
func TestNumberedPadsToTheWidestLine(t *testing.T) {
got := numbered(strings.Repeat("x\n", 10))
if !strings.HasPrefix(got, " 1| x\n") || !strings.HasSuffix(got, "10| x\n") {
t.Errorf("numbered = %q", got)
}
}
func TestOutcome(t *testing.T) {
r := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Verdict: runner.Unchecked}, {Verdict: runner.Unchecked}}}
if got := Outcome(r); got != "2 ran, unchecked" {
t.Errorf("Outcome = %q", got)
}
if got := Outcome(&runner.RunResponse{}); got != "did not compile" {
t.Errorf("Outcome = %q", got)
}
}
// fakeAsker answers with r.
type fakeAsker struct{ r Result }
func (fakeAsker) Model() string { return "fake-model" }
func (f fakeAsker) JSON(_ context.Context, _ claude.Request, out any) error {
*out.(*Result) = f.r
return nil
}
func TestGenerateCleansTheReply(t *testing.T) {
r := Result{
Verdict: "wrong",
Issues: []Issue{
{Line: 2, Severity: "error", Title: "Overflow"},
{Line: 99, Severity: "fatal", Title: "Past the end"},
{Line: 1, Severity: "info"},
},
Counterexample: Counterexample{Input: "3\n", Why: "no expected output"},
}
now := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)
run := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Verdict: runner.Accepted}}}
ev, err := Generate(context.Background(), fakeAsker{r}, Input{Lang: runner.Python, Source: "a\nb\n", Run: run}, now)
if err != nil {
t.Fatal(err)
}
want := []Issue{{Line: 2, Severity: "error", Title: "Overflow"}, {Line: 0, Severity: "info", Title: "Past the end"}}
if len(ev.Issues) != 2 || ev.Issues[0] != want[0] || ev.Issues[1] != want[1] {
t.Errorf("issues = %+v, want %+v", ev.Issues, want)
}
if ev.Counterexample != (Counterexample{}) {
t.Errorf("a counterexample with no expected output was kept: %+v", ev.Counterexample)
}
if ev.Lang != runner.Python || ev.Source != "a\nb\n" || ev.Model != "fake-model" || !ev.At.Equal(now) || ev.Tests != "1/1 passed" {
t.Errorf("evaluation = %+v", ev)
}
// The page reads the reply's fields at the top level, beside lang.
b, _ := json.Marshal(ev)
if !strings.Contains(string(b), `"verdict":"wrong"`) || !strings.Contains(string(b), `"lang":"python"`) {
t.Errorf("JSON = %s", b)
}
}
// Every property must be required and every object closed for structured
// outputs, and the Go struct must read every field the schema asks for.
func TestSchemaMatchesResult(t *testing.T) {
var check func(path string, s map[string]any)
check = func(path string, s map[string]any) {
if s["type"] == "array" {
check(path+"[]", s["items"].(map[string]any))
return
}
if s["type"] != "object" {
return
}
if s["additionalProperties"] != false {
t.Errorf("%s is not closed", path)
}
props := s["properties"].(map[string]any)
req := map[string]bool{}
for _, r := range s["required"].([]string) {
req[r] = true
}
for k, v := range props {
if !req[k] {
t.Errorf("%s.%s is not required", path, k)
}
check(path+"."+k, v.(map[string]any))
}
}
check("", Schema)
b, _ := json.Marshal(Result{Issues: []Issue{{}}})
var got map[string]any
json.Unmarshal(b, &got)
for k := range Schema["properties"].(map[string]any) {
if _, ok := got[k]; !ok {
t.Errorf("Result has no field for %q", k)
}
}
for v := range Verdicts {
found := false
for _, e := range Schema["properties"].(map[string]any)["verdict"].(map[string]any)["enum"].([]string) {
found = found || e == v
}
if !found {
t.Errorf("verdict %q is labelled but not in the schema", v)
}
}
}
+15 -6
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 {
@@ -138,7 +147,7 @@ func Prompt(in Input) string {
// Generate asks Claude and returns explain.md.
func Generate(ctx context.Context, a Asker, in Input, now time.Time) (string, error) {
var r Result
err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
err := a.JSON(ctx, claude.Request{Tag: "explain", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
if err != nil {
return "", err
}
+2 -33
View File
@@ -101,38 +101,7 @@ 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)
}
}
func TestJobsOneAtATime(t *testing.T) {
var j Jobs
if s := j.Get("a"); s.State != Idle {
t.Fatalf("fresh state = %q, want idle", s.State)
}
release := make(chan struct{})
if !j.Start("a", func() error { <-release; return nil }) {
t.Fatal("first start refused")
}
if j.Start("a", func() error { return nil }) {
t.Fatal("second start while running accepted")
}
if !j.Start("b", func() error { return context.Canceled }) {
t.Fatal("another problem's job refused")
}
close(release)
wait := func(name string) Status {
for range 200 {
if s := j.Get(name); s.State != Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatalf("%s still running", name)
return Status{}
}
if s := wait("a"); s.State != Done || s.Finished == nil {
t.Errorf("a = %+v, want done", s)
}
if s := wait("b"); s.State != Failed || s.Error != context.Canceled.Error() {
t.Errorf("b = %+v, want the error", s)
if !strings.Contains(System, MathRules) || !strings.Contains(System, DiagramRules) {
t.Error("System is missing the rules it shares with concepts")
}
}
-69
View File
@@ -1,69 +0,0 @@
package explain
import (
"sync"
"time"
)
// A job's states. Idle means nothing has run since the server started.
const (
Idle = "idle"
Running = "running"
Done = "done"
Failed = "error"
)
// Status is what the page polls for.
type Status struct {
State string `json:"state"`
Error string `json:"error,omitempty"`
Started *time.Time `json:"started,omitempty"`
Finished *time.Time `json:"finished,omitempty"`
}
// Jobs runs at most one explanation per problem at a time. An explanation
// takes a minute or more, longer than nginx waits for a response, so the
// request only starts it and the page polls. State is in memory: a restart
// mid-job loses the job, and nothing is committed until it finishes.
type Jobs struct {
mu sync.Mutex
m map[string]*Status
}
// Start runs fn in the background unless a job for name is running, and
// reports whether it started. fn's error is shown to the admin, so it must
// be a message meant for them.
func (j *Jobs) Start(name string, fn func() error) bool {
j.mu.Lock()
defer j.mu.Unlock()
if j.m == nil {
j.m = map[string]*Status{}
}
if s := j.m[name]; s != nil && s.State == Running {
return false
}
now := time.Now()
j.m[name] = &Status{State: Running, Started: &now}
go func() {
err := fn()
j.mu.Lock()
defer j.mu.Unlock()
end := time.Now()
s := &Status{State: Done, Started: &now, Finished: &end}
if err != nil {
s.State, s.Error = Failed, err.Error()
}
j.m[name] = s
}()
return true
}
// Get is name's latest job.
func (j *Jobs) Get(name string) Status {
j.mu.Lock()
defer j.mu.Unlock()
if s := j.m[name]; s != nil {
return *s
}
return Status{State: Idle}
}
+297
View File
@@ -0,0 +1,297 @@
package handlers
import (
"context"
"encoding/json"
"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.claudeReady(ctx) {
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 startJob(ctx, s.newConceptJobs, id, "that concept is already being explained", func() (any, error) { return s.writeConcept(in, "") }) {
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.claudeReady(ctx) {
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 startJob(ctx, s.conceptJobs, slug, "this concept is already being rewritten", func() (any, error) { return s.writeConcept(in, slug) }) {
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"`
}
// conceptDraft is a written concept waiting to be committed. Slug is set
// for a rewrite; a new concept's is picked when it is saved.
type conceptDraft struct {
Slug string `json:"slug,omitempty"`
Result concept.Result `json:"result"`
Topic string `json:"topic"`
Code string `json:"code,omitempty"`
Model string `json:"model"`
Written time.Time `json:"written"`
}
// writeConcept is one job's work: 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")
}
return conceptDraft{Slug: slug, Result: r, Topic: in.Topic, Code: in.Code, Model: s.Claude.Model(), Written: time.Now()}, nil
}
// saveConcept commits a concept and answers where it is now.
func (s *Server) saveConcept(raw json.RawMessage) (any, error) {
var d conceptDraft
if err := json.Unmarshal(raw, &d); err != nil {
return nil, err
}
slug, rewrite := d.Slug, d.Slug != ""
if !rewrite {
var saved bool
if slug, saved = newConceptSlug(s.Index(), d); saved {
return conceptResult{Slug: slug}, nil
}
}
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
files := concept.Files(d.Result, concept.Input{Topic: d.Topic, Code: d.Code}, slug, d.Model, d.Written)
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; saving again picks another.
return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; save again to pick another name", 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
}
// newConceptSlug is the name Claude gave the concept, or name-2, name-3...
// if a concept already has it: a new question never overwrites a saved
// concept, and rewriting one is its own request. saved reports that the
// concept under slug is this very draft (the same question, and the same
// snippet in Claude's own words), which a save run again after a restart that came after its push
// finds, and must not save a second time.
func newConceptSlug(idx *index.Index, d conceptDraft) (slug string, saved bool) {
want, req := d.Result.Slug, strings.TrimSpace(concept.Request(d.Topic, d.Code))
slug = want
for n := 2; ; n++ {
c, taken := idx.Concepts[slug]
if !taken {
return slug, false
}
if strings.TrimSpace(c.Request) == req && c.Snippet != nil &&
strings.TrimSpace(c.Snippet.Content) == strings.TrimSpace(concept.Snippet(d.Result.Snippet, slug)) {
return slug, true
}
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/jobs"
)
// 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) jobs.Status {
t.Helper()
for range 400 {
rec := do(r, "GET", path, "", true)
var s jobs.Status
json.Unmarshal(rec.Body.Bytes(), &s)
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatalf("%s still running", path)
return jobs.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 != jobs.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 != jobs.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")
}
}
+28 -3
View File
@@ -27,8 +27,6 @@ func (s *Server) leetcode() LeetCode {
// startDaily is `usaco daily`: it imports today's LeetCode daily question
// into solving/ and commits it, and answers its name for the page to open.
// A daily question already in the repo (started yesterday from the CLI, or
// solved months ago) is only named, never imported again.
func (s *Server) startDaily(ctx *gin.Context) {
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
@@ -44,6 +42,33 @@ func (s *Server) startDaily(ctx *gin.Context) {
ctx.JSON(http.StatusBadGateway, gin.H{"error": "LeetCode named the daily question " + slug + ", which is not a usable name"})
return
}
s.startLeetCode(ctx, c, lc, slug)
}
// startImport is `usaco new <leetcode-link>`: the same import, for the
// problem a pasted link names.
func (s *Server) startImport(ctx *gin.Context) {
var body struct {
URL string `json:"url"`
}
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
slug, err := leetcode.Slug(body.URL)
if err != nil || !validName.MatchString(slug) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "not a LeetCode problem link"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
s.startLeetCode(ctx, c, s.leetcode(), slug)
}
// startLeetCode imports slug into solving/, commits it as "Start <slug>" and
// answers {name, created}. A problem already in the repo (started yesterday
// from the CLI, or solved months ago) is only named, never imported again.
func (s *Server) startLeetCode(ctx *gin.Context, c context.Context, lc LeetCode, slug string) {
if idx := s.Index(); idx != nil {
if _, ok := idx.Problems[slug]; ok {
ctx.JSON(http.StatusOK, gin.H{"name": slug, "created": false})
@@ -51,7 +76,7 @@ func (s *Server) startDaily(ctx *gin.Context) {
}
}
created := false
err = s.Repo.Mutate(c, "Start "+slug, func(dir string) error {
err := s.Repo.Mutate(c, "Start "+slug, func(dir string) error {
if _, err := findOnDisk(dir, slug); err == nil {
created = false
return nil
+63
View File
@@ -84,3 +84,66 @@ func TestDailyImportFails(t *testing.T) {
t.Fatalf("daily = %d %s, commits %v", rec.Code, rec.Body, repo.msg)
}
}
func TestImportLink(t *testing.T) {
r, repo, _ := setup(t)
lc := &fakeLeetCode{}
repo.srv.LeetCode = lc
body := `{"url":"https://leetcode.com/problems/two-sum/description/?envType=problem-list-v2"}`
if rec := do(r, "POST", "/usaco/api/leetcode/import", body, false); rec.Code != 401 {
t.Fatalf("non-admin = %d, want 401", rec.Code)
}
rec := do(r, "POST", "/usaco/api/leetcode/import", body, true)
var got dailyReply
json.Unmarshal(rec.Body.Bytes(), &got)
if rec.Code != 200 || got != (dailyReply{"two-sum", true}) {
t.Fatalf("import = %d %s", rec.Code, rec.Body)
}
if len(repo.msg) != 1 || repo.msg[0] != "Start two-sum" {
t.Fatalf("commits = %v", repo.msg)
}
if _, ok := repo.srv.Index().Problems["two-sum"]; !ok {
t.Fatal("two-sum is not in the index after the import")
}
rec = do(r, "POST", "/usaco/api/leetcode/import", body, true)
got = dailyReply{}
json.Unmarshal(rec.Body.Bytes(), &got)
if rec.Code != 200 || got != (dailyReply{"two-sum", false}) || lc.imports != 1 {
t.Fatalf("second import = %d %s after %d imports", rec.Code, rec.Body, lc.imports)
}
}
func TestImportExisting(t *testing.T) {
r, repo, _ := setup(t)
lc := &fakeLeetCode{}
repo.srv.LeetCode = lc
rec := do(r, "POST", "/usaco/api/leetcode/import", `{"url":"https://leetcode.com/problems/moocast/"}`, true)
if rec.Code != 200 || lc.imports != 0 || len(repo.msg) != 0 {
t.Fatalf("import = %d %s, %d imports, commits %v", rec.Code, rec.Body, lc.imports, repo.msg)
}
}
func TestImportBadLink(t *testing.T) {
r, repo, _ := setup(t)
lc := &fakeLeetCode{}
repo.srv.LeetCode = lc
for _, body := range []string{`{"url":"https://codeforces.com/problemset/problem/1/A"}`, `{"url":""}`, `not json`} {
if rec := do(r, "POST", "/usaco/api/leetcode/import", body, true); rec.Code != 400 {
t.Fatalf("import %s = %d %s, want 400", body, rec.Code, rec.Body)
}
}
if lc.imports != 0 || len(repo.msg) != 0 {
t.Fatalf("%d imports, commits %v", lc.imports, repo.msg)
}
}
func TestImportFails(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.LeetCode = &fakeLeetCode{err: errors.New("LeetCode has no problem 'nope'")}
rec := do(r, "POST", "/usaco/api/leetcode/import", `{"url":"https://leetcode.com/problems/nope/"}`, true)
if rec.Code != 502 || len(repo.msg) != 0 {
t.Fatalf("import = %d %s, commits %v", rec.Code, rec.Body, repo.msg)
}
}
+114
View File
@@ -0,0 +1,114 @@
package handlers
import (
"context"
"errors"
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/runner"
)
// The saved tests run first and Claude takes a minute or two after.
const evaluateTimeout = 10 * time.Minute
// startEvaluate starts judging the editor's source and answers at once; the
// page polls evaluateStatus, whose result is the evaluation. Nothing is
// committed: the source is a draft, and the answer is about this version of
// it only.
func (s *Server) startEvaluate(ctx *gin.Context) {
if !s.claudeReady(ctx) {
return
}
body, p, l, ok := s.readCode(ctx)
if !ok {
return
}
if strings.TrimSpace(body.Source) == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"})
return
}
if len(body.Note) > maxNote {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"})
return
}
if strings.TrimSpace(p.Statement) == "" && p.URL == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"})
return
}
in := evaluate.Input{
Name: p.Name, Statement: p.Statement, Examples: examples(p),
Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note,
}
link := p.URL
if startJob(ctx, s.evalJobs, p.Name, "a solution is already being evaluated", func() (any, error) { return s.evaluate(in, link, l) }) {
ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name))
}
}
func (s *Server) evaluateStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.evalJobs.Get(p.Name))
}
}
// evaluate is one job. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) evaluate(in evaluate.Input, link string, l *layout) (*evaluate.Evaluation, error) {
ctx, cancel := context.WithTimeout(context.Background(), evaluateTimeout)
defer cancel()
name := in.Name
// A fetched statement is not saved: that would be the only commit an
// evaluation makes. Explain or Edit details keep one.
if _, err := s.ensureStatement(ctx, "evaluate", name, &in.Statement, link); err != nil {
return nil, err
}
in.Run, in.RunNote = s.evaluationRun(ctx, name, in.Lang, in.Source, l)
ev, err := evaluate.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[evaluate] %s: %s: %v", name, f.Msg, f.Err)
return nil, f
}
log.Printf("[evaluate] %s: %v", name, err)
return nil, errors.New("the evaluation could not be written")
}
return ev, nil
}
// evaluationRun is Submit's run, for Claude to read. A run that cannot
// happen costs the evaluation its test verdicts, not the evaluation: the
// note says why, and goes to Claude in their place.
func (s *Server) evaluationRun(ctx context.Context, name, lang, source string, l *layout) (*runner.RunResponse, string) {
if s.Runner == nil {
return nil, "The tests were not run: the code runner is not configured."
}
tests, err := readRunTests(l)
if err != nil {
log.Printf("[evaluate] %s: reading the tests: %v", name, err)
return nil, "The tests were not run: they could not be read."
}
files, err := s.headers(l, lang)
if err != nil {
log.Printf("[evaluate] %s: reading the headers: %v", name, err)
return nil, "The tests were not run: the headers could not be read."
}
c, cancel := context.WithTimeout(ctx, runTimeout)
defer cancel()
res, err := s.Runner.Run(c, runner.RunRequest{Lang: lang, Source: source, Files: files, IO: l.io, Tests: tests})
if err != nil {
log.Printf("[evaluate] %s: running the tests: %v", name, err)
return nil, "The tests were not run: the code runner failed."
}
return &res, ""
}
+146
View File
@@ -0,0 +1,146 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/jobs"
)
// fakeEvaluator flags line 1 of whatever it is shown, or fails.
type fakeEvaluator struct {
user string
fail bool
}
func (f *fakeEvaluator) Model() string { return "fake-model" }
func (f *fakeEvaluator) JSON(_ context.Context, req claude.Request, out any) error {
f.user = req.User
if f.fail {
return &claude.Failure{Msg: "Claude declined to answer"}
}
*out.(*evaluate.Result) = evaluate.Result{
Verdict: "edge_cases", Summary: "Prints zero.",
Issues: []evaluate.Issue{{Line: 1, Severity: "error", Title: "Never reads n"}},
}
return nil
}
type evalStatus struct {
State string `json:"state"`
Error string `json:"error"`
Result *evaluate.Evaluation `json:"result"`
}
func waitEvaluate(t *testing.T, r *gin.Engine, name string) evalStatus {
t.Helper()
for range 400 {
var s evalStatus
json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/evaluate", "", true).Body.Bytes(), &s)
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("evaluation still running")
return evalStatus{}
}
const evalBody = `{"lang":"cpp","source":"int main() {}\n","note":"is it fast enough?"}`
func TestEvaluateRefusals(t *testing.T) {
r, repo, _ := setupRun(t)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 503 {
t.Fatalf("no Claude = %d, want 503", rec.Code)
}
repo.srv.Claude = &fakeEvaluator{}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, false); rec.Code != 401 {
t.Fatalf("public evaluate = %d, want 401", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 400 {
t.Fatalf("no statement or link = %d, want 400: %s", rec.Code, rec.Body)
}
withStatement(t, r)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"cpp","source":" \n"}`, true); rec.Code != 400 {
t.Fatalf("empty source = %d, want 400", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"rust","source":"fn main() {}"}`, true); rec.Code != 400 {
t.Fatalf("rust = %d, want 400", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/two-sum/evaluate", `{"lang":"python","source":"x"}`, true); rec.Code != 400 {
t.Fatalf("python on LeetCode = %d, want 400", rec.Code)
}
}
func TestEvaluateRunsTheTestsAndCommitsNothing(t *testing.T) {
r, repo, fr := setupRun(t)
fc := &fakeEvaluator{}
repo.srv.Claude = fc
withStatement(t, r)
commits := len(repo.msg)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 202 {
t.Fatalf("evaluate = %d %s", rec.Code, rec.Body)
}
s := waitEvaluate(t, r, "moocast")
if s.State != jobs.Done || s.Result == nil {
t.Fatalf("job = %+v", s)
}
ev := s.Result
if ev.Verdict != "edge_cases" || ev.Lang != "cpp" || ev.Source != "int main() {}\n" || ev.Model != "fake-model" || ev.Tests != "1/1 passed" {
t.Errorf("evaluation = %+v", ev)
}
if len(ev.Issues) != 1 || ev.Issues[0].Line != 1 {
t.Errorf("issues = %+v", ev.Issues)
}
// Submit's run: the saved tests, with the headers.
if fr.run == nil || len(fr.run.Tests) != 3 || fr.run.IO != "moocast" || fr.run.Files["debugging.h"] == "" {
t.Errorf("run = %+v", fr.run)
}
for _, want := range []string{"walkie-talkies", "<code lang=\"cpp\">\n1| int main() {}\n</code>", "1/1 passed on the saved tests", "is it fast enough?"} {
if !strings.Contains(fc.user, want) {
t.Errorf("prompt is missing %q:\n%s", want, fc.user)
}
}
if len(repo.msg) != commits {
t.Errorf("an evaluation committed: %v", repo.msg[commits:])
}
}
func TestEvaluateWithoutARunner(t *testing.T) {
r, repo, fr := setupRun(t)
fc := &fakeEvaluator{}
repo.srv.Claude = fc
withStatement(t, r)
// A runner that fails costs the verdicts, not the evaluation.
fr.err = errors.New("runner down")
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != jobs.Done || s.Result.Tests != "The tests were not run: the code runner failed." {
t.Fatalf("with a failing runner = %+v", s)
}
repo.srv.Runner = nil
if c := getCodeReply(t, r, "moocast"); c.Runner {
t.Fatal("runner still reported")
}
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
s := waitEvaluate(t, r, "moocast")
if s.State != jobs.Done || !strings.Contains(fc.user, "the code runner is not configured") {
t.Fatalf("with no runner = %+v\n%s", s, fc.user)
}
fc.fail = true
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != jobs.Failed || s.Error != "Claude declined to answer" || s.Result != nil {
t.Fatalf("a failed evaluation = %+v", s)
}
}
+35 -20
View File
@@ -2,6 +2,7 @@ package handlers
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
@@ -82,8 +83,7 @@ func (s *Server) startExplain(ctx *gin.Context) {
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
var body explainBody
@@ -105,28 +105,33 @@ func (s *Server) startExplain(ctx *gin.Context) {
in.Code = mainFile(p)
}
link := p.URL
if !s.jobs.Start(p.Name, func() error { return s.explain(in, link) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "an explanation is already being written"})
return
if startJob(ctx, s.explainJobs, p.Name, "an explanation is already being written", func() (any, error) { return s.explain(in, link) }) {
ctx.JSON(http.StatusAccepted, s.explainJobs.Get(p.Name))
}
ctx.JSON(http.StatusAccepted, s.jobs.Get(p.Name))
}
func (s *Server) explainStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.jobs.Get(p.Name))
ctx.JSON(http.StatusOK, s.explainJobs.Get(p.Name))
}
}
// explain is one job. Its error is shown to the admin, so every path returns
// a message meant for them and logs the detail.
func (s *Server) explain(in explain.Input, link string) error {
// explainDraft is a written explanation waiting to be committed.
type explainDraft struct {
Name string `json:"name"`
Fetched string `json:"fetched,omitempty"`
Markdown string `json:"markdown"`
}
// explain is one job's work. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) explain(in explain.Input, link string) (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
fetched, err := s.ensureStatement(ctx, "explain", in.Name, &in.Statement, link)
if err != nil {
return err
return nil, err
}
md, err := explain.Generate(ctx, s.Claude, in, time.Now())
@@ -134,25 +139,35 @@ func (s *Server) explain(in explain.Input, link string) error {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err)
return f
return nil, f
}
log.Printf("[explain] %s: %v", in.Name, err)
return errors.New("the explanation could not be written")
return nil, errors.New("the explanation could not be written")
}
return explainDraft{Name: in.Name, Fetched: fetched, Markdown: md}, nil
}
name := in.Name
err = s.Repo.Mutate(ctx, "Explain "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
// saveExplain commits an explanation. Running it again for a draft already
// pushed changes nothing, so commits nothing.
func (s *Server) saveExplain(raw json.RawMessage) (any, error) {
var d explainDraft
if err := json.Unmarshal(raw, &d); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
err := s.Repo.Mutate(ctx, "Explain "+d.Name, func(dir string) error {
status, err := findOnDisk(dir, d.Name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if err := saveFetched(pdir, fetched); err != nil {
pdir := filepath.Join(dir, status, d.Name)
if err := saveFetched(pdir, d.Fetched); err != nil {
return err
}
return writeOrRemove(filepath.Join(pdir, "explain.md"), md)
return writeOrRemove(filepath.Join(pdir, "explain.md"), d.Markdown)
})
return jobSaveError("explain", name, "the explanation was written but could not be saved to git", err)
return nil, jobSaveError("explain", d.Name, "the explanation was written but could not be saved to git", err)
}
// ensureStatement fetches the statement when none is saved, so a job can
+8 -7
View File
@@ -13,6 +13,7 @@ import (
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/statement"
)
@@ -43,19 +44,19 @@ func (fakeJudge) Fetch(_ context.Context, link string) (string, error) {
return "", statement.ErrUnsupported
}
func waitJob(t *testing.T, r *gin.Engine, name string) explain.Status {
func waitJob(t *testing.T, r *gin.Engine, name string) jobs.Status {
t.Helper()
for range 400 {
rec := do(r, "GET", "/usaco/api/problems/"+name+"/explain", "", true)
var s explain.Status
var s jobs.Status
json.Unmarshal(rec.Body.Bytes(), &s)
if s.State != explain.Running {
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job still running")
return explain.Status{}
return jobs.Status{}
}
func TestExplainNeedsClaudeAndAStatement(t *testing.T) {
@@ -87,7 +88,7 @@ func TestExplainWritesAndCommits(t *testing.T) {
t.Fatalf("second start while running = %d, want 409", rec.Code)
}
close(fc.gate)
if s := waitJob(t, r, "moocast"); s.State != explain.Done {
if s := waitJob(t, r, "moocast"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
@@ -124,13 +125,13 @@ func TestExplainFetchesAMissingStatement(t *testing.T) {
do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://cses.fi/x"}`, true)
do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true)
if s := waitJob(t, r, "watermelon"); s.State != explain.Failed || !strings.Contains(s.Error, "paste it") {
if s := waitJob(t, r, "watermelon"); s.State != jobs.Failed || !strings.Contains(s.Error, "paste it") {
t.Fatalf("unfetchable statement: job = %+v, want an error asking to paste it", s)
}
do(r, "PUT", "/usaco/api/problems/watermelon/meta", `{"url":"https://usaco.org/moocast"}`, true)
do(r, "POST", "/usaco/api/problems/watermelon/explain", `{}`, true)
if s := waitJob(t, r, "watermelon"); s.State != explain.Done {
if s := waitJob(t, r, "watermelon"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
if b, _ := os.ReadFile(filepath.Join(repo.dir, "solving/watermelon/problem.md")); !strings.Contains(string(b), "walkie-talkies") {
+38 -8
View File
@@ -1,8 +1,9 @@
// Package handlers is the site's REST API: the problem list and pages (public
// 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 the Gitea webhook that
// tells the server to pull.
// solve page's code editing and runs (run.go) and evaluations
// (evaluate.go), the library of concepts Claude explained (concept.go), and
// the Gitea webhook that tells the server to pull.
package handlers
import (
@@ -20,6 +21,7 @@ import (
"regexp"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
@@ -28,7 +30,9 @@ import (
"adam-french.co.uk/usaco-site/internal/auth"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/repo"
"adam-french.co.uk/usaco-site/internal/usage"
)
// Repo is the part of repo.Repo the handlers use, so tests can fake it.
@@ -53,8 +57,8 @@ type Server struct {
// Statements reads a statement from the problem's judge; nil means the
// real judges.
Statements Fetcher
// LeetCode starts the daily question; nil means the real API and the
// clone's lib/leetcode.py.
// LeetCode starts the daily question and pasted links; nil means the
// real API and the clone's lib/leetcode.py.
LeetCode LeetCode
// Transcriber turns review recordings into text; nil when
// TRANSCRIBE_API_KEY is not set, which turns reviews off.
@@ -66,10 +70,20 @@ type Server struct {
// RUNNER_URL is not set, which turns only running and linting off.
Runner Runner
// Jobs keeps the background jobs' records (internal/jobs); nil keeps
// them in memory, which the tests use.
Jobs *jobs.Registry
// Usage is the Claude cost ledger and monthly budget; nil tracks
// nothing and allows everything.
Usage *usage.Ledger
idx atomic.Pointer[index.Index]
// Separate, so a review and an explanation of one problem can run at
// the same time.
jobs, reviewJobs explain.Jobs
jobsOnce sync.Once
// Separate kinds, so a review, an explanation and an evaluation of one
// problem can run at the same time. New concepts are keyed by a job id
// (the slug is Claude's to pick), rewrites by slug.
explainJobs, reviewJobs, evalJobs, newConceptJobs, conceptJobs *jobs.Kind
}
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
@@ -92,7 +106,10 @@ func (s *Server) Index() *index.Index { return s.idx.Load() }
// Routes registers everything under api.
func (s *Server) Routes(api *gin.RouterGroup) {
admin := api.Group("", auth.Require(s.Checker))
s.initJobs()
// SameOrigin first, so a cross-site request is refused without asking
// the site backend about its cookies.
admin := api.Group("", auth.SameOrigin(), auth.Require(s.Checker))
api.GET("/health", s.health)
api.GET("/me", s.me)
@@ -111,7 +128,20 @@ func (s *Server) Routes(api *gin.RouterGroup) {
admin.PUT("/problems/:name/code", s.saveCode)
admin.POST("/problems/:name/run", s.run)
admin.POST("/problems/:name/lint", s.lint)
admin.POST("/problems/:name/evaluate", s.startEvaluate)
admin.GET("/problems/:name/evaluate", s.evaluateStatus)
admin.POST("/leetcode/daily", s.startDaily)
admin.POST("/leetcode/import", s.startImport)
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)
admin.POST("/jobs/:kind/:key/save", s.retrySave)
admin.GET("/usage", s.usage)
api.POST("/hooks/gitea", s.webhook)
}
+8
View File
@@ -15,6 +15,8 @@ import (
"testing"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/repo"
)
// cookieChecker: the admin is whoever sends the cookie "admin=1".
@@ -31,9 +33,15 @@ type dirRepo struct {
dir string
srv *Server
msg []string
// reject refuses that many edits, as a remote that kept moving would.
reject int
}
func (d *dirRepo) Mutate(_ context.Context, message string, edit func(string) error) error {
if d.reject > 0 {
d.reject--
return repo.ErrRejected
}
if err := edit(d.dir); err != nil {
return err
}
+90
View File
@@ -0,0 +1,90 @@
package handlers
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/jobs"
)
// saveTimeout bounds a job's commit: a sync, the edit and a push.
const saveTimeout = 2 * time.Minute
// initJobs registers the job kinds, with the save funcs that commit their
// drafts (explain.go, review.go, concept.go). Routes calls it, and so does
// ResumeJobs, whichever runs first.
func (s *Server) initJobs() {
s.jobsOnce.Do(func() {
if s.Jobs == nil {
s.Jobs = jobs.New("")
}
s.explainJobs = s.Jobs.Kind("explain", jobs.Options{Save: s.saveExplain})
s.reviewJobs = s.Jobs.Kind("review", jobs.Options{Save: s.saveReview, Discard: s.discardReview})
s.evalJobs = s.Jobs.Kind("evaluate", jobs.Options{})
s.newConceptJobs = s.Jobs.Kind("concept", jobs.Options{Save: s.saveConcept})
s.conceptJobs = s.Jobs.Kind("rewrite", jobs.Options{Save: s.saveConcept})
})
}
// ResumeJobs saves the drafts a restart interrupted. main calls it once the
// first sync has made the clone ready.
func (s *Server) ResumeJobs() {
s.initJobs()
s.Jobs.Resume()
}
// startJob starts work as key's job of kind k, or answers why it cannot:
// busy (409) when one is running, 503 while the server shuts down.
func startJob(ctx *gin.Context, k *jobs.Kind, key, busy string, work jobs.Work) bool {
err := k.Start(key, work)
switch {
case err == nil:
return true
case errors.Is(err, jobs.ErrDraining):
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "the server is restarting; try again in a minute"})
default:
ctx.JSON(http.StatusConflict, gin.H{"error": busy})
}
return false
}
// claudeReady answers 503 without CLAUDE_API_KEY, and 429 once this month's
// Claude budget is spent; it is checked before any job that calls Claude.
func (s *Server) claudeReady(ctx *gin.Context) bool {
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
return false
}
if err := s.Usage.Allow(time.Now()); err != nil {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()})
return false
}
return true
}
// retrySave commits an unsaved job's draft again; the page then polls the
// job's usual status route.
func (s *Server) retrySave(ctx *gin.Context) {
k := s.Jobs.Lookup(ctx.Param("kind"))
if k == nil {
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such job"})
return
}
st, err := k.Retry(ctx.Param("key"))
switch {
case errors.Is(err, jobs.ErrBusy):
ctx.JSON(http.StatusConflict, gin.H{"error": "it is still running"})
case err != nil:
ctx.JSON(http.StatusNotFound, gin.H{"error": "there is nothing unsaved to save"})
default:
ctx.JSON(http.StatusAccepted, st)
}
}
// usage is the Claude spend for the stats page.
func (s *Server) usage(ctx *gin.Context) {
ctx.JSON(http.StatusOK, s.Usage.Summarize(time.Now()))
}
+111
View File
@@ -0,0 +1,111 @@
package handlers
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/concept"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/usage"
)
// A commit the remote keeps refusing leaves the explanation unsaved, not
// lost: saving again commits it without asking Claude a second time.
func TestUnsavedExplanationIsSavedAgain(t *testing.T) {
r, repo, _ := setup(t)
fc := &fakeClaude{}
repo.srv.Claude = fc
do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast"}`, true)
repo.reject = 1
do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true)
s := waitJob(t, r, "moocast")
if s.State != jobs.Failed || !s.Unsaved || !strings.Contains(s.Error, "try again") || s.Kind != "explain" || s.Key != "moocast" {
t.Fatalf("rejected save = %+v", s)
}
fc.user = ""
if rec := do(r, "POST", "/usaco/api/jobs/explain/moocast/save", "", false); rec.Code != 401 {
t.Fatalf("public save = %d, want 401", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/jobs/explain/moocast/save", "", true); rec.Code != 202 {
t.Fatalf("save again = %d: %s", rec.Code, rec.Body)
}
if s := waitJob(t, r, "moocast"); s.State != jobs.Done || s.Unsaved {
t.Fatalf("saved again = %+v", s)
}
if fc.user != "" {
t.Error("saving again asked Claude again")
}
if b, _ := os.ReadFile(filepath.Join(repo.dir, "solved/moocast/explain.md")); !strings.Contains(string(b), "Think in reverse.") {
t.Errorf("explain.md = %q", b)
}
if rec := do(r, "POST", "/usaco/api/jobs/explain/moocast/save", "", true); rec.Code != 404 {
t.Fatalf("nothing left to save = %d, want 404", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/jobs/nope/moocast/save", "", true); rec.Code != 404 {
t.Fatalf("unknown kind = %d, want 404", rec.Code)
}
}
// A new concept whose save is run again after it was pushed (a restart
// between the push and the record) is found, not saved a second time.
func TestConceptSavedTwiceIsSavedOnce(t *testing.T) {
_, repo, _ := setup(t)
s := repo.srv
raw, _ := json.Marshal(conceptDraft{
Result: concept.Result{Slug: "kmp", Title: "KMP", Snippet: "int kmp();"},
Topic: "kmp", Model: "m", Written: time.Now(),
})
for range 2 {
res, err := s.saveConcept(raw)
if err != nil || res.(conceptResult).Slug != "kmp" {
t.Fatalf("save = %+v, %v", res, err)
}
}
if len(repo.msg) != 1 {
t.Fatalf("commits = %v, want one", repo.msg)
}
}
func TestClaudeBudget(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.Claude = &fakeClaude{}
l, err := usage.Open(filepath.Join(t.TempDir(), "usage.jsonl"), 1)
if err != nil {
t.Fatal(err)
}
repo.srv.Usage = l
do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast"}`, true)
l.Record(usage.Entry{Kind: "explain", Model: "claude-opus-5-5", Out: 100_000}) // $2
rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true)
if rec.Code != 429 || !strings.Contains(rec.Body.String(), "budget") {
t.Fatalf("over budget = %d: %s", rec.Code, rec.Body)
}
rec = do(r, "GET", "/usaco/api/usage", "", true)
var sum usage.Summary
json.Unmarshal(rec.Body.Bytes(), &sum)
if rec.Code != 200 || !sum.Tracked || sum.Budget != 1 || sum.Month < 2 {
t.Fatalf("usage = %d: %s", rec.Code, rec.Body)
}
if rec := do(r, "GET", "/usaco/api/usage", "", false); rec.Code != 401 {
t.Fatalf("public usage = %d, want 401", rec.Code)
}
}
// An admin's cookies on a request from another origin change nothing.
func TestCrossSiteEditRefused(t *testing.T) {
r, repo, _ := setup(t)
rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true, "Sec-Fetch-Site", "same-site")
if rec.Code != 403 || len(repo.msg) != 0 {
t.Fatalf("cross-origin edit = %d, commits %v", rec.Code, repo.msg)
}
if rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true, "Sec-Fetch-Site", "same-origin"); rec.Code != 200 {
t.Fatalf("same-origin edit = %d: %s", rec.Code, rec.Body)
}
}
+55 -21
View File
@@ -3,6 +3,7 @@ package handlers
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
@@ -62,8 +63,7 @@ func (s *Server) startReview(ctx *gin.Context) {
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
if !s.claudeReady(ctx) {
return
}
if s.Transcriber == nil {
@@ -125,11 +125,9 @@ func (s *Server) startReview(ctx *gin.Context) {
id := time.Now().UTC().Format(reviewIDLayout)
rec := recording{name: id + ext, contentType: contentType, data: audio}
link := p.URL
if !s.reviewJobs.Start(p.Name, func() error { return s.review(in, link, id, rec) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "a recording is already being reviewed"})
return
if startJob(ctx, s.reviewJobs, p.Name, "a recording is already being reviewed", func() (any, error) { return s.review(in, link, id, rec) }) {
ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name))
}
ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name))
}
func (s *Server) reviewStatus(ctx *gin.Context) {
@@ -143,16 +141,26 @@ type recording struct {
data []byte
}
// review is one job. Its error is shown to the admin, so every path returns
// a message meant for them and logs the detail.
func (s *Server) review(in review.Input, link, id string, rec recording) (err error) {
// reviewDraft is a written review waiting to be committed. Audio is the
// recording's key in the store, kept until the review is saved or replaced.
type reviewDraft struct {
Name string `json:"name"`
ID string `json:"id"`
Fetched string `json:"fetched,omitempty"`
Markdown string `json:"markdown"`
Audio string `json:"audio,omitempty"`
}
// review is one job's work. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) review(in review.Input, link, id string, rec recording) (draft any, err error) {
ctx, cancel := context.WithTimeout(context.Background(), reviewTimeout)
defer cancel()
name := in.Name
fetched, err := s.ensureStatement(ctx, "review", name, &in.Statement, link)
if err != nil {
return err
return nil, err
}
tr, err := s.Transcriber.Transcribe(ctx, rec.name, rec.data)
@@ -160,17 +168,19 @@ func (s *Server) review(in review.Input, link, id string, rec recording) (err er
var f *transcribe.Failure
if errors.As(err, &f) {
log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err)
return f
return nil, f
}
log.Printf("[review] %s: transcribing: %v", name, err)
return errors.New("the recording could not be transcribed")
return nil, errors.New("the recording could not be transcribed")
}
in.Transcript, in.Metrics = tr, tr.Metrics()
// The recording is kept only if there is somewhere to keep it, and a
// failure to keep it costs the playback, not the review. It is stored
// before Claude runs so the review can point at it, and removed again
// if the review never gets saved.
// if Claude fails. Once there is a review it stays with the draft: a
// failed commit can be retried, and discardReview removes it if a new
// recording replaces the draft instead.
key := ""
if s.Audio != nil {
k := name + "/" + rec.name
@@ -194,27 +204,51 @@ func (s *Server) review(in review.Input, link, id string, rec recording) (err er
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err)
return f
return nil, f
}
log.Printf("[review] %s: %v", name, err)
return errors.New("the review could not be written")
return nil, errors.New("the review could not be written")
}
return reviewDraft{Name: name, ID: id, Fetched: fetched, Markdown: md, Audio: key}, nil
}
err = s.Repo.Mutate(ctx, "Review "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
// saveReview commits a review. The id was chosen when the recording came
// in, so running it again for a draft already pushed rewrites the same
// file and commits nothing.
func (s *Server) saveReview(raw json.RawMessage) (any, error) {
var d reviewDraft
if err := json.Unmarshal(raw, &d); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
err := s.Repo.Mutate(ctx, "Review "+d.Name, func(dir string) error {
status, err := findOnDisk(dir, d.Name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if err := saveFetched(pdir, fetched); err != nil {
pdir := filepath.Join(dir, status, d.Name)
if err := saveFetched(pdir, d.Fetched); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(pdir, "reviews"), 0o755); err != nil {
return err
}
return writeOrRemove(filepath.Join(pdir, "reviews", id+".md"), md)
return writeOrRemove(filepath.Join(pdir, "reviews", d.ID+".md"), d.Markdown)
})
return jobSaveError("review", name, "the review was written but could not be saved to git", err)
return nil, jobSaveError("review", d.Name, "the review was written but could not be saved to git", err)
}
// discardReview removes the recording of a review that was never saved and
// has been replaced by a new one.
func (s *Server) discardReview(raw json.RawMessage) {
var d reviewDraft
if json.Unmarshal(raw, &d) != nil || d.Audio == "" || s.Audio == nil {
return
}
if err := s.Audio.Delete(context.Background(), d.Audio); err != nil {
log.Printf("[review] %s: removing the unsaved review's recording: %v", d.Name, err)
}
}
// findReview is the problem's review with the URL's id.
+9 -9
View File
@@ -18,8 +18,8 @@ import (
"adam-french.co.uk/usaco-site/internal/audiostore"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/jobs"
"adam-french.co.uk/usaco-site/internal/review"
"adam-french.co.uk/usaco-site/internal/transcribe"
)
@@ -121,18 +121,18 @@ func upload(r *gin.Engine, name, filename string, size int, fields ...string) *h
return do(r, "POST", "/usaco/api/problems/"+name+"/review", body.String(), true, "Content-Type", w.FormDataContentType())
}
func waitReview(t *testing.T, r *gin.Engine, name string) explain.Status {
func waitReview(t *testing.T, r *gin.Engine, name string) jobs.Status {
t.Helper()
for range 400 {
var s explain.Status
var s jobs.Status
json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/review", "", true).Body.Bytes(), &s)
if s.State != explain.Running {
if s.State != jobs.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("review still running")
return explain.Status{}
return jobs.Status{}
}
func withStatement(t *testing.T, r *gin.Engine) {
@@ -183,7 +183,7 @@ func TestReviewWritesAndCommits(t *testing.T) {
if rec := upload(r, "moocast", "Take 1.M4A", 10, "note", "mock interview", "includeCode", "true"); rec.Code != 202 {
t.Fatalf("start = %d: %s", rec.Code, rec.Body)
}
if s := waitReview(t, r, "moocast"); s.State != explain.Done {
if s := waitReview(t, r, "moocast"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
if !strings.HasSuffix(ft.file, ".m4a") || string(ft.audio[:3]) != "ID3" {
@@ -241,7 +241,7 @@ func TestReviewKeepsAndRemovesTheRecording(t *testing.T) {
withStatement(t, r)
upload(r, "moocast", "take.mp3", 100)
if s := waitReview(t, r, "moocast"); s.State != explain.Done {
if s := waitReview(t, r, "moocast"); s.State != jobs.Done {
t.Fatalf("job = %+v, want done", s)
}
var p index.Problem
@@ -288,7 +288,7 @@ func TestReviewFailures(t *testing.T) {
commits := len(repo.msg)
upload(r, "moocast", "a.mp3", 10)
if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "no speech was found in the recording" {
if s := waitReview(t, r, "moocast"); s.State != jobs.Failed || s.Error != "no speech was found in the recording" {
t.Fatalf("transcription failure: job = %+v", s)
}
@@ -296,7 +296,7 @@ func TestReviewFailures(t *testing.T) {
// behind when the review fails.
ft.err, fr.fail = nil, true
upload(r, "moocast", "a.mp3", 10)
if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" {
if s := waitReview(t, r, "moocast"); s.State != jobs.Failed || s.Error != "Claude declined to answer" {
t.Fatalf("Claude failure: job = %+v", s)
}
if len(repo.msg) != commits || len(store.keys()) != 0 {
+17 -13
View File
@@ -16,6 +16,7 @@ import (
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/runner"
)
@@ -159,6 +160,7 @@ func (s *Server) getCode(ctx *gin.Context) {
"languages": l.languages(),
"default": def,
"runner": s.Runner != nil,
"claude": s.Claude != nil,
"code": code,
})
}
@@ -248,44 +250,46 @@ type codeBody struct {
// Mode and Input are for runs only.
Mode string `json:"mode"`
Input string `json:"input"`
// Note is for evaluations only.
Note string `json:"note"`
}
// readCode reads and checks a solve page request against the problem's
// layout. It has answered when ok is false.
func (s *Server) readCode(ctx *gin.Context) (body codeBody, l *layout, ok bool) {
p, ok := s.lookup(ctx, true)
func (s *Server) readCode(ctx *gin.Context) (body codeBody, p *index.Problem, l *layout, ok bool) {
p, ok = s.lookup(ctx, true)
if !ok {
return body, nil, false
return body, nil, nil, false
}
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxRunBody)
if err := ctx.ShouldBindJSON(&body); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the request is over 512 KB"})
return body, nil, false
return body, nil, nil, false
}
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return body, nil, false
return body, nil, nil, false
}
if len(body.Source) > maxSource {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the source is over 256 KB"})
return body, nil, false
return body, nil, nil, false
}
if body.Lang != runner.Cpp && body.Lang != runner.Python {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "lang must be cpp or python"})
return body, nil, false
return body, nil, nil, false
}
l, err := s.readLayout(p.Status, p.Name)
if err != nil {
log.Printf("[code] %s: %v", p.Name, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
return body, nil, false
return body, nil, nil, false
}
if !l.allows(body.Lang) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "a LeetCode problem runs through its C++ driver only"})
return body, nil, false
return body, nil, nil, false
}
return body, l, true
return body, p, l, true
}
// headers are the files written next to a C++ source; Python needs none.
@@ -333,7 +337,7 @@ func (s *Server) run(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
body, _, l, ok := s.readCode(ctx)
if !ok {
return
}
@@ -472,7 +476,7 @@ func (s *Server) lint(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
body, _, l, ok := s.readCode(ctx)
if !ok {
return
}
@@ -496,7 +500,7 @@ func (s *Server) lint(ctx *gin.Context) {
// saveCode commits the editor's source as the problem's solution. An
// unchanged source makes no commit: Mutate skips an empty diff.
func (s *Server) saveCode(ctx *gin.Context) {
body, _, ok := s.readCode(ctx)
body, _, _, ok := s.readCode(ctx)
if !ok {
return
}
+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)
+376
View File
@@ -0,0 +1,376 @@
// Package jobs runs the site's slow work in the background: Claude writing
// an explanation, a concept or a review, or judging a draft. Each takes a
// minute or more, longer than nginx waits for a response, so the request
// only starts a job and the page polls its Status.
//
// Every job belongs to a Kind ("explain", "review"...) and has a key within
// it (a problem name, a concept slug, a job id); a kind runs at most one job
// per key at a time.
//
// A job that commits is split in two. Its work (the expensive part: Claude)
// returns a draft, which is written to disk before the kind's save func
// commits it. So a commit that fails (the remote kept moving, Gitea was
// down) or a restart in the middle of one does not throw away a paid-for
// answer: the job is left unsaved, Retry runs the save again, and Resume
// does so on its own after a restart.
//
// Records live in Dir/<kind>/<key>.json, so a finished job's status and
// result survive a restart too. With no Dir everything is in memory, which
// the tests use.
package jobs
import (
"encoding/json"
"errors"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
// A job's states. Idle means the key has never had a job.
const (
Idle = "idle"
Running = "running"
Done = "done"
Failed = "error"
)
var (
// ErrBusy is a Start or Retry for a key whose job is still running.
ErrBusy = errors.New("a job is already running")
// ErrDraining is a Start during shutdown: the running jobs are being
// let finish, and nothing new begins.
ErrDraining = errors.New("the server is restarting")
// ErrNothingToSave is a Retry for a key with no unsaved draft.
ErrNothingToSave = errors.New("nothing to save")
)
// interrupted is the error a job is left with when the server stopped
// before its work finished. Only work that had not produced a draft yet
// ends up here; a draft is saved again by Resume.
const interrupted = "the server restarted while this was running; start it again"
// finishedTTL is how long a finished record without a draft is kept on
// disk. New concepts are keyed by a fresh id each, so their records would
// otherwise pile up.
const finishedTTL = 7 * 24 * time.Hour
// Status is what the page polls for.
type Status struct {
Kind string `json:"kind"`
Key string `json:"key"`
State string `json:"state"`
Error string `json:"error,omitempty"`
Started *time.Time `json:"started,omitempty"`
Finished *time.Time `json:"finished,omitempty"`
// Result is a finished job's answer, for kinds that return one.
Result any `json:"result,omitempty"`
// Unsaved means the work finished but its commit did not: the draft is
// kept, and POST /jobs/<kind>/<key>/save tries the commit again.
Unsaved bool `json:"unsaved,omitempty"`
}
// record is a Status as stored, with the draft the page never sees.
type record struct {
Status
Draft json.RawMessage `json:"draft,omitempty"`
}
// Work is a job's expensive part. For a kind with a save func it returns
// the draft to save, which must marshal to JSON; otherwise its result.
// Its error is shown to the admin, so it must be a message meant for them.
type Work func() (any, error)
// Save commits a draft and returns the job's result. It may run more than
// once for one draft (a retry, or a resume after a restart that came after
// the commit was pushed), so it must cope with finding its work already
// done. Its error is shown to the admin.
type Save func(draft json.RawMessage) (any, error)
// Registry holds every kind, and knows when the server is shutting down.
type Registry struct {
dir string
wg sync.WaitGroup
draining atomic.Bool
mu sync.Mutex
kinds []*Kind
}
// New is a registry keeping records under dir; "" keeps them in memory.
func New(dir string) *Registry { return &Registry{dir: dir} }
// Kind is one sort of job.
type Kind struct {
r *Registry
name string
dir string
save Save
discard func(draft json.RawMessage)
mu sync.Mutex
m map[string]*record
}
// Options configure a kind.
type Options struct {
// Save commits a draft; nil for a kind whose work's answer is the
// result (an evaluation), which commits nothing.
Save Save
// Discard cleans up after a draft that will never be saved, because a
// new job for the key replaced it (a review's stored recording).
Discard func(draft json.RawMessage)
}
// Kind registers a kind and loads its records. A record left running by
// the last process is settled here: one with a draft waits for Resume,
// one without is marked interrupted.
func (r *Registry) Kind(name string, o Options) *Kind {
k := &Kind{r: r, name: name, save: o.Save, discard: o.Discard, m: map[string]*record{}}
if r.dir != "" {
k.dir = filepath.Join(r.dir, name)
if err := os.MkdirAll(k.dir, 0o755); err != nil {
log.Printf("[jobs] %s: %v; its jobs are kept in memory only", name, err)
k.dir = ""
}
}
k.load()
r.mu.Lock()
r.kinds = append(r.kinds, k)
r.mu.Unlock()
return k
}
func (k *Kind) load() {
if k.dir == "" {
return
}
entries, err := os.ReadDir(k.dir)
if err != nil {
log.Printf("[jobs] %s: %v", k.name, err)
return
}
for _, e := range entries {
path := filepath.Join(k.dir, e.Name())
if !strings.HasSuffix(e.Name(), ".json") {
continue
}
b, err := os.ReadFile(path)
if err != nil {
log.Printf("[jobs] %s: %v", path, err)
continue
}
var rec record
if err := json.Unmarshal(b, &rec); err != nil || rec.Key == "" {
log.Printf("[jobs] %s: unreadable, removed: %v", path, err)
os.Remove(path)
continue
}
if rec.State != Running && len(rec.Draft) == 0 && rec.Finished != nil && time.Since(*rec.Finished) > finishedTTL {
os.Remove(path)
continue
}
if rec.State == Running && len(rec.Draft) == 0 {
now := time.Now()
rec.State, rec.Error, rec.Finished = Failed, interrupted, &now
k.store(&rec)
}
// A loaded result is generic JSON (maps and slices), which goes back
// out to the page as it was stored.
k.m[rec.Key] = &rec
}
}
// Start runs work in the background unless key's job is running, or the
// server is shutting down.
func (k *Kind) Start(key string, work Work) error {
if k.r.draining.Load() {
return ErrDraining
}
k.mu.Lock()
defer k.mu.Unlock()
old := k.m[key]
if old != nil && old.State == Running {
return ErrBusy
}
if old != nil && len(old.Draft) > 0 && k.discard != nil {
go k.discard(old.Draft)
}
now := time.Now()
rec := &record{Status: Status{Kind: k.name, Key: key, State: Running, Started: &now}}
k.m[key] = rec
k.store(rec)
k.r.wg.Add(1)
go func() {
defer k.r.wg.Done()
out, err := work()
if err != nil {
k.finish(key, nil, err, false)
return
}
if k.save == nil {
k.finish(key, out, nil, false)
return
}
draft, err := json.Marshal(out)
if err != nil {
log.Printf("[jobs] %s %s: the draft does not marshal: %v", k.name, key, err)
k.finish(key, nil, errors.New("the answer could not be kept"), false)
return
}
k.mu.Lock()
rec.Draft = draft
k.store(rec)
k.mu.Unlock()
k.runSave(key, draft)
}()
return nil
}
// runSave commits key's draft; the caller has counted it in the wait group
// when it runs in the background.
func (k *Kind) runSave(key string, draft json.RawMessage) {
res, err := k.save(draft)
k.finish(key, res, err, err != nil)
}
func (k *Kind) finish(key string, res any, err error, unsaved bool) {
k.mu.Lock()
defer k.mu.Unlock()
rec := k.m[key]
if rec == nil {
return
}
end := time.Now()
rec.Finished = &end
rec.State, rec.Error, rec.Result, rec.Unsaved = Done, "", res, false
if err != nil {
rec.State, rec.Error, rec.Result, rec.Unsaved = Failed, err.Error(), nil, unsaved
}
if !unsaved {
// Saved, or never got as far as a draft: nothing left to retry.
rec.Draft = nil
}
k.store(rec)
}
// Retry runs an unsaved job's save again.
func (k *Kind) Retry(key string) (Status, error) {
if k.save == nil {
return Status{}, ErrNothingToSave
}
k.mu.Lock()
rec := k.m[key]
switch {
case rec != nil && rec.State == Running:
k.mu.Unlock()
return Status{}, ErrBusy
case rec == nil || len(rec.Draft) == 0:
k.mu.Unlock()
return Status{}, ErrNothingToSave
}
rec.State, rec.Error, rec.Unsaved, rec.Finished = Running, "", false, nil
k.store(rec)
draft, st := rec.Draft, rec.Status
k.mu.Unlock()
k.r.wg.Add(1)
go func() {
defer k.r.wg.Done()
k.runSave(key, draft)
}()
return st, nil
}
// Get is key's latest job.
func (k *Kind) Get(key string) Status {
k.mu.Lock()
defer k.mu.Unlock()
if rec := k.m[key]; rec != nil {
return rec.Status
}
return Status{Kind: k.name, Key: key, State: Idle}
}
// store writes rec to disk, through a temporary file so a crash never
// leaves half a record. The caller holds k.mu.
func (k *Kind) store(rec *record) {
if k.dir == "" {
return
}
b, err := json.Marshal(rec)
if err != nil {
log.Printf("[jobs] %s %s: %v", k.name, rec.Key, err)
return
}
path := filepath.Join(k.dir, url.PathEscape(rec.Key)+".json")
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
log.Printf("[jobs] %s: %v", path, err)
return
}
if err := os.Rename(tmp, path); err != nil {
log.Printf("[jobs] %s: %v", path, err)
}
}
// Lookup is the kind called name, or nil.
func (r *Registry) Lookup(name string) *Kind {
r.mu.Lock()
defer r.mu.Unlock()
for _, k := range r.kinds {
if k.name == name {
return k
}
}
return nil
}
// Resume saves the drafts the last process left running: it stopped after
// the work and before (or during) the commit. Call it once the clone is
// ready, since saving needs it.
func (r *Registry) Resume() {
r.mu.Lock()
kinds := append([]*Kind(nil), r.kinds...)
r.mu.Unlock()
for _, k := range kinds {
k.mu.Lock()
var keys []string
var drafts []json.RawMessage
for key, rec := range k.m {
if rec.State == Running && len(rec.Draft) > 0 && k.save != nil {
keys, drafts = append(keys, key), append(drafts, rec.Draft)
}
}
k.mu.Unlock()
for i, key := range keys {
log.Printf("[jobs] %s %s: saving the draft a restart interrupted", k.name, key)
r.wg.Add(1)
go func(key string, draft json.RawMessage) {
defer r.wg.Done()
k.runSave(key, draft)
}(key, drafts[i])
}
}
}
// Drain stops new jobs from starting and waits for the running ones, or
// until stop is closed. It reports whether they all finished.
func (r *Registry) Drain(stop <-chan struct{}) bool {
r.draining.Store(true)
done := make(chan struct{})
go func() {
r.wg.Wait()
close(done)
}()
select {
case <-done:
return true
case <-stop:
return false
}
}
+181
View File
@@ -0,0 +1,181 @@
package jobs
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
)
func wait(t *testing.T, k *Kind, key string) Status {
t.Helper()
for range 400 {
if s := k.Get(key); s.State != Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job still running")
return Status{}
}
func TestResultKind(t *testing.T) {
k := New("").Kind("evaluate", Options{})
if s := k.Get("a"); s.State != Idle || s.Kind != "evaluate" || s.Key != "a" {
t.Fatalf("fresh = %+v", s)
}
release := make(chan struct{})
if err := k.Start("a", func() (any, error) { <-release; return "verdict", nil }); err != nil {
t.Fatal(err)
}
if err := k.Start("a", func() (any, error) { return nil, nil }); !errors.Is(err, ErrBusy) {
t.Fatalf("second start = %v, want ErrBusy", err)
}
if err := k.Start("b", func() (any, error) { return nil, nil }); err != nil {
t.Fatalf("another key's job = %v", err)
}
close(release)
if s := wait(t, k, "a"); s.State != Done || s.Result != "verdict" {
t.Fatalf("done = %+v", s)
}
k.Start("a", func() (any, error) { return nil, errors.New("Claude declined") })
if s := wait(t, k, "a"); s.State != Failed || s.Error != "Claude declined" || s.Unsaved {
t.Fatalf("failed = %+v", s)
}
}
// A commit that fails keeps the draft; Retry saves it.
func TestRetrySavesTheDraft(t *testing.T) {
var mu sync.Mutex
var saved []string
fail := true
k := New(t.TempDir()).Kind("explain", Options{Save: func(d json.RawMessage) (any, error) {
mu.Lock()
defer mu.Unlock()
if fail {
return nil, errors.New("the repository changed while saving; try again")
}
var s string
json.Unmarshal(d, &s)
saved = append(saved, s)
return nil, nil
}})
if _, err := k.Retry("p"); !errors.Is(err, ErrNothingToSave) {
t.Fatalf("retry with no job = %v", err)
}
k.Start("p", func() (any, error) { return "# explanation", nil })
s := wait(t, k, "p")
if s.State != Failed || !s.Unsaved {
t.Fatalf("failed save = %+v", s)
}
mu.Lock()
fail = false
mu.Unlock()
if _, err := k.Retry("p"); err != nil {
t.Fatal(err)
}
if s := wait(t, k, "p"); s.State != Done || s.Unsaved {
t.Fatalf("retried = %+v", s)
}
if len(saved) != 1 || saved[0] != "# explanation" {
t.Fatalf("saved %q", saved)
}
if _, err := k.Retry("p"); !errors.Is(err, ErrNothingToSave) {
t.Fatalf("retry after saving = %v", err)
}
}
// A restart settles what the last process left running: a job still at
// its work is interrupted, one with a draft is saved by Resume, and a
// finished one keeps its result.
func TestRestart(t *testing.T) {
dir := t.TempDir()
write := func(kind, key string, rec record) {
os.MkdirAll(filepath.Join(dir, kind), 0o755)
b, _ := json.Marshal(rec)
os.WriteFile(filepath.Join(dir, kind, key+".json"), b, 0o600)
}
now := time.Now()
old := now.Add(-30 * 24 * time.Hour)
write("explain", "working", record{Status: Status{Kind: "explain", Key: "working", State: Running, Started: &now}})
write("explain", "saving", record{Status: Status{Kind: "explain", Key: "saving", State: Running, Started: &now}, Draft: json.RawMessage(`"md"`)})
write("explain", "stale", record{Status: Status{Kind: "explain", Key: "stale", State: Done, Finished: &old}})
write("evaluate", "done", record{Status: Status{Kind: "evaluate", Key: "done", State: Done, Finished: &now, Result: map[string]any{"verdict": "correct"}}})
r := New(dir)
var saved []string
var mu sync.Mutex
ex := r.Kind("explain", Options{Save: func(d json.RawMessage) (any, error) {
mu.Lock()
saved = append(saved, string(d))
mu.Unlock()
return nil, nil
}})
ev := r.Kind("evaluate", Options{})
if s := ex.Get("working"); s.State != Failed || s.Error != interrupted {
t.Fatalf("interrupted = %+v", s)
}
if s := ex.Get("stale"); s.State != Idle {
t.Fatalf("stale record kept: %+v", s)
}
if _, err := os.Stat(filepath.Join(dir, "explain", "stale.json")); !os.IsNotExist(err) {
t.Fatal("stale record not removed")
}
if s := ev.Get("done"); s.State != Done || s.Result.(map[string]any)["verdict"] != "correct" {
t.Fatalf("finished = %+v", s)
}
if s := ex.Get("saving"); s.State != Running {
t.Fatalf("before Resume = %+v", s)
}
r.Resume()
if s := wait(t, ex, "saving"); s.State != Done {
t.Fatalf("resumed = %+v", s)
}
if len(saved) != 1 || saved[0] != `"md"` {
t.Fatalf("saved %q", saved)
}
}
func TestDrain(t *testing.T) {
r := New("")
k := r.Kind("explain", Options{})
release := make(chan struct{})
k.Start("a", func() (any, error) { <-release; return nil, nil })
stop := make(chan struct{})
close(stop)
if r.Drain(stop) {
t.Fatal("Drain reported done with a job running")
}
if err := k.Start("b", func() (any, error) { return nil, nil }); !errors.Is(err, ErrDraining) {
t.Fatalf("start while draining = %v", err)
}
close(release)
if !r.Drain(make(chan struct{})) {
t.Fatal("Drain did not finish")
}
}
// Replacing an unsaved draft with a new job hands the old one to Discard.
func TestDiscard(t *testing.T) {
discarded := make(chan string, 1)
k := New("").Kind("review", Options{
Save: func(json.RawMessage) (any, error) { return nil, errors.New("push failed") },
Discard: func(d json.RawMessage) { discarded <- string(d) },
})
k.Start("p", func() (any, error) { return "first", nil })
wait(t, k, "p")
k.Start("p", func() (any, error) { return nil, errors.New("no") })
select {
case d := <-discarded:
if d != `"first"` {
t.Fatalf("discarded %s", d)
}
case <-time.After(time.Second):
t.Fatal("old draft not discarded")
}
}
+49 -1
View File
@@ -1,5 +1,5 @@
// Package leetcode starts LeetCode problems from the site the way `usaco
// daily` does from the CLI. The import itself is the CLI's: lib/leetcode.py
// daily` and `usaco new <leetcode-link>` do from the CLI. The import itself is the CLI's: lib/leetcode.py
// in the clone writes problem.md, main.cpp, the generated driver.h and the
// examples as tests. Rewriting its driver generator in Go would leave two
// copies to drift apart, so the site image carries python3 to run it.
@@ -13,8 +13,11 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
@@ -73,6 +76,31 @@ func (i *Importer) Daily(ctx context.Context) (string, error) {
return out.Data.Daily.Question.Slug, nil
}
var slugRe = regexp.MustCompile(`^[a-z0-9-]+$`)
// Slug is the problem a LeetCode link names, as slug_of in lib/leetcode.py
// reads it: https://leetcode.com/problems/<slug>/ with anything after (the
// /description/ and ?envType=... a copied link carries), with or without the
// scheme, or a bare slug.
func Slug(link string) (string, error) {
link = strings.TrimSpace(link)
if slugRe.MatchString(link) {
return link, nil
}
if !strings.Contains(link, "://") {
link = "https://" + link
}
u, err := url.Parse(link)
if err != nil || strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") != "leetcode.com" {
return "", errors.New("not a LeetCode problem link")
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) < 2 || parts[0] != "problems" || !slugRe.MatchString(parts[1]) {
return "", errors.New("not a LeetCode problem link")
}
return parts[1], nil
}
// Import runs `lib/leetcode.py root slug` in the clone at root, which
// creates solving/<slug>. The script reports a failure as "Error: ..." on
// stderr, which is what the admin is shown.
@@ -83,6 +111,7 @@ func (i *Importer) Import(ctx context.Context, root, slug string) error {
}
var stderr bytes.Buffer
cmd := exec.CommandContext(ctx, python, "-I", filepath.Join(root, "lib", "leetcode.py"), root, slug)
cmd.Env = scriptEnv()
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
for _, line := range strings.Split(stderr.String(), "\n") {
@@ -94,3 +123,22 @@ func (i *Importer) Import(ctx context.Context, root, slug string) error {
}
return nil
}
// scriptEnv is the environment the importer runs with: what python3 needs
// to reach LeetCode over HTTPS, and nothing else. The script comes from the
// clone, so whoever can push to the repo writes it, while this process holds
// the Claude, Gitea and S3 secrets in its environment. Those must not be
// inherited.
func scriptEnv() []string {
env := []string{"HOME=" + os.TempDir(), "LANG=C.UTF-8"}
if _, ok := os.LookupEnv("PATH"); !ok {
env = append(env, "PATH=/usr/local/bin:/usr/bin:/bin")
}
for _, k := range []string{"PATH", "TMPDIR", "SSL_CERT_FILE", "SSL_CERT_DIR",
"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"} {
if v, ok := os.LookupEnv(k); ok {
env = append(env, k+"="+v)
}
}
return env
}
+42
View File
@@ -32,6 +32,32 @@ func TestDailyMissing(t *testing.T) {
}
}
func TestSlug(t *testing.T) {
for _, link := range []string{
"https://leetcode.com/problems/two-sum/",
"https://leetcode.com/problems/two-sum/description/?envType=daily-question",
" https://www.leetcode.com/problems/two-sum ",
"leetcode.com/problems/two-sum/",
"two-sum",
} {
if got, err := Slug(link); err != nil || got != "two-sum" {
t.Errorf("Slug(%q) = %q, %v; want two-sum", link, got, err)
}
}
for _, link := range []string{
"",
"https://codeforces.com/problems/two-sum/",
"https://leetcode.com/contest/weekly-contest-400/",
"https://leetcode.com/problems/",
"https://leetcode.com/problems/../x/",
"https://evil.com/leetcode.com/problems/two-sum/",
} {
if got, err := Slug(link); err == nil {
t.Errorf("Slug(%q) = %q, want an error", link, got)
}
}
}
// The script's own "Error: ..." line is the message, not the exit status.
func TestImportError(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
@@ -46,3 +72,19 @@ func TestImportError(t *testing.T) {
t.Fatalf("Import = %v, want the script's message", err)
}
}
// The script is the clone's, so it must not see the server's secrets.
func TestImportHidesSecrets(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("no python3")
}
t.Setenv("CLAUDE_API_KEY", "sk-secret")
t.Setenv("GIT_TOKEN", "gitea-secret")
root := t.TempDir()
os.MkdirAll(filepath.Join(root, "lib"), 0o755)
script := "import os, sys\nleaked = [k for k in ('CLAUDE_API_KEY', 'GIT_TOKEN') if k in os.environ]\nprint('Error: leaked ' + ','.join(leaked) if leaked else 'Error: clean', file=sys.stderr)\nsys.exit(1)\n"
os.WriteFile(filepath.Join(root, "lib", "leetcode.py"), []byte(script), 0o644)
if err := (&Importer{}).Import(context.Background(), root, "x"); err == nil || err.Error() != "clean" {
t.Fatalf("Import = %v, want the script to see no secrets", err)
}
}
+17 -4
View File
@@ -52,10 +52,14 @@ type Repo struct {
cfg Config
askpass string
// onChange runs under the lock after every sync or edit, with the clone
// in a consistent state, so the index is never built from a half-reset
// tree.
// onChange runs under the lock after a sync or edit that moved HEAD,
// with the clone in a consistent state, so the index is never built
// from a half-reset tree.
onChange func(dir string) error
// indexed is the HEAD onChange last succeeded on. A sync that finds
// nothing new (the interval's pull, the webhook for the site's own
// push) skips the rebuild, which reads every file and the whole log.
indexed string
mu sync.Mutex
}
@@ -163,7 +167,16 @@ func (r *Repo) changed() error {
if r.onChange == nil {
return nil
}
return r.onChange(r.cfg.Dir)
out, err := r.git(context.Background(), "rev-parse", "HEAD")
head := strings.TrimSpace(out)
if err == nil && head == r.indexed {
return nil
}
if err := r.onChange(r.cfg.Dir); err != nil {
return err
}
r.indexed = head
return nil
}
// Mutate syncs, lets edit change files in the clone, and commits the result
+34
View File
@@ -90,6 +90,40 @@ func TestSyncClonesThenFollowsRemote(t *testing.T) {
if *changes != 2 {
t.Fatalf("onChange ran %d times, want 2", *changes)
}
// Nothing new: no rebuild.
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
if *changes != 2 {
t.Fatalf("a sync with nothing new ran onChange (%d times)", *changes)
}
}
// A rebuild that failed is tried again on the next sync, though HEAD has
// not moved since.
func TestFailedRebuildIsRetried(t *testing.T) {
bare, _ := remote(t)
fail := true
calls := 0
r, err := New(Config{Dir: filepath.Join(t.TempDir(), "clone"), Remote: "file://" + bare, Branch: "main", Push: true},
func(string) error {
calls++
if fail {
return os.ErrInvalid
}
return nil
})
if err != nil {
t.Fatal(err)
}
if err := r.Sync(context.Background()); err == nil {
t.Fatal("the failed rebuild was not reported")
}
fail = false
if err := r.Sync(context.Background()); err != nil || calls != 2 {
t.Fatalf("retry: err %v, %d calls, want 2", err, calls)
}
}
func TestMutateCommitsAndPushes(t *testing.T) {
+1 -1
View File
@@ -264,7 +264,7 @@ type Meta struct {
// Generate asks Claude and returns the review's markdown.
func Generate(ctx context.Context, a explain.Asker, in Input, meta Meta) (string, error) {
var r Result
err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
err := a.JSON(ctx, claude.Request{Tag: "review", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
if err != nil {
return "", err
}
+234
View File
@@ -0,0 +1,234 @@
// Package usage keeps a ledger of what the site's Claude calls cost, and
// enforces an optional monthly budget on them.
//
// Each call is one JSON line in DATA_DIR/usage.jsonl: its tokens, the model
// that answered (a server-side fallback can make that a different one) and
// an estimated cost. The estimate is the token counts times the price table
// below. It is not the bill: it leaves out the transcriber, which costs a
// fraction of a cent a minute.
package usage
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"sort"
"strings"
"sync"
"time"
)
// Price is a model's rate in dollars per million tokens.
type Price struct{ In, Out, CacheRead float64 }
// cacheWrite is a 5-minute cache write's rate as a multiple of the input
// rate. The site only writes 5-minute entries (claude.Client caches the
// system prompt).
const cacheWrite = 1.25
// prices are Anthropic's first-party rates. A model is matched by the
// longest id that prefixes it.
var prices = map[string]Price{
"claude-fable-5-1": {10, 50, 0.25},
"claude-fable-5": {10, 50, 1},
"claude-opus-5-5": {4, 20, 0.20},
"claude-opus-5": {5, 25, 0.50},
"claude-opus-4-8": {5, 25, 0.50},
"claude-opus-4-7": {5, 25, 0.50},
"claude-opus-4-6": {5, 25, 0.50},
"claude-sonnet-5-5": {2, 10, 0.20},
"claude-sonnet-5": {2, 10, 0.20},
"claude-sonnet-4-6": {3, 15, 0.30},
"claude-haiku-5-5": {0.10, 0.50, 0.01},
"claude-haiku-4-5": {1, 5, 0.10},
}
// unknown prices a model the table does not have at the most expensive
// rate, so a budget errs on the side of stopping early.
var unknown = prices["claude-fable-5-1"]
// PriceOf is model's rate, and whether the table knows it.
func PriceOf(model string) (Price, bool) {
best := ""
for id := range prices {
if strings.HasPrefix(model, id) && len(id) > len(best) {
best = id
}
}
if best == "" {
return unknown, false
}
return prices[best], true
}
// Entry is one call.
type Entry struct {
Time time.Time `json:"time"`
Kind string `json:"kind"`
Model string `json:"model"`
In int64 `json:"in"`
CacheRead int64 `json:"cacheRead,omitempty"`
CacheWrite int64 `json:"cacheWrite,omitempty"`
Out int64 `json:"out"`
Cost float64 `json:"cost"`
}
// Estimate fills in e.Cost from its tokens.
func (e *Entry) Estimate() {
p, ok := PriceOf(e.Model)
if !ok {
log.Printf("[usage] no price for %s; counted at the highest rate", e.Model)
}
e.Cost = (float64(e.In)*p.In + float64(e.CacheRead)*p.CacheRead +
float64(e.CacheWrite)*p.In*cacheWrite + float64(e.Out)*p.Out) / 1e6
}
// ErrOverBudget is a call refused because this month's spend has reached
// the budget.
var ErrOverBudget = errors.New("over budget")
// Ledger is the record of every call. A nil *Ledger records nothing and
// allows everything, so the tests and a server without a data directory
// need no special case.
type Ledger struct {
path string
budget float64
mu sync.Mutex
entries []Entry
}
// Open loads the ledger at path (a missing file is an empty ledger).
// budget is the monthly limit in dollars; 0 means none.
func Open(path string, budget float64) (*Ledger, error) {
l := &Ledger{path: path, budget: budget}
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return l, nil
}
if err != nil {
return nil, err
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
var e Entry
if err := json.Unmarshal(sc.Bytes(), &e); err != nil {
// A line cut short by a crash costs that one call, not the
// ledger.
log.Printf("[usage] %s: skipping an unreadable line: %v", path, err)
continue
}
l.entries = append(l.entries, e)
}
return l, sc.Err()
}
// Record estimates e's cost and appends it.
func (l *Ledger) Record(e Entry) {
if l == nil {
return
}
if e.Time.IsZero() {
e.Time = time.Now()
}
e.Estimate()
l.mu.Lock()
defer l.mu.Unlock()
l.entries = append(l.entries, e)
b, _ := json.Marshal(e)
f, err := os.OpenFile(l.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600)
if err != nil {
log.Printf("[usage] %v", err)
return
}
defer f.Close()
if _, err := f.Write(append(b, '\n')); err != nil {
log.Printf("[usage] %v", err)
}
}
func month(t time.Time) string { return t.UTC().Format("2006-01") }
// spent is the month's total. The caller holds l.mu.
func (l *Ledger) spent(now time.Time) float64 {
m, total := month(now), 0.0
for _, e := range l.entries {
if month(e.Time) == m {
total += e.Cost
}
}
return total
}
// Allow refuses a new call once this month's spend has reached the budget.
// A call already running is never stopped, so a month can end a little
// over it.
func (l *Ledger) Allow(now time.Time) error {
if l == nil || l.budget <= 0 {
return nil
}
l.mu.Lock()
defer l.mu.Unlock()
if spent := l.spent(now); spent >= l.budget {
return fmt.Errorf("%w: $%.2f of this month's $%.2f Claude budget is spent; it resets on the 1st (CLAUDE_MONTHLY_BUDGET)", ErrOverBudget, spent, l.budget)
}
return nil
}
// Total is one month's or one kind's spend.
type Total struct {
Name string `json:"name"`
Calls int `json:"calls"`
Cost float64 `json:"cost"`
}
// Summary is what the stats page shows the admin.
type Summary struct {
Tracked bool `json:"tracked"`
Budget float64 `json:"budget,omitempty"`
Month float64 `json:"month"`
// Months are newest first; Kinds are this month's, costliest first.
Months []Total `json:"months"`
Kinds []Total `json:"kinds"`
}
// Summarize totals the ledger by month, and this month by kind.
func (l *Ledger) Summarize(now time.Time) Summary {
s := Summary{Months: []Total{}, Kinds: []Total{}}
if l == nil {
return s
}
l.mu.Lock()
defer l.mu.Unlock()
s.Tracked, s.Budget, s.Month = true, l.budget, l.spent(now)
months, kinds := map[string]*Total{}, map[string]*Total{}
add := func(m map[string]*Total, name string, e Entry) {
t := m[name]
if t == nil {
t = &Total{Name: name}
m[name] = t
}
t.Calls++
t.Cost += e.Cost
}
this := month(now)
for _, e := range l.entries {
add(months, month(e.Time), e)
if month(e.Time) == this {
add(kinds, e.Kind, e)
}
}
for _, t := range months {
s.Months = append(s.Months, *t)
}
for _, t := range kinds {
s.Kinds = append(s.Kinds, *t)
}
sort.Slice(s.Months, func(i, j int) bool { return s.Months[i].Name > s.Months[j].Name })
sort.Slice(s.Kinds, func(i, j int) bool { return s.Kinds[i].Cost > s.Kinds[j].Cost })
return s
}
+72
View File
@@ -0,0 +1,72 @@
package usage
import (
"errors"
"math"
"os"
"path/filepath"
"testing"
"time"
)
func near(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
func TestEstimate(t *testing.T) {
e := Entry{Model: "claude-opus-5-5", In: 1_000_000, CacheRead: 1_000_000, CacheWrite: 1_000_000, Out: 1_000_000}
e.Estimate()
if want := 4 + 0.20 + 5 + 20.0; !near(e.Cost, want) {
t.Fatalf("opus 5.5 = %v, want %v", e.Cost, want)
}
// The longest prefix wins: claude-opus-5-5 is not claude-opus-5.
if p, ok := PriceOf("claude-opus-5"); !ok || p.In != 5 {
t.Fatalf("opus 5 = %+v %v", p, ok)
}
if p, ok := PriceOf("claude-something-new"); ok || p != unknown {
t.Fatalf("unknown = %+v %v", p, ok)
}
}
func TestBudgetAndSummary(t *testing.T) {
path := filepath.Join(t.TempDir(), "usage.jsonl")
l, err := Open(path, 1)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 10, 23, 12, 0, 0, 0, time.UTC)
last := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
// $0.40 output each on Opus 5.5.
l.Record(Entry{Time: last, Kind: "explain", Model: "claude-opus-5-5", Out: 20_000})
l.Record(Entry{Time: now, Kind: "explain", Model: "claude-opus-5-5", Out: 20_000})
if err := l.Allow(now); err != nil {
t.Fatalf("$0.40 of $1 refused: %v", err)
}
l.Record(Entry{Time: now, Kind: "review", Model: "claude-opus-5-5", Out: 40_000})
if err := l.Allow(now); !errors.Is(err, ErrOverBudget) {
t.Fatalf("$1.20 of $1 = %v", err)
}
// Reopened from disk, with a torn last line.
f, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
f.WriteString(`{"time":"2026-10`)
f.Close()
l, err = Open(path, 0)
if err != nil {
t.Fatal(err)
}
if err := l.Allow(now); err != nil {
t.Fatalf("no budget refused: %v", err)
}
s := l.Summarize(now)
if !s.Tracked || !near(s.Month, 1.2) || len(s.Months) != 2 || s.Months[0].Name != "2026-10" || s.Months[0].Calls != 2 {
t.Fatalf("summary = %+v", s)
}
if len(s.Kinds) != 2 || s.Kinds[0].Name != "review" {
t.Fatalf("kinds = %+v", s.Kinds)
}
var none *Ledger
none.Record(Entry{Model: "claude-opus-5-5"})
if none.Allow(now) != nil || none.Summarize(now).Tracked {
t.Fatal("a nil ledger should allow everything and track nothing")
}
}
+24
View File
@@ -8,6 +8,7 @@
"name": "usaco-site-web",
"version": "0.0.0",
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-python": "^6.2.1",
@@ -16,6 +17,7 @@
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.5",
"@replit/codemirror-vim": "^6.4.0",
"@vscode/markdown-it-katex": "^1.1.2",
"codemirror": "^6.0.2",
"dompurify": "^3.4.17",
@@ -748,6 +750,28 @@
"node": "^22.20 || ^24.12 || >=25"
}
},
"node_modules/@replit/codemirror-vim": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/@replit/codemirror-vim/-/codemirror-vim-6.4.0.tgz",
"integrity": "sha512-t9UMDNhkmeAkl0uRbiJVotv97bGD6mf4GyJJoEbrjUqa/Pov0s9eL+4AaI0Xto3OGri17i9qwIpT0JbVlVXt8A==",
"license": "MIT",
"dependencies": {
"@replit/codemirror-vim-core": "^0.1.0"
},
"peerDependencies": {
"@codemirror/commands": "6.x.x",
"@codemirror/language": "6.x.x",
"@codemirror/search": "6.x.x",
"@codemirror/state": "6.x.x",
"@codemirror/view": "6.x.x"
}
},
"node_modules/@replit/codemirror-vim-core": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/@replit/codemirror-vim-core/-/codemirror-vim-core-0.1.0.tgz",
"integrity": "sha512-1i6EBKpcNfDKvTmTh6N6g9lL6udD5t+uFNh4JCqozRnVlvUGOps7h/QzS2ne4zcvPUjvApKpmcP7Grc3fNbZiQ==",
"license": "MIT"
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+2
View File
@@ -12,6 +12,7 @@
"preview": "vite preview"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-python": "^6.2.1",
@@ -20,6 +21,7 @@
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.5",
"@replit/codemirror-vim": "^6.4.0",
"@vscode/markdown-it-katex": "^1.1.2",
"codemirror": "^6.0.2",
"dompurify": "^3.4.17",
+39 -8
View File
@@ -17,9 +17,9 @@ const route = useRoute();
<RouterLink to="/" class="brand">USACO practice</RouterLink>
<nav>
<RouterLink to="/" exact-active-class="on">Problems</RouterLink>
<RouterLink to="/concepts" :class="{ on: route.name === 'concept' }" active-class="on">Concepts</RouterLink>
<RouterLink to="/stats" active-class="on">Stats</RouterLink>
<RouterLink to="/cli" active-class="on">CLI</RouterLink>
<a href="/gitea/adamf/usaco">Source</a>
<a href="/">adam-french.co.uk</a>
</nav>
</header>
@@ -33,7 +33,7 @@ const route = useRoute();
.shell {
max-width: 1100px;
margin: 0 auto;
padding: 0 16px 48px;
padding: 0 24px 56px;
}
.shell.wide {
max-width: none;
@@ -60,9 +60,20 @@ const route = useRoute();
align-items: baseline;
justify-content: space-between;
gap: 8px 24px;
padding: 24px 0 16px;
padding: 28px 0 18px;
border-bottom: 1px solid var(--color-line);
margin-bottom: 24px;
margin-bottom: 32px;
position: relative;
}
.top::after {
content: "";
position: absolute;
left: 0;
bottom: -2px;
width: 64px;
height: 3px;
border-radius: 2px;
background: var(--color-accent);
}
.brand {
font-family: var(--font-heading);
@@ -75,17 +86,37 @@ const route = useRoute();
nav {
display: flex;
flex-wrap: wrap;
gap: 4px 20px;
gap: 4px 6px;
}
nav a {
padding: 6px 10px;
border-radius: 5px;
color: var(--color-ink-muted);
text-decoration: none;
white-space: nowrap;
}
nav a:hover,
nav a.on {
color: var(--color-ink);
text-decoration: underline;
text-underline-offset: 4px;
color: var(--color-accent);
background: var(--color-accent-soft);
text-decoration: none;
}
@media (max-width: 640px) {
.shell {
padding: 0 16px 40px;
}
.top {
align-items: flex-start;
margin-bottom: 24px;
}
.brand {
font-size: 2rem;
}
nav {
gap: 2px;
}
nav a {
padding: 5px 7px;
}
}
</style>
+30
View File
@@ -60,6 +60,36 @@ export const runCode = (name, body) => request("POST", `/problems/${encodeURICom
export const lintCode = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/lint`, body);
// Commits the source as the problem's solution file in that language.
export const saveCode = (name, body) => request("PUT", `/problems/${encodeURIComponent(name)}/code`, body);
// body: { lang, source, note? }. Starts Claude judging the source (after a
// run of the saved tests) and answers 202; the status's result is the
// evaluation once it is done. Nothing is committed.
export const startEvaluate = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/evaluate`, body);
export const evaluateStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/evaluate`);
// Imports today's LeetCode daily question (or finds it, if it is already a
// problem) and answers { name, created }. It takes a few seconds.
export const startDaily = () => request("POST", "/leetcode/daily");
// The same for the problem a LeetCode link names.
export const importLeetCode = (url) => request("POST", "/leetcode/import", { url });
// Concepts: techniques Claude explained, with a C++ snippet. Anyone can read
// them; starting one answers 202 { id, status } and the job's status, at
// conceptJob(id), has result { slug } once it is saved.
export const listConcepts = () => request("GET", "/concepts");
export const getConcept = (slug) => request("GET", `/concepts/${encodeURIComponent(slug)}`);
// body: { topic, code? }
export const startConcept = (body) => request("POST", "/concepts", body);
export const conceptJob = (id) => request("GET", `/concept-jobs/${encodeURIComponent(id)}`);
// body: { note? }. Rewrites the concept in place; polled like an explanation.
export const rewriteConcept = (slug, body) => request("POST", `/concepts/${encodeURIComponent(slug)}/explain`, body);
export const rewriteStatus = (slug) => request("GET", `/concepts/${encodeURIComponent(slug)}/explain`);
export const deleteConcept = (slug) => request("DELETE", `/concepts/${encodeURIComponent(slug)}`);
// Every job status carries its kind and key. One that ends with unsaved:
// true wrote its answer but could not commit it; this commits that answer
// again, without asking Claude again, and answers the job (running), which
// is then polled at its usual status route.
export const saveJobAgain = (job) =>
request("POST", `/jobs/${encodeURIComponent(job.kind)}/${encodeURIComponent(job.key)}/save`);
// The admin's Claude spend: { tracked, budget, month, months, kinds }.
export const getUsage = () => request("GET", "/usage");
+47 -12
View File
@@ -32,13 +32,16 @@
--color-ink-soft: #333;
--color-ink-muted: #555;
--color-ink-faint: #8a8a8a;
--color-ink-link: #0066cc;
--color-ink-link: #1d5f8f;
--color-ink-danger: #c00;
--color-paper: #fff;
--color-paper-tint: #f5f5f5;
--color-paper-shade: #eee;
--color-line: #ccc;
--color-line-soft: #e0e0e0;
--color-paper-tint: #f4f1eb;
--color-paper-shade: #ebe7df;
--color-line: #c8c2b7;
--color-line-soft: #ded9d0;
--color-accent: #1d5f8f;
--color-accent-soft: #e3edf3;
--shadow-paper: 0 10px 26px rgb(46 39 28 / 0.06), 0 1px 2px rgb(46 39 28 / 0.08);
/* Status: identity, so always shown with its label, never colour alone. */
--color-solved: #0a7d0a;
@@ -63,6 +66,7 @@ body {
min-height: 100vh;
overflow-x: hidden;
background: var(--color-paper-tint);
background-image: linear-gradient(rgb(255 255 255 / 0.22), transparent 240px);
color: var(--color-ink);
line-height: 1.5;
}
@@ -80,6 +84,24 @@ a {
color: var(--color-ink-link);
}
input,
select,
textarea {
transition: border-color 120ms ease, box-shadow 120ms ease, background 120ms ease;
}
input:focus,
select:focus,
textarea:focus {
border-color: var(--color-accent);
box-shadow: 0 0 0 3px rgb(29 95 143 / 0.14);
outline: none;
}
::selection {
background: #c8dbe8;
color: var(--color-ink);
}
/* Preflight leaves focus to the browser default, which is faint on the
paper background; keyboard users get a clear ring everywhere. */
:focus-visible {
@@ -90,7 +112,8 @@ a {
.card {
background: var(--color-paper);
border: 1px solid var(--color-line-soft);
border-radius: 6px;
border-radius: 8px;
box-shadow: var(--shadow-paper);
}
.badge {
@@ -117,23 +140,34 @@ a {
}
.btn {
min-height: 34px;
padding: 6px 14px;
border: 1px solid var(--color-line);
border-radius: 4px;
border-radius: 5px;
background: var(--color-paper);
color: var(--color-ink);
cursor: pointer;
font: inherit;
transition: border-color 120ms ease, background 120ms ease, transform 120ms ease;
}
.btn:hover:not(:disabled) {
border-color: var(--color-ink-muted);
border-color: var(--color-accent);
background: var(--color-accent-soft);
color: var(--color-accent);
transform: translateY(-1px);
}
.btn:disabled {
opacity: 0.5;
cursor: default;
}
.btn.primary {
background: var(--color-ink);
border-color: var(--color-ink);
background: var(--color-accent);
border-color: var(--color-accent);
color: var(--color-paper);
}
.btn.primary:hover:not(:disabled) {
background: #174d74;
border-color: #174d74;
color: var(--color-paper);
}
@@ -211,9 +245,10 @@ a {
border-radius: 3px;
}
.prose pre {
background: var(--color-paper-tint);
background: #f1eee8;
padding: 12px;
border-radius: 4px;
border: 1px solid var(--color-line-soft);
border-radius: 6px;
overflow-x: auto;
}
.prose pre code {
+258
View File
@@ -0,0 +1,258 @@
/**
* The solve page's autocomplete. CodeMirror's basicSetup already shows
* completions as you type, but @codemirror/lang-cpp offers none, and
* lang-python only keywords, builtins and the names defined in the file.
*
* Both languages get the library a contest solution reaches for, and
* member names after "." (and "->"), which neither language package does.
* Members are the common STL (or list/dict/str) ones plus every member
* already used in the file: without a type checker, that is as close as a
* completion can get to what the object actually has. C++ also gets every
* name in the file, so the template's macros and typedefs (F, takeI, ll)
* come up with what they expand to, and snippets for the loops and lambdas
* that are typed over and over.
*
* A real language server (clangd) would know types, but would have to run
* beside the code runner and hold a session open per editor; this is local
* and instant.
*/
import { completeFromList, ifNotIn, snippetCompletion as snip } from "@codemirror/autocomplete";
import { syntaxTree } from "@codemirror/language";
import { cppLanguage } from "@codemirror/lang-cpp";
import { pythonLanguage } from "@codemirror/lang-python";
// "a b c" as completions of one type, with a detail (the header).
const words = (list, type, detail) => list.trim().split(/\s+/).map((label) => ({ label, type, detail }));
// ---- C++ ----
const CPP_KEYWORDS = words(
`auto bool break case catch char class const constexpr continue default delete do double else enum explicit
extern false float for friend goto if inline int long mutable namespace new noexcept nullptr operator private
protected public return short signed sizeof static static_assert static_cast struct switch template this throw
true try typedef typename union unsigned using virtual void volatile while`,
"keyword",
);
const CPP_LIBRARY = [
...words(
"vector string array deque list map multimap set multiset unordered_map unordered_set unordered_multimap stack queue priority_queue bitset pair tuple optional function",
"type",
"std",
),
...words("int64_t uint64_t int32_t uint32_t size_t __int128", "type"),
...words("greater less hash", "class", "<functional>"),
...words("cin cout cerr endl", "variable", "<iostream>"),
...words("getline to_string stoi stoll stod freopen printf scanf puts", "function", "<string>/<cstdio>"),
...words(
`sort stable_sort reverse min max swap minmax lower_bound upper_bound equal_range binary_search unique fill
find find_if count count_if max_element min_element next_permutation prev_permutation nth_element
partial_sort rotate all_of any_of none_of transform copy remove remove_if shuffle`,
"function",
"<algorithm>",
),
...words("accumulate iota partial_sum adjacent_difference gcd lcm", "function", "<numeric>"),
...words("abs sqrt sqrtl cbrt pow exp log log2 log10 floor ceil round hypot", "function", "<cmath>"),
...words("make_pair make_tuple tie get move distance next prev advance begin end", "function", "std"),
...words("memset memcpy strlen", "function", "<cstring>"),
...words(
"__builtin_popcount __builtin_popcountll __builtin_clz __builtin_clzll __builtin_ctz __builtin_ctzll __lg",
"function",
"builtin",
),
...words("INT_MAX INT_MIN LLONG_MAX LLONG_MIN UINT_MAX", "constant", "<climits>"),
{ label: "numeric_limits", type: "class", detail: "<limits>" },
{ label: "mt19937", type: "class", detail: "<random>" },
{ label: "chrono", type: "namespace" },
{ label: "std", type: "namespace" },
];
// Nothing knows the object's type, so the members used most come first.
const COMMON_MEMBERS = new Set(["push_back", "size", "begin", "end", "first", "second", "back", "pop_back", "insert", "count"]);
const CPP_MEMBERS = words(
`push_back emplace_back pop_back push_front emplace_front pop_front back front size empty clear begin end
rbegin rend insert emplace erase find count lower_bound upper_bound resize reserve assign at data swap
push pop top first second substr length append c_str compare set reset flip test any none all to_string
to_ullong value has_value`,
"method",
).map((c) => (COMMON_MEMBERS.has(c.label) ? { ...c, boost: 1 } : c));
// The template's habits, as snippets. Same-named fields are edited
// together, so typing the loop variable once fills in all three.
const CPP_SNIPPETS = [
snip("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", { label: "for", detail: "loop", type: "keyword" }),
snip("for (int ${i} = ${n} - 1; ${i} >= 0; ${i}--) {\n\t${}\n}", { label: "forr", detail: "loop down", type: "keyword" }),
snip("for (auto &${x} : ${v}) {\n\t${}\n}", { label: "foreach", detail: "range loop", type: "keyword" }),
snip("while (${}) {\n\t${}\n}", { label: "while", detail: "loop", type: "keyword" }),
snip("if (${}) {\n\t${}\n}", { label: "if", detail: "block", type: "keyword" }),
snip("if (${}) {\n\t${}\n} else {\n\t${}\n}", { label: "ifelse", detail: "block", type: "keyword" }),
snip("struct ${Name} {\n\t${}\n};", { label: "struct", detail: "definition", type: "keyword" }),
snip("auto ${f} = [&](${}) {\n\t${}\n};", { label: "lambda", detail: "[&] lambda", type: "keyword" }),
snip("function<void(int)> ${dfs} = [&](int ${u}) {\n\t${}\n};", {
label: "dfs",
detail: "recursive lambda",
type: "keyword",
}),
snip("sort(${a}.begin(), ${a}.end(), [&](const auto &${x}, const auto &${y}) {\n\treturn ${};\n});", {
label: "sortby",
detail: "sort with a comparator",
type: "keyword",
}),
];
// A keyword with a snippet of the same name would hide it behind a plain
// word, so the snippet stands in for it.
const SNIPPED = new Set(CPP_SNIPPETS.map((c) => c.label));
const CPP_FIXED = [...CPP_KEYWORDS.filter((c) => !SNIPPED.has(c.label)), ...CPP_LIBRARY, ...CPP_SNIPPETS];
const CPP_FIXED_LABELS = new Set(CPP_FIXED.map((c) => c.label));
// Comments, strings and #include <...> get no completions.
const CPP_SKIP = new Set(["LineComment", "BlockComment", "String", "RawString", "CharLiteral", "SystemLibString"]);
const CPP_NAMES = new Set(["Identifier", "TypeIdentifier", "NamespaceIdentifier"]);
// "#define F(i, L, R) for (...)": a macro, shown with its parameters and
// what it expands to.
const DEFINE = /^[ \t]*#[ \t]*define[ \t]+([A-Za-z_]\w*)(\([^)]*\))?/dgm;
// "typedef long long ll;" and "using vi = vector<int>;"
const ALIAS = /\btypedef\s+([^;]+?)\s+([A-Za-z_]\w*)\s*;|\busing\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g;
function brief(s) {
s = s.replace(/\s+/g, " ").trim();
return s.length > 48 ? s.slice(0, 47) + "…" : s;
}
// A macro's body: the rest of its line, and the next while a line ends in
// a backslash.
function macroBody(text, at) {
let body = "";
for (;;) {
const end = text.indexOf("\n", at);
const line = text.slice(at, end < 0 ? text.length : end);
if (!line.endsWith("\\") || end < 0) return body + line;
body += line.slice(0, -1) + " ";
at = end + 1;
}
}
// The file's own names, leaving out the word being typed (at skipFrom):
// otherwise every half-typed name would complete to itself.
function cppFileNames(state, skipFrom) {
const text = state.doc.toString();
const out = new Map();
for (const m of text.matchAll(DEFINE)) {
if (m.indices[1][0] === skipFrom) continue;
const body = brief(macroBody(text, m.index + m[0].length));
// The template defines DBG twice, the #else one empty: keep the one
// that says something.
if (!body && out.has(m[1])) continue;
out.set(m[1], {
label: m[1],
type: m[2] ? "function" : "constant",
detail: m[2] ? m[2].replace(/\s+/g, "") : undefined,
info: body || undefined,
boost: 2,
});
}
for (const m of text.matchAll(ALIAS)) {
const [name, to] = m[2] ? [m[2], m[1]] : [m[3], m[4]];
if (!out.has(name)) out.set(name, { label: name, type: "type", detail: brief(to), boost: 2 });
}
syntaxTree(state).iterate({
enter(n) {
if (CPP_SKIP.has(n.name)) return false;
if (!CPP_NAMES.has(n.name) || n.from === skipFrom) return;
const name = text.slice(n.from, n.to);
if (name.length < 2 || out.has(name) || CPP_FIXED_LABELS.has(name)) return;
out.set(name, { label: name, type: n.name === "TypeIdentifier" ? "type" : "variable", boost: 1 });
},
});
return [...out.values()];
}
// Members already used in the file (x.first, it->second, seg.query).
function fileMembers(state, nodeName, skipFrom, known) {
const out = [];
const seen = new Set(known);
syntaxTree(state).iterate({
enter(n) {
if (n.name !== nodeName || n.from === skipFrom) return;
const name = state.sliceDoc(n.from, n.to);
if (seen.has(name)) return;
seen.add(name);
out.push({ label: name, type: "property" });
},
});
return out;
}
const CPP_MEMBER_LABELS = CPP_MEMBERS.map((c) => c.label);
// Whether the word at from follows a member access: "." but not the one in
// "1." (a number), and in C++ "->" too.
function afterMember(state, from, arrow) {
const text = state.sliceDoc(Math.max(0, from - 32), from);
if (arrow && text.endsWith("->")) return true;
return text.endsWith(".") && !/(^|[^\w])\d+\.$/.test(text);
}
function cppSource(context) {
const node = syntaxTree(context.state).resolveInner(context.pos, -1);
for (let n = node; n; n = n.parent) if (CPP_SKIP.has(n.name)) return null;
const word = context.matchBefore(/[A-Za-z_]\w*/);
const from = word ? word.from : context.pos;
if (afterMember(context.state, from, true)) {
return {
from,
options: [...CPP_MEMBERS, ...fileMembers(context.state, "FieldIdentifier", from, CPP_MEMBER_LABELS)],
validFor: /^\w*$/,
};
}
if (!word && !context.explicit) return null;
return { from, options: [...cppFileNames(context.state, from), ...CPP_FIXED], validFor: /^\w*$/ };
}
export const cppCompletions = () => cppLanguage.data.of({ autocomplete: cppSource });
// ---- Python ----
// The standard library a contest solution imports from. lang-python
// already completes builtins and the file's own names, and has its own
// def/for/class snippets.
const PY_LIBRARY = [
...words("defaultdict Counter deque OrderedDict", "class", "collections"),
...words("heappush heappop heapify heappushpop nlargest nsmallest", "function", "heapq"),
...words("bisect_left bisect_right insort", "function", "bisect"),
...words("lru_cache cache cmp_to_key reduce", "function", "functools"),
...words("accumulate permutations combinations combinations_with_replacement product groupby pairwise", "function", "itertools"),
...words("gcd lcm isqrt comb perm inf sqrt log2 ceil floor", "function", "math"),
...words("setrecursionlimit stdin stdout", "function", "sys"),
snip("sys.setrecursionlimit(${10 ** 6})", { label: "recursionlimit", detail: "sys", type: "keyword" }),
];
const PY_MEMBERS = words(
`append extend insert pop remove clear sort reverse index count copy keys values items get setdefault update
add discard union intersection difference split join strip lstrip rstrip startswith endswith replace find
lower upper isdigit appendleft popleft most_common read readline buffer`,
"method",
);
const PY_MEMBER_LABELS = PY_MEMBERS.map((c) => c.label);
const pyLibrary = completeFromList(PY_LIBRARY);
function pySource(context) {
const word = context.matchBefore(/[A-Za-z_]\w*/);
const from = word ? word.from : context.pos;
if (afterMember(context.state, from, false)) {
return {
from,
options: [...PY_MEMBERS, ...fileMembers(context.state, "PropertyName", from, PY_MEMBER_LABELS)],
validFor: /^\w*$/,
};
}
// lang-python leaves property names alone; everywhere else the library
// joins its builtins.
return pyLibrary(context);
}
export const pythonCompletions = () =>
pythonLanguage.data.of({ autocomplete: ifNotIn(["String", "FormatString", "Comment"], pySource) });
+3 -20
View File
@@ -1,19 +1,9 @@
<script setup>
/**
* A file with line numbers, highlighting and a copy button. Only the
* languages the workspace uses are registered, which keeps highlight.js to a
* few kilobytes instead of the full bundle.
* A file with line numbers, highlighting and a copy button.
*/
import { computed, ref } from "vue";
import hljs from "highlight.js/lib/core";
import cpp from "highlight.js/lib/languages/cpp";
import python from "highlight.js/lib/languages/python";
import rust from "highlight.js/lib/languages/rust";
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("c", cpp);
hljs.registerLanguage("python", python);
hljs.registerLanguage("rust", rust);
import { highlight } from "@/highlight";
const props = defineProps({
content: { type: String, required: true },
@@ -21,14 +11,7 @@ const props = defineProps({
truncated: { type: Boolean, default: false },
});
// highlight.js escapes the source itself, so v-html on its output is safe.
const html = computed(() => {
const text = props.content.replace(/\n$/, "");
if (props.lang && hljs.getLanguage(props.lang)) {
return hljs.highlight(text, { language: props.lang }).value;
}
return text.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
});
const html = computed(() => highlight(props.content.replace(/\n$/, ""), props.lang));
const lines = computed(() => props.content.replace(/\n$/, "").split("\n").length);
const copied = ref(false);
+59 -5
View File
@@ -14,10 +14,18 @@
* is remote and debounced by the page), and are pushed with setDiagnostics
* rather than through a linter() source the editor would schedule itself.
* CodeMirror maps them through later edits until the next set arrives.
*
* Completions come from basicSetup's autocompletion with sources of our own
* (completions.js), since lang-cpp has none.
*
* Vim keys (@replit/codemirror-vim) sit in a Compartment, unlike the
* language: turning them on or off keeps the text and its history. The
* states put aside for the other languages are brought up to date when
* they are swapped back in.
*/
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { basicSetup } from "codemirror";
import { EditorState, Prec } from "@codemirror/state";
import { Compartment, EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { indentWithTab } from "@codemirror/commands";
import { HighlightStyle, indentUnit, syntaxHighlighting } from "@codemirror/language";
@@ -25,6 +33,8 @@ import { lintGutter, setDiagnostics } from "@codemirror/lint";
import { cpp } from "@codemirror/lang-cpp";
import { python } from "@codemirror/lang-python";
import { tags as t } from "@lezer/highlight";
import { CodeMirror, vim } from "@replit/codemirror-vim";
import { cppCompletions, pythonCompletions } from "@/completions";
const props = defineProps({
modelValue: { type: String, required: true },
@@ -32,14 +42,15 @@ const props = defineProps({
// The server's: 1-based line/col, endLine/endCol optional.
diagnostics: { type: Array, default: () => [] },
label: { type: String, default: "Code" },
vim: { type: Boolean, default: false },
});
const emit = defineEmits(["update:modelValue", "run", "submit", "save"]);
// The workspace's styles: clang-format's two spaces for C++, PEP 8's four.
const LANGS = {
cpp: () => [cpp(), indentUnit.of(" ")],
c: () => [cpp(), indentUnit.of(" ")],
python: () => [python(), indentUnit.of(" ")],
cpp: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
c: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
python: () => [python(), pythonCompletions(), indentUnit.of(" ")],
};
const highlight = HighlightStyle.define([
@@ -95,10 +106,35 @@ const theme = EditorView.theme(
".cm-diagnostic-info": { borderLeftColor: "var(--color-ink-faint)" },
".cm-diagnosticSource": { color: "var(--color-ink-muted)" },
".cm-panels": { backgroundColor: "var(--color-paper-tint)", color: "var(--color-ink)" },
".cm-tooltip.cm-tooltip-autocomplete > ul": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", maxHeight: "16em" },
".cm-tooltip.cm-tooltip-autocomplete > ul > li": { padding: "1px 8px 1px 4px" },
".cm-tooltip-autocomplete ul li[aria-selected]": { backgroundColor: "#d7e6fb", color: "var(--color-ink)" },
".cm-completionMatchedText": { textDecoration: "none", fontWeight: "600" },
".cm-completionDetail": { color: "var(--color-ink-muted)", fontStyle: "normal", marginLeft: "1em" },
".cm-completionIcon": { opacity: "0.55" },
".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" },
".cm-snippetField": { backgroundColor: "rgba(0, 0, 0, 0.05)" },
// The vim extension's own theme is at the highest precedence, so these
// win on specificity (the cursor layer) instead.
".cm-vimCursorLayer .cm-fat-cursor": { background: "#9ec5f4", color: "var(--color-ink)" },
"&:not(.cm-focused) .cm-vimCursorLayer .cm-fat-cursor": { background: "none", outline: "1px solid #5598e7" },
".cm-panels-bottom": { borderTop: "1px solid var(--color-line-soft)" },
".cm-vim-panel": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "2px 12px" },
".cm-vim-panel input": { fontFamily: "inherit", fontSize: "inherit", color: "var(--color-ink)" },
},
{ dark: false },
);
// The status line shows the mode and the command being typed; vim must
// come before basicSetup's keymaps, which then work in insert mode.
const vimKeys = new Compartment();
const vimExtension = (on) => (on ? vim({ status: true }) : []);
// :w is vim's save, which calls CodeMirror.commands.save if there is one.
// It is global, so it finds the editor's own handler through the view.
const savers = new WeakMap();
CodeMirror.commands.save = (cm) => savers.get(cm.cm6)?.();
// The page also listens for these on the window, for when the editor is not
// focused; stopping them here keeps one press from running twice, and keeps
// basicSetup's Mod-Enter (insert a blank line) out of the way.
@@ -119,6 +155,7 @@ function newState(doc, lang) {
doc,
extensions: [
pageKeys,
vimKeys.of(vimExtension(props.vim)),
basicSetup,
keymap.of([indentWithTab]),
(LANGS[lang] || (() => []))(),
@@ -162,6 +199,7 @@ function pushDiagnostics() {
onMounted(() => {
view = new EditorView({ state: newState(props.modelValue, props.lang), parent: host.value });
savers.set(view, () => emit("save"));
states.set(props.lang, view.state);
});
onBeforeUnmount(() => view?.destroy());
@@ -178,6 +216,7 @@ watch(
states.set(oldLang, view.state);
const kept = states.get(lang);
view.setState(kept && kept.doc.toString() === value ? kept : newState(value, lang));
syncVim();
pushDiagnostics();
} else if (value !== view.state.doc.toString()) {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
@@ -186,7 +225,22 @@ watch(
);
watch(() => props.diagnostics, () => view && pushDiagnostics());
defineExpose({ focus: () => view?.focus() });
function syncVim() {
const on = vimKeys.get(view.state).length > 0;
if (on !== props.vim) view.dispatch({ effects: vimKeys.reconfigure(vimExtension(props.vim)) });
}
watch(() => props.vim, () => view && syncVim());
// Puts the cursor at the start of a line's code and shows it.
function goto(line) {
if (!view) return;
const l = view.state.doc.line(Math.min(Math.max(line, 1), view.state.doc.lines));
const at = l.from + (/^\s*/.exec(l.text)?.[0].length || 0);
view.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
view.focus();
}
defineExpose({ focus: () => view?.focus(), goto });
</script>
<template>
@@ -0,0 +1,280 @@
<script setup>
/**
* The solve page's Evaluation tab: Claude's judgement of the code in the
* editor (internal/evaluate), after a run of the saved tests.
*
* It is about the source it was given, which the editor may have moved on
* from: the report says so rather than hiding, since most of it still
* applies after a small fix. Its issues are also marked in the editor by
* the page, on the lines they were about, for as long as those lines are
* unchanged.
*/
import { computed } from "vue";
import CodeBlock from "@/components/CodeBlock.vue";
import { markdown } from "@/markdown";
import { EVAL_VERDICTS, LANG_LABELS } from "@/format";
const props = defineProps({
// The job: { state: idle | running | done | error, error? }.
job: { type: Object, required: true },
evaluation: { type: Object, default: null },
// The editor's language, and whether its source is still the one judged.
lang: { type: String, required: true },
stale: { type: Boolean, default: false },
// Why Evaluate is off, or "".
disabled: { type: String, default: "" },
note: { type: String, default: "" },
});
defineEmits(["evaluate", "goto", "use-input", "update:note"]);
const md = markdown();
const render = (s) => (s ? md.render(s) : "");
const ev = computed(() => props.evaluation);
const verdict = computed(() => EVAL_VERDICTS[ev.value?.verdict] || { label: ev.value?.verdict, tone: "plain" });
const otherLang = computed(() => !!ev.value && ev.value.lang !== props.lang);
const running = computed(() => props.job.state === "running");
const at = computed(() =>
ev.value ? new Date(ev.value.at).toLocaleString(undefined, { hour: "2-digit", minute: "2-digit", day: "numeric", month: "short" }) : "",
);
const counter = computed(() => (ev.value?.counterexample?.input ? ev.value.counterexample : null));
</script>
<template>
<div class="evaluation">
<form class="ask" @submit.prevent="$emit('evaluate')">
<input
:value="note"
type="text"
maxlength="4000"
placeholder="Anything to check? (optional) e.g. overflow, the n = 1 case"
aria-label="What Claude should look at"
@input="$emit('update:note', $event.target.value)"
/>
<button class="btn" type="submit" :disabled="!!disabled || running" :title="disabled">
{{ running ? "Evaluating…" : ev ? "Evaluate again" : "Evaluate" }}
</button>
</form>
<p v-if="running" class="working" role="status">
Running the saved tests, then Claude reads the code. This takes a minute or two.
</p>
<p v-else-if="job.state === 'error'" class="error" role="status">Evaluation failed: {{ job.error }}</p>
<p v-else-if="!ev" class="muted intro">
Claude judges the code in the editor against the statement and the saved tests' verdicts: whether it will be
accepted, its complexity, the lines that are wrong, and an input that breaks it. Nothing is committed.
</p>
<template v-if="ev">
<p class="facts">
<span class="badge verdict" :class="verdict.tone">{{ verdict.label }}</span>
<span v-if="ev.tests" class="muted">Tests: {{ ev.tests }}</span>
<span class="muted">{{ LANG_LABELS[ev.lang] || ev.lang }} · {{ ev.model }} · {{ at }}</span>
</p>
<p v-if="otherLang" class="stale">
This is about your {{ LANG_LABELS[ev.lang] || ev.lang }} code; its issues are not marked in this editor.
</p>
<p v-else-if="stale" class="stale">
The code has changed since. Issues stay marked on the lines that haven't.
</p>
<div class="prose" v-html="render(ev.summary)"></div>
<section v-if="ev.issues?.length">
<h3>Issues</h3>
<ul class="issues">
<li v-for="(is, i) in ev.issues" :key="i">
<p class="issue-head">
<span class="sev" :class="is.severity" :title="is.severity" aria-hidden="true"></span>
<button v-if="is.line && !otherLang" type="button" class="line" @click="$emit('goto', is.line)">
Line {{ is.line }}
</button>
<span v-else-if="is.line" class="line plain">Line {{ is.line }}</span>
<strong>{{ is.title }}</strong>
<span class="visually-hidden">({{ is.severity }})</span>
</p>
<div class="prose detail" v-html="render(is.detail)"></div>
</li>
</ul>
</section>
<section v-if="counter">
<h3>Counterexample</h3>
<div class="io">
<div>
<p class="filename muted">Input</p>
<CodeBlock :content="counter.input" />
</div>
<div>
<p class="filename muted">Expected</p>
<CodeBlock :content="counter.expected" />
</div>
</div>
<div class="prose" v-html="render(counter.why)"></div>
<button class="btn" type="button" @click="$emit('use-input', counter.input)">Use as custom input</button>
</section>
<section v-if="ev.correctness">
<h3>Correctness</h3>
<div class="prose" v-html="render(ev.correctness)"></div>
</section>
<section v-if="ev.complexity">
<h3>Complexity</h3>
<div class="prose" v-html="render(ev.complexity)"></div>
</section>
<section v-if="ev.style">
<h3>Style</h3>
<div class="prose" v-html="render(ev.style)"></div>
</section>
</template>
</div>
</template>
<style scoped>
.evaluation {
display: grid;
gap: 12px;
min-width: 0;
font-size: 0.9rem;
}
.evaluation > * {
min-width: 0;
}
.ask {
display: flex;
gap: 8px;
}
.ask input {
flex: 1;
min-width: 0;
padding: 6px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
font-size: 0.85rem;
color: var(--color-ink);
background: var(--color-paper);
}
.intro {
font-size: 0.85rem;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 12px;
font-size: 0.85rem;
}
.verdict {
font-size: 0.8rem;
}
.verdict.ok {
color: var(--color-solved);
border-color: currentColor;
}
.verdict.warn {
color: var(--color-solving);
border-color: currentColor;
}
.verdict.bad {
color: var(--color-ink-danger);
border-color: currentColor;
}
.stale {
font-size: 0.85rem;
color: var(--color-solving);
}
h3 {
font-size: 1.05rem;
margin-bottom: 6px;
}
.issues {
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: 10px;
}
.issue-head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 8px;
}
.detail {
margin: 2px 0 0 16px;
}
.sev {
width: 8px;
height: 8px;
border-radius: 50%;
flex: none;
background: var(--color-ink-faint);
}
.sev.error {
background: var(--color-ink-danger);
}
.sev.warning {
background: var(--color-solving);
}
.line {
font-family: var(--font-mono);
font-size: 0.8rem;
padding: 0 6px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper-tint);
color: var(--color-ink-link);
cursor: pointer;
}
.line.plain {
color: var(--color-ink-muted);
cursor: default;
}
.io {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
margin-bottom: 8px;
}
.io > div {
min-width: 0;
}
.filename {
font-family: var(--font-mono);
font-size: 0.8rem;
margin-bottom: 4px;
}
section > .btn {
margin-top: 8px;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
/* The results panel's pulsing dot: the job is still going. */
.working {
font-size: 0.85rem;
}
.working::before {
content: "";
display: inline-block;
width: 8px;
height: 8px;
margin-right: 8px;
border-radius: 50%;
background: var(--color-solving);
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.25;
}
}
@media (prefers-reduced-motion: reduce) {
.working::before {
animation: none;
}
}
</style>
+19 -2
View File
@@ -11,11 +11,13 @@
* they are inserted as SVG after DOMPurify's SVG profile has stripped
* scripts, event handlers and
* anything else that is not drawing. Claude wrote them, the admin can edit
* them, and the public sees them once the problem is solved.
* them, and the public sees them once the problem is solved. Code fences in
* a language CodeBlock knows (a concept's usage example) are highlighted.
*/
import { computed } from "vue";
import { markdown } from "@/markdown";
import DOMPurify from "dompurify";
import { highlight } from "@/highlight";
const props = defineProps({
source: { type: String, required: true },
@@ -26,7 +28,11 @@ const md = markdown();
const fence = md.renderer.rules.fence;
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
const t = tokens[idx];
if (t.info.trim() !== "svg") return fence(tokens, idx, options, env, self);
const lang = t.info.trim();
if (lang === "cpp" || lang === "python") {
return `<pre class="hljs code"><code>${highlight(t.content.replace(/\n$/, ""), lang)}</code></pre>`;
}
if (lang !== "svg") return fence(tokens, idx, options, env, self);
const clean = DOMPurify.sanitize(t.content, { USE_PROFILES: { svg: true, svgFilters: true } });
return `<figure class="diagram">${clean}</figure>`;
};
@@ -91,6 +97,17 @@ const parts = computed(() => {
background: var(--color-paper);
color: var(--color-ink);
}
.body :deep(pre.code) {
margin: 12px 0;
padding: 12px;
overflow-x: auto;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
background: var(--color-paper);
font-family: var(--font-mono);
font-size: 0.8125rem;
line-height: 1.55;
}
.body :deep(.diagram svg) {
display: block;
width: 100%;
+21 -3
View File
@@ -7,6 +7,9 @@
*
* After a run the panel opens the tab worth reading first: the compile
* error, else the first test that failed, else the first test.
*
* With evaluationTab set there is also an Evaluation tab, whose content is
* the page's (the evaluation slot); the page opens it with show().
*/
import { computed, ref, watch } from "vue";
import CodeBlock from "@/components/CodeBlock.vue";
@@ -19,6 +22,8 @@ const props = defineProps({
running: { type: String, default: "" },
error: { type: String, default: "" },
modelValue: { type: String, default: "" },
// { label, tone: ok | warn | bad | plain | "" } for the Evaluation tab.
evaluationTab: { type: Object, default: null },
});
defineEmits(["update:modelValue"]);
@@ -38,6 +43,7 @@ const warnings = computed(() => compile.value?.ok && compile.value.output?.trim(
const tabs = computed(() => {
const out = [{ id: "custom", label: "Custom input" }];
if (props.evaluationTab) out.push({ id: "evaluation", ...props.evaluationTab });
if (compile.value && !compile.value.ok) out.push({ id: "compile", label: "Compile error", verdict: "bad" });
if (warnings.value) out.push({ id: "warnings", label: "Warnings" });
results.value.forEach((r, i) => {
@@ -77,6 +83,8 @@ const summary = computed(() => {
});
const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plain" : "bad");
defineExpose({ show: (id) => (tab.value = id) });
</script>
<template>
@@ -94,7 +102,12 @@ const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plai
:class="{ on: tab === tb.id }"
@click="tab = tb.id"
>
<span v-if="tb.verdict" class="dot" :class="verdictClass(tb.verdict)" aria-hidden="true"></span>
<span
v-if="tb.verdict || tb.tone"
class="dot"
:class="tb.tone || verdictClass(tb.verdict)"
aria-hidden="true"
></span>
{{ tb.label }}
</button>
</div>
@@ -105,9 +118,11 @@ const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plai
</div>
<div id="run-panel" class="body" role="tabpanel" :aria-labelledby="`tab-${tab}`">
<p v-if="error" class="error">{{ error }}</p>
<p v-if="error && tab !== 'evaluation'" class="error">{{ error }}</p>
<label v-if="tab === 'custom'" class="custom">
<slot v-if="tab === 'evaluation'" name="evaluation"></slot>
<label v-else-if="tab === 'custom'" class="custom">
<span class="muted">
Input for Run ({{ MOD_KEY }}+Enter). Submit ({{ MOD_KEY }}+Shift+Enter) runs the saved tests instead.
</span>
@@ -219,6 +234,9 @@ const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plai
.dot.bad {
background: var(--color-ink-danger);
}
.dot.warn {
background: var(--color-solving);
}
.summary,
.working {
font-size: 0.85rem;
+9
View File
@@ -4,6 +4,15 @@
export const STATUS_LABELS = { solving: "Solving", solved: "Solved", skipped: "Skipped" };
// internal/evaluate's verdicts, with a tone for badges and tab dots.
export const EVAL_VERDICTS = {
correct: { label: "Looks correct", tone: "ok" },
edge_cases: { label: "Misses edge cases", tone: "warn" },
too_slow: { label: "Too slow", tone: "bad" },
wrong: { label: "Wrong", tone: "bad" },
incomplete: { label: "Unfinished", tone: "plain" },
};
export const LANG_LABELS = { cpp: "C++", c: "C", python: "Python", java: "Java", rust: "Rust", go: "Go" };
// "diamond-collector" -> "Diamond Collector"
+22
View File
@@ -0,0 +1,22 @@
/**
* highlight.js with only the languages the workspace uses registered, which
* keeps it to a few kilobytes instead of the full bundle. CodeBlock and the
* code fences in explanations share it.
*/
import hljs from "highlight.js/lib/core";
import cpp from "highlight.js/lib/languages/cpp";
import python from "highlight.js/lib/languages/python";
import rust from "highlight.js/lib/languages/rust";
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("c", cpp);
hljs.registerLanguage("python", python);
hljs.registerLanguage("rust", rust);
const escape = (text) => text.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
// highlight.js escapes the source itself, so the result is safe for v-html.
export function highlight(text, lang) {
if (lang && hljs.getLanguage(lang)) return hljs.highlight(text, { language: lang }).value;
return escape(text);
}
+2
View File
@@ -20,6 +20,8 @@ export default createRouter({
props: true,
meta: { wide: true },
},
{ path: "/concepts", name: "concepts", component: () => import("@/views/ConceptList.vue") },
{ path: "/c/:slug", name: "concept", component: () => import("@/views/ConceptPage.vue"), props: true },
{ path: "/stats", name: "stats", component: () => import("@/views/StatsPage.vue") },
{ path: "/cli", name: "cli", component: () => import("@/views/CliPage.vue") },
{ path: "/:pathMatch(.*)*", redirect: "/" },
+25 -7
View File
@@ -2,13 +2,23 @@
/**
* How to use ./usaco, the workspace CLI. A condensed copy of the repo
* README's Commands section: the Docker build context is site/, so the README
* itself can't be imported. Keep the two in step when the CLI changes.
* itself can't be imported. Keep the two in step when the CLI changes;
* site/docs_test.go fails when a command in the README is missing here.
*/
import { ref } from "vue";
import { getMe } from "@/api";
// The repo on the site's Gitea, behind the same nginx, so a root-relative
// link works.
// link works. It is private (it holds the judges' statements and the
// admin's review transcripts), so only the admin gets links into it; for
// anyone else they would be 404s, and the names render as plain text.
const repo = "/gitea/adamf/usaco";
const src = (path) => `${repo}/src/branch/main/${path}`;
const admin = ref(false);
getMe()
.then((me) => (admin.value = me.admin))
.catch(() => {});
const src = (path) => (admin.value ? (path ? `${repo}/src/branch/main/${path}` : repo) : undefined);
// Every command that takes a problem name accepts a unique prefix, so the
// examples use the full name only where it reads better.
@@ -53,6 +63,7 @@ const sections = [
["usaco open <name>", "Open the saved problem link in a browser."],
["usaco cat <name>", "Print the solution to stdout."],
["usaco copy <name>", "Copy the solution to the clipboard (wl-copy, xclip/xsel, or OSC52 over SSH)."],
["usaco snippet [concept] [name]", "List the concepts explained on this site, print one's C++ snippet, or paste it into a solution above main (the old one goes to a .bak)."],
],
},
{
@@ -90,7 +101,7 @@ usaco [watermelon:solved]> q`;
<h1>The usaco CLI</h1>
<p class="muted">
Every problem here is written in a workspace managed by <a :href="src('usaco')"><code>./usaco</code></a>, a small bash script at
the root of <a :href="repo">the repo on Gitea</a> (the commands themselves are in
the root of <a :href="src('')">the repo on Gitea</a> (the commands themselves are in
<a :href="src('lib/cmd')"><code>lib/cmd/</code></a>). Each problem lives in <code>solving/</code>, <code>solved/</code> or
<code>skipped/</code> as a directory with <code>main.cpp</code> or <code>main.rs</code> and its <code>.in</code>/<code>.out</code>
files. Wherever a command takes a problem name, a unique prefix works too:
@@ -101,8 +112,11 @@ usaco [watermelon:solved]> q`;
<section>
<h2>Setup</h2>
<div class="card body">
<p>Clone the repo and run <code>./usaco</code> from its root:</p>
<pre><code>git clone https://www.adam-french.co.uk{{ repo }}.git</code></pre>
<template v-if="admin">
<p>Clone the repo and run <code>./usaco</code> from its root:</p>
<pre><code>git clone https://www.adam-french.co.uk{{ repo }}.git</code></pre>
</template>
<p v-else>The repo is private. In a clone of it, run <code>./usaco</code> from its root.</p>
<p>Or add this to <code>~/.zshrc</code>:</p>
<pre><code>source ~/Coding/USACO/<a :href="src('usaco.zsh')">usaco.zsh</a></code></pre>
<p>
@@ -167,7 +181,7 @@ section {
min-width: 0;
}
h1 {
font-size: 2.25rem;
font-size: 3rem;
margin-bottom: 8px;
}
h2 {
@@ -188,6 +202,7 @@ p code {
flex-direction: column;
gap: 10px;
padding: 14px 16px;
border-top: 3px solid var(--color-accent);
}
pre {
background: var(--color-paper-tint);
@@ -203,6 +218,9 @@ pre {
padding: 10px 16px;
border-bottom: 1px solid var(--color-line-soft);
}
.row:hover {
background: var(--color-accent-soft);
}
.row:last-child {
border-bottom: none;
}
+325
View File
@@ -0,0 +1,325 @@
<script setup>
/**
* The concept library: techniques Claude explained, each with a C++ snippet
* to reuse. Anyone can browse it; the admin also gets the form that asks
* for a new one, by topic ("help explain fenwick trees") or by pasting code
* they could not follow.
*
* A new concept is a job keyed by an id, since Claude picks the slug. The id
* is kept in localStorage while it runs, so leaving the page and coming
* back picks the wait up again; the job opens the concept when it is done.
*/
import { computed, onMounted, onUnmounted, ref } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import { conceptJob, listConcepts, saveJobAgain, startConcept } from "@/api";
import { formatDate } from "@/format";
const route = useRoute();
const router = useRouter();
const concepts = ref([]);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
const search = computed({
get: () => route.query.q || "",
set: (v) => router.replace({ query: { ...route.query, q: v || undefined } }),
});
const shown = computed(() => {
const q = search.value.trim().toLowerCase();
if (!q) return concepts.value;
return concepts.value.filter(
(c) =>
c.title.toLowerCase().includes(q) ||
c.slug.includes(q.replace(/\s+/g, "-")) ||
(c.summary || "").toLowerCase().includes(q) ||
c.tags.some((t) => t.includes(q.replace(/\s+/g, "-"))),
);
});
// ---- asking for a new one ----
const PENDING = "usaco.pendingConcept";
const topic = ref("");
const code = ref("");
const showCode = ref(false);
const job = ref({ state: "idle" });
let poll = null;
function remember(id) {
try {
if (id) localStorage.setItem(PENDING, id);
else localStorage.removeItem(PENDING);
} catch {
// Storage blocked: the wait just does not survive leaving the page.
}
}
async function check(id) {
clearTimeout(poll);
try {
const s = await conceptJob(id);
job.value = s;
if (s.state === "running") {
poll = setTimeout(() => check(id), 3000);
return;
}
remember(null);
if (s.state === "done" && s.result?.slug) router.push({ name: "concept", params: { slug: s.result.slug } });
} catch (e) {
remember(null);
job.value = { state: "error", error: e.message };
}
}
async function ask() {
try {
const { id, status } = await startConcept({ topic: topic.value, code: showCode.value ? code.value : "" });
job.value = status;
remember(id);
poll = setTimeout(() => check(id), 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
// Written but not committed: commit the same answer again.
async function saveAgain() {
try {
job.value = await saveJobAgain(job.value);
remember(job.value.key);
poll = setTimeout(() => check(job.value.key), 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
const canAsk = computed(
() => job.value.state !== "running" && (topic.value.trim() || (showCode.value && code.value.trim())),
);
onMounted(async () => {
try {
const data = await listConcepts();
concepts.value = data.concepts;
admin.value = data.admin;
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
let pending = null;
try {
pending = localStorage.getItem(PENDING);
} catch {
// As above.
}
// A job the server no longer knows (it restarted) comes back idle.
if (pending && admin.value) check(pending);
});
onUnmounted(() => clearTimeout(poll));
</script>
<template>
<section class="page">
<header class="page-heading">
<div>
<p class="eyebrow">Reference library</p>
<h1>Concepts</h1>
</div>
<span v-if="!loading && !error" class="heading-count">{{ concepts.length }} guides</span>
</header>
<p class="intro muted">
Techniques and data structures, explained with diagrams, each with C++ ready to paste into a solution.
</p>
<form v-if="admin" class="ask card" @submit.prevent="ask">
<h2>Explain a concept</h2>
<input
v-model="topic"
type="text"
placeholder="e.g. help explain fenwick trees"
aria-label="What to explain"
:disabled="job.state === 'running'"
/>
<textarea
v-if="showCode"
v-model="code"
rows="10"
placeholder="Paste code you want explained"
aria-label="Code to explain"
:disabled="job.state === 'running'"
></textarea>
<div class="row">
<label class="check"><input v-model="showCode" type="checkbox" /> Explain some code</label>
<button class="btn primary" type="submit" :disabled="!canAsk">
{{ job.state === "running" ? "Claude is writing…" : "Explain" }}
</button>
<span v-if="job.state === 'running'" class="muted">This takes a minute or two; the concept opens when it is saved.</span>
</div>
<p v-if="job.state === 'error'" class="error">
{{ job.error }}
<button v-if="job.unsaved" class="btn" type="button" @click="saveAgain">Save again</button>
</p>
</form>
<div class="controls">
<input v-model="search" type="search" placeholder="Search concepts" aria-label="Search concepts" />
</div>
<p v-if="loading" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
<p v-else-if="!concepts.length" class="muted">No concepts yet.</p>
<p v-else-if="!shown.length" class="muted">Nothing matches.</p>
<ul v-else class="list card">
<li v-for="c in shown" :key="c.slug">
<RouterLink :to="{ name: 'concept', params: { slug: c.slug } }" class="item">
<span class="name">{{ c.title }}</span>
<time v-if="c.updated" class="muted" :datetime="c.updated">{{ formatDate(c.updated) }}</time>
<span v-if="c.summary" class="summary muted">{{ c.summary }}</span>
<span v-if="c.tags.length" class="tags">
<span v-for="t in c.tags" :key="t" class="badge">{{ t }}</span>
</span>
</RouterLink>
</li>
</ul>
</section>
</template>
<style scoped>
.page {
display: grid;
gap: 16px;
min-width: 0;
}
.intro {
max-width: 58ch;
margin: -8px 0 4px;
}
.page-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 16px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--color-accent);
font-size: 0.75rem;
font-weight: bold;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 3rem;
}
.heading-count {
padding-bottom: 5px;
color: var(--color-ink-faint);
font-size: 0.85rem;
}
.ask {
display: grid;
gap: 10px;
padding: 18px;
border-top: 3px solid var(--color-accent);
}
.ask h2 {
font-size: 1.6rem;
margin: 0;
}
input[type="text"],
input[type="search"],
textarea {
padding: 6px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper);
color: var(--color-ink);
min-width: 0;
}
textarea {
font-family: var(--font-mono);
font-size: 0.85rem;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
}
.row .muted {
font-size: 0.85rem;
}
.check {
display: flex;
align-items: center;
gap: 6px;
margin-right: auto;
}
.controls input {
width: 100%;
max-width: 320px;
}
.controls {
padding: 8px;
border: 1px solid var(--color-line-soft);
border-radius: 8px;
background: rgb(255 255 255 / 0.42);
}
.list > li + li {
border-top: 1px solid var(--color-line-soft);
}
.item {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 2px 16px;
padding: 10px 16px;
color: inherit;
text-decoration: none;
}
.item:hover {
background: var(--color-accent-soft);
}
li:first-child .item {
border-radius: 6px 6px 0 0;
}
li:last-child .item {
border-radius: 0 0 6px 6px;
}
.name {
font-size: 1.05rem;
overflow-wrap: anywhere;
}
time {
font-size: 0.85rem;
white-space: nowrap;
}
.summary,
.tags {
grid-column: 1 / -1;
}
.summary {
font-size: 0.875rem;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 4px;
}
@media (max-width: 639px) {
.page-heading {
align-items: flex-start;
}
h1 {
font-size: 2.5rem;
}
.heading-count {
padding-top: 12px;
}
}
</style>
+258
View File
@@ -0,0 +1,258 @@
<script setup>
/**
* One concept: the snippet to reuse first, since that is what a return
* visit is usually for, then the explanation folded into sections like a
* problem's. The admin can have it rewritten, with a note on what to
* change, or forget it.
*/
import { onUnmounted, ref, watch } from "vue";
import { RouterLink, useRouter } from "vue-router";
import { deleteConcept, getConcept, getMe, rewriteConcept, rewriteStatus, saveJobAgain } from "@/api";
import { formatDate } from "@/format";
import CodeBlock from "@/components/CodeBlock.vue";
import Explanation from "@/components/Explanation.vue";
const props = defineProps({ slug: { type: String, required: true } });
const router = useRouter();
const concept = ref(null);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
const panel = ref("");
const note = ref("");
const job = ref({ state: "idle" });
const actionError = ref("");
let poll = null;
function stopPolling() {
clearTimeout(poll);
poll = null;
}
onUnmounted(stopPolling);
async function load() {
stopPolling();
loading.value = true;
error.value = "";
panel.value = "";
job.value = { state: "idle" };
try {
const [c, me] = await Promise.all([getConcept(props.slug), getMe().catch(() => ({ admin: false }))]);
concept.value = c;
admin.value = me.admin;
// A rewrite started before a reload is still worth waiting for.
if (me.admin) checkRewrite();
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
}
watch(() => props.slug, load, { immediate: true });
async function checkRewrite() {
stopPolling();
const slug = props.slug;
try {
const s = await rewriteStatus(slug);
if (slug !== props.slug) return;
const finished = job.value.state === "running" && s.state === "done";
job.value = s;
if (s.state === "running") {
poll = setTimeout(checkRewrite, 3000);
} else if (finished) {
concept.value = await getConcept(slug);
}
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
async function rewrite() {
try {
job.value = await rewriteConcept(props.slug, { note: note.value });
panel.value = "";
note.value = "";
poll = setTimeout(checkRewrite, 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
async function saveAgain() {
try {
job.value = await saveJobAgain(job.value);
poll = setTimeout(checkRewrite, 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
async function forget() {
if (!confirm(`Delete “${concept.value.title}” and its snippet?`)) return;
actionError.value = "";
try {
await deleteConcept(props.slug);
router.push({ name: "concepts" });
} catch (e) {
actionError.value = e.message;
}
}
</script>
<template>
<div class="page">
<RouterLink to="/concepts" class="back">← All concepts</RouterLink>
<p v-if="loading && !concept" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
<template v-else-if="concept">
<header>
<p class="eyebrow">Reference guide</p>
<h1>{{ concept.title }}</h1>
<div class="facts">
<span v-for="t in concept.tags" :key="t" class="badge">{{ t }}</span>
<time v-if="concept.updated" class="muted" :datetime="concept.updated">
Updated {{ formatDate(concept.updated) }}
</time>
</div>
</header>
<section v-if="admin" class="admin">
<div class="admin-row">
<button class="btn" :disabled="job.state === 'running'" @click="panel = panel === 'rewrite' ? '' : 'rewrite'">
{{ job.state === "running" ? "Claude is rewriting…" : "Rewrite" }}
</button>
<button class="btn" :disabled="job.state === 'running'" @click="forget">Delete</button>
</div>
<div v-if="panel === 'rewrite'" class="panel">
<p class="muted">
Claude writes it again from the same question, starting from this version. Say what to change, or leave it
empty for a fresh take.
</p>
<textarea v-model="note" rows="3" placeholder="e.g. step 3's diagram is wrong; add range updates"></textarea>
<div class="admin-row">
<button class="btn primary" @click="rewrite">Rewrite</button>
<button class="btn" @click="panel = ''">Cancel</button>
</div>
</div>
<p v-if="job.state === 'error'" class="error">
Rewrite: {{ job.error }}
<button v-if="job.unsaved" class="btn" @click="saveAgain">Save again</button>
</p>
<p v-if="actionError" class="error">{{ actionError }}</p>
</section>
<section v-if="concept.snippet">
<h2>Code</h2>
<p class="filename muted">snippet.cpp</p>
<CodeBlock :content="concept.snippet.content" lang="cpp" :truncated="concept.snippet.truncated" />
<p class="cli muted">
From the CLI: <code>usaco snippet {{ concept.slug }} &lt;problem&gt;</code> pastes it above
<code>main</code>.
</p>
</section>
<section v-if="concept.content">
<h2>Explanation</h2>
<Explanation :source="concept.content" :open="['Intuition']" />
</section>
</template>
</div>
</template>
<style scoped>
.page {
display: grid;
gap: 24px;
min-width: 0;
}
.page > section {
min-width: 0;
}
.back {
font-size: 0.875rem;
color: var(--color-ink-muted);
text-decoration: none;
}
.back:hover {
color: var(--color-ink);
}
.eyebrow {
margin: 0 0 5px;
color: var(--color-accent);
font-size: 0.75rem;
font-weight: bold;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
font-size: 3rem;
margin: 0 0 12px;
overflow-wrap: anywhere;
}
h2 {
font-size: 1.6rem;
margin-bottom: 8px;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 10px;
font-size: 0.9rem;
}
.admin {
display: grid;
gap: 10px;
padding: 14px 16px;
border: 1px solid var(--color-line-soft);
border-top: 3px solid var(--color-accent);
border-radius: 8px;
background: var(--color-paper);
box-shadow: var(--shadow-paper);
}
.admin-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.panel {
display: grid;
gap: 10px;
}
.panel p {
margin: 0;
font-size: 0.9rem;
}
textarea {
padding: 8px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
font-family: var(--font-mono);
font-size: 0.85rem;
color: var(--color-ink);
background: var(--color-paper);
}
.filename {
margin: 0 0 4px;
font-family: var(--font-mono);
font-size: 0.8rem;
}
.cli {
margin: 8px 0 0;
font-size: 0.85rem;
}
.cli code {
font-family: var(--font-mono);
}
@media (max-width: 639px) {
h1 {
font-size: 2.5rem;
}
}
</style>
+78 -19
View File
@@ -7,7 +7,7 @@
*/
import { computed, onMounted, ref } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import { listProblems, startDaily } from "@/api";
import { importLeetCode, listProblems, startDaily } from "@/api";
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
const route = useRoute();
@@ -18,21 +18,26 @@ const admin = ref(false);
const loading = ref(true);
const error = ref("");
// "Today's LeetCode" imports the daily question as `usaco daily` would and
// opens it on the solve page; one already in the repo is just opened.
const starting = ref(false);
const dailyError = ref("");
async function openDaily() {
starting.value = true;
dailyError.value = "";
// "Today's LeetCode" imports the daily question as `usaco daily` would, and
// a pasted link the problem it names as `usaco new <link>` would; either
// opens on the solve page, and one already in the repo is just opened. One
// import at a time: they share the busy flag and the error line.
const importing = ref("");
const importError = ref("");
const link = ref("");
async function startImport(kind, start) {
importing.value = kind;
importError.value = "";
try {
const { name } = await startDaily();
const { name } = await start();
router.push({ name: "solve", params: { name } });
} catch (e) {
dailyError.value = e.message;
starting.value = false;
importError.value = e.message;
importing.value = "";
}
}
const openDaily = () => startImport("daily", startDaily);
const openLink = () => link.value.trim() && startImport("link", () => importLeetCode(link.value.trim()));
const status = computed({
get: () => route.query.status || "all",
@@ -104,6 +109,13 @@ const groups = computed(() => {
<template>
<section>
<header class="page-heading">
<div>
<p class="eyebrow">Practice archive</p>
<h1>Problems</h1>
</div>
<span v-if="!loading && !error" class="heading-count">{{ counts.all }} total</span>
</header>
<p v-if="!loading && !error" class="intro muted">
{{ counts.solved }} solved problems from USACO and other judges, each with its solution and test cases.
</p>
@@ -126,11 +138,17 @@ const groups = computed(() => {
<option value="recent">Most recent</option>
<option value="name">Name</option>
</select>
<button v-if="admin" class="btn primary" :disabled="starting" @click="openDaily">
{{ starting ? "Fetching today's problem…" : "Today's LeetCode" }}
</button>
</div>
<p v-if="dailyError" class="error daily-error">{{ dailyError }}</p>
<form v-if="admin" class="controls" @submit.prevent="openLink">
<input v-model="link" type="url" placeholder="Paste a LeetCode link" aria-label="LeetCode problem link" />
<button class="btn" type="submit" :disabled="!!importing || !link.trim()">
{{ importing === "link" ? "Importing…" : "Import" }}
</button>
<button class="btn primary" type="button" :disabled="!!importing" @click="openDaily">
{{ importing === "daily" ? "Fetching today's problem…" : "Today's LeetCode" }}
</button>
</form>
<p v-if="importError" class="error import-error">{{ importError }}</p>
<p v-if="loading" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
@@ -169,9 +187,34 @@ const groups = computed(() => {
<style scoped>
.intro {
margin-bottom: 16px;
max-width: 58ch;
margin: -8px 0 22px;
}
.daily-error {
.page-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 16px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--color-accent);
font-size: 0.75rem;
font-weight: bold;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 3rem;
}
.heading-count {
padding-bottom: 5px;
color: var(--color-ink-faint);
font-size: 0.85rem;
font-variant-numeric: tabular-nums;
}
.import-error {
margin: -8px 0 16px;
}
.controls {
@@ -179,7 +222,11 @@ const groups = computed(() => {
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
margin-bottom: 16px;
margin-bottom: 12px;
padding: 8px;
border: 1px solid var(--color-line-soft);
border-radius: 8px;
background: rgb(255 255 255 / 0.42);
}
.tabs {
display: flex;
@@ -198,6 +245,7 @@ const groups = computed(() => {
border-color: var(--color-ink);
color: var(--color-ink);
background: var(--color-paper);
box-shadow: 0 1px 3px rgb(46 39 28 / 0.08);
}
.tabs .n {
color: var(--color-ink-faint);
@@ -249,7 +297,7 @@ input {
text-decoration: none;
}
.row:hover {
background: var(--color-paper-tint);
background: var(--color-accent-soft);
}
li:first-child .row {
border-radius: 6px 6px 0 0;
@@ -307,4 +355,15 @@ time {
display: contents;
}
}
@media (max-width: 639px) {
.page-heading {
align-items: flex-start;
}
h1 {
font-size: 2.5rem;
}
.heading-count {
padding-top: 12px;
}
}
</style>
+54 -8
View File
@@ -21,6 +21,7 @@ import {
getMe,
getProblem,
reviewStatus,
saveJobAgain,
setStatus,
startExplain,
startReview,
@@ -186,6 +187,16 @@ async function explain() {
}
}
// The explanation was written but not committed: commit it again.
async function saveExplainAgain() {
try {
job.value = await saveJobAgain(job.value);
poll = setTimeout(checkExplain, 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
const canExplain = computed(() => !!(problem.value?.statement || problem.value?.url));
// ---- recording reviews ----
@@ -258,6 +269,15 @@ async function checkReview() {
}
}
async function saveReviewAgain() {
try {
reviewJob.value = await saveJobAgain(reviewJob.value);
reviewPoll = setTimeout(checkReview, 3000);
} catch (e) {
reviewJob.value = { state: "error", error: e.message };
}
}
async function submitReview() {
const form = new FormData();
form.append("audio", recording.value);
@@ -302,6 +322,7 @@ const moves = computed(() => {
<article v-else-if="problem" class="page">
<header class="head">
<RouterLink to="/" class="back">← All problems</RouterLink>
<p class="eyebrow">Problem archive</p>
<h1>{{ title(problem.name) }}</h1>
<div class="facts">
<span class="badge" :class="problem.status">{{ STATUS_LABELS[problem.status] }}</span>
@@ -408,8 +429,14 @@ const moves = computed(() => {
<!-- Outside the panels, so a job that fails after its panel was
closed still says so. -->
<p v-if="editError" class="error">{{ editError }}</p>
<p v-if="job.state === 'error'" class="error">Explain: {{ job.error }}</p>
<p v-if="reviewJob.state === 'error'" class="error">Review: {{ reviewJob.error }}</p>
<p v-if="job.state === 'error'" class="error">
Explain: {{ job.error }}
<button v-if="job.unsaved" class="btn" @click="saveExplainAgain">Save again</button>
</p>
<p v-if="reviewJob.state === 'error'" class="error">
Review: {{ reviewJob.error }}
<button v-if="reviewJob.unsaved" class="btn" @click="saveReviewAgain">Save again</button>
</p>
</section>
<section v-if="notesHtml" class="notes card prose" v-html="notesHtml"></section>
@@ -490,7 +517,7 @@ const moves = computed(() => {
<style scoped>
.page {
display: grid;
gap: 28px;
gap: 32px;
min-width: 0;
}
.page > section {
@@ -504,9 +531,17 @@ const moves = computed(() => {
.back:hover {
color: var(--color-ink);
}
.eyebrow {
margin: 18px 0 0;
color: var(--color-accent);
font-size: 0.75rem;
font-weight: bold;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
font-size: 2.75rem;
margin: 6px 0 10px;
font-size: 3.25rem;
margin: 3px 0 12px;
overflow-wrap: anywhere;
}
h2 {
@@ -526,9 +561,10 @@ h2 {
font-size: 0.85em;
}
.admin {
padding: 12px 16px;
padding: 14px 16px;
display: grid;
gap: 12px;
border-top: 3px solid var(--color-accent);
}
.admin-row {
display: flex;
@@ -557,7 +593,8 @@ h2 {
background: var(--color-paper);
}
.notes {
padding: 16px 20px;
padding: 18px 22px;
border-left: 3px solid var(--color-accent);
}
.label-row {
display: flex;
@@ -694,7 +731,8 @@ h2 {
}
.file-tabs button.on {
border-color: var(--color-ink);
background: var(--color-paper);
background: var(--color-accent-soft);
color: var(--color-accent);
}
.filename {
font-family: var(--font-mono);
@@ -731,4 +769,12 @@ h2 {
.history time {
min-width: 7.5em;
}
@media (max-width: 639px) {
h1 {
font-size: 2.6rem;
}
.facts {
gap: 6px 10px;
}
}
</style>
+211 -7
View File
@@ -2,22 +2,25 @@
/**
* Solve a problem in the browser (admin only): the statement and saved
* tests on the left, an editor on the right with Run (the custom input),
* Submit (the saved tests) and Save (a commit, like the CLI's).
* Submit (the saved tests), Evaluate (Claude's judgement of the code, after
* a run of the tests) and Save (a commit, like the CLI's).
*
* What is typed is kept as a draft in this browser per problem and language
* until it is saved or reset, so leaving the page loses nothing and there
* is no "unsaved changes" prompt. Runs and lints are plain requests to the
* server, which passes them to the code runner: a run answers when it has
* finished, which can take up to a minute.
* finished, which can take up to a minute. An evaluation takes longer
* than nginx waits, so it is a job the page polls, as on the problem page.
*/
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { RouterLink } from "vue-router";
import CodeBlock from "@/components/CodeBlock.vue";
import CodeEditor from "@/components/CodeEditor.vue";
import EvaluationReport from "@/components/EvaluationReport.vue";
import RunResults from "@/components/RunResults.vue";
import { markdown } from "@/markdown";
import { getCode, getMe, getProblem, lintCode, runCode, saveCode } from "@/api";
import { LANG_LABELS, MOD_KEY, STATUS_LABELS, title } from "@/format";
import { evaluateStatus, getCode, getMe, getProblem, lintCode, runCode, saveCode, startEvaluate } from "@/api";
import { EVAL_VERDICTS, LANG_LABELS, MOD_KEY, STATUS_LABELS, title } from "@/format";
const props = defineProps({ name: { type: String, required: true } });
@@ -44,6 +47,15 @@ const diagnostics = ref([]);
const linted = ref(false);
const lintError = ref("");
const editor = ref(null);
const results = ref(null);
const evalJob = ref({ state: "idle" });
const evaluation = ref(null);
const evalNote = ref("");
const evalDiagnostics = ref([]);
// The lint's marks and Claude's together; lintSummary counts the lint's.
const editorDiagnostics = computed(() => [...diagnostics.value, ...evalDiagnostics.value]);
const statementHtml = computed(() => (problem.value?.statement ? md.render(problem.value.statement) : ""));
const current = computed(() => info.value?.code[lang.value]);
const dirty = computed(() => !!current.value && source.value !== current.value.source);
@@ -62,6 +74,7 @@ const codeStatus = computed(() => {
async function load() {
flushDraft();
clearTimeout(lintTimer);
stopEvalPolling();
const name = props.name;
loading.value = true;
error.value = "";
@@ -73,6 +86,10 @@ async function load() {
notice.value = "";
diagnostics.value = [];
linted.value = false;
evalJob.value = { state: "idle" };
evaluation.value = null;
evalNote.value = "";
evalDiagnostics.value = [];
try {
const [p, me] = await Promise.all([getProblem(name), getMe().catch(() => ({ admin: false }))]);
if (name !== props.name) return;
@@ -86,6 +103,8 @@ async function load() {
if (name !== props.name) return;
info.value = c;
open(c.code[c.default] ? c.default : c.languages[0]);
// The server keeps the last evaluation until it restarts.
if (c.claude) checkEvaluate();
} catch (e) {
if (name !== props.name) return;
problem.value = null;
@@ -105,6 +124,7 @@ function open(l) {
lintError.value = "";
notice.value = "";
saveError.value = "";
anchorIssues();
lintSoon();
}
@@ -194,6 +214,8 @@ async function lintNow() {
const r = await lintCode(name, { lang: l, source: src });
if (seq !== lintSeq || name !== props.name || l !== lang.value || src !== source.value) return;
diagnostics.value = r.diagnostics || [];
// Re-placed against the same text, so the two sets agree.
anchorIssues();
linted.value = true;
lintError.value = "";
} catch (e) {
@@ -258,6 +280,114 @@ async function save() {
}
}
// ---- evaluate ----
// Polled every 3 s while it runs, as the problem page's jobs are. A job
// that fails leaves the last evaluation on show under its error.
let evalPoll = null;
function stopEvalPolling() {
clearTimeout(evalPoll);
evalPoll = null;
}
async function checkEvaluate() {
stopEvalPolling();
const name = props.name;
try {
const s = await evaluateStatus(name);
if (name !== props.name) return;
const finished = evalJob.value.state === "running" && s.state !== "running";
evalJob.value = s;
if (s.result) evaluation.value = s.result;
if (s.state === "running") evalPoll = setTimeout(checkEvaluate, 3000);
else if (finished) results.value?.show("evaluation");
} catch (e) {
if (name === props.name) evalJob.value = { state: "error", error: e.message };
}
}
const evalDisabled = computed(() => {
if (!info.value?.claude) return "Claude isn't configured on this server (CLAUDE_API_KEY)";
if (!problem.value?.statement && !problem.value?.url) return "Add the statement or a link on the problem page first";
if (!source.value.trim()) return "The editor is empty";
return "";
});
const evaluating = computed(() => evalJob.value.state === "running");
const canEvaluate = computed(() => !evalDisabled.value && !evaluating.value);
async function evaluate() {
if (!canEvaluate.value) return;
const name = props.name;
results.value?.show("evaluation");
try {
const s = await startEvaluate(name, { lang: lang.value, source: source.value, note: evalNote.value });
if (name !== props.name) return;
evalJob.value = s;
evalPoll = setTimeout(checkEvaluate, 3000);
} catch (e) {
if (name !== props.name) return;
// Started from another tab: follow that one.
if (e.status === 409) checkEvaluate();
else evalJob.value = { state: "error", error: e.message };
}
}
// Whether the editor still holds what was judged. In another language it
// is a different file, which the report says instead.
const evalStale = computed(() => {
const ev = evaluation.value;
return !!ev && ev.lang === lang.value && ev.source !== source.value;
});
const evaluationTab = computed(() => {
if (!info.value?.claude) return null;
if (evaluating.value) return { label: "Evaluation", tone: "plain" };
return { label: "Evaluation", tone: EVAL_VERDICTS[evaluation.value?.verdict]?.tone || "" };
});
// Claude's issues as editor marks, on the lines they were about. Once the
// code has changed, a line is found again by its text, at the copy nearest
// to where it was; a line edited since loses its mark, which is usually
// the fix. Called when the evaluation, the language or the lint changes,
// and CodeMirror moves the marks through edits in between.
function anchorIssues() {
const ev = evaluation.value;
if (!ev || ev.lang !== lang.value) {
evalDiagnostics.value = [];
return;
}
const same = ev.source === source.value;
const was = ev.source.split("\n");
const now = source.value.split("\n");
const out = [];
for (const is of ev.issues || []) {
const text = was[is.line - 1];
if (!is.line || text === undefined) continue;
let line = same ? is.line : 0;
for (let d = 0; !line && text.trim() && d < now.length; d++) {
if (now[is.line - 1 - d] === text) line = is.line - d;
else if (now[is.line - 1 + d] === text) line = is.line + d;
}
if (!line) continue;
out.push({
line,
col: /^\s*/.exec(text)[0].length + 1,
endLine: line,
endCol: text.length + 1,
severity: is.severity,
message: is.detail ? `${is.title}\n\n${is.detail}` : is.title,
source: "Claude",
});
}
evalDiagnostics.value = out;
}
watch(evaluation, anchorIssues);
function useInput(input) {
customInput.value = input;
results.value?.show("custom");
}
// The editor handles these itself while it has focus (and stops them);
// this is for everywhere else on the page, the custom input included.
function onKey(e) {
@@ -280,9 +410,33 @@ onUnmounted(() => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pagehide", flushDraft);
clearTimeout(lintTimer);
stopEvalPolling();
flushDraft();
});
// ---- vim keys ----
// Off by default, and remembered in this browser like the split.
const VIM_KEY = "usaco:solve:vim";
const vimMode = ref(readVim());
function readVim() {
try {
return localStorage.getItem(VIM_KEY) === "1";
} catch {
return false;
}
}
watch(vimMode, (on) => {
try {
if (on) localStorage.setItem(VIM_KEY, "1");
else localStorage.removeItem(VIM_KEY);
} catch {
// As in readDraft.
}
editor.value?.focus();
});
// ---- the divider between the panes ----
// A share of the width, remembered in this browser.
const SPLIT_KEY = "usaco:solve:split";
@@ -412,6 +566,9 @@ watch(() => props.name, load, { immediate: true });
<button class="btn" type="button" :disabled="busy || !dirty" @click="reset">
Reset to {{ current.saved ? "saved" : "starter" }}
</button>
<label class="check" title="Vim keys in the editor (:w saves)">
<input v-model="vimMode" type="checkbox" /> Vim
</label>
<span class="grow"></span>
<button
class="btn"
@@ -431,6 +588,15 @@ watch(() => props.name, load, { immediate: true });
>
{{ running === "tests" ? "Submitting…" : "Submit" }}
</button>
<button
class="btn"
type="button"
:disabled="!canEvaluate"
:title="evalDisabled || 'Run the saved tests and have Claude judge this code'"
@click="evaluate"
>
{{ evaluating ? "Evaluating…" : "Evaluate" }}
</button>
<button class="btn" type="button" :disabled="!canSave" :title="`Commit to the repo (${MOD_KEY}+S)`" @click="save">
{{ saving ? "Saving…" : "Save" }}
</button>
@@ -455,17 +621,41 @@ watch(() => props.name, load, { immediate: true });
</p>
<CodeEditor
ref="editor"
v-model="source"
class="code"
:lang="lang"
:diagnostics="diagnostics"
:diagnostics="editorDiagnostics"
:label="`${LANG_LABELS[lang] || lang} solution`"
:vim="vimMode"
@run="run('custom')"
@submit="run('tests')"
@save="save"
/>
<RunResults v-model="customInput" class="out" :result="result" :running="running" :error="runError" />
<RunResults
ref="results"
v-model="customInput"
class="out"
:result="result"
:running="running"
:error="runError"
:evaluation-tab="evaluationTab"
>
<template #evaluation>
<EvaluationReport
v-model:note="evalNote"
:job="evalJob"
:evaluation="evaluation"
:lang="lang"
:stale="evalStale"
:disabled="evalDisabled"
@evaluate="evaluate"
@goto="(line) => editor?.goto(line)"
@use-input="useInput"
/>
</template>
</RunResults>
</div>
</div>
</template>
@@ -481,6 +671,7 @@ watch(() => props.name, load, { immediate: true });
min-height: 0;
overflow: auto;
padding: 14px 18px 20px;
border-top: 3px solid var(--color-accent);
display: grid;
align-content: start;
gap: 16px;
@@ -563,7 +754,7 @@ h2 {
}
.split:hover::after,
.split:focus-visible::after {
background: var(--color-line);
background: var(--color-accent);
}
.right {
min-width: 0;
@@ -577,6 +768,11 @@ h2 {
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 8px;
border: 1px solid var(--color-line-soft);
border-radius: 8px;
background: var(--color-paper);
box-shadow: var(--shadow-paper);
}
.toolbar select {
padding: 6px 10px;
@@ -590,6 +786,13 @@ h2 {
opacity: 0.5;
cursor: default;
}
.check {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.9rem;
cursor: pointer;
}
.grow {
flex: 1;
}
@@ -600,6 +803,7 @@ h2 {
gap: 4px 14px;
font-size: 0.85rem;
color: var(--color-ink-muted);
padding: 0 4px;
}
.status .draft {
color: var(--color-solving);
+90 -2
View File
@@ -4,13 +4,15 @@
* headline counts, a year of solves as a calendar heatmap, and the same data
* by month as a table (the heatmap's accessible equivalent).
*
* The admin also sees what Claude has cost (GET /usage, the server's ledger).
*
* Days are the viewer's local days (format.dayKey). The solve date is the
* commit that moved a problem into solved/, so a batch of problems committed
* together lands on one day.
*/
import { computed, nextTick, onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { listProblems } from "@/api";
import { getMe, getUsage, listProblems } from "@/api";
import { dayKey, formatDate, title } from "@/format";
const problems = ref([]);
@@ -18,7 +20,16 @@ const loading = ref(true);
const error = ref("");
const scroller = ref(null);
// The Claude spend; null for anyone but the admin.
const spend = ref(null);
const money = (n) => `$${n.toFixed(2)}`;
const KIND_LABELS = { explain: "Explanations", concept: "Concepts", review: "Reviews", evaluate: "Evaluations" };
onMounted(async () => {
getMe()
.then((me) => (me.admin ? getUsage() : null))
.then((u) => (spend.value = u?.tracked ? u : null))
.catch(() => {});
try {
problems.value = (await listProblems()).problems;
} catch (e) {
@@ -156,6 +167,13 @@ const monthly = computed(() => {
<p v-else-if="error" class="error">{{ error }}</p>
<div v-else class="stats">
<header class="page-heading">
<div>
<p class="eyebrow">Progress journal</p>
<h1>Stats</h1>
</div>
<span class="heading-count">A year in review</span>
</header>
<div class="tiles">
<div v-for="t in tiles" :key="t.label" class="tile card">
<span class="label muted">{{ t.label }}</span>
@@ -217,6 +235,38 @@ const monthly = computed(() => {
</table>
<p v-else class="muted">Nothing solved yet.</p>
</section>
<section v-if="spend">
<h2>Claude spend</h2>
<p class="muted">
{{ money(spend.month) }} this month<template v-if="spend.budget"> of a {{ money(spend.budget) }} budget</template>.
Estimated from token counts at list prices; transcription is not included.
</p>
<table v-if="spend.months.length" class="card">
<thead>
<tr><th scope="col">Month</th><th scope="col" class="num">Calls</th><th scope="col" class="num">Cost</th></tr>
</thead>
<tbody>
<tr v-for="m in spend.months" :key="m.name">
<td>{{ formatDate(m.name + "-01T00:00:00", { month: "long", year: "numeric" }) }}</td>
<td class="num">{{ m.calls }}</td>
<td class="num">{{ money(m.cost) }}</td>
</tr>
</tbody>
</table>
<table v-if="spend.kinds.length" class="card">
<thead>
<tr><th scope="col">This month, by feature</th><th scope="col" class="num">Calls</th><th scope="col" class="num">Cost</th></tr>
</thead>
<tbody>
<tr v-for="k in spend.kinds" :key="k.name">
<td>{{ KIND_LABELS[k.name] || k.name }}</td>
<td class="num">{{ k.calls }}</td>
<td class="num">{{ money(k.cost) }}</td>
</tr>
</tbody>
</table>
</section>
</div>
</template>
@@ -226,9 +276,35 @@ const monthly = computed(() => {
gap: 28px;
min-width: 0;
}
.page-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 16px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--color-accent);
font-size: 0.75rem;
font-weight: bold;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.page-heading h1 {
margin: 0;
font-size: 3rem;
}
.heading-count {
padding-bottom: 5px;
color: var(--color-ink-faint);
font-size: 0.85rem;
}
.stats > section {
min-width: 0;
}
table + table {
margin-top: 12px;
}
h2 {
font-size: 1.6rem;
margin-bottom: 8px;
@@ -242,6 +318,7 @@ h2 {
display: flex;
flex-direction: column;
padding: 14px 16px;
border-top: 3px solid var(--color-accent);
}
.label {
font-size: 0.8rem;
@@ -286,7 +363,7 @@ svg {
fill: var(--color-seq-4);
}
.cell.hot {
stroke: var(--color-ink);
stroke: var(--color-accent);
stroke-width: 1.5;
}
.legend {
@@ -342,4 +419,15 @@ tr:last-child td {
td:first-child {
white-space: nowrap;
}
@media (max-width: 640px) {
.page-heading {
align-items: flex-start;
}
.page-heading h1 {
font-size: 2.5rem;
}
.heading-count {
padding-top: 12px;
}
}
</style>
@@ -0,0 +1 @@
https://leetcode.com/problems/count-vowel-substrings-of-a-string/
@@ -0,0 +1,3 @@
"aeiouu"
"unicornarihan"
"cuaieuouac"
@@ -0,0 +1,13 @@
// driver.h - generated by 'usaco new' from LeetCode's metadata (edit freely).
// Reads count-vowel-substrings-of-a-string.in in LeetCode's testcase format, cases back to back:
// one argument per line
// and writes one answer per case to count-vowel-substrings-of-a-string.out, formatted the way LeetCode
// shows its output. Parsing/printing helpers: leetcode.h.
int main() {
freopen("count-vowel-substrings-of-a-string.in", "r", stdin);
freopen("count-vowel-substrings-of-a-string.out", "w", stdout);
for (vector<string> in; lc::read_case(in, 1);) {
auto word = lc::parse<string>(in[0]);
cout << lc::show(Solution().countVowelSubstrings(word)) << '\n';
}
}
@@ -0,0 +1,117 @@
_Explained by claude-opus-5-5 on 20 October 2026._
## Key observation
Fix the right end `j`. A left end `l` works iff `l` is past the last consonant and every vowel's most recent occurrence is $\ge l$. So the valid left ends form one contiguous range whose length you can read off directly.
## Hint 1
A valid substring can never contain a consonant. What does that tell you about how the string splits into independent pieces?
## Hint 2
Instead of fixing where a substring *starts*, try fixing where it *ends*. For a fixed right end `j`, which left ends work?
## Hint 3
For a left end `l` and right end `j` inside one vowel block, `[l, j]` contains vowel `v` iff the most recent occurrence of `v` at or before `j` is at index $\ge l$.
## Hint 4
So the valid left ends form one contiguous range: from the start of the current vowel block up to $\min_v last[v]$. Add the length of that range for every `j`.
## Approach
## Why your two-pointer idea is close but slippery
Your plan fixes the **left** end `i`. As soon as `[i, j]` contains all five vowels, you add every extension `[i, j'] ` with $j' \ge j$. Then you drop `word[i]` and advance. The idea is sound, but three details usually break it:
1. **The extensions stop at the next consonant, not at the end of the string.** `[i, j']` is only valid while `word[j']` is still a vowel. So you add `(end of vowel block) - j`, not `n - j`.
2. **After dropping `word[i]`, the window may *still* contain all five vowels.** For example, in `"aaeiou"`, dropping the first `a` leaves `"aeiou"`. You must keep shrinking and adding in a **loop** while the window stays complete, before you move `j` again. Doing it only once undercounts.
3. **A consonant resets everything.** No valid substring can cross a consonant, so `i` jumps past it and all counts clear.
With those fixes your version works. The bookkeeping gets much easier if you flip the viewpoint and fix the **right** end instead.
## Fix the right end, count the left ends
For each index `j`, ask: *how many valid substrings end exactly at `j`?* Summing that over all `j` counts every substring once, with no double counting.
Track two things while scanning:
- `start` is the first index after the most recent consonant. Every left end must be $\ge$ `start`.
- `last[v]` is the most recent index (in the current vowel block) where vowel `v` appeared, or $-1$ if `v` hasn't appeared since `start`.
A substring `[l, j]` contains vowel `v` exactly when `last[v] >= l`. It contains all five exactly when
$$l \le m = \min_{v \in \{a,e,i,o,u\}} last[v].$$
Combined with $l \ge start$, the valid left ends are exactly $start, start+1, \dots, m$. That gives
$$\text{contribution of } j = \max(0,\; m - start + 1).$$
When `word[j]` is a consonant, set `start = j + 1` and reset every `last[v]` to $-1$. Any missing vowel then makes $m = -1 < start$, so the contribution is automatically 0.
This is a sliding window in disguise. `start` is the hard left wall, and $m$ is the furthest the left pointer could move while keeping all five vowels. You never move a pointer back and forth, you just read off the count.
*(With $n \le 100$, a plain double loop also passes. For each `i`, extend `j` until a consonant, keeping a set of seen vowels and adding 1 whenever the set has size 5. But the idea above is the clean $O(n)$ version.)*
## Walkthrough
**Step 1.** `word = "cuaieuouac"`. The `c` at index 0 forces `start = 1`. Scanning up to `j = 5` records `last`: a=2, e=4, i=3, u=5, but `o` hasn't appeared yet ($-1$). So $m = -1 < start$ and nothing is added.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 250"><g stroke="currentColor"><rect x="40" y="60" width="56" height="44" fill="#ef4444" fill-opacity="0.35"/><rect x="96" y="60" width="56" height="44" fill="none"/><rect x="152" y="60" width="56" height="44" fill="none"/><rect x="208" y="60" width="56" height="44" fill="none"/><rect x="264" y="60" width="56" height="44" fill="none"/><rect x="320" y="60" width="56" height="44" fill="#3b82f6" fill-opacity="0.35"/><rect x="376" y="60" width="56" height="44" fill="none"/><rect x="432" y="60" width="56" height="44" fill="none"/><rect x="488" y="60" width="56" height="44" fill="none"/><rect x="544" y="60" width="56" height="44" fill="none"/></g><g font-family="ui-monospace, monospace" font-size="18" fill="currentColor" text-anchor="middle"><text x="68" y="88">c</text><text x="124" y="88">u</text><text x="180" y="88">a</text><text x="236" y="88">i</text><text x="292" y="88">e</text><text x="348" y="88">u</text><text x="404" y="88">o</text><text x="460" y="88">u</text><text x="516" y="88">a</text><text x="572" y="88">c</text></g><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="68" y="124">0</text><text x="124" y="124">1</text><text x="180" y="124">2</text><text x="236" y="124">3</text><text x="292" y="124">4</text><text x="348" y="124">5</text><text x="404" y="124">6</text><text x="460" y="124">7</text><text x="516" y="124">8</text><text x="572" y="124">9</text></g><g font-family="sans-serif" font-size="14" fill="currentColor" text-anchor="middle"><text x="124" y="45">start</text><text x="348" y="45">j</text></g><text x="40" y="180" font-family="ui-monospace, monospace" font-size="15" fill="currentColor">last: a=2 e=4 i=3 o=-1 u=5</text><text x="40" y="215" font-family="sans-serif" font-size="15" fill="currentColor">o missing: +0, total = 0</text></svg>
```
**Step 2.** `j = 6` (`o`). Now all five vowels are present. `last`: a=2, e=4, i=3, o=6, u=5, so $m = 2$. Valid left ends are 1..2 (green), giving `"uaieuo"` and `"aieuo"`. Add $2 - 1 + 1 = 2$.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 250"><g stroke="currentColor"><rect x="40" y="60" width="56" height="44" fill="#ef4444" fill-opacity="0.35"/><rect x="96" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="152" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="208" y="60" width="56" height="44" fill="none"/><rect x="264" y="60" width="56" height="44" fill="none"/><rect x="320" y="60" width="56" height="44" fill="none"/><rect x="376" y="60" width="56" height="44" fill="#3b82f6" fill-opacity="0.35"/><rect x="432" y="60" width="56" height="44" fill="none"/><rect x="488" y="60" width="56" height="44" fill="none"/><rect x="544" y="60" width="56" height="44" fill="none"/></g><g font-family="ui-monospace, monospace" font-size="18" fill="currentColor" text-anchor="middle"><text x="68" y="88">c</text><text x="124" y="88">u</text><text x="180" y="88">a</text><text x="236" y="88">i</text><text x="292" y="88">e</text><text x="348" y="88">u</text><text x="404" y="88">o</text><text x="460" y="88">u</text><text x="516" y="88">a</text><text x="572" y="88">c</text></g><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="68" y="124">0</text><text x="124" y="124">1</text><text x="180" y="124">2</text><text x="236" y="124">3</text><text x="292" y="124">4</text><text x="348" y="124">5</text><text x="404" y="124">6</text><text x="460" y="124">7</text><text x="516" y="124">8</text><text x="572" y="124">9</text></g><g font-family="sans-serif" font-size="14" fill="currentColor" text-anchor="middle"><text x="124" y="45">start</text><text x="404" y="45">j</text><text x="180" y="146">min</text></g><text x="40" y="180" font-family="ui-monospace, monospace" font-size="15" fill="currentColor">last: a=2 e=4 i=3 o=6 u=5</text><text x="40" y="215" font-family="sans-serif" font-size="15" fill="currentColor">m=2: +2, total = 2</text></svg>
```
**Step 3.** `j = 7` (`u`). `last[u]` becomes 7, but the minimum is still `a` at index 2, so $m = 2$. Left ends 1..2 still work: +2, total 4.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 250"><g stroke="currentColor"><rect x="40" y="60" width="56" height="44" fill="#ef4444" fill-opacity="0.35"/><rect x="96" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="152" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="208" y="60" width="56" height="44" fill="none"/><rect x="264" y="60" width="56" height="44" fill="none"/><rect x="320" y="60" width="56" height="44" fill="none"/><rect x="376" y="60" width="56" height="44" fill="none"/><rect x="432" y="60" width="56" height="44" fill="#3b82f6" fill-opacity="0.35"/><rect x="488" y="60" width="56" height="44" fill="none"/><rect x="544" y="60" width="56" height="44" fill="none"/></g><g font-family="ui-monospace, monospace" font-size="18" fill="currentColor" text-anchor="middle"><text x="68" y="88">c</text><text x="124" y="88">u</text><text x="180" y="88">a</text><text x="236" y="88">i</text><text x="292" y="88">e</text><text x="348" y="88">u</text><text x="404" y="88">o</text><text x="460" y="88">u</text><text x="516" y="88">a</text><text x="572" y="88">c</text></g><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="68" y="124">0</text><text x="124" y="124">1</text><text x="180" y="124">2</text><text x="236" y="124">3</text><text x="292" y="124">4</text><text x="348" y="124">5</text><text x="404" y="124">6</text><text x="460" y="124">7</text><text x="516" y="124">8</text><text x="572" y="124">9</text></g><g font-family="sans-serif" font-size="14" fill="currentColor" text-anchor="middle"><text x="124" y="45">start</text><text x="460" y="45">j</text><text x="180" y="146">min</text></g><text x="40" y="180" font-family="ui-monospace, monospace" font-size="15" fill="currentColor">last: a=2 e=4 i=3 o=6 u=7</text><text x="40" y="215" font-family="sans-serif" font-size="15" fill="currentColor">m=2: +2, total = 4</text></svg>
```
**Step 4.** `j = 8` (`a`). `last[a]` jumps to 8, so the bottleneck becomes `i` at index 3 and $m = 3$. Left ends 1..3 are valid: +3, total 7.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 250"><g stroke="currentColor"><rect x="40" y="60" width="56" height="44" fill="#ef4444" fill-opacity="0.35"/><rect x="96" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="152" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="208" y="60" width="56" height="44" fill="#22c55e" fill-opacity="0.35"/><rect x="264" y="60" width="56" height="44" fill="none"/><rect x="320" y="60" width="56" height="44" fill="none"/><rect x="376" y="60" width="56" height="44" fill="none"/><rect x="432" y="60" width="56" height="44" fill="none"/><rect x="488" y="60" width="56" height="44" fill="#3b82f6" fill-opacity="0.35"/><rect x="544" y="60" width="56" height="44" fill="none"/></g><g font-family="ui-monospace, monospace" font-size="18" fill="currentColor" text-anchor="middle"><text x="68" y="88">c</text><text x="124" y="88">u</text><text x="180" y="88">a</text><text x="236" y="88">i</text><text x="292" y="88">e</text><text x="348" y="88">u</text><text x="404" y="88">o</text><text x="460" y="88">u</text><text x="516" y="88">a</text><text x="572" y="88">c</text></g><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="68" y="124">0</text><text x="124" y="124">1</text><text x="180" y="124">2</text><text x="236" y="124">3</text><text x="292" y="124">4</text><text x="348" y="124">5</text><text x="404" y="124">6</text><text x="460" y="124">7</text><text x="516" y="124">8</text><text x="572" y="124">9</text></g><g font-family="sans-serif" font-size="14" fill="currentColor" text-anchor="middle"><text x="124" y="45">start</text><text x="516" y="45">j</text><text x="236" y="146">min</text></g><text x="40" y="180" font-family="ui-monospace, monospace" font-size="15" fill="currentColor">last: a=8 e=4 i=3 o=6 u=7</text><text x="40" y="215" font-family="sans-serif" font-size="15" fill="currentColor">m=3: +3, total = 7</text></svg>
```
**Step 5.** `j = 9` (`c`). A consonant resets `start = 10` and clears `last`. Nothing more can be added, so the answer is **7**, matching the expected output.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 250"><g stroke="currentColor"><rect x="40" y="60" width="56" height="44" fill="#ef4444" fill-opacity="0.35"/><rect x="96" y="60" width="56" height="44" fill="none"/><rect x="152" y="60" width="56" height="44" fill="none"/><rect x="208" y="60" width="56" height="44" fill="none"/><rect x="264" y="60" width="56" height="44" fill="none"/><rect x="320" y="60" width="56" height="44" fill="none"/><rect x="376" y="60" width="56" height="44" fill="none"/><rect x="432" y="60" width="56" height="44" fill="none"/><rect x="488" y="60" width="56" height="44" fill="none"/><rect x="544" y="60" width="56" height="44" fill="#ef4444" fill-opacity="0.35"/></g><g font-family="ui-monospace, monospace" font-size="18" fill="currentColor" text-anchor="middle"><text x="68" y="88">c</text><text x="124" y="88">u</text><text x="180" y="88">a</text><text x="236" y="88">i</text><text x="292" y="88">e</text><text x="348" y="88">u</text><text x="404" y="88">o</text><text x="460" y="88">u</text><text x="516" y="88">a</text><text x="572" y="88">c</text></g><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="68" y="124">0</text><text x="124" y="124">1</text><text x="180" y="124">2</text><text x="236" y="124">3</text><text x="292" y="124">4</text><text x="348" y="124">5</text><text x="404" y="124">6</text><text x="460" y="124">7</text><text x="516" y="124">8</text><text x="572" y="124">9</text></g><g font-family="sans-serif" font-size="14" fill="currentColor" text-anchor="middle"><text x="572" y="45">j</text></g><text x="40" y="180" font-family="ui-monospace, monospace" font-size="15" fill="currentColor">last: all -1, start = 10</text><text x="40" y="215" font-family="sans-serif" font-size="15" fill="currentColor">consonant reset: answer = 7</text></svg>
```
## Complexity
- **Time:** $O(n)$. Each character is processed once, with a constant 5-way min.
- **Memory:** $O(1)$. Only five `last` slots plus `start` and the counter.
## Pitfalls
- Counting extensions up to the end of the string instead of up to the next consonant.
- Shrinking the left pointer only once after finding a complete window. It must loop while the window still has all five vowels (`"aaeiou"` exposes this).
- Forgetting to reset the vowel tracking when a consonant appears. Stale positions from an earlier block would produce substrings that cross the consonant.
- Tracking vowels in a window with a plain *set* and then removing a vowel when the left pointer passes it, even though another copy is still inside. Use counts, or last-seen indices.
- Not guarding against a missing vowel. With `last = -1` and the check `m >= start`, it naturally adds 0.
## Solution sketch
```text
count = 0
start = 0
last = {a:-1, e:-1, i:-1, o:-1, u:-1}
for j from 0 to n-1:
ch = word[j]
if ch is not a vowel:
start = j + 1
set every last[v] = -1
continue
last[ch] = j
m = min(last[a], last[e], last[i], last[o], last[u])
if m >= start:
count += m - start + 1
return count
```
@@ -0,0 +1,142 @@
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL // set by ./usaco builds only, so this is safe to submit as-is
#include "debugging.h"
#include "leetcode.h" // ListNode, TreeNode
#endif
// ----- TYPES -----
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
// ----- FILE IO -----
#define STDIN(filename) freopen(filename, "r", stdin)
#define STDOUT(filename) freopen(filename, "w", stdout)
#define FASTIO cin.tie(0)->sync_with_stdio(0)
#define STDIO(filename) \
FASTIO; \
string filenamee(filename); \
STDIN((filenamee + ".in").c_str()); \
STDOUT((filenamee + ".out").c_str())
#define NL '\n'
#define CM ", "
#define SP " "
// ----- FOR LOOPS -----
#define F(i, L, R) for (int i = L; i < R; i++)
#define FE(i, L, R) for (int i = L; i <= R; i++)
#define FD(i, L, R) for (int i = L; i > R; i--)
#define FDE(i, L, R) for (int i = L; i >= R; i--)
// ----- WEZ -----
#define takeI(n) \
int n; \
cin >> n
#define takeII(n, m) \
int n, m; \
cin >> n >> m
#define takeIII(n, m, k) \
int n, m, k; \
cin >> n >> m >> k
#define takeL(n) \
ll n; \
cin >> n
#define takeS(s) \
string s; \
cin >> s
#define takeV(v, n) \
vi v(n); \
for (auto &x : v) \
cin >> x
#define takeVL(v, n) \
vector<ll> v(n); \
for (auto &x : v) \
cin >> x
#define whileZ \
takeI(T); \
while (T--)
//
// ----- MAX MIN -----
#define REMAX(a, b) (a) = max((a), (b))
#define REMIN(a, b) (a) = min((a), (b))
// ----- PAIRS -----
#define fi first
#define se second
// ----- OUTPUT -----
#define YESNO(b) cout << ((b) ? "YES" : "NO") << NL
// ----- DEBUG ----- (compiled out on the judge)
#ifdef LOCAL
#define DBG(vari) cerr << #vari << " = " << (vari) << endl
#define DBG2(a, b) cerr << #a "=" << (a) << CM << #b "=" << (b) << endl
#define printA(a, L, R) FE(i, L, R) cerr << a[i] << (i == R ? '\n' : ' ')
#define printV(a) printA(a, 0, SZ(a) - 1)
#else
#define DBG(vari)
#define DBG2(a, b)
#define printA(a, L, R)
#define printV(a)
#endif
// ----- STL DS
#define ALL(c) (c).begin(), (c).end()
#define SZ(c) ((int)(c).size())
#define SORT(c) sort(ALL(c))
#define RSORT(c) sort(ALL(c), greater<>())
#define UNIQ(c) SORT(c), (c).erase(unique(ALL(c)), (c).end())
#define pb push_back
class Solution {
private:
int toIdx(char x) {
if (x == 'a') return 0;
if (x == 'e') return 1;
if (x == 'i') return 2;
if (x == 'o') return 3;
if (x == 'u') return 4;
return 5;
}
int minLast(int last[5]) {
int res = last[0];
for (int i = 1; i < 5; i++) res = min(last[i], res);
return res;
}
public:
int countVowelSubstrings(string word) {
int n = word.size();
int res = 0;
int start = 0;
int last[5];
memset(last, -1, sizeof(last));
for (int j = 0; j < n; j++) {
int idx = toIdx(word[j]);
// Have const
if (idx > 4) {
start = j + 1;
memset(last, -1, sizeof(last));
continue;
}
last[idx] = j;
int minLst = minLast(last);
if (minLst != -1) {
res += minLst - start + 1;
}
}
return res;
}
};
#ifdef LOCAL // runs the examples; see driver.h
#include "driver.h"
#endif
@@ -0,0 +1,45 @@
# 2062. Count Vowel Substrings of a String
A **substring** is a contiguous (non-empty) sequence of characters within a string.
A **vowel substring** is a substring that **only** consists of vowels (`'a'`, `'e'`, `'i'`, `'o'`, and `'u'`) and has **all five** vowels present in it.
Given a string `word`, return *the number of **vowel substrings** in* `word`.
**Example 1:**
```
Input: word = "aeiouu"
Output: 2
Explanation: The vowel substrings of word are as follows (underlined):
- "aeiouu"
- "aeiouu"
```
**Example 2:**
```
Input: word = "unicornarihan"
Output: 0
Explanation: Not all 5 vowels are present, so there are no vowel substrings.
```
**Example 3:**
```
Input: word = "cuaieuouac"
Output: 7
Explanation: The vowel substrings of word are as follows (underlined):
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
- "cuaieuouac"
```
**Constraints:**
- `1 <= word.length <= 100`
- `word` consists of lowercase English letters only.
@@ -0,0 +1 @@
"aeiouu"
@@ -0,0 +1 @@
2
@@ -0,0 +1 @@
"unicornarihan"
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
"cuaieuouac"
@@ -0,0 +1 @@
7
@@ -0,0 +1 @@
https://leetcode.com/problems/minimum-operations-to-sort-a-string/
@@ -0,0 +1,13 @@
// driver.h - generated by 'usaco new' from LeetCode's metadata (edit freely).
// Reads minimum-operations-to-sort-a-string.in in LeetCode's testcase format, cases back to back:
// one argument per line
// and writes one answer per case to minimum-operations-to-sort-a-string.out, formatted the way LeetCode
// shows its output. Parsing/printing helpers: leetcode.h.
int main() {
freopen("minimum-operations-to-sort-a-string.in", "r", stdin);
freopen("minimum-operations-to-sort-a-string.out", "w", stdout);
for (vector<string> in; lc::read_case(in, 1);) {
auto s = lc::parse<string>(in[0]);
cout << lc::show(Solution().minOperations(s)) << '\n';
}
}
@@ -0,0 +1,102 @@
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL // set by ./usaco builds only, so this is safe to submit as-is
#include "debugging.h"
#include "leetcode.h" // ListNode, TreeNode
#endif
// ----- TYPES -----
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
// ----- FILE IO -----
#define STDIN(filename) freopen(filename, "r", stdin)
#define STDOUT(filename) freopen(filename, "w", stdout)
#define FASTIO cin.tie(0)->sync_with_stdio(0)
#define STDIO(filename) \
FASTIO; \
string filenamee(filename); \
STDIN((filenamee + ".in").c_str()); \
STDOUT((filenamee + ".out").c_str())
#define NL '\n'
#define CM ", "
#define SP " "
// ----- FOR LOOPS -----
#define F(i, L, R) for (int i = L; i < R; i++)
#define FE(i, L, R) for (int i = L; i <= R; i++)
#define FD(i, L, R) for (int i = L; i > R; i--)
#define FDE(i, L, R) for (int i = L; i >= R; i--)
// ----- WEZ -----
#define takeI(n) \
int n; \
cin >> n
#define takeII(n, m) \
int n, m; \
cin >> n >> m
#define takeIII(n, m, k) \
int n, m, k; \
cin >> n >> m >> k
#define takeL(n) \
ll n; \
cin >> n
#define takeS(s) \
string s; \
cin >> s
#define takeV(v, n) \
vi v(n); \
for (auto &x : v) \
cin >> x
#define takeVL(v, n) \
vector<ll> v(n); \
for (auto &x : v) \
cin >> x
#define whileZ \
takeI(T); \
while (T--)
//
// ----- MAX MIN -----
#define REMAX(a, b) (a) = max((a), (b))
#define REMIN(a, b) (a) = min((a), (b))
// ----- PAIRS -----
#define fi first
#define se second
// ----- OUTPUT -----
#define YESNO(b) cout << ((b) ? "YES" : "NO") << NL
// ----- DEBUG ----- (compiled out on the judge)
#ifdef LOCAL
#define DBG(vari) cerr << #vari << " = " << (vari) << endl
#define DBG2(a, b) cerr << #a "=" << (a) << CM << #b "=" << (b) << endl
#define printA(a, L, R) FE(i, L, R) cerr << a[i] << (i == R ? '\n' : ' ')
#define printV(a) printA(a, 0, SZ(a) - 1)
#else
#define DBG(vari)
#define DBG2(a, b)
#define printA(a, L, R)
#define printV(a)
#endif
// ----- STL DS
#define ALL(c) (c).begin(), (c).end()
#define SZ(c) ((int)(c).size())
#define SORT(c) sort(ALL(c))
#define RSORT(c) sort(ALL(c), greater<>())
#define UNIQ(c) SORT(c), (c).erase(unique(ALL(c)), (c).end())
#define pb push_back
class Solution {
public:
int minOperations(string s) {
}
};
#ifdef LOCAL // runs the examples; see driver.h
#include "driver.h"
#endif
@@ -0,0 +1,3 @@
"dog"
"card"
"gf"
@@ -0,0 +1,44 @@
# 3863. Minimum Operations to Sort a String
You are given a string `s` consisting of lowercase English letters.
In one operation, you can select any **substring** of `s` that is **not** the entire string and **sort** it in **non-descending alphabetical** order.
Return the **minimum** number of operations required to make `s` sorted in **non-descending** order. If it is not possible, return -1.
**Example 1:**
**Input:** s = "dog"
**Output:** 1
**Explanation:**​​​​​​​
- Sort substring `"og"` to `"go"`.
- Now, `s = "dgo"`, which is sorted in ascending order. Thus, the answer is 1.
**Example 2:**
**Input:** s = "card"
**Output:** 2
**Explanation:**
- Sort substring `"car"` to `"acr"`, so `s = "acrd"`.
- Sort substring `"rd"` to `"dr"`, making `s = "acdr"`, which is sorted in ascending order. Thus, the answer is 2.
**Example 3:**
**Input:** s = "gf"
**Output:** -1
**Explanation:**
- It is impossible to sort `s` under the given constraints. Thus, the answer is -1.
**Constraints:**
- `1 <= s.length <= 10^5`
- `s` consists of only lowercase English letters.
@@ -0,0 +1 @@
"dog"
@@ -0,0 +1 @@
1
@@ -0,0 +1 @@
"card"
@@ -0,0 +1 @@
2
@@ -0,0 +1 @@
"gf"
@@ -0,0 +1 @@
-1
@@ -0,0 +1 @@
https://leetcode.com/problems/number-of-wonderful-substrings/
@@ -0,0 +1,13 @@
// driver.h - generated by 'usaco new' from LeetCode's metadata (edit freely).
// Reads number-of-wonderful-substrings.in in LeetCode's testcase format, cases back to back:
// one argument per line
// and writes one answer per case to number-of-wonderful-substrings.out, formatted the way LeetCode
// shows its output. Parsing/printing helpers: leetcode.h.
int main() {
freopen("number-of-wonderful-substrings.in", "r", stdin);
freopen("number-of-wonderful-substrings.out", "w", stdout);
for (vector<string> in; lc::read_case(in, 1);) {
auto word = lc::parse<string>(in[0]);
cout << lc::show(Solution().wonderfulSubstrings(word)) << '\n';
}
}
@@ -0,0 +1,139 @@
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL // set by ./usaco builds only, so this is safe to submit as-is
#include "debugging.h"
#include "leetcode.h" // ListNode, TreeNode
#endif
// ----- TYPES -----
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
// ----- FILE IO -----
#define STDIN(filename) freopen(filename, "r", stdin)
#define STDOUT(filename) freopen(filename, "w", stdout)
#define FASTIO cin.tie(0)->sync_with_stdio(0)
#define STDIO(filename) \
FASTIO; \
string filenamee(filename); \
STDIN((filenamee + ".in").c_str()); \
STDOUT((filenamee + ".out").c_str())
#define NL '\n'
#define CM ", "
#define SP " "
// ----- FOR LOOPS -----
#define F(i, L, R) for (int i = L; i < R; i++)
#define FE(i, L, R) for (int i = L; i <= R; i++)
#define FD(i, L, R) for (int i = L; i > R; i--)
#define FDE(i, L, R) for (int i = L; i >= R; i--)
// ----- WEZ -----
#define takeI(n) \
int n; \
cin >> n
#define takeII(n, m) \
int n, m; \
cin >> n >> m
#define takeIII(n, m, k) \
int n, m, k; \
cin >> n >> m >> k
#define takeL(n) \
ll n; \
cin >> n
#define takeS(s) \
string s; \
cin >> s
#define takeV(v, n) \
vi v(n); \
for (auto &x : v) \
cin >> x
#define takeVL(v, n) \
vector<ll> v(n); \
for (auto &x : v) \
cin >> x
#define whileZ \
takeI(T); \
while (T--)
//
// ----- MAX MIN -----
#define REMAX(a, b) (a) = max((a), (b))
#define REMIN(a, b) (a) = min((a), (b))
// ----- PAIRS -----
#define fi first
#define se second
// ----- OUTPUT -----
#define YESNO(b) cout << ((b) ? "YES" : "NO") << NL
// ----- DEBUG ----- (compiled out on the judge)
#ifdef LOCAL
#define DBG(vari) cerr << #vari << " = " << (vari) << endl
#define DBG2(a, b) cerr << #a "=" << (a) << CM << #b "=" << (b) << endl
#define printA(a, L, R) FE(i, L, R) cerr << a[i] << (i == R ? '\n' : ' ')
#define printV(a) printA(a, 0, SZ(a) - 1)
#else
#define DBG(vari)
#define DBG2(a, b)
#define printA(a, L, R)
#define printV(a)
#endif
// ----- STL DS
#define ALL(c) (c).begin(), (c).end()
#define SZ(c) ((int)(c).size())
#define SORT(c) sort(ALL(c))
#define RSORT(c) sort(ALL(c), greater<>())
#define UNIQ(c) SORT(c), (c).erase(unique(ALL(c)), (c).end())
#define pb push_back
class Solution {
public:
long long wonderfulSubstrings(string s) {
/**
Let x be a bitmask for the parity of a string s
A string is wonderful if the bitmask has less than 2 ones
For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
abcj
0010 - Wonderful
0000 - Wonderful
1100 - Not wonderful
Given a string word that consists 'a' through 'j'
return the number of wonderful non-empty substrings in word
If the same substring appears multiple times in word
then count each occurrence separately.
"aabb"
-> 0 1 2 3
"a" -> 0 1000
"aa" -> 1 0000 , 1000
"aab" -> 2 0100 , 1100 , 0100
"aabb" -> 3 0000 , 1000 , 0000, 0100
T(0, j) = T(0, j-1) ^ s[j]
*/
vector<long long> counts(1024, 0);
counts[0] = 1;
int prefix = 0;
long long res = 0;
for (int i = 0; i < s.size(); i++) {
prefix ^= 1 << (s[i] - 'a');
res += counts[prefix];
for (int i = 0; i < 10; i++) {
res += counts[prefix ^ (1 << i)];
}
counts[prefix]++;
}
return res;
}
};
#ifdef LOCAL // runs the examples; see driver.h
#include "driver.h"
#endif

Some files were not shown because too many files have changed in this diff Show More