Add an Explain button that has Claude explain a problem
Test and publish the site / publish (push) Successful in 8m15s
Test and publish the site / test (push) Successful in 5m51s

When stuck, the admin can ask Claude for an intuitive explanation of a
problem. It is committed as explain.md and shown as folded sections, so
the reader opens only as much as they need: the key observation, hints
that get stronger, the approach, a walkthrough with an SVG diagram per
step, complexity, pitfalls and a pseudocode sketch.

- internal/claude: streamed call with a JSON-schema reply, high effort,
  the server-side refusal fallback, fixed error messages and logged
  token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5);
  without a key only this feature is off.
- internal/explain: the prompt, the schema, rendering to markdown, and
  a per-problem job tracker. The request starts a job and the page polls,
  since a call outlasts nginx's 120s timeout.
- internal/statement: fetches statements from LeetCode's GraphQL API and
  USACO's problem pages. Others (Codeforces is behind Cloudflare) are
  pasted.
- problem.md holds the statement, editable from the meta editor and
  shown only to the admin. Diagrams are sanitized with DOMPurify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-19 20:38:15 +01:00
co-authored by Claude Opus 5.5
parent f0e10d2a58
commit 995b44a57a
27 changed files with 2144 additions and 67 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ skipped/<name>/ problems set aside for later
The website's CLI page (`site/web/src/views/CliPage.vue`) is a condensed copy of the Commands section below; keep it in step.
Each problem dir contains `main.cpp` plus `<io>.in` / `<io>.out` files (USACO file IO is wired up automatically via `STDIO("<io>")`). Optional extras: `.url` (the problem link), `tests/N.in` + `N.out`, and `notes.md` (shown on the website, usually written from there).
Each problem dir contains `main.cpp` plus `<io>.in` / `<io>.out` files (USACO file IO is wired up automatically via `STDIO("<io>")`). Optional extras: `.url` (the problem link), `tests/N.in` + `N.out`, `notes.md` (shown on the website, usually written from there), `problem.md` (the statement, saved or fetched from the website's editor) and `explain.md` (an explanation the website had Claude write).
## Commands
+7
View File
@@ -40,3 +40,10 @@ AUTH_MODE=
# The site backend's validate-admin route, on the Docker network
# (default http://backend:8080/auth/validate-admin).
AUTH_VALIDATE_URL=
# --- Claude -----------------------------------------------------------------
# API key for the Explain button. Blank turns explanations off; the rest of
# the site is unaffected.
CLAUDE_API_KEY=
# Model for explanations (default claude-opus-5-5).
CLAUDE_MODEL=
+2 -1
View File
@@ -16,7 +16,8 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al
- **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.
- **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.
- **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.
## Conventions
+23 -2
View File
@@ -4,7 +4,9 @@ The public face of this repo, served at `/usaco/` on adam-french.co.uk. It shows
- mark a problem solved, skipped or back in progress
- set its link
- save the problem statement (pasted, or fetched from a LeetCode or USACO link)
- write notes
- have Claude write an explanation for a problem they are stuck on
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.
@@ -17,6 +19,8 @@ There is no database. The CLI's layout is the data model (see the root README.md
- `tests/N.in` and `N.out`
- `.url` for the problem link
- `notes.md` for notes
- `problem.md` for the statement (shown only to the admin, and sent to Claude)
- `explain.md` for a Claude-written explanation
The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into memory.
@@ -27,7 +31,7 @@ The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into
3. commit as `GIT_AUTHOR_NAME`
4. push
The commit subjects match the CLI's: "Solve <name>", "Skip <name>", "Reopen <name>" and "Update <name>". If someone pushed in between and the push is rejected, the edit is replayed once on the new tip. A second rejection returns 409.
The commit subjects match the CLI's: "Solve <name>", "Skip <name>", "Reopen <name>" and "Update <name>". An explanation commits as "Explain <name>". If someone pushed in between and the push is rejected, the edit is replayed once on the new tip. A second rejection returns 409.
- **Dates come from git, not mtimes.** A problem's solve date is the commit that moved it into `solved/`. Its first and last dates are its first and last commits.
The site commits, so the laptop must pull before pushing. `usaco sync` does `pull --rebase --autostash` and then `push`.
@@ -40,6 +44,9 @@ internal/auth/ is this request the admin? (asks the site backend; copied fr
internal/repo/ the clone: sync, and edit-commit-push with one replay on rejection
internal/index/ reads the clone into memory: problems, files, tests, git dates
internal/handlers/ REST API, Gitea webhook, SPA file server
internal/claude/ the Claude client: streamed call, JSON-schema reply, fixed error messages
internal/explain/ the explanation prompt and schema, explain.md rendering, the job tracker
internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page)
web/ Vue 3 + Vite SPA, built for base /usaco/
```
@@ -53,7 +60,10 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
| `GET /usaco/api/problems` | open; the admin also gets unsolved problems | the list |
| `GET /usaco/api/problems/<name>` | open for solved problems; 404 for others unless admin | one problem, with files, tests and history |
| `GET /usaco/api/me` | open | `{admin}`, so the SPA knows whether to show the edit controls |
| `PUT /usaco/api/problems/<name>/meta` | admin | `{url?, notes?}`: writes `.url` and `notes.md` (blank removes the file) |
| `PUT /usaco/api/problems/<name>/meta` | admin | `{url?, notes?, statement?}`: writes `.url`, `notes.md` and `problem.md` (blank removes the file) |
| `GET /usaco/api/problems/<name>/statement/fetch?url=` | admin | the statement behind `url` (default: the saved link) as markdown, for review; saves nothing. 422 for a judge it can't read |
| `POST /usaco/api/problems/<name>/explain` | admin | `{note?, includeCode?}`: starts an explanation and answers 202; 409 if one is running, 503 without `CLAUDE_API_KEY` |
| `GET /usaco/api/problems/<name>/explain` | admin | the latest job: `{state: idle\|running\|done\|error, error?}` |
| `POST /usaco/api/problems/<name>/status` | admin | `{to: solving\|solved\|skipped}`: moves the directory |
| `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull |
| `GET /usaco/api/health` | open | 200 once the clone is indexed |
@@ -126,8 +136,19 @@ The registry setup is shared with job-tracker (see its README, "One-off: registr
Gitea only delivers to Docker-network hosts that are on `[webhook] ALLOWED_HOST_LIST`. web_server's compose sets that to `external,usaco`. Use "Test delivery": the response should be `202`, and `docker logs usaco` should show a new `[index]` line.
## Explanations
The Explain panel on a problem page (admin only) asks Claude for an intuitive explanation and commits it as `explain.md`.
- **Input.** The statement (`problem.md`; when it is missing, it is fetched from the link and saved too), up to three saved tests with outputs or the sample input, optionally the main solution file, and the admin's "where I'm stuck" note.
- **Output.** A JSON-schema reply (`internal/explain` `Schema`): the key observation, 2 to 4 hints, the approach, a walkthrough whose steps each carry an SVG diagram, complexity, pitfalls and a pseudocode sketch. It is stored as markdown with one `## ` section each, and the page shows every section folded so the reader opens only as much as they need. Diagrams are ```` ```svg ```` fences, sanitized with DOMPurify before they are inserted.
- **The call.** `CLAUDE_MODEL` (default `claude-opus-5-5`) at high effort, streamed, with the server-side refusal fallback on. It takes a minute or two and costs roughly $0.10 to $0.60. The request only starts a background job, because nginx gives up after 120 seconds; the page polls. Token usage is logged as `[claude]` lines.
- **Statements.** LeetCode and USACO can be fetched. Codeforces sits behind a Cloudflare challenge, and other judges are unknown, so paste those.
## 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 job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again.
- **`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.
+13 -1
View File
@@ -1,6 +1,7 @@
// Command usacosite serves the USACO practice log at /usaco/: the problems
// from adamf/usaco on the site's Gitea, their solutions and tests, and a few
// admin edits (problem link, notes, status) that it commits back to git.
// admin edits (problem link, notes, statement, status) and Claude-written
// explanations that it commits back to git.
//
// It is built to sit behind adam-french.co.uk's nginx and borrow its login
// (internal/auth), like the job tracker. There is no database: the server
@@ -21,6 +22,7 @@ import (
"github.com/gin-gonic/gin"
"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/repo"
)
@@ -66,6 +68,16 @@ func main() {
log.Println("[webhook] WEBHOOK_SECRET is not set: the push hook is off, pulls happen on the interval only")
}
// CLAUDE
// Optional: without a key the site runs as before and the Explain
// button answers 503.
if c, err := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL")); err == nil {
srv.Claude = c
log.Printf("[claude] explanations use %s", c.Model())
} else {
log.Printf("[claude] %v: explanations are off", err)
}
rp, err := repo.New(repo.Config{
Dir: filepath.Join(dataDir, "repo"),
Remote: remote,
+4
View File
@@ -27,6 +27,10 @@ services:
GIT_CONFIG_COUNT: "1"
GIT_CONFIG_KEY_0: safe.directory
GIT_CONFIG_VALUE_0: "*"
# From your shell or a .env next to this file; blank turns the
# Explain button off.
CLAUDE_API_KEY: ${CLAUDE_API_KEY:-}
CLAUDE_MODEL: ${CLAUDE_MODEL:-}
volumes:
- ..:/seed:ro
- usaco-data:/data
+32 -11
View File
@@ -1,39 +1,60 @@
module adam-french.co.uk/usaco-site
go 1.26
require github.com/gin-gonic/gin v1.11.0
go 1.26.0
require (
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2
github.com/anthropics/anthropic-sdk-go v1.82.0
github.com/gin-gonic/gin v1.11.0
golang.org/x/net v0.61.0
)
require (
github.com/JohannesKaufmann/dom v0.3.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.2 // indirect
github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/invopop/jsonschema v0.14.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel v1.33.0 // indirect
go.opentelemetry.io/otel/metric v1.33.0 // indirect
go.opentelemetry.io/otel/trace v1.33.0 // indirect
go.uber.org/mock v0.5.0 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
golang.org/x/arch v0.20.0 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/mod v0.25.0 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/tools v0.34.0 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.51.0 // indirect
google.golang.org/protobuf v1.36.9 // indirect
)
+141 -17
View File
@@ -1,3 +1,47 @@
cloud.google.com/go/auth v0.7.2 h1:uiha352VrCDMXg+yoBtaD0tUF4Kv9vrtrWPYXwutnDE=
cloud.google.com/go/auth v0.7.2/go.mod h1:VEc4p5NNxycWQTMQEDQF0bd6aTMb6VgYDXEwiJJQAbs=
cloud.google.com/go/auth/oauth2adapt v0.2.3 h1:MlxF+Pd3OmSudg/b1yZ5lJwoXCEaeedAguodky1PcKI=
cloud.google.com/go/auth/oauth2adapt v0.2.3/go.mod h1:tMQXOfZzFuNuUxOypHlQEXgdfX5cuhwU+ffUuXRJE8I=
cloud.google.com/go/compute/metadata v0.5.0 h1:Zr0eK8JbFv6+Wi4ilXAR8FJ3wyNdpxHKJNPos6LTZOY=
cloud.google.com/go/compute/metadata v0.5.0/go.mod h1:aHnloV2TPI38yx4s9+wAZhHykWvVCfu7hQbF+9CWoiY=
github.com/JohannesKaufmann/dom v0.3.1 h1:J16l9JAHWgkFPR3VIPbQ1gvS0cWab6laK1q7PFL3qh0=
github.com/JohannesKaufmann/dom v0.3.1/go.mod h1:BZPkf8ZeYrBgABjwJn9iiKt8aiCtkxpHkevms+Yp2DE=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 h1:XFJZFWESIWlUEHHjzBuv8RvrtCWnSGlimEX17ysSDb8=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2/go.mod h1:BHWO8lJzttJLqwuV8Rb1B3OG2OSzLbssZDI1FRg2eAA=
github.com/anthropics/anthropic-sdk-go v1.82.0 h1:A82J+yHEMbQ3+7ObCagOX4tVm1uyBhELCHd2dDYZYuo=
github.com/anthropics/anthropic-sdk-go v1.82.0/go.mod h1:GThfYqPJoaQ/6pmibCI98Cr4y5su2FXMUHn3NrSSnIc=
github.com/aws/aws-sdk-go-v2 v1.38.0 h1:UCRQ5mlqcFk9HJDIqENSLR3wiG1VTWlyUfLDEvY7RxU=
github.com/aws/aws-sdk-go-v2 v1.38.0/go.mod h1:9Q0OoGQoboYIAJyslFyF1f5K1Ryddop8gqMhWx/n4Wg=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM=
github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90=
github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg=
github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI=
github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII=
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM=
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw=
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE=
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ=
github.com/aws/smithy-go v1.22.5 h1:P9ATCXPMb2mPjYBgueqJNCA5S9UfktsW0tTxi+a7eqw=
github.com/aws/smithy-go v1.22.5/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
@@ -7,12 +51,21 @@ github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gE
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -25,21 +78,39 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/modelcontextprotocol/go-sdk v1.3.1 h1:TfqtNKOIWN4Z1oqmPAiWDC2Jq7K9OdJaooe0teoXASI=
github.com/modelcontextprotocol/go-sdk v1.3.1/go.mod h1:DgVX498dMD8UJlseK1S5i1T4tFz2fkBk4xogC3D15nw=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@@ -48,6 +119,16 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI=
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -57,32 +138,75 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw=
go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I=
go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ=
go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M=
go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM=
go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM=
go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s=
go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=
go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
google.golang.org/api v0.189.0 h1:equMo30LypAkdkLMBqfeIqtyAnlyig1JSZArl4XPwdI=
google.golang.org/api v0.189.0/go.mod h1:FLWGJKb0hb+pU2j+rJqwbnsF+ym+fQs73rbJ+KAUgy8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade h1:oCRSWfwGXQsqlVdErcyTt4A93Y8fo0/9D4b1gnI++qo=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY=
google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA=
google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+148
View File
@@ -0,0 +1,148 @@
// Package claude is the site's one way of calling Claude: a fixed system
// prompt and one user message in, a reply constrained to a JSON schema out.
//
// It follows web_server's python/app/claude.py (the key is CLAUDE_API_KEY,
// a missing key only switches the Claude features off, and the errors shown
// to the admin are fixed strings while the detail goes to the log) but is
// tuned for the opposite kind of call: a long, considered answer rather than
// a few hundred tokens of extraction. Hence streaming (a non-streaming
// request this size risks the HTTP timeout), high effort, and structured
// outputs instead of parsing JSON out of free text.
package claude
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/anthropics/anthropic-sdk-go/shared/constant"
)
// DefaultModel is used when CLAUDE_MODEL is blank.
const DefaultModel = "claude-opus-5-5"
// ErrNotConfigured is a server with no CLAUDE_API_KEY.
var ErrNotConfigured = errors.New("CLAUDE_API_KEY is not set")
// Failure is a call that did not produce an answer. Msg is safe to show the
// admin; Err (logged, never sent) says why.
type Failure struct {
Msg string
Err error
}
func (f *Failure) Error() string { return f.Msg }
func (f *Failure) Unwrap() error { return f.Err }
// Request is one call.
type Request struct {
System string
User string
Schema map[string]any
MaxTokens int64
}
// Client calls the API with one model.
type Client struct {
api anthropic.Client
model string
}
// New builds a client, or returns ErrNotConfigured for a blank key. opts
// are for tests (a fake server's base URL).
func New(key, model string, opts ...option.RequestOption) (*Client, error) {
if key == "" {
return nil, ErrNotConfigured
}
if model == "" {
model = DefaultModel
}
return &Client{api: anthropic.NewClient(append([]option.RequestOption{option.WithAPIKey(key)}, opts...)...), model: model}, nil
}
// Model is the model every call uses.
func (c *Client) Model() string { return c.model }
// JSON makes the call and unmarshals the reply into out.
func (c *Client) JSON(ctx context.Context, req Request, out any) error {
params := anthropic.BetaMessageNewParams{
Model: c.model,
MaxTokens: req.MaxTokens,
// The system prompt is the same on every call, so it is worth
// caching; the problem goes in the user message after it.
System: []anthropic.BetaTextBlockParam{{
Text: req.System,
CacheControl: anthropic.NewBetaCacheControlEphemeralParam(),
}},
Messages: []anthropic.BetaMessageParam{
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(req.User)),
},
// Explaining a problem well is the whole point, so effort is set
// explicitly: claude-opus-5-5 defaults to medium. Thinking is left
// unset, which is adaptive on every model this is meant for.
OutputConfig: anthropic.BetaOutputConfigParam{
Effort: anthropic.BetaOutputConfigEffortHigh,
Format: anthropic.BetaJSONOutputFormatParam{Schema: req.Schema},
},
// A request the safety classifiers decline is retried on whichever
// model the API picks for that category, inside the same call.
Fallbacks: anthropic.BetaFallbacksParamUnion{OfDefault: constant.ValueOf[constant.Default]()},
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaServerSideFallback2026_07_01},
}
stream := c.api.Beta.Messages.NewStreaming(ctx, params)
msg := anthropic.BetaMessage{}
for stream.Next() {
if err := msg.Accumulate(stream.Current()); err != nil {
return &Failure{"Claude's reply could not be read", err}
}
}
if err := stream.Err(); err != nil {
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)
switch msg.StopReason {
case anthropic.BetaStopReasonRefusal:
return &Failure{"Claude declined to answer", fmt.Errorf("refusal: %s %s", msg.StopDetails.Category, msg.StopDetails.Explanation)}
case anthropic.BetaStopReasonMaxTokens:
return &Failure{"Claude's answer ran past the length limit", errors.New("max_tokens")}
}
// With thinking on, the reply's first block can be a thinking block, so
// the answer is the text block, wherever it is.
for _, b := range msg.Content {
if b.Type == "text" {
if err := json.Unmarshal([]byte(b.Text), out); err != nil {
return &Failure{"Claude's reply could not be read", err}
}
return nil
}
}
return &Failure{"Claude's reply was empty", errors.New("no text block")}
}
func apiFailure(err error) error {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return &Failure{"Claude took too long", err}
}
var apiErr *anthropic.Error
if errors.As(err, &apiErr) {
switch {
case apiErr.StatusCode == 401 || apiErr.StatusCode == 403:
return &Failure{"the Claude API key was refused", err}
case apiErr.StatusCode == 429:
return &Failure{"Claude is rate limited; try again in a minute", err}
case apiErr.StatusCode >= 500:
return &Failure{"Claude is unavailable; try again later", err}
}
return &Failure{"the request to Claude was rejected", err}
}
return &Failure{"could not reach Claude", err}
}
+113
View File
@@ -0,0 +1,113 @@
package claude
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/anthropics/anthropic-sdk-go/option"
)
// sse is a minimal streamed reply: one text block holding text.
func sse(text, stop string) string {
ev := func(typ string, data any) string {
b, _ := json.Marshal(data)
return fmt.Sprintf("event: %s\ndata: %s\n\n", typ, b)
}
return ev("message_start", map[string]any{"type": "message_start", "message": map[string]any{
"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-opus-5-5", "content": []any{},
"usage": map[string]any{"input_tokens": 10, "output_tokens": 0}}}) +
ev("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}) +
ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": text}}) +
ev("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) +
ev("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop}, "usage": map[string]any{"output_tokens": 5}}) +
ev("message_stop", map[string]any{"type": "message_stop"})
}
func fake(t *testing.T, status int, reply string, got *map[string]any, header *http.Header) *Client {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
if got != nil {
json.Unmarshal(b, got)
}
if header != nil {
*header = r.Header.Clone()
}
if status != 200 {
w.WriteHeader(status)
w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`))
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Write([]byte(reply))
}))
t.Cleanup(srv.Close)
c, err := New("k", "", option.WithBaseURL(srv.URL), option.WithMaxRetries(0))
if err != nil {
t.Fatal(err)
}
return c
}
func TestNotConfigured(t *testing.T) {
if _, err := New("", ""); !errors.Is(err, ErrNotConfigured) {
t.Fatalf("blank key: %v", err)
}
}
func TestJSONRequestAndReply(t *testing.T) {
var body map[string]any
var hdr http.Header
c := fake(t, 200, sse(`{"a":"hi"}`, "end_turn"), &body, &hdr)
var out struct{ A string }
err := c.JSON(context.Background(), Request{System: "sys", User: "u", Schema: map[string]any{"type": "object"}, MaxTokens: 100}, &out)
if err != nil {
t.Fatal(err)
}
if out.A != "hi" {
t.Errorf("decoded %+v", out)
}
if body["model"] != DefaultModel || body["stream"] != true || body["fallbacks"] != "default" {
t.Errorf("model/stream/fallbacks = %v %v %v", body["model"], body["stream"], body["fallbacks"])
}
oc, _ := body["output_config"].(map[string]any)
format, _ := oc["format"].(map[string]any)
if oc["effort"] != "high" || format["type"] != "json_schema" || format["schema"] == nil {
t.Errorf("output_config = %v", oc)
}
if !strings.Contains(hdr.Get("Anthropic-Beta"), "server-side-fallback-2026-07-01") {
t.Errorf("beta header = %q", hdr.Get("Anthropic-Beta"))
}
}
func TestFailures(t *testing.T) {
cases := []struct {
name string
status int
reply string
want string
}{
{"refusal", 200, sse("", "refusal"), "declined"},
{"cut off", 200, sse(`{"a":`, "max_tokens"), "length limit"},
{"not json", 200, sse("plain words", "end_turn"), "could not be read"},
{"bad key", 401, "", "key was refused"},
{"overloaded", 529, "", "unavailable"},
}
for _, tc := range cases {
c := fake(t, tc.status, tc.reply, nil, nil)
var out map[string]any
err := c.JSON(context.Background(), Request{System: "s", User: "u", Schema: map[string]any{}, MaxTokens: 10}, &out)
var f *Failure
if !errors.As(err, &f) || !strings.Contains(f.Msg, tc.want) {
t.Errorf("%s: err = %v, want a Failure mentioning %q", tc.name, err, tc.want)
}
}
}
+191
View File
@@ -0,0 +1,191 @@
// Package explain turns a problem the admin is stuck on into explain.md: an
// intuitive walkthrough of the solution, written by Claude, with SVG
// diagrams of the idea running on the sample.
//
// The reply is a fixed JSON shape (Result) so the page can lay it out as a
// ladder the reader climbs only as far as they need: the key observation,
// hints that get stronger, then the approach, the walkthrough, and a sketch.
// It is stored as markdown, not JSON, so it reads fine on Gitea and can be
// edited by hand like notes.md.
package explain
import (
"context"
"fmt"
"strings"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/index"
)
// Asker is the part of claude.Client used here, so tests can fake it.
type Asker interface {
JSON(ctx context.Context, req claude.Request, out any) error
Model() string
}
// Example is one sample case shown to Claude.
type Example struct {
In, Out string
}
// Input is what Claude is told about the problem.
type Input struct {
Name string
Statement string
Note string // what the admin says they are stuck on
Code *index.File // their current attempt, when they chose to send it
Examples []Example
}
// Step is one frame of the walkthrough.
type Step struct {
Caption string `json:"caption"`
SVG string `json:"svg"`
}
// Result is the reply's shape; Schema is the same thing for the API.
type Result struct {
Observation string `json:"observation"`
Hints []string `json:"hints"`
Approach string `json:"approach"`
Walkthrough []Step `json:"walkthrough"`
Complexity string `json:"complexity"`
Pitfalls []string `json:"pitfalls"`
Sketch string `json:"sketch"`
}
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{
"observation": str("The single key insight the solution rests on, in one or two sentences of markdown. Name the insight without describing the algorithm."),
"hints": strs("Two to four hints in markdown, each a step stronger than the last. The first only nudges; the last leaves the reader one step from the approach."),
"approach": str("Markdown. The algorithm explained intuitively: how you would think of it from the problem, why it is correct, and what each piece of state means."),
"walkthrough": map[string]any{
"type": "array",
"description": "Two to six steps tracing the approach on a small example, ideally the sample.",
"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 and memory, with a one-line reason for each."),
"pitfalls": strs("Markdown. The mistakes that commonly break this problem: edge cases, overflow, off-by-ones, wrong greedy choices."),
"sketch": str("Language-agnostic pseudocode for the core of the solution, without any I/O boilerplate. Plain text, no code fence."),
},
"required": []string{"observation", "hints", "approach", "walkthrough", "complexity", "pitfalls", "sketch"},
"additionalProperties": false,
}
// maxTokens leaves room for adaptive thinking at high effort on top of the
// reply, which is a few thousand tokens of prose plus the SVGs.
const maxTokens = 32000
// 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.
How to explain:
- Lead with intuition. Explain how someone could arrive at the idea from the problem's structure: what about the constraints or the question suggests it, and what simpler approach fails and why.
- Make every part of the state concrete. When you introduce a DP table, a heap, a union-find or two pointers, say exactly what each entry or pointer means.
- Justify correctness informally but convincingly, especially for greedy choices.
- 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. Use $...$ only if the problem statement does.
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.`
// Prompt is the user message: the problem and what the admin has given.
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")
}
if in.Code != nil {
fmt.Fprintf(&b, "\n<my_attempt file=%q>\n%s\n</my_attempt>\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n"))
}
if note := strings.TrimSpace(in.Note); note != "" {
fmt.Fprintf(&b, "\n<where_i_am_stuck>\n%s\n</where_i_am_stuck>\n", note)
}
b.WriteString("\nExplain how to solve this problem.")
return b.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)
if err != nil {
return "", err
}
return Render(r, a.Model(), now), nil
}
// Render lays a Result out as markdown. The page folds each "## " section
// away; the line above the first one stays visible.
func Render(r Result, model string, now time.Time) string {
var b strings.Builder
fmt.Fprintf(&b, "_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("Key observation", r.Observation)
for i, h := range r.Hints {
section(fmt.Sprintf("Hint %d", i+1), h)
}
section("Approach", r.Approach)
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())
section("Complexity", r.Complexity)
section("Pitfalls", bullets(r.Pitfalls))
if sk := strings.TrimSpace(strings.ReplaceAll(r.Sketch, "```", "")); sk != "" {
section("Solution sketch", "```text\n"+sk+"\n```")
}
return b.String()
}
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()
}
+138
View File
@@ -0,0 +1,138 @@
package explain
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/index"
)
func TestRender(t *testing.T) {
r := Result{
Observation: "The answer is monotone in the effort limit.",
Hints: []string{"Fix a limit.", "Binary search it, or run Dijkstra on max-edge."},
Approach: "Dijkstra where a path costs its largest step.",
Walkthrough: []Step{
{Caption: "Start at (0,0).", SVG: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"></svg>`},
{Caption: "Relax neighbours.", SVG: "```<svg></svg>"},
},
Complexity: "O(RC log RC).",
Pitfalls: []string{"Effort is the max, not the sum.", ""},
Sketch: "dist[0][0] = 0\npop smallest",
}
got := Render(r, "claude-opus-5-5", time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC))
want := "_Explained by claude-opus-5-5 on 19 October 2026._\n" +
"\n## Key observation\n\nThe answer is monotone in the effort limit.\n" +
"\n## Hint 1\n\nFix a limit.\n" +
"\n## Hint 2\n\nBinary search it, or run Dijkstra on max-edge.\n" +
"\n## Approach\n\nDijkstra where a path costs its largest step.\n" +
"\n## Walkthrough\n\n**Step 1.** Start at (0,0).\n\n```svg\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"></svg>\n```\n\n" +
"**Step 2.** Relax neighbours.\n\n```svg\n<svg></svg>\n```\n" +
"\n## Complexity\n\nO(RC log RC).\n" +
"\n## Pitfalls\n\n- Effort is the max, not the sum.\n" +
"\n## Solution sketch\n\n```text\ndist[0][0] = 0\npop smallest\n```\n"
if got != want {
t.Errorf("Render =\n%s\nwant\n%s", got, want)
}
}
func TestPrompt(t *testing.T) {
p := Prompt(Input{
Name: "min-effort-path",
Statement: "# Path With Minimum Effort\n\nA hiker...",
Note: " my BFS is wrong ",
Code: &index.File{Name: "main.rs", Content: "fn main() {}\n"},
Examples: []Example{{In: "1 2\n", Out: "3\n"}, {In: "5\n"}},
})
for _, want := range []string{
"<problem name=\"min-effort-path\">\n# Path With Minimum Effort",
"<example n=\"1\">\n<input>\n1 2\n</input>\n<output>\n3\n</output>",
"<example n=\"2\">\n<input>\n5\n</input>\n</example>",
"<my_attempt file=\"main.rs\">\nfn main() {}\n</my_attempt>",
"<where_i_am_stuck>\nmy BFS is wrong\n</where_i_am_stuck>",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
if q := Prompt(Input{Name: "x", Statement: "s"}); strings.Contains(q, "my_attempt") || strings.Contains(q, "stuck") {
t.Errorf("empty code and note should leave their blocks out:\n%s", q)
}
}
// 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{Hints: []string{}, Walkthrough: []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{Observation: "obs"}
return nil
}
func TestGenerate(t *testing.T) {
a := &fakeAsker{}
md, err := Generate(context.Background(), a, Input{Name: "x", Statement: "s"}, time.Now())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(md, "_Explained by fake on") || !strings.Contains(md, "## Key observation\n\nobs") {
t.Errorf("unexpected markdown:\n%s", md)
}
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)
}
}
+69
View File
@@ -0,0 +1,69 @@
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}
}
+219
View File
@@ -0,0 +1,219 @@
package handlers
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
"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/repo"
"adam-french.co.uk/usaco-site/internal/statement"
)
// Fetcher is the part of statement.Fetcher the handlers use, so tests can
// fake the judges.
type Fetcher interface {
Fetch(ctx context.Context, link string) (string, error)
}
func (s *Server) fetcher() Fetcher {
if s.Statements != nil {
return s.Statements
}
return &statement.Fetcher{}
}
// fetchStatement returns the statement behind ?url= (or the saved link) for
// the admin to review in the editor. It saves nothing.
func (s *Server) fetchStatement(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
link := strings.TrimSpace(ctx.Query("url"))
if link == "" {
link = p.URL
}
if u, err := url.Parse(link); link == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "give the problem an http(s) link first"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), 20*time.Second)
defer cancel()
md, err := s.fetcher().Fetch(c, link)
switch {
case errors.Is(err, statement.ErrUnsupported):
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
case err != nil:
log.Printf("[statement] %s: %v", link, err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
default:
ctx.JSON(http.StatusOK, gin.H{"statement": md})
}
}
type explainBody struct {
Note string `json:"note"`
IncludeCode bool `json:"includeCode"`
}
const maxNote = 4 << 10
// Claude can take a few minutes at high effort; this also bounds the
// commit that follows.
const explainTimeout = 10 * time.Minute
// startExplain starts writing explain.md and answers at once; the page polls
// explainStatus. Everything Claude sees is taken from the index now, so a
// sync during the call changes nothing but where the result is committed.
func (s *Server) startExplain(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
return
}
var body explainBody
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
}
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 := explain.Input{Name: p.Name, Statement: p.Statement, Note: body.Note, Examples: examples(p)}
if body.IncludeCode {
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
}
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))
}
}
// 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 {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
// No statement saved: fetch it, and save it alongside the explanation
// so the next one does not need the judge.
fetched := ""
if strings.TrimSpace(in.Statement) == "" {
md, err := s.fetcher().Fetch(ctx, link)
if err != nil {
log.Printf("[explain] %s: fetching %s: %v", in.Name, link, err)
return fmt.Errorf("could not fetch the statement (%v); paste it into the editor", err)
}
in.Statement, fetched = md, md
}
md, err := explain.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err)
return f
}
log.Printf("[explain] %s: %v", in.Name, err)
return errors.New("the explanation could not be written")
}
name := in.Name
err = s.Repo.Mutate(ctx, "Explain "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if fetched != "" {
// Only if it is still missing: the admin may have pasted one
// while Claude was working.
if _, err := os.Stat(filepath.Join(pdir, "problem.md")); os.IsNotExist(err) {
if err := writeOrRemove(filepath.Join(pdir, "problem.md"), fetched); err != nil {
return err
}
}
}
return writeOrRemove(filepath.Join(pdir, "explain.md"), md)
})
var re *requestError
switch {
case err == nil:
return nil
case errors.As(err, &re):
return errors.New(re.msg)
case errors.Is(err, repo.ErrRejected):
return errors.New("the repository changed while saving; try again")
default:
log.Printf("[explain] %s: saving: %v", name, err)
return errors.New("the explanation was written but could not be saved to git")
}
}
// mainFile is the CLI's solution (main.cpp, main.rs...), else the first
// solution file.
func mainFile(p *index.Problem) *index.File {
for i := range p.Files {
if strings.HasPrefix(p.Files[i].Name, "main.") {
return &p.Files[i]
}
}
if len(p.Files) > 0 {
return &p.Files[0]
}
return nil
}
// A case bigger than this is a stress test, not something to trace by hand,
// and a truncated one would mislead.
const maxExample = 2 << 10
// examples are the saved tests that have an expected output, then the
// sample input if no test has the same input. Three is plenty to trace.
func examples(p *index.Problem) []explain.Example {
var out []explain.Example
seen := map[string]bool{}
for _, t := range p.TestSet {
if len(out) == 3 {
return out
}
if t.Output == nil || t.Input.Truncated || len(t.Input.Content) > maxExample || len(t.Output.Content) > maxExample {
continue
}
out = append(out, explain.Example{In: t.Input.Content, Out: t.Output.Content})
seen[strings.TrimSpace(t.Input.Content)] = true
}
if sm := p.Sample; sm != nil && len(out) < 3 && len(sm.Content) <= maxExample && !seen[strings.TrimSpace(sm.Content)] {
out = append(out, explain.Example{In: sm.Content})
}
return out
}
+161
View File
@@ -0,0 +1,161 @@
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/explain"
"adam-french.co.uk/usaco-site/internal/statement"
)
// fakeClaude answers every request with one observation. If gate is set,
// it waits for it to close first, so a test can catch a job mid-run.
type fakeClaude struct {
gate chan struct{}
user string
}
func (f *fakeClaude) Model() string { return "fake-model" }
func (f *fakeClaude) JSON(_ context.Context, req claude.Request, out any) error {
if f.gate != nil {
<-f.gate
}
f.user = req.User
*out.(*explain.Result) = explain.Result{Observation: "Think in reverse."}
return nil
}
// fakeJudge knows one link.
type fakeJudge struct{}
func (fakeJudge) Fetch(_ context.Context, link string) (string, error) {
if link == "https://usaco.org/moocast" {
return "# Moocast\n\nCows with walkie-talkies.", nil
}
return "", statement.ErrUnsupported
}
func waitJob(t *testing.T, r *gin.Engine, name string) explain.Status {
t.Helper()
for range 400 {
rec := do(r, "GET", "/usaco/api/problems/"+name+"/explain", "", true)
var s explain.Status
json.Unmarshal(rec.Body.Bytes(), &s)
if s.State != explain.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job still running")
return explain.Status{}
}
func TestExplainNeedsClaudeAndAStatement(t *testing.T) {
r, repo, _ := setup(t)
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true); rec.Code != 503 {
t.Fatalf("no Claude = %d, want 503", rec.Code)
}
repo.srv.Claude = &fakeClaude{}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true); rec.Code != 400 {
t.Fatalf("no statement or link = %d, want 400: %s", rec.Code, rec.Body)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, false); rec.Code != 401 {
t.Fatalf("public explain = %d, want 401", rec.Code)
}
}
func TestExplainWritesAndCommits(t *testing.T) {
r, repo, _ := setup(t)
fc := &fakeClaude{gate: make(chan struct{})}
repo.srv.Claude = fc
if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast\nsecret statement"}`, true); rec.Code != 200 {
t.Fatalf("saving a statement = %d: %s", rec.Code, rec.Body)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{"note":"stuck on order","includeCode":true}`, true); rec.Code != 202 {
t.Fatalf("start = %d: %s", rec.Code, rec.Body)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/explain", `{}`, true); rec.Code != 409 {
t.Fatalf("second start while running = %d, want 409", rec.Code)
}
close(fc.gate)
if s := waitJob(t, r, "moocast"); s.State != explain.Done {
t.Fatalf("job = %+v, want done", s)
}
for _, want := range []string{"secret statement", "stuck on order", "<my_attempt file=\"main.cpp\">"} {
if !strings.Contains(fc.user, want) {
t.Errorf("prompt is missing %q:\n%s", want, fc.user)
}
}
b, err := os.ReadFile(filepath.Join(repo.dir, "solved/moocast/explain.md"))
if err != nil || !strings.Contains(string(b), "## Key observation\n\nThink in reverse.") {
t.Fatalf("explain.md = %q, %v", b, err)
}
if last := repo.msg[len(repo.msg)-1]; last != "Explain moocast" {
t.Errorf("commit subject = %q", last)
}
// The public sees the explanation of a solved problem, not the statement.
var pub struct{ Statement, Explanation string }
json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", false).Body.Bytes(), &pub)
if pub.Statement != "" || !strings.Contains(pub.Explanation, "Think in reverse.") {
t.Errorf("public view = %+v", pub)
}
var adm struct{ Statement string }
json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", true).Body.Bytes(), &adm)
if !strings.Contains(adm.Statement, "secret statement") {
t.Errorf("admin should see the statement, got %q", adm.Statement)
}
}
func TestExplainFetchesAMissingStatement(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.Claude = &fakeClaude{}
repo.srv.Statements = fakeJudge{}
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") {
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 {
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") {
t.Errorf("fetched statement not saved: %q", b)
}
}
func TestFetchStatement(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.Statements = fakeJudge{}
if rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch", "", true); rec.Code != 400 {
t.Fatalf("no link = %d, want 400", rec.Code)
}
if rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch?url=https://cses.fi/x", "", true); rec.Code != 422 {
t.Fatalf("unsupported judge = %d, want 422", rec.Code)
}
rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch?url=https://usaco.org/moocast", "", true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "walkie-talkies") {
t.Fatalf("fetch = %d %s", rec.Code, rec.Body)
}
if _, err := os.Stat(filepath.Join(repo.dir, "solved/moocast/problem.md")); !os.IsNotExist(err) {
t.Error("fetching must not save anything")
}
if rec := do(r, "GET", "/usaco/api/problems/moocast/statement/fetch?url=https://usaco.org/moocast", "", false); rec.Code != 401 {
t.Fatalf("public fetch = %d, want 401", rec.Code)
}
}
+37 -4
View File
@@ -1,6 +1,7 @@
// 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, and the
// Gitea webhook that tells the server to pull.
// for solved problems, everything for the admin), the admin's edits, the
// Claude explanations (explain.go), and the Gitea webhook that tells the
// server to pull.
package handlers
import (
@@ -24,6 +25,7 @@ import (
"github.com/gin-gonic/gin"
"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/repo"
)
@@ -41,8 +43,15 @@ type Server struct {
// Pull asks for a sync. It must not block: the webhook answers at once
// and the sync runs in the background.
Pull func()
// Claude writes the explanations; nil when CLAUDE_API_KEY is not set,
// which turns only that feature off.
Claude explain.Asker
// Statements reads a statement from the problem's judge; nil means the
// real judges.
Statements Fetcher
idx atomic.Pointer[index.Index]
jobs explain.Jobs
}
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
@@ -73,6 +82,9 @@ func (s *Server) Routes(api *gin.RouterGroup) {
api.GET("/problems/:name", s.get)
admin.PUT("/problems/:name/meta", s.updateMeta)
admin.POST("/problems/:name/status", s.setStatus)
admin.GET("/problems/:name/statement/fetch", s.fetchStatement)
admin.POST("/problems/:name/explain", s.startExplain)
admin.GET("/problems/:name/explain", s.explainStatus)
api.POST("/hooks/gitea", s.webhook)
}
@@ -144,9 +156,20 @@ func (s *Server) lookup(ctx *gin.Context, admin bool) (*index.Problem, bool) {
}
func (s *Server) get(ctx *gin.Context) {
if p, ok := s.lookup(ctx, s.isAdmin(ctx)); ok {
ctx.JSON(http.StatusOK, p)
admin := s.isAdmin(ctx)
p, ok := s.lookup(ctx, admin)
if !ok {
return
}
// The statement is the judge's text, kept for the admin and for Claude;
// the public page links to the judge instead. The index is shared, so
// this blanks a copy.
if !admin && p.Statement != "" {
c := *p
c.Statement = ""
p = &c
}
ctx.JSON(http.StatusOK, p)
}
// requestError is an edit that cannot be made, with the status to send.
@@ -196,6 +219,7 @@ func findOnDisk(dir, name string) (status string, err error) {
type metaBody struct {
URL *string `json:"url"`
Notes *string `json:"notes"`
Statement *string `json:"statement"`
}
const maxNotes = 64 << 10
@@ -225,6 +249,10 @@ func (s *Server) updateMeta(ctx *gin.Context) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "notes are too long"})
return
}
if body.Statement != nil && len(*body.Statement) > maxNotes {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the statement is too long"})
return
}
name := p.Name
s.mutate(ctx, name, "Update "+name, func(dir string) error {
@@ -244,6 +272,11 @@ func (s *Server) updateMeta(ctx *gin.Context) {
return err
}
}
if body.Statement != nil {
if err := writeOrRemove(filepath.Join(pdir, "problem.md"), *body.Statement); err != nil {
return err
}
}
return nil
})
}
+17 -3
View File
@@ -3,9 +3,11 @@
//
// The layout is the CLI's (README.md at the repo root): solving/, solved/
// and skipped/<name>/, each with a solution (main.cpp, sol.py...), an <io>.in
// the CLI wires up, tests/N.in + N.out, an optional .url and an optional
// notes.md. The repo is small, so everything, file contents included, is
// read on each rebuild, and a rebuild only happens when the clone changes.
// 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)
// and explain.md (an explanation the site had Claude write). The repo is
// small, so everything, file contents included, is read on each rebuild,
// and a rebuild only happens when the clone changes.
package index
import (
@@ -68,6 +70,7 @@ type Summary struct {
Langs []string `json:"langs"`
Tests int `json:"tests"`
HasNotes bool `json:"hasNotes"`
HasExplanation bool `json:"hasExplanation"`
FirstSeen *time.Time `json:"firstSeen,omitempty"`
SolvedAt *time.Time `json:"solvedAt,omitempty"`
LastTouched *time.Time `json:"lastTouched,omitempty"`
@@ -78,6 +81,10 @@ type Problem struct {
Summary
IO string `json:"io,omitempty"`
Notes string `json:"notes"`
// Statement is the judge's text, so the handlers send it to the admin
// only: the site should not republish it.
Statement string `json:"statement,omitempty"`
Explanation string `json:"explanation"`
Files []File `json:"files"`
Sample *File `json:"sample,omitempty"`
TestSet []Test `json:"testCases"`
@@ -157,6 +164,12 @@ func readProblem(pdir, status string) (*Problem, error) {
case name == "notes.md":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.Notes = string(b)
case name == "problem.md":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.Statement = string(b)
case name == "explain.md":
b, _ := os.ReadFile(filepath.Join(pdir, name))
p.Explanation = string(b)
case strings.HasSuffix(name, ".in") && p.IO == "":
// The first *.in, as detect_io in lib/common.sh picks it.
p.IO = strings.TrimSuffix(name, ".in")
@@ -195,6 +208,7 @@ func readProblem(pdir, status string) (*Problem, error) {
p.TestSet = tests
p.Tests = len(tests)
p.HasNotes = strings.TrimSpace(p.Notes) != ""
p.HasExplanation = strings.TrimSpace(p.Explanation) != ""
p.Source = Source(p.URL)
return p, nil
}
+8
View File
@@ -70,6 +70,8 @@ func fixture(t *testing.T) string {
write("solved/moocast/tests/3.in", "e\n")
write("solved/moocast/notes.md", "union find\n")
write("solved/moocast/problem.md", "# Moocast\n")
write("solved/moocast/explain.md", "## Key observation\n")
commit(4, "Add a test")
return dir
}
@@ -87,6 +89,12 @@ func TestBuild(t *testing.T) {
if m.Status != Solved || m.IO != "moocast" || m.Source != "USACO" || !m.HasNotes {
t.Fatalf("moocast summary wrong: %+v", m.Summary)
}
if m.Statement != "# Moocast\n" || m.Explanation != "## Key observation\n" || !m.HasExplanation {
t.Fatalf("moocast statement/explanation = %q / %q", m.Statement, m.Explanation)
}
if w := idx.Problems["watermelon"]; w.HasExplanation || w.Statement != "" {
t.Fatal("watermelon has no problem.md or explain.md")
}
if len(m.Files) != 2 || m.Files[0].Name != "main.cpp" || m.Files[1].Lang != "python" {
t.Fatalf("moocast files = %+v, want main.cpp then sol.py", m.Files)
}
+194
View File
@@ -0,0 +1,194 @@
// Package statement fetches a problem's statement from its judge, as
// markdown, for problem.md. Only the judges this repo mostly uses are known:
// LeetCode (its public GraphQL API) and USACO (the problem page's HTML).
// Anything else is pasted by hand.
package statement
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
"golang.org/x/net/html"
)
// ErrUnsupported is a link to a judge this package cannot read.
var ErrUnsupported = errors.New("statements can't be fetched from this site; paste it instead")
// maxBody caps a judge's response. A statement page is tens of kilobytes.
const maxBody = 1 << 20
// Fetcher reads statements. The zero value talks to the real judges; tests
// point the bases at an httptest server.
type Fetcher struct {
Client *http.Client
LeetCodeAPI string // default https://leetcode.com/graphql
USACOBase string // default https://usaco.org
}
func (f *Fetcher) client() *http.Client {
if f.Client != nil {
return f.Client
}
return &http.Client{Timeout: 15 * time.Second}
}
// Fetch returns the statement behind a problem link as markdown, headed by
// the problem's title.
func (f *Fetcher) Fetch(ctx context.Context, link string) (string, error) {
u, err := url.Parse(strings.TrimSpace(link))
if err != nil || u.Host == "" {
return "", ErrUnsupported
}
switch strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") {
case "leetcode.com":
return f.leetcode(ctx, u)
case "usaco.org":
return f.usaco(ctx, u)
}
return "", ErrUnsupported
}
// leetcode asks the GraphQL API the problem page itself uses. Free problems
// answer without a login; a premium one comes back with null content.
func (f *Fetcher) leetcode(ctx context.Context, u *url.URL) (string, error) {
// /problems/<slug>/ and /problems/<slug>/description/ both name it.
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) < 2 || parts[0] != "problems" || parts[1] == "" {
return "", fmt.Errorf("not a LeetCode problem link")
}
body, _ := json.Marshal(map[string]any{
"query": "query($s:String!){question(titleSlug:$s){title content}}",
"variables": map[string]string{"s": parts[1]},
})
api := f.LeetCodeAPI
if api == "" {
api = "https://leetcode.com/graphql"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", "https://leetcode.com")
b, err := f.do(req)
if err != nil {
return "", err
}
var resp struct {
Data struct {
Question *struct {
Title string `json:"title"`
Content *string `json:"content"`
} `json:"question"`
} `json:"data"`
}
if err := json.Unmarshal(b, &resp); err != nil {
return "", fmt.Errorf("LeetCode answered with something other than JSON")
}
q := resp.Data.Question
if q == nil {
return "", fmt.Errorf("LeetCode has no problem %q", parts[1])
}
if q.Content == nil || strings.TrimSpace(*q.Content) == "" {
return "", fmt.Errorf("LeetCode returned no statement (a premium problem?)")
}
return toMarkdown(q.Title, *q.Content)
}
// usaco reads the problem page: the title is its second <h2> (the first is
// the contest) and the statement is div.problem-text.
func (f *Fetcher) usaco(ctx context.Context, u *url.URL) (string, error) {
base := f.USACOBase
if base == "" {
base = "https://usaco.org"
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(base, "/")+u.RequestURI(), nil)
if err != nil {
return "", err
}
b, err := f.do(req)
if err != nil {
return "", err
}
doc, err := html.Parse(bytes.NewReader(b))
if err != nil {
return "", err
}
var h2s []string
var text *html.Node
for n := range doc.Descendants() {
if n.Type != html.ElementNode {
continue
}
switch {
case n.Data == "h2":
h2s = append(h2s, strings.TrimSpace(textOf(n)))
case text == nil && n.Data == "div" && hasClass(n, "problem-text"):
text = n
}
}
if text == nil {
return "", fmt.Errorf("no statement on that USACO page")
}
title := ""
if len(h2s) > 0 {
title = h2s[len(h2s)-1]
}
var buf bytes.Buffer
if err := html.Render(&buf, text); err != nil {
return "", err
}
return toMarkdown(title, buf.String())
}
func (f *Fetcher) do(req *http.Request) ([]byte, error) {
resp, err := f.client().Do(req)
if err != nil {
return nil, fmt.Errorf("could not reach %s", req.URL.Host)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s answered %d", req.URL.Host, resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, maxBody))
}
func toMarkdown(title, body string) (string, error) {
md, err := htmltomarkdown.ConvertString(body)
if err != nil {
return "", err
}
md = strings.TrimSpace(md)
if title != "" {
md = "# " + title + "\n\n" + md
}
return md, nil
}
func hasClass(n *html.Node, class string) bool {
for _, a := range n.Attr {
if a.Key == "class" && strings.Contains(" "+a.Val+" ", " "+class+" ") {
return true
}
}
return false
}
func textOf(n *html.Node) string {
var sb strings.Builder
for d := range n.Descendants() {
if d.Type == html.TextNode {
sb.WriteString(d.Data)
}
}
return sb.String()
}
+81
View File
@@ -0,0 +1,81 @@
package statement
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
// judge serves the saved responses in testdata: LeetCode's GraphQL answer
// for path-with-minimum-effort and USACO's page for cpid=644.
func judge(t *testing.T) *Fetcher {
t.Helper()
lc, _ := os.ReadFile("testdata/leetcode.json")
us, _ := os.ReadFile("testdata/usaco.html")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/graphql":
b, _ := io.ReadAll(r.Body)
if !strings.Contains(string(b), `"s":"path-with-minimum-effort"`) {
w.Write([]byte(`{"data":{"question":null}}`))
return
}
w.Write(lc)
case r.URL.Query().Get("cpid") == "644":
w.Write(us)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return &Fetcher{LeetCodeAPI: srv.URL + "/graphql", USACOBase: srv.URL}
}
func TestLeetCode(t *testing.T) {
md, err := judge(t).Fetch(context.Background(), "https://leetcode.com/problems/path-with-minimum-effort/description/")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"# Path With Minimum Effort", "You are a hiker", "`heights`"} {
if !strings.Contains(md, want) {
t.Errorf("markdown is missing %q:\n%s", want, md)
}
}
if strings.Contains(md, "<p>") {
t.Errorf("HTML left in the markdown:\n%s", md)
}
}
func TestLeetCodeUnknownSlug(t *testing.T) {
if _, err := judge(t).Fetch(context.Background(), "https://leetcode.com/problems/no-such-thing/"); err == nil {
t.Fatal("want an error for a problem LeetCode does not have")
}
}
func TestUSACO(t *testing.T) {
md, err := judge(t).Fetch(context.Background(), "https://usaco.org/index.php?page=viewproblem2&cpid=644")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"# Problem 3. Closing the Farm", "FJ wants to temporarily close", "SAMPLE INPUT"} {
if !strings.Contains(md, want) {
t.Errorf("markdown is missing %q:\n%s", want, md)
}
}
if strings.Contains(md, "navbar") || strings.Contains(md, "Contest has ended") {
t.Errorf("page chrome leaked into the statement:\n%s", md)
}
}
func TestUnsupported(t *testing.T) {
for _, link := range []string{"https://cses.fi/problemset/task/1068", "not a url", ""} {
if _, err := judge(t).Fetch(context.Background(), link); !errors.Is(err, ErrUnsupported) {
t.Errorf("Fetch(%q) = %v, want ErrUnsupported", link, err)
}
}
}
+1
View File
@@ -0,0 +1 @@
{"data":{"question":{"title":"Path With Minimum Effort","content":"<p>You are a hiker preparing for an upcoming hike. You are given <code>heights</code>, a 2D array of size <code>rows x columns</code>, where <code>heights[row][col]</code> represents the height of cell <code>(row, col)</code>. You are situated in the top-left cell, <code>(0, 0)</code>, and you hope to travel to the bottom-right cell, <code>(rows-1, columns-1)</code> (i.e.,&nbsp;<strong>0-indexed</strong>). You can move <strong>up</strong>, <strong>down</strong>, <strong>left</strong>, or <strong>right</strong>, and you wish to find a route that requires the minimum <strong>effort</strong>.</p>\n\n<p>A route&#39;s <strong>effort</strong> is the <strong>maximum absolute difference</strong><strong> </strong>in heights between two consecutive cells of the route.</p>\n\n<p>Return <em>the minimum <strong>effort</strong> required to travel from the top-left cell to the bottom-right cell.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex1.png\" style=\"width: 300px; height: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> heights = [[1,2,2],[3,8,2],[5,3,5]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex2.png\" style=\"width: 300px; height: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> heights = [[1,2,3],[3,8,4],[5,3,5]]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex3.png\" style=\"width: 300px; height: 300px;\" />\n<pre>\n<strong>Input:</strong> heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> This route does not require any effort.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>rows == heights.length</code></li>\n\t<li><code>columns == heights[i].length</code></li>\n\t<li><code>1 &lt;= rows, columns &lt;= 100</code></li>\n\t<li><code>1 &lt;= heights[i][j] &lt;= 10<sup>6</sup></code></li>\n</ul>\n"}}}
+249
View File
@@ -0,0 +1,249 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>USACO</title>
<link rel="stylesheet" type="text/css" href="current/usaco.css?v=2.0">
<script src="current/js/jquery.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<META HTTP-EQUIV="EXPIRES" CONTENT="0">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
"HTML-CSS": {
scale: 85,
preferredFont: "STIX"
},
tex2jax: {
inlineMath: [['$','$'],['\\(','\\)']],
processEscapes: true,
skipTags: ['pre'],
processClass: "mathjax",
ignoreClass: "no-mathjax"
}
});
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</head>
<body class="no-mathjax">
<div align="center">
<div class="shadow1">
<div class="content">
<a href="index.php"><img src="current/images/usaco_logo.png" height="130px" border="0px" /></a>
<div class="navbar" align="left" border="10px">
<ul>
<li><a href="index.php">Overview</a></li>
<li><a href="index.php?page=details">Details / FAQ</a></li>
<li><a href="index.php?page=training">Training</a></li>
<li><a href="index.php?page=history">History</a></li>
<li><a href="index.php?page=resources">Resources</a></li>
</ul>
</div><br/>
<div style="position:relative; float:left; left:10px; top:-50px; width:550px;">
<div class="panel">
<h2> USACO 2016 US Open Contest, Silver </h2>
<h2> Problem 3. Closing the Farm </h2>
</div>
</div>
<div align="right" style="position:relative; float:right; right:30px; top:-40px; width:350px;">
<button style="margin-bottom:6px;" type="button" onClick="window.location='index.php?page=open16results';">Return to Problem List</button><br style="padding-top:6px"/>
Contest has ended.
</div>
<br style="clear:both" />
<div id="last-status" style="padding:10px; position:relative; float:left; left:30px; top:-45px; width:820px; border:1px solid black; background-color:#FFF; "
data-response-code="-1" data-sid="-1">
<img src="current/images/ajax.gif"/> <p style="display:inline;"> <b>Log in to allow submissions in analysis mode</b></p>
<div id="trial-information"></div>
<p style="text-align:left;" class="mono prewrap output-data"></p>
</div>
<br style="clear:both" />
<div align="right" style="position:relative; float:right; right:40px; top:-93px; width:350px; z-index:2; padding:0px;">
<form style="padding-top:60px;" action="">
<select name="lang" style="background-color:#eee;" id="choose-language">
<option value='en' selected='yes'>English (en)</option>
<option value='hy'>Armenian (hy)</option>
<option value='bg'>Bulgarian (bg)</option>
<option value='fr'>French (fr)</option>
<option value='ru'>Russian (ru)</option>
<option value='es'>Spanish (es)</option>
</select>
</form>
</div>
<div align="left" style="position:relative; float:left; left:30px; top:-100px; width:840px; z-index:1;">
<div align="left" class="problem-text" style='width:800px; padding-top:10px;'>
<span id="probtext-text" class="mathjax">Farmer John and his cows are planning to leave town for a long vacation, and so
FJ wants to temporarily close down his farm to save money in the meantime.
<p>The farm consists of $N$ barns connected with $M$ bidirectional paths between
some pairs of barns ($1 \leq N, M \leq 3000$). To shut the farm down, FJ plans
to close one barn at a time. When a barn closes, all paths adjacent to that
barn also close, and can no longer be used.
<p>FJ is interested in knowing at each point in time (initially, and after each
closing) whether his farm is "fully connected" -- meaning that it is possible to
travel from any open barn to any other open barn along an appropriate series of
paths. Since FJ's farm is initially in somewhat in a state of disrepair, it may
not even start out fully connected.
<p><div class='prob-in-spec'><h4>INPUT FORMAT (file closing.in):</h4>
The first line of input contains $N$ and $M$. The next $M$ lines each describe a
path in terms of the pair of barns it connects (barns are conveniently numbered
$1 \ldots N$). The final $N$ lines give a permutation of $1 \ldots N$
describing the order in which the barns will be closed.
</div>
<p><div class='prob-out-spec'><h4>OUTPUT FORMAT (file closing.out):</h4>
The output consists of $N$ lines, each containing "YES" or "NO". The first line
indicates whether the initial farm is fully connected, and line $i+1$ indicates
whether the farm is fully connected after the $i$th closing.
</div>
<p><h4>SAMPLE INPUT:</h4><pre class='in'>
4 3
1 2
2 3
3 4
3
4
1
2
</pre><h4>SAMPLE OUTPUT:</h4> <pre class='out'>
YES
NO
YES
YES
</pre>
<p>
<p>Problem credits: Yang Liu
</span>
</div>
Contest has ended. No further submissions allowed.
</div>
<div align="left" style="position:relative; float:left; left:30px; top:-70px; width:840px;">
</div>
<br style="clear:both" />
<script>
var retries = 100, timeout = 1000;
function postback()
{
var sid = $('#last-status').data('sid'); if (sid == -1) return;
$.post('current/tpcm/status-update.php', { sid: sid }, update_response, 'json');
}
function update_response(s)
{
// only try a limited number of times
if (--retries < 0) return;
// if there is xml data, update the DOM
if (s != null)
{
$('#last-status img').attr("src","current/images/medal_none.png");
if (parseInt(s.cd) <= -8 && s.sc == 'status-working') { $('#last-status img').attr("src","current/images/ajax.gif"); }
// change class and text of the response box
$('#last-status').removeClass().addClass(s.sc);
$('#last-status p').text(s.sr);
// change the response code of the data section
$('#last-status').data('response-code', parseInt(s.cd));
$('#last-status .output-data').hide();
if (s.output != null)
{
$('#last-status .output-data').show().text(s.output);
// if the status is in a "working" state, keep checking
if (parseInt($('#last-status').data('response-code')) <= -8)
{ setTimeout(postback, timeout); timeout *= 1.1; }
return;
}
if (s.jd != null && s.jd.length != 0)
$('#trial-information').html(s.jd);
}
// if the status is in a "working" state, keep checking
if (parseInt($('#last-status').data('response-code')) <= -8)
{ setTimeout(postback, timeout); timeout *= 1.1; }
}
$(document).ready(function(){
$('#last-status .output-data').hide();
$('#last-status img').attr("src","current/images/medal_none.png");
if ($('#last-status').length) postback();
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>').text(title).appendTo('body').fadeIn('fast');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip').css({ top: mousey, left: mousex })
});
});
$('#choose-language').change(function(e){
window.location = "index.php?page=viewproblem2&cpid=644&lang=" + $(this).val();
});
</script>
</div>
</div>
</div>
<br style="clear:both" />
<script>(function(){function c(){var b=a.contentDocument||(a.contentWindow&&a.contentWindow.document);if(b){var d=b.createElement('script');d.innerHTML="window.__CF$cv$params={r:'a4d22a230b2cc51c',t:'MTc5MjQzNzg4Mw=='};var a=document.createElement('script');a.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js';document.getElementsByTagName('head')[0].appendChild(a);";b.getElementsByTagName('head')[0].appendChild(d)}}if(document.body){var a=document.createElement('iframe');a.height=1;a.width=1;a.style.position='absolute';a.style.top=0;a.style.left=0;a.style.border='none';a.style.visibility='hidden';document.body.appendChild(a);if('loading'!==document.readyState)c();else if(window.addEventListener)document.addEventListener('DOMContentLoaded',c);else{var e=document.onreadystatechange||function(){};document.onreadystatechange=function(b){e(b);'loading'!==document.readyState&&(document.onreadystatechange=e,c())}}}})();</script></body>
</html>
+17
View File
@@ -8,6 +8,7 @@
"name": "usaco-site-web",
"version": "0.0.0",
"dependencies": {
"dompurify": "^3.4.17",
"highlight.js": "^11.11.1",
"markdown-it": "^14.1.0",
"vue": "^3.5.22",
@@ -1267,6 +1268,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@vitejs/plugin-vue": {
"version": "6.0.10",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.10.tgz",
@@ -1422,6 +1430,15 @@
"node": ">=8"
}
},
"node_modules/dompurify": {
"version": "3.4.17",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz",
"integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/enhanced-resolve": {
"version": "5.26.0",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz",
+1
View File
@@ -12,6 +12,7 @@
"preview": "vite preview"
},
"dependencies": {
"dompurify": "^3.4.17",
"highlight.js": "^11.11.1",
"markdown-it": "^14.1.0",
"vue": "^3.5.22",
+4
View File
@@ -35,3 +35,7 @@ export const getProblem = (name) => request("GET", `/problems/${encodeURICompone
export const updateMeta = (name, meta) => request("PUT", `/problems/${encodeURIComponent(name)}/meta`, meta);
export const setStatus = (name, to) => request("POST", `/problems/${encodeURIComponent(name)}/status`, { to });
export const getMe = () => request("GET", "/me");
export const fetchStatement = (name, url) =>
request("GET", `/problems/${encodeURIComponent(name)}/statement/fetch?url=${encodeURIComponent(url || "")}`);
export const startExplain = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/explain`, body);
export const explainStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/explain`);
+96
View File
@@ -0,0 +1,96 @@
<script setup>
/**
* explain.md, laid out as the ladder it was written to be: every "## "
* section folded away so the reader opens only as much as they need (the
* observation, then one hint at a time, ...). The line above the first
* section (who wrote it, when) stays visible.
*
* Markdown is rendered with html: false like the notes. The one exception
* is ```svg fences, the walkthrough's diagrams: 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.
*/
import { computed } from "vue";
import MarkdownIt from "markdown-it";
import DOMPurify from "dompurify";
const props = defineProps({ source: { type: String, required: true } });
const md = new MarkdownIt({ html: false, linkify: true });
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 clean = DOMPurify.sanitize(t.content, { USE_PROFILES: { svg: true, svgFilters: true } });
return `<figure class="diagram">${clean}</figure>`;
};
// Split on "## " headings outside code fences.
const parts = computed(() => {
const intro = [];
const sections = [];
let inFence = false;
for (const line of props.source.split("\n")) {
if (line.startsWith("```")) inFence = !inFence;
if (!inFence && line.startsWith("## ")) {
sections.push({ title: line.slice(3).trim(), lines: [] });
} else {
(sections.length ? sections[sections.length - 1].lines : intro).push(line);
}
}
return {
intro: md.render(intro.join("\n")),
sections: sections.map((s) => ({ title: s.title, html: md.render(s.lines.join("\n")) })),
};
});
</script>
<template>
<div class="explanation">
<div v-if="parts.intro.trim()" class="intro muted prose" v-html="parts.intro"></div>
<details v-for="(s, i) in parts.sections" :key="i + s.title" class="step card">
<summary>{{ s.title }}</summary>
<div class="body prose" v-html="s.html"></div>
</details>
</div>
</template>
<style scoped>
.explanation {
display: grid;
gap: 8px;
min-width: 0;
}
.intro {
font-size: 0.85rem;
}
.step summary {
padding: 8px 14px;
cursor: pointer;
font-weight: bold;
}
.step[open] summary {
border-bottom: 1px solid var(--color-line-soft);
}
.body {
padding: 12px 16px 16px;
min-width: 0;
overflow-wrap: anywhere;
}
.body :deep(.diagram) {
margin: 12px 0;
padding: 12px;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
background: var(--color-paper);
color: var(--color-ink);
}
.body :deep(.diagram svg) {
display: block;
width: 100%;
max-width: 640px;
height: auto;
margin: 0 auto;
}
</style>
+158 -8
View File
@@ -1,15 +1,18 @@
<script setup>
/**
* One problem: its solution files, sample input, saved tests, notes and git
* history. The admin also gets the status buttons and the link/notes editor;
* each edit is a commit the server pushes, and the response is the problem
* as it is afterwards, so the page just takes it.
* One problem: its solution files, sample input, saved tests, notes,
* explanation and git history. The admin also gets the status buttons, the
* link/statement/notes editor and the Explain panel; each edit is a commit
* the server pushes, and the response is the problem as it is afterwards, so
* the page just takes it. An explanation takes minutes, so starting one only
* queues it and the page polls until it is committed.
*/
import { computed, ref, watch } from "vue";
import { computed, onUnmounted, ref, watch } from "vue";
import { RouterLink } from "vue-router";
import MarkdownIt from "markdown-it";
import CodeBlock from "@/components/CodeBlock.vue";
import { getMe, getProblem, setStatus, updateMeta } from "@/api";
import Explanation from "@/components/Explanation.vue";
import { explainStatus, fetchStatement, getMe, getProblem, setStatus, startExplain, updateMeta } from "@/api";
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
const props = defineProps({ name: { type: String, required: true } });
@@ -31,6 +34,7 @@ async function load() {
const [p, me] = await Promise.all([getProblem(props.name), getMe().catch(() => ({ admin: false }))]);
problem.value = p;
admin.value = me.admin;
if (me.admin) checkExplain();
} catch (e) {
problem.value = null;
error.value = e.status === 404 ? "No such problem." : e.message;
@@ -41,6 +45,7 @@ async function load() {
watch(() => props.name, load, { immediate: true });
const notesHtml = computed(() => (problem.value?.notes ? md.render(problem.value.notes) : ""));
const statementHtml = computed(() => (problem.value?.statement ? md.render(problem.value.statement) : ""));
const file = computed(() => problem.value?.files[activeFile.value]);
// ---- admin edits ----
@@ -49,10 +54,13 @@ const editError = ref("");
const editing = ref(false);
const draftUrl = ref("");
const draftNotes = ref("");
const draftStatement = ref("");
const fetching = ref(false);
function startEdit() {
draftUrl.value = problem.value.url || "";
draftNotes.value = problem.value.notes || "";
draftStatement.value = problem.value.statement || "";
editError.value = "";
editing.value = true;
}
@@ -72,11 +80,67 @@ async function run(action) {
}
async function saveMeta() {
if (await run(() => updateMeta(props.name, { url: draftUrl.value, notes: draftNotes.value }))) {
const meta = { url: draftUrl.value, notes: draftNotes.value, statement: draftStatement.value };
if (await run(() => updateMeta(props.name, meta))) {
editing.value = false;
}
}
// Fills the statement box for review; nothing is saved until Save.
async function fillStatement() {
fetching.value = true;
editError.value = "";
try {
draftStatement.value = (await fetchStatement(props.name, draftUrl.value)).statement;
} catch (e) {
editError.value = e.message;
} finally {
fetching.value = false;
}
}
// ---- explanations ----
const stuckNote = ref("");
const includeCode = ref(true);
const job = ref({ state: "idle" });
let poll = null;
function stopPolling() {
clearTimeout(poll);
poll = null;
}
onUnmounted(stopPolling);
watch(() => props.name, stopPolling);
async function checkExplain() {
stopPolling();
const name = props.name;
try {
const s = await explainStatus(name);
if (name !== props.name) return;
const finished = job.value.state === "running" && s.state === "done";
job.value = s;
if (s.state === "running") {
poll = setTimeout(checkExplain, 3000);
} else if (finished) {
problem.value = await getProblem(name);
}
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
async function explain() {
try {
job.value = await startExplain(props.name, { note: stuckNote.value, includeCode: includeCode.value });
poll = setTimeout(checkExplain, 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
const canExplain = computed(() => !!(problem.value?.statement || problem.value?.url));
const moves = computed(() => {
const s = problem.value?.status;
return [
@@ -115,7 +179,7 @@ const moves = computed(() => {
<button v-for="m in moves" :key="m.to" class="btn" :disabled="saving" @click="run(() => setStatus(problem.name, m.to))">
{{ m.label }}
</button>
<button v-if="!editing" class="btn" :disabled="saving" @click="startEdit">Edit link and notes</button>
<button v-if="!editing" class="btn" :disabled="saving" @click="startEdit">Edit link, statement and notes</button>
<span v-if="saving" class="muted">Saving to git…</span>
</div>
<form v-if="editing" class="editor" @submit.prevent="saveMeta">
@@ -123,6 +187,15 @@ const moves = computed(() => {
Problem link
<input v-model="draftUrl" type="url" placeholder="https://usaco.org/index.php?page=viewproblem2&cpid=…" />
</label>
<label>
<span class="label-row">
Problem statement (markdown, shown only to you and Claude)
<button class="btn small" type="button" :disabled="fetching || !draftUrl" @click="fillStatement">
{{ fetching ? "Fetching…" : "Fetch from link" }}
</button>
</span>
<textarea v-model="draftStatement" rows="8" placeholder="Paste the statement, or fetch it from a LeetCode or USACO link"></textarea>
</label>
<label>
Notes (markdown)
<textarea v-model="draftNotes" rows="8" placeholder="Approach, complexity, what tripped you up…"></textarea>
@@ -135,8 +208,36 @@ const moves = computed(() => {
<p v-if="editError" class="error">{{ editError }}</p>
</section>
<section v-if="admin" class="stuck card">
<h2>Stuck?</h2>
<p class="muted">
Claude writes an intuitive explanation with diagrams, laid out as hints you open one at a time. It takes a
minute or two and is committed as <code>explain.md</code>.
</p>
<textarea v-model="stuckNote" rows="3" placeholder="Optional: what you've tried and where you're stuck"></textarea>
<div class="admin-row">
<label class="check"><input v-model="includeCode" type="checkbox" /> Include my current code</label>
<button class="btn primary" :disabled="job.state === 'running' || !canExplain" @click="explain">
{{ problem.explanation ? "Explain again" : "Explain" }}
</button>
<span v-if="job.state === 'running'" class="muted">Claude is writing it…</span>
<span v-else-if="!canExplain" class="muted">Add a link or the statement first.</span>
</div>
<p v-if="job.state === 'error'" class="error">{{ job.error }}</p>
</section>
<section v-if="notesHtml" class="notes card prose" v-html="notesHtml"></section>
<section v-if="problem.explanation">
<h2>Explanation</h2>
<Explanation :source="problem.explanation" />
</section>
<details v-if="admin && statementHtml" class="statement card">
<summary>Problem statement</summary>
<div class="prose" v-html="statementHtml"></div>
</details>
<section>
<h2>Solution</h2>
<p v-if="!problem.files.length" class="muted">No solution file yet.</p>
@@ -267,6 +368,55 @@ h2 {
.notes {
padding: 16px 20px;
}
.label-row {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.btn.small {
padding: 2px 10px;
font-size: 0.8rem;
}
.stuck {
padding: 12px 16px 16px;
display: grid;
gap: 10px;
}
.stuck h2 {
margin: 0;
}
.stuck p {
margin: 0;
font-size: 0.9rem;
}
.stuck code {
font-family: var(--font-mono);
font-size: 0.85em;
}
.stuck textarea {
padding: 8px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
font-size: 0.9rem;
color: var(--color-ink);
background: var(--color-paper);
}
.check {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.9rem;
}
.statement summary {
padding: 8px 14px;
cursor: pointer;
}
.statement .prose {
padding: 4px 20px 16px;
overflow-wrap: anywhere;
}
.file-tabs {
display: flex;
flex-wrap: wrap;