package handlers import ( "context" "errors" "fmt" "log" "net/http" "os" "path/filepath" "sort" "strings" "time" "github.com/gin-gonic/gin" "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/concept" "adam-french.co.uk/usaco-site/internal/index" ) // listConcepts is the library, newest first. It leaves out the content and // snippets, which only a concept's own page needs. func (s *Server) listConcepts(ctx *gin.Context) { idx := s.Index() if idx == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"}) return } out := []index.Concept{} for _, c := range idx.Concepts { sum := *c sum.Content, sum.Snippet = "", nil out = append(out, sum) } sort.Slice(out, func(i, j int) bool { a, b := out[i].Updated, out[j].Updated if (a == nil) != (b == nil) { return a == nil // uncommitted ones are the newest } if a != nil && !a.Equal(*b) { return a.After(*b) } return out[i].Slug < out[j].Slug }) ctx.JSON(http.StatusOK, gin.H{"admin": s.isAdmin(ctx), "concepts": out}) } func (s *Server) lookupConcept(ctx *gin.Context) (*index.Concept, bool) { slug := ctx.Param("slug") idx := s.Index() if idx == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"}) return nil, false } c, ok := idx.Concepts[slug] if !validName.MatchString(slug) || !ok { ctx.JSON(http.StatusNotFound, gin.H{"error": "no such concept"}) return nil, false } return c, true } func (s *Server) getConcept(ctx *gin.Context) { if c, ok := s.lookupConcept(ctx); ok { ctx.JSON(http.StatusOK, c) } } type conceptBody struct { Topic string `json:"topic"` Code string `json:"code"` } const maxConceptCode = 32 << 10 // startConcept starts explaining a new concept. Its slug is Claude's to // choose, so the job is keyed by an id of its own, which the page polls // until the result names the slug to open. func (s *Server) startConcept(ctx *gin.Context) { if s.Claude == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) return } idx := s.Index() if idx == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"}) return } var body conceptBody if err := ctx.ShouldBindJSON(&body); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"}) return } switch { case strings.TrimSpace(body.Topic) == "" && strings.TrimSpace(body.Code) == "": ctx.JSON(http.StatusBadRequest, gin.H{"error": "say what to explain"}) return case len(body.Topic) > maxNote: ctx.JSON(http.StatusBadRequest, gin.H{"error": "the topic is too long"}) return case len(body.Code) > maxConceptCode: ctx.JSON(http.StatusBadRequest, gin.H{"error": "the code is too long"}) return } topic := strings.TrimSpace(body.Topic) if topic == "" { topic = "How does this code work?" } in := concept.Input{Topic: topic, Code: body.Code, Existing: conceptRefs(idx, "")} // Microseconds, so two requests in one second are two jobs. id := time.Now().UTC().Format("2006-01-02-150405.000000") if !s.newConceptJobs.StartWith(id, func() (any, error) { return s.writeConcept(in, "") }) { ctx.JSON(http.StatusConflict, gin.H{"error": "that concept is already being explained"}) return } ctx.JSON(http.StatusAccepted, gin.H{"id": id, "status": s.newConceptJobs.Get(id)}) } func (s *Server) newConceptStatus(ctx *gin.Context) { ctx.JSON(http.StatusOK, s.newConceptJobs.Get(ctx.Param("id"))) } type rewriteBody struct { Note string `json:"note"` } // rewriteConcept explains a saved concept again, from the question it was // asked with, the current version and what the admin wants changed. func (s *Server) rewriteConcept(ctx *gin.Context) { c, ok := s.lookupConcept(ctx) if !ok { return } if s.Claude == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) return } var body rewriteBody if err := ctx.ShouldBindJSON(&body); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"}) return } if len(body.Note) > maxNote { ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"}) return } topic, code := concept.ParseRequest(c.Request) if topic == "" { topic = c.Title } prev := "# " + c.Title + "\n\n" + c.Content if c.Snippet != nil { prev += "\n\n## Snippet\n\n```cpp\n" + c.Snippet.Content + "\n```" } in := concept.Input{Topic: topic, Code: code, Previous: prev, Note: body.Note, Existing: conceptRefs(s.Index(), c.Slug)} slug := c.Slug if !s.conceptJobs.StartWith(slug, func() (any, error) { return s.writeConcept(in, slug) }) { ctx.JSON(http.StatusConflict, gin.H{"error": "this concept is already being rewritten"}) return } ctx.JSON(http.StatusAccepted, s.conceptJobs.Get(slug)) } func (s *Server) rewriteStatus(ctx *gin.Context) { if c, ok := s.lookupConcept(ctx); ok { ctx.JSON(http.StatusOK, s.conceptJobs.Get(c.Slug)) } } // conceptRefs are the saved concepts but skip, for Claude to name a new one // apart from. func conceptRefs(idx *index.Index, skip string) []concept.Ref { var refs []concept.Ref for _, c := range idx.Concepts { if c.Slug != skip { refs = append(refs, concept.Ref{Slug: c.Slug, Title: c.Title}) } } sort.Slice(refs, func(i, j int) bool { return refs[i].Slug < refs[j].Slug }) return refs } // conceptResult is a finished job's answer: where the concept is now. type conceptResult struct { Slug string `json:"slug"` } // writeConcept is one job: a new concept when slug is empty, else a rewrite // of that one. Its error is shown to the admin, so every path returns a // message meant for them and logs the detail. func (s *Server) writeConcept(in concept.Input, slug string) (any, error) { ctx, cancel := context.WithTimeout(context.Background(), explainTimeout) defer cancel() r, err := concept.Generate(ctx, s.Claude, in) if err != nil { var f *claude.Failure if errors.As(err, &f) { log.Printf("[concept] %s: %s: %v", in.Topic, f.Msg, f.Err) return nil, f } log.Printf("[concept] %s: %v", in.Topic, err) return nil, errors.New("the explanation could not be written") } rewrite := slug != "" if !rewrite { slug = freeSlug(s.Index(), r.Slug) } files := concept.Files(r, in, slug, s.Claude.Model(), time.Now()) err = s.Repo.Mutate(ctx, "Explain concept "+slug, func(dir string) error { cdir := filepath.Join(dir, index.Concepts, slug) _, err := os.Stat(cdir) switch { case rewrite && os.IsNotExist(err): return &requestError{http.StatusNotFound, "the concept was deleted while Claude was writing"} case !rewrite && err == nil: // Saved since the slug was picked; the next try picks another. return &requestError{http.StatusConflict, fmt.Sprintf("a concept named %s was saved meanwhile; try again", slug)} } if err := os.MkdirAll(cdir, 0o755); err != nil { return err } for name, content := range files { if err := writeOrRemove(filepath.Join(cdir, name), content); err != nil { return err } } return nil }) if err := jobSaveError("concept", slug, "the explanation was written but could not be saved to git", err); err != nil { return nil, err } return conceptResult{Slug: slug}, nil } // freeSlug is want, or want-2, want-3... if a concept already has it. A // new question never overwrites a saved concept; rewriting one is its own // request. func freeSlug(idx *index.Index, want string) string { slug := want for n := 2; ; n++ { if _, taken := idx.Concepts[slug]; !taken { return slug } slug = fmt.Sprintf("%s-%d", want, n) } } func (s *Server) deleteConcept(ctx *gin.Context) { c, ok := s.lookupConcept(ctx) if !ok { return } slug := c.Slug cctx, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second) defer cancel() msg := "Forget concept " + slug err := s.Repo.Mutate(cctx, msg, func(dir string) error { // Already gone on a newer tip is what was asked for. return os.RemoveAll(filepath.Join(dir, index.Concepts, slug)) }) if err != nil { editFailed(ctx, msg, err) return } ctx.JSON(http.StatusOK, gin.H{}) }