Files
faunosteo/.claude/memory/learnings.md
T

139 KiB
Raw Blame History

Learnings Registry

Format: LRN-XXX | Date | Pattern | Context | Future application


LRN-001 | 2026-05-18 | Zod discriminatedUnion for nextAppointment

Report.nextAppointment uses discriminatedUnion('kind', [...]). Gives precise TS narrowing on .kind; avoids optional union type ambiguity. Apply: any polymorphic field with a literal discriminant.


LRN-002 | 2026-05-18 | SVG hitbox+visible twin pattern

Two SVG elements share same data-anno-id: hitbox (pointer-events:all, fill:transparent) + visible (pointer-events:none, colored). Parser groups by data-anno-id → Bone.hitboxEls[], Bone.visibleEls[]. Apply: any SVG-based interactive map needing precise click areas.


LRN-003 | 2026-05-18 | pnpm via corepack shim breaks on older Node 20

corepack shim on Node 20.20.0 throws ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. Fix: install pnpm directly via get.pnpm.io/install.sh. Binary lands at ~/.local/share/pnpm/bin/pnpm. Apply: CI/dev envs without system pnpm.


LRN-004 | 2026-05-19 | SVG behavior hints via free-form data-anno-special

Branch click handling on data-anno-special (free-form string), not on data-anno-category. Why: category is free-form metadata (LRN follow-up to refactor BDR/cad94a4 chain); coupling logic to category re-introduces a closed enum and silently breaks when SVG author renames a slug. Hints stay opaque to parser, consumed only at use site. Apply: any SVG-driven UI where authors add new annotation types regularly — use data-anno-special for behavior triggers, keep category for grouping/filters only.


LRN-005 | 2026-05-19 | Detail-popup needs its own bones map

When a popup loads a separate SVG, its annotation ids are not in the parent's bones map. Parse detail SVG on popup open and keep a detailBones map; fall back lookup bones.get(id) ?? detailBones.get(id) in shared click handler. Apply: any nested/zoom-popup pattern where the child SVG has independent ids.


LRN-006 | 2026-05-19 | Strip authoring annotations before rasterizing for print

Source SVGs carry interaction-only artifacts (data-anno-, transparent hitboxes, faint default fills) that are invisible in-app via CSS but leak into PDF rasterization. Before raster: walk [data-anno-id], hide non-selected via display="none", strip data-anno- attributes, recolor selected. Apply: any "screen → print" pipeline where the screen SVG has interaction layers.


LRN-007 | 2026-05-19 | pdf-lib maxWidth wraps glyphs, not your cursor

pdf-lib's drawText({ maxWidth }) wraps the visible glyph run but the returned y is unchanged — caller must measure with widthOfTextAtSize and advance the cursor per wrapped line. Otherwise subsequent text blocks overlap the wrapped tail. Apply: any pdf-lib layout with variable-length user text. Always wrap explicitly + advance per line.


LRN-008 | 2026-05-19 | pdf-lib eyebrow + title vertical spacing

Times-22 ascender ≈ 17pt. Eyebrow size-9 baseline above title baseline needs ≥22pt gap to clear the ascender + leave ≥6pt visual breathing. Header rule needs ≥30pt cushion below for a size-22 title (title baseline at height-120ish on A4). Apply: any pdf-lib heading stack (eyebrow + title or chained headings). Compute from font.heightAtSize/widthOfTextAtSize, never eyeball pixel offsets.


LRN-009 | 2026-05-19 | pdf-lib variable-count image layout — pre-rasterize, reserve text, then grid

Variable-count image blocks (N SVGs per observation) overflow page when stacked top-down because each item's height depends on its rasterized aspect ratio, unknown until after embedPng. Order: (1) pre-rasterize every image in parallel via Promise.all, capture aspect = img.height/img.width; (2) build text sections + estimate their height with wrapLines on real font metrics; (3) reserve bottom area = MARGIN_BOTTOM + textHeight + gap, derive availH for images; (4) pick cols (1 if single image, else 2), rows = ceil(n/cols); (5) rowBudget = (availH - rows*labelGap - (rows-1)rowGap)/rows with a min-cell floor; (6) cellH per item = min(cellWaspect, rowBudget) — preserves aspect, capped by budget. Apply: any pdf-lib page where image count is data-driven and text must remain visible. Never lay out images before measuring text; never embed-then-skip — embed all, then place. Min-cell floor prevents zero-height when content is dense.


LRN-010 | 2026-05-19 | React effect that mutates async-appended DOM needs a "loaded" gate

Symptom: highlight effect (querySelectorAll + setAttribute) silently no-ops when sibling effect appends DOM async via loadSvg().then(append). First render: mutate-effect runs against empty container, then DOM arrives, then nothing re-paints because deps didn't change. Symptom is intermittent ("sometimes highlighted, sometimes not") — actually depends on which effect resolves first on a given mount. Fix pattern: hold a loadedSrc state, set it to null at src-change, set it to src right after appendChild, and depend the mutate-effect on [data, loadedSrc, src] with guard if (loadedSrc !== src) return. Now the mutate-effect re-runs both on data change AND when DOM finishes mounting. Apply: any React component that mounts external DOM async and applies attribute/style mutations in a separate effect. Includes inline SVG injection, MapLibre overlays, Lottie players. Never rely on effect ordering across an async boundary.


LRN-011 | 2026-05-20 | Zod recursive schema via z.lazy + explicit ZodType

Recursive shapes (FindingNode with optional children: FindingNode[]) need TS interface declared first, then const FindingNodeSchema: z.ZodType<FindingNode> = z.lazy(() => z.object({...})). Without the explicit ZodType annotation, TS infers any for the recursive arm and the entire downstream type chain collapses. Without z.lazy, the schema references itself before initialization → runtime ReferenceError. Apply: any tree/AST-style schema in Zod 3.x. Declare interface first, type the schema explicitly, wrap recursive shape in z.lazy. Same trick works for ZodType<U[]> when the recursion is via children: U[].


LRN-012 | 2026-05-20 | Once-per-session UX modal via sessionStorage flag

Pattern: state disclaimer: string | null, useEffect on the data dep that reads sessionStorage.getItem(FLAG); if absent, set state to the message. Acknowledge handler writes the flag and clears state. Survives reloads within tab, resets on new tab. Cheaper than persisting per-user (no backend) and respects practitioner intent — they see the legal scope reminder once per work session. Apply: any single-praticien tool needing one-shot acknowledgment per session (legal disclaimers, version-change notices, GDPR banners scoped to a session). Use a stable string key prefixed with osteo: to avoid collision.


LRN-013 | 2026-05-20 | Vite import.meta.glob + default-export = plugin discovery

import.meta.glob<{ default: T }>('./*/index.ts', { eager: true }) scans the folder at build time and returns a Record<path, module>. Combined with a "each module must default-export a T" convention, you get drop-folder plugin discovery: drop a conforming folder → it shows up in Object.values(modules).map(m => m.default). Eager mode resolves synchronously so the registry is a plain object literal in the bundled output. Pitfalls: a missing default export silently disappears (warn explicitly on !mod.default), and duplicate ids need a tie-break policy (first-wins + warn). Glob ordering is filesystem-dependent — sort the output by a stable key (e.g. labelFr) before exposing it to UI. Apply: any registry-style module set where you want zero-touch onboarding — species, integrations, plugins, theme packs.


LRN-014 | 2026-05-20 | Cross-walk human strings via normalize + Levenshtein

When bridging two sources of the same human label (SVG data-anno-name-fr ↔ JSON zone.name_fr), strict equality is too brittle (casse, accents, "(ATM)" abbreviations, typos). Robust strategy: aggressive normalize (lowercase + NFD-strip combining marks + drop non-alphanumerics), then score by 0=exact, 1=substring, 2+d=Levenshtein within max(2, floor(maxLen*0.25)), ∞=no match. EN-first if both languages available — no accent normalization edge cases. Apply: any cross-system label match where one side is authored, the other generated or hand-typed. The 25% character tolerance is a sweet spot — catches single typos on labels 8+ chars, refuses cross-zone collisions (Sphenoid ↛ Spheno-Basilar Synchondrosis even though both share "spheno").


LRN-015 | 2026-05-20 | Per-source try/catch beats loop-wrapping try/catch

Original buildZoneLabels wrapped main + every detail SVG fetch in one outer try/catch. First failing source (e.g. 404 on a detail asset) aborted the whole loop, leaving callers a partially-filled map with no signal — the rest of the labels never made it in. Lesson: when each iteration is independent, the try/catch belongs INSIDE the iteration (or inside the Promise.all callback). Outer catch only makes sense when iterations are sequentially dependent and the work is moot after a failure. Apply: any fan-out fetch / parse / transform over heterogeneous sources — config loaders, plugin enumerators, asset preloaders. Bonus: log on failure (console.warn) so the silent skip is observable in dev.


LRN-016 | 2026-05-20 | PDF custom-font text is glyph-subset — bytes-grep won't find it

pdf-lib with embedded TTF fonts (Inter, Fraunces) subsets glyphs and stores text streams as glyph indices, not codepoints. A latin1 / utf-8 grep over the raw PDF bytes will not match user-visible strings ("Temporo" never appears literally in the dump). Standard PDF text show ops (Tj, TJ) carry the glyph IDs inside content streams that are typically Flate-encoded too. Testing implication: don't assert PDF text via byte grep — either re-extract the embedded JSON attachment (already plain text) or refactor the offending logic into an exported helper and unit-test that. Same pattern when smoke-testing PDF output in CI.


LRN-017 | 2026-05-20 | i18n dict parity via Object.keys.sort equality

