This site uses one functional cookie to keep feature rollouts consistent for you. Nothing is set until you choose. See the privacy notice.
Dev notes
I sat down to audit this codebase for structure, not bugs: where the same idea lives in six places, where a boundary leaks, what I would redesign. Thirteen bugs fell out anyway. What made me write this up is that nearly all of them had the same shape. Something failed, and the code reported a plausible result instead. A 500 became “not connected”. A rejected write became a success. A prop became nothing. None of them crashed, which is exactly why none of them had been noticed.
I used the first half of an untangle-the-codebase method: list every problem, then redesign from first principles, and stop there. No code changed during the audit. That rule mattered more than I expected. The moment you are allowed to fix things, you stop reading the next file and start fixing the first one, and the list ends up as long as your patience rather than as long as the problems.
The evidence was an import graph I could query for upward and cross-feature imports, grep sweeps for repeated idioms, read-throughs of each area, and git log co-change counts to find files that always move together. Anything I had only read and not run got marked reasoned, so the bugs I was confident about and the ones I was guessing at didn’t look the same on the page.
The bugs went in their own table, separate from the redesign. The method says not to hunt bugs, and I didn’t, but these turned up while tracing how things connect. Keeping them apart meant I could fix them one by one without the redesign riding along.
Most of the thirteen live inside one feature, and those write-ups carry them now (the list is further down). Five belonged to the site as a whole.
The root layout set a canonical URL. Next merges metadata shallowly, so any page that didn’t set alternates itself inherited it, and the shared helper every write-up uses didn’t set one:
export const metadata: Metadata = {
metadataBase: new URL(SITE_URL),
alternates: { canonical: "/" },Each write-up was declaring itself a duplicate of /. Nothing looks wrong in a browser, which is the whole problem. The root canonical is gone, buildArticleMetadata emits the page’s own path, and an integration check renders real pages instead of only inspecting the root metadata object.
encodeURIComponent does not stop ..Nine API routes put the id from the URL into the backend URL like this:
`${API_URL}/api/zeroproof/leagues/${encodeURIComponent(id)}/join`It reads as safe. But Next decodes %2e%2e to .. before the handler runs, encodeURIComponent("..") is still .., and fetch resolves it. So /api/zeroproof/leagues/%2e%2e/join went out as /api/zeroproof/join with the caller’s token attached. Every other route already used safeSegment; these nine were older. They use it now, and a test fails if any route goes back to encodeURIComponent for a path id.
Button with an href only forwarded its own styling props:
const shared = { ref, variant, size, loading, disabled, className } as const;
if (href) {
return (
<PaulButton {...shared} href={href}>
{children}
</PaulButton>
);
}An aria-label, a target or an onClick on a link button type-checked and then vanished. Chip had the same habit in its link form, and Input with hideLabel rendered a <label htmlFor> pointing at an id the input never got. The fix that holds is in the types: Button is a union of a button and a link, everything is passed through, and the link form of Chip refuses the handlers it can’t honour at compile time instead of accepting and dropping them.
Each feature has a theme-aware token and one hex in the feature data for places that can’t switch on theme. The hex is supposed to be derived from the token. When I swapped the palette, some of them weren’t:
vitals #2d8f66 -> #7b68ce green in the data, purple in the token learn #718d2d -> #218c62 nba #be5d68 -> #937322 calendar #9f7d27 -> #218c6a zeroproof #6451ba -> #7b6bc4 2.89:1 on the dark surface mind-reader #7c4fa3 -> #9065b5 2.95:1 on the dark surface
The hub card painted its dot from the data and its tint from the token, so the drift was visible as two colours on one card, and I still hadn’t seen it. The dot reads the token now, and a test checks every feature’s hue against its token and its contrast against both themes, so the next palette swap fails a build instead of waiting for me to notice.
The route template picked its wrapper from a preference the server can’t see:
if (reduced) return <>{children}</>;
return (
<m.div initial={isFirstLoad ? false : { opacity: 0 }} ...>The flag only turns on after hydration. Swapping the element above the page at that moment makes React throw the page away and mount it again, so for visitors who asked for less motion every effect ran twice and every first-load fetch went out twice. I had marked this one reasoned in the audit. The test I wrote first counted two mounts, which turned it from a guess into a bug. The wrapper now stays put and reduced motion just skips the fade.
A bug in the calendar belongs on the calendar’s page, where someone reading about the calendar will find it. Each of these is a dated update there:
Every fix started as a test that failed against the code as it was, committed and pushed on its own before the fix. For bugs whose whole character was looking fine, that first red run was the point: it is the only evidence that the bug was real and not something I talked myself into while reading.
They went out as stacked pull requests, one bug each, in audit order, each with its own patch version. Thirteen small diffs were easy to review. One diff touching thirteen features wouldn’t have been, and a revert of one fix would have taken the other twelve with it.
Two of the fixes turned up worse bugs underneath. Making the calendar say when a card failed to save showed that on a new event every card had always failed, because the cards went to an id the modal made up. And the operator’s resume fix showed that the saved counts were also being dropped on the floor. Reading found the first bug in each case. Only writing the test found the second.
Update — November 19, 2026
A day after the stack went up I reviewed the fixes as if someone else had written them, one bug shape at a time, and checked whether each shape still lived anywhere else. It did, in seven places, and they went out as seven more stacked PRs, each failing first like the originals.
The flags console showed the built-in demo flags whenever the flags API didn’t answer, with nothing to say so. The BFF knew which one it had, and the route threw that away:
const { flags, environments } = await loadFleet();
return NextResponse.json({ flags, environments });My notes said to throw instead of falling back. That would have been wrong: the server-side gate for the Pocket page reads through the same loadFleet, and it is supposed to keep working when the API is asleep. So the fallback stays, the route passes source along, and the console says when it’s showing demo data. The operator reads had the opposite problem. A real restock session isn’t in the seed, so a 500 came back as “not found” and the resume hook forgot the session. Now only the API saying 404 means gone.
The Pokémon set page caught every SDK error and called notFound(), so a tcgdex outage told everyone a real set didn’t exist, and a day’s revalidate could keep it that way. The test guarding the 404 was this:
it("still 404s a set that genuinely is not there", async () => {
setGet.mockRejectedValue(new Error("upstream 404"));The SDK resolves null for an unknown id and only throws when tcgdex fails, so that test mocked an outage and called it a missing set. It passed because the bug was there. It mocks null now, and a second test says an outage is an error, not a 404.
Eleven components ran their own query on the shared me key. The hub on /discover seeded it from the server:
type MeData = { name: string | null; email: string | null };
// ...
const meQuery = useQuery({
queryKey: queryKeys.me(),
// ...
initialData: initialMe,
staleTime: 5 * 60_000,
});No sub in it, and every gated page checks sub. Open one from the hub and the cache said signed out for five minutes. There’s one useMe hook now, a failed check throws instead of caching “signed out”, and the hubs keep their server value to themselves. With one hook it was easy to find the panels that asked for my walls, my leagues and my picks on every signed-out visit, for answers that could only be 401.
// Before September → the season that started last fall return now.getMonth() >= 9 ? now.getFullYear() + 1 : now.getFullYear(); const CURRENT_YEAR = new Date().getFullYear();
The first is the playoffs routes (and getMonth() is zero-based, so 9 is October, not September). The second is the fantasy pages, which spent every October to December opening on last season. Both use currentNbaSeason() now.
} else {
console.warn(
`[E2E] Could not create test calendar: ${res.status()} ${await res.text()}`,
);
}If setup couldn’t make the test calendar, the calendar specs found no id and skipped themselves. I had fixed the guards inside those tests already. This one sat a level up, in setup, so it survived. It throws now.
The rest were smaller: the root layout still set openGraph.url (the canonical bug again, in a different field), a count-up that froze on its first number and swapped elements for reduced motion (the remount bug again, in a smaller place), and a Textarea wrapper that drew a label pointing at an id nothing had.
Update — November 20, 2026
The audit covered portfolio_api too. Its bugs went out as eight stacked PRs on the API, each starting from a failing test like the ones here. Most of them shared a shape with this side: something failed, and the code was written so that nobody would hear about it.
const service = new CalendarService();
if (this.google && calendar.syncMode === 'two_way') {When the calendar module moved to TypeScript, the controller built its service without the Google helpers, so this.google was always null. Connecting a calendar to Google returned a 500, and every event push was skipped by a guard that read like “this calendar isn’t two-way”. The helpers are a required constructor argument now, so the service can’t be built without them and the guard only means what it says.
describe.skipIf(!DATABASE_URL)('vitals version SQL against a real database', () => {
test:
steps:
- run: pnpm install --frozen-lockfile
- run: pnpm run testThe SQL smoke tests skip without a database, and the test job never had one, so every CI run reported them as skipped and the check stayed green. They had only ever run on a laptop that happened to have a DATABASE_URL. The job gets its own throwaway Postgres now, and tests that write rows also need a separate flag, because a laptop’s DATABASE_URL often points at production.
* The available-balance floor is checked here, against the live
* derived balance, so two concurrent bets can't both spend the same cents.
*/
export async function placeBet(input: PlaceBetInput): Promise<PlaceBetResult> {
return db.transaction(async (tx) => {
const entries = await tx.select(...).from(zeroproofLedgerEntries)A transaction at read committed doesn’t serialise two requests reading the same ledger. Both see the same balance, both pass the check, both insert. The wallet row is locked with FOR UPDATE first now. Settling and refunding had the matching problem the other way round: neither checked that the bet was still open, so a retried or overlapping settle run paid out twice. Both only update open bets now. What I haven’t done yet is look at the production ledger for a payout that already landed twice, and until I do I can’t say the bug never cost anyone anything.
export function buildState(userId: string, origin: string): string {
const payload = Buffer.from(JSON.stringify({ userId, origin })).toString('base64url');The OAuth state named the user and never expired, and the callback stored the Google tokens under whoever the state named. So I could start a connect, send someone the link, and their Google calendar would land on my account. The state expires now, and the callback sends the person back to this site to confirm the connection as themselves before anything is saved, which is the confirm step in #704. That one had to deploy before the API side or connecting would have stopped working altogether.
const userId = (req as any).auth.sub as string;
The JWT middleware puts claims on req.auth.payload, so the medical journal’s userId had always been undefined, and the any made sure the compiler couldn’t say so. Every controller read the caller through the same cast, 73 times. They go through one typed helper now, and a wrong claim path is a type error.
The rest were smaller: malformed JSON, a non-uuid id and a duplicate key all answered 500 instead of 4xx; two anonymous write endpoints had no rate limit; clearing the F1 cache only needed an account; and the calendar’s own database connection skipped certificate checks that the shared one does.
The day the stack merged, creating a calendar on production said it had failed when it hadn’t. The write answered without a role, the browser’s schema rejected that, and the toast showed the raw validation error. Fixing that (portfolio_api#288 and #715 here), I found the card update next to it:
UPDATE event_cards ec SET quantity = $1, notes = $2 ... Error: Expected 5 bindings, saw 0
Knex binds ?, not $1, so every edit to a card on a calendar event had been a 500. Neither bug was the kind the database job catches. Nothing checked the API’s write responses against the schema the browser validates them with, and the calendar repository tests mock knex, which will take SQL that knex itself refuses. The database job only runs tests that ask for a database, and these didn’t. The card fix (portfolio_api#289) compiles the statement with the real knex in its test, which is enough to catch this without a database.
Update — November 22, 2026
The redesign half of the audit went out as seven stacked PRs, #724 to #730, each about one domain. Most of them were the same complaint from the bug list, one level further up: the code knew what had gone wrong and threw that away before anyone saw it.
if (!res.ok) throw new Error("Failed to create event");The calendar client had ten of these, the calendar hooks another nine, and the budget, practice, gallery and ZeroProof clients each had their own version. The API answers a failed write with { error: "..." }, so the reason was sitting in the body and every toast showed the fixed string instead. There is one responseError now that reads the server’s reason and keeps the status, plus a requestJson for the clients that were each wrapping fetch the same way. A test scans the browser code for anyone parsing an error body by hand again.
I nearly took the status off the pack bar’s message while moving it over. Its test wanted reason (503), and it was right: a 503 and a 409 send the same words and need different things from me when someone reports them.
for (const rule of RATE_LIMITS) {
if (!rule.match(pathname, request.method)) continue;The rules had their own tests, run against matchRateLimit. The proxy ran its own copy of that loop, so those tests could pass while the proxy matched something else. The proxy calls matchRateLimit now, and the new test floods proxy() itself. ZeroProof telemetry also had a second limiter inside its route, counting batches the proxy had already counted. It’s a rule in the table now.
this.reset = ()=>{ this.setState({ error: null }); },
this.retry = ()=>{ startTransition(()=>{ this.context?.refresh(); this.reset(); }); };That’s Next 16.3’s error boundary. All thirty of my route boundaries passed reset to the shared error screen, which re-renders the payload that just failed. Most of my pages fail because an upstream API was down, which is exactly what the screen’s copy says, and the button couldn’t do anything about it short of a reload. They pass retry now. There was also no root boundary, so a write-up that crashed got the framework’s bare screen. It has one, plus a global-error.tsx for the root layout.
The test that failed first, with the backend mocked to answer a save with 204:
[practice PUT] backend unavailable: TypeError: Response constructor: Invalid response status code 204
Budget and practice each had a hand-copied catch-all proxy. The budget copy had learned that a 204 can’t carry a body. The practice copy hadn’t, so the first 204 would have come back as a 502. It also dropped the query string. Neither had happened yet: the practice API always answers with JSON and the page never sends a query. And neither copy capped the body it forwarded. Two copies is normally where I wait for a third before sharing anything, but these had already disagreed, and the next change would have landed in one and not the other. They share signedInCatchAll now. Budget keeps the same 64 KB cap as the other write routes, and practice takes up to 100 KB like the backend does, because importing every problem reviewed in both modes comes to about 69 KB.
disallow: ["/api/", "/dev/", "/settings", "/calendar", "/auth/"], allowlist: process.env.FLAG_ADMIN_ALLOWED_EMAILS,
robots.txt kept its own list of private pages, which had fallen behind the proxy’s list. It reads the proxy’s list now. The admin check was spelled out in ten places, and is one isSiteAdmin now. And a dead-code pass took out a streaming hook, a stats helper and some props that no caller used.
Update — November 22, 2026
The second stack ran from #732 to #746, still one domain per PR. The small ones went quickly. The NFL pages default to the kickoff season, and one ESPN league form serves both pages that had a copy. Reduced motion reads from one hook now, every palette command is either a link or an action, and a copy button says so when the clipboard refuses. The ones worth writing down are where I found the code had been quietly lying, and one where I was the one who was wrong.
// AUTO-GENERATED by scripts/count-tests.mjs — do not edit by hand. // Regenerated on every build via the `prebuild` script. export const UNIT_TEST_COUNT = 3432; export const E2E_TEST_COUNT = 67; export const TEST_COUNT = 3499;
The repo has over 6,400. The counter was wired up as a prebuild script, and pnpm doesn’t run pre and post hooks unless you turn them on, so pnpm build went straight to next build and every deploy shipped whatever number was last committed. The stats strip’s own doc comment promised it couldn’t go stale, and I believed it, because the script was right there and the hook name looked right. The counter runs inside build now, and a test fails if it ever moves back into a hook.
expect(layoutBetween(dir, enclosingBoundary(dir))).toBe(true); // 28 failed. lab/particles and zeroproof passed.
The first stack switched all thirty route boundaries from reset to retry and added a root one. That was the moment the thirty stopped mattering. A boundary renders inside every layout above it, so a nested copy only changes what anyone sees when a layout sits between it and the next boundary out. Twenty-eight of them had none and were byte-identical to the root. They were left over from a test that required one per feature, written back when there was no root to fall through to. I spent a PR making them consistent before asking whether they needed to exist. The guard now asks that question instead.
export class OperatorWriteTimeoutError extends Error {
constructor(readonly path: string) {
super(`operator write ${path} got no answer in ${UPSTREAM_TIMEOUT_MS} ms`);
this.name = "OperatorWriteTimeoutError";
}
}The operator writes had no deadline, and when one failed the BFF fell back to the seed. For a read that’s fine. A write that got no answer may well have applied upstream, so replaying it against the seed reported a success that wasn’t one. Writes time out on their own error now, and the route tells the dashboard to reload rather than try again. The same PRs keep the server’s reason on a refused write, and report it once. Each tab had its own error toast on top of the app-wide one, so a single failure showed up twice.
const list: Team[] = json.data?.data ?? json.data ?? [];
The API wraps teams one level deeper than a roster, and both pages covered that with a chain of fallbacks. Any other shape, including an error body, became an empty team picker with nothing to say what went wrong. One pair of queries parses exactly what the API sends, and anything else is an error the page can show.
res.headers.set("Content-Security-Policy", CSP); // x7
if (isSessionTimeout(false, marker)) { // always falseNothing was missing yet. But an eighth exit would have needed someone to remember, and nothing would have noticed if they forgot. Every pass-through goes through withCsp or rollSession now, and a test pins what every exit carries before the refactor touched anything. The parameter that was always false is gone.
expect(
!needsEntry || shipped.has(version),
`${version} is a minor/major release but has no UPDATE_ENTRIES entry — add one to entries.data.ts`,
).toBe(true); // true on every patchThe feed guard only checked anything on an X.Y.0 version, so for every patch in between it was a pass. It checks the release the current line started from now. The keyboard guard counted how many demos used the shared hook instead of asking whether each stepped demo did. I made sure both can fail by breaking the code they watch, which is the step I skipped the first time around.
Partway through, I also took the landing’s project shelf out of the sideways scroll and gave each project its own row. That story is on the v5 redesign write-up, where the shelf was first written up.
Update — November 22, 2026
The third stack picked up what the first two left: ZeroProof write bodies checked before they leave the site (#756), the rest of the proxy cleanup (#757), registries that had drifted from what they describe (#758), and four small sharing passes, covering the external link check, the theme key and a few timers, the 3D models’ motion hook, and the ESPN readers (#759 to #762). I re-read each audit item against the current code before starting it, and some of them turned out smaller than the audit said, or wrong.
if (!res.ok) {
return NextResponse.json({ picks: null }, { status: 404 });
}
// ...
} catch {
return NextResponse.json({ picks: null }, { status: 404 });
}
// and on the page, for any error at all:
This bracket isn’t publicly available yet.The public picks route turned any non-ok answer from the backend, and any body it couldn’t parse, into a 404. A timeout already came back as a 502 through the shared helper, but the view showed one fixed sentence for any error, so an outage read as someone keeping their bracket to themselves either way. Only a real 404 means missing now. Anything else is a 502 with Couldn’t load these picks right now, and the view shows whatever reason it was given. It’s the same bug as the empty-state ones from the first pass, just on a page I hadn’t looked at.
FAIL src/app/api/authedProxyRoutes.test.ts > POST /api/zeroproof/wallets > sends an empty object, not a crash, when the body isn't JSON FAIL src/app/api/routePathSegments.test.ts > 'POST zeroproof/leagues/:id/espn-leagu…' rejects `..` with a 400 FAIL src/app/design-system/catalog.test.ts > never claims 'not adopted here' for a component the app already imports AssertionError: expected [ 'timeline' ] to deeply equal []
While building each PR I ran the tests for the folders it touched. That felt thorough and wasn’t. The body checks in #756 made two older tests wrong: one still expected a non-JSON body to reach the API as {}, and the other sent a body the new schema rejected before the path check it was meant to test ever ran. The experience timeline in #755 used the design system’s Timeline, and the catalog still said nothing on the site imported it. None of those tests sit near the code that broke them, which is the whole point of having them. I fixed each on the branch that broke it and carried the fix up the stack, and meant to give every PR a full run before writing its body from then on. I didn’t manage it: #759, #761 and #762 still went up quoting folder runs of 2,985, 178 and 100 tests. The full suite does run on the top of the stack, so a break would still show up there, just later and further from the PR that caused it.
× 'deployment' lists every update it has, and only those × 'tcg' lists every update it has, and only those × 'vitals' lists every update it has, and only those × 'work-portfolio' lists every update it has, and only those
The audit named one: the TCG timeline listed one of its four updates. A fix for that page alone would have left the other three, so the test reads every write-up with a timeline and compares it to the update anchors in that folder, both ways. Vitals was missing three of six. The work portfolio was also out of order.
The card showed three entries from version 5. The obvious fix is to read the newest entries from the feed, but the feed is a 75 KB file and the card lives in a client module that most of the hub imports, so the whole changelog would ship with it. The three rows stay written by hand, and a test fails when a new entry lands and the card falls behind. Budget had the same kind of gap: its colour token existed and nothing mapped the card to it.
It flagged three hand-written Request failed errors in ZeroProof. All three feed an error box with fixed copy, so the message never reaches the screen, and changing them would change nothing. The leaderboard and vitals catches looked redundant around a fetch that never throws, but they still catch a non-JSON body. The two ESPN roster schemas looked like copies, but one requires a field the other treats as optional. Merging them would quietly change what one of the readers accepts.
The risk route’s own five-second timeout is the one I kept on purpose rather than fixed. Scoring one transaction is a single lookup behind a button someone is waiting on, so it should give up sooner than the shared default. #757 only gave the number a name and the reason a comment. The route still calls fetch with AbortSignal.timeout(RISK_TIMEOUT_MS) instead of going through fetchUpstream, so it doesn’t share that helper’s timeout handling yet.