Learnings
Tool quirks, false positives and root causes that a future developer would trip on again, newest first.
Tool quirks, false positives and root causes in this repo that a future developer would trip on again and that the code
does not show: the "why," not the "what." stack.md holds the settled stack choices; decisions and why
one approach beat another go to trail (trail note, saved in .trail/learnings/).
New entries go at the top. Keep each one short: what was learned, and why it matters. Delete an entry once the code or another doc states it or it stops being true.
2026-11-30 — Static docs site on TanStack Start and GitHub Pages
- Nitro's static preset breaks the Start build (the SSR input is an html file), so
apps/docshas no nitro. It uses Start's own prerender withcrawlLinks, and the output isapps/docs/dist/client. "type": "module"is required inapps/docs/package.json. Without it the SSR bundle isserver.mjswhile the prerender's preview server importsserver.js, and every prerendered page fails with an unexplained 500. The real error shows only undervite preview.@tanstack/start-static-server-functionsignores the Vite base when it fetches its cache files (checked up to 1.167.44), so client navigation breaks under any non-root base.patches/@tanstack__start-static-server-functions@1.167.33.patchprefixesimport.meta.env.BASE_URL. The package is pinned to 1.167.33, the last release whose peer accepts react-start ^1.168. Re-check the patch on every upgrade.- Pages needs a 404 the SPA shell can serve. A prerendered page that returns 404 fails the build, so
404.htmlis the prerendered SPA shell and the rootnotFoundComponentshows the message. React logs hydration error #418 once on that page, which still renders. Turning onspaalso makes the dev server render pages in the browser. - Prerender dedupes by path string. The SPA shell takes
/, so the real home page is requested as/?home(listed inpagesinvite.config.mts); without it a site served at the domain root has noindex.html. - Fumadocs collections.
filesreplaces the default glob anddirmay point outside the app. The record form ofloader({ source: { a, b } })does not setpage.data.type, so the two collections are told apart by virtual path.defineDocsneeds an explicitDocsCollection<...>type to avoid TS2883 under composite. In a route,loadermust come beforehead, orloaderDatatypes asnever. gh-pagesleaks dotfiles on the first publish. With nogh-pagesbranch on the remote it checks out an orphan that keeps the files ofmain, and its default remove pattern skips dotfiles, so.claude,.trailand.vscodewould go public.docs:deploypasses a--removeglob that includes dotfiles. Check it withdocs:deploy:dryandgit ls-filesinnode_modules/.cache/gh-pages/*.- Nx already infers a
serve-statictarget, so the custom one isserve-pages. Apackage.jsontarget with onlyoptions.commandbecomesnx:noop, and a secondnx dev docsonly waits for the first. - pnpm adds
minimumReleaseAgeExcludeentries for packages newer than the release-age policy, herefumadocs-coreandfumadocs-ui. Review them before committing.
2026-11-30 — OpenTelemetry and audit: where spans, logs and rows silently go missing or double up
Node side
@orpc/otelrecords nothing unless re-enabled after the SDK starts. It loads as ESM with its own copy of@opentelemetry/api, so the tracer it takes in its constructor stays a no-op.startObservabilitycallsorpc.enable()again afterstartNodeSdk. Its version must equal@orpc/serverexactly (pnpm-workspace.yamlpins it): a caret range gave two@orpc/sharedcopies and the config never arrived.- A second esbuild entry loads the SDK first.
additionalEntryPointswritesdist/instrument.jsbesidemain.js;servepassesruntimeArgs: ["--require", "./{projectRoot}/dist/instrument.js"]and the Dockerfile runsnode --require ./instrument.js main.js. Importing it first inmain.tsalso works but depends on import order surviving edits. - No mongoose instrumentation: Better Auth uses the raw driver, and mongoose spans only duplicate the driver spans as siblings.
instrumentation-httpalready recordshttp.server.request.duration, so onlyauth.failuresandworkspace.invites.acceptedare ours. open.router(...)re-applies theopenchain to guarded procedures, which ran authenticate, audit and the span twice (two audit rows, two spans). iam-service usesimplementers.router, which applies no middleware; the audit middleware is idempotent as a guard.- Logs and traces only join in Grafana when
service.namematches. evlog names a log after the package;runInstrumentationsetsOTEL_SERVICE_NAMEand the log plugin passes it on. - Grafana LGTM's data must be a named volume on macOS. With a bind mount Loki answered every OTLP log write with 503 while traces and metrics worked. Grafana is on 9300 (3xxx is the services, 4300 another project).
- Contrib 0.166 has no rate limiter (only
memory_limiter), so a per-IP limit on the public OTLP/HTTP port belongs on a reverse proxy (LOCAL_INFRA/README.md). The Collector'stransform/redactstrips query strings again.
Browser side
- No
sdk-trace-web3.x (latest 2.12 peersapi <1.10): useTracerProviderandStackContextManagerfrom@opentelemetry/sdk-trace3.1 (libs/observability/src/web.ts). The classic fetch and document-load instrumentations are deprecated; use@opentelemetry/browser-instrumentation/experimental/*(0.x, expect breaking changes). - Query strings and tokens end up in
url.fullof every fetch, document-load and resource span. Rewrite them once in a span processor'sonEnding(the only hook with a writable span); attributes cannot be deleted, only overwritten. - An unanchored
propagateTraceHeaderCorsUrlspattern matcheshttps://api.example.com.evil.test: use anchored regexes. Playwright'srequest.postDataBuffer()shows what the browser really exported to the Collector. - Spans of the last ~2 s of a run are orphans (the page closes or the server is killed before the parent span ends); everything else is complete in Tempo.
Audit
- oRPC's
.meta()merge drops method bivariance, so theauditextractors are typedany(AuditProcedureMeta). - The audit middleware must run before the intent guard: a refusal throws before any later middleware runs, so only an earlier one records a denied attempt.
evlog/auditis not a subpath (it is in the rootevlogexport), andevlog/better-authhas no lifecycle hooks, so account events use Better Auth'shooks.after(account-audit.ts).
2026-11-29 — Zod 4 .meta() in the form builder
Pinned by ui-libs/design-system/src/form/zod-meta-facts.spec.ts (Zod 4.5.4):
.meta(x)returns a new schema; the original keeps its meta. It copies Zod'sdescriptionto the clone but notid, and spreading a meta that holds anidback into.meta()does not throw..meta(x).optional(),.default()and.nullable()leave the outer schema without meta (it stays on the inner one);.meta(x).min(n)keeps it. Soui.*goes outermost and the walker (describe-schema.ts) merges meta from every layer.- Our meta key for help text is
hint, notdescription: Zod typesdescriptionas a string, so a locale function there does not compile (and would breakz.toJSONSchema). - Specs are excluded from
tsc(tsconfig.lib.json), so a// @ts-expect-errorin a spec is only proven by a manualtscoversrc/form/**with a temporary tsconfig that drops the exclude. - A
SelectFieldwith 7 options is a searchable combobox, and while its popover is open Radix hides the other comboboxes: a spec cannot open a second popover after picking in the first without it being closed again.
2026-11-29 — Form system: decisions the code does not show
The forms plans were deleted once finished (git history has them); what is not obvious from the code:
showErrorsmodes also show an error after a submit attempt: TanStack setsisTouchedon submit but neverisBlurred, so a strict blur rule would hide every error on an untouched form.ArrayFielddrag uses native HTML5 drag and drop on a grip button (no library); it has no touch drag, so the arrow buttons stay the touch and keyboard path.@tanstack/react-tableis pinned to v8: v9 has a differentuseTableAPI.form.Formand the login form post (method="post"): a submit before hydration must never put a password in the URL.- A
withFieldGroupcomponent (NewPasswordFields) needsBoundexported fromdesign-system/form, or tsc reports TS2883 (a type that "cannot be named"). - todo-ui must mount
<Toaster />in__root.tsx; without it everytoast.*call is silent.
2026-11-29 — fallow false positives are fixed in .fallowrc.json, not by deleting
fallow dead-code lists scripts run by node, hooks or Nx targets as unused files, and the root package.json
dependency mirrors that CLAUDE.md requires as unused dev dependencies. They are covered by entry,
ignoreDependencies and, for generated shadcn files (ignoreExports, one file at a time), not by removing anything. A
mirror is removable only when no workspace package.json, import or generator under tools/nx-plugin uses it.
2026-11-29 — Playwright e2e quirks
- IAM's sign-up and sign-in limits are stored in Mongo, so a restart does not reset them. A todo-ui e2e run uses 2 of
each and
retriesstays at 0; back-to-back runs within a minute get HTTP 429. playwright test --listdoes not run global-setup, so listing works withoutE2E_PASSWORD.- A
package.jsonnx.targetsentry with onlyoptions.commandand nothing that infers it is dropped from the project graph without a warning. Give it"executor": "nx:run-commands", or a top-levelcommand.
2026-11-29 — A closed Radix Select can hang a long jsdom test sequence
SelectField's 4-to-5-option control first used the Radix Select. In apps/todo-ui/src/routes/app.spec.tsx (20 tests) the
admin route rendered one, and the later fireEvent.click of the invite test then spun at 100% CPU inside React's event
dispatch (no failure, no timeout, because the loop is synchronous). Each test passed alone and in short sequences; raw
RadioGroup, Combobox and Field did not trigger it. The control is now shadcn's native-select, which also suits phones.
Debugging that worked: start vitest with --inspect=127.0.0.1:9239 --no-file-parallelism, connect with a small WebSocket
client and send Debugger.pause (a worker's stdout is blocked while it spins, so the reporter shows the wrong test).
2026-11-29 — shadcn add output needs fixing up
- The registry's
field,textareaandsidebaritems importcnfrom the npm packagecn, which is unrelated to shadcn's helper, and the CLI adds"cn"toui-libs/design-system/package.json. Point those imports at../../lib/utils, delete the dependency and runpnpm install. - Generated files often fail our Biome rules (
useSemanticElements,noDoubleEquals,noLeakedRender,noArrayIndexKey), so runpnpm exec biome checkon them. - To decline the overwrite prompts (
sidebarwantsbutton,sheetandseparator), pipeyes n |intopnpm dlx shadcn@latest add ...;-yoverwrites. sonner.tsximportsuseThemefromnext-themes, andsidebarappends hard-coded--sidebar-*colours toglobals.css: point the first at the design system's ownuseThemeand alias the second to existing tokens, ordesign-tokens:generate-checkfails.
2026-11-28 — Todos moved into workspaces
- Todos created before workspaces no longer parse and there is no migration: delete them by hand
(
db.todos.deleteMany({ workspaceId: { $exists: false } })). - The todo cache tag stays
todo: a contract'smetais static, so it cannot carry a workspace id. A write therefore over-invalidates other workspaces' lists.
2026-11-28 — Workspace guard typing and in-process sign-up cookies
auth.api.signUpEmail({ returnHeaders: true })sends each ofsession_tokenandsession_datatwice, and only the last token is a real session row. Joining everySet-Cookieinto onecookieheader works while the cookie cache is on and fails oncedisableCookieCacheis set.createRequireIntentreturns{ ...context, membership }. A service whoseRequestContexthasprincipal?optional must instantiate it withRequestContext & { principal: Principal<...> }, or oRPC rejects.use()after the session middleware.
2026-11-28 — IAM and Better Auth gotchas
Checked against better-auth 1.7.28.
- The rate limiter keys on a spoofable header. By default it uses the first
x-forwarded-forentry, which any client can set. Requests with no or a multi-hop header all share oneno-trusted-ipbucket per path, so five bad sign-ins from anyone lock everyone out. A server-to-serverget-sessioncall without the client's IP puts every user in one bucket. Behind your own hosting, count hops from the right and check the real hop count before treating per-IP limits as hard. get-sessionanswers from the signed cookie forIAM_SERVICE_SESSION_COOKIE_CACHE_SECONDS(300), so a ban or revoke reached services late.createIamSessionAuthProvidersendsdisableCookieCache=true; browsers' own calls still use the cache.rateLimit.customStorageneeds an atomicconsume; separate get/set are rejected, solibs/rate-limitcannot be plugged in as is. Better Auth's limiter covers/api/auth/*only.
2026-11-28 — TanStack Start and Radix testing gotchas
- Testing routes:
router.flatRoutesis undefined at runtime, userouter.routesByPath. The design system's@/alias must be set invitest.config.mtsas well asvite.config.mts. - Radix in jsdom: a
DropdownMenuopens withfireEvent.keyDown(trigger, { key: "Enter" }); jsdom has noPointerEvent, so a pointer click does not. - A query keyed on its arguments (the admin users table) needs
placeholderData: keepPreviousData, or the table unmounts on every sort and page change.
2026-10-27 — Device frames: Duo captures and syncing new assets
A Duo simulator has two displays, so capture duo and capture duo-closed both run on it: unfold or fold it first.
scripts/sync-from-stack.mjs copies git-tracked files only: git add -N new assets before syncing.
2026-10-19 — Tilted store cards are not byte-stable
Store cards with a tilted device (variant left or right) differ between runs by at most 16 per channel on the device edge: Chromium rasterizes the rotated, layer-promoted device and its blurred shadow differently on some launches. Compare them with a small pixel tolerance, not cmp; centre cards are byte-identical. Awaiting img.decode() and --disable-gpu --force-color-profile=srgb were tried and reverted (the flags changed every card).
2026-10-19 — Shared Biome config pitfalls
- A
biome.shared.jsoncthat itself extended the ultracite presets silently dropped them (217 instead of 347 rules);biome rage --linteris the quick check. - Biome 2.5 ignores
.editorconfigby default, so it only guides editors. - Format generated config with the repo's own formatter (
pnpm exec biome format --write <file>); a generated.mcp.jsonwith tabs failedpnpm run checkin repos that format JSON with spaces.
2026-10-19 — Docs lint skips node ../ commands
scripts/docs-lint.mjs skips node paths starting with ../ because they resolve from a cd earlier in the same
block, which a static check cannot follow.
2026-10-19 — Error handling decisions
- Every internal failure is
INTERNAL_SERVICE_ERRORwithdata: {}: public codes that echoed driver messages leaked index names and duplicated values. There is noCONFIGURATION_ERROR:libs/configurationfails at startup with a plainError, and a request-time misconfiguration (a procedure with no RBAC intent) isnew AppError("INTERNAL_SERVICE_ERROR", {}, { cause: "missing_rbac_intent" }). - A malformed JSON body never reached
handleErrorbecause oRPC decodes the body beforeclientInterceptorsrun, hence the request-level interceptor inlibs/server-setup. A non-JSON multipart body still gets oRPC'sBAD_REQUEST; the stack is JSON-only.
2026-10-19 — Platforms layer and Firebase auth
- fallow ignores unzoned files. A
platformszone alone would not stoplibs/cache,libs/rate-limitorlibs/test-supportimporting a platform unnoticed, so they sit in astandalone-libszone (.fallowrc.json). The gate isfallow architecture --boundaries; plainfallow checkexits 1 on unrelated findings, so it can't serve as one. platforms/*/*matched the script-only folderplatforms/gcp/cloud-run, so fallow warned about a missingpackage.json.pnpm-workspace.yamlexcludes it (!platforms/gcp/cloud-run) and.fallowrc.jsonlists it inignorePatterns; fallow'sworkspaces.patternshas no negation. Add the same pair for any script-only folder underplatforms/.- A new workspace package needs a root
tsconfig.jsonreference, or everypnpm nxrun refuses with "workspace is out of sync". Runpnpm nx sync;pnpm nx sync:checkis the read-only diagnosis. - The nested skill
platforms/gcp/.claude/skills/firebase-auth-testsloads once Claude works on files under that directory, so products without GCP never see it.
2026-10-19 — Cloud Run scripts
--dry-runprints mutatinggcloudcalls and the docker build to stderr, because several calls end in>/dev/null; stdin values are never printed.- macOS bash 3.2 errors on an empty array expanded under
set -u, hence${SECRET_NAMES[@]+"${SECRET_NAMES[@]}"}.
2026-10-18 — Agent tooling env and context cost
- Secrets that MCP config expands (
${CONTEXT7_API_KEY}) must be exported from~/.zshenv, not~/.zshrc: the desktop app and its tool shells start non-interactive zsh, which skips~/.zshrc, and context7 then connected keylessly with onlyclaude mcp listwarning.zsh -cvszsh -icshows the difference. - Every user-scoped MCP server costs context in every repo (its instructions block and tool-name list arrive at session start); only project scope avoids that. Skills cost a listing line each against a budget (1% of the context window), past which the least-used skills lose their descriptions.
2026-10-13 — Mobile skeleton and email tokens
- Generated Dart is not formatted by the generator (
formatFileshandles ts/json/md only), somobile-apptemplates with no placeholders are copies of the formatted files inapps/todo-mobile; diff a rendered app against it to catch drift. - Keep app names out of
Logger('...')strings:mobile-app-renamerewrites imports, package names and titles, not logger names. - Email tokens keep the alpha hex of the dark
border/inputtokens (#RRGGBBAA); older Outlook may not render it.
2026-10-13 — Patterns carried back from the first product built on this stack
- Rate-limit rules: procedure meta is a list of rules because one limit per dimension is the only way to say "10 per IP and 3 per email". Abuse-sensitive public endpoints such as "email me a link" fail closed.
- Client IP: a header set by your own frontend is only trustworthy with a shared secret compared with
timingSafeEqualover SHA-256 digests. - Emailed token links: store only the SHA-256 of the token. Mail scanners prefetch links, so the GET that opens a link must never be the destructive step: show a preview, and only a button that POSTs acts. Put the token in the request body, not the URL, to keep it out of access logs. Endpoints that take an email answer the same way and with the same timing whether or not the account exists, and send the email after responding.
tsconfiglibreplaces, it doesn't extend:lib: ["dom"]drops the basees2022and hidesArray.prototype.at, which Biome'suseAtIndexthen asks for. Use["dom", "es2022"].- Run
pnpm fixandnx syncon a clean or backed-up tree: in a product repo, running them coincided with every unstaged edit to tracked files vanishing (cause not found); it was recovered from a dangling stash commit (git fsck --no-reflog --lost-found). Takegit diff HEAD > filefirst when the tree is dirty. - Release builds bake in Flutter's
.env: an app that lists.envas an asset ships whateverAPI_BASE_URLit holds, so a LAN address yields a build that succeeds and is useless.
2026-10-02 — Mobile app generator
flutter create .into a directory that already haspubspec.yamlandlib/main.dartkeeps them and only adds the platform folders, so themobile-appgenerator writes its files first and runsflutter createin the post-generation callback (which also deletes the stray<name>.iml).design-tokens:generatediscovers Flutter apps byapps/*/pubspec.yaml, so a new app needs no registration.mobile-app-renamerewrites only known contexts (package:x/,apps/x,nx run x:, bundle id strings), never a bare name, because short names likeappalso appear inside file names.- A
CardinsidePaddingas aScaffoldbody stretches to full screen height (tight constraints); widget tests missed it and the simulator showed it. Use aListViewbody.
2026-09-25 — Profile Biome rules before blaming monorepo file discovery
biome lint --profile-rules showed suspicious/noUnnecessaryConditions consuming 27 s of CPU in a few configuration
files (pathological type inference) while every other rule stayed under 41 ms. A narrow override in biome.jsonc
disables it only there.
2026-09-15 — Mongo authentication and operation databases must stay aligned
Mongoose's dbName option overrides the URI path for database operations, but credentials still authenticate against
the URI's authentication database, so a user can connect and then fail every query. Grant the user on the exact database
the service operates on.
2026-09-15 — Vitest project discovery must target first-party configs
A recursive **/vitest.config.* project glob reaches declaration files under node_modules, and including both vite.config.* and vitest.config.* registers a package twice. Scope the root project glob to package directories and dedicated Vitest configs.
2026-09-14 — Connector and Redis quirks
Under NodeNext, relative test imports need .js, and ioredis v6 exposes its constructable client as the named Redis
export.
2026-09-09 — A missing generator spec hides coverage and confuses fallow
A generator is reachable only through generators.json's dynamic lookup, so fallow flags one with no spec as dead code;
a spec that imports it makes it traceable and covers its output. Writing the domain generator's spec also exposed a
template that made new domains depend on packages the generated code never imports.
2026-09-09 — Deploy dependencies and pnpm linking
- A
deployable-serviceesbuild bundle inlines every workspace lib it composes, but the Docker prune step reads only the service's ownpackage.json. A package used only by a composed lib (josevialibs/auth) can be missing from the service'sdependencies, and the gap surfaces only when the pruned image runs (MODULE_NOT_FOUND).scripts/sync-bundle-dependencies.mjs --checkscans the compiled bundle for retainedrequire()calls; the generatedsync-deploy-depstarget runs it (pnpm nx run <service>:sync-deploy-deps). - pnpm's strict linking already fails
typecheck/build for a lib that imports an undeclared package, so no extra tooling is needed for that case.