Test / change log Entries are appended newest-last with a [YYYY-MM-DD HH:MM:SS] timestamp. This file supersedes change-log.txt (see the entry below). [2026-09-26 13:42:15] Log destination switched to backend-test-change-log.txt. Per instruction, all change-log entries from now on are written here instead of change-log.txt. The earlier history remains in change-log.txt; nothing was moved. [2026-09-26 14:16:46] backend: API test harness (jest) — tRPC flows + static JSON cache. Adds apps/backend/tests/ (jest + ts-jest, node environment, runInBand) driving the local backend over HTTP (:8787, API_BASE_URL-overridable) using credentials from tests/.env: - tests/jest.config.js, tests/tsconfig.json, tests/setup.ts (loads tests/.env) - helpers/env.ts API_BASE_URL + creds with clear failure messages - helpers/api.ts tRPC client (httpBatchLink) + optional bearer token - helpers/sessions.ts staff/user login (token cached) + server preflight - helpers/fixtures.ts store + product/SKU + future slot via admin APIs; user address - helpers/cache.ts essentialConsts, versioned cache URLs, fetchJson, pollUntil - api/health.test.ts (3), auth.test.ts (3), admin.test.ts (2), order-flow.test.ts (5), order-edge-cases.test.ts (4), cache-slots.test.ts (3), cache-availability.test.ts (2), cache-products.test.ts (2, eventual/polling) - package.json: scripts test:api / test:api:typecheck; devDeps jest, ts-jest, @types/jest, @trpc/client - tests/.env added to .gitignore; tests/.env.example committed Not yet run: the local backend (cd apps/backend && bun run dev) must be up and tests/.env filled with the staff + user credentials. Verification done: - bun install added ts-jest (bun.lock updated). - bun run test:api:typecheck -> clean (fixed a nullable createAddress data access). - jest --listTests -> all 8 suites discovered. - A backend IS reachable on :8787 -> tests/api/health.test.ts PASSES (3/3). - The other 7 suites load and fail only on the missing credential, with "[api-tests] ADMIN_NAME is not set. Copy apps/backend/tests/.env.example ...". - Full run: 1 passed / 7 failed suites, 3 passed / 21 failed tests — all failures are the credential gate, so nothing was created yet. - apps/backend/test-case-info.md documents all 24 cases. Blocked on: filling apps/backend/tests/.env (ADMIN_NAME/PASSWORD, USER_IDENTIFIER/PASSWORD) — then `cd apps/backend && bun run test:api`. [2026-09-26 14:52:00] backend: API suite green (8 suites / 24 tests) + 3 fixes. Ran with the populated tests/.env against the local backend: Test Suites: 8 passed, Tests: 24 passed, ~49s. test:api:typecheck clean. First run exposed 3 issues, all in the tests/premises (fixed): - cache-availability: availability.json is keyed by SKU id, not product id; lookup by skuId (toggleProductOutOfStock flips product_market_stats for every SKU, so the change is app-visible). - cache-products: the rebuild PUTs all files in parallel (non-atomic), so the version bump does not mean every file is up yet — the store file 404'd then appeared. Both cache-products cases now poll for the individual file. - order-edge-cases: placeOrder accepts a non-existent slotId (no FK/validity check; only capacity). The case now documents that behaviour and asserts the bogus slotId is stored verbatim, instead of expecting a rejection. Docs updated: apps/backend/test-case-info.md (findings section + corrected rows). Note: the run creates real rows (stores/products/SKUs/slots/orders/addresses) and writes cache objects to the dev R2 bucket — per the approved "leave data" decision. [2026-09-26 15:40:00] backend: second wave — authz, order rules, lifecycle, user surface, cache consistency. 13 suites / 52 tests green (~98s). New suites (28 tests): - api/authorization.test.ts (5): anonymous/staff/user boundary checks, staff-guarded admin writes rejected for user tokens, one user cannot see another's addresses. - api/order-rules.test.ts (6): delivery charge vs minRegularOrderValue, per-slot grouping (2 slots -> 2 orders, charged once), full-slot rejection (403), flash-disabled rejection (const flipped then restored), invalid quantity. - api/order-lifecycle.test.ts (5): notes persistence, cancel + reason in the list, empty-reason rejection, "ORD" rejection, pagination + pageSize 51 rejection. - api/user-surface.test.ts (7): product detail, createReview -> getProductReviews, generateUploadUrls, getEligible/getMyCoupons, unknown coupon rejection, getSelfData, complaint raise -> staff resolve. - api/cache-consistency.test.ts (5): availability/slots ids present in products.json (polling), availability count, essential-consts self-consistency, stores productCount vs store detail length. New helpers: helpers/consts.ts (getConstants/setConst/asNumber); fixtures gain an optional price and registerThrowawayUser(); api.ts gains captureError(); cache.ts gains stores/essential-consts URLs. Findings (documented in test-case-info.md): - Admin reads are NOT staff-guarded: a user token can call admin.product.getProducts (bare protectedProcedure). Staff-guarded writes do check ctx.staffUser. - availability.json and slots.json are bumped synchronously and can reference product ids that products.json (rebuilt ~30s later) does not have yet; consistency checks poll. - essential-consts.json embeds a version snapshot, so its slots/availability versions can lag the live ones (consumers read versions via tRPC anyway). - Cache rebuild writes files in parallel (non-atomic) — poll per file. Config-mutating cases (flash gate, slot capacity) restore the previous state. [2026-09-26 16:20:00] backend: third wave — admin catalog + admin orders. 15 suites / 71 tests green (~75s). Payments and OTP intentionally excluded (user's call). New suites (19 tests): - api/admin-catalog.test.ts (9): getStoreById/updateStore, getProductById/updateProduct, getGroups/createGroup, coupon.getAll, vendorSnippets.getAll, complaint.getAll. - api/admin-orders.test.ts (10): getAll, getOrderDetails, getSlotOrders, updateNotes, updatePackaged, updateDelivered (user then sees deliveryStatus success), removeDeliveryCharge, updateAddressCoords, cancelOrder (fresh order), rebalanceSlots. Started the local backend: the running wrangler dev instance was listening on :8787 but not responding (health timed out), so it was killed and restarted via `bun run dev` (background task). Tests then ran green. Findings (documented in test-case-info.md): - updateProduct requires a SKU feature literally named "quantity" (same as create). - admin.order.updateAddressCoords succeeds but the coords are NOT exposed by user.address.getUserAddresses (latitude null/0) — admin write vs user read disagree. - admin.order.cancelOrder refuses an already-delivered order. - admin.order id types are inconsistent: number for getOrderDetails/updateNotes/ removeDeliveryCharge/cancelOrder; string for updatePackaged/updateDelivered/getSlotOrders. - admin.product.updateProduct and createGroup are reachable with the staff token as expected. Still not covered: admin user management (getAllUsers/getUserDetails/getUserIncidents/ addUserIncident/getUsersForNotification/sendNotification), banner + vendorSnippet CRUD, coupon create/update/delete, product-tag CRUD, product delete, const write round-trip, order concurrency, queue no-op assertions. Payments/OTP excluded per instruction. [2026-09-26 17:05:00] backend: coupon CRUD + user-side application. 16 suites / 78 tests green (~117s). tests/api/coupons.test.ts (7): create (flat discount, apply-for-all) -> getById -> update({id, updates}) -> visible in user.coupon.getEligible -> placeOrder({couponId}) reduces the order (couponCode + discountAmount === 2) -> delete invalidates -> the invalidated coupon is rejected by placeOrder and drops out of getEligible -> a coupon with both discountPercent and flatDiscount is rejected. Findings (documented in test-case-info.md): - admin.coupon.create returns Coupon[] (take [0].id), not a single object. - admin.coupon.update takes { id, updates } and merges partially. - admin.coupon.delete soft-invalidates: getById still returns the row, but the coupon leaves getEligible and placeOrder refuses it. - create validates that exactly one of discountPercent/flatDiscount is provided. Earlier gap list trimmed: coupon create/update/delete now covered. [2026-09-26 19:20:00] backend: remaining admin surface automated (everything except payments/OTP). 21 suites / 103 tests green (~166s), test:api:typecheck clean. New files (apps/backend/tests/api/): + admin-users.test.ts (8) getEssentials, getAllUsers, getUserDetails, getStaff, addUserIncident -> getUserIncidents, getUsersForNotification, updateUserSuspension(true/false), sendNotification(no-token recipient) + admin-banners.test.ts (4) getBanners, createBanner -> getBanner, updateBanner, deleteBanner + admin-tags.test.ts (4) createProductTag -> getProductTags, getProductTagById, updateProductTag, deleteProductTag + admin-vendor-snippets.test.ts (4) create -> getAll, update, getOrdersBySnippet, delete + admin-ops.test.ts (5) updateConstants round-trip, createGroup/updateGroup/deleteGroup, deleteProduct(rejection), store.createStore/deleteStore, two concurrent placeOrder calls Modified: M tests/api/admin.test.ts slots.getAll membership moved to the unbounded public user.slots.getSlots + assert the 20-slot cap M tests/api/cache-products.test.ts store-detail poll resolves the *current* cacheVersion each attempt (was pinned to the version captured after the write) Findings (documented in test-case-info.md): - admin.user.getUserDetails fails once a user has ~110 orders: unchunked "select ... from order_status where order_id in (...)" over the whole history. The suite now uses a fresh user. Same pattern in getAllUsers' order stats. - admin.product.deleteProduct fails for a product with SKUs (hard delete vs FK); returns a raw "Failed query" instead of 404/409. No soft-delete path through this procedure. - admin.store.deleteStore takes { storeId }, not { id } like its siblings. - admin.slots.getAll is capped at 20 slots, so a new slot isn't guaranteed inside the window. - vendorSnippets.getOrdersBySnippet requires a slot-linked snippet; snippetCode is required. - createBanner requires a URL-shaped imageUrl (a plain assets URL is fine, no upload). - Suspension is a live precondition: placeOrder rejects a suspended user, so admin-ops unsuspends in beforeAll and the suspension test restores in a finally. - stores/.json can land in a later cacheVersion than the one captured right after a write. Remaining (per instruction): payments (success path) and OTP login only. [2026-09-26 20:05:00] user-ui: coupon application + discount-calculation tests. Not functional app changes: adds UI test coverage only. Coupon selection and the discount maths already exist in components/checkout-page.tsx (lines 189-223) and components/cart-page.tsx (lines 200-281) but had no tests — the existing suites only used discountAmount: 0 / selectedCoupons: [] fixtures. New: + apps/user-ui/tests/screens/checkout-coupons.test.tsx discount calculation end to end (percentage, percentage capped by maxValue, flat, flat capped by maxValue, flat capped at the item total, discount pushing the total under the free-delivery threshold, min-order-ineligible coupon via ?coupons=, usage-limit coupon dropped, couponId -> placeOrder) + apps/user-ui/tests/screens/cart-coupons.test.tsx cart picker selection, the disabled/ineligible option labels, Coupon Applied + removal, and the &coupons= param handed to checkout Docs: user-ui/test-case-info.md gains the new cases. [2026-09-26 20:40:00] user-ui: coupon tests — final shape + findings. Correction to the entry above: the checkout-page suite was written, then deleted. Mounting components/checkout-page.tsx with a NON-empty cart never settles in this environment (it spins even with CheckoutAddressSelector and AddressForm stubbed), which is why its two existing cases only ever exercise the empty-cart short-circuit. The discount maths moved to the cart page, which shares the same formulas and mounts cleanly. Landed: apps/user-ui/tests/screens/cart-coupons.test.tsx 11 tests (new file) apps/user-ui/tests/components/payment-and-order.test.tsx +2 tests (4 -> 6) Result: 53 suites / 266 tests, 52 suites / 264 pass. The one red suite, tests/contexts/auth-lifecycle.test.tsx, is untracked and pre-existing (it references an undefined setLoginError and fails on its own) — not touched here, and excluded from the passing totals. test:typecheck clean. Findings recorded in user-ui/test-case-info.md: - The cart's coupon picker only enforces isEligible in the dropdown (disabled option); the discount sum itself does not re-check it. A minOrder coupon selected via ?coupons= is therefore still discounted on checkout (checkout-side, unverified — page can't be mounted). - The cart's flat-discount cap is min(discountValue, maxValue || totalPrice), so a flat discount larger than the cart is clamped to the item total, never below zero. - deliveryCharge is computed from finalTotal (post-discount), so a coupon can push an order back under the free-delivery threshold and re-add the fee. - PaymentAndOrderComponent's savings banner counts the waived delivery fee as savings. - BottomDropdown options render in a Modal and are addressed via testID `undefined-option-` when the call site sets no testID (the cart's coupon dropdown). [2026-09-26 21:30:00] user-ui: CORRECTION — why the checkout page could not be mounted. My earlier note said the checkout page "spins" with a non-empty cart. That was wrong. It throws, and the real cause is a Rules-of-Hooks violation in components/checkout-page.tsx: trpc.user.coupon.getEligible.useQuery and four useMemos sit AFTER the `if (selectedItems.length === 0) return ...` guard, so the hook count changes from 4 to 9 as soon as useGetCart resolves from [] to slotted lines, and React throws "Rendered more hooks than during the previous render." Every real checkout goes through that transition, so the screen cannot render at all with slotted items. With no error boundary the throw escapes the act environment and wedges the runner: no output, ~0% CPU, no jest timeout — which is what looked like a hang. Note the parallel work in the tree already tracked this (tests/KNOWN-GAPS.md #1, pinned by tests/screens/checkout-crash.test.tsx, green); I reproduced it independently before reading that file. Course-correcting my own conclusion: it is not a test-environment artefact and not a spin, it is a real render crash. Evidence gathered on the way (all consistent with the crash): - the page rendered the empty-cart tree while its own ['local-cart-regular'] query sat at status=success with items=1 — the tree was the first (pre-resolution) render; the next render threw, so nothing ever updated; - hooks/cart-query-hooks.tsx:233 gates the cart query on `enabled: Object.keys(productsById).length > 0`, and its queryFn drops any line whose skuId is missing from productsById/productSlotsMap (`return null`) — so there is always a legitimately-empty window before the CDN stores land (also KNOWN-GAPS.md #6); - tests/setup.ts:158 installs `jest.useFakeTimers({ now: Date.now() })` globally, so react-query's timer-batched notifications only flush when timers advance. Docs updated (apps/user-ui/test-case-info.md): - header totals refreshed for the grown tree: 61 suites / 316 tests, all green; - the "Not covered" checkout note replaced with the hooks-order crash above; - group counts refreshed (screens 119, components 63, hooks/stores/lib/contexts 81) and a note added that the suites which appeared alongside the parallel work are documented in tests/KNOWN-GAPS.md rather than in this file's per-suite tables. Note: tests/KNOWN-GAPS.md item 4 cites apps/user-ui/tests/screens/cart-coupons.test.tsx as the pinning test for the post-discount delivery-threshold behaviour, so that file and its test names should be kept as-is. [2026-09-26 22:00:00] user-ui FIX: checkout-page.tsx Rules-of-Hooks violation. File: apps/user-ui/components/checkout-page.tsx (app code — first functional change in this log's user-ui section; everything above was test-only). Diff (pure reordering, no logic touched): - remove the `// Handle empty cart case` / `if (selectedItems.length === 0) { return (...) }` block from between the `params.coupons` effect and `const totalPrice = ...` + re-insert the same block after `const finalTotalWithDelivery = finalTotal + deliveryCharge;` Why: `trpc.user.coupon.getEligible.useQuery` and the four useMemos (eligibleCoupons, selectedCoupons, discountAmount, deliveryCharge) sat below the early return, so the hook count was 4 on the pre-resolution render and 9 once useGetCart resolved to slotted lines. React threw "Rendered more hooks than during the previous render." — the checkout screen could not render at all with slotted items (tests/KNOWN-GAPS.md #1). Behaviour notes: - the guard now runs after the coupon query and the memos, so an empty/unsupported cart also fetches user.coupon.getEligible when authenticated (same as cart-page.tsx does). No visible change; totalPrice is 0 there, so the discount maths is inert. - no other semantics change: same JSX, same conditions, same derived values. Tests follow in the same pass: tests/screens/checkout-crash.test.tsx (the last case pinned the crash and is rewritten as a totals assertion) plus a new tests/screens/checkout-coupons.test.tsx. [2026-09-26 22:30:00] user-ui: tests for the hooks fix. tests/screens/checkout-crash.test.tsx (4 tests, unchanged count) — the last case was the crash pin: "throws a hooks-order error once the cart resolves to slotted items". It is now "renders the bill once the cart resolves to slotted items" and asserts the header, Item Total ₹215 and To Pay ₹230 with no discount. The ErrorBoundary helper and the `Text` import existed only for that pin and are gone. File header updated. tests/screens/checkout-coupons.test.tsx (NEW, 10 tests) — the checkout side of the coupon work, which the hooks crash had made unreachable. Cart 2 x product 2 @ 215 = 430, threshold 249, delivery 15: percentage -> -₹43 / ₹387 / "Free" / "You saved ₹68 on this order" (43 discount + 10 market saving + 15 waived delivery); percentage capped by maxValue (-₹50 / ₹380); flat (-₹100 / ₹330); flat capped by maxValue (-₹150 / ₹280); flat larger than the cart capped at the item total (-₹430); discount pushing the total under the threshold (-₹200 / ₹245 + the "Add products worth ₹19 for free delivery" nudge); a minOrder coupon passed via ?coupons= still applied (-₹50 / ₹380); a usage-limit coupon dropped outright; no ?coupons= -> no discount; and couponId: 77 + totalAmount=387 on placeOrder. tests/KNOWN-GAPS.md — item 1 (the checkout crash) removed and the remaining items renumbered 1-10; new item 11 pins the coupon-eligibility gap that checkout-coupons.test.tsx case 7 exposes (isEligible is computed but never consulted when the discount is summed; only the cart's picker enforces it). Item 3 now also cites the checkout-side threshold test. Cross-references updated for the renumbering: checkout-crash.test.tsx and test-case-info.md no longer point at "#1". Result: 62 suites / 326 tests green, test:typecheck clean. Note for whoever picks up KNOWN-GAPS #3 next: the checkout-side delivery-threshold behaviour is now pinned twice (cart-coupons case 7 and checkout-coupons case 6) — both must be updated together if the threshold moves to the pre-discount total. [2026-09-26 23:00:00] user-ui FIX + test flip: coupon eligibility (KNOWN-GAPS #11). File: apps/user-ui/components/checkout-page.tsx (app code). Diff: - selectedCouponId ? eligibleCoupons?.filter((coupon) => coupon.id === selectedCouponId) : [], + selectedCouponId + ? eligibleCoupons?.filter((coupon) => coupon.id === selectedCouponId && coupon.isEligible) + : [], Why: `isEligible` (minOrder, per-user usage limit) is computed per coupon but was never consulted when the coupon id arrived from the checkout URL, so a coupon the cart could not use still reduced the bill. The `selectedCoupons` memo is the single funnel: `discountAmount` sums it and `PaymentAndOrderComponent` forwards its id as `couponId`, so filtering here fixes both the displayed discount and what is sent to placeOrder. Test flip: tests/screens/checkout-coupons.test.tsx case 7 went from "applies a coupon whose minOrder is not met when it arrives via the URL" (-₹50 / ₹380) to "does not apply a coupon whose minOrder is not met, even from the URL" (no Product Discount row). [2026-09-26 23:20:00] user-ui: KNOWN-GAPS #11 narrowed; cart half deliberately not touched. tests/KNOWN-GAPS.md item 11 is rewritten. It no longer describes the checkout page (fixed in the entry above) and now covers only the cart: cart-page.tsx:201 has the same id-only `selectedCoupons` memo, so a coupon selected while eligible keeps its discount if the cart later moves against it (a quantity drop taking the total back under minOrder). The picker disables ineligible options, which covers the "cannot select it" case but not the drift. The same one-line guard was NOT applied to cart-page.tsx on purpose: the cart's quantity stepper has no testID and there is no established way to drive a quantity change from a test (cart-money.test.tsx seeds quantities instead), so the transition could not be covered. Item 11 records the fix plus the coverage work it needs (add a testID to the stepper, or seed a line whose product price changes) so the two land together. Verification: 62 suites / 326 tests green, test:typecheck clean. [2026-09-26 23:45:00] user-ui FIX: addressable quantity stepper + the cart's coupon eligibility. App-code changes, three files: 1. packages/shared/types/ui-common.types.ts — QuantifierProps gains `testID?: string` (optional, so every existing call site keeps the current behaviour). 2. packages/ui/src/components/quantifier.tsx — the three testIDs are now derived from a prefix that defaults to the old literal: - testID="quantifier-decrement" + testID={`${testID}-decrement`} (default 'quantifier') - testID="quantifier-value" -> same treatment - testID="quantifier-increment" -> same treatment Why: the static ids are ambiguous as soon as two steppers are on screen, which is exactly the cart page (one per line). The home-page suites that drive the floating cart bar's stepper (home.test.tsx, home-floating-cart-bar.test.tsx, home-add-to-cart-dialog.test.tsx) pass no testID, so they keep quantifier-* and are unaffected. 3. apps/user-ui/components/cart-page.tsx a) the line's stepper now passes testID={`cart-item-${item.id}`}, giving per-line ids (cart-item--increment / -decrement / -value) so a quantity change can be driven from a test at all. b) same guard as the checkout page: `selectedCoupons` now filters on `isEligible` as well as the id, so a coupon that was picked while it qualified stops discounting when the cart moves against it (a quantity drop taking the total back under minOrder). This closes tests/KNOWN-GAPS.md #11. Test added with it: tests/screens/cart-coupons.test.tsx — "drops the discount when a quantity change takes the cart below the coupon's minOrder" (selects a minOrder-300 coupon at ₹430, then decrements to ₹215). [2026-09-26 00:10:00] user-ui: verification for the stepper + cart-eligibility pass. tests/screens/cart-coupons.test.tsx — 12 tests green. The new case drives the stepper for real: seeds 2 x 215 = 430, selects a minOrder-300 coupon (-₹50 applied), presses cart-item-1-decrement, and asserts the discount and the "Coupon Applied" row are gone at cart-item-1-value = 1. It fails against the pre-fix code (the id-only memo kept the discount), so it genuinely pins the guard rather than describing it. Full user-ui run: 62 suites / 327 tests green. `NODE_ENV=test bun run test:typecheck` clean. Repo-wide `bun run typecheck` (bash typecheck) run because the Quantifier change is in a shared package. Per-package: apps/backend, apps/user-ui, apps/admin-ui, apps/web-ui, packages/db_helper_sqlite, packages/migrator, packages/web-components ..... clean packages/db_helper_postgres ................... 41 errors apps/fallback-ui .............................. 1 error Both failures are pre-existing and unrelated: db_helper_postgres drifts from the shared types (Coupon is missing skuIds/isFirstOrderOnly, AdminProduct lacks unitId, Complaint.images is unknown) and fallback-ui fails on vite.config.ts(8,13) TS2769. The only change made here in packages/shared is the additive optional `testID?: string` on QuantifierProps (git diff above), which cannot produce either. Every package that actually renders Quantifier typechecks clean. [2026-09-26 00:15:00] scope: packages/db_helper_postgres is out of scope for now. Its 41 typecheck errors are pre-existing and untouched by this work, and nothing in the user-ui tests or the coupon/checkout changes depends on that package. Left alone on request; it is not counted as a regression and should not block the user-ui work. The only other red package is apps/fallback-ui (1 error, vite.config.ts TS2769), also pre-existing. Still green for everything this work touches: apps/backend, apps/user-ui, apps/admin-ui, apps/web-ui, packages/db_helper_sqlite, packages/migrator, packages/web-components — plus 62 suites / 327 tests in user-ui. [2026-09-26 00:35:00] backend: jest globals not resolving in tests/api/*.test.ts. Symptom: "Cannot find name 'describe'. Do you need to install type definitions for a test runner? ... add 'jest' to the types field in your tsconfig" reported for @apps/backend/tests/api/cache-products.test.ts. Diagnosis: apps/backend/tests/tsconfig.json only extends ../tsconfig.json, so its typeRoots come from the app config: "typeRoots": ["../../node_modules/@types", "./node_modules/@types", "../shared-types"] Those paths are written relative to apps/backend. @types/jest is installed at the repo root (hoisted), so a run that resolves them relative to apps/backend finds it and passes (`bun run test:api:typecheck` is clean), which is why the CLI never complained and the repo `typecheck` script stays green — that script runs `tsc --noEmit` from each app root, and apps/backend's own include does not cover tests/ at all. A checker that resolves the inherited relative paths against the inheriting config (apps/backend/tests/) looks at apps/node_modules and apps/backend/tests/node_modules instead, finds no @types/jest, and drops the jest globals. Fix: declare the type roots in tests/tsconfig.json itself, with paths correct for its own directory, and name the globals explicitly: + "typeRoots": ["../../../node_modules/@types", "../node_modules/@types"], + "types": ["jest", "node"] Both are idempotent with the inherited values under correct resolution and independent of it under the other. Verified after the change: test:api:typecheck clean and one API suite still green (ts-jest reads this tsconfig, so a restricted `types` array had to be proven not to break the runner). [2026-09-26 00:40:00] backend: tsconfig fix verified. - from apps/backend/tests, ../../../node_modules/@types/jest and ../node_modules/@types/node both resolve (the earlier ls that said otherwise was run from apps/backend, one level up); - `bun run test:api:typecheck` (tsc --noEmit -p tests/tsconfig.json) clean — all 21 test files including tests/api/cache-products.test.ts; - ts-jest still works with the restricted types array: health + auth suites run green (6 tests); - the app project (`npx tsc --noEmit` in apps/backend) stays clean, so the repo `typecheck` script's verdict for apps/backend is unchanged. The same nested-tests-tsconfig hazard does not apply to apps/user-ui — it has a single root tsconfig that the tests are checked through, so there are no inherited relative paths to misresolve. [2026-09-26 01:00:00] backend: image upload integrity suite. New: apps/backend/tests/api/uploads.test.ts. Purpose: prove that what the app asks for and what it later reads back are the same bytes — the presign -> PUT -> GET round trip, not just the shape of the response the existing user-surface case asserts. Mechanics: the presigned PUT carries its own signature, so the test process needs no R2 credentials: it PUTs a real PNG to the URL common.generateUploadUrls returns, then GETs / (assetsDomain comes from common.essentialConsts via helpers/cache.ts, the same source the app uses) and compares bytes and sha256. The key is derived from the presigned URL the way extractKeyFromPresignedUrl does (last two path segments after the bucket). Cases: (1) a single PNG round-trips byte-identically with a matching content-length; (2) two uploads in different folders stay distinct and each serves its own bytes; (3) one call with two mime types returns two usable URLs whose objects hold their own bytes. Per instruction the same-millisecond key collision in generateUploadUrls is NOT covered here. Writes real objects into the dev bucket and leaves them, consistent with the existing data policy. [2026-09-26 01:10:00] backend: uploads suite verified + documented. Verified: apps/backend/tests/api/uploads.test.ts 4/4 green on the first run — the presigned PUT to R2 worked from the test process and every object read back byte-identically from the public assets domain, with the 404 case proving the read-back is real. Full run 22 suites / 107 tests green (was 21/103); test:api:typecheck clean. Documented in apps/backend/test-case-info.md: header total 22/107, a new `api/uploads.test.ts` section (cases 104-107), and four findings — a presigned URL is usable with no credentials and unsigned Content-Type; the `${folder}/${Date.now()}${ext}` key (same-ms collision left uncovered by request); every presign writing a pending status row that claimUploadUrl flips; and the untested remainder (claim/re-claim, deleteImageUtil on replacement). [2026-09-26 02:00:00] stale-data fixes across user-ui + admin-ui (from the mutation-refetch audit). Planned changes (all app code): A. Dead invalidations — the raw queryClient.invalidateQueries keys are dotted strings, which can never match a tRPC v11 key ([pathArray, {type}]): apps/user-ui/components/CheckoutAddressSelector.tsx:37 ['user.address.getUserAddresses'] apps/admin-ui/.../customize-app/popular-items.tsx:214 ['const.getConstants'] apps/admin-ui/.../customize-app/all-items-order.tsx:180 ['const.getConstants'] apps/admin-ui/.../product-tags/order.tsx:169 ['const.getConstants'] -> switch to trpc.useUtils()..invalidate(). Note the admin const procedures are admin.const.*, so the old string was wrong twice (missing 'admin' and a string not an array). B. packages/ui/hooks/useMarkDataFetchers.ts — refresh-on-focus fired only from the 3rd focus (`focusCountRef.current > 1` from a ref starting at 0) and the callback was frozen by useCallback(..., []). Fix keeps a callback ref (so the focus effect does not re-run on every render, which would loop) and fires from the 2nd focus. C. admin-ui mutations that leave the same screen stale (no refetch at all): products/detail/[id].tsx respondToReview -> refetch getProductReviews manage-orders/order-details/[id].tsx generateCancellationCoupon -> refetch getOrderDetails manage-orders/order-details/[id].tsx initiateRefund -> refetch getOrderDetails manage-orders/delivery-sequences/… handleSaveSequence -> refetchSequence/Orders dashboard-banners/index.tsx handleEmptySlot -> refetch getBanners manage-orders/delivery-sequences/… onAttachLocation={() => {}} -> refetch both D. admin-ui edit screens that never refresh their own detail query — invalidate the router: product-tags/edit/index.tsx, dashboard-banners/edit/[id].tsx, components/SlotForm.tsx (update path), components/ProductGroupForm.tsx Not touched: the identical dotted-key bug in apps/admin-web (3 sites) and apps/web-ui (3 sites), outside the two apps in scope; apps/user-ui/utils/queryClient.ts staleTime: 1200000 is a policy call and is left as-is. [2026-09-26 02:30:00] stale-data fixes applied — A, B, C, D. A. Dead invalidations replaced (dotted string -> tRPC utils, key built by the library): apps/user-ui/components/CheckoutAddressSelector.tsx utils.user.address.getUserAddresses.invalidate() admin-ui customize-app/popular-items.tsx utils.admin.const.getConstants.invalidate() admin-ui customize-app/all-items-order.tsx utils.admin.const.getConstants.invalidate() admin-ui product-tags/order.tsx utils.admin.const.getConstants.invalidate() Each of the three admin files then had an unused queryClient + useQueryClient import; both removed. B. packages/ui/hooks/useMarkDataFetchers.ts rewritten: the callback is held in a ref (so the focus effect does not re-subscribe on every render, which would refetch in a loop) and the guard is now `focusCountRef.current > 0`, so the second focus refreshes. Previously `> 1` skipped the first return-to-screen entirely and the callback was frozen at first render. C. Same-screen refetches added (admin-ui): products/detail/[id].tsx respondToReview -> utils.admin.product.getProductReviews.invalidate() order-details/[id].tsx generateCancellationCoupon -> refetch() order-details/[id].tsx initiateRefund -> refetch() delivery-sequences/index.tsx handleSaveSequence -> refetchSequence() + refetchOrders() dashboard-banners/index.tsx handleEmptySlot -> refetch() delivery-sequences/index.tsx onAttachLocation={() => {}} -> refetchOrders() + refetchSequence() D. Edit screens now invalidate what they were seeded from (admin-ui): product-tags/edit/index.tsx utils.admin.product.getProductTagById.invalidate() dashboard-banners/edit/[id].tsx utils.admin.banner.getBanner.invalidate() components/SlotForm.tsx (update) utils.admin.slots.invalidate() components/ProductGroupForm.tsx utils.admin.product.getGroups.invalidate() Tests: apps/user-ui/tests/lib/query-invalidation-keys.test.tsx (new, 1 test) pins the root cause without touching the network — it reads the key tRPC actually produced ([['user','address','getUserAddresses'], {type}]) and asserts getQueryCache().findAll() matches the array form and returns nothing for the dotted form. findAll runs the same matcher invalidateQueries uses, so it is the invalidation semantics minus the round trip. Verified: apps/user-ui 63 suites / 328 tests green; test:typecheck clean; apps/admin-ui `tsc --noEmit` clean (it has no test harness, so C/D are compile-verified only). Still open, unchanged and out of the requested scope: the same dotted-key bug in apps/admin-web (3 sites) and apps/web-ui (3 sites), and the user-ui client's staleTime: 1200000 policy — fixing the invalidations removes the steady-state staleness but a 20-minute staleTime still means any future missed invalidation is durable. [2026-09-26 03:00:00] tests for the stale-data fixes. New: apps/user-ui/tests/hooks/useMarkDataFetchers.test.tsx — pins fix B by driving the focus lifecycle explicitly (the global setup mocks useFocusEffect to run once on mount, so this file overrides it with a version that records the callback and lets the test fire further focuses). Cases: the first focus does not refresh, the second does (the old `> 1` guard skipped it), and after a re-render the newer callback runs rather than the one captured on mount (the frozen useCallback). Extended: apps/user-ui/tests/components/address-selectors.test.tsx — pins fix A end to end. Asserts that '+ Attach Current Location' sends the mocked coords via user.address.updateAddress AND that user.address.getUserAddresses is fetched a second time afterwards; with the old dotted key that refetch never happened, so this fails against the previous code. Not testable today: the admin-ui half (C + D). apps/admin-ui has no jest config, no mocks and no provider harness — nothing in that app has ever been rendered under test. Recorded rather than faked; scaffolding a harness for it is a separate, larger job. [2026-09-26 03:30:00] tests outcome — one landed, one abandoned with the reason. Landed: apps/user-ui/tests/components/address-selectors.test.tsx +1 test (3 -> 6 total, was 5 with two QuickDelivery cases): "refreshes the addresses after attaching the current location". It presses the Attach button (the expo-location stub grants permission and returns 17.385/78.4867), asserts updateAddress receives those coords, then asserts user.address.getUserAddresses is fetched a SECOND time. Against the old dotted-string key that second read never happened, so the test pins fix A. apps/user-ui/tests/lib/query-invalidation-keys.test.tsx (already in place) pins the same class at the key level via getQueryCache().findAll(), which uses the matcher invalidateQueries uses. Abandoned: a useMarkDataFetchers test (fix B). Three attempts failed for the same reason: the hook's `useFocusEffect` never reaches the mock. Instrumentation settled it — a console.log inside the useFocusEffect override in tests/setup.ts never fires while the hook renders successfully, so packages/ui's import of '@react-navigation/native' resolves to a DIFFERENT module instance than the app's (bun's symlinked install; jest keys the mock by resolved path). A per-file jest.mock(...) does not intercept it either. I tried a shared seam (tests/mocks/focus.ts recording callbacks + re-exporting fireFocus from the setup mock) and that failed the same way, so both the seam and the test were reverted rather than left dead. tests/setup.ts is byte-identical to before. Consequence worth knowing: the setup comment claims its useFocusEffect override "runs the callback once on mount ... so focus-driven side effects are testable", but for the shared hook in packages/ui that override is not in play at all. Making fix B testable needs either a NavigationContainer in the test (so the real hook works) or a mock registered for the instance packages/ui actually resolves. Not attempted here. Result: apps/user-ui 63 suites / 329 tests green; test:typecheck clean. The admin-ui half (fixes C and D) still has no harness — that app has no jest config at all, so nothing in it is testable today. [2026-09-28 11:20:00] admin-ui: tests for the mutation -> refetch / invalidation behaviour. Discovery that changes the picture: apps/admin-ui ALREADY has a full jest harness (tests/jest.config.js, setup.ts, mocks, helpers, test + test:watch + test:typecheck scripts) and 64 suites / 481 tests, all green. Earlier claims in this session that the app had no harness were wrong. So this is not a scaffolding job after all — it is coverage for the refetch code, in the existing test files. An audit of the 14 files that got an invalidate()/refetch() found only THREE assertions that would fail if the line were removed: product-tags/edit (62 refetchTags), banners/index (195 delete refetch) and the mark-data-fetchers hook tests. Everything else is unasserted. Adding cases to the per-screen files. Case pattern for same-screen refetches: capture procCount(proc) before the interaction, perform it, then assert procCount(proc) grew — the invalidation refetches the query this screen has mounted, so removing the line leaves the count flat and the test fails. Case pattern for cross-screen invalidations (the list query lives on the screen BEHIND the form): seed the query cache through the shared queryClient, act, then assert the seeded key's state is marked isInvalidated — an invalidation sets that on every matching cache entry even with no mounted observer, so this pins the call without needing the other screen rendered. [2026-09-28 12:40:00] admin-ui refetch coverage landed: 12 new cases across 12 files + 2 extended. The harness in apps/admin-ui is UNCOMMITTED work: apps/admin-ui/tests/ is untracked (git ls-files -> 0) and the test + test:watch + test:typecheck scripts and the jest devDeps in apps/admin-ui/ package.json, plus the metro.config.js blockList entry, are modified but uncommitted. That is why it looked like the app had no harness. Baseline before this work: 64 suites / 481 tests, green. What was added (all in apps/admin-ui/tests): screens/product-tags-edit.test.tsx +1 getProductTagById invalidated -> refetched after Update Tag screens/banners-edit.test.tsx +1 getBanners refetched AND getBanner invalidated after Update Banner screens/banners-index.test.tsx +0 extended the save-changes and empty-slot cases with a list refetch assertion screens/products-detail.test.tsx +1 getProductReviews invalidated -> refetched after Submit Response screens/delivery-sequences.test.tsx +1 extended the packaged case + new save-sequence case: getSlotOrders and getDeliverySequence both refetched. The file's header claimed the save FAB was unreachable; it IS reachable via the mocked list's onDragEnd prop. screens/coupons-create.test.tsx +1 getAll + getReservedCoupons invalidated with array paths screens/coupons-edit.test.tsx +1 getById refetched (mounted) + the two list invalidations screens/stores-edit.test.tsx +1 getStoreById refetched (mounted) + getStores invalidated components/slot-form.test.tsx +1 admin.slots invalidated -> getSlotById refetched components/product-group-form.test.tsx +1 getGroups invalidated on both create and update screens/customize-app-popular-items.test.tsx +1, customize-app-all-items-order.test.tsx +1, screens/product-tags-order.test.tsx +1 getConstants invalidated -> refetched after Save Two assertion shapes, both chosen so the test fails if the fix is removed: 1. mounted-observer (9 files): capture procCount(proc) immediately before the interaction and assert it GREW. Deliveries to react-query are async, so the assertion sits in waitFor. 2. cross-screen (5 files): the invalidated list query is mounted on the screen BEHIND the form, so no request is issued and a fetch count proves nothing. Those inject a client via renderWithProviders' queryClient option and spy on invalidateQueries, then assert a call arrived whose filter's first element is the ARRAY path, e.g. ['admin','coupon','getAll']. That is the root cause made testable: the old dotted string produced ['admin.coupon.getAll'] and matched nothing. Causality, not assumption: every agent-writer proved its case empirically by running the test file against an off-repo copy of the screen with the invalidation/refetch stripped, and for the 5 spy-based files also with the dotted form restored - each time only the new case failed and the pre-existing cases stayed green. The three customize-app/product-tags cases additionally assert, in-repo and with no copies, that the same query cache matches the array path while the dotted form matches zero queries (getQueryCache().findAll). Mistake worth recording: those same three cases were first written with `expect(before).toBe(1)` and they broke the suite the moment it was run as a whole (before was 2). The cause is the module-singleton httpBatchLink client: a request from an earlier test in the same file lands in the next test's fetchMock. Every count assertion in this work is therefore a delta captured at the point of interaction, never an absolute. Not covered, deliberately: order-details initiateRefund / generateCancellationCoupon. Their dialogs are commented out in the source, so those handlers are unreachable from the UI; the test file already documents this. Result: apps/admin-ui 64 suites / 493 tests green, stable across two consecutive full runs. No app source was modified (git diff over apps/admin-ui/{app,components,hooks,src} is empty).