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
+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)
}
}
+40 -7
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]
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.
@@ -194,8 +217,9 @@ func findOnDisk(dir, name string) (status string, err error) {
}
type metaBody struct {
URL *string `json:"url"`
Notes *string `json:"notes"`
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
})
}
+33 -19
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 (
@@ -61,27 +63,32 @@ type Commit struct {
// Summary is what the list shows.
type Summary struct {
Name string `json:"name"`
Status string `json:"status"`
URL string `json:"url,omitempty"`
Source string `json:"source,omitempty"`
Langs []string `json:"langs"`
Tests int `json:"tests"`
HasNotes bool `json:"hasNotes"`
FirstSeen *time.Time `json:"firstSeen,omitempty"`
SolvedAt *time.Time `json:"solvedAt,omitempty"`
LastTouched *time.Time `json:"lastTouched,omitempty"`
Name string `json:"name"`
Status string `json:"status"`
URL string `json:"url,omitempty"`
Source string `json:"source,omitempty"`
Langs []string `json:"langs"`
Tests int `json:"tests"`
HasNotes bool `json:"hasNotes"`
HasExplanation bool `json:"hasExplanation"`
FirstSeen *time.Time `json:"firstSeen,omitempty"`
SolvedAt *time.Time `json:"solvedAt,omitempty"`
LastTouched *time.Time `json:"lastTouched,omitempty"`
}
// Problem is everything known about one problem.
type Problem struct {
Summary
IO string `json:"io,omitempty"`
Notes string `json:"notes"`
Files []File `json:"files"`
Sample *File `json:"sample,omitempty"`
TestSet []Test `json:"testCases"`
History []Commit `json:"history"`
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"`
History []Commit `json:"history"`
}
// Index is one snapshot of the clone.
@@ -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>