Cheapest drift guard between fr/en dicts: one test asserts Object.keys(fr).sort() deep-equals Object.keys(en).sort() + every value non-empty. Catches any forgotten translation at CI time without enumerating keys. Pairs with a flat <area>.<key> convention so adding a key in fr.ts forces matching update in en.ts at the next test run. Apply: any project with N parallel translation dicts (i18n, locale strings, error-code maps). Beats type-level enforcement (TS can't easily require Record<K, ...> shapes to match across two as const literals without ceremony).


LRN-018 | 2026-05-20 | useT hook: selector subscribe + closure-per-render

export function useT() {
  const locale = useLocaleStore((s) => s.locale)
  const dict = getDict(locale)
  return (key) => dict[key] ?? (warn(key), key)
}

Selector subscribe re-renders consumer only on locale change. Dict resolved once per render, the returned closure does a single hash lookup per call. No prop drilling, no context provider, no React useMemo needed. Missing-key path warns in DEV (import.meta.env?.DEV) and falls back to the key literal so the UI never crashes on a typo. Apply: any Zustand-state-driven derived computation that needs to re-render N components without prop chains. Same pattern works for theme tokens, feature flags, current user.


LRN-019 | 2026-05-20 | exhaustive-deps trap with closures over store values

Defining a helper like const nameOf = (z) => locale === 'en' ? z.name_en : z.name_fr inside a component and using it inside useMemo([deps]) triggers react-hooks/exhaustive-deps: nameOf is a fresh function each render, listing it in deps invalidates the memo every render; omitting it makes the linter complain. Two fixes:

  1. Inline the locale-conditional inside the memo body (no closure).
  2. Wrap the helper in useCallback([locale]) so it's referentially stable. Inline is simpler when the helper is one expression. Apply: any closure that bridges a memoized computation to an outer hook value (store selector, prop, context). Same trap with useEffect deps.

LRN-021 | 2026-05-21 | pdf-lib StandardFonts use WinAnsi — Latin-1 only, throws on any non-WinAnsi char

PDFDocument.embedFont(StandardFonts.Helvetica) (and the 13 other Adobe built-ins) returns a font whose encoding is WinAnsi (cp1252). Any text op (widthOfTextAtSize, drawText) on a string carrying a non-WinAnsi codepoint throws synchronously: WinAnsi cannot encode "<glyph>" (0x<hex>). Common offenders: ⚠ U+26A0, → U+2192, ✓ U+2713, ★, em-dash variants outside cp1252, all CJK. The error surfaces at the FIRST measurement pass (text-height estimator) — well before any draw call — so even a try/catch around drawing won't save you. Fix paths:

  • Quick: replace the offending glyph with a WinAnsi-safe ASCII surrogate ((!) instead of ⚠ , -> instead of →).
  • Right: embed a TTF (Inter, NotoSans, Fraunces…) via pdfDoc.embedFont(ttfBytes). pdf-lib then subsets the actually-used glyphs into the PDF; arbitrary Unicode works. Per CLAUDE.md spec our PDF should already use TTFs — current StandardFonts shipment is a drift. Why: Slipped past CI because the existing PDF roundtrip tests exercised observations without vet-referral findings; the WinAnsi error only fires when the offending glyph is present in a measured string. How to apply: When a new visual cue (icon, badge, arrow) is added to PDF output, either restrict to ASCII or audit the font path. Add a regression test that exercises the measurement path with a representative string. The cheap canary: font.widthOfTextAtSize(candidateGlyph, 10) in a test.

LRN-020 | 2026-05-21 | Forward-compat Zod schema absorbs catalog version bump zero-code

Catalog JSON went v1.2→v2.0 (semantic breaking change per author doc), but findings.ts Zod schema declared requires_vet_referral boolean + description_fr optional from B0 day-one. Result: v2.0 file dropped in, parses clean, 154/154 tests stay green, no schema edit, no consumer rewrite. Picker + PDF already keyed on boolean (no textual description_fr.includes('vétérinaire') fallback ever existed in our code), so the v2.0 "removed redundant text" change is a no-op at consumption site. Lesson: when authoring a Zod schema for external content, mark anything that "might or might not" appear as .optional() + make booleans authoritative early. The schema then forms a stable contract that absorbs author-side simplifications without code churn. Apply: any data contract sourced from non-engineering authors (clinical, legal, marketing). Decouple presence-of-field from semantic-of-field; let the boolean drive logic, let text be display-only ornamentation.


LRN-023 | 2026-05-22 | DOMParser for safe SVG loading in React-wrapped vanilla editors

When wrapping vanilla JS editor in React, avoid innerHTML = svgText for user-uploaded SVG. Use new DOMParser().parseFromString(svgText, 'image/svg+xml') + document.importNode(parsedSvg, true) to safely parse and import SVG into DOM. Parser rejects malformed XML, returns parseerror element on failure — gives clean error path. importNode deep-clones into current document context so all DOM APIs (createSVGPoint, getScreenCTM) work correctly. Apply: any user-uploaded SVG injection into a React-hosted vanilla canvas. Also avoids security hook warnings about innerHTML with untrusted content.


LRN-022 | 2026-05-21 | pnpm 11.x requires Node 22.13 — pin pnpm to ≤10.x when staying on Node 20, never use @latest

pnpm 11.x imports node:sqlite for its store-index module — loaded at pnpm startup for any command that touches the store (install, fetch, add, prune). node:sqlite is a Node 22.13+ built-in. Result: ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite on every fresh Docker build using node:20-alpine + pnpm 11.x. The crash is deterministic for cold installs and invisible for warm dev hosts that already have node_modules resolved (pnpm 11 on Node 20 can still spawn child scripts because the store module isn't required for pnpm run). Initial hypothesis ("pnpm@latest pulls a newer 11.x with a new Node floor") was wrong — the whole pnpm 11.0+ line carries the sqlite dependency. Fix paths:

  • Stay on Node 20 → pin Dockerfile to pnpm@10.x (e.g. corepack prepare pnpm@10.13.1 --activate). pnpm 10 reads lockfile v9 unchanged.
  • Move to Node 22 → bump FROM node:22-alpine, .nvmrc, and CLAUDE.md stack table together. Required if pnpm 11+ features needed.
  • Mirror exact version in package.json: "packageManager": "pnpm@X.Y.Z" so host + Docker stay synced via corepack.
  • Never corepack prepare pnpm@latest — re-resolves at every cold build, silently bumps toolchain across deploys with no commit. Why: Floating tag = drift bomb between cached dev + fresh prod resolve. Same risk for unpinned node:lts, :alpine, GitHub Actions uses: foo@v1 (prefer SHA). Lockfile pins app deps; Dockerfile must pin toolchain. How to apply: Before first prod deploy, audit every Dockerfile, docker-compose, and CI workflow for floating upstream refs. For pnpm specifically, check Node version against pnpm minimum (pnpm 11 ↔ Node 22.13, pnpm 10 ↔ Node 18+, pnpm 9 ↔ Node 18+).

LRN-025 | 2026-05-22 | SVG importNode executes inline scripts — sanitize before append

DOMParser.parseFromString(text, 'image/svg+xml') is safe — doesn't execute scripts during parse. But document.importNode(svg, true) into a live document DOES allow <script>, on* event handlers, and <foreignObject> to execute. Must strip these after importNode, before appending to DOM. Why: discovered during pathology editor code review — file upload path accepts arbitrary SVG. How to apply: any tool accepting user-uploaded SVG: strip script, foreignObject, and all on* attributes after importNode. Or use DOMPurify. Applies to both standalone HTML tools and React-wrapped vanilla editors.


LRN-026 | 2026-05-22 | Standalone HTML tools: port logic inline, don't share modules

When standalone .html tools (no build step) need logic from TS modules (zoneMatch, ID generation), port algorithm inline as vanilla JS. Cannot import .ts files. Keep algorithms identical to source for consistency. Document which .ts file was ported so future changes can sync. Why: pathology-editor.html ports normalizeLabel/levenshtein/scorePair/matchZone from src/lib/zoneMatch.ts. How to apply: if zoneMatch.ts changes, pathology-editor.html matching must be updated manually. Consider a test that compares outputs of both implementations on a shared fixture set.


LRN-027 | 2026-05-22 | CSS h-full fails in nested flex — use flex-1

height: 100% (Tailwind h-full) resolves to auto when parent has flex-1 but no explicit height. Caused 3 failed centering attempts on route containers inside App.tsx flex layout. Fix: use flex-1 (flex-grow) on child instead — works because parent IS a flex container, no explicit height needed. Why: nested flex layout: App wrapper (min-h-screen flex-col) → main (flex-1) → route (h-full broke here) → section (flex-1 grid place-items-center). The section's place-items-center needs actual height to center within. How to apply: any flex-nested layout where child needs to fill parent — use flex-1, not h-full, unless parent has explicit height or is viewport-sized (h-screen).


LRN-028 | 2026-05-27 | Drive derived UI by spawning the source-of-truth row, not patching each consumer

SVG highlight (boneStates) AND findings picker both derive from observation.zones. So making a cross-region vertebra pick "highlight + add zone + add findings" = ONE lever: spawn the spine zone in observation.zones. No separate highlight call, no separate findings wiring — both consumers already react to zones. Keep distribution logic pure (distributeVertebraeToZones(zones, targetIndex, verts, bones) → new zones[]) so it unit-tests without React; component handler stays a one-liner. Inverse-map region→zone via reusing the same label heuristic (regionFromLabel) that maps zone→region — store the function once, scan bones for special==='vertebral-precision' whose label matches. Apply: any feature where "select X in modal → reflect in N places". Find the single derived-from state; mutate that; let existing selectors fan out. Avoids drift between the highlight path and the data path.


LRN-029 | 2026-06-13 | Vite bundles only index.html — standalone HTML must live in public/

Extra .html at repo root never reaches dist/ — Vite build entry = index.html only. Prod 404: nginx try_files falls through to SPA index.html, React shows "Page introuvable". Fix: put standalone HTML in public/ (copied verbatim to dist/). Links resolve from web root, so href stays /file.html. Why: pathology-editor.html shipped at root (BDR-020 standalone-HTML pattern), worked in pnpm dev (Vite serves root files in dev) but 404'd in prod (only public/ + bundled entries land in dist/). Dev-vs-prod gap hid it. How to apply: standalone HTML tool / extra entry → public/, OR add to vite build.rollupOptions.input for hashed-asset processing. Verify via vite preview (serves real dist/), not just pnpm dev. Ties to BDR-020.

LRN-030 | 2026-07-12 | Dockerized SPA on port >=1024 — full non-root nginx works

nginx:alpine default = master root, workers nginx. Listen port >=1024 → USER nginx viable: chown /var/cache/nginx + pre-created /var/run/nginx.pid + /etc/nginx/conf.d (entrypoint envsubst rewrite) + html dir (env.js write). Official image log symlinks (/dev/stdout|stderr) work non-root. Why: tour 2026-07-12 semgrep HIGH (no USER before ENTRYPOINT, Dockerfile:34). Fixed d8e478a; verified docker run: HTTP 200, SPA fallback, env override, ps = uid 101 master+workers. How to apply: any nginx-served SPA container: keep listen >=1024, chown the 4 paths above, USER nginx. Contract change: PORT <1024 now fails to bind — flag BREAKING. Alt base: nginxinc/nginx-unprivileged.

LRN-031 | 2026-07-12 | Build toolchain in dependencies inflates prod CVE audit surface

vite + @vitejs/plugin-react-swc + @tailwindcss/vite sat in dependencies → pnpm audit --prod reported their CVEs as prod findings. Build-time-only packages belong in devDependencies; SPA runtime imports none of them. Why: tour 2026-07-12 cso posture audit — all 3 "prod" advisories were build-toolchain. Moved 187dfb5; build+tests green, prod audit clean. How to apply: scaffold check: anything imported only by vite.config / build pipeline → devDependencies. Then pnpm audit --prod reflects real runtime surface. Docker multi-stage unaffected (builder installs all).


LRN-032 | 2026-10-08 | pnpm via corepack prepare, not ~/.local/bin

Dev host: no pnpm on PATH, no node_modules, Node 24.21 (CLAUDE.md said Node 20 + ~/.local/bin/pnpm, both stale). corepack prepare pnpm@10.13.1 --activate + corepack pnpm <cmd> works, zero global install, same pin as Dockerfile (BLK-005). Suite 271/271 on Node 24. Apply: never export PATH=… in Bash tool (denied); call corepack pnpm. Pin packageManager in package.json so corepack picks version alone.


LRN-033 | 2026-10-08 | Characterise legacy via DOM + prototype spies, no refactor

Untestable seams (click chain inside route, PDF text) pinned without touching src: render route in MemoryRouter + mock @/anatomy/svgLoader to parse real files, dispatch bubbling click on [data-anno-id]; vi.spyOn(PDFPage.prototype,'drawText') captures every drawn string (pdf-lib has no extractor); attachment dicts via doc.context.enumerateIndirectObjects() + String(obj) (object streams hide names from raw bytes). Standalone HTML tool: slice functions by text markers, new Function(src) → parity test. Trap: store set outside React then click = stale closure; drive state through UI (collapse card) and waitFor. Apply: any "tests before migration" step on untested legacy code.


LRN-034 | 2026-10-08 | pnpm 10.13 reads onlyBuiltDependencies, not allowBuilds

allowBuilds key in pnpm-workspace.yaml = pnpm ≥10.14 syntax; 10.13.1 ignores it silently → "Ignored build scripts: @swc/core, esbuild" on every install. Fix: onlyBuiltDependencies list. Warning persists until pnpm rebuild (state cached in node_modules/.modules.yaml), then disappears. Also: root scripts calling pnpm -r fail under corepack pnpm (shim not on child PATH) → pin pnpm as root devDependency. Apply: any pnpm 10.x workspace; check pnpm --version vs key syntax before trusting a silent config.


LRN-035 | 2026-10-08 | PGlite + pgtap = Dockerless Supabase RLS tests

@electric-sql/pglite 0.3 bundles pgtap, pgcrypto, uuid_ossp (import { pgtap } from '@electric-sql/pglite/pgtap'). Boot ~1s, create extension pgtap with schema extensions + set search_path to public, extensions (else pgTAP functions pollute public and break "list public functions" checks; filter pg_depend deptype='e' too). db.exec(file) runs multi-statement begin…rollback; collect string cells → TAP lines; fail on /^not ok/ or # Looks like. After error: rollback to clear aborted tx. Impersonate: set local role authenticated; set_config('request.jwt.claims', '{"sub":…}', true). now() frozen in tx → test updated_at by overwriting then is(updated_at, now()). Apply: any Supabase project needing SQL tests in CI without Docker.


LRN-036 | 2026-10-08 | Supabase default privileges grant ALL to anon/authenticated on new public tables

Hosted/local Supabase: alter default privileges … grant all on tables/functions to anon, authenticated, service_role. New table or RPC = anon can SELECT/EXECUTE until revoked (RLS still filters rows, but RPC runs). Pattern per migration: revoke all on <table> from public, anon, authenticated; then exact grants (column-level for partial UPDATE); revoke all on function … from public, anon. Also Postgres default EXECUTE to PUBLIC on functions in own schemas → alter default privileges in schema private revoke execute on functions from public. Shim replicates defaults so pgTAP has_table_privilege('anon',…) catches omissions. Apply: every migration; pin with pgTAP privilege checks.


LRN-037 | 2026-10-08 | SQL tests seed-agnostic; generated files through a deterministic formatter

Real stack applies seed.sql before supabase test db; PGlite harness applies migrations only → absolute count(*) and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". supabase gen types (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both db:types and db:types:check, else CI diff flaps. Apply: any dual-runner test setup (shim vs real); any CI diff on generated code.


LRN-038 | 2026-10-08 | RLS filters, never raises: test "no change", and trigger guards under the owner role

API-role UPDATE/DELETE on a row hidden by policy touches 0 rows silently → throws_ok wrong; assert the row unchanged afterwards (is((select content ...), expected)). Trigger-level immutability must be proven with reset role (table owner bypasses RLS). pgTAP is() cannot wrap a data-modifying CTE (with u as (update …) must be top level) → plain statement then a read. Triggers fire alphabetically by name: when two BEFORE triggers reject, the first name's errcode surfaces (species check 23514 before guard 42501) → pick test inputs that isolate the guard. Apply: every RLS + trigger pgTAP file.


LRN-039 | 2026-10-08 | Dual-runner parity: pin collation, grant pg_temp fixtures to API roles

Real Supabase image sorts text with a locale collation (anatomical_sheet_asset… before anatomical_sheet.archived), PGlite with C → results_eq on order by text flaps; pin order by col collate "C". pg_temp tables/functions created as postgres are invisible to set local role authenticated → grant all on pg_temp.t to anon, authenticated; grant execute on function pg_temp.f(...). jsonb equality check beats (x->>'k')::int = n in a CHECK (no cast error on garbage). Apply: any pgTAP file with fixtures read while impersonating; any ordered results_eq (extends LRN-037).


LRN-040 | 2026-10-08 | Function privileges: revoke per function, pin with a pg_proc census

alter default privileges in schema X revoke execute on functions from public does nothing (BLK-007). Pattern: every migration ends with revoke all on function private.f(args) from public per function + explicit grants; a pgTAP census (has_function_privilege('anon'|'authenticated', p.oid, 'execute') over pg_proc of private/audit, compared to an allowlist via string_agg(... order by proname::text collate "C")) fails the next omission. results_eq over name-typed columns vs text literals raises "could not determine which collation" on PGlite → compare one aggregated string. Trigger functions that call other private functions must be security definer once EXECUTE is revoked (the invoking API role no longer holds it). Apply: every Supabase migration; the census is the backstop.


LRN-041 | 2026-10-09 | Real Supabase image vs PGlite shim: storage triggers, pnpm script cwd

Real storage.objects carries storage.protect_delete (statement trigger: "Direct deletion from storage tables is not allowed") → a pgTAP that runs DELETE as an API role passes on the shim and aborts the whole file on the real stack; assert write restrictions through a pg_policies census instead. Shim stays minimal (buckets/objects columns actually touched). pnpm --filter pkg script <relative path> runs inside the package dir → resolve CLI paths from process.env.INIT_CWD. Node 24 strip-types cannot follow workspace directory imports (ERR_UNSUPPORTED_DIR_IMPORT) → tsx for CLIs that import workspace packages. Apply: every pgTAP touching storage.*; every workspace CLI.


LRN-042 | 2026-10-10 | Changeset authoring over a baseline: python modules per theme, stylised SVG audited by gridded crops

Authoring 44 changes / 679 ops by hand is error-prone → scratch python modules (one per research theme, shared helpers set_op/cite_op/add_change, auto-numbered ids, targets derived from the baseline by walking it) built into changes.json; the pipeline's Zod + integrity rules catch any bad target at once. Order of modules = order of ops: a later module must address ids renamed by an earlier one (consultation-reason category ids). Stylised drawing: render with magick + 50-unit grid crops; sample first non-white row per column to prove "point floats above the silhouette" (t18-l1, l6-s1 were 30-70 units above the back). ImageMagick's internal SVG renderer drops shapes with fill="none" and shapes containing a <title> child → overlay uses fill-opacity and puts <title> on the <g>. Research agents: one theme each, every citation tagged VERIFIED-fetched/snippet/UNVERIFIED; only fetched or bibliographically confirmed entries enter the registry, unread books say "non consulté" in the citation. Apply: next species/sheet curation; any overlay/diagnostic SVG rasterised with ImageMagick.


LRN-043 | 2026-10-10 | Migrating an app onto a new data model: freeze goldens first, make ids + maps data, read fresh state in DOM handlers

Freeze golden artifacts with the OLD code before touching it (v2 PDFs via a one-shot vitest, MAKE_GOLDEN=1, deleted after): the new importer is then tested against real archive-like bytes. Generate id/path maps from the pipeline's own records (renames/removals), never hand-written, and commit them as golden-tested data. In React routes, click handlers bound through useEffect capture stale closures when two DOM clicks land before a re-render (tests dispatch synchronously): read store.getState() inside the handler. A sheet needed to restore a draft but only known from the draft → load the default species' sheet when no report is open. Vitest has its own config: a Vite plugin providing a virtual module must be registered there too. ImageMagick cannot verify marker look with <title> children or fill="none": strip titles for the raster only. Apply: Step 6 (PDF v3 snapshot), Step 13 (Supabase SheetProvider), any future schema bump.

LRN-044 | 2026-10-10 | CLI over untrusted documents: escape before print, privacy default, generic parse errors

Context: report:compare prints content of archive PDFs (attachment JSON). Security audit: raw interpolation lets a crafted attachment carry ESC/CR sequences that erase or forge lines, including a !! UNRESOLVED marker in an integrity tool; free text leaks names when stdout lands in CI logs; V8 JSON.parse message echoes ~15 chars of the input. Pattern: one esc() helper (/[\p{Cc}\p{Cf}\u2028\u2029]/gu → \uXXXX) on every interpolated untrusted string incl. file names and error messages; default output = ids + catalog labels + counts + placeholders, --full opt-in for names and free text, same rule in every mode (--diff too); SyntaxError → generic reason; statSync().isFile() + size before readFileSync; INIT_CWD for paths under pnpm. Apply: any future CLI/log over report content (Step 6 server import, worker). Test with \u001b[2K, \n, \u009b, \u202e, __proto__ ids.


LRN-045 | 2026-10-10 | Permanent will-change: transform blurs text; promote only during the animation

Context: findings picker text blurry on screen, crisp in PDF (Step 5 validation). motion.ul kept inline will-change: transform, opacity after its 220 ms slide (computed transform none); list sat at fractional offset inside height-animated card (left 561.1875 px desktop, top 735.77 px mobile) → element stayed on own compositor layer, text resampled at non-integer position → blur. Fix = drop the prop; motion promotes the element itself while animating (1f0b710). Pattern: never set permanent will-change on text containers; let the animation lib promote for the duration. Diagnose with headless Chromium: computed willChange, bounding rect fractional offsets, edge-sharpness ratio before/after (headless has no LCD antialiasing → desktop delta flat, user confirms in real browser). Regression test = rendered element has no inline will-change. Apply: any motion.*/CSS transition on lists, cards, modals holding text; design-review audits.


LRN-046 | 2026-10-11 | Refactor a render pipeline behind goldens frozen in two fixture modes; lean-document snapshot beats a new schema

Step 6 moved the PDF pipeline into packages/pdf with zero visible change. What made it provable: Phase 0 froze drawn text (page, x, y, size, font), image placements, link annotations and per-view structural facts with the OLD code, in two harness modes (logos absent / present via a fetch stub serving the real public/ bytes) and per locale (footer geometry depends on label width). Golden JSON = oracle; the port had 0 mismatch; the two intentional differences (hidden markers absent, data-* gone) were declared as relaxed fields, never by editing goldens. Snapshot shaped as a valid lean AnatomicalSheetDocument reused the index, the renderer and 21 integrity rules (3 challengers killed the dedicated-schema idea). Node-side xmldom composer already existed in curation (app-review.ts): promote, don't rewrite. resvg 0.40 panics on gradient fills culled by a cropped root viewBox (head view) → test adapter renders the full box and crops pixels; Chrome is fine. Executors denied rm/git rm: orchestrator deletes on literal relative paths after checking importers. Apply: any pipeline extraction (Step 13 Supabase provider, Step 14 worker); any "snapshot" design: reuse the live schema minus content before inventing one.

LRN-047 | 2026-10-11 | Supabase Auth in a SPA: initialize() + PKCE same-browser rule, GoTrue codes → closed kinds, pgTAP data-modifying CTE trap

Step 7 facts worth keeping. (1) client.auth.initialize() is public and idempotent: await it at store start to catch the URL exchange error (expired/foreign link) that onAuthStateChange never reports; INITIAL_SESSION ordering vs that promise is not guaranteed → a callback route landing signed-out = failure, don't wait for a flag. (2) PKCE confirmation/recovery links only open a session in the browser that made the request (verifier in its localStorage); the email is still confirmed server-side → phrase it ("opened in another browser… just sign in"), don't claim expiry. (3) supabase-js 2.117 AuthError.code (invalid_credentials, user_already_exists, weak_password, otp_expired, bad_code_verifier…) → map to a closed union in the access layer, UI translates auth.failure.<kind>; raw messages never rendered. (4) Account load must run outside the auth callback (setTimeout 0): the client serialises callbacks, awaiting a request inside deadlocks. (5) pgTAP: select is((with upd as (update … returning 1) select count(*) from upd), …) fails ("data-modifying CTE must be top level") and silently breaks the plan count; use lives_ok + a read after reset role. (6) Mailpit API (/api/v1/search?query=to:<email>, /api/v1/message/<id>) makes the confirmation + recovery flows scriptable headlessly; playwright-core installed in the scratchpad + cached ms-playwright chromium via executablePath = no project dependency. Apply: every future Supabase auth surface (Step 14 gating, invitations), any pgTAP write assertion, any e2e of email flows.

LRN-048 | 2026-10-12 | Before porting a module, list the hidden serialisation contracts; goldens on drawn primitives make an engine swap provable

Context: Rust review inventories. Facts found: documentSha256 = sha256 of Prettier-formatted text (only compared at runtime → mismatch = rebase, not loss); coordinates = raw JS number strings (serde_json prints 1523.0); attachment = insertion-order JSON, snapshot = Zod schema order; .optional() absent vs nullable null (serde-wasm-bindgen json preset writes null → breaks readers); text x positions = AFM widths + kerning pairs; dates = ICU; toUpperCase, /\s+/, non-fatal TextDecoder, last-dup-key JSON.parse, Zod .int() accepting 2.0. The 39 PDF goldens record draw calls (spies), never bytes → a Rust engine with a draw-log layer can match them exactly; byte goldens (xmldom XMLSerializer, Prettier files) cannot be matched by another stack → compare parsed trees or regenerate by decision. Apply: any port (R2–R5): freeze unpinned outputs with the old code (LRN-046), write the contract list with a fixture each, decide lenient-vs-strict per item, keep an N-1 reader test permanently. Challengers found 2 blockers rev 1: deletion schedule vs surviving consumers (name the last consumer per module), and deployment facts (CSP without 'wasm-unsafe-eval', VPS compiling images) → check the serving path before the language.

LRN-049 | 2026-10-13 | R0 experimental findings: serde_json fast float path, wasm traps and the ESM cache, RLIMIT_CPU soft=hard, minimal rustup profile, traced seccomp set

Facts proven on the real environment (docs/development/RUST.md §5), each one changed a design assumption of the review:

  • serde_json default float parsing is a fast path one ULP off on some inputs (1715.4285714285713 → 1715.428571428571): enable float_roundtrip whenever bytes must match JSON.stringify; the formatter alone (js_number) is not enough.
  • wasm32 = panic=abort: a panic and a shadow-stack overflow both surface as WebAssembly.RuntimeError; after a stack-overflow trap the next call fails in the allocator (deterministic), after a plain panic the instance still answers with a never-unwound stack pointer (silent) → never reuse an instance after any trap; the wasm-bindgen glue caches its instance in a module variable and import() of the same URL returns it → a fresh instance needs a new module record (cache-busting query) or a new Worker.
  • setrlimit(RLIMIT_CPU, soft, hard) with soft == hard kills with SIGKILL (hard checked first), indistinguishable from a parent deadline kill → soft two seconds below hard gives SIGXCPU.
  • Official rust: images install rustup's minimal profile: rustup component add rustfmt clippy in the image, else every container downloads them (rust-toolchain.toml lists the components).
  • A single-threaded musl static decode (image/zune-jpeg/png/image-webp + libwebp encode) makes exactly 7 syscalls after start: read write mmap munmap mremap exit_group getrandom; mallocng used neither brk nor mprotect, no futex. Derive with strace after a stderr marker, compare in the build, keep an explicit abort-path set (rt_sigaction rt_sigprocmask getpid gettid tkill tgkill exit) proven by the RLIMIT_AS → SIGABRT test.
  • Unoptimised debug decoders blow a 10 s CPU budget on 4096² inputs: [profile.dev.package."*"] opt-level = 3.
  • cargo-deny 0.20: a versionless path dependency is a "wildcard" (allow-wildcard-paths = true) and a workspace-inherited path dependency triggers an unresolved-workspace-dependency bug (declare path = "../core" per crate).
  • CSP: 'wasm-unsafe-eval' is required for WebAssembly.instantiateStreaming under script-src 'self' and allows nothing else (inline scripts still blocked); proven with the production nginx image + headers in headless Chrome 156. Apply: R1 (worker loop keeps the same child), R2 (browser loader: fresh-instance mechanism, float_roundtrip stays on, CSP line at activation), any future "it should work" assumption about a runtime → run it in the real environment first.

LRN-050 | 2026-10-13 | Native vs Docker Rust: rustup auto-install, non-interactive PATH, path strings in the wasm, worker unit tests native

  • rustup show inside a repo with rust-toolchain.toml auto-installs the channel (rustup 1.29, default profile → rust-docs too, ~1.5 GB per toolchain); rustup target add --toolchain <ver> + two cargo install --locked ≈ 100 s with a warm registry.
  • Agent / hook / editor shells are non-interactive: ~/.bashrc returns early, ~/.cargo/bin absent from PATH while the user's shell has it → scripts source a 5-line guard (scripts/rust-env.sh), never assume PATH. The harness refuses tool commands containing export PATH=: use absolute paths or a sourced file.
  • Same rustc + lock → wasm differs by 64 B and by hash between build roots (/w vs /home/...): panic Location paths embedded; bit-identity needs --remap-path-prefix (unset at R0). Builder image = reference when bytes must match.
  • Worker sandbox tests are #![cfg(feature = "test-hooks")]: plain cargo test --workspace compiles them empty → the 9 worker unit tests run natively for free (R0's --exclude faunosteo-worker was unneeded); seccomp derivation stays Docker/musl only (glibc syscalls differ).
  • Contract oracles need a dry run before dispatch (EVAL-013/017 lesson, applied): a grep for width * 4 matched my own SAFETY prose; pnpm -r test:run prints per-package totals, never one root line.

LRN-051 | 2026-10-13 | Supabase Storage + worker facts: 400-as-404, RETURNS TABLE arg names, service_role cannot read private tables, pg_temp definer helpers in pgTAP

  • storage-api v1.79 answers a missing object with HTTP 400 and body {"statusCode":"404","error":"not_found"} (DELETE and GET alike): classify by body, not status, or purge acks never happen (sweep errors loop every interval; caught by the e2e queue-drained assertion, not by unit tests).
  • pg_proc.proargnames lists OUT columns of a returns table function: a types-vs-schema test must filter proargmodes in ('i','b','v') or the generator's Args (IN only) never match.
  • service_role has BYPASSRLS but no table grants on private.*: a pgTAP block running as service_role cannot select the purge queue → read private tables after reset role; the worker RPCs are definer anyway.
  • pgTAP pattern: pg_temp.row(key) returns public.assets security definer + pg_temp.ids map lets authenticated/service sessions inspect rows across role switches; is((row).status, 'literal') resolves the enum from the first arg; rows inserted in the test share now() → an "older than 0 s" sweep needs <=, not <.
  • PostgREST: raise exception using message = '<code>', errcode = 'P0001' → 400 {code:"P0001", message:"<code>"}; only accept messages with the closed-code shape (lowercase + _, ≤ 40) to keep server free text out of the kinds.
  • Harness: writing any .env* file and gitflow finish (merge + push to develop) are refused by the auto-mode classifier; forks (full-context subagents) parallelise Rust vs TS tracks well when a contract-level doc (STORAGE.md) is written first.
  • Real browser proof without a project dep: playwright-core in the scratchpad + cached ~/.cache/ms-playwright/chromium-* via executablePath, Vite on a spare port with VITE_SUPABASE_*; setInputFiles exercises createImageBitmap + canvas for real (happy-dom cannot). Apply: every Storage call in later steps (documents, logos), every returns table RPC, future pgTAP on service-role paths, R2+ gates.

LRN-052 | 2026-10-13 | Restrict Supabase CLI ports under Docker rootless without sudo: daemon default ip + gateway; rootless file-permission trap

  • Supabase CLI 2.120 publishes 54321-54324 with no host address and has no bind option in config.toml → Docker uses the daemon's default (0.0.0.0 + [::]). Docker rootless reads ~/.config/docker/daemon.json: {"ip":"127.0.0.1"} makes every address-less published port loopback-only, no sudo, no firewall (needs daemon restart + containers recreated: pnpm db:stop && pnpm db:start).
  • Rootless publishing = rootlesskit listening sockets in the host netns → host INPUT/UFW rules DO apply (rootful Docker's DNAT bypasses UFW). Still prefer removing the listener over filtering it.
  • Re-expose only what browsers need with a tiny nginx on the stack's network, published on the LAN address explicitly (<ip>:54321, <ip>:54324); resolver 127.0.0.11 + variables in proxy_pass so a restarted stack is followed.
  • Rootless bind mounts: a 600 file owned by the user is unreadable by the container's non-root user (subordinate uid) → nginx 500 "open() htpasswd failed (13)". Make hash-only files 644, keep clear secrets 600 outside the mount.
  • Probing "closed" vs "open" with curl: exit 7 (refused) / 28 (timeout) = closed; a non-HTTP TCP service (PostgreSQL) gives exit 52/56 = OPEN. HTTP 000 alone proves nothing. Apply: any DEV service exposure on this machine; future staging compose.

LRN-053 | 2026-10-13 | Correction of LRN-052: Supabase CLI 2.120 binds 0.0.0.0 explicitly; rootless container probes cannot see the host LAN firewall

  • Owner applied ~/.config/docker/daemon.json {"ip":"127.0.0.1"} + restart: the CLI still published 54321-54324 on 0.0.0.0 and prints "All services bind to 0.0.0.0" → it sets the host IP explicitly; the daemon default never applies. LRN-052 bullet 1 is wrong for the CLI (still true for address-less ports of other containers). Only a host firewall closes PG/Studio/raw Mailpit; UFW rules scoped in on <lan-iface> work on rootless listeners.
  • A gateway cannot share a port with a 0.0.0.0 listener whatever its own address ("port is already allocated") → serve the authenticated Mailpit on another port (54325).
  • Rootless (slirp/pasta) containers reach the host's own LAN IP by local delivery, never through the LAN interface → firewall refusals on that interface are invisible to any probe run on the host; prove them from another device (nc -zv -w 3 <ip> <port>).
  • Lesson: an "it should apply" assumption about a third-party tool's binding must be tested before handing a procedure to the owner (I flagged it as a hypothesis, but the owner still spent a daemon restart on it). Apply: any exposure work on this machine; staging compose (bind explicitly there).

LRN-054 | 2026-10-14 | Porting Zod to serde without drift; wasm in Vite; agent and harness traps

  • serde silently widens Zod: a missing Option field defaults to None (use deserialize_with to make a nullable key required), null reads as None for an optional (use a present helper refusing null), u32 refuses 2.0 that .int() accepts (JsInt over f64), internally tagged enums print the tag first (untagged enum + literal tag field at the schema position keeps Zod order). Zod drops a __proto__ key in z.record; JS regex $ = end of input; .min/.max count UTF-16. Prove with byte equality against JSON.stringify(Schema.parse(x),null,2) on real documents, a characterisation set frozen from the old functions, and a verdict table run by Zod once.
  • Vite: import x from 'pkg/glue.js?url' emits the wasm-bindgen glue as an asset (no bundling); import(${url}?instance=${n}) gives a fresh module record in dev (/@fs/…) and build; works under CSP script-src 'self' 'wasm-unsafe-eval'. In happy-dom suites Vite rewrites new URL(rel, import.meta.url) into /@fs/… → Node readFile fails: build paths from fileURLToPath(import.meta.url).
  • A caught WebAssembly.compile CSP refusal logs nothing in the console: read the securitypolicyviolation event (blockedURI = wasm-eval). Headless Chromium defaults to en-US: set the page locale before asserting French strings. The DEPLOY CSP also refuses the footer's external credit logo (img-src).
  • This harness decodes \uXXXX in tool inputs (heredocs, Write): build escape sequences with python chr(92).
  • isolation: worktree forks started at an old commit (605ee7c, not HEAD): each fork had to move its temp branch; brief forks to check git log -1 first. git worktree remove / git branch -d on those temp branches refused by the auto-mode classifier → leftover worktrees (3.2 GB) for the owner to remove.
  • Forks with full context + disjoint file ownership + "no commit, I collect the diff" merged with zero conflicts (one deliberate stub replaced). Apply: R3/R4/R5 ports (same oracle stack), any wasm loaded by Vite, any agent fan-out.

LRN-055 | 2026-10-14 | Lossy normalisation pre-pass hides user-data alteration; classify parser refusal instead

Context: R2 rewrote lone surrogate escapes to U+FFFD before serde_json so JS-era texts still parsed (L1). Owner refused: silent change of historical data. Fix: drop pre-pass; serde_json already refuses; scan text only after failure to name kind (zero cost on valid input, exact refusal kind for UI message + quarantine). Trap found by fix: oracle file freezing TS outputs carried lone escapes → whole-file parse failed; test loader must spell escapes out as literal text (evidence kept), never re-normalise. Also: u32::from_str_radix accepts leading + → escape scanner checks hex digits explicitly. Apply: any reader of user data (R3 SVG, R4 PDF reader, R5 pipeline) → refuse with closed kind + keep original, never repair silently; a leniency step needs explicit owner decision and declared-difference test.

LRN-056 | 2026-10-15 | XML parser recursion, prescan closers, URL/CSS whitespace: three traps porting an SVG sanitiser

  • roxmltree 0.21.1 recurses per nesting level (parse_element ↔ parse_content); 1 MiB wasm stack overflows between 1,000 and 3,000 levels; nodes_limit checked too late. Measure parser depth on the real stack size before trusting "iterative" claims (plan rev 1 said iterative: false). Fix = own markup prescan before any parse; fixed release only in unreleased git.
  • A prescan must search each closer AFTER its whole opener (--> from +4, ]]> from +9, ?> from +2): searching from +1 let <!--> desync scanner vs XML grammar and hide 5,000 levels (security audit MEDIUM). Prove with differential fuzz vs the real parser (auditor ran ~4M docs) + calibrated small-stack run.
  • Locality of href / url(#…) must follow the browser's parsers: URL parser strips only C0+space, CSS tokenizer only space/tab/newline. JS trim()/\s include NBSP/ideographic/BOM → \u00A0#a passes as local, resolves as relative URL. TS engine has the same flaw (declared difference).
  • Mutation checks on oracle tests find blind spots: namespace check mutant passed until a rebound-prefix corpus case was added.
  • vitest/React: effect with per-render deps (useT closure) + setState(new array) → infinite render loop (OOM); guard side-effectful restore per attempt with a ref.
  • Visual parity: freeze happy-dom trees + Chromium screenshots BEFORE switch; same-build double capture gives the noise floor (30/30 identical); synthetic controls validate the comparator; baseline = git archive develop built in scratchpad (no worktree). Apply: R4 PDF reader/writer (byte scanners, inflate), Step 13 uploads (reader in worker child), any parser fed untrusted input.

LRN-057 | 2026-10-16 | Terminal-failure UX: bind data-safety promises to save status, census every retry surface

  • Message promising data kept ("report kept in this tab") must read real persistence status (quota flag); else variant + core-free rescue (download of in-memory state).
  • Capped recovery → enumerate EVERY failure surface (grep failure keys, retry handlers, full-page degraded states), not only those the patch touched; enforce with ESLint no-restricted-syntax on t('<key>') literals (dictionaries untouched, file-scoped exceptions; later block overrides earlier for same rule).
  • Each "retry" label needs reachable path to the runtime's recovery; runtime-level restart on next call beats per-surface buttons.
  • Rescue must exist in every non-ready state, not only terminal one: a restart loop offline never reaches "stopped".
  • Status listeners from a state machine: notify via microtask, try/catch per listener, never inside load/recover try blocks; stable module-scope subscribe for useSyncExternalStore. Apply: R4 PDF worker failure states, Step 8 avatar upload errors, any capped retry or offline mode.

LRN-058 | 2026-10-17 | Rescue paths need proven restore; remember trapping inputs; sniff and cap before read

  • "Download a copy" is no rescue until an in-app restore exists and a round-trip test proves equality; reuse the reader that already parses that format (here core draft.restore) instead of a new parser.
  • Input that trapped a recoverable engine must be remembered (key = every input of the trapping call, e.g. draft + archive) and re-read only on explicit Retry: each re-read spends a capped recovery and pins dead-instance memory.
  • Untrusted file pick: route by content from first KiB, apply that path's cap on file.size before any full read, decode UTF-8 with fatal: true (refuse, never alter).
  • User text into i18n templates: .replace(re, () => value); string replacement expands $&/$'.
  • Picker opened from a confirm dialog: call input.click() synchronously in the confirm handler (user activation, WebKit). Apply: any export/backup feature, R4 PDF reader worker failures, Step 13 uploads.

LRN-059 | 2026-10-17 | Rust from_utf8_lossy matches TextDecoder; serde_json differs from JSON.parse on overflow and surrogates

  • String::from_utf8_lossy after stripping one BOM = new TextDecoder().decode() (non-fatal): 200,015 random + edge byte strings (overlong, UTF-8 surrogates, truncated, double BOM), 0 diff. Parity holds on tested sequences, not proven in general.
  • JSON.parse vs serde_json: 1e400 → JS Infinity (JSON.stringify writes null), serde_json "number out of range"; lone surrogate escape kept by JS, refused by serde_json; duplicate key last value at first position in both (preserve_order). A JS path that did parse → stringify has side effects (overflow → null, dropped duplicates): reproduce them or declare them. Apply: Rust ports of JS readers of untrusted text (R4 PDF reader, Step 13 uploads, Step 15 server validation).

LRN-060 | 2026-10-17 | wasm-bindgen glue retains its instance until reload; only a terminated worker frees linear memory

  • --target web glue keeps the instance in module scope (let wasm, __wbg_finalize_init); ES module records are never unloaded, so each fresh glue import (?instance=n) keeps its old instance and memory (BLK-012: dead instances retained until reload). Linear memory never shrinks.
  • Memory-heavy one-shot work: reuse the long-lived instance (high-water kept until reload) or run in a Worker terminated after (everything freed). A "disposable instance" on the main thread is a leak, not a release. Apply: R4 import worker and export placement, any future in-browser wasm batch job.

LRN-061 | 2026-10-18 | A multi-budget pre-scan must keep every budget sound, even once another check already refuses

  • R4.2 json_js::prescan returned early at depth > 64 with the partial value count; the PDF probe checked both verdicts, the rescue copy checked values only → a 16 MiB copy nested 65 deep reported 66 values, passed the budget, built 792 MiB (security gate BLOCK, fixed 593893a: count runs to the end, depth verdict kept).
  • Rule: one linear pass serving several guards finishes every measure; an early return for one verdict silently disarms the callers that rely on the others. Controls must never neutralise each other; a refusal path stays bounded in time and memory. Apply: any shared pre-scan / lexer feeding several caps (R4.3 worker, R5 pipeline, Step 13 uploads); test each guard alone with the other verdict already failing.

LRN-062 | 2026-10-18 | Non-finite numbers: follow the JSON actually serialised, not the JS type before serialisation

  • parseVersioned tested typeof version === 'number' on JSON.parse output: 1e999 → Infinity, a number, so the probe accepted; JSON.stringify then wrote null, so the core saw no version → no_attachment. A Rust port that rewrote overflow → null before the probe gave attachment_stripped (3 O8 rows).
  • Fix: probe on a copy where overflowing tokens stay finite numbers (rewrite_overflow_numbers_as_finite, 0), hand the null form to the core. Same family as LRN-059 (overflow, lone surrogates): every JS parse → stringify hop is a transformation to reproduce step by step, in order. Apply: porting any JS reader whose acceptance test ran between parse and stringify (R4 writer inputs, R5 pipeline, server validation).

LRN-063 | 2026-10-19 | wasm linear memory: never grow one big Vec; long-lived chunks big enough not to interleave with transients

  • Growing Vec<u8> for a 44 MiB file in wasm (dlmalloc) peaked 125 MiB: realloc keeps old + new while copying; decode transients (≈ 10 MB per PNG) sit between file and heap top so no in-place growth. Linear memory never shrinks → spike is the high-water for the page.
  • Fixed chunks (never realloc) remove the spike. 1 MiB chunks still cost 0.12 MB per view (long-lived alloc every other raster interleaved with transients → fragmentation); 8 MiB chunks cost 0. Adaptive target 1 → 8 MiB: small files pay one small chunk, big files few long-lived allocs. shrink_to_fit on seal gives slack back.
  • Hand chunks to JS one by one (take_part, freed in module), new Blob(parts): file never held twice across heaps. Apply: any wasm producer of large outputs (R5 pipeline, future image work): measure stage by stage with memory.buffer.byteLength, never trust the estimate.

LRN-064 | 2026-10-19 | Test facts from the produced PDF, not from draw-call spies; recorder order ≠ file order

  • Step 6 goldens were recorded by spying pdf-lib drawText/drawImage: footers recorded after every page's content (global call order). Read back from content streams, facts come page by page. Same set, same within-page order: compare against the golden stably sorted by page.
  • tests/helpers/pdfRead.ts: pdf-lib loads the file, inflates each content stream, parses Tf/Tm/Tj/ET and cm … Do, resolves /F1 through page resources, WinAnsi = windows-1252. Lets 16 roundtrip + 7 goldens cases run unchanged on the Rust output. Apply: when an implementation is swapped under a test that spied the old one, read the artefact instead of mocking the new one; keep the old generator pinned to the old engine (r4.writer-oracles → exportReportArchive).

LRN-065 | 2026-10-20 | Feature unification hides no-default builds; host refusal by resolution, not spelling; control run isolates browser memory

  • cargo test --workspace unifies features across members: crates/wasm enabling pdf-read made core compile in every gate while cargo check -p faunosteo-core (default = []) failed. Apply: gate runs one per-crate no-feature build (cargo clippy -p <crate> --all-targets) whenever a crate has optional features.
  • Refusing wildcard binds by string set fails: getaddrinfo accepts 0, 0x0, 0.0.0, 0::, ::ffff:0.0.0.0, ::%lo. Apply: dns.lookup(host,{all:true}) → refuse if any result in BlockList(0.0.0.0, ::) (scope stripped, type from net.isIPv6(address)), listen on resolved literal, re-check server.address() (its family is 'IPv6', lookup's is 6).
  • Opening before stat-checking type blocks on a FIFO (O_RDONLY): stat path first, then open, then fstat recheck.
  • Browser RSS growth across exports: run the same raster steps with no core call (control) in the same page; same slope + same plateau = browser cache/allocator, not app retention. FinalizationRegistry counters + createObjectURL/revoke ledger + CDP Performance.getMetrics / heap census separate page-held objects from renderer memory; Memory.simulatePressureNotification critical tests reclaimability.

LRN-066 | 2026-10-21 | Recette server must mirror production cache headers; headless never proves native dialogs

  • Offline import (J1.7) failed on owner's Brave + Firefox but harness server serve.mjs sent no Cache-Control on /assets/ while nginx sends immutable: Chromium refuses stale cache entry offline (net::ERR_ABORTED), Firefox offline mode serves it anyway, WebKit headless never serves worker script from cache offline. Apply: any test server standing in for prod copies prod's cache + CSP lines verbatim and the harness asserts them (r4-offline-import.mjs); test "offline" two ways (Playwright setOffline + server killed), they differ per engine.
  • Headless browsers replace OS file dialogs: a frozen <input type=file> picker cannot be reproduced or excluded headless. Apply: write a discriminating human step (Ctrl+O in empty tab offline, kit copied local) instead of claiming a cause.
  • Expected recette result written from an oracle fixture (nologos = fetch 404 mode) described the fixture, not the product rule (editor export always embeds bundled branding; archived branding only via export_from_envelope). Apply: before writing an expected result, trace which code path the recette step actually runs.

LRN-067 | 2026-10-21 | "Known violation" excluded from a verdict hides a real defect; wait before calling a dialog frozen

  • Footer hotlinked zenquality.fr logo since 2026-05-21, same day DEPLOY.md CSP img-src 'self' written; R2 + R4 CSP proofs saw refusal on every page, harness listed it as KNOWN_IMAGE_HOST and excluded from verdict → nobody fixed it for 5 months. Live site sends no CSP yet, so symptom invisible. Apply: a harness never carries a "known" exception longer than one slice; either fix the cause or open a TODO line with owner date. Bundle third-party images (?url, exact remote bytes = no branding change) instead of widening CSP.
  • Owner's J1.7 "picker never opens, browser unusable" = OS file dialog taking ~60 s to open with system network cut (same from Ctrl+O in empty tab). Apply: recette step for any "hang" says wait 2 min before declaring FAIL and records time; a symptom reproduced outside the app closes the app-defect hypothesis, cause of delay stays unclaimed unless traced.

LRN-068 | 2026-10-21 | Contract FILE SCOPE lists itself, memory files by name and every redaction; harness results carry repo-relative paths

  • R4.10 verifier: 8/8 MET but formal gap: contract's own file in the diff, absent from FILE SCOPE ("memory" written vaguely). Apply: FILE SCOPE names the contract path, each .claude/memory/*.md and TODO touched, and gets amended in the same commit as any later scope growth; never drop a CHECK to pass.
  • scripts/browser/lib/app-build.mjs wrote absolute DIST_DIR (user home) into committed results JSON from R4.6 on (older runs relative). Apply: any committed report names paths relative to repo or a placeholder; scan git grep -E "/home/|-home-" before each report commit.

LRN-069 | 2026-10-21 | Runbook syntax fixes need the target's real version; URL sanitiser must re-check its own output

  • Context7 said nginx listen ... http2 deprecated → http2 on;, but live VPS sends Server: nginx/1.24.0 and 1.24 rejects http2 on (unknown directive). Apply: before changing a runbook directive, read the target's version (Server header, nginx -v) and nginx -t both forms in throwaway containers of each version; document both when the fleet straddles.
  • WHATWG URL normalisation can create the escape it was meant to catch (/..//host → pathname //host, same origin for the probe). Apply: sanitiser re-validates the value it returns (not only the input), plus an idempotence test; fuzz with dot segments, %2e, tabs inside ...

LRN-070 | 2026-10-22 | Rust {:e} shortest digits ≠ ECMAScript on exact decimal ties; oracle that re-prints expected through the port cannot see it

Found by R5.1 study. js_number (core json.rs) takes shortest digits from format!("{:e}") (Grisu): exact tie between two shortest candidates → Grisu picks upper, ECMAScript/Python/zmij pick even. 840.1692504882812 (= 840.16925048828125, float32-exact, Horse.svg legacy cx) → Rust …813. Rate: 7,401 / 100,000 float32-exact values in 0..2000, 769 / 100,000 random doubles, zmij (serde_json 1.0.154 formatter, locked) 0. Draft seed has no tie → every R2/R3/R4 suite green, but sheet_contract.rs zod_oracle computes expected = to_js_pretty(oracle.output) → same function both sides → blind. 134 JSON fixtures Node vs Rust pretty: 2 differ (legacy baseline, that value). Apply: shortest-float port → take digits from zmij/ryu-class crate, never {:e}; tie vectors (float32-exact values) in unit tests; oracle expected must be the recorded JS text, never re-printed by the port under test. Any R5 importer emitting legacy coordinates needs the fix first.

LRN-071 | 2026-10-22 | Prettier byte parity for generated JSON/Markdown is cheap: four layout rules + one width table, oracle-probed

R5.2 reproduced Prettier 3.8.3 parser: json over JSON.stringify(v, null, 2) and markdown table alignment in ~350 lines Rust, byte-exact on 968 synthetic probes + 7 seed files + 3 reports. Rules that mattered: objects always expanded (stringify newline after {), array breaks when >1 element and all elements arrays >1, or child breaks, or flat form + trailing comma > 80 cols; broken all-number arrays use fill, others one per line; printNumber drops e+; width = length if all bytes 0x20..0x7F else per code point (controls/combining/VS16 = 0, East Asian wide/fullwidth = 2) after RGI emoji replaced by spaces. Emoji table not reproduced → refuse (UnsupportedWidth), declared. Probe generator in TS (vitest, MAKE_R5_ORACLES=1) sweeping depth × key width × count × digits around the 80-col boundary found both bugs (e+21 form, width fast path) before any real file did. Apply: any port that must match a formatter's bytes: sweep the boundary with synthetic probes written by the formatter itself; transcribe tables from the installed package (same table lives in index.mjs and plugin), never from memory; refuse unreproduced classes loudly instead of approximating.

LRN-072 | 2026-10-23 | serde Option<T> reads JSON null as absent; Zod .optional() refuses it

Found by R5.3 verifier pass 2: changeset scope / position / field declared Option + #[serde(default)] → "scope": null parsed as absent, Zod refused (expected 'self' | 'subtree', received null). Committed data had none → every parity test green, only a hostile input shows it. Core already had js::present (R2) for exactly this; port forgot it. Complement of LRN-048 (serializer side: .optional() absent vs nullable null). Apply: porting a Zod schema to serde: .optional() → default, deserialize_with = "js::present"; .nullable() → js::nullable; add one null refusal case per optional key to the differential oracle.

LRN-073 | 2026-10-23 | In-band markers replacing object identity must be reserved keys refused at input

R5.3 applier replaced TS object identity (touched items) with a transient key "\0touched", stripped after each change. Verifier pass 3: an authored value holding that key was taken for a mark and the cleanup deleted it silently, where TS refused it at the strict gate → silent author-data loss. Fix: refuse any NUL-prefixed key in the changeset at parse (reserved key), test it. Apply: any in-band sentinel (key, id prefix, magic value) gets a reserved namespace, a refusal at the input boundary and a test; never rely on "no author would write that". Prefer out-of-band state (side table by path) when the cost is similar.

LRN-074 | 2026-10-23 | Formatter-parity guard: allowlist + generator sweep, never denylist

R5.4 ported CHANGELOG/REVIEW-REPORT without a Markdown printer: reproduce Prettier's table alignment only, refuse text Prettier would rewrite. Denylist guard leaked every gate round (emphasis, links, autolinks, entities, strong pairs, URL underscores, image refs, nested padded wiki links, underscore paired across code spans, wiki opened in one field closed in another, field segment closing author [ from a code span). Allowlist (letters, digits, single spaces, fixed punctuation, few ruled forms; code spans only the generator alphabet [A-Za-z0-9_:/. -]; list-item fields refuse [[ ]] {% %} whole) + TS-written sweep (798 probes, 400 seeded random, cross-field pairs) converged: rounds 11-14 found 0 silent over ~400,000 TS-vs-Rust cases. Apply: byte parity with a formatter you do not port → allowlist of what the real data uses, refuse rest loudly, sweep frozen by the formatter itself incl. random strings and constructs split across fields/lines; state guarantee as empirical; add each gate-found family to sweep.

LRN-075 | 2026-10-23 | Resource bounds: charge at the allocation site, projection must be a tested upper bound

R5.4 security rounds 6-11 each broke a bound that looked done: table bound checked after raw rows built; records bound checked after a whole op (one op records once per item, each record cloning change texts); weight counted 1/byte while each cloned String costs header + alloc (~56 B for 1-char id); drawings projected from cleaned SVG only, unnamed triggers copy opened view names ×4; projection 477 B under written for a draft with no annotations (fixed parts uncharged). Each time docs claimed "refused before built". Apply: bound = check before the clone/allocation, at every producer (record push, marking, subtree loop); weight ≈ real bytes (64 per node/String + bytes); output projection = upper bound per element + fixed part per file, with a test asserting projected ≥ written on real and degenerate inputs (empty, max-copy); measure hostile inputs at 1/10 of the read cap before claiming a bound in docs.

LRN-076 | 2026-10-24 | Stub suite ≠ real-service recette; record both apart

Context: R5.5 upload tool. 12 loopback-stub tests green; Claude's run vs real local stack refused by permission layer (transfer tool + service key). Owner ran pnpm e2e:sheet-assets by hand → PASS 11/11. Pattern: stub proves tool logic (plan, refusals, retries, no overwrite); only real service proves endpoints, status codes, grants (anon key refused at Storage, not stub). Ship a hand-run e2e script beside stub suite; record each result with its author (simulated by Claude / real by owner), never merge into one "tested". Apply: any tool touching a real service with a privileged key: stub tests in cargo test, owner-run e2e script, both results in RUST.md + TODO separately. Owner validated 2026-10-24.

LRN-077 | 2026-10-25 | Privilege decision needs proof at the call site holding the evidence

Context: R5.6 M1. Alias granted at export from snapshot's claimed value; export never saw the loaded sheet. Load-time flag alone also insufficient (pub mutable document/reference). Pattern: put the decision where the evidence object lives (build_sheet_snapshot holds LoadedSheet), keep private verified state set only by the trusted constructor, and recompute the proof at decision time; every other site stays strict equality. Make the raw comparison crate-private so no caller can skip the proof. Apply: any equivalence/allowlist privilege (aliases, migrations, trust marks): one decision method on the verified object, recompute, strict elsewhere, negative tests on the direct API not just app paths.

LRN-078 | 2026-10-25 | Before deleting old engine, census contracts only its test code checks

Context: R5.7. Oracles + Rust parity looked full; case-by-case map of 407 TS cases found 15 anatomy + 1 domain contracts no Rust test checked (612-leaf fates, 26 legacy ids, region inference, R5.1 ledger rows, overlay removal, halo, CHG-000, dollar tag, viewBox, cite of added ref, move via renamed path, folder file list, map vs oracle per entry). Oracle generators' own asserts carried them. Pattern: ledger row per old case (contract, disposition, live target, oracle); census test checks target is non-ignored #[test] fn and oracle file exists; port gaps before git rm. Apply: any engine deletion (R-phases): map every case first, "oracle covers it" is a claim to prove per case. Owner validated 2026-10-25.

LRN-079 | 2026-10-25 | Optional peer in lockfile ≠ live use of deleted engine

Context: R5.7 C6. After removing anatomy, tsx stayed in pnpm-lock.yaml as vite's optional peer (optional: true, no importer, no bin); pnpm install keeps it, dedupe --check clean; only hand edit/override would drop name. Contract said "tsx gone" → false NOT-MET. Pattern: prove use by pnpm why <pkg> -r path + importer blocks + manifest/script/source census, not lockfile name grep. Never hand-edit lockfile or add override just to drop a name. Apply: dependency-removal clauses state objective (no declared dep, no script, no import), allow transitive/optional peers; census guards declared deps and optional: true. Owner validated 2026-10-25.

LRN-080 | 2026-10-25 | Throwaway Supabase stack beside DEV: test migrations, grants, sign-up and HTTP without touching DEV

Shown on this host (Docker rootless, daemon ip 127.0.0.1, CLI 2.120, images postgres 17.11.0.004, gotrue v2.197.0, storage v1.79.36, postgrest v16.4, mailpit v1.31.3): own network + -p 127.0.0.1:<57xxx> per service, no -v (images declare no VOLUME → nothing to drop at teardown, docker rm -f of literal names suffices). db needs the CLI's role-password init (/etc/postgresql.schema.sql via --entrypoint sh -c); GoTrue + storage-api migrate their schemas on start; then the CLI's own runners take --db-url: migration up (records history like DEV), test db (pg_prove, rows unchanged), gen types. Upgrade path = --workdir copy holding the older migrations, then migration up from the repo. Real sessions prove what PGlite cannot: concurrency (two psql sessions), GoTrue sign-up/confirm via Mailpit API, PostgREST role refusals, residual GoTrue-admin path. pg_dump -Fc as postgres with the container's $POSTGRES_PASSWORD dumps auth data too; restore with --no-owner keeps every row, prints only managed-object privilege errors. Limits: one host; not a hosted project; vault/realtime/edge absent; CLI may change bind/runner behaviour across versions. Apply: scripts/db-sandbox.sh (pnpm db:sandbox) for every migration step; DEV changes stay owner actions.

LRN-081 | 2026-10-25 | supabase gen types --db-url to the sandbox needs ?sslmode=disable

CLI 2.120 against the sandbox PostgreSQL (127.0.0.1:57432, image 17.11.0.004, no TLS configured): without the option → DbConnectError … tls error (The server does not support SSL connections) and the error JSON lands on stdout (piping it to prettier gives a confusing syntax error). With ?sslmode=disable the output matched the committed database.types.ts byte for byte for the pre-existing schema (same generator as --local). Same URL works for migration up, test db. Not checked: other CLI versions, TLS-enabled targets (keep TLS there). Apply: any --db-url to a local non-TLS Postgres; never pipe generator output without checking the exit code.

LRN-082 | 2026-10-25 | Native modal <dialog> in Chromium: three traps, one test blind spot

Shown on Chromium 156 (Playwright 1.64.1): (1) Escape cancelled only via cancel event → second Escape without user activation closes anyway (close-watcher anti-abuse); preventDefault on keydown Escape stops the close request entirely. (2) Initial focus = scrollable panel when content long, first button otherwise → focus first tabbable explicitly. (3) Tab past last control → document.hasFocus() false one step (browser UI), then back to first; page never reached. happy-dom: showModal only sets open (no inert, no focus) → unit tests prove wiring only. Exit animation (motion, 180 ms) masked async focus loss: a fast sandbox RPC settled before unmount, test green with defect → slow the RPC via page.route + route.fallback() to discriminate. axe color-contrast false positives while entrance animation runs → wait document.getAnimations() settled. Apply: any modal or async confirmation test; mutation-check browser tests.

LRN-083 | 2026-10-26 | PL/pgSQL traps met writing M3

(1) A parameter cannot share a name with a returns table output column (species_id filter vs output): CREATE fails "parameter name used more than once" → rename the parameter. (2) SQL or does not promise left-to-right: p !~ '^[0-9]{4}$' or p::integer > … can cast first and raise 22P02 echoing the value → two IF statements. (3) '2015-02-30'::date raises 22008, not 22P02 → catch data_exception (class 22). (4) pgTAP audit rows of one transaction share occurred_at (now()) → order also by action collate "C": ICU sorts _ before ., C the reverse. Apply: any plpgsql RPC parsing text input; any pgTAP string_agg over same-transaction rows.

LRN-084 | 2026-10-26 | FK backstop hides an authorisation-order bug; only a lock-wait probe shows it

Context: M3 mutation M9 removed the workspace filter on the client lookup in create_animal_client_relation. pgTAP stayed green: the composite FK refused the row and the RPC mapped it to the same not_found. Real effect: B's call took FOR SHARE on A's client → B waited on A's lock (timing side channel, cross-tenant contention). Caught only by sandbox test: A holds the row FOR UPDATE 2 s, B's refusal must answer < 1 s (measured 15 ms; mutated 1 749 ms). Apply: for every RPC that locks rows, a real-session test where the victim holds the locks and the attacker's refusal must be fast; equal error text alone does not prove "no lock outside the workspace".

LRN-085 | 2026-10-26 | Focus after drawer navigation: page inert during exit animation, StrictMode cleanup kills listeners

Context: V1-1.5 page heading focus on open. Drawer (native modal dialog + motion exit 200 ms) keeps page inert → heading.focus() fails; then dialog close restores focus to menu button. Fix: callback ref on heading; if dialog:modal present, one-shot close listener + setTimeout(0) → focus after ModalDialog's microtask restore. Trap: useEffect cleanup removing the listener ran in React StrictMode's simulated unmount (dev) → listener gone; keep one-shot listener, check isConnected, no cleanup. Also: a page that renders its h1 after loading needs a callback ref, not a mount effect. Traced with a temporary focusin/close logger spec. Apply: any focus-on-navigation or focus handoff next to a modal with exit animation; never rely on effect cleanup for listeners that must survive StrictMode.

LRN-086 | 2026-10-26 | Playwright HTML report keeps every typed value in step titles

Context: V1-1.5 report check. locator.fill(value) step titles hold the value; the shell suite's HTML report (embedded base64 zip) held the throwaway accounts' passwords, contrary to BROWSER_TESTS.md ("no trace" was thought enough). Found by decoding the zip in memory and counting fixture patterns. Apply: suites typing secrets → reporter: [['list']] (no html, no trace); audit reports by decoding the embedded zip, not by grepping the html. Also: never run Prettier on a whole src tree here (EVAL-037 repeat) — format new files only.

LRN-087 | 2026-10-26 | TS does not type-check hyphenated props on components: Card dropped aria-labelledby silently

Context: V1-1.6 e2e locator section[aria-labelledby=…] found nothing. Card (props children/className/as) ignored aria-labelledby; TypeScript accepts any aria-*/data-* attribute on a component without declaring it, so every V1-1.5 section card shipped unnamed; axe never flags an unnamed section (no violation), unit tests queried by heading text. Fixed by declaring and passing the prop. Apply: wrapper components that render landmarks must declare and forward aria-* explicitly; test named regions by role + name (getByRole('region', {name}) or the attribute selector), not only by heading text.

LRN-088 | 2026-10-26 | useT() returns a new function each render: never a dependency of a data effect

Context: V1-1.6 record picker. A search callback formatting rows with t would change every render → effect re-runs → request loop. Fix: search callbacks depend on ids only (useCallback([workspaceId])) and return raw rows; a toItem(row) prop formats at render (a language switch needs no new search). Apply: in this app, keep t/dict out of useCallback/useEffect deps of anything that fetches; format at render. Same for any hook returning fresh functions.

LRN-089 | 2026-10-26 | Playwright on the sandbox: late replays fail after the test; axe target-size flags controls under a sticky bar

Context: V1-1.6 e2e. (1) routeToSandbox replays with route.fetch then fulfill; a request still in flight when the last assertion passed hit « Fetch response has been disposed » at context close → test failed after success. Fix: afterEach(context.unrouteAll({ behavior: 'ignoreErrors' })); and end tests on a state that needs the last reload (e.g. relations reloaded). (2) At 375 px, axe target-size failed on 44 px buttons partly under the sticky top bar when the page was scrolled to the bottom state under test; scanning after scrollTo(0,0) passes; documented as a limit, not hidden. Apply: suites that proxy requests in route handlers → unrouteAll ignoreErrors per test; phone axe scans of bottom-of-page states → scan from top and say why in BROWSER_TESTS.

LRN-090 | 2026-10-26 | Supabase CLI 2.120 side effects on a shared local stack: test db, status, migration up

Context: V1-1 DEV preflight, CLI read from bundled binary strings, not docs. (1) supabase test db runs create extension if not exists pgtap with schema extensions, then drop extension if exists pgtap only when absent before: transient DDL; interrupted run leaves pgtap. (2) supabase status default output prints SERVICE_ROLE_KEY, SECRET_KEY, JWT_SECRET; -o env | grep '^API_URL=' safe. (3) pnpm db:types:check without -s adds 2 > header lines from pnpm → count drift with pnpm -s. (4) pg_dump -Fc of postgres restored --no-owner into scratch db of same image: 26 privilege refusals only (vault, pg_stat_statements_reset, pg_reload_conf, default privileges, grant options); md5 of t::text per table (timezone UTC) identical after restore → good restore proof. (5) Storage file backend keeps bytes in container volume /mnt; DEV had 11 files for 2 rows (reset leftovers). Apply: any procedure on DEV → read CLI behaviour from installed binary; read-only SQL via PGOPTIONS default_transaction_read_only; compare fingerprints, not only counts.

LRN-091 | 2026-10-26 | Restore with "expected errors" never validated by message count; filter TOC, exit 0

Context: V1-1 restore check. LRN-090 (4) called 26 pg_restore errors "privilege refusals" and report double-counted them (28): wrong frame. Real: 26 TOC entries postgres cannot replay under --no-owner on same Supabase image: 18 DEFAULT ACL of supabase_admin/supabase_auth_admin, 5 vault ACL (grant option to self), ACL pg_reload_conf + pg_stat_statements_reset, COPY vault.secrets = data load fail, lossless only with vault empty. Each failing entry also carries other grants (service_role, anon). --no-acl loses app grants; --exit-on-error alone stops at COPY. Fix: pg_restore --list → exclude exact entries by anchored regex → count per kind must equal catalog prediction (D default ACL rows + 8) → --use-list --single-transaction --exit-on-error → exit 0, empty log, rows md5 + effective ACL (acldefault) identical. pg_dump drops ACL equal to default → compare effective, not stored. Expected count is per-instance: DEV D=21 vs sandbox 18 (supabase_functions schema). Apply: any restore check → real exit status from shell, every failing command classified (object, cause, data impact), conditions explicit (empty table), prefer filtered TOC with exit 0; derive expected exclusions from target catalog, never from rehearsal host; never widen pattern to go green.

LRN-092 | 2026-10-27 | Restore rehearsal on sandbox dump proves nothing about DEV-only objects; first real-dump run

Context: V1-1 step 3b, first run on real DEV dump. Filtered TOC (29 = D+8) right, but exit 1: GRANT USAGE ON SCHEMA supabase_functions names cluster role supabase_functions_admin, absent in sandbox (roles are cluster-level, not in dump). Rehearsal on sandbox dump (LRN-091) could not see it. Fix: NOLOGIN no-privilege role in sandbox only → exit 0, empty log, 28+15 identical. Apply: restore check on real dump before trusting rehearsal; roles named by ACL/owner entries must exist in target cluster (--no-owner needs name, not powers); never widen exclusions, fix the target; create minimal role, never copy login/CREATEROLE/password.

LRN-093 | 2026-10-27 | pgTAP on a used stack: global queue counts and fixed seed keys break; lease base work in-tx, scope to fixture

Context: db:test on DEV after M1-M3. 007 inserted seed drawing key already uploaded (unique collision, 4 assertions never run); 010 counted 13 DEV due purge rows. Audit found more: claim_avatar_jobs takes oldest uploaded row, leftovers sweep whole bucket, expire_pending_uploads counts all stale rows. Clean sandbox / PGlite never show it. Fix: 007 seed key in pg_temp table, confirmation cleared in-tx, insert only if absent + assertion "object once"; 010 section 0 leases base's due purges + jobs and expires stale uploads in-tx (capped loop) + setup assertion, leftovers by fixture key prefix. Proof: reproduce on sandbox with fictitious conditions first, mutation run (mutation + suite body in one rolled-back tx) on clean and loaded base, old vs new detection sets compared. Apply: SQL test touching a worker queue or shared bucket → neutralise or scope pre-existing work inside the test tx, never count globally; validate on a sandbox seeded like the target before running on it.

LRN-094 | 2026-10-27 | "Page scrolls sideways at 375 px": measure before CSS; zoom fakes it, implicit grid track hides a real one

Context: V1-1 DEV acceptance RESP-01. Owner saw whole-page sideways scroll everywhere at 375 px (DevTools responsive). Sandbox sweep (Chromium mobile + desktop with scrollbars shown via ignoreDefaultArgs: ['--hide-scrollbars'], WebKit iPhone, Firefox; 280-430 px) found none at 375; owner then measured DEV with a console snippet (cw/sw + topmost offending boxes, classes only): no overflow without zoom → browser zoom was the cause. Same sweep with long account e-mails found a real defect: dashboard grid gap-4 md:grid-cols-2 has no explicit column below md → implicit auto track = cards' min-content → truncate e-mail never truncates, cards past screen from ~31 chars at 320 px. Fix: grid-cols-1 (minmax(0,1fr)) + e-mail wraps (min-w-0 [overflow-wrap:anywhere]). Test sweeps 320-430 + desktop with long values, proven failing on old code. Apply: overflow report → ask how observed (zoom, preset, device type), give owner a read-only console probe for DEV, reproduce with realistic max-length values on sandbox; a grid used as a single column on phones needs grid-cols-1, else one unbreakable value widens every card.

LRN-095 — pgTAP across PGlite and the real Supabase image: privileges, roles, storage triggers (2026-10-28)

Adapting pgTAP across PGlite and the real Supabase image: the fixtures must respect privileges the shim doesn't enforce.

  • auth.sessions/auth.mfa_factors added to the PGlite shim (supabase-shim.sql) with the pinned image's enums (aal_level, factor_type, factor_status) and NOT-NULL columns, so aal2-session checks run Dockerless. A test that checks a live-aal2 session fabricates the session + factor rows directly.
  • API roles (authenticated, service_role, anon) hold no privilege on auth.*: every test mutation of auth.users/sessions/mfa_factors must run under reset role (postgres), never while set local role authenticated. Same for seeding public.* rows a trigger guards (the content trigger needs auth.uid() set, so direct version seeding carries a request.jwt.claims sub).
  • Real-stack-only divergences: storage.objects has a storage-API trigger forbidding direct DELETE/UPDATE (PGlite allows it) — assert "no write policy" via pg_policies census, not a runtime throws_ok. PostgREST maps a raise ... errcode='42501' to HTTP 403 with code 42501 (not P0001). An EXECUTE-revoked function raises "permission denied for function" before its own body — test that, not the body's custom error.
  • A narrow operator read RPC returning JSON null for "no row" is cleaner than raising (PostgREST won't surface a raise as a 404 the client recognises); the tool treats null as absent.
  • Real GoTrue proves what fabricated rows can't: pnpm db:sandbox test enrol+verify TOTP → aal2 token, then the role RPC works at aal2 and is refused (mfa_required, 403) at aal1; F18 cross-revoke under real concurrency leaves one owner.

LRN-096 — jsonb_path_query row iteration is quadratic; numeric text has no exponent (2026-10-28)

PostgreSQL 17 jsonb_path_query (SRF) builds its whole match list on the first call and pops rows with list_delete_first -> O(n^2) when iterated row by row (FOR loop, count(*)): 200k matches 2.2 s, 400k ~27 s. Early exit saves nothing. Use one jsonb_path_query_array(...) then jsonb_array_elements (linear: 600k 0.4 s). Also: numeric prints no exponent, so octet_length(jsonb::text) of 1e131071 x 9000 (90 kB payload) = 1.2 GB -> raw OOM; sum printed numbers first. Apply to any SQL walk over user jsonb (status walks sheet_all_reviewed, sheet_has_to_confirm use the same SRF pattern, bounded today by core caps).

LRN-097 — serde tagged enums and owned-Value reads double the wasm size (2026-10-29)

serde derive cost in wasm: internally/adjacently tagged enums buffer through serde's private Content, so every type reachable through them gets a second Deserialize monomorphization (ContentDeserializer); serde_json::from_value (owned Value) is a third, distinct from T::deserialize(&value). V1-2.2 measured: edit commands with tagged derive + owned from_value of the document = 635.7 KB gzip (budget 600); commands read via Value then T::deserialize(&inner), document via &Value = 582.7 KB. Apply: in crates reaching wasm, read tagged wire forms through serde_json::Value with hand dispatch on the tag (keep ts-rs shape with ts(tag, content, rename_all)), always deserialize documents from &Value, measure pnpm wasm:build gzip after any new op; probe by removing one export at a time (cargo release wasm + gzip -9) before guessing.

LRN-098 — Real SVG exports vs the allowlist; what the tree never reads (2026-10-29)

Real vector exports vs R3 allowlist: cairo 1.18 writes colours as rgb(20%, 40%, 70%); allowlist drops any function call in presentation attributes → cleaned drawing keeps shapes, loses colours. ImageMagick 7 MVG export writes style settings as bare text between elements (dropped silently, not a "removal"). Property test generators for SVG must avoid repeated attribute names (XML malformed) or most cases test nothing. Apply: classify fixtures by actual outcome before writing expectations; report colour loss on cleaning as an owner decision (allow numeric rgb()/rgba() = reader change); dedupe attribute names in generators.

Also: the tree drops processing instructions and comments, so "read with no removal" is not "bytes safe": <?xml-stylesheet href=…?> survives in stored bytes; scan PIs separately (fail-closed) wherever original bytes are kept.

LRN-099 — SVG local references: one strict grammar shared by every stage (2026-10-30)

Context: V1-2.2 security round on 17d9199: url(#%61) and Chromium url('#<TAB>a') passed dangling check, per-view scoping, expansion budget; browsers (Chromium 1248, Firefox 1555) resolved them. Root cause: reader, cleaner, composer each tolerated spellings browser normalises differently. Fixed a678faa (sanitize::local_url_target), f1ef6a4 (&#9; &#10; &#13; spellings, composer coarse url( count sharing no parser).

Pattern: one strict grammar for local references (href, xlink:href, url(#id)), shared by cleaning, validation (reader, verdict, preview, PDF snapshot gate), composition. Any encoded or ambiguous spelling (%XX, entity, tab/space/unbalanced quote inside, empty or non-ASCII id, url( glued to longer name) = active content, refused, never normalised. Composer check fail-closed, independent of reader parser.

Future application: any new SVG/CSS consumer (editor page, PDF, preview, V1-2.5/2.6) reuses the grammar, never its own parser. Hostile tests written apart from the reader, asserting browser behaviour, not core behaviour.

  • Status (2026-10-30): superseded by LRN-100

LRN-100 — SVG local references: one strict grammar, same reading in every stage (2026-10-30)

Context: V1-2.2 security round on 17d9199: url(#%61) and Chromium url('#<TAB>a') passed dangling check, per-view scoping, expansion budget; browsers (Chromium 1248, Firefox 1555) resolved them. Root cause: stages tolerated spellings browser normalises differently. Fixed a678faa (sanitize::local_url_target), f1ef6a4 (&#9; &#10; &#13; spellings, composer coarse url( count). Supersedes LRN-099 (wrong on glued names).

Pattern: one strict grammar for local references (href, xlink:href, url(#id)), same interpretation in cleaning, validation (reader, verdict, preview, PDF snapshot gate), composition, browsers. Non-strict url( spelling (%XX, entity, tab/space/unbalanced quote inside, empty or non-ASCII id) = active content, refused, never normalised. url( glued to longer name = another function (removed in CSS attrs, kept elsewhere), not a reference.

Trap: independent check must share grammar rules, not just avoid parser. f1ef6a4 composer count treats glued xurl( as reference → reader accepts, verdict passes, view.canvas refuses unscoped_reference, PDF draws (final review 2026-10-30, LOW, availability only).

Future application: new SVG/CSS consumer reuses grammar. Hostile tests written apart from reader, asserting browser behaviour; every fail-closed branch gets a test reaching it. Supersedes LRN-099.

  • Status (2026-10-30): superseded by LRN-101

LRN-101 — SVG local references: one strict grammar, reader and composer agree by construction (2026-10-30)

Context: V1-2.2 security round 17d9199: url(#%61), Chromium url('#<TAB>a') passed dangling check, per-view scoping, expansion budget; browsers resolved them. Fixed a678faa (sanitize::local_url_target), f1ef6a4 (entity spellings, composer coarse url( count). Final review 2026-10-30: composer count also saw glued xurl(#a) reader kept in class/result/values → verdict passed, canvas refused unscoped_reference, PDF drew. Fixed by sanitize::urls_unglued (reader removes any attribute holding a url( url_openings does not read). Supersedes LRN-100.

Pattern: one strict grammar for local references (href, xlink:href, url(#id)), same reading in cleaning, validation (reader, verdict, preview, PDF snapshot gate), composition, browsers. Non-strict url( (%XX, entity, tab/space/unbalanced quote inside, empty or non-ASCII id, backslash) = active content, file refused. url( glued to longer name = attribute removed, any attribute. Reader keeps only values whose every url( is a strict reference → composer check true by construction.

Trap: independent defence-in-depth check must agree with reader on what reader keeps; else fail-closed check becomes availability bug. Every fail-closed branch needs a test reaching it (tree built outside reader).

Future application: new SVG/CSS consumer reuses url_openings/local_url_target, never own parser. Hostile tests written apart from reader, assert browser behaviour. Supersedes LRN-100.

LRN-102 — Unquoted heredocs expand backticks: quote the delimiter, scan before commit (2026-10-30) (2026-10-30)

Pattern: unquoted heredoc (<<EOF) runs command substitution on backticks and $(…) inside body. Markdown/Rust doc text with `id` became output of id (uid, groups incl. sudo, lxd) inside test doc comment; caught by fresh verifier before commit (V1-2.2 K, 2026-10-30). Same run: `tests/svg_reserved_ids.rs` and `snapshot_invalid` erased silently (shell errors only on stderr).

Context: any shell-written file holding backticks: Rust/TS doc comments, markdown, commit bodies, python snippets passed via python3 - <<EOF.

Application: always quote delimiter (<<'EOF', <<'PYEOF') unless expansion wanted; prefer Write/Edit tools for prose; before commit grep added lines for uid=, gid=, home paths and empty backtick pairs; treat command not found lines during a file write as corruption signal, re-read file.

  • Status (2026-11-02): superseded by LRN-110

LRN-103 — SVG pointer-events all hits the stroke area even unpainted: hitboxes declare stroke none + visibleFill (2026-11-01)

Pattern: SVG pointer-events="all" hits fill AND stroke area whether painted or not. Transparent hitbox with no own stroke-width inherits ancestor's: root stroke-width="2000" widened every point hitbox, last one took 13 of 19 equine clicks (Chromium, WebKit). stroke="none" alone does not shrink hit area under all.

Context: V1-2.2 lot B (2026-10-30/11-01), marker layer hitboxes on editor canvas.

Application: invisible capture surface declares its own geometry + rule: stroke="none" + pointer-events="visibleFill" (hit = fill only; transparent fill still counts as painted). Visible element that should win → visiblePainted. Never rely on inherited stroke for a hit area; test with hostile root stroke in 3 engines.

LRN-104 — Precomputed click coordinates go stale when the page moves after the first interaction (2026-11-01)

Pattern: click coordinates computed once (boundingBox before first click) go stale when page layout moves after first interaction. Canvas harness listed recorded clicks above canvas: first click grew list, canvas shifted down, later precomputed points hit wrong marker/nothing. Looked like hit-test bug.

Context: V1-2.2 canvas click proofs (Playwright, e2e/harness/canvas.tsx), 2026-10-30.

Application: recompute target box right before each press (centreOf per click), or keep layout fixed (output with fixed height, overflow:hidden). Treat "first click right, next ones wrong" as layout shift first, hit-test second.

LRN-105 — WebKit snaps real taps and clicks to whole CSS px: press with 1.5 px margin, else elementFromPoint (2026-11-01)

Pattern: WebKit snaps real input to whole CSS px. Playwright touchscreen.tap and mouse.click at fractional coords land on rounded pixel; hit test then answers rounded point. Chromium keeps fraction on click, rounds tap.

Context: V1-2.2 canvas click proofs, WebKit 27.2 (Playwright 1.64.1), desktop 1280 and iPhone SE 375 emulation, 2026-11-01. Measured: tap at x 100.1 lands right of edge at 100.4; click at 100.9 lands left of it. Two junction-edge tests failed only on WebKit until margin added.

Application: real presses keep ≥ 1.5 px margin from any edge they test. Below that margin ask document.elementFromPoint at exact point instead of pressing. Never read a WebKit-only edge miss as hit-test bug before checking snapping.

LRN-106 — Firefox getBoundingClientRect drifts (1/60 px units, stroke included); confirm by painted pixels (2026-11-01)

Pattern: Firefox getBoundingClientRect drifts from rendered geometry: client rects in 1/60 px app units, and include stroke of element. Rendering itself exact. Size checks via client rects in Firefox show error up to 0.4 % (24 % on 0.067 px hitbox) though pixels are right.

Context: V1-2.2 frame and visible-size probes vs Rust f64 expectation, Firefox 157 (Playwright 1.64.1), preview box 286 × 310, 2026-11-01. Chromium 156 / WebKit 27.2 agree with core ≤ 8.2e-5 relative on same cases. One-unit frame: Firefox rects 3.3 % off 286 px/unit while painted pixels exact.

Application: compare geometry across engines with stroke none on probed element, and confirm Firefox outliers by painted pixels (canvas/screenshot count) before calling a rendering gap. Report Firefox rect gap as measurement artifact, not defect.

LRN-107 — WebKit and Chromium stop painting SVG at tiny viewBox spans (f32): floors from painted pixels (2026-11-01)

Pattern: WebKit and Chromium stop painting SVG at tiny viewBox spans. Frame span 2⁻⁷ → WebKit paints nothing; Chromium drifts at 2⁻¹⁴ (0.46 px), paints nothing at 2⁻²⁰; Firefox exact at every span. f32 view transform the cause.

Context: V1-2.2 frame range rules, disc a quarter of frame in 286 px box, painted-pixel count, WebKit 27.2 / Chromium 156 / Firefox 157 (Playwright 1.64.1), 2026-11-01. First span floor 2⁻²⁰ withdrawn on this measure; floor set to 1 unit (factor 32 from WebKit's last exact span 2⁻⁵).

Application: bound SVG frame spans and offsets by browser f32 range before trusting geometry; derive floors from painted pixels in all three engines, never from f64 math alone.

LRN-108 — Chromium touch emulation sends taps ~10 px around point disc to the point; WebKit does not (observation, not contract) (2026-11-01)

Pattern: Chromium touch emulation redirects taps near small targets: in V1-2.2 tap grid, taps up to ~10 px around point marker's visible disc went to the point, not to zone under finger. Not seen under WebKit. Experimental, browser-dependent observation, never a selection guarantee.

Context: V1-2.2 interior rule, Playwright 1.64.1 touch projects chromium-320 / chromium-375 vs webkit-375, equine main view, 2026-11-01. Taps at zone witness centre landed on junction points; zone taps recorded 18/21 (caudal) to 195/195 (cervical) at 320. Tool .claude/audits/2026-11-01-v1-2-2-interior-tools/.

Application: Chromium touch tests press away from point discs (clearest fill point, margin) or ask elementFromPoint. Never use this tolerance as functional contract: explicit selection rules and Rust core guarantees stay authority (owner 2026-11-01).

LRN-109 — M6 worker musl image: verify child at caps needed brk, decode never did; derive seccomp in real image per child path (2026-11-01) (2026-11-01)

Pattern: In M6 worker musl image, allocator needed brk syscall when verify child heap grew at caps; decode paths measured before never needed it. Seccomp policy must be checked in real image for each new child path. Observation scoped to this image and this measure: not generalised to all allocators or all musl environments.

Context: V1-2.3 verify child, rust:1.99.0-alpine3.24 build (musl mallocng), distroless runtime, 2026-11-01. At-caps fixture under full filter died SIGSYS; strace derivation (crates/worker/scripts/derive-seccomp.sh) in Docker test stage showed brk only missing call. Decode traces (R1) showed neither brk nor mprotect. Owner approved brk in shared filter (brief 2026-11-01), wording of this entry owner-validated.

Application: new child command or new input path (bigger frames, other library) → rerun seccomp derivation inside real image on that path before trusting allowlist; add a syscall only when trace proves it, with trace as justification; never infer from native glibc runs.

LRN-110 — Bash traps that reached DEV: backgrounded cd list, unquoted heredoc backticks; absolute verified cwd, env validated in-script, rules in sub-agent briefs (2026-11-02)

Pattern: two Bash traps made a DEV-targeting test run from the main checkout (2026-11-01, 23:03:49 and 23:10:59 UTC, 13 GET each on DEV, no write seen). (1) cd /path && cmd & backgrounds the whole AND-list in a subshell: the caller's cwd never changes, next commands run where the shell was. (2) Unquoted heredoc (<<EOF) runs command substitution on backticks and $(…) in its body: a TODO text holding `pnpm e2e:sheet-assets` executed that command (LRN-102 had already caught `id`; its rule was not applied).

Context: orchestrator shell writes (python via python3 - <<EOF, markdown, TODO, commit bodies) and sub-agent test commands in a multi-worktree repo whose other checkouts still hold old scripts that read DEV keys (supabase status). Rule: a wrong cwd must never be able to reach DEV.

Application: quote every heredoc delimiter (<<'EOF', <<'PYEOF') unless expansion is wanted, pass values as arguments; prefer Write/Edit for prose. Run commands with an absolute, verified directory (git -C <abs>, pnpm --dir <abs>, [ "$(pwd -P)" = <abs> ] before acting); never cd X && cmd &. Validate the environment before any side effect (target URL, key issuer, container name) inside the script itself, so its safety never depends on cwd. Put these rules in every sub-agent brief that may run shell commands, with the explicit ban on running scripts from other worktrees. Supersedes LRN-102.

LRN-111 — Closing modal drawer leaves page inert: e2e typing lost until dialog gone (2026-11-02)

Context: V1-2.5 e2e P1 at 375 px: search fill lost 2/4 full runs (8 cards, not 1). Test clicked drawer link, saw heading + first card, filled search at once. Pattern: native <dialog> showModal kept mounted through motion AnimatePresence exit → page behind inert ~200 ms; Playwright fill there goes nowhere, intermittently under load. Fix in test: after drawer link click, expect(dialog).toHaveCount(0) before typing. Proof: 1/16 red repro, 32/32 after. Apply: any e2e acting right after closing a modal drawer/dialog waits for it gone; flaky "input ignored" → suspect inert from closing modal first. Keep failure snapshot (check:all e2e:ui wipes test-results).

LRN-112 — GoTrue v2.197 MFA: aal2 needed for password/email change; factor removal downgrades only its sessions (2026-11-02)

Context: V1-2.5 sandbox proofs on GoTrue v2.197.0 (mfa-behaviour.sandbox.ts, IDENTITY.md §4.1). Pattern: once a TOTP factor verified: password change and recovery-link reset refused at aal1 (401 insufficient_aal) → reset/change UI must step up first; email change same. Removing verified factor downgrades only sessions last verified with that factor; their access token keeps aal2 claim until expiry (has_mfa true, has_aal2_session false). supabase-js mfa.listFactors().totp hides unverified factors → read all. Apply: never assume aal from claim alone for sensitive RPCs (session row check); any password/email flow on MFA accounts needs a step-up path; factor lists show unverified ones.

LRN-113 — GoTrue v2.197 TOTP reuse observed; Storage 400 with statusCode 409; fresh sandbox, order test-db, e2e:shell, test (2026-11-03)

Context: V1-2.5 checkpoint gates (2026-11-02/03) on sandbox pnpm db:sandbox (GoTrue v2.197.0 image defaults, Storage API of the pinned Supabase images). Pattern:

  1. TOTP reuse, OBSERVED on sandbox only (IDENTITY §4.1 case 11), no general guarantee: GoTrue keeps no used-code record. Code C of step N accepted by session A, by second aal1 session B, by A again; session D in step N+1 accepted (one step skew); session E in N+2 refused 422 mfa_verification_failed. Span 30-60 s, replayable by any session holding password within it. CLI/DEV config sets no replay option, same behaviour expected but unmeasured; other GoTrue versions/configs unverified.
  2. Storage duplicate upload: answers HTTP 400 with body statusCode: "409" (KeyAlreadyExists), not HTTP 409. Delete of missing object likewise HTTP 400 + statusCode 404. Test/client must read body statusCode; any other 400 still fails.
  3. Sandbox suites share one stack: e2e:shell seeds content-addressed drawings + working copies that later test cases meet (duplicate upload, working_copy.exists), so a case green only from 2nd run or only after another suite hides defects. Gate run = fresh stack (db:sandbox down + up fresh), order test-db → e2e:shell → test, each case robust to state the earlier suites leave; never re-run until green. Apply: never cite TOTP span as a guarantee (measured fact + version); Storage error handling reads body statusCode; V1-2.6+ gates start from fresh sandbox in that order, report state-dependent failures instead of masking them.

LRN-114 — Worktree in session scratchpad dies with harness cleanup; durable path + tracked ledger (2026-11-04)

  • Context: V1-2 worktree lived in a past session's scratchpad (/tmp/claude-1000/<project>/<session>/scratchpad/v1-2). 2026-11-04 13:08 harness cleanup of ended sessions removed it (and other old session dirs) mid V1-2.6 execution.
  • Lost: uncommitted lot H work, uncommitted lot G review fix, git-ignored SDD workspace (briefs, reports, rulings ledger). Kept: every commit — pushed by gitflow hooks (origin at 8343528).
  • Pattern: long-running worktree → durable path outside /tmp and outside session dirs (now /home/bchanot/Documents/faunosteo-v1-2). Rulings, contract changes, findings and resume checkpoints → git-tracked file, committed + pushed after each validated lot. Scratch (SDD briefs/reports) may stay ignored; nothing needed to resume lives only there or in an agent's context.
  • Recovery recipe: git worktree list --porcelain → git worktree prune --dry-run --verbose (only entries whose dir is gone; check their commits reachable from a branch) → git worktree prune → git worktree add <durable path> <existing branch> → HEAD = origin, tree clean → pnpm install --offline, pnpm wasm:build (ignored build outputs).

LRN-115 — Playwright label locator hits outgoing page during navigation (2026-11-04)

Playwright getByLabel resolved on OUTGOING page during navigation: sheets list filter « Espèce » (#filter-species) and create form field « Espèce » share label; selectOption hit list filter before create route mounted, choice lost, looked like product remount (V1-2.6 Lot K, 3/3 repro, refuted by capture-phase change listener). Rule: after a navigation, wait for destination landmark (page h1 « Nouvelle fiche ») before any label-based locator. Instrument native events before blaming a remount.

LRN-116 — Native dialog exit animation drops keystrokes (page inert) (2026-11-04)

Native modal <dialog> closing with exit animation leaves page inert until animation ends; keystrokes sent then are dropped (no React onChange). V1-2.6 journey: fields filled right after « Nettoyer et utiliser cette version » emptied, later fields kept, looked like form reset. Rule: after closing a modal, wait for dialog count 0 (getByRole('dialog', {name}) toHaveCount(0)) before typing; never retry fills (masks real resets). Users cannot type during inert phase either, so no data loss.

LRN-117 — Index-only staging past format noise: observation, strict control only (2026-11-04)

Observation, not a routine: worktree held uncommitted format-only Prettier changes (owner pending) on files a fix had to touch. Staging logic hunks onto HEAD text via git hash-object -w + git update-index --cacheinfo kept format noise out of commits. Risky: index content bypasses working-tree review. Only with strict control: apply hunks by exact-match script on git show HEAD:<file>, prove equivalence (prettier(staged) == prettier(worktree)), run checks, inspect git diff --cached. Prefer resolving the noise first (owner decision) over routine index surgery.

LRN-118 — Wasm budget margin: measure with the gate's exact call (Node gzipSync level 9 on pkg), never system gzip, never raise silently (2026-11-05)

  • Context: V1-2.6 UX prep, 2026-11-05. Earlier study measured wasm with GNU gzip -9 (583 126 B) and claimed ~17 KB margin. Gate measures otherwise: real margin 7 857 B. Owner asked rule recorded.
  • Gate (verified in repo): packages/core-wasm/tests/size.test.ts runs Node gzipSync(bytes, { level: 9 }) on shipped build packages/core-wasm/pkg/faunosteo_wasm_bg.wasm (coreWasmPath('pkg')), asserts toBeLessThanOrEqual(COMPRESSED_BUDGET_BYTES), COMPRESSED_BUDGET_BYTES = 600_000 (D-R13).
  • Reference: 592 143 B of 600 000 B → margin 7 857 B (raw 1 569 864 B; pkg built 2026-11-04 after last core change bbab0e6; re-measured 2026-11-05 with same call, same figure).
  • Rule: margin = same call, same params (level: 9), same pkg file as gate. No system gzip substitute: results differ. Measure after every core change (each new op). Never raise ceiling silently: raise = explicit owner decision (D-R13) on measured figure.
  • How: after pnpm wasm:build, run size test (prints figure) or node -e with zlib.gzipSync(buf, {level: 9}) on that file.

LRN-119 — React 19.2 Activity keeps state but re-runs effects on reveal: audit one-shot mount effects, no general ban (2026-11-06)

  • Context: V1-2.6 U1 plan (2e46c14) chose kept-mounted hidden wrappers over React 19.2 <Activity> for tab places; owner asked distinction recorded, no general ban (2026-11-06).
  • Fact (react.dev/reference/react/Activity, checked 2026-11-06): mode="hidden" keeps state, refs and DOM (display: none) but destroys Effects (cleanups run); reveal re-creates them (setups run again). Conceptually hidden = unmounted with saved state. Hidden children still re-render on prop changes, at lower priority.
  • Trap: state kept ≠ effects quiet. Effect that does one-shot action on mount re-fires at each reveal:
    • apps/app/src/catalogue/useFraming.ts:69 useEffect(() => setFraming(FIT), [resetKey]) → zoom and pan reset at each return, though framing state was kept.
    • apps/app/src/components/editor/findings/FindingTree.tsx:31-33 useEffect(() => focus(focusId), [focusId]) → stale focusId re-focuses tree item at each return (steals focus).
  • Rule: before wrapping subtree in <Activity>, audit its effects. Idempotent on re-run (subscriptions, listeners, measures with cleanup) → fine. One-shot on mount (reset, focus, scroll, fetch, write) → make reveal-safe (apply once per key via ref, consume one-shot request) or keep hidden wrapper. hidden wrapper: no effect runs on switch, but hidden places re-render at normal priority (U1 plan §2 cost control). <Activity> stays allowed where audit passes.
  • Future application: U1 makes focusId one-shot and bans focus in mount effects; U2b search, filter panel, drawing in filter panel (useFraming reuse) follow same rule, so a later move to <Activity> stays possible.
  • Status (2026-11-06): correct, amended 2026-11-06 after fresh verifier: hidden Activity keeps state (useRef values included) and DOM; refs to DOM elements detached while hidden (safelyDetachRef, react-dom 19.2.6), re-attached on reveal in layout phase before effects re-run; impact lines unchanged.

LRN-120 — Never edit src while a browser suite runs against a live dev server: HMR mixes code, run unusable (2026-11-09) (2026-11-09)

  • Context: V1-2.6 U1 Lot H. Controller ran whole shell suite on a474dda (Playwright against live Vite dev server) while fix round 1 edited src. HMR served half-edited code mid-run → failures mixed old/new code, run unusable, verdict lost.
  • Rule: suite against a live dev server = frozen tree for its whole duration. No edit dispatch while a suite runs. Fix needed during a run → wait for run end, or work in separate worktree with own port.
  • Apply: SDD controller sequences implementer dispatches and suite runs; report names commit the suite ran on and confirms no edit landed during it.

LRN-121 — Sandbox volume and consumed state fail browser suites independent of code: check data before bisecting (2026-11-09) (2026-11-09)

  • Context: V1-2.6 U1 Lots F-I. admin.spec « Target crashed » in every full run since Lot F, bisect 89da8d3 / 580ff28 / 606f7ba same failure → not code. Cause: long-lived sandbox grew 2 306 grant rows; list_catalog_grants() + GrantList unbounded; axe scan drove Chromium renderer ~2.2 GB, earlyoom killed it. Same pressure SIGTERMed DEV pg_meta. Fresh sandbox (owner go) → 192/0. Later second run on same sandbox: admin.spec:717 failed 4/4, single working-copy slot taken by earlier run (WorkingCopyAction.tsx:88).
  • Rule: suite failing outside changed files → check sandbox data volume and consumed state before bisecting code. Tests create own state or tolerate existing state. Unbounded list endpoints = latent OOM under test tooling; page server-side. Never reset sandbox just to get green (owner go per reset, BDR-105/106).
  • Apply: report exact counts per commit and sandbox age; RR-13 covers paging + admin scenario independence + memory check.

LRN-122 — pgrep -f wait loop matches its own command line: bracket the pattern or wait on PID (2026-11-09) (2026-11-09)

  • Context: V1-2.6 U1 Lot I. Implementer wait loop while pgrep -f 'playwright.shell.config'; do sleep …; done never ended: pgrep -f matched the loop's own shell command line, which contains the pattern.
  • Rule: pgrep -f pattern must not match the caller: bracket trick pgrep -f '[p]laywright.shell.config', or wait on a known PID (wait $pid, kill -0), or the harness Monitor / background notification.
  • Apply: any wait-for-process loop in briefs and scripts.

LRN-123 — docker inspect -f failure: bare newline on stdout, error sentence on stderr (2026-11-11)

Context: db:trial absent detection, resource_exists in scripts/db-trial.sh. Measured 2026-11-11 on this machine: docker client 29.9.3, rootless daemon 29.9.2, read-only inspect of absent name faunosteo_probe_absent.

Fact (demonstrated): docker <container|volume|network|image> inspect -f '{{...}}' <absent> -> rc 1, stdout exactly "\n" (template inspector flush), stderr one sentence:

  • container: Error response from daemon: No such container: <name>
  • volume: Error response from daemon: get <name>: no such volume
  • network: Error response from daemon: network <name> not found
  • image: Error response from daemon: No such image: <name> Daemon unreachable: stdout also "\n", stderr = dial error.

Trap: out="$(docker ... inspect -f ... 2>&1)" then exact compare never matches (leading "\n"): every absent resource refused. Shipped in a fix round, stub printed stderr line only, 353 green tests missed it; fresh re-review caught it (d3bdbbe history).

Apply: absent = rc != 0 AND stderr alone (2>&1 >/dev/null) equals the per-kind sentence; anything else refuses. Stubs reproduce both streams (control: merged compare restored -> 288 harness fails). Measure real tool output stream by stream before freezing it in a stub.

Limit: sentences proven on this version pair only; a Docker upgrade may reword them (absent_answer then refuses everything, fail-closed).

LRN-124 — bash 5.3 EXIT trap sees exit status 0 after SIGTERM (2026-11-11)

Context: db:trial backup_now EXIT trap (scripts/db-trial.sh ~1170 comment), lot B2.

Fact (demonstrated 2026-11-11, GNU bash 5.3.9): script with trap '...' EXIT and no TERM trap, killed by SIGTERM -> EXIT trap runs, $? inside it is 0, process still exits 143. With trap 'exit 143' TERM the EXIT trap sees 143. Repro: bash -c 'trap "echo \$?" EXIT; kill -TERM $$; sleep 2' prints 0.

Apply: never decide success/failure from $? in an EXIT trap. Clear the trap on success (trap - EXIT) so any run of it means failure, or set a status variable, or add trap 'exit 143' TERM / trap 'exit 130' INT.

Limit: only bash 5.3.9 tested; other versions unproven.

LRN-125 — psql single-transaction commits a truncated piped script (documented, unproven here) (2026-11-11)

Context: db:trial rotation and grant SQL (scripts/db-trial.sh ~1525 comment; plan .claude/tasks/plans/2026-11-09-db-trial-stack.md B2/B3 records).

Rule (NOT demonstrated here, derived from psql's documented behaviour): psql --single-transaction / -1 wraps the whole input in BEGIN ... COMMIT. If the producer of stdin dies mid-script (pipe closed early), psql sees EOF and sends COMMIT: the truncated prefix commits. ON_ERROR_STOP stops on SQL errors only, never on a short input.

Apply: for multi-statement writes fed through a pipe, write explicit begin; ... commit; in the script itself (a truncated script then never reaches its commit and rolls back on disconnect), plus a commit marker checked afterwards when the outcome matters (db-trial rotation digest marker).

Limit: no run in this project reproduced the truncation; treat as design rule pending a real psql test. Note: seed_equine still uses sb_psql --single-transaction < file (file input, not a pipe: lower risk).

LRN-126 — Docker daemon-down error contains no such file or directory (2026-11-11)

Context: db:trial daemon-down handling. Measured 2026-11-11, docker client 29.9.3, DOCKER_HOST=unix:///nonexistent/docker.sock.

Fact (demonstrated): every docker call with no daemon -> rc 1, stderr failed to connect to the docker API at unix:///nonexistent/docker.sock; check if the path is correct and if the daemon is running: dial unix /nonexistent/docker.sock: connect: no such file or directory.

Trap: substring tests like *"no such"* (meant for "No such container" / "no such volume") also match the dial error: daemon-down reads as "absent". On destructive paths (destroy, restore) that meant deleting live state or extracting into a non-empty volume.

Apply: never classify Docker errors by substring; exact whole-sentence match per kind on stderr, everything else refuses (see the inspect -f learning).

Limit: wording of this client version only.

LRN-127 — Postgres image init logs role password: log_statement must be off on server command line (2026-11-11)

Context: db:trial first real create 2026-11-11 (255dd67). TR_PW found in docker logs faunosteo_trial_db line 379: postgres@postgres LOG: statement: ALTER USER supabase_admin WITH PASSWORD '…'. Cause (demonstrated): image supabase/postgres:17.11.0.004 init script /docker-entrypoint-initdb.d/migrate.sh sends role password as SQL text (lines 36/46/54/59) on init temp server; image /etc/postgresql/postgresql.conf:545 has log_statement = 'ddl' → statement + password to stderr = container log. Our /etc/postgresql.schema.sql session set log_statement='none' runs after → too late. Per-role log_statement=none (image migration 20250205060043) also after. Fix (5f63d22): -c log_statement=none appended to exec docker-entrypoint.sh postgres ... in DB_INIT. Entrypoint _main → docker_temp_server_start "$@" → pg_ctl -o "$(printf '%q ' "$@")" passes every arg after postgres to temp server and final server; command line (PGC_S_ARGV) beats postgresql.conf + auto.conf; no init script sets log_statement other than none (grep). Harness check db-trial-check.sh:726, positive control red 372/1 → green 373/0. Static proof only: real proof = create on fresh volume + container log scan (counts only, SUPABASE.md §5.2). Trade-off: DDL no longer logged on trial server. Not closed (named, owner scope): failing init statement still logged (log_min_error_statement = error); migrate.sh puts password on psql argv during init; db-sandbox.sh same DB_INIT without flag; DEV CLI stack likely same log line. Remediation of exposed value: one-off TR_PW rotation 2026-11-11 (owner): 5 roles one tx (local logging off), secrets.env, auth/storage/rest recreated by pnpm db:trial start; old pw refused on scram path (container network IP; 127.0.0.1 is trust, proves nothing), new ok ×5; db container frozen env keeps dead old value. Future application: any self-hosted Postgres image with init scripts → set logging GUCs on server command line, never in init SQL; mandatory pre-production check in DEPLOY.md security prerequisites. Password probe must use non-trust pg_hba path + control with wrong password.

LRN-128 — Click-time hit tests lie: pointer capture, blur-rebuild and touch click synthesis; decide taps from the press (2026-11-12)

Context: R1 D6b (deselect on empty drawing press), sheet editor, Chromium. Found by plan challenge + code review, confirmed by e2e recorder. Observed mechanisms (facts):

  • Pointer capture retargets: setPointerCapture on the box at pointerdown (move gesture) → mouseup/click delivered to capture target (box), not the pressed marker → closest('[data-anno-id]') on click target = null.
  • Blur commit at mousedown: focusable box takes focus → field blur commits → store version bump → canvas replaceChildren rebuild before mouseup → pressed node detached → click can be dropped (Blink).
  • Touch: Chromium builds the tap's click after touchend, hit-tests the layout as it is then (after any pointerup state change shifting it), and applies touch adjustment toward cursor:pointer targets near the finger (~6-10 px).
  • happy-dom reproduces none of these (no capture retarget, no focus on pointerdown, no layout). Implementation recommendations (choices, not facts):
  • Decide a "tap on empty" from the press (pointerdown target, movement, pointer count), not from the click target.
  • Apply mouse verdict at pointerup and swallow the following click; apply touch/pen verdict in the tap's own click and re-check its target.
  • Unit tests: simulate capture retarget (upOn: box) and mousedown focus explicitly; prove the rest in real Chromium (CDP touch) with an event recorder asserting which guard fired. Refs: plan challenge records (.claude/tasks/plans/2026-11-12-r1-history-deselect-1141.md), useEmptyTap.ts, e2e/shell/editor-deselect.spec.ts, BDR-113.

LRN-129 — Document-level Escape must re-check dialog and panel layers (body focus skips the React root) (2026-11-12)

Context: R1 Escape priority in sheet editor (React 19). Code review found body-focused Escape skipping higher layers. Facts: keydown with focus on document.body (after click on non-focusable text) never traverses the React root → React handlers (ModalDialog, ReferencesPanel, workspace onKeyDown) never run. React synthetic stopPropagation does stop native propagation to document. A capture listener on document runs before everything, incl. dialogs. Rule: a document-level Escape listener must re-check the priority interfaces itself: dialog[open] present → skip; references panel open → skip deselect (and close panel for body-targeted Escape); defaultPrevented, isComposing, text field target → skip; act only on shown body. Keep validated order dialog > « Plus » > references > tracing > selection; every consumer preventDefault so later layers skip. Test: unit cases with focus on body + dialog open / references open / dialog outside workspace (phone drawer). Refs: deselect.ts useEscapeDeselect, EditorWorkspace useBodyEscape, EditorTabs useMoreEscape, commit 132756e, BDR-113.

LRN-130 — happy-dom pointer/focus defaults; compressed-output proxy false OOM on piped pnpm lint (2026-11-12)

happy-dom (20.x, vitest): PointerEvent init defaults isPrimary: false, pointerType: '', buttons: 0; fireEvent.click moves no focus; no layout (box size 0), no pointer-capture retarget. → pass isPrimary: true, button: 0, buttons: 1, pointerType explicitly; focus explicitly; pan translation assertions impossible (assert zoom / preventDefault instead). Compressed command output (rtk proxy): pnpm lint | tail printed [warn] Linter process terminated abnormally (possibly out of memory) with rc 254, while pnpm lint > file 2>&1 gave rc 0 and every package "Done" (2026-11-12, worktree faunosteo-v1-2). Observed once in this context only; the message comes from the proxy wrapping a piped command, NOT proof that eslint never runs out of memory elsewhere. → For gate evidence, redirect to a file and read rc + per-package lines; a real OOM still has to be ruled out from the unproxied log. Refs: scratchpad gate logs r1-gates/final*, .superpowers ledger for plan 2026-11-12-r1-history-deselect-1141.

LRN-131 — Conditional in-flow element above a canvas = layout shift; fix per message, sr-only only for redundant text (2026-11-12)

Context: R1 owner feedback 2026-11-12: drawing jumped at each selection change in sheet editor (BLK of same date, 927537b). General problem (layout): any element mounted/unmounted or resized on a state change and placed in flow ABOVE a canvas or hit-tested area moves that area: visual jump, and next clicks/taps land on stale coordinates. Sources: selection labels, transient hints, notices, banners. Detection: e2e reads target boundingBox().y before and after each state change (select, deselect, hint on/off), desktop + phone; happy-dom has no layout, so unit tests can only assert classes/structure. Fix options (choose per message, not one rule): (a) redundant info already carried elsewhere (highlight, side panel) → drop visually, keep sr-only text if useful for SR browse (SelectionTag case); (b) message user must see (warning, refusal, error, save state) → stays VISIBLE: reserve fixed space (min-height slot), overlay inside canvas box (relative parent, absolute + pointer-events-none), or place below / beside canvas. Never sr-only a warning to fix layout. A11y check: sr-only text not live = no announce, available to browse only; announce needs live region, avoid duplicating an existing one. Open instance: ToolNotes hint above canvas (EditableAnnotations.tsx ~373) cleared on select = remaining shift, needs option (b). Refs: SelectionTag.tsx, editor-deselect.spec.ts layout tests, docs/design/README.md deviation 2026-11-12, LRN on layout shift vs hit-test (recompute box per press).

LRN-132 — E2E tests and database-wide singleton state (2026-11-12)

Context: anomaly B (BLK-014, 2cdee42): e2e on shared persistent sandbox asserted an action that needs a database-wide singleton free (one active working copy of historical sheet per database). Rules:

  • Never require a unique/singleton resource to be AVAILABLE in a shared persistent database: state depends on earlier runs and parallel suites.
  • Need to check the UI of that action → test the REAL component on a harness (e2e:ui, no backend) with the state simulated; import the production component, no fork/mock of its logic; prove it is the real one (e.g. its computed default value).
  • Server-side (shell) tests assert CONSISTENCY of the state actually present (e.g. button disabled iff reason shown and linked), both branches written, not conditional skips.
  • Clean up / archive ONLY resources created and identified by the current run (capture ids from successful calls, all calls, before classification); verify ids actually modified (returning id = expected set); each cleanup step independent, first error rethrown; skip empty in ().
  • Avoid concurrent suites mutating the same singleton (set-aside/restore patterns race with readers under fullyParallel and alter pre-existing metadata such as updated_at).
  • Prove non-interference: per-id snapshot (id, status, archived_at, updated_at) of pre-existing rows before/after; counts alone lie (fixtures add rows). Refs: BLK-014, e2e/ui/working-copy.spec.ts, sheets-admin.sandbox.ts afterAll, editor-equine.spec.ts set-aside (open), LRN-076, LRN-082.

LRN-133 — Guarded e2e on persistent sandbox: preflight wrapper, full-row guard, A/B then dose-response (2026-11-13)

Context: R2 shell e2e on persistent sandbox (editor-equine must never run there; pre-existing rows must stay identical). Rules:

  • Wrap every shell e2e run in a script: refuse bare args, refuse any spec named editor-equine, run --list first and abort if editor-equine appears (preflight), then run.
  • Guard = full-row md5 per id of pre-existing rows in every touched table, snapshot before/after; report new rows per table + « pre-existing rows changed or deleted: none ». Counts alone lie; metadata (updated_at) included in the hash.
  • Diagnose suite failures with interleaved A/B (pre-change worktree vs HEAD, same lockfile, same data) then a dose-response probe (cap the suspect input, same code/data) in a quiet window; loaded runs confound. Refs: scratchpad wrappers run-shell.sh / guard.sh (R2), BLK-015, LRN-132.

LRN-134 — Blur-commit plus explicit commit: stale value duplicates history; one error slot vs several refused fields (2026-11-13)

Context: R2 reference tiles: field blur commits value to history; « Terminer » / panel close also commit. Pattern: blur-commit + explicit commit on the same gesture read a stale value → duplicate history entry (two undos for one edit). Fix: one commit path per edit, compare against document value at commit time, test « one history entry per edit » for blur, « Terminer », panel close (criterion 26, 1bf2701). Also: a guard that tries several pending fields with one shared error slot leaves the LAST field's message; focus first refused field then re-assert its refusal (94f8a8b). Test focused field's aria-invalid, not just that an error exists. Apply: any form with commit-on-blur plus a submit-like button.

LRN-135 — Refusal layout shift loses the click (mousedown preventDefault); happy-dom observer and touch-slop test traps (2026-11-13)

Context: R2 « Terminer » below a field whose blur-commit is refused. Pattern: mouse down blurs field → refusal line inserted → layout shifts → mouseup lands elsewhere → click lost (« Terminer » looks dead). Fix: mousedown preventDefault on the button (focus stays, button then runs the leave guard). Editor-wide general cure not done. Also (tests): happy-dom 20.10.6 holds MutationObserver callback in WeakRef → GC under load silently stops observation; count live-region announcements by wrapping textContent/nodeValue setters, restore in afterEach (c8109af, b1fd896). Touch e2e: CDP synthesizeScrollGesture touch scrolls nothing in Chromium 1248; dispatchTouchEvent swipes do, but slop floor ~60 px + load-dependent gain → pixel-exact touch landing not reproducible; prove reachability by touch, place worst case by programmatic scroll (78fb2d0).

LRN-136 — Implementer gate claims need exit codes, controller reruns (2026-11-13)

Pattern: subagent implementer claimed typecheck/lint green while red (Task 2, 18085ce: missing import, readonly fixtures). Caught only when controller reran gates rounds later. Apply: briefs demand real exit codes per gate; controller reruns typecheck + lint itself on every report before review. Never accept "green" without rc.

LRN-137 — Template-built i18n keys escape typecheck (2026-11-13)

Pattern: i18n key built by template literal (t(editor.findings.new.${kind})) escapes typecheck: Dict typed as string map, missing key renders raw. Found in final round: editor.findings.new.category absent in fr+en, title showed raw key. Apply: every dynamic key site gets unit test asserting heading text has no 'editor.' prefix, or enumerate union kinds against both dicts in a test. Audit dynamic key sites in touched files at review.

LRN-138 — Unblockable leave + no draft storage: content-free loss flag (2026-11-13)

Pattern: browser Back not interceptable (BDR-078) + owner forbids storing drafts + owner forbids silent loss. Resolution: on unmount with dirty dialog write one content-free flag (kind + element key, scoped sheetId+userId) to sessionStorage, try/catch; next mount of same sheet+user shows notice once, clears flag. Relies on React 19 parent-first cleanup on deletion. Apply: any "cannot block leave, cannot keep data" conflict -> record the fact of loss, not the data, and tell user on return.

LRN-139 — Navigation API cancels same-document Back traversal in Chromium (2026-11-14)

Pattern: Navigation API navigate event on same-document traverse is cancelable in Chromium 156 (probe: CDP Page.navigateToHistoryEntry -3, userInitiated true, preventDefault keeps entry). Gives real "confirm before leave" for SPA Back/history-menu jumps without data router (BDR-078). Then navigation.traverseTo(destination.key) after user confirms; pass-through flag for that follow-up event. Apply: guard only when dirty + destination leaves route + event.cancelable; fallback (no API, Firefox/Safari unverified) = after-the-fact notice. e2e via CDP history jump; page.goBack with cancel times out. Probe browser behaviour with throwaway page before planning.

LRN-140 — crypto.subtle missing on http LAN origin (2026-11-14)

Pattern: crypto.subtle absent on non-secure origin (http LAN dev/trial address); loopback 127.0.0.1 counts secure so tests miss it. Async SHA-256 binding broke reload restore on owner trial origin + added blank first frame. Apply: for equality binding (not secret) use sync non-crypto hash (FNV-1a 64 BigInt) salted with random per-record value; test with crypto.subtle undefined. Check every crypto.subtle use against the LAN http origin.

LRN-141 — Stacked modals: ask only removed layers; never rule silent loss into a limit (2026-11-14)

Pattern: stacked modal layers + "ask all layers" guard: question appeared in lower dialog hidden under still-open upper modal (citations sheet) -> looks frozen. Also ruling "accept as documented limit" for silent loss broke owner condition; reviewer caught it. Apply: a guard asks only layers the move actually removes; before showing a question, close clean layers above the dirty one. Never rule a silent-loss case into "documented limit" when owner condition forbids silent loss: restore notice instead. Label limits owner did not see as "to confirm", never "accepted".

LRN-142 — Transactional dialog owns side-effect creations and explicit commit (2026-11-15)

Context: R2 closure, owner db:trial trials 2026-11-14/15 drove Rev 4-6. Pattern: in dialog that edits draft, side-effect creations (new reference) belong to draft, written with save as one batch (one undo); abandon = no write. Select browses only, explicit action button commits choice; save refuses pending uncommitted choice with message + focus. Reason: arrow keys on native select fire change, silent draft edits. Apply: any future transactional dialog (U2 annotation properties dialog).

LRN-143 — E2E cleanup on persistent stack: archive own rows by captured id + name read-back (2026-11-17)

Context: R4 e2e on persistent sandbox seeded published sheets; app never deletes sheet with published history (delete_anatomical_sheet refuses + needs aal2). Pattern: clean only own rows: capture ids at seed, UUID-guard every id before SQL text (capturedId), read name back by id and compare exact seeded name (mismatch → archive nothing, fail run), archive via app's status RPC, revoke own grant by id, read back; data guard before/after (0 removed, 0 changed). Never match by pattern. Apply: e2e fixtures on shared persistent stack → reachable end state (archive) over delete; identity check by id + name before any write; guard diff proves no pre-existing row touched.

LRN-144 — Per-card retry in lists: no live line, polite region on retry, focus rule (2026-11-17)

Pattern: list of N cards each with own failure + retry. No live region on card lines (burst of N announcements at load). Retry: line + button stay mounted, button aria-disabled (not disabled, keeps focus), card aria-busy, clicks ignored by ref guard (two calls same tick = one attempt). Polite sr-only region empty at load, cleared at each attempt, says new line on repeat failure; stays mounted once a retry ran. When attempt settles without « Réessayer », move focus to card's « Consulter » only if focus was on removed button or body. Apply: any per-item retry in lists/grids; test focus on body vs elsewhere, repeat failure, failure with no retry left.

LRN-145 — Single-request failure e2e via route.fallback + remount; 0fr grid row keeps child padding (2026-11-17)

Pattern: (1) Playwright: fail one request (one version) with route.abort for its URL and route.fallback() for the rest; remount the component (search filter out/in) instead of page reload so failure state is reached without reload side effects; DevTools offline + search is the manual equivalent. (2) CSS collapse grid-rows 0fr→1fr: padding/border on the 0fr row's direct child stays visible (R3 phone panel kept 12 px); put padding on an inner wrapper inside the min-h-0 overflow-hidden child, assert closed height 0. Apply: single-request failure e2e; any CSS-only collapsible panel.