- internal/jobs replaces explain.Jobs: one registry for every kind of background job, with records in DATA_DIR/jobs. A job's draft is written before its commit, so a failed commit can be saved again (POST /jobs/<kind>/<key>/save) and a restart mid-commit resumes it, without paying Claude twice. - Graceful shutdown: SIGTERM stops new jobs and waits SHUTDOWN_GRACE for running ones while still serving the pages that poll them. - internal/usage records every Claude call's tokens and estimated cost in DATA_DIR/usage.jsonl; CLAUDE_MONTHLY_BUDGET refuses new jobs (429) once a month reaches it. The stats page shows the admin the spend. - auth.SameOrigin refuses cross-origin writes to admin routes. - The LeetCode importer runs the clone's script without the server's secrets in its environment. - A sync that leaves HEAD where it was skips the re-index. - docs_test.go checks README's route table against the routes, and the CLI page against the root README's commands. - The repo is going private: Gitea links on the site are admin-only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
337 lines
15 KiB
Go
337 lines
15 KiB
Go
// Package review turns a recording of the admin explaining their solution,
|
||
// already transcribed, into reviews/<id>.md: interview-style feedback on the
|
||
// approach (is it right, are the complexities right, what was missed) and on
|
||
// the delivery (structure, clarity, pace, fillers), written by Claude.
|
||
//
|
||
// Claude only reads the transcript. Pace, silences and fillers come from the
|
||
// transcriber's timestamps (transcribe.Metrics) and are given to it as
|
||
// numbers, and it is told it cannot hear tone, so it does not guess at it.
|
||
//
|
||
// Like explain.md, the reply is a fixed JSON shape stored as markdown, so it
|
||
// reads fine on Gitea and can be edited by hand.
|
||
package review
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"math"
|
||
"sort"
|
||
"strings"
|
||
"time"
|
||
|
||
"adam-french.co.uk/usaco-site/internal/claude"
|
||
"adam-french.co.uk/usaco-site/internal/explain"
|
||
"adam-french.co.uk/usaco-site/internal/index"
|
||
"adam-french.co.uk/usaco-site/internal/transcribe"
|
||
)
|
||
|
||
// Input is what Claude is told.
|
||
type Input struct {
|
||
Name string
|
||
Statement string
|
||
Examples []explain.Example
|
||
Code *index.File // their solution, when they chose to send it
|
||
Note string // context from the admin: "mock interview, 20 minutes"
|
||
Transcript *transcribe.Transcript
|
||
Metrics transcribe.Metrics
|
||
}
|
||
|
||
// Score is one area of the rubric.
|
||
type Score struct {
|
||
Score int `json:"score"`
|
||
Reason string `json:"reason"`
|
||
}
|
||
|
||
// Scores are the rubric's areas, in the order they are shown.
|
||
type Scores struct {
|
||
Understanding Score `json:"understanding"`
|
||
Approach Score `json:"approach"`
|
||
Correctness Score `json:"correctness"`
|
||
Complexity Score `json:"complexity"`
|
||
Communication Score `json:"communication"`
|
||
}
|
||
|
||
// Result is the reply's shape; Schema is the same thing for the API.
|
||
type Result struct {
|
||
Verdict string `json:"verdict"`
|
||
Summary string `json:"summary"`
|
||
Approach string `json:"approach"`
|
||
Gaps []string `json:"gaps"`
|
||
Delivery string `json:"delivery"`
|
||
Scores Scores `json:"scores"`
|
||
Strengths []string `json:"strengths"`
|
||
Improvements []string `json:"improvements"`
|
||
}
|
||
|
||
// Verdicts, and how they read on the page.
|
||
var Verdicts = map[string]string{
|
||
"correct": "Correct",
|
||
"partially_correct": "Partly correct",
|
||
"incorrect": "Incorrect",
|
||
"incomplete": "Incomplete",
|
||
}
|
||
|
||
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}
|
||
}
|
||
|
||
func score(desc string) map[string]any {
|
||
return map[string]any{
|
||
"type": "object",
|
||
"description": desc,
|
||
"properties": map[string]any{
|
||
"score": map[string]any{"type": "integer", "enum": []int{1, 2, 3, 4, 5}},
|
||
"reason": str("One sentence: why this score, specific to what they said."),
|
||
},
|
||
"required": []string{"score", "reason"},
|
||
"additionalProperties": false,
|
||
}
|
||
}
|
||
|
||
// Schema constrains the reply to Result. Structured outputs need every
|
||
// object closed and every property required.
|
||
var Schema = map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{
|
||
"verdict": map[string]any{"type": "string", "enum": []string{"correct", "partially_correct", "incorrect", "incomplete"}, "description": "Whether the approach they described solves the problem within its constraints. incomplete: they never reached a full approach."},
|
||
"summary": str("Markdown, two or three sentences: the approach they described, restated plainly, so they can check it was understood."),
|
||
"approach": str("Markdown. An interviewer's assessment of the approach: whether it is correct and why, whether it fits the constraints, the time and memory complexity they stated against the real ones, and how well they justified it. If it is wrong, say where it breaks, with a small counterexample if there is one, and point toward the right idea without giving a full solution."),
|
||
"gaps": strs("Markdown. Edge cases, constraints or errors they missed or got wrong, one per item. Empty if there are none."),
|
||
"delivery": str("Markdown. How the explanation came across: its structure (restating the problem, brute force, optimisation, complexity, edge cases, checking an example), clarity and signposting, pace, pauses and filler words. Quote them with [mm:ss] timestamps and refer to the measured metrics."),
|
||
"scores": map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{
|
||
"understanding": score("Did they restate the problem and its constraints correctly, and ask or settle what was ambiguous?"),
|
||
"approach": score("How good is the algorithm, and how well did they arrive at it?"),
|
||
"correctness": score("Is it right, and did they justify it and check it on an example?"),
|
||
"complexity": score("Did they state time and memory complexity, and were they right?"),
|
||
"communication": score("Was it structured, clear and easy to follow aloud?"),
|
||
},
|
||
"required": []string{"understanding", "approach", "correctness", "complexity", "communication"},
|
||
"additionalProperties": false,
|
||
},
|
||
"strengths": strs("Markdown. What they did well, one per item, specific to this recording. Two to four."),
|
||
"improvements": strs("Markdown. The most useful things to do differently next time, each concrete enough to act on in the next recording, most important first. Two to five."),
|
||
},
|
||
"required": []string{"verdict", "summary", "approach", "gaps", "delivery", "scores", "strengths", "improvements"},
|
||
"additionalProperties": false,
|
||
}
|
||
|
||
// The reply is a page of prose; the rest is room for adaptive thinking.
|
||
const maxTokens = 24000
|
||
|
||
// System is the same on every call, so it is cached.
|
||
const System = `You are an experienced technical interviewer coaching someone for coding interviews and competitive programming. They solved a problem on their own, then recorded themselves explaining their solution out loud as they would to an interviewer. You get the problem, an automatic transcript of the recording with timestamps, delivery metrics measured from the audio, and sometimes their code. Give them the feedback a good interviewer would give after a mock interview.
|
||
|
||
Reading the transcript:
|
||
- It is machine transcription of speech. Technical terms, variable names, numbers and notation are often misheard ("oh of n" for O(n), "a ray" for array). Read charitably and judge what they evidently meant; never criticise spelling, punctuation or grammar.
|
||
- You cannot hear the recording. Judge delivery only from the words, the timestamps and the metrics given. Do not guess at tone of voice, confidence or energy.
|
||
- Timestamps are [mm:ss]. Cite them when you quote or point at a moment.
|
||
|
||
Judging the approach:
|
||
- Decide for yourself whether the approach they describe is correct and fast enough for the constraints in the statement. Do not trust their claims, and do not assume that because they solved it their explanation is right: a correct submission can be explained wrongly, and the explanation is what is being assessed.
|
||
- Check the complexities they state against the real ones. Notice if they never state them.
|
||
- Look for edge cases they did not address: empty or minimal input, duplicates, overflow, disconnected graphs, ties, off-by-ones at the boundaries.
|
||
- If code is included, compare what they said with what they wrote, and point out where the two differ.
|
||
- If the approach is wrong, say where it breaks and nudge toward the right idea. Never write out a full solution in a real programming language.
|
||
|
||
Judging delivery:
|
||
- A strong explanation restates the problem, mentions the obvious approach and why it is too slow, builds to the real one with the key insight made explicit, states time and memory complexity, covers edge cases, and checks the idea on an example. Say which of these were missing or came late.
|
||
- Comfortable spoken pace is roughly 120 to 160 words per minute. A few pauses to think are normal; long or frequent ones, and long runs of filler words, are worth naming. The filler counts are raw word counts, so "like" may include real uses: look at the transcript before calling it a habit.
|
||
|
||
Scores, each 1 to 5: 1 missing or wrong, 2 weak, 3 adequate, 4 good, 5 what a strong candidate would do. Most decent attempts land at 3 or 4; give 5 only when nothing meaningful could be better.
|
||
|
||
Be direct and specific. Praise only what earned it, and make every improvement something they could act on in the next recording. Write in plain, direct prose, using markdown for emphasis, lists and inline code, and LaTeX between $...$ for math such as complexities ($O(n \log n)$); the page typesets it with KaTeX.`
|
||
|
||
// Prompt is the user message.
|
||
func Prompt(in Input) string {
|
||
var b strings.Builder
|
||
fmt.Fprintf(&b, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
|
||
for i, ex := range in.Examples {
|
||
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
|
||
if ex.Out != "" {
|
||
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
|
||
}
|
||
b.WriteString("</example>\n")
|
||
}
|
||
if in.Code != nil {
|
||
fmt.Fprintf(&b, "\n<my_code file=%q>\n%s\n</my_code>\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n"))
|
||
}
|
||
if note := strings.TrimSpace(in.Note); note != "" {
|
||
fmt.Fprintf(&b, "\n<context>\n%s\n</context>\n", note)
|
||
}
|
||
b.WriteString("\n<delivery_metrics>\n" + metricsText(in.Metrics) + "</delivery_metrics>\n")
|
||
b.WriteString("\n<transcript>\n" + transcriptText(in.Transcript, "") + "</transcript>\n")
|
||
b.WriteString("\nReview my explanation of this problem.")
|
||
return b.String()
|
||
}
|
||
|
||
// Clock formats seconds as mm:ss, or h:mm:ss past an hour.
|
||
func Clock(sec float64) string {
|
||
s := int(math.Round(sec))
|
||
if s >= 3600 {
|
||
return fmt.Sprintf("%d:%02d:%02d", s/3600, s/60%60, s%60)
|
||
}
|
||
return fmt.Sprintf("%02d:%02d", s/60, s%60)
|
||
}
|
||
|
||
// At most this many pauses are listed; the longest are kept.
|
||
const maxPauses = 10
|
||
|
||
func metricsText(m transcribe.Metrics) string {
|
||
var b strings.Builder
|
||
fmt.Fprintf(&b, "- Length %s, %d words, %.0f words per minute\n", Clock(m.Duration), m.Words, m.WPM)
|
||
if len(m.Pauses) == 0 {
|
||
fmt.Fprintf(&b, "- No pauses of %.0fs or more\n", transcribe.PauseThreshold)
|
||
} else {
|
||
longest := m.Longest()
|
||
fmt.Fprintf(&b, "- %d pauses of %.0fs or more; longest %.1fs at [%s]\n", len(m.Pauses), transcribe.PauseThreshold, longest.Length, Clock(longest.At))
|
||
ps := m.Pauses
|
||
if len(ps) > maxPauses {
|
||
ps = longestPauses(ps, maxPauses)
|
||
}
|
||
var at []string
|
||
for _, p := range ps {
|
||
at = append(at, fmt.Sprintf("[%s] %.1fs", Clock(p.At), p.Length))
|
||
}
|
||
b.WriteString("- Pauses: " + strings.Join(at, ", ") + "\n")
|
||
}
|
||
if m.FillerCount == 0 {
|
||
b.WriteString("- No filler words\n")
|
||
} else {
|
||
var fs []string
|
||
for _, f := range m.Fillers {
|
||
fs = append(fs, fmt.Sprintf("%q × %d", f.Word, f.Count))
|
||
}
|
||
perMin := 0.0
|
||
if m.Duration > 0 {
|
||
perMin = float64(m.FillerCount) / (m.Duration / 60)
|
||
}
|
||
fmt.Fprintf(&b, "- Filler words: %d (%.1f per minute): %s\n", m.FillerCount, perMin, strings.Join(fs, ", "))
|
||
}
|
||
if m.ComplexityAt < 0 {
|
||
b.WriteString("- Complexity never mentioned by name\n")
|
||
} else {
|
||
fmt.Fprintf(&b, "- Complexity first mentioned at [%s]\n", Clock(m.ComplexityAt))
|
||
}
|
||
return b.String()
|
||
}
|
||
|
||
// longestPauses keeps the n longest, still in order.
|
||
func longestPauses(ps []transcribe.Pause, n int) []transcribe.Pause {
|
||
lengths := make([]float64, len(ps))
|
||
for i, p := range ps {
|
||
lengths[i] = p.Length
|
||
}
|
||
sort.Sort(sort.Reverse(sort.Float64Slice(lengths)))
|
||
// Ties at the cut keep the earlier ones.
|
||
cut := lengths[n-1]
|
||
var out []transcribe.Pause
|
||
for _, p := range ps {
|
||
if len(out) < n && p.Length >= cut {
|
||
out = append(out, p)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
// transcriptText is one line per segment, each line starting with prefix
|
||
// and its timestamp.
|
||
func transcriptText(t *transcribe.Transcript, sep string) string {
|
||
var b strings.Builder
|
||
if len(t.Segments) == 0 {
|
||
return strings.TrimSpace(t.Text) + "\n"
|
||
}
|
||
for _, s := range t.Segments {
|
||
if text := strings.TrimSpace(s.Text); text != "" {
|
||
fmt.Fprintf(&b, "[%s] %s\n%s", Clock(s.Start), text, sep)
|
||
}
|
||
}
|
||
return b.String()
|
||
}
|
||
|
||
// Meta is what the markdown records about how the review was made.
|
||
type Meta struct {
|
||
Now time.Time
|
||
Transcriber string
|
||
// Audio is the recording's key in the audio store, or "" if it was not
|
||
// kept.
|
||
Audio string
|
||
}
|
||
|
||
// Generate asks Claude and returns the review's markdown.
|
||
func Generate(ctx context.Context, a explain.Asker, in Input, meta Meta) (string, error) {
|
||
var r Result
|
||
err := a.JSON(ctx, claude.Request{Tag: "review", System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return Render(r, in, a.Model(), meta), nil
|
||
}
|
||
|
||
// Render lays a Result out as markdown. The first line is a comment that
|
||
// index reads (and strips) for the verdict and the recording; the page folds
|
||
// each "## " section away and keeps the line after it visible.
|
||
func Render(r Result, in Input, model string, meta Meta) string {
|
||
var b strings.Builder
|
||
head := "<!-- review verdict=" + r.Verdict
|
||
if meta.Audio != "" {
|
||
head += " audio=" + meta.Audio
|
||
}
|
||
b.WriteString(head + " -->\n")
|
||
fmt.Fprintf(&b, "_Reviewed by %s on %s: a %s recording, transcribed by %s._\n",
|
||
model, meta.Now.Format("2 January 2006 at 15:04"), Clock(in.Metrics.Duration), meta.Transcriber)
|
||
|
||
section := func(title, body string) {
|
||
if body = strings.TrimSpace(body); body != "" {
|
||
fmt.Fprintf(&b, "\n## %s\n\n%s\n", title, body)
|
||
}
|
||
}
|
||
verdict := Verdicts[r.Verdict]
|
||
if verdict == "" {
|
||
verdict = r.Verdict
|
||
}
|
||
section("Verdict", "**"+verdict+".** "+strings.TrimSpace(r.Summary))
|
||
|
||
var sc strings.Builder
|
||
sc.WriteString("| Area | Score | Why |\n| --- | --- | --- |\n")
|
||
for _, row := range []struct {
|
||
name string
|
||
s Score
|
||
}{
|
||
{"Understanding", r.Scores.Understanding},
|
||
{"Approach", r.Scores.Approach},
|
||
{"Correctness", r.Scores.Correctness},
|
||
{"Complexity", r.Scores.Complexity},
|
||
{"Communication", r.Scores.Communication},
|
||
} {
|
||
fmt.Fprintf(&sc, "| %s | %d/5 | %s |\n", row.name, row.s.Score, cell(row.s.Reason))
|
||
}
|
||
section("Scores", sc.String())
|
||
section("Approach", r.Approach)
|
||
section("Gaps", bullets(r.Gaps))
|
||
section("Delivery", r.Delivery)
|
||
section("Strengths", bullets(r.Strengths))
|
||
section("To work on", bullets(r.Improvements))
|
||
section("Metrics", metricsText(in.Metrics))
|
||
section("Transcript", transcriptText(in.Transcript, "\n"))
|
||
return b.String()
|
||
}
|
||
|
||
// cell keeps a table cell on one line and its pipes from splitting it.
|
||
func cell(s string) string {
|
||
return strings.ReplaceAll(strings.Join(strings.Fields(s), " "), "|", `\|`)
|
||
}
|
||
|
||
func bullets(items []string) string {
|
||
var b strings.Builder
|
||
for _, it := range items {
|
||
if it = strings.TrimSpace(it); it != "" {
|
||
b.WriteString("- " + strings.ReplaceAll(it, "\n", "\n ") + "\n")
|
||
}
|
||
}
|
||
return b.String()
|
||
}
|