This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
GitDiagram turns a GitHub repository into an interactive Mermaid architecture diagram. It is one Next.js 16 App Router application (React 19, TypeScript, Tailwind 4, Bun runtime). There is no separate backend — the generation API lives in Next.js Route Handlers under src/app/api/. Vercel is the only live deployment; the Dockerfile and railway.json are a dormant Railway disaster-recovery recipe, not a live standby.
Bun is the package manager and runtime (bun install; bun ci for frozen lockfile).
bun run dev # dev server (Turbopack) at localhost:3000
bun run test # all tests (vitest run)
bun run test src/server/generate/graph.test.ts # single test file
bun run test:watch # vitest watch mode
bun run lint # eslint (fails on any warning)
bun run typecheck # TypeScript 7 tsc --noEmit
bun run check # lint + typecheck
bun run format:check # prettier (ts/js/mdx/css/json/yaml)
bun run knip # unused files/exports/dependencies
bun run build # production build
bun run check:video-tracing # after build: video routes trace ffmpeg/Chromium only where needed
bun run perf:budget # after build: bundle budgetsFull gate (what CI runs): bun run lint && bun run typecheck && bun run format:check && bun run knip && bun audit && bun run test && bun run build && bun run check:video-tracing && bun run perf:budget. bun install turns on .githooks/pre-push (format, lint, typecheck, knip). workers/presence has its own CI job (typecheck, tests, audit). experiments/ (historical scripts) is excluded from typecheck and lint.
Vitest runs two projects (see vitest.config.ts): server (node env: src/server/**, src/app/api/**) and client (jsdom env with testing-library: everything else). Tests are colocated *.test.ts(x) files. Path alias ~ → src/.
/api/generate/stream (src/app/api/generate/stream/route.ts, runtime = "nodejs", maxDuration = 300) streams SSE through this pipeline, mostly in src/server/generate/:
- Ingestion (
github.ts) — fetch default branch, recursive tree, README via GitHub API. A partial (truncated) tree is kept, and top-level folders it left out are read one level deep (≤8 requests); only an oversized README (>750 KB) is rejected.MAX_GENERATION_INPUT_TOKENS(900k) only stops requests the model would reject. - Source context and explanation (
repository-context.ts,source-context.ts,source-excerpt.ts) — select at most 12 source blobs from the verified tree, fetch with a 12-second enrichment deadline, and bound excerpts to 48k characters. The server-funded OpenAI Luna configuration uses Terra for analysis when there are more than eight eligible implementation files; small repos, BYOK and custom model/provider configurations keep their configured model. Streams an evidence-grounded architecture explanation. - Graph stage (
graph-planner.ts,openai.ts) — model returns a strict, size-bounded graph AST (groups/nodes/edges/labels/paths), validated bygraph.ts(identifiers, edge endpoints, limits, every linked path checked against the real repo tree). Structural failures are retried with focused feedback up toMAX_GRAPH_ATTEMPTS; a graph whose only fault is unresolvable node paths is repaired in place instead (stripUnknownNodePaths), since a path only drives a node's GitHub link. - Compilation (
compileDiagramGraphingraph.ts) — deterministic AST→Mermaid compiler with total text escaping and GitHub-only links.mermaid.tsis only a re-export of the JSDOM-backed parser inmermaid-validator.ts; that parser is intentionally test-only (mermaid.test.tscontract tests) to keep the server bundle small — do not import it into production code. - Client rendering (
src/components/mermaid-diagram.tsx,src/features/diagram/mermaid-security.ts) — sanitize source, render Mermaid withsecurityLevel: "antiscript"andhtmlLabels: false, sanitize the resulting SVG with DOMPurify, then re-enforce the GitHub-only link allowlist. (strictis not usable here: it disables theclickdirectives the diagram depends on, so the allowlist enforcement is what carries that weight.)
Other routes: /api/generate/cost (pre-run estimate), /api/generate/cancel (distributed cancellation via Redis), /api/diagram-state (persisted result contract), /api/healthz.
generation-policy.ts centralizes model/token/effort constants; model-config.ts selects the provider (AI_PROVIDER = openai | openrouter — both via the OpenAI SDK); pricing.ts + complimentary-gate.ts handle cost accounting and the free-tier daily token gate.
VIDEO_EXPLAINER_ENABLED=1 + NEXT_PUBLIC_VIDEO_EXPLAINER=1 turn on a Video toggle in the repo toolbar (the diagram stays the default view) and the shareable watch page /[username]/[repo]/video (poster as its link preview; never starts a diagram run). Code lives in src/{server,features,components}/explainer/.
-
Generation (
/api/video/generate,generate.ts): reads the repo with the diagram pipeline's own GitHub/source-selection modules, then one model works in two roles sharing one cached prompt prefix (director.ts,shot-prompt.ts).planner.ts(premiumPlanner/standardPlanner) picks the models once the star count is known: every video is written by Claude Opus 5.5 (the better storyteller, seeexperiments/video-models/) and designed by GPT-6 Sol at medium effort (OpenAI Responses API, same tools and prompt), blind-judged level with Opus alone and faster than Sol alone (experiments/video-bespoke/). Premium films (the operator's, repos with 10k+ stars (VIDEO_PREMIUM_MIN_STARS) and a priority visitor's first video of the day) are made the same way unlessVIDEO_PREMIUM_OPUS_DESIGNS=1, which has Opus design them too. If Opus fails for any reason but a refusal (out of credit, overloaded), Sol takes over: it writes the script, and on Opus-designed films designs too (VIDEO_PLANNER_MODELpicks the premium director,VIDEO_STANDARD_DIRECTOR_MODELthe standard one); a run makes at most 3 director calls. While Opus directs a standard film, Sol's shared prefix is prewarmed; OpenAI calls use explicit prompt caching with one breakpoint after the repository block, andstore: false. The model's name shows while the video is made, under the player and in the repo toolbar's Info panel (video-info.tsx). The director writes the narration first as one continuous story (a single thread followed from a hook to a closing line), then cuts it into a 12–16 beat script that leads with practical use (what the project is for and what people do with it, about half the words → briefly how the main parts fit → one decision under the hood;experiments/video-practical/); one designer per scene runs in parallel and turns briefs into a free-form JSON shot language; a failed scene is retried once on the other model, and a film with more than a third of its beats undesigned fails instead of being stored. Both are non-strict tool calls (the schemas are too large for strict structured output), defined inshot-tools.ts;script.tschecks the script andshots.tsvalidates shots against the real tree (≤12 elements and ≤16 actions per beat).SHOT_KINDS/SHOT_ACTIONS(plusSHOT_TONES,SHOT_ICONS,SHOT_TRANSITIONS,SVG_SHAPES,SVG_PAINT) insrc/features/explainer/types.tsare the one source for the shot format (types, tool schema, normalizer, and tests that the engine and prompt cover each). Up to three README pictures (readme-images.ts: from the README's first 100k characters, https only, every connection and redirect hop through a DNS lookup that refuses non-public addresses, badges and sponsors skipped, still PNG/JPEG/WebP only with the type read from the bytes and a structure check that drops truncated or corrupt files, at most 3 MB and 4000 px, 8 s for the whole step) are shown to both roles as images, and dropped for the rest of the run if a model API refuses them; a film may put one on screen as animageelement, and only the pictures a film shows are stored in its version folder and served by/api/video/file?format=picture. Repository text reaches the prompt fenced as untrusted<repository_material>, andwithoutStrangeAddresses(text.ts) cuts narration and on-screen text naming web addresses the repo never mentions. OpenRouter's text-to-speech (OPENROUTER_API_KEY; modelgoogle/gemini-3.8-flash-tts, voice Charon, chosen by ear in a blind bake-off,experiments/voices/) narrates the whole script as one continuous take while designers work (voice.ts); one style directs the take. whisper-1 word timestamps (never prompted: with the script as a prompt it hallucinated) are matched back onto the script (voice-alignment.ts), and those timings split the take into beats (narration.ts, timed to the take's real length); a take heard too poorly is recorded again once, and if that one is unclear too its words are spread over it by length (video.voice.untimed) rather than failing the run. The estimated voice and whisper cost is stored asstats.voiceCostUsdand included in the "Made … for $X" line. Per-scene takes sounded stitched together. There is no fallback voice: when the OpenRouter balance runs out (402), new videos pause for ten minutes (Redisvideo:v1:voice:paused-until) so no run pays for a script it cannot voice;/adminshows the balance. The director writes for the ear, pacing it with punctuation (commas, ellipses, short questions);text.tsdrops any bracketed direction the model writes anyway, so the voice, captions and cues all read the same line. After the video is stored, its poster is made on the segment route (remakePosterRemotely) within the function's remaining time (skipped under 20 s). A run has a 240 s deadline threaded through every model and voice call; when one parallel part fails, the others are aborted and settled before the lock is released. -
Priority places and audience (
audience.ts,features/admin/priority-places.ts): two definitions of the priority places, picked live in/admin: "cities" (California, Washington, New York, Ontario, British Columbia, or within 60 km of London or Paris; Paris also matches all of Île-de-France) or "countries" (all of the US, Canada and the UK, plus the Paris area), from Vercel IP geolocation headers. People there get more videos a day (their first is a premium film). The audience switch decides who may start videos at all: the priority places (any device), those plus any desktop, or everyone; everyone can watch. On top of the audience, the limited countries (features/admin/limited-countries.ts: India, Vietnam, Brazil, the Philippines, Pakistan, Indonesia, and all of Africa except Egypt, South Africa, Libya, Morocco and Algeria) are set live in/adminto blocked, "some" (the default: a daily draw per connection, not per browser, letslimitedCountryShare% in, default 10, for one video a day on the standard models even for 10k+ star repos) or open. It is an access rule, not a security boundary (VPNs pass).VIDEO_PREVIEW_PAUSED=audience|device|limitpreviews the paused UI in development. The operator can also pause new videos and override the daily limits live from/admin(see below). -
Budget (
limits.ts): public generations are capped per UTC day overall, per person (one browser, a random-id cookie fromvisitor.ts, set byGET /api/videoand required on POST; default 1, orVIDEO_PRIORITY_PERSON_DAILY_LIMIT, default 3, in a priority place, of whichVIDEO_PREMIUM_PERSON_DAILY_LIMIT, default 1, use Opus; premium is also capped per connection,VIDEO_PREMIUM_NETWORK_DAILY_LIMIT, default twice that) and per connection as a looser backstop (default 10, so a shared office still works) in Redis (fails closed). Each connection may also startVIDEO_NETWORK_ATTEMPT_LIMIT(default 10) runs perVIDEO_NETWORK_ATTEMPT_WINDOW_SECONDS(default 3600), taken before the GitHub read and never refunded. At mostVIDEO_MAX_PAID_RUNS(default 10) paid runs at once (the slot is taken at the first model call,onPaidWork, not at admission); runs pause while the voice balance is out and are locked per repo across instances (existence is re-checked under the lock; the 409s carryreasongeneratingorexists). A failed run is refunded only if it failed before the first model call or because the narrator ran out of credit; other paid failures are not retryable for the public.GET /api/videoreads the same counters to show the paused state up front. Admin resets bump a counter epoch instead of deleting keys. Only the operator (VIDEO_ADMIN_TOKENas Bearer, or a signed-in/adminbrowser) may regenerate an existing video; locally every caller is trusted. -
Storage (
store.ts):.video-cache/locally, R2video/v1/<owner>/<repo>/in production. The artifact points at a version folder (itscreatedAt) holding narration clips, MP4s (named with the engine version),poster.jpg(the title card) andstill.jpg(a scene frame for the/videosgallery,catalog.ts), so every file URL is immutable (poster/still URLs also carry apstamp, so a remade poster gets a fresh URL). A regeneration keeps the published version it replaced (read fromartifact.json; open tabs keep playing) and deletes all others. The gallery and sitemap read a Redis index (video:v1:index,video-index.ts) that is backfilled from R2 on first read (claim keyvideo:v1:index:building; marked ready only after a complete backfill) and falls back to listing R2 if Redis is down./videosships its first page and pages throughGET /api/video/catalog. A video run outlives its panel (src/features/explainer/runs.ts); whileGET /api/videoreportsgenerating, the panel polls, and a refused or dropped run falls back to that waiting path. Watch pages without a video arenoindex. -
Playback: the engine directs the camera: each beat frames what is on screen (inside the area the label and captions leave free), so a scene opens close and widens as it builds;
focuspushes in from there andresetreturns to it.explainer-player.tsxruns the shot engine (public/video-engine/:kit.jshelpers,sound.js,camera.js,shots.js, andstage.jsfor captions, the vertical layout and posters; the stage waits up to 5 s for pictures to decode before reporting ready) in a same-origin iframe with its own strict CSP, mixes narration and soft untuned foley (no music) with Web Audio, and seeks the scene timeline to the audio clock (minus output latency) every frame. Speed changes are time-stretched in a Web Worker (time-stretch.worker.ts; the 2× press-and-hold stretch is prepared on the first hold); pausing suspends the AudioContext, and arrow keys seek ±5 s. BumpENGINE_VERSIONinsrc/features/explainer/engine.tsand every?v=instage.htmlandengine.csstogether with any change underpublic/video-engine(a test enforces they match; sound-effect URLs use?v=ENGINE_VERSION);stage-engine.test.tsruns the real engine in JSDOM on a production plan. -
MP4s (
/api/video/render,segments.ts; Chromium half inrender.ts, ffmpeg-only code inffmpeg.ts): headless Chromium (@sparticuz/chromiumon Vercel,VIDEO_RENDER_CHROME_PATHlocally) seeks the same stage frame by frame into ffmpeg (ffmpeg-static, a trusted dependency). Films render as ~5 s segments through/api/video/render/segment(jobs HMAC-signed with a key derived fromCACHE_KEY_SECRET;supportsCancellationinvercel.json), at mostVIDEO_SEGMENT_FAN_OUT(default 10) requests in flight andVIDEO_SEGMENT_CONCURRENCY(default 2) Chromiums per instance; busy instances answer 503 and the orchestrator retries (also 408/429). Segments get 700 s with 240 s per attempt, and one 780 s deadline covers the whole render including the ffmpeg mix and join; the first final failure aborts the rest. Segments then join with the loudness-normalized soundtrack; captions are burned in. Every self-call is pinned to the running deployment (x-deployment-id/?dpl=, for Skew Protection); off Vercel the server calls itself onhttp://127.0.0.1:$PORT(VIDEO_INTERNAL_ORIGINoverrides,render-origin.ts). A render is refunded only if it failed before the first segment request, or if the video was replaced mid-render (it answers the reload message). Poster remakes also run through the segment route, so/api/video/renderand/api/video/generatetrace no Chromium (check:video-tracingenforces this with size ceilings). The client sends thev(createdAt) it is showing and gets a 409staleif the video changed./api/video/fileserves posters and redirects MP4 downloads to signed R2 URLs; a poster request withoutvserves the current video's poster (the share row's README picture embeds it, cache-tagged so a new video purges it). The Bun dev server cannot load these externals; runnext devunder Node to test renders locally. -
Analytics (
src/features/explainer/watch-analytics.ts): the player reportsvideo_startedandvideo_progress(percent25/50/75/100 of the film actually played; seeks never count) and the share rowvideo_shared(method:mp4_landscape,mp4_vertical,native,link,badge,picture), each withvideo_repo,video_created_at,video_modelandvideo_duration, so films, models and prompt versions compare in PostHog. -
Reels (
/reels,src/components/explainer/reels/,src/features/explainer/reels.ts): every stored video in a swipe feed, one phone screen each (the most-starred page, shuffled, then more pages as you scroll;?v=owner/repoopens on one and the address follows the reel on screen). The engine'sreellayout (stage.js) makes a canvas 1080 wide and as tall as the screen is in proportion, keeps the scene clear of the insets the page reports for its own buttons and text, and shows captions a few words at a time.reflow.jsre-lays each wide scene for it before the build: parts drawn over each other stay together, the rest is cut into columns and rows, every way of turning those cuts is tried, and the arrangement the camera can show biggest wins (arrows that would cross other parts count against it; a beat that clears the screen starts a fresh layout).camera.jsreads the frame fromShotKit.frame, so the wide film is unchanged. The first tap unlocks one sharedAudioContext(reelOutput) that every reel'sExplainerAudioplays into; the reel on screen plays and loops, the ones either side are built and waiting behind a title card. The feed turns off pinch zoom (touch-action: pan-y): zooming multiplies the stage's WebKit graphics memory.
Only the owner gets in: sign in with VIDEO_ADMIN_TOKEN (wrong tokens, typed or sent as a Bearer to the video API, share one per-network limit counted in a Lua script, sign-in-guard.ts); the browser keeps a signed, HttpOnly session cookie (src/server/admin/operator.ts), which also makes that browser a video admin (no limits). Cookies are signed over a session generation in Redis (admin:v1:session-generation); "Sign out everywhere" bumps it, and every admin check verifies against it (while Redis is unreadable a correctly signed, unexpired cookie still works; rotating the token is the hard stop). Parts:
- Live presence (
workers/presence, a Cloudflare Worker + one Durable Object, deployed separately withbunx wrangler deployfrom that folder): every tab holds one WebSocket (src/components/live-presence.tsx, only whenNEXT_PUBLIC_PRESENCE_URLis set), so "on the site now" is exact and changes the instant a tab opens or closes. The worker runs on Cloudflare's free plan (100k requests/day, and every connect costs two, every tab message and alarm one), so a tab connects only after 15 s in view in all, says it went out of view only after a minute (HIDDEN_REPORT_MS; the worker backdates it, so "people here" is unchanged), and the dashboard lets its socket go after a minute out of view. While no dashboard is open, the site parks feed events in Redis (admin:v1:feed:parked) instead of sending them; the worker takes them from/api/admin/presence-feed(BearerPRESENCE_SECRET;SITE_ORIGINinwrangler.jsonc) when a dashboard connects and at every sweep, which also marks the feed watched forFEED_WATCH_MSso events go straight to it meanwhile. Hibernating sockets and runtime-answered pings keep idle connections free. The dashboard's own socket (a 5-minute HMAC token fromPRESENCE_SECRET, sent as the WebSocket subprotocol and renewed over the socket; "Sign out everywhere" closes every dashboard) gets join/leave/page changes batched every 250 ms. Counts and peaks use only sockets whose pings are still answered; a sweep closes dead visitor sockets (every minute while a dashboard is open, else every 15). The worker rate-limits connects per network (IPv6 per /64, aratelimitsbinding; dead sockets are closed before a per-network 429), closes tabs sending more than 30 changing messages or 120 frames a minute, binary frames (1003) and oversize ones (1009). Tabs send only the referrer's origin. The "clock/IP mismatch" flag is a hint, not VPN detection.PRESENCE_PROTOCOL(presence-protocol.ts) is sent in every snapshot and the dashboard warns when it differs; bump it with any protocol change and deploy the worker before the site. - Live feed and running jobs: routes call
emitLiveEvent(src/server/admin/live-events.ts, best effort, never blocks) for diagram/video/MP4 start and finish, visitors held back by the video gate, sign-ins and switch changes. Repository names are only sent once ingestion confirms the repo is public; held-back notices are sent once per connection and repo every 10 minutes. (The Pages panel can still show a private repo's path from presence.) - Live switches (
src/server/admin/controls.ts): Redis hashadmin:v1:controls, read with a 1 s per-instance cache, so a flip reaches every instance within a second. Starting a video fails closed when the controls cannot be read; display paths show the last controls read, and the dashboard warns when they could not be read. - Counters (
/api/admin/state, polled every 5 s and re-read on relevant events at most once per 2 s): video/MP4 budgets, the voice balance (cached 30 s), Claude credit (cached 60 s), complimentary diagram tokens. Each outside balance has a 3 s deadline and shows as unreadable past it.
src/server/— server-only code (importsserver-only): generation pipeline, GitHub auth (github-auth.tssupports single PAT, PAT pool, or GitHub App), storage, HTTP guards, OG image generation.src/server/http/—same-origin.ts/same-origin-json.ts/request-credentials.ts: mutating API routes require same-origin requests; user GitHub tokens travel per-request and are never persisted server-side.client-ip.tsresolves the caller for abuse control only — it trusts forwarding headers and is never an authentication signal.- Abuse control — generations billed to the server's own key pass through a per-IP fixed-window limiter (
generate/rate-limit.ts,GENERATION_RATE_LIMIT_MAX/GENERATION_RATE_LIMIT_WINDOW_SECONDS, default 8 per hour) before the daily complimentary quota; callers supplying their own API key skip it. Every caller of/api/generate/costand/stream, BYOK included, also passes a looser infrastructure limiter bounding GitHub and session work (GENERATION_INFRASTRUCTURE_RATE_LIMIT_MAX/_WINDOW_SECONDS, default 60 per hour). Both fail open on Redis errors because the daily quota still bounds total spend. src/server/storage/— R2 (r2.ts,artifact-store.ts) for diagram artifacts, with a separate private namespace derived fromCACHE_KEY_SECRETfor private repos (cache-key.ts); Upstash Redis (upstash.ts) for quota (quota-store.ts), cancellation, short-lived failure state (status-store.ts), anddistributed-lock.ts(newest-session-wins persistence ingeneration-persistence.ts).src/features/— client/shared domain logic per feature (diagram SSE parsing, export, github-url parsing, credentials, browse catalog). The graph AST schema/types insrc/features/diagram/graph.tsare shared between server validation and client.src/hooks/useDiagram.ts+src/hooks/diagram/— orchestrate the client generation lifecycle (cost check → stream → render → persist).src/app/[username]/[repo]/— the diagram page (ISRrevalidate6 h plus on-demand invalidation, but the root layout's star-count fetch revalidates every 5 min, which caps the effective lifetime; a page rendered after a failed stored-state read is cached 60 s) (andvideo/, the watch page); also/browse,/videos,/advertise(/sponsorredirects there),/admin, and/out/[campaign](sponsor click-through).
Copy .env.example → .env. Minimum to run generation locally: R2 vars, CACHE_KEY_SECRET, Upstash vars, and one AI provider key. .env.example lists every setting with its default; docs/dev-setup.md groups them.
- Prettier with
prettier-plugin-tailwindcss(bun run format:write); ESLint 10 flat config (eslint.config.mjs). - Server code must not leak into client bundles — keep it under
src/server/behindserver-only. - Diagram output safety is defense-in-depth (server validation → deterministic compiler → client sanitization); changes to any layer should keep the others intact and are covered by
mermaid-security.test.tsand the compiler contract tests.
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in node_modules/next/dist/docs/ (resolved from this file's directory; in monorepos the next package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by next dev — verify at node_modules/next/dist/server/lib/generate-agent-files.js. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.