Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
Lessons Learned
Recurring patterns and mistakes to avoid. Review at session start for relevant tasks.
Format: Context → Problem → Rule → Applies to
Onshape individual release assets need the complete source identity
Context: Syncing a released part from a multi-part Part Studio to an existing Carbon item.
Problem: Omitting partIds and configuration exports the whole studio; getElementThumbnail also depicts the entire element. Refreshing raw data under the same model ID leaves successful optimized artifacts in place and allows old background jobs to overwrite repaired assets.
Rule: Resolve one exact released document/version/element/revision and propagate its part ID and configuration. Never fall back to a version-only match or unselected Part Studio export. Render the selected model's thumbnail after optimization. Give corrected individual-part sources deterministic immutable model generations, preserving item IDs and manufacturing records; repeat repairs reuse that generation. Repair existing items with explicit per-release events, not a company-wide backfill or new CAD releases.
Applies to: Onshape revision sync, backfill, model export and attachment helpers in packages/jobs/src/inngest/functions/integrations/.
Sales-order Paid Amount uses invoice-target principal
Context: Summarizing linked sales-invoice payments on a sales order.
Problem: invoiceSettlement.sourceAmount is principal in the payment funding source's currency, so it does not represent the amount applied to the invoice. Using it for the order's Paid Amount disagrees with the invoice Payments panel and can mix currency semantics.
Rule: Sales-order Paid Amount sums posted payment appliedAmount (company base) per invoice, then converts it with that invoice's exchange rate into the matching order currency. Do not use sourceAmount for this summary. There is no legacy baseStatus === "Paid" fallback that counts the full invoice total — every payment flows through invoiceSettlement, so a fully-paid invoice's settlements already sum to its total.
Applies to: getSalesOrderInvoicePaymentsByIds, the sales-order loader's invoiceSummary, and any UI summarizing cash applied to invoice targets.
ioredis retryStrategy returning null kills auto-recovery
Context: Making the Redis client (@carbon/kv) resilient to outages (issue #1076).
Problem: A retryStrategy that returns null after N attempts (e.g. if (times > 3) return null) tells ioredis to stop reconnecting permanently. Once Redis is briefly unreachable the client gives up and every later command fails with "Connection is closed." even after Redis is healthy again — the app never recovers without a process restart. Command-level timeouts/try-catch cannot fix this; it is a connection-lifecycle setting. Unit tests with ioredis-mock do NOT catch it — only a real kill-and-restart test does.
Rule: For long-running servers, retryStrategy must keep reconnecting with capped backoff (min(times * 200, 5000)) and never return null. Bound per-command latency elsewhere (maxRetriesPerRequest + a timeout wrapper), not by abandoning reconnection. Verify recovery by stopping and restarting a real Redis, not just mocks.
Applies to: packages/kv/src/client.ts, packages/kv/src/resilient.ts, any ioredis client config.
Permission scope renames are invisible to typecheck
Context: Renaming DB RLS policies (e.g., plm_* → production_*) as part of a module rename.
Problem: The app layer's requirePermissions() and permissions.can() calls use string literals like "plm". These are invisible to TypeScript's type checker and linter — the rename passes all automated checks but 403s every route at runtime.
Rule: When renaming permission scopes, grep the ENTIRE codebase for all string literal references, not just the DB layer. Check requirePermissions, permissions.can, usePermissions, route loaders, and any conditional UI gating.
Applies to: Any permission or scope rename, apps/erp/app/routes/, apps/erp/app/modules/.
Multi-tenancy: every query must scope by companyId
Context: Writing service functions that query the database.
Problem: Forgetting to include .eq("companyId", companyId) in a query exposes cross-tenant data. RLS provides a safety net, but defense in depth requires application-level scoping too.
Rule: Every database query in a service function MUST include companyId scoping. Never rely solely on RLS for tenant isolation — treat it as a backup, not the primary guard.
Applies to: All *.service.ts files, any Kysely or Supabase query.
ValidatedForm needs the validator, not the raw schema
Context: Building forms with zod validation.
Problem: Passing a raw zod schema to ValidatedForm instead of wrapping it with validator() from @carbon/form results in silent validation failures — the form submits without client-side validation.
Rule: Always use validator(schema) from @carbon/form, not the raw zod schema. Validate with validator(schema).validate(formData), not schema.parse().
Applies to: All forms in apps/erp/app/routes/, packages/form/.
Features live inside existing permission modules
Context: Building a new feature that belongs to an existing domain (e.g., assembly instructions within production).
Problem: Creating a standalone module enum value / permission family (Assembly module with assembly_* permissions) for something that is really part of an existing domain. Assembly instructions belong to production, governed by production_<view|create|update|delete>.
Rule: Don't invent a new module/permission family for a feature that fits an existing domain. Add a sub-link in the existing sidebar group (like Procedures) and a full-screen editor in its own route tree (x+/assembly+/$id, handle.module: "production", mirroring x+/procedure+/). Pattern: list route under x+/<module>+/<plural>.tsx, full-screen editor in a sibling x+/<singular>+/ tree whose _layout.tsx declares the parent module. Module folder = permission module = nav module.
Applies to: New features under apps/erp/app/routes/x+/, apps/erp/app/modules/.
Assembly viewer camera + animation principles
Context: Camera transitions and part-motion animation in the assembly instruction viewer (packages/viewer).
Problem: Per-step re-zooming and pure-geometry view heuristics lose the "where are we on the model" context; small fasteners are invisible at assembly scale; sparse path sampling produced false "removable" results (washer/bolt ordering bugs).
Rule (user directives):
- Constant zoom, rotate-only: per-step camera transitions keep the standing whole-assembly distance and only rotate toward the action — never re-zoom per step or frame a single small part tightly.
- Occlusion-aware angles: choose view direction by scoring how many parts block the line of sight to the animated part (seated pose + travel midpoint), not by pure geometry heuristics.
- Exaggerate small parts: bolts/washers get display-only exaggerated travel (>=2.5x their size) so insertions read at assembly scale.
- Manual motion editing is a 0.001% escape hatch: keep it collapsed behind "Edit manually"; motions come from the geometry planner.
- Planner correctness beats coverage: cap sample spacing (2mm) rather than sample count. Threaded fasteners need a thread-depth penetration allowance along their own axis because CAD models them as interfering solid cylinders.
Applies to: packages/viewer/, geometry planner (crates/planner).
"What is drawn" and "what blocks the view" must be derived from one predicate
Context: Adding installedMode to the assembly viewer (packages/viewer/src/visibility.ts). Two pieces of code answered questions about the same timeline: visualForComponent decided how a component renders, while the camera's AABB view-direction scorer decided how much it counts as an obstacle. The scorer was written inline inside AssemblyPlayer, hundreds of lines away.
Problem: They disagreed on one input. visualForComponent treats a component that no step installs exactly like a future-step one ("never already there"), so under the MES default futureMode: "hidden" it rendered hidden. The inline scorer computed isFuture = stepIndex !== undefined && stepIndex > activeStepIndex — undefined failed that test, so the same component kept full occluder weight. The camera picked view angles that dodged geometry it was not drawing. Silent: no error, nothing visibly broken, just subtly worse framing that no test covered because the logic was un-extractable inline.
Rule: When one fact (here: a component's position relative to the active step) drives both what the user sees and what the system reasons about, derive both from a single exported predicate in the same module, and assert the invariant that links them — anything invisible is never an obstacle — over the full cross-product of modes, not over hand-picked cases. The cross-product test is what caught this; a case-by-case test would have encoded the bug. Extracting the inline logic is the fix, not adding a comment telling the next person to keep them in sync.
Applies to: packages/viewer/src/visibility.ts (visualForComponent / occluderWeight), packages/viewer/src/AssemblyPlayer.tsx; any pair of render-vs-reason helpers over the same state.
Posting-group-style matrices are a rejected pattern
Context: Designing multi-jurisdiction tax determination; the spec anchored on the customerType × itemPostingGroup posting-group matrix as "Carbon precedent."
Problem: The posting-group matrix was deliberately REMOVED (20260229000000_drop-posting-groups.sql) because the indirection was confusing — but the 2023 creation migration still exists, so searches find it first and it masquerades as live precedent. Anchoring a new design on it resurrects a pattern the project already rejected.
Rule: Do not design N×M classification-matrix configuration (party-group × item-group → outcome). Prefer flat company defaults (accountDefault) plus direct per-entity assignment with per-child override (the Xero model). Before citing any schema "precedent," grep for a later DROP/rename migration.
Applies to: New config/settings design anywhere; accounting/tax/posting; .ai/specs/, packages/database/supabase/migrations/.
Backdated migration timestamps break remote deploys
Context: CI supabase db push --include-all failed on all remotes with column pi.balance does not exist while applying 20260616061244, which recreated the purchaseInvoices view.
Problem: A migration merged with a timestamp OLDER than already-deployed migrations gets applied out of order on remotes: the remote had already run 20260630095023 (drops purchaseInvoice.balance), so the backdated view recreation referenced a dropped column. Worse, the newer 20260630* batch had forked its view body from a pre-fix definition, silently reverting the backdated migration's fix (supplierShippingCost multiply vs divide) — the backdated migration was both broken AND dead code.
Rule: Never merge a migration whose timestamp is older than the newest migration already on main/deployed. Before writing a view/RPC recreation, fork from the NEWEST definition of that view (grep all migrations, take the last). When rescuing a failed backdated migration, strip the superseded parts and re-land the still-wanted change in a fresh forward-dated migration; don't rename already-partially-applied files (re-applies them).
Applies to: packages/database/supabase/migrations/, ci/src/migrations.ts, any long-lived branch adding migrations.
Never resolve a control account by number/name
Context: Posting intercompany invoices/payments needed the "Inter-Company Receivables" control account. The edge functions (post-sales-invoice, post-payment) fetched it with .eq("number", "1130").
Problem: Account number and name are user-editable at any time. Resolving a control account by a hardcoded number silently mis-posts the moment someone renumbers/renames the account — no error, wrong GL account. It also duplicates a magic constant across posting paths that can drift.
Rule: Resolve internal/control accounts by id via a column on accountDefault scoped to the companyId (the same pattern as receivablesAccount/payablesAccount). If no default column exists, add one to accountDefault (+ seed it in seed.data.ts and seed-company, + one-time backfill migration resolving the seeded number → id), then read ad.<xxx>Account. The only legitimate uses of .where("number"/"eq("number") on account are: building the chart at seed time, and mapping external codes in an integration (e.g. Xero AccountCodes) — never resolving an internal control account at posting time.
Applies to: the post-* postings (apps/erp/app/modules/*/*.service.ts), close-job, issue, anything posting to journalLine; accountDefault schema + lib/seed.data.ts.
Chart-of-accounts group headers have no number — resolve parents by name/key
Context: 20260524143827_fixed-assets.sql seeded a "Deferred Tax Expense" (7090) account for every existing company group, resolving its parent with number = '7000' AND "isGroup" = true.
Problem: Group header accounts in Carbon's chart carry number = NULL (they are identified by seed key/name, e.g. other-expenses / "Other Expenses") — only leaf posting accounts have numbers. The lookup silently returned NULL and the account was inserted with parentId = NULL, leaving it orphaned at the root of the chart for every pre-existing company. New companies were unaffected because seed.data.ts parents via parentKey. The bug is invisible in dev (fresh seeds go through seed.data.ts) and only shows on long-lived databases.
Rule: In migrations that insert account rows, resolve the parent group by "isGroup" = TRUE AND name = '<Group Name>' (optionally + class), never by number — and treat a NULL parent as an error or explicit fallback, never insert silently orphaned. 20260630093809_ar-ap-payments.sql is the correct precedent. When a past migration did orphan accounts, ship a follow-up UPDATE re-parenting parentId IS NULL rows to the group seed.data.ts assigns (see 20260702192816).
Applies to: packages/database/supabase/migrations/ touching account; packages/database/src/seed-data.ts; anything walking the chart-of-accounts tree.
Never fabricate a "best-effort" motion through geometry
Context: The assembly motion planner (crates/planner/src) had a tier-4 "forced removal" that gave unsolvable parts a straight-line motion through whatever blocked them, so every part animated. On the seat-rail assembly 6/30 parts got 48–647mm fly-through motions early in the sequence — the whole animation read as wrecked.
Problem: A fabricated path is worse than no path: it renders as a collision, erodes trust in every other step, and hides the real geometric finding (interlocked unit, embedded solid, missing mate exemption) behind a fake answer.
Rule: When a solver can't prove a result, emit an explicit flagged state (motion: "none" + blockedBy + warning) and give the UI a degraded-but-honest rendering (fade-in at the seated pose). Never ship a fabricated approximation of a geometric/physical claim. Same for display fallbacks: an AABB "least-blocked direction" guess may only be used where it's labeled as a guess, never silently for planner output.
Applies to: crates/planner/src, packages/viewer (fallback.ts, AssemblyPlayer), generateAssemblyStepsFromPlan.
Penetration tolerances must stay far below sample spacing
Context: The planner allowed 1.5mm "thread depth" penetration along a fastener's axis versus ALL parts, with collision samples every 2.0mm, to make solid-thread models removable through their nuts.
Problem: Tolerance ≈ spacing means a thin blocker (1mm washer, flange, cover) can pass between samples entirely below the allowance — the part "removes" through solid metal, which scrambles the greedy disassembly order downstream. A blanket allowance also applies to parts that have nothing to do with the threads.
Rule: Scope allowances to the specific mating pair that justifies them (fastener ↔ its detected threaded mate, capped at the seated interference + margin), keep the global tolerance an order of magnitude below sample spacing, and locally refine sampling near any contact that approaches the tolerance.
Applies to: crates/planner/src collision sampling; any sampled sweep/clearance check.
trimesh CollisionManager rebuilds BVHs on every single-object query
Context: Re-planning the 31-part seat rail took ~2 hours; the old planner took ~59s. manager.in_collision_single(mesh, transform) builds a fresh FCL BVH for the queried mesh on EVERY call, and the greedy loop also removed/re-added parts per attempt (another BVH rebuild each).
Rule: For sampled sweeps, cache the FCL BVH per mesh (mesh_to_BVH once, fcl.CollisionObject per query) and collide against manager._manager directly; never remove/re-add a manager object to "exclude" it — filter its contacts by name with an infinite allowance instead. Bound sampling by the AABB separation distance (beyond it, disjointness is provable).
Applies to: crates/planner/src (_contacts_at, _self_exempt), any trimesh/fcl sampling loop.
Don't pre-sign a short-lived upload URL before a long-running operation
Context: assembly-plan pre-signed a createSignedUploadUrl for plan.json, then called the geometry /plan service which ran the motion planner (~3 min) and finally PUT the result to that URL. Uploads 400'd and the job stuck in Processing forever; the ERP UI polled "Solving motions…" indefinitely.
Problem: Supabase createSignedUploadUrl mints a 60-second token and the SDK gives no way to extend it (it only honors { upsert }; the TTL is a storage-server setting). By the time a multi-minute planner finished, the token had expired → 400 InvalidJWT "exp claim timestamp check failed" → the service returned 502. The fast /convert path (~16s) never tripped it, so the pattern looked fine. Re-runs/"already exists" are a red herring — an upsert PUT to an existing object returns 200.
Rule: A pre-signed upload URL must be consumed within ~60s of minting. For any operation that can outlast that, don't hand the worker a pre-signed PUT URL — have the service return the artifact inline and let the worker persist it with the service-role client the moment it has the bytes (no token, no expiry). Also bound the outbound fetch with AbortSignal.timeout(...) so a hung service fails cleanly (→ onFailure marks the row Failed) instead of pinning it in Processing.
Applies to: packages/jobs/src/inngest/functions/tasks/assembly-plan.ts, apps/assembler/src/main.rs (/plan); any Inngest task that pre-signs storage upload URLs before a slow external call.
Direct psql DDL needs a PostgREST schema-cache reload
Context: Applied an unshipped migration's delta (drop assemblyGroup, create assemblyUnit) to the local DB with psql instead of crbn migrate, to avoid a full rebuild. The ERP page then hung: the $id loader's Promise.all timed out (fetchWithRetry TimeoutError) even on queries against unrelated tables.
Problem: PostgREST caches the DB schema. crbn migrate / db:migrate reload it after applying migrations; a raw psql DDL does not. With a stale cache, queries against the changed tables can't resolve and hang, which exhausts the connection pool and times out other queries too. (Confirmed after: assemblyGroup returned PGRST205 "Could not find the table in the schema cache".)
Rule: After any direct-psql schema change to a local Supabase DB, reload PostgREST — psql -c "NOTIFY pgrst, 'reload schema';" (or docker restart <...>-postgrest-1). Prefer crbn migrate when possible; when patching by hand (e.g. editing an unshipped migration in place), the reload is a required follow-up.
Applies to: any local schema change applied outside crbn migrate; symptom is loader/REST timeouts after a DDL patch.
Synthetic box meshes fake huge penetration under sustained sliding contact
Context: Writing planner ordering tests (test_part_with_blocked_insertion_is_not_demoted) with raw trimesh.creation.box parts: a slider seated 0.05mm into a channel floor read as depth 29.8mm against the rail at every sweep sample, so the planner declared it inseparable and rigid-merged it.
Problem: FCL reports per-triangle-pair local penetration. A box face is two giant triangles; two near-coplanar giant triangles overlapping 0.05mm in the normal direction report a depth spanning their tangential overlap. Real STEP models never hit this — tessellation at linearDeflection keeps triangles small, so local depths stay bounded by element scale. The artifact only appears in synthetic tests whose parts sustain face-on-face sliding contact; brief seated contact that separates immediately (stacked boxes lifting off) is fine.
Rule: In planner tests, any part that must SLIDE while touching another needs mesh.subdivide_to_size(5.0) on both meshes — and prefer seating the moving part against a face perpendicular to its travel (contact vanishes on the first sample) over a face parallel to it (contact persists the whole sweep). Also avoid geometry where a seated bite must scrape past an opening sill: that is a real interference, not an artifact.
Applies to: crates/planner/tests synthetic fixtures; debugging any "cannot separate / planned as one rigid unit" result on hand-built trimesh geometry.
Ordering heuristics must be gated on a large noisy model, not just the seat rail
Context: The weakly-secured-last + sandwich-gasket refactor validated green on 47 unit tests and a byte-identical 31-part seat-rail baseline, then made real planning slower with worse results. A 20-line classification probe on the 118-part SA Mando & Battery Harness immediately showed why: 4 sandwich detections — ALL false positives, including a 33mm "thin" part (ratio-only thinness cap) and two 10.4mm isotropic pass-through allowances (uncapped observed depth granted as "compliant squish").
Problem: The seat rail is a best-case model: named fasteners, clean contacts, no ambiguous plate stacks. Proxy signals calibrated there (name-only fastener detection, contact counts, thinness ratios) explode on models with unnamed hardware, clearance fits, and interpenetrating CAD. Two failure classes: (1) a preference wired into the greedy removal priority is not a preference — that ranking schedules expensive removal attempts and picks flag/merge victims, so fronting hard-to-remove parts multiplies failed sweeps (slower); (2) any heuristic that grants collision allowances fails open — one false positive corrupts collision truth for every sweep it touches (worse).
Rule: Before shipping a planner ordering/allowance heuristic: (a) run the classification-only probe (.ai/scratch/geometry-probe.py) on a large noisy model (harness/BCU class) and eyeball every cohort member and every allowance value — a 10mm "squish" is a bug, not a gasket; (b) keep display preferences in the topo sort only, never in removal_priority; (c) cap and axis-gate anything that relaxes collision tolerance, and prefer fail-closed (reject classification) over fail-open (grant allowance) when evidence is out of range.
Applies to: crates/planner/src ordering preferences, _sandwiched_parts-style classifiers, any future exempt/allowance mechanism.
Profile the planner before optimizing — the flood was pass-through, not self-collision
Context: Motion planning took ~3 min (seat rail) / >30 min (harness). A micro-benchmark showed a 2,000× per-sample cost for a part colliding with its own seated copy (it stays registered in the manager), so the "obvious" fix was to unregister the moving part during its own sweeps. Implemented, byte-identical output — and zero real-model speedup (191→211s). cProfile told the truth: 86% of total time was _contacts_at under _path_blockers, dominated by pass-through enumeration — sweeping a part THROUGH its blockers enumerates the blocker's full triangle-contact set (53M contact objects on a 31-part model) at every sample for the whole travel, when all _path_blockers needs is each blocker's identity, discovered once.
Problem: Micro-benchmarks measure the mechanism you built them around, not the workload. Self-collision flooding is real but self-overlap ends early in most sweeps; deep pass-throughs persist for hundreds of samples and were the actual cost. The two look identical from the outside (both are "too many contacts").
Rule: For planner performance work, cProfile the real model FIRST (cProfile.run('plan_step(...)') — 30s of setup) and read cumtime by caller before choosing a lever. The winning fix: in _path_blockers, once a partner is recorded as a blocker, unregister it from the broadphase for the remainder of the sweep and re-register before returning (registerObject/unregisterObject on the SAME CollisionObject rebuilds nothing — the BVH lives on the geometry). Seat rail 191–211s → 20–26s (8×), harness >30min → 9.5min, byte-identical sequences. Keep the self-unregister too (it's what makes the synthetic test suite 8× faster), but don't mistake it for the fix.
Applies to: crates/planner/src sweep functions (_path_blockers, _contacts_at, _unregistered); any future "collect all X along a path" collision query.
Verify what actually rendered before root-causing a "bad motion" report
Context: A user reported step 4's screw+washer "colliding through the 3D MARKETING and seat rail clamp" and asked for a motion-planning refactor. A trimesh/FCL sweep of the STORED motion against the real GLB meshes showed it was collision-free against the entire model — and the only geometrically feasible insertion (the reverse sense jams the washer into the clamp bore by 3.4mm). The visible garbage came from elsewhere: a re-motion job was still running, so steps played stale/"none" motions through the collision-blind AABB display fallback, on top of 26 never-installed components being rendered solid.
Problem: A "the animation collides" report conflates at least four layers: the stored plan motion, the display-time fallback synthesis (displayMotionForStep → synthesizeFallbackMotion), display adjustments (exaggerateMotion), and the visibility model (what else is on canvas). Root-causing the planner first is attacking the strongest layer — the geometry service's motion had verified: true and meant it.
Rule: Before touching planner code for a visual-collision report: (1) check assemblyPlanJob.status — Queued/Processing means the user watched placeholder motions; (2) dump the step's stored motion from assemblyInstructionStep and sweep it against the GLB (the collision crate, or a small trimesh script; storage files live in the storage container under /var/lib/storage/stub/stub/<bucket>/...); (3) only if the stored motion itself collides is it a planner problem — otherwise it's fallback/visibility/display-layer work in packages/viewer.
Applies to: assembly-instruction motion bug reports; packages/viewer/src/{motion,fallback,AssemblyPlayer}; crates/planner/src.
GLB node↔nodeId joins must be validated against graph.json bboxes
Context: Building BCU acceptance fixtures from the viewer GLB: nodeIds live in glTF node extras which trimesh drops, so the join went through world-transform matching. The geometry service bakes vertices in world space with identity node transforms — every node "matched" position (0,0,0) and the assignment silently scrambled 431 parts. The resulting degree/volume table looked plausible ("Seal Electronics Box, degree 19, 742cm³") and drove two wrong fix iterations before the graph.json bboxes exposed it.
Problem: A shuffled mesh↔name assignment still produces plausible-looking planner output — garbage in, plausible garbage out. Name-prefix or transform heuristics have no error signal of their own.
Rule: When joining GLB scene nodes to graph.json nodeIds, match on world BBOX against graph.json's per-leaf bbox (authoritative, written by the same converter) and assert coverage (all nodes matched, max error < 1mm) before trusting any downstream analysis. /tmp-fixture recipe: parse the GLB JSON chunk for extras + walk scenes for world matrices, then bbox-match to trimesh geometry.
Applies to: acceptance/repro scripts over viewer GLBs; any offline analysis pairing graph.json with model.glb.
Name-only fastener classification: "pin" and spec suffixes mark structure as hardware
Context: The SA BCU's enclosure is named "Electronics Box - 36 Pin" (a connector pin COUNT). The fastener name regex matched \bpin\b, classifying the box as hardware: removal priority fronted it (fasteners first → expensive failed sweeps → flagged early), base candidacy excluded it, and the assembly sequence anchored on a gasket. One word in a part name inverted the entire build order.
Problem: Fastener detection is name-only; real CAD names carry fastener-ish tokens in structural parts (pin counts, "M8 slot pattern" spec suffixes). A false positive is fail-open: it changes scheduling, exemptions, and base selection everywhere at once.
Rule: Never classify on ambiguous single tokens — "pin" is out (dowel pins still match via "dowel"). Back the name test with physical sanity in _classify_fasteners: a name-matched part spanning more than max(100mm, 0.35 × assembly diagonal) keeps its structural role. When ordering goes absurd on a new model, print the fasteners cohort first — one misclassified structural part explains a scrambled sequence.
Applies to: crates/planner/src (FASTENER_NAME_RE, _classify_fasteners, removal_priority, _reselect_base); future classification heuristics.
Client-side entity caches must be company-keyed in a multi-tenant app
Context: A prod company export failed its closure guard: a salesOrder (and its opportunity) in one company referenced another company's customer. Root cause chain: RealtimeDataProvider (ERP + MES) cached the customer/item/supplier/people lists in IndexedDB under global keys ("customers"), and company switching is a client-side navigation — so after a switch, the previous company's cached list could hydrate the pickers before the properly-scoped server fetch landed. Nothing downstream caught the bad pick: zod validated customerId as a bare string, services inserted it blindly, RLS only checks the row's own companyId, and the FK was single-column (customerId → customer(id)).
Problem: Any client cache (IndexedDB/localforage, localStorage, nanostores hydrated from them) that isn't keyed by companyId becomes a cross-tenant leak the moment a multi-company user switches companies without a full reload. Multi-company users legitimately pass RLS for both companies, so no server layer notices.
Rule: (1) Key every persisted client cache entry by company (customers:${companyId}) and guard async hydration callbacks against mid-flight company switches. (2) Tenant-scoped references between tables should be composite FKs (refId, companyId) → parent(id, companyId) so the DB rejects cross-company refs from every write path (see 20260703143904_composite-tenant-fks.sql, which converts customer/supplier refs introspectively and tolerates pre-existing bad rows via NOT VALID + warning).
Applies to: apps/{erp,mes}/app/components/RealtimeDataProvider.tsx, apps/erp/app/stores/*, any new client-side cache; migrations adding FKs to company-scoped parents.
Never feed a nullable user id into a NOT NULL audit column from a DB function
Context: A live demo failed to record production quantities, backflush materials, or complete the job. sync_update_job_operation_quantities auto-flipped the operation to Done without stamping updatedBy; sync_finish_job_operation then passed p_new->>'updatedBy' (NULL) as p_user_id into complete_job_to_inventory, whose itemLedger insert violated createdBy NOT NULL (23502) and rolled back the entire cascade. A sweep found the same latent bug in sync_purchase_invoice_line_price_change (payload updatedBy → NOT NULL purchaseInvoicePriceChange.updatedBy) — right next to a migration that had fixed the adjacent trigger for exactly this reason.
Problem: updatedBy is nullable on every table, and trigger/interceptor UPDATEs don't go through the app layer that normally stamps it. So p_new->>'updatedBy', NEW."updatedBy", and p_user_id DEFAULT NULL params are all NULL-able user sources; writing them into a NOT NULL createdBy/updatedBy/postedBy makes the whole transaction (including the user's original write) roll back with 23502. The failure is invisible in testing whenever the row happens to have been user-updated before.
Rule: In SQL functions: (1) any UPDATE issued by a trigger/interceptor that other interceptors may react to must stamp "updatedBy" (from the payload's createdBy/updatedBy) and "updatedAt"; (2) never write a payload user field into a NOT NULL column without a fallback — COALESCE(p_new->>'updatedBy', p_new->>'createdBy') (createdBy is NOT NULL on source tables); (3) functions taking p_user_id that write audit columns must not default it to NULL, or must guard right after BEGIN with a fallback to the entity's createdBy (see 20260706182830_fix-null-user-audit-columns.sql). When forking a large function to add such a guard, extract the newest body verbatim (sed) and diff-verify instead of retyping.
Applies to: packages/database/supabase/migrations/ — all sync_* interceptors and any PL/pgSQL function writing createdBy/updatedBy/postedBy; reviews of new event-system interceptors.
A LANGUAGE sql set-returning function's internal ORDER BY is not guaranteed through PostgREST
Context: get_available_tracked_entities (a LANGUAGE sql STABLE set-returning function) was extended with a p_sort_method param and a CASE-based ORDER BY (FEFO/FIFO/LIFO) to power an on-the-fly picking suggestion. FEFO worked, but calling the RPC for FIFO returned rows in the wrong order — its only effective sort key was the trailing te."createdAt" ASC, which came back unordered. Adding an explicit outer ORDER BY "createdAt" at the call site fixed it, proving the function's internal order was being dropped.
Problem: The Postgres planner inlines simple LANGUAGE sql functions into the calling query; when the caller (here, PostgREST via client.rpc(...)) supplies no outer ORDER BY, the inlined subquery's ORDER BY can be optimized away. Ordering that leads with a real indexed/leading column (expiration for FEFO) may survive by luck; ordering whose only key is a trailing column silently does not. Unit tests and typecheck can't catch this — only real-data querying does.
Rule: Do not rely on a LANGUAGE sql set-returning function's internal ORDER BY to reach the app. Either (a) sort authoritatively in the app after the RPC returns (return the sort columns and order in TS — see apps/mes/app/services/allocation.ts sortLotsByPickMethod, applied in getSuggestedAllocationForMaterial), or (b) if ordering must live in SQL, use LANGUAGE plpgsql with RETURN QUERY ... ORDER BY (plpgsql is never inlined). Always verify RPC ordering against seeded real data, not just unit tests.
Applies to: packages/database/supabase/migrations/ set-returning LANGUAGE sql functions consumed via client.rpc(...); any app code that greedy-fills / picks "the first row" from an RPC result.
Tracked consumption/split must book against the entity's ACTUAL bin, not an arbitrary ledger row
Context: Building "return unused picks at job complete" surfaced a pre-existing bug in the issue edge function (trackedEntitiesToOperation). Consuming a batch that had been picked to a lineside shelf booked the Consumption + split itemLedger rows against itemLedgers.find(il => il.trackedEntityId === id)?.storageUnitId — the FIRST row for the entity in a createdBy-ordered list, i.e. an arbitrary bin. A picked entity has ledger rows in BOTH its warehouse source and its lineside bin, so consumption landed on the warehouse bin, leaving the entity at −N on-hand in one bin / +N in another: a per-bin-negative, internally inconsistent ledger, and the un-consumed remainder (a split entity) stranded on the wrong bin.
Problem: For a tracked entity that has moved between bins (pick/transfer), "which bin holds the stock" is NOT the first ledger row — it's the bin whose net on-hand is positive. Picking any row's storageUnitId silently misplaces consumption and breaks any downstream feature that reasons about physical location (e.g. returning lineside remainder to source).
Rule: When booking a consumption/split/movement ledger row for a tracked entity, resolve the storage unit from net on-hand per bin (the bin with the highest positive net), never .find(...)?.storageUnitId over an unordered/createdBy-ordered list. See resolveTrackedEntityBin (packages/utils/src/resolve-tracked-entity-bin.ts, pure + test-covered; exported by @carbon/utils). Scope such a fix to the path you can verify — the same .find pattern exists in other cases (e.g. unconsumeTrackedEntities); don't blanket-replace untested paths.
Applies to: issueMaterial (apps/erp/app/modules/inventory/inventory.service.ts) and any posting inserting itemLedger rows for a tracked entity that may hold stock in multiple bins.
A tracked entity's bin is where it IS, never the document line's bin — and "no storage unit" is a bin
Context: Sales order shipments booked every serial and batch against shipmentLine.storageUnitId (copied from the sales order line, which defaults to the item's default bin). A unit picked from any other bin drove the line's bin negative and left its real bin showing stock that had already shipped. The stock transfer picker had the matching gap: it listed every lot at the location, not the line's source bin, and an empty source (fromStorageUnitId null — the wizard's "No storage unit") meant "any bin".
Problem: A document line's bin is a default for untracked stock. For a serial or batch the ledger already knows the bin, and ignoring it corrupts two bins at once. resolveTrackedEntityBin skips the unassigned bin (null), so a unit moved into "no storage unit" resolves back to the named bin it left. And NULL as a filter value cannot also mean "no filter".
Rule: Book a tracked entity's outbound row against its actual bin: resolveTrackedEntityBins (@carbon/utils, null-aware) through getTrackedEntityBins (apps/erp/app/modules/shared/shared.service.ts). Refuse when it has no stock anywhere rather than falling back to the line's bin. A void reverses into the bin the posting used (read the posted itemLedger rows), not the line's. A bin filter that must express "no storage unit" takes an explicit switch (p_filter_storage_unit on get_available_tracked_entities) and compares with IS NOT DISTINCT FROM.
Applies to: post-shipment (Sales Order post/void, serial + batch), post-stock-transfer (assertInSourceBin), the stock transfer picker. Return and outbound-transfer shipments still use the line's bin.
Biome does not apply 3rd-level nested configs — enforce Deno via an override
Context: Bringing Supabase edge functions (packages/database/supabase/functions/**, Deno) into Biome's lint surface for the new noConsole rule. These files sit outside the linted globs (apps/*/app/**, packages/*/src/**) and were never Biome-formatted.
Problem: A dedicated nested functions/biome.jsonc (root:false, formatter off, noConsole only) is silently ignored. Biome applies the depth-1 nested config (packages/biome.jsonc) for the whole packages/ subtree; a depth-2 nested config under it never governs — the format diagnostic keeps appearing and formatter.enabled:false has no effect. Letting packages/biome.jsonc (which extends "//") govern the Deno files directly produces ~270 CI-failing errors (Deno globals → noUndeclaredVariables, useImportType, organizeImports, formatting) on never-linted code.
Rule: Do not rely on 3-level Biome config nesting. Add the target path to the depth-1 config's files.includes, then scope an overrides entry there (glob relative to that config) that turns off formatter/assist and the Node-oriented error rules (correctness.noUndeclaredVariables, noUnusedVariables, style.useImportType) while inheriting the one rule you want (noConsole as a warning). Verify with pnpm exec biome check --reporter=summary <dir> expecting 0 errors. See packages/biome.jsonc.
Applies to: biome.jsonc / packages/biome.jsonc rule scoping; any attempt to lint Deno edge functions or other non-src/ trees.
React Router v7 middleware next() never rejects on thrown Responses/errors
Context: Writing requestIdMiddleware (@carbon/logger) that sets an x-request-id header on the response after await next(), and worrying that thrown redirects/data() from loaders/actions would skip the header.
Problem: It is easy to assume next() propagates the thrown redirect/error (route handlers DO throw redirect(...)), which would mean post-next() response mutation is skipped on those paths. That assumption is wrong and leads to defensive try/catch that isn't needed.
Rule: In RR v7 middleware (callRouteMiddleware, react-router dist), next() wraps the downstream chain in try/catch and resolves with errorHandler(error)'s Response — it only rejects if request.signal.aborted. So mutating headers on the resolved response after await next() correctly covers redirects and error (500) responses; only aborted requests skip it, which is fine (client is gone). Register the middleware first so downstream runs inside its withContext/ALS scope.
Applies to: any RR v7 middleware/clientMiddleware that reads or mutates the response after next(); packages/logger/src/middleware.server.ts, packages/auth/src/middleware/*.
Composite (id, companyId) FKs break PostgREST alias:column(...) embeds
Context: RFQ supplier linking silently failed — getPurchasingRFQSuppliersWithLinks / getPurchasingRFQSuppliers (purchasing.service.ts) returned an empty suppliers array even though the purchasingRfqSupplier row existed, so the Properties multiselect never showed linked suppliers and an optimistic add reverted on revalidation.
Problem: The embed .select("*, supplier:supplierId(id, name)") uses the alias:foreignKeyColumn(...) disambiguation form. That only resolves when supplierId is a single-column FK. Multi-tenant FKs here are composite — purchasingRfqSupplier_supplierId_fkey FOREIGN KEY ("supplierId","companyId") REFERENCES supplier(id,"companyId") — so PostgREST returns PGRST200: Could not find a relationship ... 'supplierId' ... Perhaps you meant 'supplier'. The whole query errors, data is null. Loaders that do result.data?.map(...) ?? [] (and never check result.error) swallow it as "no rows". Same bug hit the nested supplier:supplierId (*) inside supplierQuote:supplierQuoteId(*, ...) for linked-quote reads.
Rule: For a composite-FK relationship, embed by target table name — .select("*, supplier(id, name)") (or the explicit constraint supplier:supplier!purchasingRfqSupplier_supplierId_fkey(...)), never alias:fkColumn(...). Verify a PostgREST embed against the running REST API (/rest/v1/<table>?select=... with the service-role key) — PGRST200 is a schema-cache error returned even on empty tables. And when a loader powers UI state, check .error, don't ?? [] a failed query into silent emptiness.
Applies to: any supabase-js embed on a join table with a composite (entityId, companyId) FK — purchasingRfqSupplier, supplierQuote.supplierId, and siblings; apps/erp/app/modules/purchasing/purchasing.service.ts.
Dual-major deps of workspace source packages crash the SSR bundle when the shared dep is externalized
Context: Merging assembly instructions (#1075) added @carbon/viewer (a source-only workspace package) with @react-three/fiber@8, whose ESM dist does import create from 'zustand' against its own nested zustand v3. The app + @react-three/drei use the catalog zustand v5, which removed the default export.
Problem: Production (app.carbon.ms) 500'd on every request while builds stayed green. Vite/rolldown inlines deps of linked workspace packages into the SSR bundle but externalizes packages resolvable from the app root by package name, merging fiber's v3 default import with v5 named imports into one import ste,{create,...}from"zustand" in build/server/index.js. Node resolves that to v5 at runtime → SyntaxError: The requested module 'zustand' does not provide an export named 'default' at ModuleJob._instantiate — before any code runs, so the error never reaches error reporting, dev SSR never reproduces it (per-importer resolution), and Vercel previews show READY (crash is invocation-time). The runtime log dumps a random window of the minified bundle (logtape's timezone formatter), which reads like an Intl/timezone error — red herring.
Rule: When a dep of a workspace source package pins a different major of a package the app also depends on, add that package to ssr.noExternal in the consuming apps' vite.config.ts so each importer keeps its own inlined copy. Verify with a build + grep -E "from *[\"']zustand" build/server/** (expect no bare imports) and node --input-type=module -e "await import('.../build/server/index.js')" — reaching an env-var error proves linking succeeded. For any all-requests-500 Vercel incident with a minified source dump, read the last lines for the real error and check node:internal/modules/esm/module_job in the stack before believing anything the dumped source suggests.
Applies to: apps/erp/vite.config.ts, apps/mes/vite.config.ts ssr.noExternal; any new dep of @carbon/viewer or other source-only workspace packages (@carbon/form, @carbon/onboarding, ...) that pins an older major of a shared package.
@ts-expect-error TS2589 on Supabase joined-selects is fragile — flips "used/unused" as files are added
Context: The $itemId.purchasing.$supplierPartId.delete.tsx routes (material / tool / consumable / part / …) each do client.from("supplierPart").select("id, supplierId, supplier:supplierId(name)"). Some carried // @ts-expect-error TS2589 — … type instantiation too deep. Adding an unrelated new route file (periods.generate.tsx) flipped which file the checker reported: material went from TS2578 (unused directive) to clean, tool went from clean to TS2589 — a whack-a-mole that broke erp typecheck without touching those files.
Problem: TS2589 ("type instantiation is excessively deep") on PostgREST joined-select types is order/threshold dependent — it surfaces at whichever file crosses a cumulative-depth limit during a given check pass, so which file errors changes as files are added/removed elsewhere. @ts-expect-error requires an error on the next line, so a directive that was "used" becomes an "unused directive" (TS2578) the moment the trigger moves — and the newly-triggering file now lacks a directive (TS2589). Swapping directives just moves the problem.
Rule: Don't manage TS2589 on Supabase joined-selects with @ts-expect-error — it requires an error, so it flips to TS2578 the moment the trigger moves to another file. Use @ts-ignore instead (the codebase's choice on the supplierPart delete routes): it suppresses the error when it fires and stays green when it doesn't, and it preserves the inferred result type. A localized (client as any) cast is the heavier alternative — it removes the file from the cumulative-depth pool entirely but drops the result's type; prefer @ts-ignore unless you specifically need to break the inference chain.
Applies to: the supplierPart joined-select delete routes and any similar alias:fkColumn(...) embed that trips TS2589; apps/erp/app/routes/x+/{material,tool,consumable,part}+/...delete.tsx.
Changing seed.data.ts only reaches NEW companies — existing companies need a reconciling migration
Context: The period-close checklist changed (dropped "Close the period", reclassified two Auto/Manual tasks to Action). Those edits went into packages/database/supabase/functions/lib/seed.data.ts (+ seed-company / seed-dev), which only run on company creation. Existing companies — seeded by the original migration's INSERT … FROM company — kept the old task set, so the fixes never reached them.
Problem: Seed data (seed.data.ts + seed-company) and migration-time seeds (INSERT … FROM company) are two different populate paths. Editing the former fixes new companies; existing companies are frozen at whatever the migration inserted. The two silently drift.
Rule: When you change seeded per-company template rows (periodCloseTaskDefinition, paymentTerm, accountDefault, …) in seed.data.ts, also write an idempotent reconciling migration for existing companies (INSERT … FROM company … ON CONFLICT DO UPDATE, plus deletes for removed rows), guarded on the system user for the createdBy FK. Validate it in a rolled-back psql txn that simulates the old state. Deleting instance rows to force re-instantiation is fine when no real data depends on them (confirm first).
Applies to: any change to packages/database/src/seed-data.ts per-company templates; seedCompany (apps/erp/app/modules/settings/settings.service.ts), seed-dev.ts.
meshopt vertex codec requires a stride that is a multiple of 4 — i16 VEC3 normals break it
Context: crates/optimize quantizes normals to i16 (SHORT, normalized) to shrink the optimised GLB, encoding each attribute as its own EXT_meshopt_compression vertex buffer. An i16 VEC3 normal is 6 bytes, so the normal view was emitted with byteStride: 6. The GLB reparsed and round-tripped fine through the Rust meshopt decoder, and all crate tests passed.
Problem: meshopt_encodeVertexBuffer/decodeVertexBuffer require the vertex size be a multiple of 4 (assert(vertex_size % 4 == 0)); the Rust binding doesn't assert in release, so it emitted a 6-byte-stride stream that only its own decoder round-trips. The spec-compliant JS MeshoptDecoder (three.js / three-stdlib) rejects it with Malformed buffer data: -2, so the viewer showed a black screen — and because the failure is inside the decoder, no obvious app-level error surfaced. Positions (stride 12) and indices were fine; only the 6-byte normal stream broke.
Rule: Any attribute encoded as a meshopt vertex buffer must have a stride divisible by 4. Pad i16 VEC3 normals to i16 VEC4 (8 bytes, 4th lane 0) — the accessor stays VEC3 (reads x,y,z; the 8-byte stride skips the pad) and the constant pad lane compresses to ~nothing. Never trust "reparses + Rust-decoder round-trips" as proof a meshopt GLB is valid; validate against the spec JS decoder (GLTFLoader.setMeshoptDecoder). The regression test quantized_normals_keep_meshopt_stride_multiple_of_four asserts every ATTRIBUTES view stride is % 4 == 0.
Applies to: crates/optimize/src/lib.rs (ViewData, the meshopt assemble path); any new quantized attribute type added to the optimiser; the @carbon/viewer useAssembly loader that consumes these GLBs.
Large text .gltf with an embedded base64 buffer can't be serde-parsed bounded — stream it into a GLB
Context: The assembler optimises uploaded models. Text .gltf (the Onshape export shape) carries its single geometry buffer as a base64 data: URI. optimize_gltf did serde_json::from_slice(gltf_bytes) then base64-decoded the URI. GLB (optimize_glb) was already bounded — its BIN chunk is a &[u8] slice into the mmap.
Problem: For a 1.73 GB .gltf, serde materialises the base64 as an owned ~1.73 GB String, then base64-decode allocates ~1.3 GB more — both live at once → ~3 GB peak. mmap doesn't help because serde copies the string out of the mapped bytes. The assembler failed with "source file exceeds the size limit" (a separate cap) and, once that was lifted, was on track to OOM on parse.
Rule: Don't serde-parse a glTF whose buffer is a giant base64 data URI. Repack .gltf → .glb first with a streaming base64 decode: walk the JSON with struson (transfer_to copies the small structural fields verbatim, dropping the buffer's uri), then next_string_reader() the base64 value through base64::read::DecoderReader straight into the GLB BIN chunk on disk. Then mmap the .glb and use the already-bounded optimize_glb path — geometry never heaps. Verify decoded length == the buffer's declared byteLength (fail loud, never emit a corrupt GLB). crates/optimize::gltf_to_glb + apps/assembler load_source (Format::Gltf → repacked temp .glb → Src::MappedTemp).
Applies to: crates/optimize/src/lib.rs (gltf_to_glb; optimize_gltf was removed), apps/assembler/src/actions/optimize.rs (load_source, run_optimize — every source is GLB now); any new large-text-JSON asset with an embedded base64 blob.
Raw-SQL item fixtures break type-specific UI — Material items need a companion material row keyed by readableId
Context: Posting-flow verification created a type-Material item (RM-STEEL) with a raw INSERT INTO "item". Interceptors auto-created itemCost/itemReplenishment/etc., so purchasing and posting worked. Later, selecting that material on a part's BOM (/x/part/{id}/details?materialId=…) crashed the whole page with "Not Found".
Problem: Type-specific detail RPCs join companion tables the interceptors do NOT create: get_material_details requires a material row joined via material."id" = item."readableId" (readableId, not item id — all revisions share one taxonomy row). The properties route throws 404 when the RPC returns nothing, and a fetcher 404 bubbles to the route error boundary, taking down the entire details page.
Rule: When creating item fixtures via SQL, create the type's companion row too (material keyed by readableId for Materials; check the get_{type}_details RPC joins for the type). Prefer creating fixtures through the UI or service functions when the item will be used in UI flows, not just ledger posting.
Applies to: any psql/SQL test-fixture item creation; get_material_details / get_part_details / get_tool_details consumers; apps/erp/app/routes/x+/items+/$itemId.properties.tsx.
Journal debit/credit is derived from account class + amount sign, not the raw sign
Context: Seeding a Cash sale as a journal via SQL, I used Cash (Asset) amount = +1000 and Sales (Revenue) amount = -1000, assuming + = debit, - = credit (which the journal AGENTS.md states for the stored value). The journalEntries view then reported the entry as totalDebits = 2000, totalCredits = 0 — unbalanced — and the period-close "Trial balance in balance" auto-check (tb-balanced) refused the close.
Problem: journalEntries.totalDebits/totalCredits are computed from account class AND amount sign: Asset/Expense amount>0 OR Liability/Equity/Revenue amount<0 → debit; the mirror → credit. So a positive amount on a Revenue account is a credit, not a debit. A correctly-balanced sale is Cash (Asset) +1000 and Sales (Revenue) +1000 — both positive. The raw SUM(amount) the balance RPCs use is a separate, class-agnostic signed sum; don't conflate the two.
Rule: When hand-seeding journalLine rows, set the sign to move the account toward its natural balance: + increases an Asset/Expense (debit) and increases a Liability/Equity/Revenue (credit). Verify against the journalEntries view (totalDebits == totalCredits per journalEntryId) before relying on the data — an unbalanced entry silently blocks period close. Posted journal/journalLine rows are immutable (journal_posted_immutable / journalLine_posted_immutable); to correct seeded mistakes you must disable those triggers on the local DB (superuser), never in a migration.
Applies to: any SQL journal fixtures; the journalEntries view; the tb-balanced close check in computePeriodReadiness (accounting.service.ts).
A period snapshot written at close races Locked-period postings unless the posting guard locks the period row
Context: closeAccountingPeriod writes the accountingPeriodBalance snapshot inside its transaction, after flipping the period to Closed. check_accounting_period_open only rejects postings when a period is already Closed; a Locked period still accepts them (Locked is a soft freeze for adjustments). A period only becomes Closed on COMMIT.
Problem: In the window between the close txn's snapshot SELECT and its COMMIT, a concurrent posting reads the period as still-Locked (the flip is uncommitted under READ COMMITTED), is allowed, and commits a line with postingDate <= endDate that the snapshot never captured. The read path's delta only adds postingDate > endDate, so that line is silently dropped from the optimized balance until reopen+reclose — a wrong financial figure with no error.
Rule: When a cache/snapshot is written inside a state-flip transaction and a concurrent writer keys off the committed state, make the writer take a lock that conflicts with the flip. Here: the posting guard reads the target accountingPeriod row FOR SHARE (migration 20260713235930), which blocks behind the close's row lock — postings before the flip commit first (and land in the snapshot); postings after block, then see Closed and are rejected. FOR SHARE is shared, so normal concurrent postings don't block each other; only an in-flight close serializes them. Verify with two psql sessions + lock_timeout.
Applies to: check_accounting_period_open; snapshotAccountingPeriodBalances / accountingPeriodBalance; any close/snapshot-on-commit pattern.
Inline-editable table cells commit on blur — the container must own navigation keys in the capture phase
Context: Inventory count table (PR #1135 follow-up): typed Counted Qty values were lost on Tab/Enter (only click-away saved), Enter never navigated, arrows stepped the number instead of moving the selection, and keyboard nav went dead after a commit.
Problem: Editable cells (~/components/Editable/*) persist via the input's native onBlur, but three things prevent that blur from ever firing on keyboard navigation: (1) the Table's key handler preventDefault()s Tab/Enter, so the browser never moves focus; (2) React unmounts the still-focused input when the selection moves, and browsers fire no blur on a removed element; (3) react-aria's NumberField swallows Enter entirely (onKeyDownEnter commits internally without continuePropagation()) and consumes ArrowUp/Down as spinbutton steps, so a bubble-phase table handler never sees those keys. Blurring at the input level without navigating drops document.activeElement to body, after which the table wrapper hears no further keys.
Rule: The table container owns the Excel keyboard model: attach the handler with onKeyDownCapture (so it beats react-aria to Enter/arrows), stopPropagation() for handled keys while editing, blur document.activeElement to commit before setSelectedCell, and let the roving-tabindex cell ref (useMovingCellRef) refocus the newly selected cell. Skip events targeting portaled overlays ([data-radix-popper-content-wrapper], [role=menu|listbox|dialog]) — those own their keys. Editors must keep blur as their single commit path (no keydown commits — they double-fire the mutation, as EditableText did in Grid).
Applies to: apps/erp/app/components/Table/Table.tsx, apps/erp/app/components/Grid/Grid.tsx, apps/erp/app/components/Editable/*, any future inline-editable cell editor.
Seeding useState from a prop goes stale when the document flips state in place
Context: After Rectify flipped a Posted inventory count back to Draft, the lines table stayed read-only until a full page reload.
Problem: Table read forceEditMode only as the useState initial value. Rectify/Post actions revalidate the route in place — the component never remounts, so the prop change never reached the state, and the Edit/Lock toggle is hidden while forceEditMode is set, leaving no way to recover. The same staleness applied in the opposite direction after posting a Draft (table looked editable on a read-only document).
Rule: When a prop derives from a document's mutable status (Draft/Posted etc.) and controls interaction mode, sync it with an effect (useEffect(() => setEditMode(forceEditMode), [forceEditMode])) or derive it instead of seeding state once. Test the transition without a reload — loader revalidation does not remount components.
Applies to: apps/erp/app/components/Table/Table.tsx (forceEditMode), any component seeding state from status-derived props on revalidating routes.
journalLineDocumentType and itemLedgerDocumentType are different enums with near-identical value sets
Context: Adding GL posting for inventory adjustments: journal lines needed a documentType of 'Inventory Adjustment', and the plan also stamped the same value onto itemLedger/costLedger rows.
Problem: journalLine.documentType uses the journalLineDocumentType enum while itemLedger.documentType AND costLedger.documentType share the itemLedgerDocumentType enum. The two lists overlap heavily ('Inventory Count' exists in both) but are not identical — 'Inventory Adjustment' existed in neither and was added only to journalLineDocumentType. Writing a journal-only value into a ledger column fails at runtime with an invalid-enum error, and stamping a new documentType onto manual-adjustment itemLedger rows would also have broken the "byte-identical ledger writes when accounting is disabled" guarantee (they are NULL today).
Rule: Before using a documentType string, check WHICH enum the target column uses (\dT+ or grep the migration) — never assume the journal and ledger enums share values. When adding GL posting to an existing subledger flow, keep the subledger rows' shape unchanged (documentType stays whatever it was, usually NULL) and put the new linkage value on the journal lines only.
Applies to: packages/database/supabase/migrations/ enum additions; bookAdjustment / valueMovement (apps/erp/app/modules/shared/shared.service.ts); any post-* function writing both itemLedger/costLedger and journalLine.
Deno edge functions are not deno-check-clean — gate on own-file error deltas, not exit code
Context: Verifying new/edited Supabase edge functions (post-inventory-adjustment, post-inventory-count) with deno check.
Problem: deno check on ANY edge function fails with ~10–20 pre-existing errors from the shared dependency graph (TS2589 in shared/get-next-sequence.ts, kysely pool-config type skew, supabase-js generic inference collapsing to implicit-any callbacks). CI never runs deno check, so committed, working functions fail it — a red exit code proves nothing about the change, and chasing those errors means rewriting shared files out of scope.
Rule: Obsolete: the two remaining edge functions (embedding, thumbnail) are self-contained and deno check-clean, and CI's edge-functions job runs deno check on both — keep them clean; a red exit code is now a real failure.
Applies to: packages/database/supabase/functions/** verification; .claude/skills/check-and-commit runs touching edge functions.
Forking a SQL function migration silently drops sibling branches added since your fork base
Context: complete_job_to_inventory gained a Non-Inventory branch in 20260707022142 (services post WIP→COGS, no inventory artifacts). Six days later, two migrations (20260713190909 raw-materials split, 20260713222236 overhead fix) each forked the function from the older 20260630092517 baseline — silently deleting the Non-Inventory branch. Service job completions then posted phantom Finished Goods until the branch was restored in 20260714043017.
Problem: "Fork from the newest definition" fails when the author greps for the migration that matters to their change and misses intermediate redefinitions that added orthogonal branches. The dropped branch produces no error — the divergent behavior only surfaces when someone exercises the other feature.
Rule: Before redefining a function, list EVERY migration that touches it (grep -l '<fn_name>' migrations/*.sql | sort), and fork from the last one — then diff your new body against that exact file (diff <(sed -n 'a,bp' newest.sql) <(...)) so the only hunks are your intended edits. If the timeline shows a branch you don't understand (an itemTrackingType guard, a feature flag), it is load-bearing — carry it forward, never re-derive the body from an older file or memory.
Applies to: packages/database/supabase/migrations/ — any CREATE OR REPLACE FUNCTION fork; reviews of migrations that redefine shared functions (complete_job_to_inventory, backflush_job_materials, get_inventory_quantities, sync interceptors).
Also after a merge (2026-09-28): a branch's migration that added the Make to Asset branch to
complete_job_to_inventory and main's 20260925121735_rpc-function-guards (forked from the
definition before it, to add one guard line) merged cleanly — different files. In timestamp
order main's copy ran last, so every fresh or local database lost the asset branch; production
pushes with --include-all, which applies the older branch file AFTER main's, so there the
guard went missing instead. check-clobbers compares against the merge base and reported
nothing. After merging main, list main's migrations newer than your branch's oldest and grep
them for every function and view your migrations define; for any hit, write a NEW migration
dated after both that carries both changes (here, since folded into
20261006221601_complete-job-to-asset.sql).
Job-completion side effects must live in complete_job_to_inventory, not in route actions
Context: Service-job fulfillment (advance the linked salesOrderLine on completion) was first implemented in the ERP $jobId.complete.tsx action after the RPC call. In e2e it never ran: the operator finished the last operation, and sync_update_job_operation_quantities → sync_finish_job_operation (DB interceptors) called complete_job_to_inventory directly — the ERP route was never involved.
Problem: Job completion has multiple entry points — the ERP Complete button AND the interceptor cascade that auto-completes when the last operation flips to Done (fired from MES quantity recording or ERP production quantities). Any completion side effect hooked at the app layer silently misses the interceptor path.
Rule: Side effects that must accompany job completion (fulfillment, status propagation, posting) go INSIDE complete_job_to_inventory — the single choke point every path crosses. Place them before the accountingEnabled / zero-WIP early returns if they must run unconditionally. App-layer completion hooks are only valid for effects the SQL function cannot perform (edge-function invocation — cf. returnAllocatedRemaindersAtJobComplete, orchestrated in TS for exactly that reason).
Applies to: complete_job_to_inventory; apps/erp/app/routes/x+/job+/$jobId.complete.tsx; sync_finish_job_operation; any future completion-triggered behavior (rev-rec POC recognition events).
A @ts-expect-error on generated DB types is evidence of a dropped column, not a type quirk
Context: InventoryTable.tsx read row.original.tags behind a // @ts-expect-error TS2339. The suppression was correct that the property was missing — 20260713235406 had forked get_inventory_quantities and dropped the tags output added by 20260113122437 (the sibling-branch failure mode above). The regression then hid in plain sight for months: the Tags column silently rendered empty, and the Tags filter sent .overlaps("tags", …) → PostgREST 42703 against a nonexistent column.
Problem: Generated types are mechanically derived from the live schema, so TS2339 on a generated Row/Returns type is never a false positive — it is the type system reporting that the column does not exist. Suppressing it converts a compile-time regression signal into a silent runtime one. The blast radius was widened by quantities.tsx calling redirect(...) without throw, which discarded the resulting PostgREST error and rendered an empty table instead of surfacing it.
Rule: Never @ts-expect-error / @ts-ignore a missing property on a @carbon/database generated type. Grep every migration touching the function or table (grep -l '<name>' migrations/*.sql | sort) and find the revision that removed it — the fix is a migration restoring the column, not a suppression. When reviewing, treat a @ts-expect-error near generated types as a probable dropped-column regression. Corollary: in a loader, always return or throw redirect(...) on a service error — a redirect(...) that is neither returned nor thrown is a no-op that swallows the error and renders empty data.
Applies to: packages/database/src/types.ts consumers; apps/erp/app/modules/**/ui/** table columns bound to RPC outputs; any loader branching on { data, error }.
A mutually-exclusive primary/fallback branch breaks when the primary source can be legitimately empty
Context: The MES Issue dialog (IssueMaterialModal) pre-selects tracked lots from two sources: pickedAllocation (lots a picking list already picked) and suggestedAllocation (the FEFO/pickMethod suggestion of what to pick). It gated the suggestion off whenever a picking allocation merely existed (shouldSuggestAllocation = … && !hasPickingAllocation) and chose seedAllocation = hasPickingAllocation ? pickedAllocation : suggestedAllocation.
Problem: hasPickingAllocation was true when quantityToPick > 0 — i.e. the material is ON a picking list — but pickedAllocation is only non-empty once something is physically PICKED (pickingListLineTrackedEntity rows are written at pick time, never at allocation). For a material on an In-Progress list that hasn't been picked yet (common in a multi-line list where other lines were picked first), the primary branch was selected but resolved empty, the suggestion was gated off, and the seed effect bailed → operator got the default first lot instead of the recommendation. The two conditions "should we prefer picked lots" and "do picked lots exist" were conflated.
Rule: When one data source is the preferred seed and another is the fallback, branch on whether the preferred source actually HAS data (primary.length ? primary : fallback), and load the fallback unconditionally — do not gate the fallback off on a proxy signal (here hasPickingAllocation) that can be true while the primary is still empty. Verify the "primary exists but is empty" state explicitly, since it's the one static reading and happy-path testing both miss.
Applies to: apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx (picked vs suggested allocation seeding); any picking-list-aware UI that distinguishes allocated-but-not-picked from picked (pickingListLineTrackedEntity.quantityPicked > 0).
PostgREST inserts NULL (not the DB default) for a present-but-undefined key spread into an insert
Context: Creating a Fixed Asset sales-order line failed with 23502 null value in column "methodType" violates not-null constraint, even though salesOrderLine.methodType is NOT NULL DEFAULT 'Pull from Inventory'. The validator (salesOrderLineValidator) intentionally coerces the form's empty methodType to undefined for Fixed Asset / Comment lines (zfd.text + a refine that exempts them). The action spreads ...validation.data into upsertSalesOrderLine, whose insert path spreads ...salesOrderLine — so the object still carries methodType: undefined. A raw psql insert omitting the column succeeded (used the default); the app's PostgREST insert did not.
Problem: postgrest-js builds its ?columns= list from Object.keys(row), which includes keys whose value is undefined. JSON.stringify then drops the value from the body, so PostgREST sees the column listed with no value and inserts NULL — it does not fall back to the column DEFAULT. A truly absent key (never spread, e.g. id) is excluded from ?columns= and does get its default. This is why the sibling update path was fine: it runs sanitize(...), which strips undefined/empty keys before the write. Only the insert path (which didn't sanitize) leaked the undefined key.
Rule: When spreading validated/optional data into a supabase-js .insert(...), a NOT-NULL column with a DB default will still fail if the key is present-but-undefined. Either (a) supply the value explicitly at the insert site next to the other defaults (methodType: x.methodType ?? "Pull from Inventory"), (b) sanitize(...) the insert object so undefined keys are dropped (matches the update path), or (c) pass { defaultToNull: false } to .insert(...) (sends Prefer: missing=default). Prefer (a) for a single column, (b) for consistency with an existing update path. Don't assume the DB DEFAULT will apply — it only does for keys entirely absent from the object.
Applies to: upsertSalesOrderLine (apps/erp/app/modules/sales/sales.service.ts); any upsert* whose insert branch spreads optional/validated fields into a table with NOT-NULL-DEFAULT columns (sales/purchase/quote/invoice line inserts especially, which all carry a NOT NULL methodType).
Twin ValidatedForms at the same JSX slot share one RVF store — controlled-field defaults seed only for whichever branch mounts first
Context: The Add Affected Item modal (AffectedItemForm) renders isNewPart ? <ValidatedForm A/> : <ValidatedForm B/>. Branch A (New Part) has replenishmentSystem/itemTrackingType Selects with defaultValues "Make"/"Inventory"; branch B (existing item) has an item picker. After switching to New Part the two Selects rendered blank and submit failed with Invalid enum value … received ''.
Problem: Both branches render a <ValidatedForm> (same element type) at the same JSX position, so React reconciles them as one component instance and just swaps props — no unmount/remount. @carbon/form's RVF store seeds controlledFields.values from defaultValues only on first hydration (syncFormProps: if (!state.isHydrated) { … }). The instance hydrates on the initial branch (B, changeType default Version), so when the user switches to A, A's Select defaults are never seeded — useControlledFieldValue returns the store value (undefined) once isHydrated, not the defaultValue. Uncontrolled fields (InputControlled) were unaffected because they write their own value via effect. defaultValues object identity was a red herring: ValidatedForm already useDeepEqualsMemos it, and syncFormProps ignores later defaultValues changes post-hydration.
Rule: When two ValidatedForms occupy the same conditional slot (cond ? <VF/> : <VF/>), give each a distinct, stable key (key="new-part" / key="existing-item") so switching forces a fresh mount + fresh store that hydrates with the correct branch's defaultValues. Consequence: the fresh mount also needs any Select value the branch relies on seeded in its own defaultValues (e.g. changeType: "New Part", added to changeOrderNewPartValidator) — a value the shared store previously carried over from the user's click is gone after remount. Symptom to watch for: a controlled Select rendering blank / submitting "" right after a branch switch.
Applies to: apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsx; any conditional twin-ValidatedForm pattern; @carbon/form controlled fields (Select/Combobox/anything on useControlField) that rely on defaultValues seeding.
Never blind-pop a stash in a Conductor worktree — the stash stack is shared/stale
Context: During /execute, proving an erp typecheck failure pre-existing by temporarily parking three edited files with git stash push -u <paths> in a Conductor workspace.
Problem: The stash push failed ("could not write index" — likely a concurrent git process from a sibling workspace; untracked-file pathspecs also fail plain stash push). No stash was created, but the follow-up git stash pop applied the TOP of the existing stash stack — an old stash from a different branch's work — half-applying unrelated files with merge conflicts (UU) and staged changes that then had to be surgically reverted.
Rule: In Conductor/multi-worktree checkouts, don't use git stash for temporary file parking at all. Prove a failure is pre-existing with git show HEAD~1:<file> / git log -- <file> / a merge-base check instead. If stash is truly unavoidable: verify the push succeeded AND git stash list shows YOUR entry at stash@{0} before ever popping, and never pop after a failed push.
Applies to: any git stash usage in Conductor workspaces; /execute and /check-and-commit loops; proving pre-existing test/typecheck failures.
A public SECURITY DEFINER function that calls net.http_post is a remote-DoS surface — put it in an internal schema
Context: The push-based event-queue wake (20260721184852_event-queue-wake.sql) originally defined wake_event_queue() / sweep_event_queue() in the public schema. Both are SECURITY DEFINER and call net.http_post (pg_net) to POST to the event-wake edge function. The trigger (dispatch_event_batch) and pg_cron call them as the owner (superuser).
Problem: Every public function is auto-exposed as a PostgREST RPC (/rest/v1/rpc/<name>), reachable by anon. Worse than mere exposure: referencing such a function as a non-superuser role segfaults the backend (pg_net 0.20 / PG15) — reproducible via SET ROLE authenticated; EXPLAIN SELECT public.wake_event_queue();, which crashed even though EXPLAIN never runs the body and the role lacked EXECUTE. The crash happens at plan/permission-resolution time, before the ACL check — so REVOKE ALL … FROM PUBLIC, anon, authenticated does NOT protect: an unauthenticated POST /rpc/wake_event_queue crash-loops the whole DB (postmaster reinitializes all backends → "database system is in recovery mode" for every client). Same-body call as superuser was fine, which is why the trigger/cron paths worked and masked it in end-to-end testing.
Rule: Never define an internal SECURITY DEFINER helper (especially one calling net.http_post / pg_net) in public. Put it in the internal util schema (the existing Carbon/Supabase convention — cf. util.process_embeddings), where anon/authenticated have no USAGE, so the API can't reference it at all and a hostile call fails cleanly with permission denied for schema util before any crash-prone planning. Callers that are triggers/pg_cron run as owner and reach util fine; update their bodies to util.<fn>(). Keep REVOKE ALL … FROM PUBLIC on the util function as defense-in-depth, but the schema-USAGE gate is the real fix. Verify with SET ROLE authenticated; SELECT util.<fn>(); → must be a clean permission denied, not a dropped connection. Note PostgREST-exposed schemas exclude util/pgmq but include public/net (has_schema_privilege('anon', <schema>, 'USAGE')).
Applies to: any new SECURITY DEFINER function that calls pg_net/net.http_post or is meant to be trigger/cron-only (packages/database/supabase/migrations/). Trigger functions returning trigger are not RPC-exposed (safe in public), but VOID/scalar helpers are.
Update (2026-09-24): pg_net is not required. On supabase/postgres:15.14.1.112, a plain
LANGUAGE sql function (select 1) with REVOKE EXECUTE … FROM PUBLIC, anon, authenticated
segfaults the backend (signal 11) when called under SET ROLE authenticated or anon. This was
reproduced in a fresh container of that image. A missing table privilege, a RAISE, and "must be owner"
are all ordinary errors. So REVOKE EXECUTE on any function in public is itself an unauthenticated DoS
(POST /rest/v1/rpc/<fn>). Gate API access INSIDE the function instead, and raise on
current_setting('role', true) IN ('anon','authenticated') without the permission — see
assert_audit_log_access in 20260924171942_audit-log-company-scope.sql. When you test a revoke, use a
throwaway container (docker run --rm supabase/postgres:<tag>), never a shared dev database. The crash
restarts every backend. 20260924192316_api-function-guards-not-revokes.sql replaced the six existing public-function
revokes (integration secrets, upsert_company_integration_patch, the job-completion helpers). A nested
helper of a SECURITY DEFINER function cannot use the role-GUC guard, because current_setting('role')
still reads authenticated inside the nested call. Make those SECURITY INVOKER instead.
The local Inngest dev server (v1.19.4) can't handle debounce — it errors on every debounce item
Context: The push-based event-queue drainer (packages/jobs/src/inngest/functions/events/queue.ts) was configured with debounce: { period: "2s", timeout: "10s" } to coalesce bursts of carbon/event-queue.process wake events into one run.
Problem: The Dockerized dev server (inngest/inngest:v1.19.4, run by crbn up) logs error unmarshalling debounce item: json: cannot unmarshal array into Go struct field DebounceItem.e.data of type map[string]interface {} on every debounced event, fails to coalesce (a 20-write burst produced 21 runs, not ~1), and spams the error each time the function is triggered (including every pg_cron sweeper tick). Fails open — events still process, queue still drains, nothing is lost — but the optimization is absent in dev and the logs are noisy. Inngest Cloud honors debounce; the dev server does not.
Rule: Don't rely on debounce for Carbon Inngest functions validated against the local dev server — it's broken there. For the event queue the coalescing was moved upstream: dispatch_event_batch() wakes at most once per transaction (txn-local GUC carbon.event_wake_sent), so the important bulk case (a CSV import = one transaction) is already one wake; concurrency: 1 + loop-until-empty drain absorbs the rest (extra runs from many separate transactions are cheap no-ops that read an empty queue). If you must coalesce many separate transactions in a burst, do it at the DB/application layer, not with debounce. Verify any flow-control choice by watching docker logs <inngest container> for error handling queue item during a burst, not just by trusting the config.
Applies to: packages/jobs/src/inngest/functions/events/queue.ts; any new Inngest function reaching for debounce/flow-control that will be exercised in local dev.
Table cells in @carbon/react highlight on row hover by default
Context: The people Capacity view needed a hover-free (then row-scoped-hover) table; removing every hover class in the feature file changed nothing — cells still tinted on row hover, and a rowSpan name cell lit up whenever its first row was hovered.
Problem: packages/react/src/Table.tsx bakes the hover in at the primitive level: Tr carries the Tailwind group class and Td/Th ship group-hover:bg-muted. No amount of feature-level class removal turns it off, and a rowSpan cell belongs to its first row, so that row's hover tints it.
Rule: To opt a table out of (or customize) hover, override per cell with group-hover:bg-transparent (tailwind-merge lets the passed className win) — a local <Td> wrapper keeps it tidy. For a rowSpan cell that must stay static, also give it an opaque bg-card so sibling-row tints can't bleed through. If more tables need this, promote a static prop into packages/react instead of copying wrappers.
Applies to: any table built on @carbon/react Tr/Td/Th, especially with rowSpan cells or custom hover semantics (PeopleCapacity.tsx is the reference).
position:sticky inside a horizontal board needs a content-width row and a clamped scroll root
Context: Making the people board's Unassigned column sticky worked for one viewport-width of scrolling, then scrolled away; fixing that caused page-level overflow on small screens.
Problem: Sticky elements only stick within their parent's bounds. The flex row inside the Radix ScrollArea was viewport-width (columns overflowed it), so the sticky column ran out of parent after one screenful. Adding min-w-max fixed that but let the ScrollArea (a flex item, which sizes to content) exceed ITS parent, pushing overflow to the page.
Rule: The sizing contract for a sticky column in a scrollable flex board is three layers: scroll root clamped (w-full min-w-0 max-w-full) > row content-width (min-w-max) > column sticky left-0 z-10 with an opaque background. With dnd-kit on top, add measuring={{ droppable: { strategy: MeasuringStrategy.Always } }} — cached droppable rects assume elements move with the scroll, and sticky ones don't.
Applies to: BoardContainer (ColumnCard.tsx) and any kanban wanting a pinned column; any dnd-kit board with sticky droppables.
Regenerating src/email/previews/ fixtures requires a follow-up biome format pass
Context: Adding ChangeOrder* entries to packages/documents/scripts/generate-notification-previews.mjs and re-running it to emit the per-event preview fixtures.
Problem: The generator writes raw JSON.stringify(..., null, 6) output (quoted keys, 6-space indent), but the committed fixtures are biome-formatted (unquoted keys, 2-space indent). Re-running the script therefore rewrites all existing fixtures into the raw style — 28 files of pure formatting churn drowning the 3 intended new files in the diff.
Rule: After running generate-notification-previews.mjs, always run pnpm exec biome check --write packages/documents/src/email/previews/ before reviewing the diff. Only intended fixture changes should remain; if pre-existing fixtures still show as modified, something else changed.
Applies to: packages/documents/scripts/generate-notification-previews.mjs, packages/documents/src/email/previews/*, and any generator whose committed output is formatter-normalized.
Turbo typecheck/test runs can regenerate @carbon/database artifacts as ride-along churn
Context: Running pnpm exec turbo run typecheck --filter=erp and turbo run test --filter=@carbon/jobs to verify unrelated changes (notification filter, invite-link fix).
Problem: Turbo builds dependency packages first, and a @carbon/database build step regenerated src/types.ts (nondeterministic FK-relationship ordering), src/swagger-docs-schema.ts, and supabase/functions/lib/types.ts — none of which the task touched. Committing them would mix generated-file drift into an unrelated PR; the drift can also reflect whatever local DB happens to be running, not migrations.
Rule: After any turbo run, check git status for modified generated files under packages/database/ before committing. If you didn't intentionally run pnpm run generate:types, revert them (git checkout -- packages/database/src/...). Regenerate deliberately and separately when schema actually changed.
Applies to: packages/database/src/types.ts, packages/database/src/swagger-docs-schema.ts; any branch running turbo tasks that build @carbon/database.
Storage keys built from raw filenames break silently — always sanitize, and the portal share route regex is a hidden contract with every upload path shape
Context: MES file/inspection step uploads (RecordModal in apps/mes/app/components/JobOperation/components/Step.tsx) put the raw file.name into the Supabase storage key. macOS screenshot names contain U+202F (narrow no-break space before "AM/PM"), which is outside Supabase storage's allowed-key charset.
Problem: The upload fails with "Invalid key", but the modal had already rendered the file card (setFile before the await), so the operator saw the file "attached" with the Record button permanently disabled — no actionable error. Separately, the customer-portal file route (share+/customer.$id.$.tsx) validated paths with a regex hardcoded to the old flat layout companyId/job/operationId/file; when 032f8d0e nested step uploads under /stepId/nanoid/, every portal file link started returning 403 and nobody noticed for months.
Rule: (1) Any storage key that embeds a user-controlled filename must pass it through stripSpecialCharacters (canonical copy in @carbon/utils, re-exported by ~/utils/string in ERP) with a || "file" fallback for names that sanitize to empty. (2) The share-route path validation (parseJobFilePath in apps/erp/app/utils/supabase.ts, unit-tested) is coupled to every writer of the companyId/job/... prefix — changing an upload path shape requires updating the parser and its test in the same PR. (3) On upload failure, reset the picker UI so the user can retry; never leave a dead-end state.
Applies to: all storage.from(...).upload(...) call sites in apps/mes and apps/erp; share+/customer.$id.$.tsx; any new externally-shared file route.
Document totals helpers guarded on truthy qty/price silently drop shipping- or tax-only lines
Context: Adding line-level shipping cost display to the purchase order PDF (packages/documents/src/pdf/blocks/purchaseOrder/). A PO line with a 0.00 unit price and a 30.00 supplierShippingCost rendered Total and Subtotal as 0 on the PDF.
Problem: The totals helpers in packages/documents/src/utils/ (purchase-order.ts getLineTotal/getTotal, and the same pattern in sales-order.ts/sales-invoice.ts getLineSubtotal/getLineTaxableSubtotal) wrapped the whole formula in if (line?.qty && line?.unitPrice) — so any line whose value was only shipping, add-on, or tax contributed 0 to the document, even though those amounts were displayed elsewhere on the page and included in posting math.
Rule: Compute document money formulas unconditionally with ?? 0 per term — never gate the whole formula on one term being truthy. Also keep a document's Subtotal semantics identical to that module's in-app summary (PO PDF Subtotal = qty × price + line shipping, matching PurchaseOrderSummary.tsx), and lock the helpers with unit tests (packages/documents/src/utils/document-totals.test.ts).
Applies to: packages/documents/src/utils/{purchase-order,sales-order,sales-invoice,quote}.ts, PDF Summary/LineItems blocks, email/{PurchaseOrder,SalesOrder,SalesInvoice}Email.tsx, and any new document totals code.
Loader-computed "current unit" must match the component's, or per-unit attribution credits the wrong unit
Context: The MES assembly view resolves the unit on screen twice: the loader (apps/mes/app/routes/x+/assembly.$operationId.tsx) computes unitIndex from ?unit/?trackedEntityId, and AssemblyView.currentUnitIndex computes it again client-side. Per-unit material issue attribution (batch parents) was moved into the loader, keyed off the loader's unitIndex.
Problem: The two defaults diverged. When there's no ?unit param, AssemblyView lands on the NEXT unit still to build (min(quantityComplete, units.length-1)) — and the auto-complete effect DELETES ?unit after finishing a unit — but the loader defaulted unitIndex to 0. So on unit 2 (default landing) the loader attributed unit 1's stamped consumes (Unit=1) to the unit-2 view: parts showed 1/1/2/1 though nothing was issued to unit 2, and the scan gate (which reads the same values) let the operator Mark done. Serial parents were unaffected (attribution is per-entity, and both default to 0).
Rule: When a loader and its component both compute the same "current X" and one feeds data the other renders, their resolution logic — including the no-param default — must be identical. For the assembly loader, mirror AssemblyView.currentUnitIndex: index-paged (batch/untracked) parents default to min(quantityComplete, opQty-1), serial parents to 0. If you make a loader-computed index load-bearing for attribution, re-derive it the exact same way the UI does.
Applies to: apps/mes/app/routes/x+/assembly.$operationId.tsx (unitIndex) ↔ apps/mes/app/components/AssemblyView.tsx (currentUnitIndex); any loader/component pair where one computes an index the other renders.
Node-side re-exports from the Deno functions tree must dodge lib/database.ts
Context: @carbon/database re-exports code from packages/database/supabase/functions/ into the node world (src/client.ts → lib/postgres/index.ts). The shared inspection engine (src/quality.ts) needed getNextSequence from supabase/functions/shared/get-next-sequence.ts, which imported its DB type from ../lib/database.ts.
Problem: lib/database.ts imports ./driver.ts — the Deno-postgres driver whose types (queryObject, deno Pool) don't typecheck under the node tsconfig. Pulling any shared/*.ts helper that touches lib/database.ts into a src/* file breaks pnpm --filter @carbon/database typecheck, even though the runtime graph would have been fine.
Rule: Obsolete: src/client.ts is now the Node-only implementation and nothing in packages/database/src imports the Deno tree. Original rule: when making a Deno-tree helper importable from packages/database/src/*, its type-only imports must come from ../lib/postgres/index.ts (node-clean, already the src/client.ts re-export source), never ../lib/database.ts. import type { KyselyDatabase as DB } from "../lib/postgres/index.ts" is behavior-neutral for Deno. Check the full import chain (lib/utils.ts is safe; lib/database.ts/lib/driver.ts are not) before re-exporting.
Applies to: packages/database/src/{client,sampling,quality}.ts.
A zod .refine that returns an object instead of a boolean silently disables the check
Context: Cross-field validation in module *.models.ts zod schemas (real case: processValidator in apps/erp/app/modules/resources/resources.models.ts, lines 305–319).
Problem: .refine((data) => { if (bad) return { workCenters: ["..."] }; return true; }) looks like it reports a field error, but .refine's callback is coerced to a boolean — any non-empty object is truthy, so the "failure" branch returns a value that passes validation. Both processValidator refinements (work-center-required and standard-factor-required) never fire: the object was meant to be an error map, but .refine has no such API. The schema typechecks and the form submits, so the missing validation is invisible until bad data lands.
Rule: A .refine predicate must return a boolean (false = invalid). To attach a path/message, either pass the second { message, path } argument to .refine and return false on failure, or use .superRefine((data, ctx) => ctx.addIssue({ path, message })) when you need per-field errors. Never return an object/array from a .refine callback expecting it to be an error map.
Applies to: all apps/erp/app/modules/**/*.models.ts (and apps/mes/app/services/models.ts) zod schemas using .refine.
ON DELETE SET NULL on a composite FK nulls every referencing column, not just the pointer
Context: A nullable pointer column that references a sibling table on Carbon's composite key, e.g. workflow.activeVersionId → workflowVersion("id", "companyId") (20260730142317_workflows-foundation.sql). Because every Carbon table is keyed ("id", "companyId"), any such pointer FK is necessarily multi-column and includes companyId.
Problem: A bare FOREIGN KEY ("activeVersionId", "companyId") REFERENCES ... ON DELETE SET NULL sets all referencing columns to NULL when the parent row is deleted — including companyId, which is NOT NULL. The delete then fails with null value in column "companyId" of relation "workflow" violates not-null constraint, and the referenced row can never be deleted. It looks correct in review, applies cleanly, and only surfaces the first time something deletes the parent.
Rule: On a composite FK whose referencing columns include companyId (or any NOT NULL column), name the column in the action: ON DELETE SET NULL ("activeVersionId"). The column-list form needs Postgres 15+ (the local stack is 15.14). Same trap applies to ON UPDATE SET NULL and to SET DEFAULT. Always prove it with a real delete against the live schema — a migration that applies successfully tells you nothing about its referential actions.
Applies to: any migration adding a nullable pointer column that references another table's composite ("id", "companyId") key.
A read-time format-migration seam must run before the current-schema parse
Context: Versioned JSON documents stored in a JSONB column with a
formatVersion sibling column, upgraded on read so stored rows never need a
backfill (packages/documents/src/template/, packages/workflows/).
Problem: packages/workflows originally parsed the row against the current
zod schema and only then called migrateDefinition. A document old enough to need
migrating cannot satisfy the current schema by definition, so it failed the parse
and never reached the migration — the seam was dead on arrival. Worse, the parse
failure fell back to an empty canvas, so opening the version in the builder showed
nothing and the next save silently destroyed the stored nodes.
Rule: Run the migration on the raw JSON, before the current-schema parse.
Default a missing formatVersion to 1, never to CURRENT_*_FORMAT_VERSION —
"current" skips the very migration a legacy row needs. Treat a formatVersion
greater than current as an explicit failure, and return a discriminated
{ok: false, failure, message} rather than an empty document, so a caller can
refuse to save over a row it could not read.
Applies to: any read-time migrate*(payload, _from) seam —
packages/workflows/src/definition/normalize.ts,
packages/documents/src/template/defaults.ts.
A default: arm silently defeats discriminated-union exhaustiveness
Context: Several functions switching on the same discriminated union
(WorkflowNode["type"] across handles, refs, outputs, type checks, config checks).
Problem: Five switches each had a default: or simply returned undefined
for unhandled members, so adding a seventh node type produced zero compile
errors — verified with tsc --noEmit. The new node type got default handles and
no validation at all, and would activate.
Rule: For behaviour that must exist for every member of a union, prefer one
record keyed by a mapped type ({ [K in Kind]: ... }) over N switches: a missing
key is a TS2741 error. Where a switch is genuinely right, omit default: and end
with a never assertion. A Record<Union, T> gives the same guarantee — that is
what caught the missing OPERATOR_LABELS entries when Operator was extended.
Applies to: packages/workflows/src/definition/nodes.ts, and any
switch (x.type) over a zod discriminated union.
A generated catalog must key entity refs off the schema, not off a hand-written hint
Context: The workflow event catalog's entity registry lets a watched column
declare ref: "supplier", which becomes entity("supplier") in the generated
property map so a customer can dot-chain record.supplierId.name.
Problem: ref was needed for real — composite foreign keys like
(supplierId, companyId) carry no <fk table=…> note in
packages/database/src/swagger-docs-schema.ts, so purchaseOrder.supplierId
has no detectable target. But a hand-written hint is a hand-written lie waiting
to happen: customer.salesContactId was declared ref: "user" when its foreign
key actually targets customerContact. Nothing would have caught it, and every
dot-path through that property would have resolved against the wrong entity.
Rule: Where a generator accepts a hand-written type hint alongside a
machine-readable source, make disagreement a hard error rather than letting the
hint win silently. buildCatalog throws when a declared ref conflicts with a
foreign key present in the schema, and only uses ref where the schema is
genuinely silent. Audit every existing hint against the real source before
trusting a slate that came from a design document.
Applies to: packages/workflows/src/catalog/build.ts, and any hand-curated
overlay on generated schema data (packages/database/src/audit.config.ts's
snapshotFields / fkDisplayRegistry).
Lingui's msg macro forces generated translatable strings into their own file
Context: The generated workflow catalog needs a human label per event, and
Carbon's convention outside React is msg from @lingui/core/macro.
Problem: msg is a build-time babel macro. A generated file containing
one can only ever be imported by Vite-built app code — importing it from plain
Node throws, which would break the phase-3 matcher in packages/jobs, every
tsx script, and any vitest run that touches the catalog.
Rule: Split the artifact: events.generated.ts carries the runtime data and
imports nothing from @lingui/*; labels.generated.ts carries only msg`` descriptors keyed by id and is excluded from the package barrel. Tooling that must read the labels reads the file as **text** (regex the keys) rather than importing it — scripts/check-workflow-catalog.tsdoes exactly that. Never put alabel` field on the runtime type; it would always be undefined.
Applies to: packages/workflows/src/catalog/, and any future generated file
that needs both translatable strings and a Node-side consumer.
apps/erp targets ES2019, so packages/workflows cannot use BigInt literals
Context: The workflow engine needed a stable 64-bit hash for batch item keys,
and the plan specified FNV-1a via BigInt.
Problem: apps/erp/tsconfig.json sets "target": "ES2019" and compiles
workspace package source, not built output. A 0xcbf29ce484222325n literal
in packages/workflows fails the erp typecheck with TS2737 even though the
package's own tsc --noEmit passes — the package config targets esnext.
Rule: Anything in a package apps/erp imports must be ES2019-safe. Reach for
Math.imul and two 32-bit passes rather than one 64-bit BigInt pass. Always run
pnpm exec turbo run typecheck --filter=erp after touching a shared package —
the package's own typecheck is not the binding constraint.
Applies to: every packages/* that apps/erp imports; packages/workflows
doubly so, since the phase-7 builder also compiles it for the browser
(no node:crypto either).
A change trigger's before and after share a record id, so an id-keyed cache collapses them
Context: The workflow engine caches loaded records per run, keyed
${entity}:${id}, and a record trigger hands out record, before and after.
Problem: All three are the same row id. Seeding one cache from all three
means whichever is written last wins, so before.orderTotal <= 10000 silently
reads the new total — quietly defeating the PRD's whole "went up" case. Both
the spec and the plan missed this.
Rule: An entity RuntimeValue carries an optional inline row.
triggerOutputs attaches each trigger row to its own value, and seeds the shared
cache with the current state only (record/after). Never put a historical
snapshot into a cache keyed by identity alone.
Applies to: packages/jobs/src/workflows/engine/loader.ts,
packages/workflows/src/runtime/, and any future cache of "the record as it is"
that also has to represent "the record as it was".
The user table has no companyId, so the usual tenancy check cannot be applied to it
Context: The workflow update executor must prove that every entity-typed
value it writes belongs to the acting company, or a workflow could point a row at
another tenant's record. The plan specified one generic
select id where id = ? and companyId = ? for that check.
Problem: Every entity-typed writable column in the workflow catalogue is an
assignee, and they all point at user — which is one of the few Carbon tables
with no companyId column. The literal check would have 400'd on every
assignee write, i.e. on every workflow that assigns anybody.
Rule: Membership for user is userToCompany(userId, companyId), not a
column on the row. Route those entities through that join instead of skipping the
check — dropping it is the tenancy hole the check exists to close. Before writing
a "every table has companyId" helper, confirm it for the specific tables it
will actually receive.
Applies to: packages/jobs/src/workflows/actions/update.ts, and any generic
company-scoping helper that takes a table name at run time.
Biome drops quotes from valid identifier keys, so a drift check that greps for "key": misses them
Context: scripts/check-workflow-catalog.ts verifies the committed generated
catalogue matches what the generator would produce, partly by grepping the label
file for its keys.
Problem: The generator emits "notify": but Biome formats the committed file
to notify:. A regex anchored on ^ {2}"([^"]+)": therefore skipped exactly the
keys that happen to be valid JS identifiers — the check passed while genuinely
missing entries.
Rule: A check that reads a formatted generated file must tolerate the
formatter's output, not the generator's. Make the quotes optional
(^ {2}"?([^":\s]+)"?:), or compare parsed data rather than text.
Applies to: scripts/check-workflow-catalog.ts and any future drift check
that greps a Biome-formatted generated file.
Never hand-measure React Flow handle positions; and never stopPropagation inside a node
Context: apps/erp/app/modules/workflows/ui/Builder/NodeCard.tsx needed one
source handle per condition path, and needed nodes draggable from their body.
Problem: Two separate self-inflicted bugs. (1) Handle rows were measured with
getBoundingClientRect() and the offset written to style.top. getBoundingClientRect()
returns zoom-scaled pixels but style.top is applied inside the zoom transform,
so every handle sat at the wrong height at any zoom except 1.0 — and the effect
depended on the freshly-built ports array, so it re-ran and re-set state every
render. (2) The body used onPointerDown={e => e.stopPropagation()} on interactive
targets to stop React Flow dragging. React's stopPropagation also stops the native
event reaching document, and Radix DismissableLayer dismisses on a document-level
pointerdown — so every dropdown inside a node became impossible to close.
Rule: React Flow measures handle bounds from the DOM itself (zoom-aware) — put
the <Handle> inside a position: relative row and let its default
.react-flow__handle-right CSS anchor it; call useUpdateNodeInternals(nodeId)
when the handle set or node size changes, and never compute top/right yourself.
To exempt something from dragging, toggle React Flow's own nodrag class (a
capture-phase pointerdown listener runs before its bubble-phase drag listener) —
never stopPropagation, which silently breaks every portalled overlay's dismissal.
Applies to: apps/erp/app/modules/workflows/ui/Builder/**, and any @xyflow/react
canvas hosting Radix popovers/selects.
The design-system Card is a gray tray + shadow edge — the white surface is CardContent, and a tint on the shell needs a dark: variant
Context: Building card surfaces with @carbon/react's Card family (packages/react/src/Card.tsx), e.g. the onboarding Implementation Hub (packages/onboarding/src/ui/**). Three separate traps hit in sequence while converting hand-rolled rounded-lg border bg-card blocks to the design system.
Problem:
Cardisbg-accent dark:bg-card— a muted gray tray in light mode, not a white card. Putting content directly in<Card>reads gray. The white surface (bg-card) comes fromCardContent; the canonical composition isCard > CardHeader + CardContent(seeMetricCard.tsx,ActionTaskList.tsx).Card'sshadow-button-basealready draws the crisp outer edge (a0 0 0 1pxring + inset highlights). ACardContentbordersitting on top of that shadow ring reads as a blurry double line.- Overriding the shell background with an un-prefixed color (
bg-emerald-500/5) leavesCard's basedark:bg-cardin the class list;.dark .dark:bg-cardout-specifies.bg-emerald-500/5, so the tint silently disappears in dark mode (border/icon still show, so it degrades quietly).
Rule:
- Single-surface white card:
Card > CardContent(not content directly inCard). - Titled card: heading in
CardHeaderoverCardContent; the shell shadow is the outer edge, so useCardContent className="border-0"and put the header/body divider on theCardHeader(border-b border-border) — never a fullCardContentborder on top of the shadow. - Colored callout on a
Card: always pair the tint with itsdark:variant (bg-emerald-500/5 dark:bg-emerald-500/5).cn/twMerge then drops the basedark:bg-card. Verify by checking the rendered class list no longer containsdark:bg-card.
Applies to: any UI composing @carbon/react Card/CardContent/CardHeader; the Section/Panel primitives in packages/onboarding/src/ui/primitives/Section.tsx centralize this composition for the hub.
A dropdown that lives inside an editor popup must own its keys on the document, not take them from its host
Context: The workflow builder's variable menu (apps/erp/app/modules/workflows/ui/Builder/fields/VariableTreeMenu.tsx), hosted both inside a tiptap suggestion popup and inside a Radix popover. Arrow-key navigation stayed dead across two rounds of fixes.
Problem: The menu exposed a ref handle and relied on each host to call it — the tiptap suggestion plugin's onKeyDown delegation in one case, the popover search input's onKeyDown in the other. That chain is long (ProseMirror direct props → plugin order → ReactRenderer ref → imperative handle) and every link is invisible when it breaks: the menu still renders, so the failure looks like "keys do nothing" with no error anywhere. Debugging it by reading the chain repeatedly produced plausible-but-wrong root causes.
Rule: Bind the navigation keys in a document keydown listener in the capture phase, inside the menu component itself, and preventDefault() + stopPropagation() only for keys it claims. The host then cannot swallow or fail to forward anything, and both hosts get identical behaviour for free. Guard the listener on the menu's own root being connected and visible — a popup that is hidden rather than unmounted (tippy's hide()) leaves the component mounted and would keep eating keys. Never claim Escape; dismissal belongs to the wrapping popup. Keep DOM focus in the field being typed into (search-as-you-type depends on it) and mark the highlighted row aria-selected instead of focusing it.
Applies to: any menu rendered by tiptap's ReactRenderer or otherwise mounted outside the React tree that owns the focused input.
react-aria compares formatOptions by reference — an inline literal wipes half-typed numbers
Context: Any NumberField / Number / NumberControlled field that passes formatOptions={{ ... }} at the call site (real case: the MES Log Completed quantity in apps/mes/app/components/JobOperation/components/QuantityModal.tsx, where operators could not enter 1.5).
Problem: useNumberFieldState (@react-stately/numberfield) guards with formatOptions !== prevFormatOptions — a reference check — and on a change calls setInputValue(format(numberValue)), replacing whatever is in the input with the last committed number. react-aria-components' NumberField spreads caller props straight through, so an inline object literal is a new reference every render. Any parent re-render while the user is mid-edit destroys the in-progress text. Commit only happens on blur/Enter/stepper, so a single digit usually survives but a decimal (1. → 1.5, two-plus keystrokes) reliably does not. It reads as "the field doesn't support decimals" even though the format options, the zod validator, and the numeric DB column all allow them.
Rule: Never let an unstable Intl.NumberFormatOptions reference reach react-aria. packages/react/src/Number.tsx's NumberField now stabilizes it via useStableFormatOptions / areNumberFormatOptionsEqual (shallow value compare — exact, since the options are all primitives), so call sites are free to pass literals. If you build another react-aria wrapper that forwards formatOptions, do the same; do not "fix" this class of bug by only adding/adjusting formatOptions at the call site — that is what introduced it here. Also note the same trap for any react-aria prop compared by identity.
Applies to: packages/react/src/Number.tsx; every formatOptions={{ ... }} call site in apps/erp / apps/mes (~144); packages/form/src/components/{Number,NumberControlled,ArrayNumeric}.tsx, whose rest.formatOptions ?? ({ ... }) default also allocates a fresh object each render.
Returns must not decrement pickingListLine.quantityPicked — the status trigger demotes terminal headers
Context: Building the picked-material return sweep (spec .ai/specs/2026-08-04-picked-material-return-timing.md). The original returnPickedRemainder case in post-picking decremented pickingListLine.quantityPicked when flushing un-consumed staged stock back to the warehouse at job complete.
Problem: update_picking_list_status (AFTER UPDATE ROW on pickingListLine, newest body 20260728120100) fires on any quantityPicked change. After the decrement the line satisfies quantityPicked < quantityToPick, so the trigger's work-remains branch moves a Completed/Partial picking-list header back to In Progress — the automatic job-complete sweep was silently reopening completed picking lists. The demotion is CORRECT for an operator unpick (work regression); it is wrong for a post-completion return.
Rule: Book returns on pickingListLine.quantityReturned (added 20260804111631) and leave quantityPicked as gross-picked; net staged at lineside = quantityPicked − quantityReturned. Only genuine unpicks (operator reversing work) may decrement quantityPicked. Any new writer of pickingListLine.quantityPicked/status must first check what update_picking_list_status will do with the change. pickingListLineTrackedEntity allocations are different — returns DO decrement those (availability RPCs net them out; no trigger watches that table).
Applies to: postPicking (apps/erp/app/modules/inventory/inventory.service.ts, all return/unpick cases), update_picking_list_status migrations, any code mutating pickingListLine quantities.
Audit FK snapshots: constraint-less columns are invisible to schema discovery; junction targets need hops
Context: Audit-log diffs resolve FK ids into frozen display names ("Location: Chicago → Dallas") via get_foreign_key_map + fkDisplayRegistry (packages/database/src/audit.config.ts, handler in packages/jobs/src/inngest/functions/events/{audit,fk-snapshots}.ts). Found while fixing "audit log shows location id instead of name" (2026-08).
Problem: Three distinct shapes made raw ids reach the UI. (1) get_foreign_key_map reads pg_constraint, so reference columns without a real FK constraint are invisible to it — no snapshot no matter what the registry says. This schema has many: salesOrder.salesPersonId, salesInvoice.assignee, line-level locationIds on purchaseOrderLine/salesOrderLine/salesInvoiceShipment, inventoryCountLine.storageUnitId, etc. (2) Junction targets (customerContact/supplierContact, opportunity, fulfillment…) have no displayable columns of their own — the name lives one hop away (contact.fullName), which single-hop resolution can't reach. (3) A target table simply missing from fkDisplayRegistry silently degrades to the raw id — no error anywhere.
Rule: When adding a reference column to an audited table, either give it a real FK constraint (registry/hops then cover it automatically) or declare a per-column snapshotFields override on that table's audit config. For targets whose display value lives on another table, use fkDisplayHops (two-stage batched lookup). Resolution precedence is override > hop > registry; hops and registry must stay disjoint, and overrides must not target hop tables — both invariants are enforced by tests in fk-snapshots.test.ts. Snapshots are frozen at write time: config changes never backfill existing audit rows.
Applies to: packages/database/src/audit.config.ts (fkDisplayRegistry, fkDisplayHops, snapshotFields), packages/jobs/src/inngest/functions/events/fk-snapshots.ts + audit.ts, and any migration adding reference columns to tables listed in auditConfig.entities.
An isolation: "worktree" subagent forks from main, not the parent's current branch
Context: Dispatching three Agent subagents with isolation: "worktree" to run /feature autonomously for NIST items, each told it was "forked from branch nist-800-110-audit" and building on code that lives ONLY on that branch (packages/auth/src/services/auth-events.server.ts etc., absent from main).
Problem: The worktree the Agent tool creates forks from the repo's default (main), NOT the parent session's current branch HEAD. A subagent that trusts the "you are on " framing is actually on a main-based commit missing all the branch's work. Two of three agents noticed (the referenced file was absent at HEAD) and re-branched from origin/nist-800-110-audit; the third did not — it vendored a duplicate of the branch-only auth-events.server.ts, and its PR branch dragged in ~70 files of main-only work plus the duplicate, so the PR was unmergeable and had to be rebuilt by hand.
Rule: When an agent's task depends on unmerged branch code, do not assume the worktree is based on that branch. In the dispatch prompt, require the agent to git fetch origin and explicitly branch from origin/<intended-base>, set the PR --base to it, and verify the base before writing code (confirm a known branch-only file exists at HEAD; STOP and report if it is missing rather than recreating/vendoring it). When a delivered branch looks wrong, check git merge-base <base> <deliveredBranch> against the base HEAD — a merge-base far back means it forked from the wrong place. To salvage a mis-based branch, extract only its real new files onto a fresh branch off the correct base (don't cherry-pick its whole divergent history).
Applies to: any Agent call with isolation: "worktree" whose work builds on unmerged branch state; PR base selection for agent-produced branches.
Resolve merge conflicts in GENERATED files by regenerating, not by hand-editing the markers
Context: Merging origin/main into a long-lived feature branch where both sides had added migrations. The only conflicts were generated outputs: packages/database/src/types.ts + functions/lib/types.ts (one FK-relationship hunk each) and apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json.
Problem: Git auto-combined most of the generated output but left one view's relationship list conflicting. Hand-picking a side drops one branch's relationships (the view genuinely has all the columns); union-merging risks duplicating entries; either way the result may not match what the real generator emits from the COMBINED schema. Generated files are outputs, not source — resolving their conflict markers by hand is guessing at the generator.
Rule: For a conflict in a generated file, regenerate instead of editing markers. For @carbon/database types: start the postgres container, apply BOTH branches' pending migrations (pnpm db:migrate), then pnpm run generate:types — it overwrites types.ts from the live schema, connects via SUPABASE_DB_URL, and needs only postgres (not the full stack; the chained swagger step needs PostgREST and can fail harmlessly). git add the regenerated files to resolve. For build-time artifacts that regenerate on pnpm dev/build (swagger-docs-schema.ts, tool-metadata.json), take the superset side (usually main's) as a placeholder — it self-corrects on next build. generate:types FK ordering is non-deterministic, so ignore ordering-only churn afterward (see the turbo-regen lesson above). Applying pending migrations forward is NOT a DB rebuild — that is the normal path; a full reset still needs the user.
Applies to: merging main into any branch with migrations on both sides; conflicts in packages/database/src/types.ts, swagger-docs-schema.ts, apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json, and any committed generated artifact.
A flip/refactor must not add ledger rows to a code path that deliberately posted none
Context: Implementing the batch-split identity flip (spec 2026-08-04-batch-split-identity-flip.md) via a shared buildBatchSplitRecords builder that emits a 2-row net-zero Batch Split itemLedger pair. Wired it into all five split writers uniformly, including post-shipment's Purchase-Order-sourced block.
Problem: The pre-flip post-shipment PO block (subcontract / outside-processing shipments against a PO) wrote split genealogy only — trackedEntity + trackedActivity + output rows — and posted zero itemLedger rows, unlike the SO block which posts a Sales Shipment negative-adjustment the split pair complements. Mechanically wiring the builder's ledger inserts into the PO block introduced a −q on the parent that nothing in that path offsets, changing inventory behavior for subcontract shipments with unclear valuation consequences. Own-file deno check and typecheck stay green (it compiles fine), so only reading the ORIGINAL of each branch caught it. Self-review found it; the browser e2e never would have (no shippable PO fixture).
Rule: When applying a uniform transformation across N sibling branches, diff each branch against its own pre-change body — don't assume they were symmetric. A branch that posted no ledger, sent no email, fired no event before your change must still post/send/fire nothing after, unless the spec explicitly says otherwise. "It typechecks and the other four branches do it" is not evidence the fifth should. Preserve per-branch behavior; the flip's mandate was which id departs, not to newly introduce inventory movements.
Applies to: apps/erp/app/modules/inventory/inventory.service.ts (PO vs SO split blocks); any refactor threading a shared record-builder through multiple writers (post-*, issue, sync handlers).
Carbon journal amounts are natural-balance-signed, not debit-signed
- Context: Wiring Rillet journal posting sync; first live push of a real
Purchase Receiptjournal failed UNBALANCED_JOURNAL (+300/+300). - Problem: The accounting sync engine (preflight balance check, netting,
consolidation, all provider journal mappers) assumed
journalLine.amountis debit-signed (positive = debit, negative = credit, sum = 0). Carbon's post-* edge functions actually sign by the account's NATURAL balance (credit("liability", x)stores +x — packages/database/src/ledger.ts), so real journals balance as debits == credits, not signed-sum-zero. Also: Kysely/pg returns DATE columns as JS Date objects —postingDate.slicecrashes; and disabled-config skip results withoutlocalIdmake the drain report the misleading "No sync result returned for entity". - Rule: Convert to debit-signed at the fetch edge with
toDebitSignedAmount(account.class, amount)(join account.class in the journal-line query), normalize dates withtoPostingDateString, and always setlocalId/remoteIdon every SyncResult, including early skips. Never trust the debit-signed assumption against live journal data without checking the edge functions' credit()/debit() helpers. - Applies to: packages/ee/src/accounting (journal syncers, posting preflight, consolidation), any new accounting provider's journal mapper.
A conformance check is only as good as its source glob — route modules are server AND client in one file
Context: The timezone audit (branch sid/timezone-tz-audit, PR #1339) added the no-local-timezone conformance check to ban process-timezone day derivation in server code. Self-review then found 26 surviving violations in route files, plus more in files the check DID scan using idioms it didn't match.
Problem: Two independent under-coverages compounded. (1) The check's source globs (sources/server-files.ts) listed services, jobs, and edge functions but not apps/*/app/routes — and collected only .ts, never .tsx — so route loaders/actions (server code!) were never scanned. (2) The banned-pattern list encoded only the idioms already found (getLocalTimeZone(, UTC-slicing), not the bug class — new Date().getDay() shift rosters and setHours(0,0,0,0) week boundaries sailed through in files that WERE scanned. Naively adding the route glob would over-flag: a route module's default export, clientLoader/clientAction, and hooks run in the browser where the local timezone is correct. Masking IN loader/action bodies also failed — module-level helpers a loader calls (e.g. getExpiredItemIds) are server code outside those bodies.
Rule: When authoring a conformance check, verify the checker actually loads every file class the rule applies to (run it, count the files, grep one known-bad file into the scan). Ban the bug class, not just the instances you found — then run the widened pattern over the full source set and fix or baseline everything it surfaces before landing. For React Router route modules, path-level globs are the wrong granularity: mask OUT the client regions by declaration shape (maskClientCode blanks default export / clientLoader / clientAction / PascalCase and use* declarations) so server helpers stay covered; masking IN named exports under-covers. And when masking by line shape, the region CLOSER is as bug-prone as the opener: a ) closer that also matches a multi-line signature's ) { line ends the region before the body and un-masks client code (only statement-terminating )/); lines close a region), while an expression-bodied one-liner (const X = () => null;) must never OPEN a region at all — pin both shapes as regression tests.
Applies to: packages/checks/src/sources/server-files.ts + conformance/no-local-timezone.ts; any new SERVER_CHECKS rule; any lint/conformance gate keyed on file paths over apps/*/app/routes.
A per-request memo keyed on the Request object never hits — React Router doesn't share one across loaders
Context: Perf work on sid/perf-audit-hot-paths (2026-08). Every matched route calls requirePermissions independently, so a detail page did one Redis GET for permission claims and one createClient() per loader. The obvious fix is to memoize per request.
Problem: The first attempt was a WeakMap<Request, …> — safe-looking, self-evicting, zero call-site changes, and it passed typecheck plus six unit tests asserting "same Request → same value, different Request → different value". It also did nothing: measured with redis-cli monitor, claims lookups on a deep page were 4 both with and without it, because React Router does not hand the same Request instance to every matched loader. The unit tests were green precisely because they constructed the shared-Request case the runtime never produces. The working mechanism is AsyncLocalStorage holding React Router's own per-request RouterContextProvider (published by a root middleware) — the same pattern requestIdMiddleware already used via LogTape's withContext. That took the page from 4 lookups to 1.
Rule: A memo is a performance claim, and a performance claim needs a measurement, not a unit test — a test can only prove the memo behaves as written, never that its key is stable in production. Before shipping request-scoped caching, count the underlying calls end-to-end (redis MONITOR, pg_stat_statements, a temporary counter) with the change toggled off and on. Reach for ALS-over-context rather than keying on Request. And note the corollary: memoizing database state must be gated to GET/HEAD/OPTIONS (oncePerRead), because React Router runs an action and its loader revalidation in a single request — an ungated memo there serves pre-write data, which for permission claims means a gate passing on permissions the action just revoked.
Applies to: packages/logger/src/context.server.ts (oncePerRequest / oncePerRead / requestContextMiddleware), packages/auth/src/services/{auth,users}.server.ts, and any future request-scoped cache.
A word-boundary rename corrupts UI copy that typecheck and tests can't see
Context: Splitting ERP list types into X (full view row, for detail screens) and XListItem (the narrowed list select) on sid/perf-audit-hot-paths. Applied with a regex renaming the whole-word alias across each table component.
Problem: Part, Material, Tool, Consumable, Service are single words that appear in user-visible strings as well as type positions. The rename produced t`PartListItem ID` , <Trans>Delete PartListItem</Trans>, and a button reading "Add PartListItem" — 20 occurrences across five files. Typecheck passed, 268 unit tests passed, all ten narrowed selects returned 206 from PostgREST, and EXPLAIN looked right. Only loading the page caught it. (The five multi-word aliases — PurchaseOrder, SalesOrder, … — were untouched, because their display text contains a space.)
Rule: After any mechanical rename of an identifier that is also an English word, grep for the new name inside string literals, template literals and JSX text (t`…` , <Trans>…</Trans>, "…") before committing — and load one affected screen. Type-level green says nothing about copy. Prefer renaming with an editor's symbol-aware rename over a regex; when a regex is the only option, exclude string/JSX regions explicitly.
Applies to: apps/erp/app/modules/*/ui/*/*Table.tsx, apps/erp/app/modules/*/types.ts; any bulk identifier rename in files containing Lingui macros.
A new package exports subpath 500s until every running dev server restarts
Context: Adding @carbon/logger/context.server and @carbon/auth/request-scope during the same perf work.
Problem: Vite resolves a package's exports map once at dev-server start. Adding a subpath and importing it immediately produced "./context.server" is not exported under the conditions [...] on every route — a hard 500 across the whole app, twice, each time looking like a code bug rather than a stale resolver. Typecheck was green throughout, since TypeScript reads the updated package.json directly.
Rule: Adding an export subpath to a workspace package is a dev-server-restart change. Either restart every running dev server as part of the change, or re-export the new module from an already-exported entry point and leave a TODO to move it at the next coordinated restart. A green typecheck does not mean the running server can resolve the import.
Applies to: packages/*/package.json exports, and any new src/*.server.ts intended for cross-package import.
space-x-* gives a phantom margin when a component injects sibling nodes
Context: A reported layout shift — hovering any row of an ERP list table shifted every column of the whole table ~8px sideways.
Problem: Hyperlink renders <Link prefetch="intent">. React Router implements that by rendering <>{anchor}{prefetchLinks}</>, so on hover four <link rel="prefetch"> elements appear as siblings of the anchor inside whatever container the caller used — here <HStack>. Tailwind v4's space-x-* compiles to & > :not(:last-child) { margin-inline-end }, so the instant those links mount the anchor stops being :last-child and gains a real 8px margin. Under table-layout: auto that re-lays out the column and the whole table. The links are display: none, which is exactly why this reads as impossible: every computed style on the <td> except background-color is unchanged, the anchor and all its children keep identical widths, and only the <td> and its wrapper grow. Two false leads first — the load-time column settle (237.5 → 245.1 with no hover, ~4s after load) masquerades as the same shift, and opacity-0 → opacity-100 on the "Open" button looks like the obvious culprit but cannot move layout.
Rule: space-x-* / space-y-* are structural (:not(:last-child)) — never use them on a container whose children a component may add to at runtime; use gap-*, which only applies between elements that generate boxes and so ignores display:none. When a component renders extra DOM next to its main element (React Router prefetch links, portals, measurement nodes), isolate it in a display: contents wrapper so it can't perturb the caller's layout. To diagnose "impossible" width changes, diff every computed property between states and count child nodes — a node-count delta with no style delta means injected DOM, not CSS.
Applies to: apps/erp/app/components/Hyperlink.tsx; packages/react/src/{HStack,VStack}.tsx (still space-x-*/space-y-*, ~2,500 call sites); any PrefetchLink (@carbon/react, which injects the same tags on press) or <Link prefetch> placed directly inside a space-* container.
A list-query benchmark that omits the ORDER BY measures a query the app never runs
Context: Lateralizing the salesOrders/purchaseOrders list views on sid/perf-audit-hot-paths. The rewrite benchmarked as a ~9x win and shipped; re-measuring later against the real endpoint showed page 1 taking 41.6 seconds.
Problem: The benchmark ran SELECT ... FROM "salesOrders" WHERE "companyId" = $1 LIMIT 100 — no ORDER BY. Every one of these endpoints applies a fixed default sort (setGenericQueryFilters(query, args, [{ column: "createdAt", ascending: false }])). That one clause inverts the result: with no sort the planner pushes LIMIT 100 below the lateral join so the aggregate runs ~100 times (10.6 ms vs 91.3 ms for the bulk form — the win that was measured); with the sort and no index supplying its order, every row must be produced before the limit applies, so the aggregate runs once per order in the company — 10,000 times, each re-scanning item under a non-indexable RLS policy. Two other things hid it: the seeded tables had never been analyzed (last_analyze and last_autoanalyze both NULL, n_live_tup 0), so plan choice was unstable; and the stated rationale — "the bulk form aggregates every tenant's lines" — was simply false, since salesOrderLine has RLS and the view is SECURITY INVOKER, so it was always company-scoped.
Rule: Benchmark the query the service actually builds — copy the projection, the ORDER BY from setGenericQueryFilters, and the LIMIT/OFFSET, not a simplified SELECT * ... LIMIT n. Run ANALYZE before trusting any timing on seeded data, and check pg_stat_user_tables.last_analyze first. When a rewrite's premise is "this touches rows it shouldn't", verify it against pg_policies before optimizing — RLS may already be doing it. A LATERAL is only a win when the limit can be pushed below the join, which needs an index supplying the sort; check the plan for Seq Scan ... loops=<number of outer rows>, which is the signature of a per-row aggregate that was meant to run per page.
Applies to: packages/database/supabase/migrations/20260807011742_lateralize-order-list-views.sql, 20260806235710_perf-list-query-indexes.sql, apps/erp/app/utils/query.ts (setGenericQueryFilters), and any future list-view or RLS-policy performance work.
Inngest concurrency: { limit: 0 } is no capacity, not unlimited
Context: Moving webhooks onto the event system. The WEBHOOK handler had never actually run — webhooks went through 39 pg_net triggers, so the handler was dead code. Once a subscription made it live, every delivery sat in QUEUED forever and nothing reached the endpoint.
Problem: webhook.ts declared concurrency: { limit: 0, key: "<table>-<recordId>" }. limit: 0 reads like "unlimited" and is almost certainly what the author meant, but Inngest treats it as zero capacity: runs are accepted, grouped by key, and never scheduled. The failure is silent and looks like the event never fired — the drainer completes, the queue empties, pgmq shows nothing pending, and only the run list reveals runs parked in QUEUED while sibling handlers from the same drain show COMPLETED. A controlled test confirmed it: three runs stuck at limit: 0, and changing only that value to 1 released them. Two more instances existed — workflow.ts (a stub, latent) and reschedule-job.ts (schedule-job, live, called from production.server.ts and production.service.ts).
Rule: Inngest concurrency.limit must be >= 1; to mean "unlimited", omit the concurrency block entirely. With a key, limit: 1 is the usual intent — serialize per record/company. Enforced by the no-zero-concurrency conformance check in @carbon/checks. More generally: a handler with zero subscriptions is dead code whose config is never exercised, so any bug in it surfaces only when something makes it live — when wiring an existing-but-unused handler, fire it end-to-end rather than trusting that it worked before.
Applies to: packages/jobs/src/inngest/** createFunction options; packages/checks/src/conformance/no-zero-concurrency.ts.
Generated DB types must come from a migration-built database, never a restored snapshot
Context: crbn restore ends with pnpm db:types. Those regenerated types were then swept into a commit by git add -A, putting 194 lines of unrelated churn into a webhooks/RLS PR.
Problem: A production snapshot carries whatever the source environment accumulated outside the migration stream, so types generated from it describe that database rather than the schema the migrations define. The diff added a v_readable_id relation absent from main — not a schema object at all, but a plpgsql local (v_readable_id TEXT; … SELECT … INTO v_readable_id, v_company_id) that ran somewhere in a plain-SQL context, where SELECT … INTO is CREATE-TABLE-AS. An accidental artifact table exists in the snapshot, and regenerating baked it into the repo's public type surface, alongside procedureStep→procedureAttribute FK-name churn.
Rule: Never commit packages/database/src/types.ts generated after a crbn restore — regenerate against a migration-built database first. crbn restore now warns about this. Stage generated types explicitly rather than with git add -A, and diff them before committing: any relation appearing that no migration defines is drift from the source environment, not a schema change. Separately, SELECT … INTO <name> in a SQL (non-plpgsql) context silently creates a table — a real hazard when copying plpgsql bodies into migrations.
Applies to: packages/dev/src/commands/restore.ts, packages/database/src/types.ts.
Kysely returns NUMERIC as a string; supabase-js returns it as a number
Context: upsertQuoteLinePrices was converted from supabase-js to a Kysely transaction so its delete + reinsert would roll back as a unit. The conversion typechecked, and the shipped result silently stopped preserving shippingCost, discountPercent and leadTime on every markup change.
Problem: The function keys the snapshot of existing rows by quantity and looks each one up while building the reinsert. Through PostgREST a NUMERIC column arrives as a JS number, so pricesByQuantity[10] matched. Through node-postgres — which Kysely uses — the same column arrives as the string "10.00000", because pg does not parse NUMERIC (oid 1700) to float and this repo sets no setTypeParser anywhere. Every Map.get(10) therefore missed, existing was always undefined, and each preserved field fell back to the caller's value: shipping to the column default 0, discount and lead time to the zeros the recalculate route passes. The generated types say number on both paths, so tsc cannot see it — the mismatch exists only at runtime.
Rule (updated by the numeric-precision standard): NUMERIC (oid 1700) now decodes to a JS number — node-postgres via setTypeParser, registered once in packages/database/src/client.ts — so runtime finally matches the generated types for numerics. The caution below still applies to BIGINT and float8 (still strings), to any pool NOT built through the shared factory, and as history for why Number(...) coercions litter Kysely call sites (they are now harmless no-ops). Original rule: when porting a query from supabase-js to Kysely, treat every NUMERIC/DECIMAL/BIGINT read as a string regardless of what the generated type claims. Normalize with Number(...) only where the value has to be a number — an object/Map key, a === comparison, arithmetic — and only for bounded fields like a quantity or a precision. Do not normalize a whole row for tidiness: Number() on a BIGINT or a wide NUMERIC silently loses precision past Number.MAX_SAFE_INTEGER, and money is exactly where that matters. Writing values back untouched is both safe and preferable — pg accepts the canonical string for a numeric param, and passing it straight through preserves the stored value exactly. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.
Applies to: apps/erp/app/modules/sales/sales.service.ts (upsertQuoteLinePrices), any Kysely<KyselyDatabase> service in apps/erp/app/modules/**, and the getPostgresClient pool in packages/database/src/client.ts.
The migration ledger must travel with the schema it describes
Context: A crbn restore left the people board dead ("Failed to load people assignments"): the dump's schema was weeks older than the branch, yet supabase migration up reported "schema already up to date", so ~60 migrations' worth of tables (people, workflows, inspections, the operationType enum consolidation) silently didn't exist.
Problem: The restore script dropped every public object and loaded the dump — but never touched supabase_migrations.schema_migrations. The local ledger (which recorded everything as applied against the PRE-restore database) survived, and the dump's own ledger rows lost their primary-key conflicts under ON_ERROR_STOP=0. Result: an older schema paired with a newer ledger, which makes every "apply what's pending" mechanism a no-op. Diagnosing it required probing per-migration artifacts (tables, enum values, functions) because the ledger could no longer be trusted; recovery was deleting the stale ledger rows and replaying, marking the two genuinely-applied ones on their loud "already exists" failures.
Rule: Any operation that replaces schema state wholesale (restore, snapshot rollback, volume swap) must replace the migration ledger in the same stroke — truncate it before the load so the source's ledger lands and anything the backup predates genuinely pends. When a ledger and its schema disagree, believe the schema: probe artifacts, don't trust records. scripts/restore-database.sh now truncates the ledger before loading the dump; crbn restore's trailing applyMigrations step is unchanged and picks up the pending set.
Applies to: scripts/restore-database.sh, any future backup/restore or snapshot tooling.
A VERIFY-flagged provider endpoint in a cron loop is an outage, not a TODO
Context: The Rillet AP payment pull assumed an org-wide GET /bill-payments feed mirroring /invoice-payments. The method carried a VERIFY comment ("assumed to mirror… not confirmed") and even named its own fallback, but shipped unguarded inside listChanges. The endpoint does not exist (404).
Problem: Every accounting-pull-sweep run threw at the AP step, killing the whole Rillet pull — including the AR invoice-payment changes collected earlier in the same call — every 30 minutes, silently. Payments recorded in Rillet never flowed back to Carbon, so a bill paid remotely stayed open locally, got paid a second time in Carbon, and the outbound push then failed forever on Rillet's over-pay guard. One unverified assumption at the bottom of a sweep became a permanent, compounding data gap that surfaced two layers away from its cause.
Rule: An API call that only runs inside a cron/sweep is exercised for the first time in production — verify VERIFY-flagged endpoints against the live sandbox before wiring them into a loop (one curl answers it), and never let one entity family's listing failure discard another family's already-collected changes. When an assumed endpoint is missing, compose from verified ones instead: Rillet AP payments = GET /bills?updated.gt (payment activity bumps the bill's updated_at) + GET /bills/{id}/payments per changed bill.
Applies to: packages/ee/src/accounting/providers/rillet/provider.ts (listChanges, listBillPaymentsUpdatedSince), any SupportsIncrementalPull.listChanges implementation, VERIFY-flagged calls anywhere under packages/ee/src/accounting/providers/**.
react-aria's blur commit makes the input formatter part of arithmetic
Context: The numeric-precision standard's motivating bug — a user typed 6.25% tax, saved, reopened, and read 6.22%.
Problem: react-aria NumberField commits on blur by running parse(format(value)) — whatever formatOptions the input carries re-rounds the committed number. A currency-formatted amount input rounds to cents on blur; the old bidirectional tax pair (amount edit → percent = amount/subtotal, percent edit → amount = subtotal×percent) then overwrote the typed 6.25% with 0.56/9.00 = 6.22%. Nothing in zod, the column type, or the service was wrong — the INPUT FORMATTER did the rounding, and the coupling propagated it.
Rule: Editable numeric inputs must use the named INPUT_FORMAT.* kinds from @carbon/utils (rate max 3 percent-digits, quantity max 5, money/price at the currency's decimals) so the blur round-trip preserves the stored scale. Round a derived value to the scale of the field that will hold it BEFORE putting it there — that is the actual fix. An unrounded 0.5625 in a cents-formatted input is re-committed as 0.56 on blur, which registers as a genuine change and feeds back through any coupling; a value derived through applyRate at the currency's decimals commits identically and triggers nothing. With that in place a value pair can safely stay coupled in both directions (TaxFields does, so the stored pair is always consistent), accepting that a rate derived back from an amount is limited by the amount's scale. When an input's digits look like a display preference, remember they are arithmetic on the persisted value.
Applies to: every formatOptions on an editable NumberField/NumberControlled/EditableNumberCell; apps/erp/app/components/Form/TaxFields.tsx; .claude/rules/numeric-precision.md; the no-inline-fraction-digits conformance check.
Postgres transition tables are visible ONLY to the function the trigger invokes directly
Context: The itemStockQuantities aggregate needed a statement-level handler on itemLedger so a bulk posting is one upsert instead of N. The event system already builds statement-level triggers (trg_event_async_* with REFERENCING NEW TABLE AS batched_new), so the obvious move was to have dispatch_event_batch() forward to a custom function.
Problem: A nested call cannot see the transition tables. A plain function called from the trigger function fails with relation "batched_new" does not exist — and this holds for dynamic SQL too (EXECUTE 'SELECT count(*) FROM batched_new' fails identically), because the ephemeral named relation lives in the trigger function's own query environment and is not propagated. The only ways to hand a batch onward are materializing it into a temp table per statement (real cost on a hot write path) or not nesting at all. Separately, dispatch_event_batch() early-returns when a table has no active subscription and when app.sync_in_progress is set — both correct for queueing, fatal for an aggregate that must always be maintained.
Rule: A function that needs batched_new/batched_old must be attached as the trigger's own function. Use attach_statement_handler(table, functions[]) (20260812002453), the statement-level sibling of the row-level interceptors; it does not enqueue to PGMQ. Handlers are attached for INSERT/UPDATE/DELETE and must branch on TG_OP — only batched_new exists on INSERT, only batched_old on DELETE (PL/pgSQL plans lazily, so an unexecuted branch never resolves its missing table). Note also that adding a defaulted parameter to attach_event_trigger is a trap: two overloads are live, and a third with defaults makes existing 2-arg calls ambiguous.
Applies to: packages/database/supabase/migrations/20260812002453_event-system-statement-handlers.sql, .claude/rules/event-system.md, any statement-level trigger work under packages/database/supabase/migrations/.
Enumerate the full ON DELETE graph before writing a data-deleting migration
Context: A migration deleted 50 jobMaterial rows where a job listed its own output item as a material. A dry run "passed": it completed, and productionQuantity was verified unchanged at 4,566 rows.
Problem: The verification only covered the one child table that happens to be NO ACTION. jobMaterial → jobMakeMethod → jobOperation cascades into six further tables — productionEvent (labor/time), jobOperationTool, jobOperationStep, jobOperationParameter, rework, nonConformanceJobOperation — all CASCADE, all silent. productionQuantity was noticed precisely because NO ACTION raises an error; the destructive edges said nothing. Comparing the restored database against the untouched backup showed productionEvent had gone 3,159 → 3,158: one real customer labor record destroyed by a migration that appeared to succeed.
Rule: Before any DELETE in a migration, query pg_constraint for confrelid of every table the delete can reach and read confdeltype for each edge (c = CASCADE, r/a = RESTRICT/NO ACTION, n = SET NULL). The RESTRICT edges are the ones that will teach you by failing; the CASCADE edges are where the data actually goes. Design the cleanup so the cascade cannot reach anything historical — here, detaching (parentMaterialId = NULL) every subtree containing ANY jobOperation, so only empty method copies are collected. Verify with a probe that builds the exact structure, runs the real delete statement, and asserts the child rows survive — and where a snapshot exists, diff the affected table's count against the backup rather than trusting that the statement completed.
Applies to: packages/database/supabase/migrations/20260812032423_job-material-self-reference-guard.sql, any migration under packages/database/supabase/migrations/ containing DELETE FROM.
max_rows is enforced in production but not by the local dev stack
Context: MRP's Phase-1 loads used bare .select("*") with no pagination, and had done so since the function was written. Every local test passed.
Problem: packages/database/supabase/config.toml sets max_rows = 1000, so PostgREST truncates responses in production. The crbn dev stack runs its own postgrest container without PGRST_DB_MAX_ROWS, so locally the same query returns everything — verified: a view with 2,497 rows returned all 2,497 locally. Two production tenants exceeded the cap on openJobMaterialLines (2,497 and 1,495 rows) and a third on demandActual (9,391), so MRP silently planned on truncated demand and its zeroing pass missed stale actuals. The bug is structurally invisible to local testing.
Rule: Any PostgREST read that can exceed 1000 rows must paginate — fetchAllFromTable/fetchAllRecords from @carbon/database in app code, fetchAll (@carbon/database/fetch-all, source packages/database/src/fetch-all.ts) in server functions, @carbon/planning and edge functions — and must carry a stable .order() so pages don't shift between requests. Do not conclude "it returns everything" from a local run; check the row count against max_rows in config.toml instead.
Applies to: packages/planning/src/mrp/mrp.ts, packages/database/src/fetch-all.ts, packages/database/supabase/config.toml, any .select() in packages/planning/src/** or apps/erp/app/modules/**.
sum(DISTINCT expr) is not a fan-out dedup — it collapses equal values from different rows
Context: The salesOrders view aggregated line totals in a lateral that also LEFT JOINs job (one line → many jobs), and used sum(DISTINCT <line total>) to cancel the join fan-out. An order with two different lines that compute to the same amount (e.g. two items at 10 × $50 each) counted that amount once, understating the total on the list page, the dashboard KPI chart, and the sales funnel — while the detail page and PDF (app-side plain sums) were correct. Dozens of real orders were affected.
Problem: DISTINCT inside an aggregate dedupes by VALUE, not by source row. It cancels duplication from a join fan-out only as long as no two distinct rows produce the same value — for money amounts (repeated items, same qty × price) that collision is routine. The failure is silent and data-dependent: the view verifies "byte-identical" against its predecessor because the predecessor had the same bug.
Rule: Never use sum(DISTINCT ...)/count(DISTINCT ...)-style aggregates to undo join fan-out. Compute the aggregate in its own lateral/subquery over just the table being summed (no fan-out ⇒ plain sum()), and keep the fanned join in a separate lateral for the aggregates that need it. When reviewing a view, treat any agg(DISTINCT ...) over a joined row set as a probable value-collapse bug. Fixed in 20260812211507_fix-sales-order-total-duplicate-line-amounts.sql.
Applies to: packages/database/supabase/migrations/ views aggregating over joins (salesOrders, purchaseOrders, quotes/invoices list views); any SQL review touching sum(DISTINCT.
w-full on a flex item ignores its siblings — use flex-1 min-w-0
Context: Every document line-item view (digital quote, quote, sales order, purchase order, supplier quote, both invoice summaries — 12 files) lays a row out as a flex row: a fixed w-24 thumbnail, then a VStack holding the heading, description and price. The VStack carried className="w-full", and VStack's own base class is w-full too, so a bare <VStack> has the same defect.
Problem: width: 100% on a flex item resolves against the flex container's content box — it takes no account of the sibling thumbnail. The content column was therefore as wide as the whole row, and the row rendered 112px (96px thumbnail + 16px gap) wider than its card, pushing the description and the line price outside the card's right edge on a customer-facing document. The truncate on the description masked the cause rather than revealing it: the text did ellipsise, just at the overflowed boundary, so it read as "text is being cut off" instead of "the box is the wrong width". Measure el.getBoundingClientRect().right against the parent's to see it.
Rule: A flex child that should fill the remaining space gets flex-1 min-w-0, never w-full; its fixed-size siblings get shrink-0. min-w-0 is required twice over — it is what lets flex-1 shrink at all (a flex item's default min-width: auto floors it at its content width) and what lets a descendant's truncate clip at the container edge. Note @carbon/react's VStack ships w-full in its base variant, so dropping the className is not enough — pass className="flex-1 min-w-0" explicitly. Separately, truncate is inert on Heading: its base text-balance resets text-wrap-mode, so the whitespace-nowrap half of truncate never lands.
Applies to: apps/erp/app/routes/share+/{quote,supplier-quote,purchasing-rfq}.$id.tsx, apps/erp/app/modules/{sales,purchasing,invoicing}/ui/** line-item summaries and drawers, packages/react/src/VStack.tsx, packages/react/src/Heading.tsx; any flex row pairing a fixed-size element with a growing text column.
A globally-unique primary key means a fixed id literal collides across companies
Context: The onboarding demo dataset hard-coded UUID literals as externalLink.id in two places so the public share URLs (/share/quote/:id, /share/supplier-quote/:id) would be stable for documentation screenshots. Seeding the first company worked; the second one onto the same database died with duplicate key value violates unique constraint "externalLinks_pkey".
Problem: Almost every Carbon table has the composite PK ("id","companyId"), which makes a repeated id harmless across tenants — so a fixed literal looks safe by analogy. But a handful of tables are keyed on id alone: externalLink (PRIMARY KEY ("id"), 20241030005037_external-links.sql) and period (PRIMARY KEY ("id"), no companyId column at all). For those, a literal is a database-wide singleton. The failure only appears on the second company, so it passes every single-company test and first surfaces in production or in a shared dev database.
Rule: Never write a literal primary key in seed/fixture code — let the column's id()/xid() default mint it and read the value back (insertId). Before assuming a repeated id is tenant-safe, check the actual PRIMARY KEY in the migration, not the table-template convention. For a global table with no unique key to conflict against (period), a read-then-insert also needs pg_advisory_xact_lock or a unique index — two companies seeding concurrently will otherwise both insert, and the duplicates are visible to every tenant.
Applies to: packages/database/src/datasets/tiers/**; any SQL/TS fixture that writes externalLink, period, or another PRIMARY KEY ("id") table; .claude/rules/onboarding-company-templates.md.
account is scoped by companyGroupId, not companyId
Context: The dataset's accounting tier picked a GL account with SELECT id FROM account WHERE class = 'Asset' ORDER BY number LIMIT 1 and posted the seeded journal lines against it. The tiers run on a raw pg client, which bypasses RLS entirely.
Problem: account is one of the few business tables NOT keyed by companyId — it belongs to the company group, so there is no companyId predicate to add by reflex and an unscoped LIMIT 1 silently reaches across tenants. With RLS off there is nothing else stopping it, so one company's journal lines can be posted to another tenant's chart of accounts. Adding AND "companyId" = $1 would simply have failed with column "companyId" does not exist, which is what makes the omission easy to leave in.
Rule: In any service-role or Kysely path, confirm which column actually scopes the table before writing the predicate — companyId for most, companyGroupId for account and its children. A LIMIT 1 with no tenancy predicate in RLS-bypassing code is a cross-tenant bug even when it "works" locally, because a single-tenant dev database cannot show it.
Applies to: packages/database/src/datasets/tiers/09-accounting.ts; any account lookup in packages/jobs/**, apps/erp/app/modules/** postings, or a Kysely transaction.
Appending SQL to an already-applied migration silently does nothing
Context: A migration adding companySettings.requireMfa was written and applied. Later, a users_with_verified_mfa RPC was appended to that SAME file and pnpm db:migrate was re-run. The function was never created. The employees page then showed "Not set up" for every user — including one with a verified factor — because the missing RPC returned an error that the loader discarded as an empty result.
Problem: Supabase tracks applied migrations by FILENAME. Once a file has run it is never re-read, so statements appended to it are invisible on every existing database while still applying to a fresh one. The two diverge silently, and there is no error at migrate time to notice.
Rule: Never append to a migration file that may already have been applied — a file is immutable the moment it runs anywhere. New statements go in a NEW timestamped file, even a one-line CREATE OR REPLACE. Corollary: a migration that adds an RPC also needs a PostgREST schema reload (NOTIFY pgrst, 'reload schema') or the function stays invisible to the app; and a service call whose failure is indistinguishable from an empty result must check error explicitly rather than data ?? [].
Applies to: packages/database/supabase/migrations/**, any client.rpc(...) call site.
form.submit() bypasses React Router; ValidatedForm needs a real submitter
Context: @carbon/form's InputOTP auto-submits when the last digit is typed, using form.submit(). On the /mfa and /verify screens the error <Alert> reading fetcher.data could therefore never render — wrong codes produced no feedback at all. Switching to a bare form.requestSubmit() then made the form do nothing whatsoever.
Problem: Two separate traps. HTMLFormElement.submit() does not fire the submit event, so React Router never intercepts it and fetcher.data stays permanently undefined — the request goes out as a raw document POST. But requestSubmit() with NO argument leaves nativeEvent.submitter null, and ValidatedForm.handleSubmit early-returns unless submitter?.form === target — so it silently does nothing.
Rule: Programmatic submits inside a ValidatedForm must pass a submitter: form.requestSubmit(form.querySelector('button[type="submit"]')), which means the form needs a real submit button (good for accessibility anyway). Never use form.submit() in a React Router app. When a form renders errors from fetcher.data, verify the submit path actually reaches the fetcher — an unreachable error branch looks identical to "no errors happen".
Applies to: packages/form/src/components/InputOTP.tsx, packages/form/src/ValidatedForm.tsx, any auto-submitting form field.
A blanket symbol rename re-homes family-neutral code into one family
Context: Renaming the "Item Rules" feature to "Sales Rules" was done with a repo-wide ItemRule → SalesRule string sweep. It also caught ItemRuleFilter / toItemRuleFilter in packages/utils — a shared item-scoping matcher where "Item" meant the item being filtered, not the feature. The result was toSalesRuleFilter, imported by the storage evaluator, with a docstring still reading "Normalize a raw storageRule row". Nothing failed: types, tests, and lint were all green, because a wrong name is not a type error.
Problem: A string-match rename cannot distinguish "the feature named X" from "the noun X used as a domain word". Shared code is exactly where the two collide, and the damage is invisible to every automated gate — it only shows up when the next reader trusts the name.
Rule: Before a blanket rename, list the symbols that will match and check each one's consumers, not just its definition: a symbol used by more than one feature is shared and must get a family-neutral name (ItemFilter, not SalesRuleFilter), not the new feature's name. After the sweep, grep the renamed symbols inside the OTHER feature's directories — a hit there is the tell. Docstrings and comments are part of the rename: a comment that contradicts its symbol's new name is proof the rename was mechanical.
Applies to: packages/utils/src/rules.ts, packages/utils/src/rule-filters.ts, packages/ee/src/rules/**, any repo-wide identifier rename.
git add aborts the whole invocation on one unmatched pathspec
Context: Committing a spec that had been moved with git mv, the staging command listed both the old and new paths. The old path no longer existed, so git add exited with fatal: pathspec … did not match any files and staged nothing — but the following git commit still ran and produced a commit containing only the already-staged deletion. The spec was removed from the branch without its replacement, and it was pushed before anyone noticed.
Problem: git add is all-or-nothing across its arguments, and a fatal: from it does not stop a &&-free command sequence. The failure message scrolls past in a multi-command block, and git commit happily commits whatever the index already held — which after a git mv is exactly the destructive half of the change.
Rule: Never list a path that a previous step may have moved or deleted. Build the staging list from git status --porcelain output rather than typing paths, and verify the index before committing — git status --porcelain | grep -vc "^[MARD]" must be 0, or diff git diff --cached --name-only against the intended file list. Treat a commit whose file count differs from the intended change as a failed commit, not a done one.
Applies to: any commit flow following a git mv, /check-and-commit, scripted staging.
Dating a synthetic-entity journal with company_today() drops it out of the "as of" report window
Context: Intercompany elimination journals post to a synthetic "elimination entity" company (no user membership, no location). generateEliminationEntries dated them company_today(elimination_entity). Because the elimination entity has no location, company_today fell back to UTC — and on an evening-Pacific boundary UTC had already rolled to the next day. The eliminations posted on Aug 18 while the invoices they eliminate posted Aug 17. The consolidated balance sheet ("Aug 2026 to date", cutoff = today = Aug 17) then showed Inter-Company Payables/Receivables = 100 (un-eliminated), while the account drill-down ("all time") correctly netted to 0 — a confusing split where the row and its own drill-down disagree.
Problem: A consolidation adjustment must fall in the SAME reporting period/date window as the transactions it adjusts. Deriving its date from a synthetic entity's own timezone (UTC fallback) is unmoored from the operating companies' business calendar and drifts a day — or a MONTH at a month-end boundary, which would misfile the whole adjustment.
Rule: Date a derived/adjusting journal (elimination, allocation, reversal) to the business date of the source transactions it references — e.g. MAX(sourceJournal.postingDate) — not to company_today() of a synthetic or parent entity that may resolve to a different day. Date a reversal to its original journal's postingDate so the two net in one window. When a balance-sheet ROW and its drill-down "Closing" disagree, suspect an out-of-window posting date, not a summing/RLS bug. Fixed in 20260817122328_intercompany-revenue-cogs-elimination.sql.
Applies to: generateEliminationEntries and any DB function posting to isEliminationEntity companies; any consolidation/allocation/reversal journal; company_today() callers where the company may lack a location.
Consolidation eliminations must allocate per transaction, not per company pair
Context: generateEliminationEntries looped over company PAIRS (LEAST/GREATEST of the two companies), summed all intragroup revenue/COGS across the pair into one margin, and split the unrealized-profit writedown across the buyer capitalization lines proportional to captured value. A deterministic SQL test harness seeded two trades between the same pair with different margins capitalizing to different accounts (Machinery margin 40, another asset margin 10) and asserted each asset landed at its own group cost — it did not (both drifted to a proportional 75).
Problem: Pair-level aggregation preserves the TOTAL (net income and total assets stay correct) but mis-allocates the writedown ACROSS accounts when trades in the pair have different margins. Two companies trade repeatedly in a real ERP, so this is a normal case, not a corner. It was invisible in single-trade tests and only surfaced when regenerate re-matched a second trade into the same pair.
Rule: Eliminate/allocate at the grain of the TRANSACTION (the matched seller↔buyer document), not the company pair. Matching links the two sides via targetJournalLineId = the other side's sourceJournalLineId; use that to pull each trade's own revenue/COGS (seller side) and capitalization (buyer side) and write each asset down by ITS margin. Any consolidation adjustment that aggregates then re-splits proportionally is suspect — prove per-item allocation with a multi-trade, mixed-margin, mixed-account test. The harness (packages/database/supabase/tests/intercompany-elimination.test.sql) pins this.
Applies to: generateEliminationEntries; any margin/cost allocation that groups by counterparty rather than by document.
Batched PostgREST .in() with hundreds of ids blows the gateway URL limit — use Kysely for big id-list reads in edge functions
Context: Fixing the N+1 traversal in get-method's itemToJob by prefetching itemReplenishment for a whole method tree (260 item ids) with client.from(...).in("itemId", ids) chunked at 200 ids per request.
Problem: PostgREST encodes .in() filters in the query string. 200 UUID-length ids ≈ 8KB of URL, which exceeded the local gateway's request-line limit — the request failed outright, the prefetch threw, and every job created for a large-BOM item silently landed with an empty BOM (the caller logs the invoke error and continues). A chunk size that works in tests fails on the tenant with the most data.
Rule: In server functions (and edge functions), batch reads keyed by a large id list go through the Kysely db handle (bind parameters, no URL cap) whenever no PostgREST embed is needed. If an embed forces PostgREST, chunk conservatively (≤50 ids) and include res.error.message in the thrown error so the failure names its cause. Never swallow a prefetch error into a bare string with no detail.
Applies to: posting batch reads (apps/erp/app/modules/*/*.service.ts); any .in(...) over tree-collected or list-collected ids.
Kysely writes in a server function bypass RLS — every one needs an explicit companyId, even when it looks batch-scoped
Context: The batch-operations edge function's remove/update/dissolve cases updated jobOperation rows filtered only by jobOperationBatchId (from the caller's payload). requirePermissions proved the caller held production_update in their own company; the following batch-scoped update carried no companyId.
Problem: Edge functions run on the service-role Kysely handle, which bypasses RLS entirely — the app-layer permission check is the ONLY gate, and it does not scope the rows a subsequent write touches. A caller passing their own companyId (to pass the gate) plus another company's batchId (a nanoid, not enumerable, but leakable) could detach or re-point the victim's operations; the companyId-scoped batch delete right after matched 0 rows but the transaction still committed the unscoped write. A batch-id predicate is not a tenant boundary.
Rule: In a server function, EVERY Kysely read and write carries .where("companyId","=",companyId) — even ones that already filter by a scoped foreign key. Assert the row count of a batch-scoped claim (assertAllOperationsClaimed) so a concurrent or cross-tenant mismatch rolls back instead of committing a partial. And a two-phase resumable flow must re-validate membership on the resume path exactly as the first pass does — a phase-2 step that flips rows batch-wide but iterates only the payload will strand the rows the short payload omitted.
Applies to: postings in apps/erp/app/modules/*/*.service.ts (any service-role Kysely write), resumable multi-phase flows.
A tested assert* helper that is never imported is worse than none — it reads as a guard that is not there
Context: batch-time-split.ts exported assertAllOperationsClaimed (concurrent-claim race guard) and assertBatchWorkCenterMutable (completed-batch immutability guard), both unit-tested. Neither was ever imported by the batch-operations edge function — the update branch happily re-pointed a Completed batch's work center, and the claim had no IS NULL race guard.
Problem: The presence of a well-named, tested guard function signals "this invariant is enforced." A reviewer (and the author) reads the export list and assumes coverage. Dead safety helpers give false confidence precisely where the risk is highest.
Rule: Wire a safety assert* into its call site in the same change that introduces it, or don't write it yet. When reviewing, grep every exported assert*/guard for a real importer — an unused one is a finding, not dead weight to leave. Duplicated cross-runtime logic (Node + Deno copies) should re-export one source (precision.ts / batch-time-split.ts pattern) rather than rely on "keep in sync" comments.
Applies to: packages/utils/src/**, packages/database/src/**, any exported guard/assert helper.
Browser code must import @carbon/documents/utils, never @carbon/documents/pdf
Context: Adding a shared getQuoteDisplayId / getPurchaseOrderDisplayId helper for showing the revision suffix on documents. The natural home looked like the ./pdf barrel, which already re-exported it for the server-side PDF routes.
Problem: ./pdf is a barrel over every @react-pdf/renderer document component. A route loader/action can import from it safely — React Router strips server-only exports and tree-shakes the rest — but a client-rendered component cannot: the /share/** quote page and the ERP UI would pull the entire react-pdf graph into the browser bundle for a five-line string helper. The existing convention confirms this: ERP client components only ever import @carbon/documents/template, never /pdf.
Rule: Pure display helpers shared by server and browser belong in packages/documents/src/utils/ and are exposed through the ./utils export (type-only deps). Import them from @carbon/documents/utils in any component that renders in the browser. src/utils/index.ts is an explicit re-export list, not export * — the per-document util files each define their own getLineDescription, so a wildcard barrel collides.
Applies to: packages/documents/package.json exports, packages/documents/src/utils/index.ts, any @carbon/documents import inside apps/erp/app/modules/**/ui/** or apps/erp/app/routes/share+/**.
A new row reusing a readable id must qualify it — externalLink is UNIQUE per document
Context: "Create Quote Revision" failed with a generic "Failed to duplicate quote". The real error was only in the edge-runtime log: duplicate key value violates unique constraint "externalLink_documentId_documentType_unique".
Problem: externalLink is UNIQUE (documentId, documentType, companyId) (20250711000000_customer-portal-links.sql). A quote revision deliberately keeps the same readable quoteId as its source, and get-method's quoteToQuote branch inserted a share-link row keyed on that bare id — so every revision collided with the original's link and rolled back the whole copy transaction. Worse, deleteQuote deletes only the quote row (the FK points quote→link, so nothing cascades), leaving orphan link rows that re-collide when the same revision number is issued again.
Rule: Any new row that reuses an existing readable id must qualify it (Q000001-1), and any insert into a table whose unique key can be orphaned by a delete needs onConflict(...).doUpdateSet(...) rather than a bare insert. When a user-facing action reports a generic failure, read the edge-runtime container log before theorising — the route's flash message hides the Postgres error code.
Applies to: getMethod in apps/erp/app/modules/production/production.service.ts (quoteToQuote), apps/erp/app/modules/sales/sales.service.ts (deleteQuote), any insert into externalLink.
A memo's direction means OPPOSITE things on AR and AP
Context: Supplier returns settle through an AP memo. The RMA spec and
createPurchaseReturnOrderCredit both used direction: "Credit" — the same
value the (correct) customer-side credit uses.
Problem: direction alone decides the CONTROL side for both parties
(buildMemoJournal): a Credit memo CREDITS the control account, a Debit memo
DEBITS it. On AR (an asset) a credit REDUCES the balance — right for a customer
refund. On AP (a liability) a credit INCREASES it — so returning goods made
Carbon show we owed the supplier MORE, and the reason leg re-debited GR/IR
instead of clearing what the return shipment had debited, leaving a permanent
2x residual in a suspense account. Every entry still BALANCED, so no guard
fired, and it survived four review rounds. The rest of invoicing already
assumed the opposite (getAvailableCredits selects supplier memos with
direction = 'Debit'), so the memos were also invisible to "Apply Credit".
Rule: A vendor return is a Debit memo (debitMemo DR- sequence); a
customer return is a Credit memo. Never reason about direction without
naming the party — write out which way the control account moves and whether
that account is an asset or a liability. Balanced ≠ correct: when a posting has
a suspense account (GR/IR), assert the CYCLE nets to zero, not just that each
entry balances.
Applies to: apps/erp/app/modules/purchasing/purchasing.service.ts
(createPurchaseReturnOrderCredit), apps/erp/app/modules/sales/sales.service.ts
(createSalesReturnOrderCredit), apps/erp/app/modules/invoicing/invoicing.service.ts,
any new memo writer.
A bare FormLabel outside FormControl 500s the whole route
Context: The returns-module line forms (SalesReturnOrderLineForm, PurchaseReturnOrderLineForm) used <FormLabel> as a standalone section heading for the tracked-entity picker area.
Problem: FormLabel (packages/react/src/Form/FormLabel.tsx) calls useFormControlContext(), which throws outside a <FormControl>. The throw happens at render, so the route's error boundary replaces the page — the user sees "Error 500. Something broke on our end." on an otherwise-valid URL. Subtler: when the crash is below a ValidatedForm, the form unmounts, so a page can LOOK fine in a stale snapshot while its Save button is dead. The error is only visible in the browser console (useFormControlContext() must be used inside of a FormControl); the server log shows nothing useful.
Rule: FormLabel/FormError are only valid inside a <FormControl>. For a standalone section heading in a form, use a plain <label>/heading element. When a page 500s with no server error, check the browser console for context-hook throws before suspecting the loader — and treat "form renders but Save does nothing" as a possible sibling-render crash, not a submit bug.
Applies to: any usage of packages/react/src/Form/{FormLabel,FormError}.tsx; form components under apps/erp/app/modules/*/ui/.
Demo-seeded attributes can make a dead query look alive
- Context: The supplier-return entity picker filtered
trackedEntityonattributes ->> Supplier. Browser verification on the local DB showed results, so the query looked correct. - Problem: No production code ever writes a
Supplierattribute — the 49 local entities carrying it came from MCP demo seeding (Axiom/Northspoke programs). In production the picker would always be empty. Verification against hand-seeded data validated the seed, not the code. - Rule: Before anchoring a query on a
trackedEntity.attributeskey, grep for the WRITER of that key in app + edge-function code (receipt tracking writesReceipt/Receipt Line/Receipt Line Index; shipment tracking writesShipment/Shipment Line). If the only writers are tests or seeds, the key does not exist in production. Local rows proving a filter matches prove nothing about who writes the attribute. - Applies to: any
attributes ->> Xfilter on trackedEntity/trackedActivity; browser verification on a DB that has been demo-seeded.
crbn reload must load root .env — compose-substituted secrets silently reset
Context: Enabling GoTrue SAML via ${SAML_ENABLED:-false} / ${SAML_PRIVATE_KEY:-} in docker-compose.dev.yml, values kept in root .env.
Problem: crbn reload <service> invoked docker compose up -d --force-recreate with only --env-file .env.local and no dotenv preload. Root .env vars referenced by compose substitution resolved to their defaults, and — worse — recreating ANY service also reconciles other services whose definition changed, so a crbn reload kong recreated gotrue with SAML silently OFF even though the user's earlier crbn up had it on. (crbn up was immune only because it loads .env.local then .env into process.env first, and shell env wins compose interpolation.)
Rule: Any crbn command that invokes docker compose must preload BOTH env files into process.env the way up.ts does (loadDotenv(.env.local) then loadDotenv(.env), both override: false). reload.ts now does this. After any reload, still verify the dependent feature's health endpoint (e.g. curl .../sso/saml/metadata → 200), not just container status.
Applies to: packages/dev reload/compose commands; any GoTrue/Kong/storage env sourced from root .env.
An incremental pull-sweep cursor must advance on the SAME field the query filters on
Context: The Stripe Connect payment pull sweep (stripe-connect-pull-sweep.ts) queried Stripe with invoices.list({ status: "paid", created: { gte: since } }) but advanced the cursor to latest status_transitions.paid_at + 1. An invoice created before the cursor but paid after it (a normal case — invoices are created, then paid later) would never be returned by a future created-filtered query once the cursor passed its paid_at, so it was permanently skipped with no error, no log, and no retry.
Problem: The query filters on one field (created) while the cursor tracks a different field (paid_at) that moves independently of it. Any record whose "when it changed" timestamp and "when it was created" timestamp can diverge — which is true of nearly all incremental-sync designs (a row's updated_at also isn't its created_at) — silently falls outside the next window once the cursor advances past its create time but the record itself hasn't changed since.
Rule: An incremental cursor MUST advance on the exact field the list query filters on, never a related-but-different timestamp. When the two are genuinely different concerns (created vs. paid, created vs. updated), either filter on the field you actually care about, or carry a trailing lookback window (pullWindowStart re-scans since - CURSOR_LOOKBACK_SECONDS) so a bounded re-scan catches what a pure cursor would miss — cheap when the record-processing step is idempotent (here, recordStripeConnectPayment is idempotent on the Stripe invoice id via a partial unique index, so re-scanning already-recorded invoices is a free no-op). Extract cursor arithmetic into an import-light pure module (stripe-connect-pull-sweep-cursor.ts) so the regression is unit-testable without booting Stripe/Inngest/DB.
Applies to: packages/jobs/src/inngest/functions/integrations/*-pull-sweep.ts, any incremental sync reading since/cursor state against an external API's list filter.
Card lists never get their own scroll region — the page is the only scroll surface
Context: The Bill of Material / Bill of Process cards were capped at max-h-[60dvh] with an internal ScrollArea (PR #1230) so long lists wouldn't grow the page unbounded. Brad asked for the scrollbars to be removed; hiding the bar but keeping the capped region was the wrong reading.
Problem: A nested scroll region doesn't reduce scrolling — the same rows still have to be scrolled through — it just hijacks the wheel whenever the cursor crosses the card, so the user gets two scroll surfaces, scroll-trapping at the region's edges, and a janky feel. "Remove the scroll bars" meant remove the scrolling, not restyle the bar.
Rule: Card lists (BoM, BoP, and anything similar) render at natural height; the page-level container is the only scroll surface. Don't add max-h + overflow-y-auto to a card's content to tame its length — if a long list is a problem, solve it with collapse/pagination/virtualization, never a nested scroll region.
Applies to: BillOfMaterial.tsx / BillOfProcess.tsx (items), JobBillOfMaterial.tsx / JobBillOfProcess.tsx, QuoteBillOfMaterial.tsx / QuoteBillOfProcess.tsx, and any new card-embedded list in apps/erp.
A prefix short-circuit in the server entry outranks every route under it
Context: /.well-known/oauth-protected-resource and /.well-known/oauth-authorization-server each have a route, and each returned an empty 204 in production instead of its JSON. The MCP endpoint hands clients the first of those URLs in its 401 WWW-Authenticate header (api+/mcp+/_index.ts:63), so OAuth discovery for the remote connector was dead.
Problem: apps/erp/server/app.ts wrapped createRequestHandler with if (pathname.startsWith("/.well-known/")) return new Response(null, { status: 204 }) — added to keep browser probes out of the dev logs, with the comment "no app route". That was true when it was written; three .well-known routes were added later and every one of them became unreachable, because the short-circuit runs BEFORE the router.
Rule: A path check in the server entry silently outranks routing for everything under it. If you short-circuit a prefix, derive the exemptions from the build manifest (build.routes) rather than assuming the prefix stays route-free — a comment asserting "no app route" is a claim that rots the moment somebody adds one. Three false leads to skip next time this shape appears: it reproduces identically on Vercel AND react-router-serve (so it is not the platform); /.foo and /.env return normal 404s (so it is not dotfile handling); and matchRoutes against the full route table picks the RIGHT route and passes WITH the bug present (so a matcher test proves nothing). The tell was that percent-encoding the dot (/%2Ewell-known/...) returned 200 application/json — new URL().pathname leaves the escape undecoded so startsWith missed, while the router decodes and matched.
Applies to: apps/erp/server/app.ts, apps/mes/server/*, and any request-handler wrapper that inspects pathname before delegating.
A browser-safe env flag isn't live until the root loader's hand-built env also carries it
Context: The Stripe Connect integration card stayed "Coming soon" even with STRIPE_SECRET_KEY set server-side. getBrowserEnv() (packages/env/src/index.ts) already exposed STRIPE_CONNECT_ENABLED and the Window.env interface declared it, so it looked fully wired — but the browser gate window.env?.STRIPE_CONNECT_ENABLED === "true" still read undefined.
Problem: apps/erp/app/root.tsx's loader does NOT pass getBrowserEnv() through — it destructures specific keys and rebuilds an env: { ... } object by hand, and window.env is populated from THAT loader object on the normal render path (const env = loaderData?.env ?? {} → <Document env={env}>). The new flag was added to getBrowserEnv() but never added to the loader's manual list, so it was silently dropped client-side. (The ErrorBoundary path uses getBrowserEnv() directly, which masks the gap during casual reading.)
Rule: Adding a browser-safe var is THREE edits, not one: the getEnv export, getBrowserEnv() + the Window.env interface, AND the consuming app's root-loader env object (destructure + literal) for every app that needs it client-side. The loader's hand-curated env is the real source of window.env on the happy path — a key present in getBrowserEnv() but absent there is undefined in the browser. When an env-driven feature is dark despite the server value being set, diff getBrowserEnv()'s keys against the loader's env object before touching anything else.
Applies to: apps/erp/app/root.tsx (and apps/mes/app/root.tsx) loader env objects, packages/env/src/index.ts getBrowserEnv(), any window.env-gated integration/feature flag.
Secret material is read through ONE reader — never off a column
Context: After 20260817132607 moved integration tokens into the Vault, three readers kept
reading companyIntegration.metadata.access_token directly (send-slack.ts, integrations.slack.interactive.ts,
notify.ts). They did not fail — they got undefined, fell back or returned [], and Slack DMs /
slash commands silently stopped for weeks. When Slack later moved to integrationConnection
(20261026151304), the same class of miss happened again with notify.ts because the consumer map
was built from module exports, not from a grep of the column.
Rule: A credential has exactly one reader (resolveIntegrationSecrets for companyIntegration,
readConnectionAccessToken / resolveConnectionAuth for integrationConnection). Before changing
where a secret lives, grep for the column and id ("companyIntegration" + "slack",
metadata.access_token, secretRef) across apps/ and packages/, not for function names — and
make the old path fail loudly (throw) rather than return undefined.
Applies to: every companyIntegration / integrationConnection reader; any future secret move.
.po catalogs are committed only after lingui:clean
Context: pnpm run lingui:extract alone leaves #: path:line origin comments and a
POT-Creation-Date header in all 26 catalogs — 170k diff lines for ~30 real strings.
Rule: always pnpm run lingui:extract && pnpm run lingui:clean (or pnpm run translate);
the commit hook normalises, but the working tree should never carry the noise.
Kysely builds ONE column list per multi-row insert — a conditionally-set key writes NULL into its siblings
Context: get-method's quoteLineToJob builds every jobMaterial row into one array, then inserts them with a single trx.insertInto("jobMaterial").values(rows). Only rows whose item had an effective supersession successor carried a unitCost key; the rest omitted it, on the assumption that omitting a key lets the column default apply.
Problem: Kysely derives the INSERT's column list from the union of keys across ALL rows, not per row. The moment one swapped row carries unitCost, the column joins the statement and every row that omitted the key is written NULL. jobMaterial.unitCost is NOT NULL DEFAULT 0, so the whole insert failed with a 23502 and job creation died — and because it is one statement in one transaction, a single swapped line took down the entire job. The column default is only reached when NO row in the batch has the key, which is why it worked until the first quote-to-job with a superseded line. It was invisible to typecheck, to 157 unit tests, and to three review agents; it surfaced the first time a human clicked the flow in a browser.
Rule: In a multi-row insert, set every column on EVERY row or on none. Never conditionally spread a key (...(cond ? {col: v} : {})) into rows of a batch — that is the shape that writes NULL into the others. If a column is NOT NULL DEFAULT x and you want the default, either omit it from all rows or write x explicitly. When in doubt write the value explicitly; a default duplicated in code is cheaper than a constraint violation that fails the whole transaction.
Applies to: any Kysely .values([...]) over more than one row, especially jobMaterial / methodMaterial / any table with NOT NULL DEFAULT columns.
A cast to an OPTIONAL property silently yields undefined on a type that lacks it
Context: JobMaterialsTable renders an "↩ substituted from X" indicator for supersession-swapped job materials, reading the field as (row.original as { substitutedFromItemId?: string | null }).substitutedFromItemId. The row type comes from the get_job_quantity_on_hand RPC, whose RETURNS TABLE never included that column.
Problem: Asserting an OPTIONAL property onto a type that does not have it is legal TypeScript and raises nothing — the expression just evaluates to undefined on every row, so {substitutedFrom && ...} never rendered. The feature wrote correct provenance data to the database for its entire life and displayed it zero times. Had the property been declared non-optional, or read without the cast, it would have been a compile error the day it was written.
Rule: Treat as { someField?: T } on a row/DTO type as a smell, not a convenience — it is indistinguishable from a field that does not exist. When a UI needs a column its loader does not return, widen the RPC/view and regenerate types so the compiler enforces the contract. More generally: a field written to the DB but rendered nowhere has no feedback loop — jobMaterial.itemScrapPercentage was wrong in three code paths for the same reason.
Applies to: apps/erp/app/** table cells reading loader rows; any as { x?: T } over a generated DB/RPC type.
Context: Ramp integration live verification kept failing at every DB touch of the chart of accounts — post-charge 500'd, pushChartOfAccounts pushed 0, every coded card charge failed "Failed to verify accounts" (2026-08-28).
Problem: The account (chart of accounts) table is scoped by companyGroupId, not companyId — it has no companyId column and its PK is id alone (globally unique). Four separate sites wrote .from("account")….eq("companyId", companyId), which PostgREST rejects ("column companyId does not exist"). Each caller either 500'd or swallowed the error and behaved as if zero accounts existed. The bug was invisible to unit tests (they mock the data, never hit the query) and recurred because a well-meaning "add companyId scoping everywhere" self-review pass applied the standard multi-tenant pattern to a table that breaks it. Same class as item (single-column PK, globally unique).
Rule: Before scoping any query by companyId, confirm the table HAS a companyId column. Group-shared config tables — account (chart of accounts), and check others — are scoped by companyGroupId; resolve it from company.companyGroupId (or ctx.companyGroupId) and filter by that, or by id alone when the ids already come from this company's own rows. account.id is globally unique, so an .in("id", ids) lookup is correct and tenant-safe on its own.
Applies to: any .from("account") in services/edge-functions/jobs; the general check "does this table actually have companyId?" before applying the multi-tenant scoping pattern (mirror of the item single-column-PK lesson).
Context: ramp-sync's card family silently created 0 transactions every run; the error "Cannot use a pool after calling end on the pool" was swallowed by family-failure isolation (2026-08-28).
Problem: getJobDatabaseClient(size) (packages/jobs/src/db.ts) caches a Kysely client over the shared pool from getPostgresConnectionPool(size). Three accounting sweeps (accounting-outbound-sweep cron 15,45, -consolidation, -reconciliation) call getPostgresConnectionPool(5) and pool.end() it in a finally. getPostgresConnectionPool evicts an ended pool for ITS callers, but getJobDatabaseClient kept a SEPARATE client cache still wrapping the dead pool — so after any sweep ran, every later getJobDatabaseClient(5) job broke until process restart.
Rule: A cached client over a shared, end-able pool must detect the ended pool and rebuild — cache the pool alongside the client and check pool.ending (node-postgres) before returning the cached client. More generally, never pool.end() a pool obtained from a shared cache (getPostgresConnectionPool) unless every cache that wraps it also re-derives on end.
Applies to: packages/jobs/src/db.ts and any code calling pool.end() on a getPostgresConnectionPool(...) result.
A verdict computed against its own input is a tautology — diff across time, at read time
Context: PR #1477 stored a "can this backup still be restored?" verdict (compatibility.json) beside each backup, written once by the export job and never refreshed. Its badge, typed-confirm gate, and no-confirm-button state were the PR's headline UX. CI was green; ~500 lines of tests passed.
Problem: The export computed reportBackupCompatibility(catalog, manifest) where the manifest had just been PROJECTED from that same catalog, in the same process. diff(x, project(x)) is empty by construction, so the stored status was "ready" for every backup forever, and every downstream state driven by findings was unreachable. Nothing failed: the function was correct, the tests exercised it with hand-built drifted inputs, and only the one production call site was degenerate.
Rule: A comparison is only meaningful when its two sides come from different points in time or different origins. When a check's input is derived from the thing it is checked against — at the same moment, by the same code — the check can only ever pass, and green tests won't catch it because tests construct the divergent inputs the call site never produces. Compute such verdicts at READ time (live schema vs stored artifact), and when reviewing, trace where each argument of a comparison actually comes from at the real call site.
Applies to: packages/jobs/src/backups/schema.ts (reportBackupCompatibility), getCompanyBackups in apps/erp/app/modules/settings/settings.service.ts, and any future "is X still valid?" precomputation (schema drift, config validation, cache-freshness verdicts).
Bare-tsx scripts: isolate the import chain, never flip a shared package's type
Context: pnpm db:check:backups (packages/jobs/src/scripts/check-backups.ts) runs under bare tsx, which cannot named-import a CJS workspace package at runtime. Its import of company-backup.ts pulled in @carbon/logger via a module-scope getLogger, and the branch "fixed" the resulting crash by adding "type": "module" to packages/logger/package.json — a module-system change to a package consumed by 13 others, made for one dev script.
Problem: Flipping a shared package's type field changes resolution for every consumer to satisfy one entrypoint, and the connection between the flip and its reason is invisible — the next person hitting the same error flips the next package. The actual dependency was incidental: the script needed six pure functions that sat in a file whose module scope also called the logger.
Rule: When a bare-tsx (or plain-node) script hits does not provide an export named …, fix the SCRIPT's runtime import chain: move the pure logic it needs into a module with no runtime @carbon/* imports (type-only imports are fine — they erase) and import that. packages/jobs/src/backups/schema.ts is the pattern; packages/database's seed scripts (relative .ts imports only) are the older precedent. Never change a shared package's type/exports for one script's benefit.
Applies to: packages/jobs/src/scripts/**, packages/database/src/{seed,check}-*.ts, ci/src/**, and any new tsx-run script in a CJS-rooted package.
Compare OAuth scopes the way the vendor REPORTS them, not the way you asked
Context: The Gmail allowlist row requested ["…/auth/gmail.send", "email"], the spelling
the Activepieces piece uses. Google's token response came back with
openid …/auth/gmail.send …/auth/userinfo.email — the alias canonicalised, an unrequested
openid added. missingScopes(granted, required) reported email missing and the account
showed "Reconnect needed" the second it connected. Google Calendar's piece has the same alias
and was never caught only because its first connections predate scope recording.
Rule: Every scope in an allowlist row (and anything else that feeds requiredScopesFor)
is spelled exactly as the vendor echoes it in the token response — for Google the full
https://www.googleapis.com/auth/… URL. When a piece's own list uses an alias, override
oauth.scope with the canonical form (same set of permissions). oauth.test.ts refuses
email / profile / openid on any row. When a "reconnect needed" appears on a freshly
connected account, diff metadata.scopes against requiredScopesFor before anything else.
Applies to: packages/jobs/src/workflows/integrations/allowlist.ts oauth.scope,
packages/ee/src/integrations/connections.ts missingScopes, any future vendor whose token
response normalises scope names (Microsoft returns short names for Graph scopes too).
CREATE OR REPLACE VIEW cannot reorder columns — DROP + CREATE when t.* grows
Context: The work-center batch-capacity migration added batchCapacity/minimumBatchQuantity to workCenter and re-declared the workCenters view (which selects wc.* before aliased join columns like locationName) with CREATE OR REPLACE VIEW.
Problem: CREATE OR REPLACE VIEW can only APPEND columns at the end — the new wc.* columns expand in the middle, shifting locationName to a new position, and Postgres refuses with cannot change name of view column "locationName" to "batchCapacity". The migration fails at apply time even though the SQL looks like a routine re-declare.
Rule: When a view selects t.* and the underlying table gains columns that land BEFORE any explicitly-aliased column, re-declare with DROP VIEW IF EXISTS + CREATE VIEW (checking dependent views first) — not CREATE OR REPLACE. Only a pure append at the end of the select list is REPLACE-safe.
Applies to: every packages/database/supabase/migrations/*.sql that re-declares a SELECT t.*, … view after an ALTER TABLE … ADD COLUMN (workCenters, processes, jobs, and siblings).
Single-column FKs on multi-tenant children accept cross-tenant ids
Context: jobOperationBatch shipped with locationId/processId/workCenterId FKs referencing only the parent's id. The batch-operations edge fn wrote payload.locationId/workCenterId straight into the row after requirePermissions — which authorizes the CALLER for a company, not the record ids in the body.
Problem: A single-column FK checks only that the id EXISTS, so a company-A row pointing at company-B's location/work center satisfies it, and a service-role edge fn bypasses RLS — the write lands, mis-filing the batch and stamping foreign work centers onto job operations. Nothing fails until an export or a human notices.
Rule: In a server function, re-read every payload record id under companyId and refuse on a miss (assertCompanyRecords, apps/erp/app/modules/shared/shared.service.ts). Structurally, make tenant-scoped FKs composite — (<col>, "companyId") REFERENCES parent(id, "companyId") — adding UNIQUE (id, "companyId") on parents whose PK is single-column, and using PG15 ON DELETE SET NULL (<col>) for nullable FKs so companyId survives. Precedents: 20260703143904_composite-tenant-fks.sql, 20260901132702_batch-composite-tenant-fks.sql.
Applies to: postings (apps/erp/app/modules/*/*.service.ts) taking record ids in the input; any migration adding an FK from a companyId-scoped table to another tenant-scoped parent.
A "did my job finish?" baseline must include the rows a FAILED run left behind
Context: The Backups page shows a spinner row while an export runs, and decides the
run finished when a backup appears in the list that was not in a baseline snapshot
taken when tracking began. The baseline recorded only backups with status ready.
Problem: A failed export leaves a pending (manifest-less) folder in the list.
When the user clicked "Skip corrupted rows and retry", that leftover folder later
flipped to ready — it was not in the ready-only baseline, so it read as "this run
completed" and the spinner vanished a second after the retry started, while the job was
still running. The job was correct throughout; only the completion test was wrong. The
same shape bit the failure banner: a marker cleared by the action could still arrive via
a revalidation already in flight, so the banner reappeared under the running row.
Rule: A baseline for "something NEW appeared" must snapshot every item already present, in every status — not just the ones in the terminal state you are waiting for. A prior failure's debris is exactly what will later transition into that state and fake a completion. And when a stale record can still arrive after you delete it, identify it by identity (the exact row you superseded), never by comparing a client timestamp against a server one — clock skew then decides your control flow.
Applies to: apps/erp/app/routes/x+/settings+/backups.tsx (runningExport,
knownBackupNames, failedIsStale), and any optimistic progress row driven by polling
a list.
Per-edge findings are not a row count
Context: findExportScopeViolations returns one entry per offending FK edge
(jobOperationDependency violates jobId, operationId and dependsOnId), and the
backup UI summed violations[].rows for the figure it showed the user.
Problem: A row escaping scope through three foreign keys was counted three times. The failed-backup banner claimed "10 rows" where 4 rows existed, and the same sum sat on the confirm button of an irreversible delete that then removed 4 — the toast and the modal disagreed inside one flow.
Rule: When a diagnostic groups by RELATIONSHIP (FK edge, constraint, rule), it
cannot be summed into a count of ROWS. Compute the distinct count separately — one
count(*) over the OR of the offending predicates — and keep the per-edge list purely
as the breakdown. Name the two so they cannot be confused (violations vs
rowsByTable) and say so in the type's doc comment.
Applies to: packages/jobs/src/backups/scope.ts
(findExportScopeViolationsDetailed, computeScopeExclusions, totalExcludedRows),
Manifest.excludedRowsByTable, and any future "N things are wrong" surface.
Browser-testing MES flows that write data
- Context: Verifying AssemblyView keyboard shortcuts with agent-browser while editing the same file (Vite HMR live).
- Problem: Step records appeared at timestamps with no corresponding keypress; hours went into suspecting the new code. Cause: overlapping test sessions — a page left open across HMR edits (sometimes with a modal up) replays/refires interactions, and interleaved key presses land on freshly auto-advanced steps.
- Rule: When a browser test writes rows, run it as a closed loop: wipe the rows, reload the page fresh, then check the DB after EVERY single action before pressing the next key. Never diagnose from an accumulated tail of prior test sessions.
- Applies to: agent-browser verification of any MES/ERP flow with side effects, especially while HMR is live.
Full-screen height calcs must subtract the app-shell inset
Context: The ERP app shell (apps/erp/app/routes/x+/_layout.tsx, PR #1551) moved
content into an inset floating panel with md:mt-2 md:mb-2 (8px top + 8px bottom
gutters). ~81 full-screen pages/explorers sized themselves with
calc(100dvh - var(--topbar-height) [- var(--header-height)]), which assumes the
content spans the full viewport.
Problem: Those containers are 16px taller than the panel at md+, so bottom-pinned content is pushed below the panel's clipped edge. The Procedures "Add Step" footer was sheared in half; the overflow was invisible on pages whose content merely scrolls.
Rule: vh/dvh ignore the panel inset by nature, so any full-height calc inside the
content panel must subtract var(--content-inset) (defined in styles/tailwind.css: 0
below md, 1rem at md+), e.g. h-[calc(100dvh-var(--topbar-height)-var(--content-inset))].
Prefer h-full/flex height inheritance from <main> for new pages so the inset never
has to be tracked by hand. Do NOT add the inset to viewport-fixed/body-portaled elements
(dialogs, drawers) or to PrimaryNavigation, which live outside the panel.
Applies to: every calc(100dvh-var(--topbar-height)...) in apps/erp/app, the shared
components/Layout/Panels.tsx + Navigation/CollapsibleSidebar.tsx, and any new
full-screen ERP route.
The backups schema baseline on main can carry phantom tables from a dirty local DB
Context: pnpm db:check:backups blocked the currency-refactor commit on onshapeSyncRun/onshapeItemSyncState — tables with NO migration anywhere in the repo.
Problem: packages/jobs/manifests/schema.json regenerates from the committing developer's LIVE schema. If that database has tables applied from an unmerged branch, they enter the committed baseline, and every later committer's check flags them as "dropped without a rename mapping" — a false alarm that invites --no-verify reflexes or, worse, bogus TABLE_RENAMES: null entries declaring never-shipped tables dropped.
Rule: When db:check:backups blocks on a missing table, first verify the table exists in ANY migration (grep -r <table> packages/database/supabase/migrations/). No migration ⇒ baseline pollution, not your break: regenerate schema.json from a clean fully-migrated database (the catalog code in src/backups/schema.ts + the manifest shape in check-backups.ts), commit it with CARBON_SKIP_BACKUP_CHECK=1, and say why in the commit message. Never add a rename entry for a table that never shipped.
Applies to: packages/jobs/manifests/schema.json, packages/jobs/src/scripts/check-backups.ts, .husky/pre-commit.
Adding CHECK + VALIDATE requires auditing every WRITER of the column and pre-cleaning data in the same migration
Context: The currency refactor added CHECK ("exchangeRate" > 0) + VALIDATE on 12 document tables. Review found get-method had been writing exchangeRate: l.exchangeRate ?? 0 into quoteLinePrice for every legacy null-rate quote line, and the old NUMERIC(10,4) clamp had stored sub-0.00005 rates as literal 0.0000.
Problem: VALIDATE CONSTRAINT scans existing rows mid-deploy — one violating row anywhere fails the whole migration in production, and post-deploy the unfixed writer fails at runtime (a whole edge-function transaction). A constraint that is obviously true "going forward" says nothing about years of rows written by code paths you didn't grep.
Rule: Before adding a CHECK on an existing column: (1) grep EVERY writer of that column — app services, edge functions, triggers, seeds — and fix any that can produce a violating value in the same change set; (2) repair existing violating rows in the same migration, before the VALIDATE (UPDATE … WHERE <violates> with an explainable value); (3) remember old NUMERIC(p,s) clamps — a widened column can still hold rounded-to-zero values from its clamped era.
Applies to: any ADD CONSTRAINT … CHECK + VALIDATE migration; posting writers (apps/erp/app/modules/*/*.service.ts) of the constrained column.
A reservation class that must outlive job status needs an explicit escape in EVERY snapshot filter
Context: Batch release schedules a Released operation batch as one coalesced capacityReservation anchored (for the NOT NULL jobId/operationId) on an arbitrary member — whose job may legitimately still be Draft (membership handoff pulls members ahead of their jobs).
Problem: getLiveReservations quietly filters j."status" IN capacityHoldingJobStatuses at the END of the query builder — separate from the excludeJobIds filter that had already been made batch-aware. The batch row vanished from every snapshot whenever its anchor job was unreleased: the machine looked free and every other job over-booked straight through the batch window.
Rule: When a reservation (or any capacity-holding row) must survive independently of its anchor row's status, grep EVERY filter in the read path — not just the one you were pointed at — and give each an explicit escape (OR "jobOperationBatchId" IS NOT NULL). A snapshot read with two filters a hundred lines apart is two bugs, not one.
Applies to: packages/ee/src/planning/scheduling/master-data-provider.ts getLiveReservations, any future scenario/what-if reservation reads, and generally any row whose lifecycle is owned by a different entity than its FK anchor.
A degenerate-input guard on a scheduling surface is a silent-vanish bug, not defensive coding
Context: The batch pre-pass had if (durationSeconds <= 0) continue; — a released batch whose member operations all carry zero setup/labor/machine time (routinely true for freshly-authored routings) was skipped entirely: no reservation, no auto work-center selection, nothing on the reservation-driven Forecast. The user released BAT000005 and it simply didn't exist anywhere schedule-shaped, indistinguishable from the (separate) dead-Inngest failure being debugged at the same time.
Problem: Zero/empty/unsized work still EXISTS. On surfaces whose only rendering source is a derived row (the Forecast draws capacityReservation rows and nothing else), a "skip nonsense input" guard doesn't degrade gracefully — it erases the entity, and the erasure reads as any of five other failures (event bus down, filter bug, RLS, wrong week, stale registration).
Rule: In the scheduling engine, degenerate input never continues past a persistence step — it emits the flagged placeholder shape (isPlaceholder = true, honest workHours, a conflictReason naming the DATA gap and its fix) so the entity stays visible and self-diagnosing. Match the unplaceable-op precedent; give the placeholder a nominal drawable window when true content is zero.
Applies to: packages/ee/src/planning/scheduling/batch-scheduler.ts, work-center-selector.ts placeholder branches, and any future pre-pass/what-if that turns entities into reservations or timeline rows.
A shared executor acquires callers nobody planned for — grep every importer before deleting one
Context: The oRPC migration plan said MCP call_tool and the in-app agent were the two consumers of the MCP direct-executor.ts, so once both moved to callOperation the file could be deleted. A pre-deletion grep found a THIRD caller: apps/erp/app/routes/api+/inngest.ts registered executeFunction as the workflow engine's setWorkflowDispatch seam — every customer workflow *.create action ran through it.
Problem: A convenient shared function gets wired into new seams (dependency-injection slots, dispatchers, adapters) without its own file ever changing, so the mental list of "who uses this" goes stale. Deleting it on the strength of the plan's caller list would have broken customer workflow create actions in production while every named caller kept working.
Rule: Before deleting or changing the contract of any shared executor/service entry point, grep the WHOLE repo for its name (not just imports of its file — injection sites pass it by value: setX(fn), register(fn), config objects), and treat each hit as a caller to migrate in the same change. A DI/seam registration is a caller even though the dependency arrow points away from the file.
Applies to: apps/erp/app/routes/api+/v1+/lib/call.server.ts (the shared entry point now), packages/jobs/src/workflows/actions/dispatcher.ts, any set*/register* seam.
In a bulk API sweep, a 4xx carrying a service's generic fallback string is a finding, not a pass
Context: The 1,495-operation API sweep triaged all 274 WRITE-op 400s as "reached the DB, expected FK rejections" and flagged only 500s. inventory_insertManualInventoryAdjustment came back 400 with "Failed to create manual inventory adjustment" and was waved through — but that string is the service's FALLBACK for an edge-function error whose real message was suppressed. A customer later hit exactly this: the published schema advertised 12 adjustmentType values (the validator spread itemLedgerTypes into its enum) while the post-inventory-adjustment edge function accepts 5, so every LLM-guided "add stock" call failed undiagnosably.
Problem: Bucketing sweep results by status code alone treats "the request was validly rejected" and "the error was swallowed somewhere in the chain" as the same outcome. The ops most likely to be broken-by-contract-drift are precisely the ones that fail with a generic message, because the generic message IS the symptom of a suppressed real error.
Rule: When triaging sweep failures, grep the response bodies for known fallback strings ("Failed to *" service fallbacks, getErrorMessage fallback arguments) and treat each match as a defect to root-cause: either the advertised schema disagrees with the actual acceptor (enum/shape drift between a .models.ts validator and a server function's input schema), or an error-sanitization layer is eating a legible message. Published-schema enums must be exactly what the write path accepts — never a wider "domain" enum reused for convenience.
Applies to: API/MCP sweep scripts, apps/erp/app/modules/*/[a-z]*.models.ts validators that feed posting wrappers, packages/api/src/errors.ts, packages/utils/src/errors.ts.
A creation-time swap must be keyed by its provenance column at every later lookup
Context: Supersession swaps a jobMaterial to its successor when the job is created (substitutedFromItemId records the predecessor). Picking then looked up itemSupersession by jobMaterial.itemId — which is now the successor, which has no row — so resolvePickTarget returned "pick the item unchanged" and Consume First never consumed the predecessor's stock. The picking-side branch was dead code for every job created after the effectivity date, and the unit tests (which passed a material still on the predecessor) could not see it.
Problem: The rule lives on the OLD item; the row already names the NEW one. Any later stage that re-reads the rule by the row's current item silently finds nothing, and "no rule" is a valid, quiet outcome.
Rule: When a row is rewritten by a rule and carries a provenance column (substitutedFromItemId, redirectedFromItemId, …), every downstream lookup of that rule must key on COALESCE(provenance, current), in BOTH the TS and SQL mirrors. Test the swapped shape explicitly — a fixture that stops at "rule set, nothing swapped yet" proves nothing about what happens after the swap.
Applies to: apps/erp/app/modules/inventory/supersession-pick.ts / generatePickingList, get_picking_schedule, packages/ee/src/planning/mrp/mrp.ts (redirected BOM children), any consumer of jobMaterial.substitutedFromItemId.
A post-insert fix-up pass must be scoped to the rows the flow inserted, not to the parent entity
Context: pullConsumeFirstPredecessors in get-method ran after every jobMaterial insert and read WHERE jobId = …. Three of the four flows rebuild the whole job, so that read was equivalent — but itemToJobMakeMethod rebuilds ONE sub-method, and the pass rewrote lines on every other sub-method too, including rows that already had issued quantity in the successor's units.
Problem: A pass keyed on the parent id is correct for the flow it was written next to and silently over-broad for any flow that rebuilds a subset. Nothing fails: the rewritten row has plausible numbers and a plausible provenance column, and only the units disagree with what was already issued.
Rule: A fix-up pass that runs after inserts takes the inserted row ids (collect them at every insert site of every flow) and filters on them, plus a guard on any state that means "this row's units are already committed" (quantityIssued > 0). Never derive the candidate set from the parent entity when some caller rebuilds only part of it.
Applies to: getMethod (apps/erp/app/modules/production/production.service.ts) post-insert passes, any future "after all rows are in, patch some" step in the four job flows.
A provenance column that records both directions of a swap cannot be trusted first
Context: jobMaterial.substitutedFromItemId holds the predecessor on a line swapped forward at creation, and the SUCCESSOR on a line pulled back onto a stocked predecessor. Picking looked the rule up on that column first — correct for the forward case, and when the successor had a rule of its own (NEW → NEWER) the pulled-back line resolved NEW's rule, the roles inverted, and the pick went back to NEW.
Problem: "Column set ⇒ rule lives there" was true until the second writer appeared. The only thing that distinguishes the two shapes is the relation between the row's own item and the column: on a pulled-back line, the row's own rule NAMES the column as its successor.
Rule: When a provenance column can be written by more than one direction of a swap, resolve by relation, not by presence: prefer the row's own rule when it points at the column; only then fall back to the column's rule. Mirror the precedence in every SQL twin (ORDER BY (own AND successor = column) IS TRUE DESC, …). Or give the two directions distinct columns.
Applies to: apps/erp/app/modules/inventory/supersession-pick.ts (resolvePickRule), get_picking_schedule, any reader of substitutedFromItemId / redirectedFromItemId.
Consume First splits are per assembly, not per unit (2026-09-15)
- Context: the Consume First partial-stock split picked the predecessor for every unit the warehouse had and the successor for the rest.
- Problem: with 2 per assembly and 3 on the shelf that put one old and one new part on the same unit. A customer would rather leave the odd part in stock than fit a mismatched pair; units of a batch may differ, one unit never.
- Rule: round a predecessor's usable on-hand DOWN to a multiple of the
line's per-assembly quantity (
consumableInWholeAssemblies) everywhere the split is computed — job creation, picking, the SQL schedule, the job materials note, Order Status, the planning list, MRP. A quantity rule that lives in seven places needs one helper, or the sites drift. - Applies to: any allocation of a per-unit component across a batch.
Consume First is one rule for bought and made parts (2026-09-16)
- Context: the Consume First stock-netting was written for bought parts
only. A made predecessor always swapped to its successor — at job creation
(
loadSupersessionRedirect's Make exclusion) and in MRP (full BOM swap) — because the post-explosion pass that moved the bought shortfall could not explode a made successor's BOM. - Problem: stocked old sub-assemblies were never used: a job named the new bracket while old brackets sat on the shelf, and planning bought the new bracket's ingredients for the whole quantity. The two "made" special cases were a workaround for where the netting lived, not a product decision.
- Rule: put the netting where the successor can still be planned as
itself. In MRP that is INSIDE
explodeBom(consumeFirstRedirect): the old part nets its running balance and moves the shortfall to the successor, which then explodes or buys at a deeper level (a synthetic leveling edge keeps it below the predecessor). In job creation the per-line settle pass is the authority for every Pull from Inventory line, and the item-level filter is provisional. When a rule has a replenishment-specific exception, ask whether the exception is a product decision or an artefact of where the code sits. - Applies to:
lib/mrp-engine.ts,packages/ee/src/planning/mrp/mrp.ts,get-methodsettleConsumeFirstLines/loadSupersessionRedirect.
A Make to Order line is never picked, and never split for Consume First (2026-09-16)
- Context: a Consume First sub-assembly on a Make to Order BOM line, three old on the shelf, five needed. The job swapped the line to the successor and built five (Plate B 5), and the picking list ALSO staged three old and two new from the shelf for the parent operation.
- Problem: two bugs stacked.
get_picking_schedulenever excluded Make to Order lines, and since unassigned materials are attributed to the first operation every Make to Order sub-assembly got a phantom pick that nothing consumes (issue's backflush skips Make to Order). And the made-line rule "always swap" meant stocked old sub-assemblies were never used. The obvious fix — split the line into "pick 3 old" + "build 2 new" — dies at the nextrecalculate, which rebuilds every line as per-assembly × parent quantity. - Rule: a Make to Order line follows the bought Consume First rule by
CHANGING METHOD TYPE, not by splitting: when the predecessor covers one whole
assembly it becomes a Pull from Inventory line on the predecessor (decided in
the row builder, before insert, so no sub-method row is ever created), and
picking splits per unit as for any picked line; otherwise it swaps and is
built. Picking excludes Make to Order lines everywhere (SQL + TS). When a
fix needs two rows where the BOM has one, check what
recalculatewill do to them before writing it. - Applies to:
get-methodrow builders (itemToJob,itemToJobMakeMethod),generatePickingList,get_picking_schedule,lib/job-quantities-engine.ts.
A helper that models a chain must be tested with a loop (2026-09-16)
- Context:
buildConsumeFirstHopswalked one Consume First hop at a time and guarded against loops only while collapsing through non-Consume-First hops. A two-item Consume First loop passed straight through, and in the engine both items would sit on one cycle level and hand demand to an item already planned — silently lost. - Problem: the guard was written for the path being walked, not for the property that matters ("does this chain terminate?"), and the first test I wrote for it was the one that caught it.
- Rule: any function that follows successor / parent / next pointers gets a cycle test of the smallest loop (two nodes) before anything else, and the guard checks termination of the WHOLE chain, not just the part the function happens to traverse.
- Applies to:
lib/supersession-pick.tschain builders, BOM walkers, anything keyed onsuccessorItemIdorparentMaterialId.
Two readers of the same shelf must share one definition (2026-09-16)
- Context: the pick-list generator credited lineside material with an all-or-nothing on-hand check per item, the schedule SQL did its own version, and consumption followed pick lines only. A job whose two assemblies' parts were already at the work centre (one pair picked on a since-cancelled list, one produced by a sub-job straight into the bin) got a list for four more, and would have consumed the wrong part from the wrong bin.
- Problem: three code paths each answered "what is at the machine for this job?" with a different formula, and none of them was wrong in isolation. The trial found it in minutes because real shop floors leave material at the machine in every way except a clean pick.
- Rule: when picking, scheduling and consumption all read the same bin,
write the definition ONCE as a pure function (
linesideCredit), mirror it in SQL under the same name (get_lineside_credit), and make every reader call it. Then enumerate the ways stock reaches a bin — pick, cancelled pick, sub-job output, manual transfer, return — and test each against the definition before calling the feature done. - Applies to:
generatePickingList,get_picking_schedule,getPickedBudgets/issue,post-picking.
Resolve adoption assumptions before designing accounting migration machinery
Context: The accounting posting-corrections spec raised legacy open-balance migration concerns; the user clarified that accounting can be assumed unused.
Problem: Designing calculation versions, correction journals, and cutover tooling before resolving adoption added unnecessary scope to a correctness fix.
Rule: Use the user's explicit adoption premise to size compatibility work. For this spec, correct the monetary contract directly; do not add legacy-accounting machinery. An unused accounting module does not imply permission to delete operational records or reset a database.
Applies to: .ai/specs/2026-09-07-accounting-posting-corrections.md and its implementation; other modules require their own adoption evidence.
Accounting review: carrying balances and source principal
- Context: Mixed positive and negative invoice lines, high FX rates, and changes to account defaults during settlement and provider replay.
- Problem: Summing control magnitudes invented FX; recovering document units from rounded base lost valid minor-unit balances; current defaults rewrote original account provenance.
- Rule: Sum signed original control amounts, preserve exact document principal independently of carrying base, and identify original journal roles through the shared exhaustive vocabulary (including intercompany roles). Reject unknown effective principal rather than infer it; retain Draft reservation policy separately from Posted effectiveness.
- Applies to: Invoice/payment/memo posting, open-balance readers, and accounting provider replay.
Apportion a document total, never concentrate its rounding residual
Context: Sales invoices push to QuickBooks/Xero/Rillet as components (merchandise, add-ons, line shipping, header shipping), each rounded at the document currency's precision, and the sum must equal the authoritative document total.
Problem: Rounding N components independently leaves a residual of up to N/2 minor units. Assigning that whole residual to one component broke that component's own percent/amount pair — a 20 x $1.99 @ 8.25% invoice gave one line $0.24 tax on $1.99 net (12.06% against a stated 8.25%). QuickBooks re-derives round(net x percent) within one minor unit and refused the invoice with UNMAPPED_TAX_CODES, a message blaming the customer's QuickBooks configuration, which they cannot act on. A randomised sweep put this at 1.6% of invoices; some cases produced a negative tax on positive revenue, which Xero accepts and posts.
Rule: Use distributeRoundingResidual (@carbon/utils) whenever a total is apportioned across parts — largest remainder, at most one minor unit moved per part. Never hand-roll "assign the difference to the biggest line". Order the parts by a stable business key (component id) before distributing, because the distributor's own tie-break is positional and the same invoice must allocate identically whatever order its lines arrive in. Where a derived value must reproduce the reconciled amount (a unit price times its quantity), derive it and then VERIFY — refuse when no representable value works, rather than emitting an inconsistent one.
Applies to: packages/ee/src/accounting/core/sales-document-components.ts, packages/database/src/sales-posting-amounts.ts, packages/ee/src/accounting/core/document-costing.ts, Ramp card/repayment allocation, and any future provider document mapper.
Two halves of an intercompany trade must round at the same scale
Context: post-sales-invoice and post-purchase-invoice each write an intercompanyTransaction row, and generate_intercompany_matches pairs them with src."amount" = tgt."amount" — exact NUMERIC equality, no tolerance.
Problem: The seller began rounding its half at the document currency's settlement precision (2dp) while the buyer kept internal SCALE (5dp). A trade of 3 x 100.005 stored 300.02 against 300.015, so the pair sat Unmatched forever and eliminations silently never ran — consolidated income kept the intragroup profit, with no error anywhere.
Rule: An amount used as a MATCHING KEY is not a settlement amount. Round both halves at internal SCALE. Before changing rounding anywhere, check whether the value is compared for equality by something else — a matcher, a tie-out, or a reconciliation — and change both sides together.
Applies to: calculateSalesIntercompanyAmount, post-purchase-invoice's IC amount, generate_intercompany_matches.
Prove provider accounting against its independent journal
Context: The live Rillet E2E run accepted invoice payloads while ignoring their FX override and crediting deferred revenue.
Problem: Request shape and HTTP success did not prove economic parity. AR_ONLY used provider FX; the supported REVENUE_RECOGNITION_ONLY scope accepted fixed document-to-base rates and same-day recognition.
Rule: Verify returned account effects in the provider's independent GL, including recognition and voids. Treat Carbon's rate as document units per base unit, invert it for Rillet, and align recognition and FX dates with Carbon's posting date. Check voided mappings before create-idempotency shortcuts and retain durable deletion markers.
Applies to: Rillet invoice/bill/payment adapters, native-void reconciliation, and future provider acceptance tests.
Seed UI-only controlled fields through the form defaults
Context: Payment type choices combine counterparty and cash direction while the persisted paymentType remains Receipt or Disbursement.
Problem: Passing only SelectControlled.value left the initial registered paymentKind empty in the real browser; unit mocks did not model form initialization. A composer also retained old targets after a saved header identity changed.
Rule: Include a UI-only field's initial value in ValidatedForm defaults, and key stateful composers by the document/party/currency/direction identity whose data they hold. Verify the initial label and actual submitted fields in the browser.
Applies to: PaymentForm, PaymentApplyTable, and other forms using derived presentation choices.
A generated column is writable in the Supabase Insert type but rejected at runtime
Context: The Ramp inbound bill/reimbursement sync inserted purchaseInvoiceLine rows with unitPrice: line.amount and exchangeRate: 1. Since 20260811123616, purchaseInvoiceLine.unitPrice/totalAmount/shippingCost/taxAmount are GENERATED ALWAYS AS (supplier* / exchangeRate) STORED — base-currency mirrors of the document-currency supplier* columns.
Problem: supabase gen types lists STORED generated columns in the Insert/Update types as optional, so unitPrice: line.amount typechecks — but Postgres rejects a non-DEFAULT write to a generated column at runtime, and the value never reaches supplierUnitPrice, so post-purchase-invoice (which posts quantity * unitPrice, unitPrice already base) had nothing to post. The path also hardcoded exchangeRate: 1, so even when it did post, a foreign-currency bill posted at par. Both are invisible to typecheck and to unit tests that mock the insert.
Rule: Write purchase amounts to the supplier* document-currency columns (supplierUnitPrice, supplierShippingCost, supplierTaxAmount) plus the real exchangeRate (foreign-per-base, from get_exchange_rate); never write the generated unprefixed unitPrice/totalAmount/shippingCost/taxAmount. A column being present in the generated Insert type is NOT proof it is writable — check the migration for GENERATED ALWAYS. The generated base column then derives correctly and posts in base currency.
Applies to: any code inserting purchaseInvoiceLine / purchaseOrderLine / supplierQuoteLinePrice rows (Ramp syncBill/reimbursement path, CSV import, AI extraction), and the general "is this Insert-typed column actually generated?" check before writing a value-bearing purchase column.
A Ramp custom accounting field is typed OTHER — match it by external id, never by the type enum
Context: Carbon pushes cost centers to Ramp as a custom SINGLE_CHOICE accounting field (POST /accounting/fields, id: "carbon-cost-center") so a card holder can tag a charge with a project. The read-back in ramp-sync matched a selection's category_info.type === "COST_CENTER" to recover the cost center.
Problem: The custom-field create body has no type property, so Ramp reports its selections as OTHER; COST_CENTER is Ramp's native enum for its own cost-center concept. The match never fired, costCenterId stayed null, and every project tag was silently dropped — while the GL-account leg (a native GL_ACCOUNT field) worked, so the sandbox verification of "a coded transaction" proved nothing about the custom field. Three more breaks hid behind it: the push sent external_id where Ramp wants id (and the string id as field_id, which wants the ramp_id UUID), POST /field-options is all-or-nothing and rejects existing options so every second converge threw into a swallowed catch, and the posting function needs a CostCenter dimension row that nothing seeds for company groups created after the 20260228024512 backfill.
Rule: Identify a custom Ramp field by category_info.external_id (the id Carbon created it with), and keep that constant in one pure, unit-tested module (packages/ee/src/ramp/lib/coding.ts). Treat every Carbon → Ramp push as a converge (list, diff by fingerprint, create/PATCH/hide) and verify the inbound leg of a custom field on the sandbox separately from the native GL account. A tag the customer typed must fail loudly if it cannot be kept — never post a balanced journal that lost it.
Applies to: pushCostCenters / pushChartOfAccounts and any future Ramp coding field (departments, locations); codeSelections; post-charge's dimension write; and, generally, any integration where a provider echoes an ERP-created object under a different classification than the ERP's own.
A per-row document representation must be decided in ONE place the policy and the syncer both read
Context: Card charges became provider objects, but only some rows of the same journal source type qualify (a Charge with a supplier; a Credit only where the provider has a refund object; never a statement Payment/Cashback/Repayment). The journal policy decides DOC_BACKED per journal; the charge syncer decides shouldSync per document.
Problem: If the two rules drift — the policy excludes the journal but the syncer skips the charge (no supplier, unsupported Credit), or the reverse — the spend reaches the provider as both a journal entry and a charge, or as neither. Neither failure is loud: DOC_BACKED is a terminal "handled" disposition and a syncer skip is a benign reason string.
Rule: Put the eligibility rule in one pure function (isDocBackedCharge(row, docSync)) with explicit inputs (type, hasSupplier, provider capability set CHARGE_CREDIT_PROVIDERS), have the executor/planner resolve those inputs with one query per batch, and make every adapter's shouldSync restate the same conditions with the same constants. Pin both sides in tests (posting-policy.test.ts, the adapter's mapper tests, reconcile-golden).
Applies to: any future "document instead of journal" family whose eligibility depends on the row rather than the source type (returns, memos, per-provider capabilities).
A live sandbox pass finds what unit tests cannot: the wire contract
Context: The Ramp Part C run (2026-09-10) on a fresh worktree DB against the demo sandbox, after Parts A/B were unit-tested and typecheck-clean.
Problem: Three things only the real API surfaced: (1) the batch account push sent a new Carbon-side visible flag inside the POST items → Ramp 422 "Unknown field" failed the whole chart push; (2) every sync confirm had been failing for weeks — successful_syncs/failed_syncs have minItems: 1 (an empty [] is a 422) and a failed item is { id, error: { message } } — and the failure was only console.error'd, so Ramp kept every synced transaction SYNC_READY; (3) ensureRampConnection only creates, so a fresh DB against a business that already has a Carbon connection cannot install.
Rule: Keep wire payloads behind pure, exported builders (toRampGlAccountPayload, buildSyncConfirmBody) with tests pinning the exact shape, never spread an internal object onto a request; put every caught provider error on the Inngest step OUTPUT (error / confirmError), not just the console — the run record is the only thing an operator can read; and when a verification note says "pushed", check the provider's own status field (sync_status, synced_at) rather than the HTTP code.
Applies to: every Ramp push/confirm, the accounting providers' adapters, and any integration verified only by "the request returned 2xx".
A document-backed journal is found through its LINES' document link, never through the document's own journalId
Context: Card charges as provider objects (2026-09-10). A charge books TWO journals over its life — the posting journal (charge.journalId) and, on void, a NEW Posted "VOID Charge" journal with no reversalOfId. Both carry journalLine.documentType = 'Charge' / documentId = <card id>.
Problem: The reconciler resolved the backing charge by charge.journalId, so only the posting journal was DOC_BACKED. The void journal looked like a plain journal, pushed to Rillet as a journal entry on top of the charge DELETE, and Rillet netted to minus one charge — invisible in unit tests, found only by voiding on the live sandbox and reading Rillet's GL.
Rule: When a journal's disposition depends on a backing document, resolve journal → document through the journal lines' documentType/documentId (one batch query), which every journal the document produces shares; treat the document's own journalId column as a fallback for unlinked rows. And any DOC_BACKED carve-out must be exercised across the document's full lifecycle (post → void) on a real provider before it is called done.
Applies to: loadChargePolicyInputs, every future DOC_BACKED source type, and the void/reversal audit still open in the always-on posting plan (Task 7).
Integration money shapes are contracts, not interchangeable numbers
Context: Ramp returns signed { value, currency } and { amount, currency_code } values in minor units, while its deprecated transaction amount fallback is a major-unit decimal. Several inbound families also still expose unverified bare-number fields.
Problem: One generic converter treated every number as minor units, understating a $123.45 fallback to $1.23; missing values became zero, unknown currency precision became two decimals, and unresolved foreign exchange rates became one. Those defaults turned malformed or incomplete provider payloads into apparently valid financial documents.
Rule: Normalize each provider money field through a helper tied to its verified wire shape. Reject missing, non-finite, fractional-minor, currency-mismatched, or unverified bare-number values per item. Currency precision and exchange rates are required accounting facts; never guess them or silently post foreign currency at par.
Applies to: Ramp charges, transfers, cashbacks, bills, bill payments, reimbursements, repayments, and future provider payloads with multiple monetary representations.
An external mapping must be committed with the Draft it makes idempotent
Context: Ramp reimbursement sync created a supplier interaction, purchase-invoice Draft, delivery, and lines through separate Supabase requests, then wrote the external mapping last.
Problem: A crash before the mapping left a complete but untracked Draft, so the next provider retry could create a duplicate. A transaction alone also leaves same-key concurrent workers racing until the final unique mapping write.
Rule: Create the local Draft structure and its external mapping in one Kysely transaction. Serialize the tenant-scoped external key before the initial mapping read (for example with a transaction advisory lock), and provide a narrowly constrained legacy-adoption path for Drafts created by the old writer. Prove create/resume, two-connection convergence, and mid-write rollback against real Postgres.
Applies to: inbound provider document/payment staging and any retryable workflow whose idempotency anchor is externalIntegrationMapping.
Prove batching through the real workflow entry point
Context: The accounting charge supplier lookup was consolidated into one joined batch loader, but the new lifecycle's pushBatchToAccounting still called the single-item push for every charge.
Problem: A test of fetchLocalBatch alone passed while the real QBO batch made four card-source reads for two rows; re-entering the parent single-item workflow also fetched mapped rows again.
Rule: Assert query counts through the public multi-item entry point, not only its loader. Load source rows and tenant/provider-scoped mappings once, pass those snapshots into the shared per-item lifecycle, and persist each remote success before advancing. Cover mixed creates, updates, voids, missing rows, and failures to prove batching preserves durability and error isolation.
Applies to: accounting sync batches and any workflow refactor that combines per-item remote effects with batched local reads.
Bind authorization to the authenticated subject
Context: An edge-function request carried a userId in its JSON body and also carried an authenticated Supabase JWT.
Problem: The permission helper looked up claims for the body-supplied user without proving that user matched the JWT sub, so a caller could borrow another user's permissions by changing one request field.
Rule: For an authenticated JWT, require a non-empty sub, require it to match the requested actor id, and use that subject for permission lookup. Treat body actor ids as attribution inputs only for trusted service-role/API-key flows; they are never authentication evidence.
Applies to: postingCaller / authorizePostingCaller (apps/erp/app/modules/shared/shared.service.ts) and any endpoint that accepts a caller/actor id alongside a bearer token.
Header-only financial documents must reject persisted detail
Context: Card Payment and Cashback journals are derived entirely from the header amount, card account, and offset account.
Problem: If either document nevertheless carried coding lines, the journal builder silently ignored those rows and posted a GL entry that did not represent all persisted document detail.
Rule: When a financial document type is header-only, assert that its detail collection is empty before posting. Never silently discard stored financial rows merely because the current journal shape does not consume them.
Applies to: Card payments and cashback today, and any future header-derived posting path that accepts a shared document shape containing optional lines.
Provider errors are not confirmation of the desired remote state
Context: Carbon retracts a pushed Ramp bill after its local invoice settles, then marks the external mapping archived so the action does not repeat.
Problem: The archive helper swallowed every provider error—including authentication, rate-limit, server, and not-found failures—and permanently marked the mapping archived even though no response proved the bill was gone.
Rule: Persist completion metadata only after a successful provider response or a specifically documented idempotent response contract. Error text, status guesses, and hoped-for remote state are not confirmation; propagate unknown failures so the workflow remains retryable.
Applies to: Ramp bill archival and every external integration that records a local completion flag after a remote mutation.
Prerequisite lookup failures must hold outbound cursors
Context: Ramp outbound purchase-order and invoice families batch-load suppliers and supplier types before deciding whether and how to export each document.
Problem: Query errors were treated like empty results. The workflow could skip documents, misclassify an Employee reimbursement as a vendor bill, and still advance the family cursor beyond the unread data.
Rule: Distinguish an empty successful lookup from a failed lookup. If data required for eligibility or payload construction cannot be read, fail the family before remote effects and keep its cursor unchanged so the same page replays after recovery.
Applies to: Ramp outbound suppliers and classifications, and every cursor-based exporter with prerequisite database reads.
Idempotent mappings do not make mutable Drafts immutable
Context: Ramp retries find an existing external mapping before staging and posting a charge.
Problem: Treating every mapping as completed caused a corrected provider record to post the stale Carbon Draft left by an earlier failed attempt. The mapping proved identity, not finalization.
Rule: Branch retry behavior on the mapped entity's lifecycle state. Refresh a mutable Draft and its lines atomically under the same lock used for posting; only a finalized, observably Posted entity may bypass source normalization and be reconfirmed unchanged.
Applies to: Ramp charges, transfers, cashback, and any mapped inbound document whose provider data can change before local finalization.
Never correlate bulk-insert results by RETURNING position
Context: Card posting and voiding bulk-insert journal lines, then create dimensions that must reference the exact source line they describe.
Problem: The code paired source rows with INSERT ... RETURNING rows by array index, but PostgreSQL does not guarantee that returned rows preserve input order. A reordered result could attach a cost center to the wrong GL account.
Rule: Allocate native ids up front in one query, include them in the bulk insert, and build dependent rows from those explicit ids. Positional correlation is safe only within application-owned arrays, never across an unordered database result.
Applies to: Journal lines and dimensions, and any bulk insert followed by dependent rows that need source-to-result identity.
Financial discriminators require explicit verified allowlists
Context: Ramp payment methods, reimbursement states, and repayment funding values determine whether Carbon creates a bank settlement, skips a card-funded payment, or leaves an invoice open.
Problem: Unknown values fell through to financially meaningful defaults, so new or misunderstood provider enums could debit the statement bank account or mark a reimbursement paid without a verified basis.
Rule: Route financial side effects only from an explicit allowlist grounded in the provider contract. Unsupported, missing, or ambiguous discriminator values must fail before mapping or posting; expanding the allowlist requires contract evidence and positive routing tests.
Applies to: Ramp bills, reimbursements, repayments, and every integration enum that selects accounts, settlement state, or document type.
Coding lines are positive magnitudes, not signed journal legs
Context: Card Charge, Credit, and Repayment documents translate positive coding allocations into debit or credit journal legs according to the transaction type.
Problem: Zero, negative, or non-finite line amounts could pass a header-sum check and invert or erase an individual accounting leg even though the overall entry still balanced.
Rule: Validate every document coding amount as finite and strictly positive before applying debit/credit semantics. A balanced journal is necessary but does not prove the document's line-level meaning is valid.
Applies to: Charge coding lines and other financial document builders that assign journal direction separately from stored line magnitude.
Unverified write contracts need a code-level release gate
Context: Ramp invoice export had complete-looking draft-bill and submit code, while its monetary units, coding fields, PDF shape, and returned bill identity had not been proven against the provider.
Problem: A customer setting could enable a financial write path whose payload contract was still explicitly speculative, allowing production data to exercise guesses.
Rule: Gate an unverified external write at its lowest shared entry point before any local or remote side effect. Do not expose a customer or environment bypass; enable it only in code after contract tests pin the real request and response shapes.
Applies to: Ramp draft-bill export and any external financial mutation implemented ahead of live contract verification.
Authenticate webhook challenges before acting on them
Context: Ramp webhook ownership challenges can trigger a provider callback and echo a challenge value from a tenant-addressed public endpoint.
Problem: Challenge extraction ran before HMAC verification and accepted an unsigned query parameter, allowing unauthenticated callers to invoke the callback path and receive an echo.
Rule: Verify the stored secret and signature over the raw body before handling any webhook delivery, including ownership challenges. Only authenticated bytes may supply challenge data; unsigned query parameters must never alter it.
Applies to: Ramp webhook verification and all provider handshakes sharing an endpoint with signed event deliveries.
Legacy adoption must prove the entire document identity
Context: Ramp reimbursement retries may encounter an untracked purchase-invoice Draft created by the older non-transactional writer before its external mapping was saved.
Problem: A supplier/reference match alone could adopt a user document, a finalized invoice, an incomplete Draft, or a document already linked to another Ramp source; silently repairing it could overwrite ambiguous business data.
Rule: Legacy adoption is a narrow compatibility proof, not a fuzzy lookup. Require one unposted system Draft with the canonical external reference, matching dates/currency, intact supporting rows, exact financial/coding/provenance lines, and no conflicting mapping. Reject mismatches without mutation.
Applies to: Ramp reimbursement Draft adoption and any retry migration that links pre-idempotency records by business keys.
Unbounded mapping sets require bounded status reads
Context: Ramp archive-on-settlement loads every unarchived external mapping, then reads the corresponding Carbon invoice statuses through PostgREST.
Problem: One .in() request could exceed both URL limits and the API's 1,000-row response cap. A settled invoice after the cap could be omitted on every sweep, while lookup and archive errors were not fully reflected in the family result.
Rule: Chunk unbounded identifier sets below transport and response limits, finish all prerequisite reads before remote writes, and count every failed remote mutation in the owning family result.
Applies to: Ramp settlement archival and any integration that joins unbounded mappings to API-backed status reads before external side effects.
Lifecycle transitions need a stored state invariant
Context: Charges use triggers to restrict Draft edits and the Draft→Posted→Voided transition sequence, while imports and test cleanup can intentionally bypass ordinary triggers.
Problem: Transition guards constrained how a row could change but did not guarantee that every stored status had its required audit shape. A status-only write could leave a Posted or Voided row without its actor and timestamp evidence.
Rule: Pair lifecycle transition guards with a validated database CHECK that defines every legal stored state. Fail migration preflight with row identities when existing data violates the invariant; never fabricate missing audit actors or timestamps.
Applies to: Charges and any auditable document lifecycle whose writers can bypass ordinary triggers or write status and audit fields independently.
A RAISE in a completion RPC aborts the UPDATE that triggered it
Context: complete_job_to_inventory gained guards refusing a completion it could not satisfy (zero quantity, a fractional serial quantity, fewer receivable units than completed).
Problem: That function is not only called from the ERP complete route — sync_finish_job_operation calls it from a BEFORE trigger interceptor, and dispatch_event_interceptors has no EXCEPTION block. So a serial item with no serial sequence (whose job keeps one whole-quantity seed entity, because assign-serial-numbers returns early with no sequence) made the raise propagate out and abort the jobOperation UPDATE itself: the operator could not mark the operation Done at all.
Rule: Before adding a RAISE to a SQL function, grep for trigger interceptors that call it. A refusal that is a useful error on a request path is a hard block on a trigger path. Either handle the case rather than refusing it, or make the trigger caller skip the call.
Applies to: complete_job_to_inventory, sync_finish_job_operation, and any function registered through attach_event_trigger.
A nullable column added by migration needs a reader that tolerates NULL
Context: The accounting corrections release added invoiceSettlement.sourceAmount (document-currency principal) without backfilling rows written before it, and the migration comment explicitly declared legacy NULLs valid.
Problem: The shared TypeScript reducer that computes an invoice's remaining balance and a payment's remaining funding threw "Settlement is missing its document principal" on any NULL. Every invoice with a pre-release partial payment or credit became unpayable: the New Payment loader seeded from such an invoice returned a 500, and posting a payment for that party would have failed the same way. The schema and the code disagreed about what a valid row is.
Rule: When a migration adds a nullable column and leaves existing rows NULL, every reader added in the same change must define what NULL means and handle it, or the migration must backfill. Keep the throw only where a DB constraint already guarantees the value (source-linked rows). Derive legacy values from the columns that did exist (appliedAmount at the applicable exchange rate) and cover the NULL case in the pure-function tests.
Applies to: payment-funding.ts reducers, any future column added to invoiceSettlement, journalLine, or other high-volume tables where a backfill is skipped.
A JSON column copied through Kysely on node-postgres only survives as an object
Context: Quote → sales order conversion (convert edge function) reads the quote with supabase-js and re-inserts its internalNotes / externalNotes into salesOrder through Kysely inside the transaction. One quote had internalNotes stored as a JSON string scalar rather than a tiptap document, written through an API path whose validator typed notes as z.any().
Problem: deno-postgres encodes query parameters by JS type, not by column type: an object is JSON.stringifyed, but a string is sent as raw text and an array as a Postgres array literal. A JSON string scalar therefore round-trips as unquoted text and Postgres rejects the insert with invalid input syntax for type json. The route sanitised the body, so Vercel only showed "Edge Function returned a non-2xx status code"; the real line was only in the Supabase function log. Every retry failed identically, and the same latent fault sat in RFQ → quote, supplier quote → PO, and quote revision copies.
Rule: Two layers, both required. (1) Any json/jsonb value written through Kysely in a server function goes through toJson() (@carbon/database/json, source packages/database/src/json.ts), which pre-serialises every non-null shape so the wire value is valid JSON text. (2) A validator for a rich-text column is never z.any(); use the shared optionalTiptapDoc / toTiptapDoc in shared.models.ts, which turns text, a JSON-encoded doc, or a doc object into a tiptap document and rejects the rest. Put .optional() AFTER the transform or zod infers a required key. When an edge function fails opaquely, read the function's own log (Supabase management API function_logs), not the caller's.
Applies to: posting Kysely inserts (apps/erp/app/modules/*/*.service.ts) of internalNotes, externalNotes, customFields, priceTrace, configuration, additionalCharges; every *.models.ts field that feeds a rich-text column (the purchasing notes: z.any() fields still need this).
Follow-up (found later): The original fix only covered the quote header row's internalNotes/externalNotes in quoteToQuote. The per-line copy loop in the SAME function (quoteToQuote's sourceQuoteLines.data insert into quoteLine) still spread the source row raw ({...line, quoteId, companyId}), leaving additionalCharges, configuration, customFields, externalNotes, internalNotes, and priceTrace unserialised — and quoteOperation.workInstruction (NOT NULL jsonb) was copied raw too. Any quote whose line ever picked up one of these as a non-object (a string/array) fails the copy deterministically with the same "invalid input syntax for type json" 500 — which the caller's fetchWithRetry (packages/auth/src/lib/supabase/client.ts) then retries blindly up to 3 times, and because this failure lands inside the SAME transaction as the quote/quoteLine/quoteLinePrice inserts it rolls back cleanly (no duplicate). Rule addendum: when applying this fix, grep the whole function for every {...row} spread and every raw column: source.column assignment into a jsonb column, not just the columns already known to be trouble — a partial rollout re-creates the exact bug it fixed, just narrower.
Resolve the accounting period BEFORE a transaction that writes for N records
Context: The batch material pick (issue case trackedEntitiesToBatch) runs one Kysely transaction and calls the per-member consumption writer once per batch member. Each member's write path reaches createMaterialWipEntries → getCurrentAccountingPeriod.
Problem: getCurrentAccountingPeriod READS the period over HTTP (supabase-js) but CREATES a missing one through the transaction handle. Inside one transaction, member 2's read cannot see member 1's uncommitted insert, so both try to create the same month and the accountingPeriod_company_fy_period_idx unique index aborts the whole pick. It only fires on the first posting of a month into a fresh database, so it passes every test run but the first — and the rollback makes it look like the pick silently did nothing (HTTP 200, empty body; the real error is only in the edge-runtime log).
Rule: Any lazily-created singleton that reads outside the transaction and writes inside it must be resolved BEFORE the transaction opens, once, when a flow writes for N records in one transaction. For the accounting period that is await getCurrentAccountingPeriod(client, companyId, db, companyToday.toString()) ahead of db.transaction(), guarded on accountingEnabled.
Applies to: getCurrentAccountingPeriod / getAccountingPeriodForDate in any multi-record edge-function transaction; the same shape applies to getNextSequence and any other get-or-create helper straddling the transaction boundary.
A post-success prompt must not live in the component the success unmounts
Context: MES batch completion. BatchCompleteModal submitted the completion and was meant to swap itself for a "merge these lots?" prompt when the action returned one.
Problem: The modal is rendered {batch && batchCompleteModal.isOpen && …}, and batch is only passed by the loader while the batch is Active/Completing. Completing it — the very thing that produces the prompt — revalidates the loader, batch becomes null, and the modal unmounts with its useFetcher still holding the response. The prompt could never render, and the symptom was indistinguishable from the server never sending it (the page just sat there, because a data() reply does not navigate).
Rule: When an action's response drives UI that appears AFTER success, own the fetcher in a component that outlives the state change — here JobOperation, passing the fetcher down into the modal and rendering the prompt itself, ungated by batch. Before wiring a post-success view, ask which component the success unmounts.
Applies to: MES JobOperation + BatchCompleteModal/BatchMergePrompt; any modal gated on loader data that its own submit invalidates.
Vite caches a module-resolution MISS for the whole dev session
Context: Added a BatchMergePrompt component: edited the importing file first, created the new file a moment later.
Problem: The SSR module graph cached the failed resolution, so every request 500'd with Failed to load url ./components/BatchMergePrompt … Does the file exist? even though it did. docker exec … grep and ls both confirmed the file, which sends you hunting a phantom bug in the import path.
Rule: Create the new module BEFORE the code that imports it. If the overlay already says "Does the file exist?" and it does, touch the new file and its importer to force re-resolution — the file's presence alone will not invalidate the cached miss.
Applies to: any new file under apps/{erp,mes}/app added after its importer during a running crbn up; the sibling failure mode for edge functions is the cached compiled isolate (crbn reload edge-runtime).
An unchecked supabase-js insert turns a NOT NULL violation into silence
Context: Inspection rejects were supposed to seed nonConformanceItemTrackedEntity links on the NCR's default Scrap row so the MRB could split or reassign specific entities. Nothing ever appeared. Both writers — x+/inspection+/$id.reject.tsx and x+/issue+/new.tsx's job-operation auto-link — built their rows without nonConformanceId, which is NOT NULL on that table (20260421130000_nc-item-tracked-entity.sql).
Problem: Every such insert returned a 23502, and nobody read it. The reject route did await (serviceRole as any).from(...).insert(rows) and discarded the result entirely, so the feature had never worked in production and no error surfaced anywhere. supabase-js does not throw — it resolves to { data, error } — so an unchecked insert is indistinguishable from a successful one, and the as any cast additionally hid that the row type was missing a required column. A Kysely insert in the same place would have thrown.
Rule: Never discard a supabase-js write result — bind it and check .error, even for a fire-and-forget link write. Treat as any on a .from(...).insert(...) as a defect in review: the cast exists precisely because the row object does not satisfy the generated type, which is the compiler telling you a required column is missing. When a "seeded" side table is mysteriously empty, check the writer's error handling before suspecting the read.
Applies to: every .from(...).insert(...) / .update(...) whose result is not bound, especially in post-commit "also link X" tails; fixed for both writers in PR #1612 by moving them into a Kysely transaction under lockIssueDispositions.
Retrying a 5xx from a non-idempotent Edge Function multiplies its side effects
Context: Duplicating a quote (quoteToQuote in get-method) kept failing with a generic toast while silently leaving 3-4 duplicate quotes behind — recurring across three separate production incidents, including twice AFTER the underlying jsonb-serialisation bug (see the lesson above) had already been fixed and deployed. Vercel logs showed exactly ONE incoming POST .../duplicate.data per incident, always HTTP 200 (the route swallows copy.error into a generic {success:false} and never throws, so the response code tells you nothing), with zero attached application logs.
Problem: getCarbonServiceRole() (and every other Supabase client) goes through fetchWithRetry (packages/auth/src/lib/supabase/client.ts), which blindly retries ANY 5xx response — including client.functions.invoke(...) calls into Edge Functions — up to MAX_RETRIES (2) more times. quoteToQuote is not idempotent (it always creates a brand-new quote/opportunity/externalLink) and runs across two separate Kysely transactions, so a deterministic failure partway through the second transaction lets the first transaction's insert commit on EVERY retry attempt before failing again — one incoming request, N internal retries, N duplicate quotes, and the client still reports failure because the last attempt also failed. This is a structural flaw independent of whatever is actually throwing: fixing one root cause (the jsonb bug) only stops the retries from being triggered by THAT cause — any other exception in the same code path reproduces the identical multiply-duplicate symptom, which is exactly what happened on the two later incidents.
Rule: Obsolete for get-method, convert and the post-* functions: they are server functions now, called in-process, so no HTTP retry sits in front of them. Still true: the isEdgeFunctionInvoke carve-out in fetchWithRetry stays for the remaining edge functions, and a retry wrapper must never blindly retry a write with real side effects and no idempotency key. Original rule: A retry wrapper must never blindly retry a write with real side effects and no idempotency key. fetchWithRetry already carved out isStorageUpload for this exact reason ("re-sending a multi-GB PUT ... is wasteful"); the same reasoning applies even harder to Edge Function invocations, which routinely do multi-table, multi-transaction writes (get-method, convert, every post-* function). Added isEdgeFunctionInvoke (matches /functions/v1/) alongside it — one attempt only, honoring the caller's own signal, no retry on status or network error. When debugging "op failed but extra copies appeared," check for exactly this shape (one incoming request, several committed results) before assuming a client-side double-submit or a browser retry.
Applies to: packages/auth/src/lib/supabase/client.ts (fetchWithRetry and isEdgeFunctionInvoke were removed with the supabase-js 2.117 upgrade; storageReadFetch retries storage reads only and never touches /functions/v1/); any future retry/timeout wrapper placed in front of client.functions.invoke. Also: $quoteId.duplicate.tsx and similar routes that discard the real error into a generic message — add logger.error there so a recurrence is diagnosable from Vercel logs alone, without needing Supabase edge-function log access.
pdfjs rejects Node Buffer by constructor check
Context: @carbon/files/pdf and the shared image pipeline feed bytes from fs.readFile / storage.download().arrayBuffer() into pdfjs (via unpdf) and jSquash codecs.
Problem: pdfjs throws Please provide binary data as 'Uint8Array', rather than 'Buffer' — it checks the constructor, and Node's Buffer fails despite being a Uint8Array subclass. The failure only appears in Node (tests, jobs), never in the browser or Deno.
Rule: Normalize at the boundary: wrap as a plain view over the same memory — new Uint8Array(data.buffer, data.byteOffset, data.byteLength) — before handing bytes to a wasm codec or pdfjs. @carbon/files does this in its toBytes helpers; new entry points must too.
Applies to: packages/files/src/pdf/pdf.ts, packages/files/src/media/image-pipeline.ts, any future wasm codec wrapper.
A functions/shared source with npm deps must register them twice
Context: functions/shared/image-pipeline.ts follows the precision.ts pattern (source under supabase/functions/, re-exported by a Node package) but, unlike precision, imports npm packages (libheif-js, @jsquash/*).
Problem: Module resolution follows the FILE's location, not the importer's. Deno resolves the bare specifiers via functions/deno.json imports; Node/Vite resolve them from packages/database/node_modules — not from the re-exporting package. Registering the dep in only one place typechecks in one world and crashes in the other, and the versions can silently drift.
Rule: Obsolete: the pipeline moved to @carbon/files (packages/files/src/media/image-pipeline.ts, its deps in that package.json) and functions/deno.json no longer pins any deps. Still true: type declarations a module needs sit next to it (triple-slash reference) — ambient .d.ts files only load for programs that include them.
Applies to: packages/files/src/media/image-pipeline.ts.
unpdf ships a dead 1.5 MB engine chunk unless aliased away
Context: @carbon/files/pdf uses unpdf but points it at react-pdf's pdfjs-dist in the browser (definePDFJSModule) so each bundle has one PDF.js engine.
Problem: unpdf's fallback import("unpdf/pdfjs") is never reached but is statically visible, so Vite emits its bundled serverless engine as a ~1.5 MB lazy chunk in every client build.
Rule: Any browser app consuming @carbon/files/pdf aliases unpdf/pdfjs to app/ssr-shims/unpdf-pdfjs-stub.mjs in its Vite config (both apps do). Verify with the built output: exactly one chunk should contain GlobalWorkerOptions + PDFWorker.
Applies to: apps/{erp,mes}/vite.config.ts, any new React Router app that reads PDFs client-side.
crbn reload of storage leaves Kong routing 502s
Context: Recreating the storage container (crbn reload storage imgproxy) after a compose edit.
Problem: Kong resolves upstreams via Docker DNS at proxy time but held the old container IP — every /storage/v1/* request returned 502 while the storage container itself was healthy and listening.
Rule: After crbn reload of any service Kong proxies (storage, auth, postgrest, edge-runtime), also run crbn reload kong. Verify with curl $SUPABASE_URL/storage/v1/version (expect 200), not with docker ps.
Applies to: packages/dev compose workflow, any per-service reload.
A running total must be subtracted from the pool it was taken from
Context: The operation-completion backflush (issue, issueJobOperationMaterials) allocates every material of the operation against its lineside budgets before inserting any ledger row. A review pointed out that two materials sharing a picked item could both be offered the same unclaimed lineside stock, and asked to track what earlier materials took and subtract it from the next budget.
Problem: The budget's available was the sum of two pools — the material's OWN pick (private) and the bin's UNCLAIMED stock (shared) — and the fix subtracted a per-item running total of whole takes from that sum. Material A consuming its own private pick therefore zeroed material B's private pick, and B fell back to the warehouse while its staged stock sat at the machine. The fix was written to the reviewer's wording ("subtract it from available"), it had no test with a non-empty running total, and the follow-up review comment landed after the fix was pushed and was never re-polled.
Rule: When a value is a sum of pools with different sharing scopes, never subtract a merged total from it. Keep the pools apart on the type, attribute each take to a pool, and subtract a take only from the pool it came from. Every fix that adds a cross-iteration accumulator gets a pure test with the accumulator non-empty before it is committed. After pushing review fixes, re-read the PR's open threads — the reviewer's follow-up is on the FIX commit, not the original diff.
Applies to: lib/picked-consumption.ts (SharedTakes, recordSharedTakes, splitTakeByBin), generatePickingList's unclaimedRemaining, getPickedBudgets callers, and any loop that allocates from a shared balance before persisting.
A cron that walks every tenant must isolate each tenant
Context: accounting-pull-sweep looped for (target of targets) await step.run(...) over every active accounting integration; mrp ran every company inside ONE step.run. One Xero tenant's refresh token died (invalid_grant "Refresh token not found"); one MRP run outgrew Vercel's function timeout.
Problem: An Inngest step that exhausts its retries throws into the function and fails the run, so the dead-token company silently skipped every company after it on every sweep — for weeks, with no notification. The single-step MRP was one Vercel invocation for all tenants, timed out, and every retry restarted from company #1. In both cases the run's status said what happened to the run, not to the tenants.
Rule: One step.run per tenant, wrapped in try/catch that records { error } and continues; return the per-tenant outcomes so the run output says who failed. Classify terminal failures (a refused OAuth grant is AccountingAuthError) and return them from the step instead of throwing — retries cannot fix them and only delay the next tenant. Pair the per-tenant step with a maxDuration on the serve route: a step's ceiling is that function's ceiling.
Applies to: packages/jobs/src/inngest/functions/** — every cron with a per-company loop (accounting-*-sweep, accounting-reconciliation, accounting-consolidation, scheduled/mrp.ts); use runIsolatedCompanyStep (integrations/accounting-auth-failure.ts) for the accounting ones.
Sweeping storage call sites by one literal misses named-constant buckets
Context: The company-private-bucket migration swept every storage.from("private") call in the repo to per-company buckets. The literal grep found ~160 call sites and missed six more: RAW_DURABLE_BUCKET = "private" (assembler-client), STORAGE_BUCKET = "private" (company-backup/export), BUCKET = "private" (onshape-attach), DOCUMENTS_BUCKET = "private" (download.$token), archiveBucket: "private" (audit.config), and the ["private", "temp-staging"] probe arrays in both apps' model.artifacts/model.download routes.
Problem: Each miss was a real defect, not noise — new CAD raws kept landing in the legacy bucket, backups silently skipped assets uploaded to company buckets, restores wrote assets back into the legacy bucket, and token downloads / audit-archive reads would 404 on new files once the legacy fallback is removed.
Rule: When migrating a string-keyed resource (a bucket, a queue, a topic), grep for the VALUE in every syntactic position — = "x", : "x", "x",, ("x", and type unions — not just the one call pattern you are rewriting. Constants exist precisely to hide the literal from the call site.
Applies to: any repo-wide sweep keyed on a string literal; storage buckets (private, temp-staging, company-templates), PGMQ queue names, Inngest event names.
A merged-away table breaks every existing backup unless the rename map and schema manifest move with it
Context: The sales-rules PR (#1382) merged storageRule / storageRuleItemAssignment / storageRuleWorkCenterAssignment into the shared enforcementRule* tables and dropped the old ones. The branch shipped with no TABLE_RENAMES entries and a stale packages/jobs/manifests/schema.json still listing the dropped tables.
Problem: A restore that meets an unmapped missing table refuses by design (applyTableRenames → assertBackupImportable), so every customer backup taken before the merge would stop restoring the moment it shipped. The pre-commit db:check:backups gate that catches this only runs against a migrated LOCAL database — on a worktree with no dev stack the hook skips with a warning, which is exactly the state a reviewer or merge-fixer is in.
Rule: A migration that renames or drops any tenant-scoped table needs, in the same commit: (1) a TABLE_RENAMES entry (packages/jobs/src/backups/renames.ts — new name, or null if the feature died), (2) a default (or nullability) on any NEW NOT-NULL column of the rename target so old backup rows can load, and (3) a regenerated manifests/schema.json, which requires running pnpm db:migrate + pnpm db:check:backups against a live local DB. If the DB isn't running, say so — a skipped hook is not a passed check.
Applies to: packages/database/supabase/migrations/** table renames/drops, packages/jobs/src/backups/renames.ts, packages/jobs/manifests/schema.json, .claude/rules/workflow-database-migration.md step 3b.
OAuth signup bypasses app-level email gates — GoTrue provisions before your code runs
Context: The free/disposable-domain self-signup blocklist (#1661) was enforced only on the email/password path (login.tsx unknown-user branch, verify.tsx before createEmailAuthAccount). "Sign in with Google" / "Sign in with Outlook" (signInWithOAuth) let a gmail/outlook address self-sign-up anyway.
Problem: For OAuth there is no app-code seam before account creation. GoTrue creates the auth.users row during the IdP handshake and the create_public_user trigger fires inside that same transaction — all before the app's /callback action runs. So an email-path-only check has an OAuth-shaped hole, and the callback is the first point app code can react. The tempting "let it create, then delete it" teardown is a smell; the truly-earlier options (a GoTrue before-user-created hook, GOTRUE_DISABLE_SIGNUP=true, or a trigger RAISE) each cost more than they save (infra + Cloud config, or breaking existing-user first-time OAuth login, or a DB-resident blocklist + no edition signal + a raw error instead of a message).
Rule: Any signup/identity gate must cover OAuth, not just the email path, and OAuth is enforced in the auth callback's non-SSO branch (both ERP and MES). Gate on a GENUINE self-signup only — no company membership AND no pending invite — so existing members and invited contractors pass. Prefer not minting a session over deleting the account: a membership-less user row can access nothing and is reused by createEmployeeAccount if the address is later invited, so no teardown is needed and the email stays invitable. Keep the check + domain list in one shared home (@carbon/auth/self-signup.server) so every entry point (ERP login/verify/callback + MES callback) shares one copy.
Applies to: apps/{erp,mes}/app/routes/_public+/callback.tsx (non-SSO branch), packages/auth/src/services/self-signup.server.ts, and any future email/domain restriction — check the OAuth callback, not only the email/password flow.
A fetcher's redirect is dropped when anything revalidates during the action
Context: MES "Complete Batch" posts through a useFetcher to an action that runs for several seconds and ends in redirect(path.to.operations). The operation page also subscribes to realtime changes on jobOperation/job and calls revalidate() on each.
Problem: The completion's own writes fired the realtime revalidate() mid-action. React Router (handleFetcherAction) ignores a fetcher's redirect when pendingNavigationLoadId > originatingLoadId — any navigation or revalidation started after the submit wins. The redirect was silently discarded, the fetcher went idle, and the page sat on stale loader data from the mid-run revalidation (the batch still "Completing", button reading "Retry Completion") even though the work had landed.
Rule: Realtime listeners must not revalidate while a fetcher on the page is submitting — use useRealtimeRevalidator() (apps/mes/app/hooks/useRealtime.tsx), never a bare useRevalidator().revalidate() in a realtime callback. Skipping loses nothing: the router revalidates after every action, which is why revalidate() already no-ops during a navigation submission. The same race also reached single-operation completion: finishing a job's last operation completes the job, the job UPDATE revalidated the operation loader mid-action, its floor gate redirected with "This operation's job has not been released to the floor", and the operator saw that error instead of "Operation finished successfully" (reproduced 2 of 10 runs before the guard, 0 of 8 after). Batch completion additionally returns data({ completed: true }) and navigates client-side.
Applies to: every realtime- or interval-driven revalidate() on a page that submits fetchers — MES useOperation, AssemblyView, useRealtime.
A hardcoded list that mirrors the schema goes stale silently, and a restore still reports success
Context: Two independent cross-company restore defects, found together while
tracing one broken restored company. (1) #1148 (2026-07-20) added glbPath /
graphPath to modelUpload and removed modelPath from STORAGE_PATH_COLUMNS
without adding the two new columns, so restored assemblies pointed at the SOURCE
company's storage prefix. (2) 2a19048def (2026-08-31) correctly widened
id-remapping to composite-PK tables, which swept in part/material/
consumable/service/tool — whose id is a human-authored part number
(ADCS-001) that the parts view joins against item."readableId", not an
identifier. Every Items page rendered empty against 860 intact rows.
Problem: Both lists mirror a schema property no constraint expresses, so neither compiler nor DB catches drift. Worse, the restore job reports SUCCESS in both cases — the rows load and the files copy; only a join or a URL silently resolves to nothing. And both are invisible on a same-company restore, where the remap is a no-op, so the usual manual test passes.
Rule: When a list in code enumerates schema facts (path columns, tables
exempt from a transform), pin it with a test that fails when the schema outgrows
it, and state in the list's own doc comment what must be added alongside a new
column/table. When widening a rule that mints or rewrites ids, ask which of the
newly-swept tables use that column as a VALUE others match on rather than as an
identifier — part.id is a part number. Verify a restore by querying the view
the UI reads (parts), not the table (part); the table was always full.
Applies to: packages/jobs/src/inngest/functions/tasks/company-backup.ts
(STORAGE_PATH_COLUMNS, READABLE_ID_TABLES), buildIdMaps in
company-backup.transforms.ts, and any future cross-company restore work — test
cross-company, never same-company.
A folder that implies "run this in production" arms every file dropped into it
Context: One-off data migrations (copying the legacy private bucket into
per-company buckets) needed to run automatically, once per database. The design
made scripts/one-off/ self-registering: discoverOneOffScripts reads the
directory and every .ts file is executed against every production database
after supabase db push, recorded in that database's own scriptRun table.
Problem: Removing the hardcoded registry array killed a real duplication —
a list that could disagree with the folder — but replaced an explicit opt-in
with an implicit one. endsWith(".ts") also matches foo.test.ts, and
scripts/lib/ already colocates *.test.ts beside its sources. A developer
following the repo's own established convention would have shipped a test file
into production execution. Nothing in the type system, the linter, or a review
diff makes a new file in a directory look dangerous.
Rule: When a directory's membership is what triggers an action, gate it with an ALLOWLIST pattern and make non-matching files a loud failure, never a silent skip. A blocklist arms whatever nobody thought to exclude; a silent skip is worse than a crash, because a script ignored for a filename typo is indistinguishable from one that already ran, and the deploy reports success having done nothing. State the naming rule in the folder's README, and test it with the exact filename the surrounding conventions would produce.
Applies to: ci/src/one-off-scripts.ts (SCRIPT_FILENAME,
discoverOneOffScripts), scripts/one-off/, and any future
convention-over-configuration discovery where the discovered thing is executed
rather than merely loaded.
A wrapper that narrows a result type needs its call sites re-read, not re-cast
Context: Replacing the free-function storage helpers
(listCompanyPrivateObjects and friends) with a fluent
storage(client).company(id) client in @carbon/files. The old helpers
returned { data: StorageFileLike[]; errors: [] } — data never null, entries
structurally typed — so ~10 call sites carried as FileObject[] /
as unknown as StorageItem[] casts to recover the real supabase fields. The
new client returns supabase's own { data: FileObject[] | null; error }.
Problem: Every one of those casts still compiled, and now silently asserted
away a null the wrapper had just introduced. (result.data as FileObject[]).map(...)
typechecks and throws at runtime the first time a company bucket errors —
exactly the case the legacy-fallback window makes likely. A cast written to
paper over a WIDER type keeps compiling when the type gets NARROWER, and TS
reports nothing.
Rule: When a refactor changes a shared helper's return type, grep its call sites for casts on the changed field BEFORE trusting a green typecheck — a cast is a silenced diagnostic, so the compiler cannot tell you it is now wrong. Delete the cast and let the type flow; if the new type is right, the cast was load-bearing only for the old one.
Applies to: packages/files/src/storage.ts (CompanyBucket), its ~60 call
sites across apps/erp, apps/mes, packages/{jobs,ee,lib}, and any future
change to a helper whose result is destructured widely.
A git hook exports GIT_DIR, so any git run from a subdirectory gets the wrong work tree
Context: The pre-commit backup check (packages/jobs/src/scripts/check-backups.ts,
reached through pnpm --filter @carbon/jobs, so its cwd is packages/jobs) regenerates
packages/jobs/manifests/schema.json and stages it with git add <absolute path>.
Problem: Run by hand it staged the right path. Under the hook it ALSO indexed the
same content as a root-level manifests/schema.json on every migration commit — a
6,994-line file that existed nowhere on disk, resurfacing after each git rm --cached.
Git runs hooks with GIT_DIR exported and no GIT_WORK_TREE; with GIT_DIR set, git
treats the CURRENT directory as the work-tree root, so an absolute path under
packages/jobs was recorded relative to packages/jobs. An absolute path does not
protect you: the index path is computed from the assumed work tree, not from cwd.
Rule: Any script a git hook may invoke must run its git commands from the
repository root (cwd: REPO_ROOT derived from import.meta.dirname, or git -C),
never from the package pnpm --filter dropped it in. Verify a hook-driven git add
by reading git show --stat HEAD after the commit, not by running the script by hand.
Applies to: check-backups.ts, scripts/generate-mcp.ts's digest staging, the
lingui staging in .husky/pre-commit, and any future hook step that writes and stages
a generated file from inside a workspace package.
Lingui: a ternary inside t`` bakes the English words as runtime values
Context: Building the quote lead-time modal, plural labels were written as
t`${days} ${days === 1 ? "day" : "days"}` and
t`${n} ${n === 1 ? "operation has" : "operations have"} no time standards`.
Problem: Lingui extracts that as {0} {1} no time standards — the "day"/
"days"/"operation has"/"operations have" strings are computed at runtime and
passed in as PLACEHOLDER VALUES, never as translatable text. So every locale's
msgstr still contains the English word, linguito check stays green (nothing
is "missing"), and a French user reads "5 days", not "5 jours". The defect is
invisible to the missing-translation gate because the placeholder IS filled.
Rule: Never put a pluralizing (or any word-choosing) ternary inside a
t tagged template or <Trans>. Use the ICU plural macro: <Plural value={n} one="# day" other="# days" /> from @lingui/react/macro (or plural() in
non-JSX — but not inside a memo(…)-wrapped component, see "Lingui: plural()
inside a memo(…) component calls the global i18n" below). The whole phrase
with # goes in each branch
(one="# operation has no time standards"), so the words are extracted and
translated. After adding one, re-run lingui:extract + /translate — the new
ICU msgid needs its own filled msgstr per locale (locales with more CLDR
categories, e.g. Polish/Russian few/many, get the extra branches).
Applies to: any apps/{erp,mes}/app or packages/{react,form}/src string
with a count-dependent word; grep ? " inside t` templates when reviewing
i18n.
A migration file created while migrations are running is recorded as applied — empty
Context: Phase D of the rentals plan. crbn up was booting (its migrate step
runs supabase migration up --include-all) while pnpm db:migrate:new lease-enum
created the next migration file, whose SQL was written a few seconds later.
Problem: The running migrate step picked up the brand-new, still-empty file and
recorded version 20260923051441 in supabase_migrations.schema_migrations with
zero statements. Every later crbn migrate treated it as applied, so the enum value
it adds never reached the database; the regenerated types silently lacked it and
the first symptom was an unrelated-looking TS2353 in @carbon/ee. A sibling file
created four seconds later had its SQL in time and applied normally — so "the other
migration worked" proves nothing.
Rule: Never create or edit a migration file while crbn up / crbn migrate /
pnpm db:migrate is running; write the SQL first (or wait for the run to finish).
When a regenerated type is missing something a new migration adds, check
select version, array_length(statements, 1) from supabase_migrations.schema_migrations order by version desc limit 5 — a NULL statement count on your version means it was
recorded empty. Idempotent SQL can then be re-applied with psql -f.
Applies to: every new migration under packages/database/supabase/migrations/
during a crbn up boot or a background migrate.
A PR's CLA check counts every commit author on the branch, including copies of main's commits
Context: PR #1697's license/cla stayed pending after the author had signed many
times. The bot listed "Brad Barbin" (not a GitHub user) and chasefostermfg as unsigned.
Problem: Two independent causes, neither fixable by signing again. (1) Commits made
before user.email was configured were authored as <user>@<hostname>.local — git's
fallback — which no GitHub account can own, so cla-assistant can never match them.
(2) Rebasing the branch onto main by replaying commits copied other contributors'
already-merged commits onto the branch with new SHAs, so they became PR commits and
their authors became CLA "committers".
Rule: Set user.name / user.email before the first commit
(git log origin/main..HEAD --format='%ae' | sort -u must show only GitHub-linked
emails). Bring main in with a MERGE, never by replaying main's commits onto the branch.
To repair an affected PR, squash onto origin/main (merge main first so the tree is
current, git reset --soft origin/main, commit once, confirm HEAD^{tree} is
unchanged) and git push --force-with-lease=<branch>:<known sha>.
Applies to: any PR on crbnos/carbon (cla-assistant.io).
The root .env overrides .env.local, so a worktree's DB port is not the default
Context: Running the post-reimbursement Deno tests with the
SUPABASE_DB_URL I found first gave 16 passed | 12 failed. Re-running the
UNTOUCHED post-charge suite gave 19 passed | 16 failed — the same shape,
failing at the same fixture line. The connection string was wrong, not the code.
Problem: Each crbn worktree gets its OWN Postgres container on a random
host port (docker ps showed 0.0.0.0:49921->5432), written to .env.local.
The root .env still carries the stock 54322, and it WINS — the same
precedence trap that produced the db:check:backups fix in c1c5e7c138. Port
54322 is often another worktree's live stack, so you don't get "connection
refused"; you connect to a real database with the wrong schema and read the
failures as a bug in your own change.
Rule: Get the port from docker ps --format '{{.Names}}\t{{.Ports}}' | grep postgres (or this worktree's .env.local) and pass it explicitly. Before
believing a Deno/DB test failure is yours, run a NEIGHBOURING suite you did not
touch — post-charge next to post-reimbursement. Identical failure counts in
untouched code means the environment, not the diff.
Vitest reads SUPABASE_DB_URL from the root .env too, so DB-backed vitest suites
(databaseTest in apps/erp/test/database/fixtures/local-database.ts) connect to the stale port: they do not skip, because the host is still local. Export the
worktree's URL before you run them:
export SUPABASE_DB_URL="$(grep -h '^SUPABASE_DB_URL' .env.local | cut -d= -f2- | tr -d '"')".
Applies to: DB-backed tests (apps/erp/test/database/fixtures/, vitest databaseTest); any pnpm db:check:* or psql work inside
a Conductor worktree.
The @carbon/ee barrel boots the server env — four places that breaks
Context: Adding providerRole + IntegrationTopology (.ai/plans/implemented/2026-09-23-provider-roles-topology.md).
Consumers across @carbon/jobs, apps/erp and tests needed the registry lookup
getIntegrationIdsByRole / resolveIntegrationTopology.
Problem: packages/ee/src/index.ts imports every integration descriptor, and
ramp/config.tsx imports RAMP_CLIENT_ID from @carbon/auth, which validates
the FULL server env at import time. So a plain import … from "@carbon/ee"
fails in four distinct ways, each with a different symptom:
- In a
*.service.ts— these were re-exported through the module barrel that client components import, so they were browser-bundled. The build fails with "server-only module referenced by client". (The barrels are gone since 2026-10-16; a service file reaches the browser now only through a route component that uses one of its values — see "A server-only value in a route component, or a dropped side-effect import, fails only the production build".) (accounting.service.tscannot use the registry at all; its id list stays hard-coded with a comment saying why.) - In a test —
Error: INNGEST_SIGNING_KEY is not setat import. Hit three times: a test importing the barrel directly, a test importing a module that imports it, and a jobs test importing a module whose sibling did. - As a lazy
await import("@carbon/ee")— moves the failure from module load to CALL time, which looks fixed until a test actually exercises the path. - Via a
vi.mock("@carbon/ee", …)fixture — the mock lists exports explicitly, so adding a registry call to a loader breaks any test mocking it withNo "X" export is defined on the "@carbon/ee" mock.
Rule: Keep decision cores free of the barrel. Put shared logic in an
import-light module (packages/ee/src/sync/** imports no @carbon/auth) and
take the registry slice as an ARGUMENT — buildIntegrationTopology(rows, descriptors), not buildIntegrationTopology(rows). Only ENTRY POINTS (Inngest
functions, route loaders/actions) import the barrel and inject what they read;
give that import its own tiny module (jobs/…/integrations/topology.ts) so the
blast radius is one file. When you add a registry call to a loader, grep for
vi.mock("@carbon/ee" and extend those fixtures in the same change. Precedent
for the same shape elsewhere: events/sync-tables.ts and
accounting/core/subscriptions.ts are both deliberately import-light.
Applies to: packages/ee/src/index.ts consumers; packages/ee/src/sync/**;
packages/jobs/src/inngest/functions/**; any apps/erp *.service.ts; any test
mocking @carbon/ee.
Kysely returns date columns as JS Dates; PostgREST returns strings
Context: Porting Ramp's outbound draft-bill push from a Supabase-client job into a
BaseEntitySyncer (which uses Kysely) — .ai/plans/implemented/2026-09-23-spend-outbound-event-engine.md.
Problem: purchaseInvoice.dateIssued / dateDue are date columns. Read through
PostgREST they arrive as "2026-09-15" strings; read through Kysely's pg driver they
arrive as JS Date objects, which JSON.stringify renders as a full ISO timestamp.
Ramp rejected every draft bill with 422 DEVELOPER_7001 "Not a valid date". Typecheck
did not catch it — the syncer's local type declared string | null and the Kysely row
was assigned straight in. Unit tests did not catch it either; only a live push did.
Rule: FIXED AT THE SOURCE for date columns — node-postgres now decodes OID 1082 to
the raw YYYY-MM-DD string, so a Kysely row matches the generated types
(packages/database/src/client.ts, pinned by
packages/database/src/postgres-type-parsers.test.ts). timestamp/timestamptz
(1114 / 1184) are deliberately still Dates — Postgres' wire text for those differs in
SHAPE from PostgREST's (… 16:36:52.677+00 vs …T16:36:52.677+00:00), so identity
would make the two clients disagree. So: when moving a query from the Supabase client to
Kysely, treat every TIMESTAMP column as a value whose runtime type just changed, and
normalize with toPostingDateString before it reaches a wire payload or a .slice.
The deeper rule: a runtime/type mismatch that the GENERATED types already paper over
is invisible to typecheck by construction. Fix it at the driver, not with a helper at
every call site — the helper is what 34 call sites and ~16 instanceof Date guards were.
Applies to: any packages/ee syncer or packages/jobs function reading timestamp
columns through Kysely and sending them to a provider API.
Comparing a Kysely timestamp against a PostgREST one is silently always-false
Context: "Why does this one vendor resync every 30 minutes?" — the v5 reconciler's
master-data change check (reconcileMasterData, jobs/…/integrations/reconcile.ts).
Problem: snapshot.updatedAt <= input.lastSyncedAt compared an ISO string (loaded
via supabase-js) against a JS Date (loaded via Kysely — see the date lesson above;
timestamptz is still decoded as a Date). JS relational operators coerce both operands
toward NUMBER: the Date becomes epoch ms, the ISO string becomes NaN, and every
comparison with NaN is false. So the "unchanged since the last successful sync"
short-circuit could never fire, and every master-data row edited inside the 7-day sweep
window re-enqueued a no-op push twice an hour — ~336 green Completed rows per row.
Nothing failed, nothing was written remotely (the provider's own bailout does the same
comparison correctly, Date <= Date), so the only symptom was ledger noise. Both the
declared type (lastSyncedAt: string | null) and the existing golden tests (two matching
ISO strings) asserted the fiction.
Rule: never use </<= on two timestamps that came from DIFFERENT clients. Convert
both to epoch ms first (instantMs). Where a value's runtime type disagrees with the
generated types, WIDEN the declared type (string | Date | null) rather than leaving the
lie in place — the widened type is what makes the next reader handle it. And write the
test with the argument shapes the caller REALLY passes: a test that feeds two tidy ISO
strings into a comparison bug passes forever.
Applies to: any decision function fed by both a Supabase-client read and a Kysely
read — jobs/…/integrations/reconcile*.ts above all; packages/ee/src/accounting/core/**
syncers (syncInstant in charge-syncer.ts is the pattern that got it right).
Context: A security report: any signed-in user could read, create, update and delete every
public."user" row through PostgREST. The policy was FOR ALL USING (has_any_company_permission('users_update')), and a self-serve signup holds users_update in
its own company.
Problem: has_any_company_permission(claim) answers "does the caller hold this permission
ANYWHERE?" It never relates the row to a company, so any policy built on it alone is
cross-tenant. A table with no companyId (user) cannot use the standard four-policy template,
so the shortcut looked reasonable.
Rule: Never gate a policy on has_any_company_permission. Every policy must connect the ROW
to a company in get_companies_with_employee_role() or
get_companies_with_employee_permission(...). For tables without companyId, go through a
membership table (userToCompany, employee, …), as 20260924153817 does. When a global
row is shared by several tenants, also pin the columns no single tenant owns (a BEFORE UPDATE
guard on current_user IN ('anon','authenticated')), and revoke INSERT/DELETE from the API
roles when only the server writes them. Also check pg_policies for qual = 'true'.
Applies to: packages/database/supabase/migrations/** RLS on global tables (user,
userPermission, group), and any review of an RLS helper.
Context: A security report: with only the published anon key, a caller could reach 84+
SECURITY DEFINER functions through /rest/v1/rpc — inventory valuation, claims, document
sequences, the event interceptors — for any company, plus a SQL injection in
get_company_id_from_foreign_key. Table RLS held on all 438 tables; the functions went around it.
Problem: Every function in public is an RPC endpoint, and a SECURITY DEFINER one bypasses
RLS. Guards were written inline as IF NOT (has_role(...) OR ...), which is NULL — not true —
when a lookup finds nothing, so they never raised. The obvious fix, REVOKE EXECUTE, segfaults
this Postgres image on the next anon call (20260924192316); a first draft of the fix did exactly
that and only a rule file caught it, because its test checked has_function_privilege instead of
making the call.
Rule: Never REVOKE EXECUTE on a public function. A SECURITY DEFINER function that takes a
company id calls assert_company_access first; one that only servers call raises on
current_setting('role'); everything internal (helpers, event interceptors) is SECURITY INVOKER.
Never trust a user id parameter without relating it to auth.uid(). Test a guard by CALLING the
function as anon and as another company's user, not by reading the catalog. Edge functions:
verify_jwt accepts the anon key, so authorize in-function (requireCaller / requireServiceRole).
Applies to: every CREATE FUNCTION in packages/database/supabase/migrations/**,
packages/database/supabase/functions/*/index.ts; enforced by the
public-definer-function-authorizes-caller invariant and supabase/tests/rpc-privileges.test.sql.
CREATE OR REPLACE VIEW without WITH (...) silently drops security_invoker
Context: openJobMaterialLines served every company's open job material lines to the anon
key (reported against production, 2026-09-26). The clause had been added, audited back in, and
then dropped by four separate migrations that recreated the view from an older copy.
Problem: CREATE OR REPLACE VIEW REPLACES the view's options with whatever the statement
states, so a recreation that omits WITH (security_invoker = true) turns an invoker view back
into an owner-rights one. Owner rights bypass RLS on every table underneath, and every public
view is a PostgREST endpoint. Nothing failed: the app filters by companyId itself, so every
screen still looked right.
Rule: Every CREATE [OR REPLACE] VIEW states security_invoker — copy a view's definition
from its NEWEST migration, and re-check the WITH clause when you do. Test a view the way an
attacker reads it: SET LOCAL ROLE anon; SELECT count(*) FROM "view"; must be 0. Join on
companyId too, so a view is tenant-consistent on its own.
Applies to: packages/database/supabase/migrations/**; enforced by the
no-view-without-invoker conformance check and the view-without-security-invoker invariant.
A local-only sync step does not deploy (authz manifest, 2026-09-27)
Context: RLS policies moved from migrations into packages/database/src/authz/manifest.ts,
applied by authz sync after crbn migrate. Production runs migrations only.
Problem: With policies forbidden in migrations, a new table would be correct locally and
ship to production with no policies and RLS off — open to the anon key, since Supabase grants
public tables to anon/authenticated by default. Edited rules would silently never deploy.
Separately, a test of a missing UPDATE WITH CHECK passed against the broken policy: a
filtered UPDATE … WHERE checks the new row against the SELECT policy too.
Rule: Anything applied outside migrations needs a CI gate that proves the deploy path
carries it (migration.test.ts → authz migration). Test a WITH CHECK with an unfiltered
UPDATE or by evaluating the policy expression directly, and prove the test red first.
Applies to: packages/database/src/authz/**, packages/database/supabase/tests/authz-*.sql.
A PostgREST update that matches no row reports success
Context: Typed item updates (upsertPart, upsertTool, upsertConsumable,
upsertService, upsertMaterial) filtered the typed table by the item's uuid,
but those tables are keyed by the item's readable id plus companyId.
Problem: client.from(t).update(...).eq(...) with no .select() returns
{ error: null } when it matches zero rows. Half of every typed update wrote
nothing, and the API and MCP reported success.
Rule: An update whose miss is a bug ends with .select("id").single(), so
a miss comes back as an error. Key each table by its own primary key: item
by uuid, the typed tables by readableId + companyId
(resolveTypedItem / updateTypedItem in items.service.ts).
Applies to: any supabase-js update in a service, above all one that writes a pair of tables keyed differently.
A Kysely write needs its own RLS gate
Context: Material property edits write the material row, every revision's
item row and itemCost in one Kysely transaction.
Problem: Kysely connects as the Postgres role and bypasses RLS, so a caller
without parts_update in the company, or naming another company's material,
would still write.
Rule: Before a Kysely transaction on rows a caller names, run one UPDATE
through the caller's supabase client, filtered by id and companyId, with
.select().single(), and stop on its error (requireMaterialUpdatable). Pick
a row whose policy also covers the other rows the transaction writes.
Applies to: any service that takes both client and db and writes with
db on behalf of an API or MCP caller.
Context: Merging origin/main into a branch that had renamed cardTransaction
→ charge and added three reimbursement* tables, after main moved RLS into the
declarative manifest (packages/database/src/authz/).
Problem: Nothing in the textual merge mentions the manifest, so the merge looks
clean and the branch's own migrations still create correct policies. The breakage
surfaces later and in three different places: crbn migrate aborts with authz rules that do not apply: cardTransaction: relation "public.cardTransaction" does not exist (the manifest still declares the OLD name), authz check reports the
new tables as unmanaged, and @carbon/database's migration.test.ts fails in CI
on unshipped because production reaches RLS only through a generated migration —
deploy does NOT run authz sync (nothing in ci/src/migrations.ts or
.github/workflows/ calls it). A branch that renames a table also strands its
baseline.json entry, which must NOT be regenerated.
Rule: When a branch renames or adds a table, treat packages/database/src/authz/manifest.ts
as part of the schema change: rename/add the entry, then
pnpm --filter @carbon/database authz migration <name> (it scopes itself to the
unshipped set — it will not sweep up unrelated drift), then authz check until it
reports 0 tables. Verify a hand-written policy and its manifest entry agree by
rendering both rather than reading them: alias (p vs h), the enum cast Postgres
adds, and an omitted WITH CHECK on UPDATE are all cosmetic, but a missing clause
is not. A two-hop parent check needs custom() — nested exists() aliases its
parent p, so the intermediate table has no name to reference.
Applies to: every in-flight worktree that adds or renames a table and then
merges main; packages/database/src/authz/**.
Context: The same merge: pnpm --filter @carbon/checks clobbers reported
function:public redefined on both sides, naming two migrations whose functions
were check_charge_* and update_receipt_line_batch_tracking — no overlap at all.
Problem: clobber.ts's patterns captured the first identifier after FUNCTION
/ VIEW, so public.foo keyed as function:public. Two unrelated schema-qualified
definitions therefore always collided, and — the half that actually matters — two
redefinitions of the SAME qualified function were never keyed by its name, so a
genuine clobber went unreported. A check that cries wolf on every merge is a check
people learn to pass with --no-verify.
Rule: Key a DB object by its OBJECT name with the schema. qualifier
discarded (public.foo and a bare foo ARE the same object — public is the
default search path). When a conformance check fires, confirm the two sides really
do name the same object before rebasing; a vague key like function:public is
evidence about the check, not about the migrations.
Applies to: packages/checks/src/clobber.ts and any future OBJECT_PATTERNS row.
Context: Immediately after that merge, crbn reset failed with
relation "cardTransaction" does not exist from assertWipeable
(datasets/wipe.ts) — a function that did not exist at the merge-base and was
added by main while this branch was renaming that table to charge.
Problem: Neither side edited the other's lines, so git merged it with no
conflict and every gate stayed green. pnpm db:check:datasets does NOT cover it:
verifyDataset seeds a SCRATCH company with wipeFirst: false, so the wipe — and
assertWipeable with it — never runs. Only a real db:seed:dev / crbn reset
reaches that path, which is exactly the step nobody runs while resolving a merge.
Typecheck cannot see it either: the table name is a string inside client.query.
Rule: After merging main into a branch that RENAMED a database object, grep the
files MAIN changed for the OLD identifier — git diff --name-only <merge-base> origin/main piped into a grep for the old name — instead of trusting a clean merge
or a green db:check:datasets. Exclude supabase/migrations/** (history),
authz/baseline.json (what production had, never regenerated) and
jobs/src/backups/renames.ts (the old→new restore map): all three are SUPPOSED to
keep the old name. Then run the seed itself. Docs count as hits too — main's new
assertWipeable paragraphs in datasets/AGENTS.md and
.claude/rules/onboarding-company-templates.md named the old table as well.
Applies to: any branch that renames a table, column or enum value and then
merges main; packages/database/src/datasets/wipe.ts above all, since no automated
gate executes it.
Never git checkout a generated file to undo a local patch — the user may have regenerated it
Context: Typechecking a new-column change in a worktree with no local database, the
generated packages/database/src/types.ts was patched by hand as a throwaway so tsc
could see the columns, then "restored" with git checkout -- …/types.ts. Meanwhile the
user had run pnpm db:migrate, which regenerated that file with the real columns.
Problem: The checkout reverted the user's regeneration to HEAD, silently leaving the
repo with types that no longer matched the live schema (the Deno copy,
functions/lib/types.ts, was untouched, so the two outputs disagreed). The first symptom
was a wall of Duplicate identifier errors from re-applying the throwaway patch on top of
the regenerated file.
Rule: Before reverting any generated file, git diff it and confirm the only changes
are yours. Prefer regenerating (pnpm generate:types, needs the local stack) over a
checkout; if there is no stack, keep the throwaway patch in a scratch copy rather than the
tracked file.
Applies to: packages/database/src/types.ts,
packages/database/supabase/functions/lib/types.ts,
apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json, any generated artifact.
A submit button that stays live is a duplicate-write engine
Context: Finalizing quote Q000699 emailed the customer the same PDF three times within
one minute, same recipient list each time. The finalize action evaluates sales rules across
every line, renders a PDF, uploads it, writes a document row, flips the quote to Sent,
renders two email bodies and signs an attachment URL before it triggers the send — seconds
of wall time, during which QuoteFinalizeModal's Finalize button was enabled and not even
spinning (isDisabled={loading}, where loading was the modal's own data-fetch flag).
Problem: Three layers of the same defect, and only the first is about a button.
(1) fetcher.submit aborts the previous BROWSER request; the server action it started runs
to completion regardless, because nothing in a route action reads request.signal. So N
clicks are N complete sets of side effects. The guard had existed as onSubmit={onClose}
(the modal unmounted before a second click was possible) and was dropped in e59a9e26e2
when closing moved to useRuleViolations({ onSuccess: onClose }) — correct on its own, since
violations must be able to reopen the modal, but nothing replaced the guard.
(2) @carbon/react's Button left isLoading out of the DOM disabled attribute while
useShortcutKeys already treated it as disabling — so a spinning button refused Enter but
still took a mouse click, and every call site guarding a submit with
isLoading={fetcher.state !== "idle"} was showing a spinner over a live button.
(3) fetchWithRetry replayed every method on a 5xx or a 25 s timeout. PostgREST commits
before it answers, so a retried insert is a duplicate row and a retried .rpc() re-runs a
transaction. The quoteToQuote incidents had already produced the rule — "a retry wrapper
must never blindly retry a write with real side effects and no idempotency key" — but the
fix carved out only /functions/v1/, leaving every PostgREST write still replaying.
Rule: A submit path needs a guard at each layer that can replay it. The button disables
while its own submission is in flight (<Submit>, or isLoading bound to the fetcher's
state); ValidatedForm drops a re-entrant submit so the form holds even when a button
forgets; a retry wrapper replays only idempotent methods; and a job retries only failures
that provably had no effect — for an SMTP send that means connect/greet/auth errors only,
never an ambiguous ETIMEDOUT that may have been delivered. When triaging "the operation
failed but extra copies appeared", check all four before assuming a browser double-submit.
isDisabled bound to any-old-boolean is not a guard: name the submit state.
Applies to: packages/react/src/Button.tsx, packages/form/src/ValidatedForm.tsx,
packages/auth/src/lib/supabase/client.ts (fetchWithRetry, isReplayable — both
since removed: database reads now use supabase-js's own retry, which never replays a
write, and only storage reads go through storageReadFetch),
packages/jobs/src/inngest/functions/notifications/send-{email,slack}.ts, and any
<Button type="submit"> — enforced by no-unguarded-submit (@carbon/checks).
Rows inserted in one transaction share createdAt
Context: The inspection plan editor listed features ORDER BY "createdAt". The save
RPC (save_inspection_document_atomic) creates every new feature in one transaction.
Problem: NOW() is fixed for the whole transaction, so those features tie, and Postgres
returns ties in heap order. An UPDATE writes a new tuple at the end of the heap, so the
feature someone just edited dropped to the bottom after a reload. Its neighbour then sat in
its place, and the edit read as "not saved" although the database had it.
Rule: An ORDER BY on a timestamp that a batch insert sets needs a deterministic
tiebreak (a label, a sort order, then the id). Never rely on insertion order surviving.
Applies to: any list ordered by createdAt whose rows are written together — RPCs,
Kysely transactions, insertInto(...).values([...]), seeds.
scripts/one-off/ is executed in production
Context: A codemod that added @mcp tags to service files was saved as
scripts/one-off/tag-mcp-exposure.ts — "a script run once".
Problem: That folder is a registry, not a scratch area. ci/src/migrations.ts runs
every .ts file in it against every workspace database on the next deploy and records it
in scriptRun. A source-rewriting codemod there would have been executed by the deploy
workflow.
Rule: scripts/one-off/ is only for one-time DATA migrations (see its README). A
codemod is run locally and deleted, or lives in scripts/ if it is worth keeping.
Applies to: anything added under scripts/one-off/.
A lookup table keyed by source text must be a Map
Context: The MCP generator decided "is this call a database write" with
WRITES[memberName] over an object literal.
Problem: memberName comes from the code being analysed, so x.toString() looked up
WRITES["toString"], found Object.prototype.toString, and counted as a write. Five read
tools silently left the manifest until the digest diff showed them missing.
Rule: When the key is arbitrary input (an identifier from parsed source, a column name,
a user string), use a Map/Set or Object.hasOwn, never obj[key] truthiness. And diff
the generated manifest against the previous one before trusting a generator change.
Applies to: scripts/lib/service-ast.ts, and any analyser or dispatcher that indexes a
record by a name it did not choose.
A JS array bound for a jsonb column must be stringified on the Kysely path
Context: quoteLinePrice.priceTrace (a PriceTraceStep[]) is written both through
supabase-js (PostgREST) and through Kysely (rewriteQuoteLinePrices,
saveQuoteLineWithPrices, get-method).
Problem: node-postgres and deno-postgres serialise a parameter by its JS type, not the
column's: an object becomes JSON, but an array becomes a Postgres array literal ({a,b}),
which a jsonb column rejects. supabase-js sends JSON either way, so the same row "works" on
one path and fails on the other — and typecheck sees nothing, since Json admits arrays.
Rule: On a Kysely write, JSON.stringify any jsonb value that can be an array (or a bare
string). In Deno use toJson / toJsonColumns (functions/lib/json.ts).
Applies to: every insertInto / updateTable that sets a jsonb column — priceTrace,
configuration, notes, customFields, any copied row spread from a supabase-js read.
Demo datasets state percentages the way people write them; the tier converts
Context: PricingRuleSpec.amount is documented and validated as percent points
(0–100], but tier 02 inserted it into pricingRule.amount unchanged.
Problem: the pricing engine multiplies by a fraction (price × amount), so every demo
"5% discount" was a 500% discount and drove prices to the ≥ 0 floor. It surfaced only when
the price trace showed the step — the validator checked the dataset's own convention, not
the column's.
Rule: When a dataset field and the column it lands in use different units, convert in the tier at the insert, next to a comment naming both units — and check any new percent field against how the engine reads the column, not against the dataset type.
Applies to: packages/database/src/datasets/tiers/* — pricingRule.amount, and any
other fraction-valued column (discountPercent, taxPercent, rates).
Single fetch re-runs every matched loader on every navigation
Context: A click on a BOM node under a part (/x/part/:itemId/make/:makeMethodId.data)
took 2.8 s in production. The Vercel log showed ~68 PostgREST calls for that one click; about
10 belonged to the page being opened.
Problem: React Router 7 single fetch passes defaultShouldRevalidate = true for every
GET navigation, so every reused ancestor loader re-runs unless its route exports
shouldRevalidate. The app shell (x+/_layout.tsx, ~20 queries plus an auth round-trip)
only opted out for same-pathname navigations, and the part layouts not at all. The burst is
what makes each call slow: the first concurrent wave ran ~200 ms per call, later ones 30–60 ms.
Rule (superseded 2026-10-06, see "A layout that skips its loader is only as correct as its
skip rule"): layouts no longer export shouldRevalidate; the skip was removed and slow layout
loaders are made faster instead. Data in a shell loader that does not gate
rendering is returned as a promise and read with useResolved (~/hooks/useResolved), never
awaited.
Applies to: every route with children under apps/erp/app/routes/x+ and
apps/mes/app/routes/x+ — _layout.tsx, $id.tsx with tabs, and list pages that parent a
drawer (foo.tsx + foo.new.tsx). A list loader reads the whole query string, so it passes
search: "all". A loader that reads the pathname, a cookie or a header must not use the
helper.
A @container block has no intrinsic width — it vanishes in a shrink-to-fit parent
Context: The planning grid's expanded row (PlanningActionLines) was reused inside the
order drawer, under a VStack, to list an item's suggested changes. The heading rendered and
the rows did not.
Problem: The block's root is @container (container-type: inline-size), which is
inline-size containment: the element contributes NO intrinsic width to its parent. In the
grid the Table hands it a width. VStack is flex flex-col items-start, so its children
shrink-to-fit — and a contained element's fit width is zero plus padding. The table inside
was w-full of nothing. Typecheck, lint and unit tests all pass on this; only a render
shows it.
Rule: Anything marked @container must be stretched by its parent (w-full, a block
parent, or a flex column with default items-stretch) — never placed in VStack/HStack
or any items-start/inline-*/w-fit parent without an explicit width. When moving a
component to a new host, check what the OLD host was giving it for free: width, padding
offsets (pl-[52px] lined the block up under a grid row and means nothing in a drawer) and
column widths sized for a different pane. A layout built for one host usually wants its own
variant in the next (the drawer now has its own OpenOrdersGrid), sharing only the
behaviour.
Applies to: apps/erp/app/modules/production/ui/Planning/PlanningActionLines.tsx
(PlanningActionLines vs PlanningOrderGrids.tsx), and any @container component rendered
through VStack/HStack (packages/react/src/VStack.tsx is items-start).
A write that changes nothing still costs a queue message, an Inngest event and a function run
Context: /api/inngest was the largest consumer on the ERP deployment (2026-10-01
traces). The audit handler's log was mostly "Skipping: no meaningful diff for UPDATE on
jobOperation".
Problem: The scheduler's persistChanges issued one UPDATE jobOperation per operation on
every regen, always setting updatedAt, and re-stamped status = 'Ready' on operations that
were already Ready. dispatch_event_batch() queued every one of those updates, the drainer
sent them to Inngest ten at a time, and the audit, search and embedding handlers then threw
them away. Nothing was wrong in any single place; the waste was the sum.
Rule: A bulk writer guards its UPDATE on the values it writes (isDistinctFromAny in
scheduling-engine.ts compares in Postgres, so DATE and timestamptz are matched in their own
type) rather than writing every row and bumping updatedAt. The trigger is the backstop: an
UPDATE that changes only updatedAt / updatedBy / embedding is not queued for AUDIT,
SEARCH or EMBEDDING (20261001195204). When forking dispatch_event_batch() into a new
migration, fork the NEWEST definition; the event-ignored-columns check (@carbon/checks)
fails if the filter is lost.
Applies to: packages/planning/src/scheduling/, any job or route that rewrites many rows
of a table with event subscriptions, and every migration that redefines
dispatch_event_batch().
A cached generator's inputs are everything it executes, not everything it parses
Context: The MCP manifest generator was made a cached Turborepo task with inputs
listing the service, models and types.ts files it parses.
Problem: It also EXECUTES every *.models.ts to convert the zod validators, so the
schemas depend on whatever those files import: sales.utils.ts, accounting.utils.ts,
samplingStandards, @carbon/utils. A change to one of those was a cache hit; turbo
restored the old manifest (and the old committed digest) over the working tree, and the
build bundled it. Uncached, this could not happen.
Rule: Before caching a task, list what it loads and runs, not only what it reads on purpose, and pin that list with a test against the task's real imports. If the true set cannot be named, leave the task uncached.
Applies to: //#generate:mcp in turbo.json (pinned by
apps/erp/test/mcp-manifest-cache-inputs.test.ts), and any task given inputs.
A key looked up "anywhere in the payload" finds the wrong one
Context: The API dispatcher decides whether an upsert creates or updates from the
record's id. It looked for id at the top level and then inside any nested object, to
support { job: { id } }.
Problem: { name: "x", customFields: { id: "z" } } matched the nested id, so a
create was stamped as an update and went down the service's update branch.
Rule: Read a record's key only where the record can be: the body itself or the wrapper named by the service's payload parameter. A search that descends into arbitrary objects will eventually match user data.
Applies to: resolveUpsertOperation / recordField in
apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts.
A git merge can move a doc comment onto a different function
Context: Every API tool is declared by an @mcp line in its function's doc comment.
Main inserted a new function directly under an existing doc block.
Problem: The merge was clean, but the doc block (and its @mcp line) now sat above
the NEW function, and the function it described had none. That function silently stopped
being a tool. Nothing fails: an untagged export is simply not exposed.
Rule: After merging into a branch that touches service files, regenerate the manifest and diff the tool NAMES against the pre-merge list. A name that disappears is a displaced tag until proven otherwise.
Applies to: apps/erp/app/modules/*/*.service.ts, pnpm run generate:mcp.
A supply figure that includes scrap cannot be written back as the order quantity
Context: Planning actions measure each open job against demand and suggest Decrease /
Increase. The job's supply came from openProductionOrders.quantityToReceive, which is
productionQuantity − received, and productionQuantity is the generated quantity + scrapQuantity.
Problem: Apply writes the suggested figure to job.quantity, the good units. A job of 80
with scrap 4 counted as 84 against a demand of 80: "Only 80 of 84 is required", every run, for
every job on an item with a scrap rate — and applying it changed nothing, so it came back.
An Increase was 4 too high the same way. No test covered a job with scrap.
Rule: Measure a document in the unit the action will WRITE. If the engine reads a derived
total (with scrap, with a conversion factor), either convert at the boundary or read the base
column. And when a write changes a base quantity, restate what rides on it (the scrap
allowance), as the insert path does — a patch that sets one column of a pair is the bug class
.claude/rules/supersession-system.md describes for itemScrapPercentage.
Applies to: generatePlanningActions (packages/planning/src/mrp/planning-actions.ts),
updatePlanningJob (production.service.ts), any engine that reads openProductionOrders
or openPurchaseOrderLines and writes a document quantity back.
An .in() list built from a result set has no upper bound
Context: The planning grids load the actions for the 100 parts on a page, then looked up
each action's purchase order line with .in("id", lineIds).
Problem: .in() writes every id into the URL. The list was one id per ACTION, so it grew
with the data, not the page size: 2,357 ids was a 54 kB request line and the gateway rejected
it (HTTP 431). The loader did planningActions.data ?? [], so the page rendered every part
with no actions — indistinguishable from "nothing to do". Demo data and hand-made test parts
(a few actions each) never came near the limit; it took load data to see it.
Rule: An id list for .in() must be bounded by something you control (the page size), and
chunked when that bound is large — about 100 ids per request (fetchAllByIds in
@carbon/database does the chunking and the paging). When the related rows hang off
a foreign key, embed them in the first read instead of looking them up afterwards. And a
loader never swaps a failed read for an empty list: log it and throw.
A list the USER builds (the ids of a bulk selection: Apply, Dismiss, Assign) has no bound at
all, and chunking a WRITE breaks its atomicity — a claim that lands in chunk 1 and fails in
chunk 2 leaves rows claimed with nothing applied. Send such a list through Kysely instead:
where("id", "in", ids) binds the ids as parameters, one statement, no URL, no max_rows.
The same bulk Apply did this over PostgREST in five functions and would have failed whole on a
page of busy parts.
Applies to: getPlanningActions and the planning action worklist writes in
apps/erp/app/modules/production/production.service.ts, the planning loaders and
planning.update routes (x+/purchasing+/planning*.tsx, x+/production+/planning*.tsx), and
any "read rows, then .in() their ids" enrichment.
useNumberFormatter() with no argument is a new formatter on every render
Context: Opening or closing the order drawer on the planning pages stuttered. The drawer itself was cheap; the table behind it was the cost.
Problem: react-aria memoizes the formatter on the options OBJECT
(useMemo(() => new NumberFormatter(locale, options), [locale, options])), and the default
options = {} is a new object on each call. So useNumberFormatter() returns a new formatter
every render. It was a dependency of the table's columns memo, so every render rebuilt the
columns; TanStack then sees new cell functions and React REMOUNTS every cell, and the
shared Table re-measures its column widths. Opening the drawer re-rendered the table six
times through fetcher state — 1,824 DOM nodes replaced, six main-thread blocks of 90–220 ms.
With a stable formatter: zero nodes replaced, and the drawer shows in ~100 ms instead of ~220.
Rule: A value that feeds a useMemo/useCallback dependency list must be stable. Pass
useNumberFormatter a module-level options constant (or use the @carbon/utils formatter
hooks), never the bare call. When a table feels slow, count DOM nodes replaced in its
tbody during the interaction before optimizing anything else — a non-zero count on an
interaction that changes no data means the columns are being rebuilt.
Applies to: PurchasingPlanningTable.tsx, ProductionPlanningTable.tsx (fixed), and the
other ERP files that still call useNumberFormatter() bare — it only costs where the
formatter reaches a memo dependency list (InventoryTable, TrackedEntitiesTable,
JobMaterialsTable, DemandProjectionTable, JobOperationStepRecordsTable are the
candidates to check).
A drawer rendered as {item && <Drawer />} cannot animate closed
Context: The planning order drawer slid in but vanished on close.
Problem: Three things each removed it before a closing animation could run. The tables
rendered it as {selectedItem && <Drawer />} and closed it by clearing selectedItem, so
it left the DOM in the same render. The shared Drawer panel only had a slide-IN. And Radix
keeps a closing dialog mounted only while the element its portal wraps is animating — that
element is DrawerPortal's positioning div, which had no animation, so even a mounted
drawer with an exit animation on its panel was removed at once. Adding the exit classes to
the panel alone changed nothing; the frame-by-frame trace still showed zero closing frames.
Rule: A drawer that should animate closed stays mounted and is driven by open; keep the
record it shows until the next open (useDrawerItem), and key it per open so each open
still starts fresh. When a Radix exit animation does not play, check every element between
the portal and the animated node — each Presence looks only at its own child. Verify with
a trace of data-state and getBoundingClientRect() per frame, not by eye.
Applies to: packages/react/src/Drawer.tsx (portalVariants + sheetVariants closing
durations must match), useDrawerItem (apps/erp/app/hooks), both planning tables, and the
other state-driven drawers that still unmount on close.
A cast that silences excess-property errors hides failed writes
Context: supabase-js 2.117 types reject keys a table does not have (RejectExcessProperties). The upgrade wrapped ~75 failing write payloads in unchecked() (a cast to never) to get typecheck green.
Problem: About 30 of those were typed payloads (a zod validator spread into an insert/update) carrying fields the table lacks: item.shelfLifeCalculateFromBom, ability.name, quote.notes, salesOrder.promisedDate, batchProperty.batchPropertyGroupId, and more. PostgREST rejects any unknown column with PGRST204, so every such write failed whenever the field was present, and itemValidator's always-present checkbox made the BoM explorer's item edit (api+/item.$type.ts → updateItem) fail on every save. The cast had removed the only warning. The 2.80 types never rejected excess keys, so these were latent all along.
Rule: Never cast a typed payload past the table's type. When the compiler names an extra key, destructure it out at the write, where every caller is covered, and say where the value actually lives. unchecked() is only for a column or table chosen at runtime ({ [field]: value }, .from(table)). To list every extra key at once rather than one per error, probe with Exclude<keyof Payload, keyof Database["public"]["Tables"][T]["Update"]>.
Applies to: every {module}.service.ts write, MES services/*.service.ts, packages/utils/src/object.ts (unchecked).
A function redefined by forking its last migration picks up whatever that fork did
Context: Database functions were changed by copying the newest definition into a new migration and editing it. create_audit_log_table was forked several times; one fork made its existing-table branch re-attach the append-only trigger and re-run secure_audit_log_table unconditionally, and insert_audit_log_batch calls it on every write.
Problem: CREATE TRIGGER fires PostgREST's pgrst_ddl_watch event trigger, which reloads the schema cache. With one audit table and one search table per company that reload took 10-13 s in production, and every request with an embed waited for it: 480+ reloads a day, each one stalling joins for every company. No test or review could see it, because each fork looked like a small diff against a file nobody reads end to end. dispatch_event_batch lost its composite-key pairing the same way once.
Rule: A function that changes more than once is authored as a single file, not as a chain of forks. The event system's functions live in packages/database/src/event-system/functions/<name>.sql; edit the file and run pnpm --filter @carbon/database authz migration <name>. A function on a write path must not run DDL: check the catalog first and only repair what is missing (audit-log-no-ddl-on-write.test.sql asserts the trigger and policy oids do not change across writes).
Applies to: packages/database/src/event-system/functions/, packages/database/src/authz/helpers/, no-authz-ddl-in-migrations (@carbon/checks).
Work a request does not await is frozen with the instance on Vercel
Context: Work-event capture (PostHog) and the GTM forward were started and not awaited, so the response would not wait for them.
Problem: A Vercel function instance is frozen once its response is sent. The unawaited call stopped mid-flight and finished only when the next request woke the instance, so traces showed analytics calls of 10 s and more, and on an instance that was never reused the event was lost. request.signal does not help either: without supportsCancellation it never aborts on Vercel.
Rule: Anything a request leaves running goes through async.background(task, onError) from @carbon/utils. Each app registers the host's waitUntil once with async.onBackground in entry.server.tsx, which keeps the instance up until that work settles. Never a bare unawaited promise, a void IIFE, or a .then chain.
Applies to: apps/{erp,mes}/app/entry.server.tsx, packages/lib/src/telemetry/capture.ts, packages/stripe/src/stripe.server.ts, any new fire-and-forget call.
React Router's instrumentation API can observe a request, not change it
Context: The request-id, access-log and request-context middlewares looked like candidates to move into instrumentations, to shorten the middleware chain.
Problem: In React Router 7.18 an instrumentation wrapper receives a read-only view: the request is { method, url, headers.get } with no signal and no clone(), the context exposes only get, and the result carries only statusCode and meta. It cannot set a response header, open an AsyncLocalStorage scope around the handler, or read the body, which is everything those middlewares do.
Rule: Instrumentation is for spans and measurements. Anything that sets a header, provides context to downstream code or reads the request stays a middleware; merge middlewares into one (requestMiddleware) instead of moving them. A middleware's own cost is recorded by timedMiddleware as carbon.middleware.<name>.ms, not by a span, because a middleware span contains everything it calls.
Applies to: packages/logger/src/middleware.server.ts, packages/logger/src/tracing.server.ts, both apps' root.tsx.
A limiter must hand a freed slot to the next waiter, not decrement and let it race
Context: async.limit first released a slot by decrementing the active count and waking the first queued call.
Problem: The woken call resumes a microtask later. A call made in between saw a free slot, took it, and the woken call then incremented too: more than concurrency ran at once, and under steady load a queued call could be overtaken indefinitely.
Rule: When a slot frees and a call is queued, pass the slot to it directly and leave the count unchanged; decrement only when the queue is empty. A queued call never increments. Test it by starting a new call in the same tick a running one finishes and asserting the queued one runs first.
Applies to: packages/utils/src/async.ts (limit), any hand-written semaphore.
Copying child rows onto a new record can make that record undeletable
Context: A new item revision now inherits the source revision's supplier parts and their
price breaks (copyItemPlanningAndPurchasing, called by createRevision). A change notice
discards its draft revision by deleting the draft item.
Problem: supplierPart.itemId → item is ON DELETE CASCADE, but
supplierPartPrice → supplierPart is ON DELETE RESTRICT. An item delete therefore cascades
into a supplier part that a price break refuses to let go, and the whole delete fails with
23503. Before the copy, a fresh revision had no supplier parts, so nothing exercised that
path; after it, every revision of an item with price breaks carries the blocker: the Item
Master delete was refused, and the change notice's draft discard ignored the delete's error,
so the draft would have survived silently. Reading the migrations for the table being copied
was not enough; the constraint that mattered sat on its child.
Rule: Before copying rows onto a record, list the delete rule of every FK that points at
the copied tables (pg_constraint.confdeltype, or grep REFERENCES for the table name) and
walk every path that deletes the parent. A RESTRICT/NO ACTION child turns a copy into a
delete blocker. Either delete the child first on that path, in the same transaction as the
parent so a refused parent delete does not lose the child, or change the rule in a migration.
And a delete whose failure the caller ignores is not a delete: return the error.
Applies to: apps/erp/app/modules/items/items.service.ts (createRevision,
deleteItemsWithPriceBreaks, deleteItem, discardChangeNoticeDrafts,
deleteSupplierPart), and any copy/duplicate of supplierPart.
"Come back here" must carry the query string
Context: Notification emails link to /api/link?event=…&documentId=…&companyId=…, and requireAuthSession sends a request away and back for a token refresh, login, MFA or idle unlock.
Problem: getCurrentPath returned pathname only, so every one of those round trips came back to a bare /api/link, which has nothing to resolve and redirects to the home page. The link itself was correct, and it worked on a second click (the token was fresh by then), so it read as an email bug. The token-refresh branch hit anyone idle for longer than the refresh threshold, which is the normal state of someone arriving from an email.
Rule: A "return to where you were" target is pathname + search, never pathname. When it is passed on inside another URL, encode it (encodeURIComponent / URLSearchParams), or its own & splits it. Test the round trip with a URL that has a query string. Drop React Router's _routes param from it, and only when present: middleware sees that param (loaders do not), a page URL that carries it limits which loaders later data requests run, and searchParams.delete re-encodes the whole query even when it removes nothing. Whatever sends the target on must be matched by something that reads it: three of the four callbacks ignored the redirectTo their login page sent.
Applies to: packages/auth/src/utils/http.ts (getCurrentPath, makeRedirectToFromHere), requireAuthSession / refreshAuthSession, every app's login.tsx callback URL and the callback.tsx that consumes it.
A resolve.alias stub reaches the server bundle too
Context: Both apps aliased unpdf/pdfjs to a throwing stub to keep unpdf's 1.5 MB engine out of the browser bundle, where react-pdf's pdfjs-dist is used instead.
Problem: A top-level resolve.alias applies to every Vite environment. On the server unpdf/pdfjs is the only PDF engine, so every deployed document extraction (purchase invoice, sales RFQ) failed with "Serverless PDF.js bundle could not be resolved". Dev and vitest passed: dev leaves unpdf external, so Node resolves the real module and the alias never applies.
Rule: A stub that exists to shrink the client bundle goes through clientOnlyAlias (@carbon/dev/vite), never resolve.alias. Verify a server-side dependency change against a bundle built with ssr.noExternal: true, not against the dev server.
Applies to: apps/{erp,mes}/vite.config.ts, app/ssr-shims/, packages/dev/vite.js.
A published schema default is a promise the server has to keep
Context: API and MCP input schemas are generated from the form validators, whose .default(0) was written for a form that submits every field. The dispatcher applied none of them.
Problem: A caller reading taxPercent: default 0 leaves the field out and expects 0. On a read typed from a validator's output that crashed (state: {} on a pivot); on an update, filling it would overwrite a stored value the caller never mentioned. And a default that looked safe to fill was not: list reads published limit: default 100, but the service pages only when it is handed a limit, so filling it would have cut every unpaged list read to 100 rows.
Rule: A default is filled or it is not published (defaultsPolicy / publishDefaults): always for a read, a create or an action, on create only for an upsert, never for an update. Before publishing or filling one, read what the service does when the field is absent, and compare with the column's own database default.
Applies to: scripts/lib/service-metadata.ts, apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts, any validator default that reaches an API schema.
Every sales invoice needs an opportunity
Context: A sales invoice's documents, including the PDF written when it is posted,
live under {companyId}/opportunity/{opportunityId}/. insertSalesInvoice and
upsertSalesInvoice mint an opportunity and convert copies the sales order's, but
salesInvoice.opportunityId is nullable.
Problem: Rental billing inserted invoices with opportunityId: null. The invoice's
documents card crashed on opportunity.id (shown as "Couldn't load documents", since
DeferredFiles catches render errors too), and posting wrote the PDF to a literal
opportunity/null/ folder.
Rule: Any new code path that inserts a salesInvoice (or salesOrder / quote)
creates an opportunity for it in the same transaction. Nullable in the schema does not
mean optional in the app.
Applies to: apps/erp/app/modules/sales/sales.service.ts, any Kysely/server-function writer
of salesInvoice; backfilled by 20261006220901_sales-invoice-opportunity-backfill.sql.
A new FK on a busy table breaks bare PostgREST embeds of it (TS2589)
Context: The contracts migration (20261006221301_contracts.sql) gave salesInvoiceLine four new FKs (customerContractId, customerContractLineId, customerContractInvoiceLineId, projectId).
Problem: After generate:types, the ERP typecheck failed with TS2589 ("type instantiation is excessively deep") in four files that the change did not touch. Each did a bare embed such as .select("salesInvoice(id, invoiceId)") from salesInvoiceLine. More relationships on the table make the inference of a bare embed too deep. A @ts-ignore would hide it, but the next new FK moves the error to another file.
Rule: When you add a FK to a table that other code embeds from, name the FK in every embed of its parent: salesInvoice!salesInvoiceLine_invoiceId_fkey(...). Run the scoped erp typecheck after generate:types, before you commit the migration. Fix the cause at the embed by naming the FK (fix commit 5b26a095dd). Use @ts-ignore (the TS2589 lesson above) only for an embed that already names its FK.
Applies to: any migration that adds a FK column to salesInvoiceLine, salesOrderLine, jobMaterial or another widely embedded table; the PostgREST selects in apps/erp that embed from it.
A schedule computed live has no row ids until the first edit writes it
Context: An unedited Draft contract has no customerContractInvoice rows. The loader computes the invoice schedule from the lines with the pure planner (@carbon/database/contract-schedule). The first edit writes the rows (plan decision 2).
Problem: The page sent the edit with the ids of computed rows that were not in the database. The server function wrote the schedule, then looked up those ids, found nothing, and refused the edit. So the first edit of every Draft failed. No test covered an edit from the computed state.
Rule: When a page shows rows that the server computes and does not store, give each row a reference by position, not an id. Contracts use planned:<invoiceDate> for an invoice and planned:<invoiceDate>:<lineId>:<periodStart>[:adjustment] for a row. The server writes the rows first, then resolves each reference against them. Test the first edit from the computed state with a database test, not from stored rows (contract-lifecycle.test.ts, fix commit 56fa0f7b8e).
Applies to: post-customer-contract edit-schedule, ContractInvoiceGrid / ContractAmountsModal (and ContractRevenueGrid for the revenue plan), and any future editable preview that persists on first edit.
Two sessions in one worktree share every uncommitted file
Context: Two parallel sessions worked in the same Conductor worktree: one on contracts Phase B, one on hardening the period runs. Both edited accounting.server.ts, propose-revenue-recognition-run/index.ts and the accounting AGENTS.md.
Problem: Each session's uncommitted edits sat in the same files as the other's. Neither could commit a file whole, so every commit needed hunk-level staging, and a doc written by one session described the other's half-finished code.
Rule: Before a task, run git status and treat any change you did not make as foreign: stage only your own hunks and never stash, reset or check out over them. For a long task, ask for an isolated worktree (isolation: "worktree") instead of sharing one.
Applies to: Any session that starts in a worktree with uncommitted changes; parallel agents dispatched into the same checkout.
A prepare script that edits git config reaches every worktree
Context: Replacing husky with simple-git-hooks, prepare unset core.hooksPath and installed hooks. It ran on every pnpm install in a worktree.
Problem: Worktrees share one .git. The unset removed the main checkout's core.hooksPath and simple-git-hooks wrote into the shared .git/hooks, so checkouts still on husky skipped their hooks without a word. The desktop app also sets core.hooksPath at WORKTREE scope, which a plain git config --unset does not touch. simple-git-hooks additionally deletes every hook it does not manage unless preserveUnused is set.
Rule: Treat a lifecycle script that touches git config or .git/hooks as a change to every checkout of the repository. Use pnpm install --ignore-scripts while such a branch is unmerged, clear both the local and the worktree scope, and set preserveUnused: true.
Applies to: root package.json (prepare, simple-git-hooks), scripts/git-hooks/.
scripts/one-off/ is a registry, not a folder of leftovers
Context: A cleanup pass listed scripts/one-off/recopy-private-buckets.ts as dead because nothing referenced it by name.
Problem: ci/src/one-off-scripts.ts runs every .ts file in that folder once per database on deploy; the folder IS the reference. Deleting a file there changes what the next deploy does.
Rule: "No grep hits" does not mean dead. Before deleting a script, check whether its directory is enumerated (readdirSync, a glob in a workflow or turbo.json).
Applies to: scripts/one-off/, ci/src/one-off-scripts.ts, any repo cleanup.
A Vite plugin that reads the file name must drop the query first
Context: Lingui 6.9.0's native macro transform chooses its parser from path.basename(id).
Problem: React Router loads route modules as route.tsx?__react-router-build-client-route. The extension no longer ends the name, the file is parsed as plain JS, and the build fails with hundreds of "Expected ','" errors on import type. vitest and non-route files never show it.
Rule: When a transform plugin misbehaves only on route modules, look at the id's query. Verify a build-plugin change with a real react-router build of ERP, not with vitest.
Applies to: packages/dev/vite.js (linguiWithoutIdQuery), apps/*/vite.config.ts.
A realtime subscription to a table that is not published fails silently
Context: The ERP job page did not show an operation completed in the MES until a reload. It subscribed with postgres_changes to jobOperationStep and jobOperationStepRecord, which were never in the supabase_realtime publication, and it had no subscription to jobOperation or job at all.
Problem: Realtime accepts a postgres_changes subscription for any table name. For an unpublished table it joins, delivers nothing and reports nothing. The code looked wired and typecheck, lint and tests were all green.
Rule: Realtime goes through broadcast topics (@carbon/query). Declare a route's tables in handle.realtime; the table type is derived from event-system/attachments.ts, so a table with no broadcast handler does not compile, and no-postgres-changes fails the old API. Verify a "live" page by changing the row while the page is open, not by reading the subscription code.
Applies to: apps/*/app/routes/** handle.realtime, useRealtime, useChangedRows, .claude/rules/realtime-system.md.
getCompanyId() read an httpOnly cookie in the browser and always returned null
Context: The client cache scoped its keys with getCompanyId(), which parsed document.cookie for companyId.
Problem: That cookie is httpOnly, so JavaScript never sees it. Every key was scoped to the string "null", and an invalidation that matched on the real company id matched nothing. It went unnoticed because a company switch reloads the page and empties the in-memory cache.
Rule: Never read a session cookie from document.cookie. A value the browser needs comes from loader data: the shell layout calls setClientCompanyId(company.id) during render (@carbon/query/cache).
Applies to: packages/query/src/cache.ts, both apps/*/app/routes/x+/_layout.tsx, any new client-side tenant scoping.
A .client.ts module is empty on the server, even for a value a route only calls at load
Context: The invalidation middleware factory lived in invalidate.client.ts, next to flash.client.ts. root.tsx calls createInvalidationMiddleware(...) while the module is evaluated.
Problem: React Router replaces a .client module's exports with undefined on the server. flash.client.ts survives because root.tsx only REFERENCES its export; a factory is CALLED, so SSR died with "is not a function". Typecheck, lint and unit tests passed.
Rule: A module whose export is called at module load of a route must not be named .client or .server. After adding anything to root.tsx or a shell layout, load the page from a running dev server before calling it done.
Applies to: apps/*/app/root.tsx, packages/query/src/invalidation.ts, any shared module imported by a route.
Two hooks that open the same Realtime topic close each other's channel
Context: The shell, the live lists and individual components each called carbon.channel(topic) for company:<id>:<table>.
Problem: RealtimeClient.channel() returns the EXISTING channel when the topic is already open. Two hooks then hold one channel object, and the first to unmount calls removeChannel and silences the other. A customers page that declared customer while the customer list also followed it would have lost one of them at random.
Rule: One owner per topic. Listeners register in the registry in packages/query/src/useRealtime.tsx (useTopic, useTableChanges) and RouteRealtime owns the channels. Do not call carbon.channel or useRealtimeChannel for a broadcast topic directly.
Applies to: packages/query/src/useRealtime.tsx, any new realtime listener.
Chained Supabase writes in a route action are not a transaction
Context: RFQ finalize and supplier quote finalize each wrote a quote, its lines, a share link and a price list as separate client.from(...) calls in a loop, logging and skipping any that failed.
Problem: Every statement was its own PostgREST request (about 34 ms each), and a failure partway left quotes without lines or half a price list while the action still reported success. The checks that made the write safe (every line priced, the RFQ still Draft) lived in the route, so the API tool for the same operation skipped them.
Rule: A write that spans tables is a posting (a building block in its module's <module>.service.ts) with one Kysely transaction. Its preconditions are checked inside it, on a locked read of the document (forUpdate()), so a double submit and every other caller get the same answer. The route keeps only what is about the request: the form, the flash, the email.
Applies to: any route action with more than one write; finalize-purchasing-rfq, finalize-supplier-quote.
A stored copy of server data belongs to a user, not a browser
Context: The live lists (items, customers, suppliers, people) were kept in IndexedDB under <list>:<companyId> and patched from a change log.
Problem: The rows a user holds are their RLS view. The next person to sign in on that browser hydrated the previous user's rows, and patching only the changed ids never removed them. The in-memory query cache had the same hole inside one tab.
Rule: Key anything stored on the device by user as well as company, and empty the in-memory cache when the user changes (setClientCompanyId(companyId, userId)). A cache that is only ever patched needs a path that replaces it.
Applies to: packages/query/src/useLiveList.tsx, packages/query/src/cache.ts, any new client-side persistence.
A prefetch the browser cannot reuse makes the click slower
Context: Links prefetched their page's data on hover, then (2026-10-02) on press, to give the click a head start.
Problem: Single-fetch .data responses carry cache-control: max-age=0, must-revalidate and no validator, so the browser never serves the click from the prefetched response: both requests reach the server. Chrome also holds a second request for a URL until the first one's response arrives (its HTTP cache admits one writer per URL). The click's request therefore waited behind the prefetch: 781 ms against 518 ms median click-to-page in production, and two same-URL fetch calls took 572 / 923 ms where two cache: "no-store" ones took 615 / 585 ms.
Rule: A prefetch only helps if the browser may reuse its response. Give a prefetch response (Sec-Purpose: prefetch) a short private lifetime and leave every other response uncached; prefetchCacheMiddleware (@carbon/utils) does it in each app's root middleware, the fix React Router points to (remix-run/react-router#13255). Measure a prefetch by click-to-page time, not by whether the request was sent. A first fix removed the prefetch instead (6e3bdf7bc6); it worked but threw away the head start.
Applies to: packages/react/src/PrefetchLink.tsx; packages/utils/src/prefetch.ts; any <Link prefetch> or PrefetchPageLinks; a revalidation started while a navigation to the same URL is loading.
A revalidation during the navigation after a save loses the save
Context: 186 layouts export shouldRevalidate and skip a GET navigation that leaves their params unchanged. Realtime calls revalidate() 300 ms after a broadcast.
Problem: A save's own broadcast arrives while its redirect is still loading. revalidate() during a loading navigation restarts it with overrideNavigation: state.navigation, and for a fetcher submission that carries no formMethod. The restarted navigation looks like a plain one, so each layout returned false and kept its data from before the save: a new quote line was missing from the quote's explorer until a reload (2026-10-05). In single fetch defaultShouldRevalidate is true for every route on every navigation, so a predicate cannot tell a forced reload from a plain one. A first fix assumed React Router's default was false after a redirect with no cookie; logging the predicate's arguments in the browser showed the default was true and the first pass did include the layout.
Rule: Never call React Router's revalidate() directly. Import useRevalidator from @carbon/query: it holds a call made while a navigation is in flight or a fetcher is submitting and runs it when the router is idle. The no-raw-revalidator check (@carbon/checks) fails an import of React Router's. Before explaining a skipped loader, log what shouldRevalidate received: wrap the route's shouldRevalidate on window.__reactRouterDataRouter.routes and read formMethod, defaultShouldRevalidate and both URLs for each call.
Applies to: packages/react/src/hooks/useRevalidator.ts; every revalidate() call (realtime, polling timers, upload callbacks); every route that exports shouldRevalidate.
A drag re-rendered every card on the board
Context: The schedule boards (operations, dates, batches) render one sortable card per operation or job, each with a form, avatars, tooltips and a menu.
Problem: A drag stuttered: with 82 cards, six frames of a 90-frame sweep took over 100 ms. Two causes. dnd-kit re-renders every useSortable consumer when the drop target changes, and the hook sat inside the card, so every card's whole body rendered each time. And useSensor(KeyboardSensor, { coordinateGetter }) passed a new options object on every render: dnd-kit memoizes the sensor on it, so every draggable got new listeners, which defeats memo on anything that takes them.
Rule: A sortable card is a thin shell that calls useSortable and a memoized body that takes plain props (sortableCardProps in Schedule/Kanban/cardShell.ts). useSensor options are a module constant (no-inline-sensor-options check). A context every card reads must have a stable value. To find what re-renders, count renders per component during a scripted drag; do not guess.
Applies to: apps/erp/app/modules/production/ui/Schedule/Kanban/**; any dnd-kit board or list with more than a few dozen items.
Lingui: plural() inside a memo(…) component calls the global i18n
Context: The jobs table's bulk-release toast needed "Released 1 job" / "Released N jobs". The table is memo((props) => { … }), and the toast text was written as t`${plural(count, { one: "Released # job", other: "Released # jobs" })}` with t from useLingui() and plural from @lingui/core/macro.
Problem: Lingui 6.9.0's macro transform folds a nested plural() into the surrounding t only when the component or hook is a function declaration or a plain const X = () => …. When the function is an inline ARGUMENT of a call (memo((props) => …)), the plural() is expanded on its own into i18n._(…) on the global @lingui/core instance, and the outer t becomes {0} with that call as its value. The global instance is never activated here (see .claude/rules/i18n-lingui-system.md), so the string throws "Attempted to call a translation function without setting a locale" the first time it is built. Typecheck, Biome and lingui:extract all pass: the catalog shows a normal ICU plural msgid. Only the compiled output shows it.
Rule: Do not call plural() (or select()) from @lingui/core/macro inside a component passed inline to memo(…) or any other call. Use <Plural> in JSX. For a string (a toast), either build it in a function-declaration hook (function useX() { const { t } = useLingui(); return (n: number) => t${plural(n, …)}; }), or choose between two whole t phrases (n === 1 ? t`Released 1 job` : t`Released ${n} jobs` ) — both phrases are extracted and translated, but a locale with more plural forms gets only two. When in doubt, read the compiled module (Vite transformRequest on the file) and check for an import of i18n from @lingui/core.
Applies to: every memo(…) component in apps/{erp,mes}/app and packages/{react,form}/src (most ERP tables); any new use of plural / select from @lingui/core/macro.
A row stayed off a screen only because a column happened to be null
Context: The MES Work Centers board, the ERP Priority board and the API read get_active_job_operations_by_location. Both boards group operations into work-center columns.
Problem: An Outside Processing operation showed up on the MES board for an operator to start (2026-10-05). The function never filtered on operationType; subcontracted operations stayed off the boards only because they usually have no work center, so they had no column. The work center came back two ways. The operation forms hide the Work Center field for Outside Processing, and a hidden field is omitted from the submit, not cleared, so an update left the work center from the operation's earlier in-house type. Batching was the second way: get_batchable_operations offered outside operations, and releasing a batch writes the batch's work center onto every member.
Rule: Filter on the fact that decides whether a row belongs, never on a column that only usually agrees with it. When a type makes a field meaningless, clear the field in the one function every writer goes through (normalizeOperationSourceIds), because hiding the input does not clear it. Hiding a row from a list is not a gate: refuse it in the routes that open and start it too.
Applies to: get_active_job_operations_by_location; get_batchable_operations and the batch-operations assertEligible; the MES operation, start and event routes; any form that hides a field by type; any list whose visibility rests on a NULL.
State seeded from loaded data is a copy that nothing updates
Context: A route's components stay mounted when only its params change, and loaded data changes under a mounted component constantly: a save's revalidation, a realtime reload, a layout that reloads after its page has mounted.
Problem: useState(valueFromLoaderData) reads the value once. Two bugs came from it (2026-10-06). The quote summary summed its totals from lines copied into state at mount, so a deleted line stayed in the subtotal until a reload. And a notes editor seeded from record A stayed mounted on record B: B showed A's notes, and the first keystroke saved A's text into B. An audit of 467 seeded useState calls found 17 confirmed cases. Reloading every layout on every navigation had hidden most of the first kind, not fixed it.
Rule: Do not copy loaded data into state. A value computed from the data is computed during render (useMemo). The user's choices over the data are the only state, combined with the current data during render (selectQuoteLines). A draft the user edits is fine as state because the page it lives in remounts for another record: every route under /x renders RecordOutlet (@carbon/react), never a plain <Outlet>. Do not write an effect that copies the data into state again. Checks: no-bare-outlet and no-state-copy-of-loader-data (@carbon/checks; the second sees only a hook result used by name in the same file, not a copy seeded from a prop).
Applies to: every component that reads useLoaderData, useRouteData or props that come from them; every route with a param in its path.
A layout that skips its loader is only as correct as its skip rule
Context: 186 layouts exported shouldRevalidate and skipped a GET navigation that left their params unchanged (isUnaffectedByNavigation, 2026-10-01), to save a layout loader run on each click.
Problem: The rule inferred "nothing changed" from formMethod. React Router passes a fetcher's submission to the first navigation after it only, so a delete that redirected to a record's bare URL, whose index route redirects again, arrived as a plain navigation and every layout kept its data (2026-10-06). An earlier patch had fixed the same blind spot for a revalidation restarting a navigation. 154 of the 186 layouts also declared no realtime tables, so another user's change did not show until the record changed. A module-level "a save happened" flag closed the redirect case and was rejected: one package set it, another cleared it, a third read it.
Rule: Layouts do not skip their loaders. Do not export shouldRevalidate from a layout to save a loader run; make the loader cheaper instead (one query, the direct connection, shared work through middleware context). The root and the app shell are the only exceptions. To see which loaders a navigation asked for, read the _routes query of its .data request. Estimated cost of removing the skip, from production traces: 100 to 300 ms on a click that used to skip, until the dozen slow record loaders are optimised.
Applies to: every layout route; packages/utils/src/revalidate.ts; the record loaders (purchase-order+/$orderId, supplier+/$supplierId, sales-invoice+/$invoiceId, part+/$itemId, sales-order+/$orderId, quote+/$quoteId).
A restore told the change log but not the open tabs
Context: Backup restore and template revert reload a company through wipeAndLoad with triggers off (session_replication_role = replica). The live lists (items, customers, suppliers, people) are kept in the browser and updated from broadcasts; the change log (tableChange) is what a tab reads when it loads or reconnects.
Problem: With triggers off nothing was broadcast. wipeAndLoad wrote a reset row to the change log, but an open tab only reads the log when a broadcast tells it to, or once an hour. After a demo template was reverted and applied again, a tab's part picker held the reverted parts next to the new ones, and creating a job with a reverted part returned 404 (2026-10-06, production). The first reproductions missed it because they applied a template (triggers on), which broadcasts correctly.
Rule: A writer that turns triggers off does both halves itself: a null-rowId row per CHANGE_LOGGED_TABLES entry, and a null-ids broadcast on every REALTIME_TABLES topic of the company, inside the same transaction. When a stale client list is suspected, compare the ids in window.clientCache.getQueryData(["live", companyId, name]) with the database before reading code.
Applies to: packages/jobs/src/inngest/functions/tasks/company-restore.ts (wipeAndLoad); any new job that sets session_replication_role.
macOS silently replaces a web notification that reuses a tag
Context: Browser push notifications (apps/erp/public/push-worker.js) passed each notification's tag (job-assignment:<id>, carbon-test) to showNotification, so a second push about the same thing would replace the first instead of stacking.
Problem: On macOS the browser hands the tag to the OS as the notification's identifier, and the OS replaces a notification with the same identifier silently: no banner, only an updated entry in Notification Center. The first test arrived while banners were still off, and every later test replaced it without a sound, so push looked broken although every send returned 201 (2026-10-08). renotify: true did not change it. The cause was only visible in the macOS log (log show --predicate 'process == "usernoted"'): updatedExisting: true.
Rule: Never pass a reused tag to showNotification when the user must see the repeat. Close the older notifications yourself (registration.getNotifications(), match on notification.data.tag), then show the new one with no tag, so it gets a fresh identifier. To debug a push that "does not arrive", read the send's status code first, then the OS notification log, before changing code.
Applies to: apps/erp/public/service-worker.js (was push-worker.js); any future service worker or Notification API caller.
A new key in an Inngest step's return breaks runs in flight at deploy
Context: The notify function's step filter-recipients-by-preference returned { emailRecipientIds, slackRecipientIds }. Browser notifications added pushRecipientIds to the same step, under the same step id, and the code after it read pushRecipientIds.length (2026-10-08).
Problem: Inngest replays a completed step from its memoized output. A run that started before the deploy and resumes after it gets the OLD output, with no pushRecipientIds, so .length throws and the notification fails. Typecheck cannot see it: the type describes the new code, not the stored output. Self-review caught it before merge.
Rule: When a step's return grows a key, read that key with a default (pushRecipientIds = []) and comment why, or rename the step id so old runs re-execute it (only when the step is idempotent). Never assume a memoized step output has the current shape. (The pushRecipientIds key was removed again later, when push stopped having a per-topic switch; the example stays as the pattern.)
Applies to: every step.run in packages/jobs/src/inngest/functions/** whose return shape changes.
A notification click on an uncontrolled tab opens nothing
Context: push-worker.js handled notificationclick with clients.matchAll({ type: "window", includeUncontrolled: true }), then focus() and navigate() on the first Carbon tab (2026-10-09).
Problem: WindowClient.navigate() rejects for a tab the worker does not control: a tab opened before the worker was installed, or a hard-reloaded one. The rejection ended the click handler, so the click opened nothing. No error reached the page.
Rule: Call matchAll({ type: "window" }) without includeUncontrolled when you will call navigate(). Focus first, because the click allows focus for a short time only. Wrap the focus and the navigation in try, and call clients.openWindow() when either fails or no tab exists.
Applies to: apps/erp/public/service-worker.js (was push-worker.js); any service worker that navigates a client.
A push service's 401 or 403 does not mean the subscription is dead
Context: After the VAPID key changed, WNS answered 401 for a subscription made with the old key, and FCM answers 403 for the same case. Deleting the row on 401/403 was proposed so such rows stop failing (2026-10-09).
Problem: Apple's push service answers 403 when it refuses our own token (BadJwtToken, for example a contact address it does not accept). That refusal hits every Safari subscription at once. A delete on 403 would remove every Safari row on each push, the page load would save them again, and no Safari user would ever get a push, with no error anywhere.
Rule: Delete a subscription only on 404 or 410. On 401 or 403, log a warning with the push service's body and keep the row (pushDeliveryOutcome → rejected). An old-key row is replaced on the browser's next page load or ages out.
Applies to: packages/jobs/src/inngest/functions/notifications/push-outcome.ts, send-push.ts; any Web Push sender.
A generated avatar is a seed, so the library version decides the face
Context: user.avatarUrl stores a generated avatar as dicebear:<style>:<seed>[:<rrggbb>] (packages/utils/src/avatar.ts). The browser draws it with DiceBear every time it renders (packages/react/src/utils/generatedAvatar.ts). Nothing about the picture is stored, only the seed.
Problem: A new DiceBear major version can draw a different face for the same seed. The move from version 9 to 10 (2026-10-08) changed every existing avatar, and nothing in the database showed it. A style removed from GENERATED_AVATAR_STYLES makes its stored values unparseable, so those avatars fall back to initials without an error.
Rule: Pin @dicebear/core and @dicebear/styles to exact versions, never a range. Treat a DiceBear upgrade as "every user's avatar may change", and compare renders of fixed seeds before and after. Only add to GENERATED_AVATAR_STYLES; the Record type of STYLE_LOADERS makes a style without a loader a type error.
Applies to: packages/react/package.json (DiceBear versions), packages/utils/src/avatar.ts, packages/react/src/utils/generatedAvatar.ts.
A library that every page renders must not be imported statically
Context: Avatar (@carbon/react) is in the shell of every app. It renders generated avatars with @dicebear/core.
Problem: A static import { Avatar, Style } from "@dicebear/core" put about 156 KB minified (25 KB gzipped) into the main bundle of the ERP, MES and academy, on every page, whether or not a generated avatar was shown (found in self-review, 2026-10-08). Typecheck, tests and Biome all passed. Only a bundle measurement showed it.
Rule: In a component that every page renders, import a heavy library with import() at the point of first use, and keep only import type at the top of the file. Check with a split bundle: npx esbuild <file> --bundle --splitting --format=esm --minify --outdir=/tmp/out '--external:@carbon/*' --external:react. The entry file must stay small, and the library must be a separate chunk.
Applies to: packages/react/src/** components used in app shells (Avatar, NavRail, layout parts); any new dependency of @carbon/react.
A JSON import attribute fixes the server and breaks the browser
Context: @carbon/react loads each DiceBear style's JSON with import() (packages/react/src/utils/generatedAvatar.ts). The same code runs in the browser (the avatar picker) and on the server (the /file/avatar/:value route).
Problem: On the server, Vite leaves a dependency's import external, and Node refuses JSON without with: { type: "json" } (ERR_IMPORT_ATTRIBUTE_MISSING). Adding the attribute fixed the route. But Vite passes the attribute through to the browser's import(), and serves the JSON as text/javascript, so the browser rejected every style and the picker previews stayed grey (2026-10-08). Typecheck, unit tests and the server route all passed; only the browser saw it.
Rule: Never put an import attribute on a JSON import in code that also runs in the browser. Make the server bundle the package instead: add it to ssrNoExternal in each app's vite.config.ts (the ERP and MES lists apply to both ssr.noExternal and environments.ssr.resolve.noExternal). To check the browser side, fetch the module from the dev server (curl $ERP_URL/@fs<absolute path>) and confirm the import() call has no second argument.
Applies to: packages/react/src/utils/generatedAvatar.ts; any isomorphic code that imports JSON from a dependency.
The three.js rotate gizmo grabs whatever sits under its center
Context: The assembly path editor shows drei TransformControls (mode="rotate") on a selected waypoint, whose draggable sphere sits at the gizmo's center.
Problem: In rotate mode the gizmo adds an invisible free-rotation picker — a sphere of radius 0.7 × gizmo size (XYZE in three-stdlib controls/TransformControls.js) — centred on its object. Dragging the waypoint sphere started that free rotation as well as the drag, so one gesture moved the part and spun it at once (2026-10-08).
Rule: Never let a rotate gizmo and another drag handle share a position. Make it a mode: either the handles drag or the rings show, never both. The path editor's Move / Rotate tool is the precedent (MotionPathEditor.tsx, tool).
Applies to: any TransformControls / PivotControls placed on top of an existing pointer handle in packages/viewer.
Browser-testing the 3D assembly page: one session, restart often
Context: Driving /x/assembly/:id with agent-browser for screenshots and drags (2026-10-08).
Problem: After roughly 40 screenshots of the WebGL page the renderer reached 3 GB+, snapshots hung for over a minute, and a later revalidation failed with "Failed to fetch" plus "WebGL Context Lost". On a fresh dev server the login's Continue button also stays disabled until hydration finishes, which looks like a broken bot check.
Rule: Set AGENT_BROWSER_SESSION to the worktree's own name, agent-browser close and reopen after ~40 shots, and reload the login page once if Continue stays disabled. Drive the canvas with mouse move/down/up, not click. Radix menus ignore synthetic clicks there — move the mouse off the menu and use the arrow keys plus Enter.
Applies to: browser verification of packages/viewer features in the ERP editor; .ai/playbooks/assembly-sub-assembly-motion-path.md.
drei GizmoHelper resets camera.up after a viewcube click
Context: The assembly player shows a step's build orientation by rolling the camera (camera.up = the bench's up in the model frame, packages/viewer/src/orientation.ts).
Problem: drei's GizmoHelper writes camera.up on every frame of a face-click tween and resets it to the value it saw at mount when the tween ends (core/GizmoHelper.js). After one viewcube click the build stood upright again, and every later turn started from the wrong up.
Rule: Do not patch drei. Anything that owns camera.up must re-assert it in its own frame loop whenever it drifts outside its own animation.
Applies to: packages/viewer/src/useBuildFrame.ts (its useFrame), any code that sets camera.up under GizmoHelper or OrbitControls.
Re-applying demo data runs code a first apply never reaches
Context: A new table (customerContractInvoiceLine) got a CHECK that needs customerContractInvoiceId OR memoId. The demo datasets seed it with only the invoice.
Problem: Settings → Demo Data on a company that already had data failed with "new row … violates check constraint". The wipe that runs first nulls every nullable FK pointing at a table it clears, which emptied both columns. pnpm db:check:datasets stayed green: it applied each dataset once, to an empty scratch company, so the wipe never met a seeded row.
Rule: A seeded table whose CHECK needs one of several nullable FKs goes in PARENT_CHECK_TABLES (packages/database/src/datasets/wipe.ts). The dataset check now re-applies each dataset over itself, so this fails before commit. When a test only exercises the first run of an idempotent operation, also run it a second time.
Applies to: packages/database/src/datasets/ (wipe, verify), migrations that add CHECKs over nullable FK columns.
A migration on main can carry a timestamp ahead of UTC
Context: supabase migration new stamps a migration with the current UTC time. A migration merged to main (20261009141827_link-custom-field-type.sql) carried a time about 2.5 hours ahead of UTC, likely from a local clock.
Problem: Every migration created after the pull got an older timestamp than that file. Production's supabase db push refuses a migration that sorts before one it already applied, so the new migrations would have failed to deploy. The clobber check and every test passed; nothing local shows it.
Rule: After you pull main, compare your migrations' timestamps with the newest one on main (ls packages/database/supabase/migrations | tail). If yours sort first, rename them to sort after it, keep their order and content, and use a non-000000 HHMMSS. Re-generate a generated authz migration file first, then rename it with the rest.
Applies to: packages/database/supabase/migrations/; every branch that adds a migration.
The license-header fixer only sees files git tracks
Context: pnpm --filter @carbon/checks license-headers -- <paths> writes the SPDX header. It walks git ls-files --cached.
Problem: A new, untracked file is not in that list, so the fixer reports "0 fixed" and the file keeps no header until the spdx-license-header check fails at commit.
Rule: Run git add -N <new files> (intent to add; it records no content) before the fixer, then run the fixer with those paths.
Applies to: every new source file outside generated output.
A value two layers must agree on lives once, in the client-safe pure module
Context: The accounting enable wizard (ERP) and activateAccounting (accounting.service.ts, ported from the activate-accounting server function) both decide whether Migration Clearing totals zero. The wizard uses the answer to offer "Enable accounting". The server function uses it to refuse the enable. The wizard steps also pass the cutover date to each other in a search param.
Problem: Until 2026-10-09 each layer kept its own copy. MigrationClearingTable.tsx defined MIGRATION_CLEARING_TOLERANCE = 0.01 and isMigrationClearingZero. activate-accounting/index.ts defined a second MIGRATION_CLEARING_TOLERANCE. accounting.server.ts defined ACTIVATION_CUTOVER_PARAM. The copies matched, but nothing kept them matched. If one copy changes, the wizard offers an enable that the server refuses, or hides one that the server accepts. Typecheck cannot see a drift between two literals.
Rule: Put a value that two layers must agree on in one place: the client-safe pure module that both layers already import. Export the predicate, not only the number, so every caller compares the same way. The accounting cutover keeps MIGRATION_CLEARING_TOLERANCE, isMigrationClearingZero, MIGRATION_CLEARING_ACCOUNT_CLASS and ACTIVATION_CUTOVER_PARAM in @carbon/database/accounting-cutover (commits 38602af774, b9f897608c, f1fe2b6c81). That module reads no database, so the browser can import it.
Applies to: packages/database/src/accounting-cutover.ts; apps/erp/app/modules/accounting/ui/Activation/MigrationClearingTable.tsx; apps/erp/app/routes/x+/accounting+/activation.enable.tsx; apps/erp/app/modules/accounting/accounting.service.ts; any check that a wizard previews and a posting enforces.
A detector and the builder it feeds share one zero-value rule
Context: The accounting enable, and the "Write missing journals" repair, find legacy documents: posted on or after the cutover with no journal (packages/database/src/legacy-documents.ts). A builder then writes each document's journal (apps/erp/app/modules/accounting/accounting.service.ts). After that, the enable's re-cost (activate-accounting/recost.ts) adjusts the inventory journal pair of each outbound movement whose cost changed.
Problem: The detection and the builders used different zero rules, in both directions:
- The detection found documents that the builders write no line for: a comment-only invoice, a receipt with no received line, a return received at no cost. Such a document got no journal, so every later run found it again.
- The posting core wrote no journal for a zero-cost movement (
valueMovementskipped the journal whencost === 0). When the re-cost gave that movement a cost, it found no pair to adjust and refused with a 409.
Commit b9f897608c removed zero-value documents from the detection. Commits b9f897608c and 188a710e24 made every outbound cost row write its pair, at zero too.
Rule: Write the zero rule once and apply it on both sides. If the builder writes no line for a document, the detection leaves the document out. If a later step adjusts a line, the builder writes that line even at zero. Pin the pair with a test that runs the detection, the builder, and the detection again: the second detection must find nothing (apps/erp/test/database/activate-accounting/legacy/detection.test.ts).
Applies to: packages/database/src/legacy-documents.ts; apps/erp/app/modules/accounting/accounting.service.ts; apps/erp/app/modules/accounting/accounting.service.ts; valueMovement in apps/erp/app/modules/shared/shared.service.ts; any detect-then-repair pair.
A migration that re-scopes companies uses the company test of the migration it follows
Context: 20261008211304_reset-accounting.sql deletes the journals of every company except the demo-template companies. It finds those as the companies that hold a JE-SEED-% journal, which only tier 09 of the dataset seed writes. 20261009004448_accounting-cutover.sql (section 7) then gives the spared companies a cutover, because their history is already in Carbon.
Problem: The second migration first chose its companies by accountingEnabled = true. Only the dev CLI ever set that flag. A template applied through onboarding or Settings → Demo Data has it false. So those companies kept their Posted seed journals, but got no cutover. Their seeded Posted Opening Balance then blocked the enable wizard for good. Commit 38602af774 changed the test to the reset's JE-SEED-% test.
Rule: If migration B acts on the companies that migration A chose, B copies A's predicate. Do not use a flag that "should" mean the same thing. Before you write the WHERE, read A's predicate. Then grep every writer of any flag you plan to use instead.
Applies to: packages/database/supabase/migrations/20261008211304_reset-accounting.sql; packages/database/supabase/migrations/20261009004448_accounting-cutover.sql; any data migration that follows another data migration.
Removing a feature flag can expose a fail-open ?.data guard
Context: Before always-posting, the return shipments in post-shipment and the sales return receipt in post-receipt read the account defaults only when accountingEnabled was true. Otherwise accountDefaults was null. The journal was written under if (accountingEnabled && accountDefaults?.data && cost > 0). So accountDefaults?.data was part of the "accounting is off" test.
Problem: The always-post change removed the flag and kept if (accountDefaults.data && cost > 0). After that, the .data check only caught a failed read, and it failed open. If the defaults read failed, the post still wrote its stock and cost rows, but it skipped the journal with no error and no log. Typecheck and the tests passed. Commit b9f897608c makes both paths throw "Error getting account defaults" when the read fails.
Rule: When you remove a flag, read every condition that used the flag. A null check that meant "feature off" becomes a silent error check when the flag goes. Turn a failed read into a throw before any write. Keep only business conditions, such as cost > 0, in the if.
Applies to: apps/erp/app/modules/inventory/inventory.service.ts (return shipments); apps/erp/app/modules/inventory/inventory.service.ts (sales return receipt); any flag removal, such as accountingEnabled or a plan gate.
The pre-commit Lingui extract reads the working tree, not the commit
Context: scripts/git-hooks/pre-commit runs pnpm lingui:check when a staged file is TS, JS or .po. That script runs lingui extract --clean and then compiles. The hook then stages every packages/locale/locales/**/*.po file.
Problem: The extract reads the working tree, not the index. On 2026-10-09, commit eac7595333 ran the hook while another session had uncommitted UI edits in the same tree (PaymentApplyTable.tsx and others). The extract removed strings that the committed code still uses ("Applied amount for {0}", "Discount for {0}"). It added strings that only the uncommitted code uses ("Apply to {0}", "FX Gain/Loss"). The hook staged all 13 catalogs, with those changes, into that commit. Commit 814631c22f restored catalogs extracted from HEAD in a clean worktree.
Rule: Before you commit TS or JS, run git status. If it shows uncommitted .ts or .tsx edits that are not part of your commit, the hook's catalogs are wrong. A catalog-only commit in the same tree does not fix them, because the hook extracts again from the same dirty tree. Make the catalog commit in a clean tree:
- Run
git worktree add -b i18n-catalogs <path> HEAD. - In that worktree, run
pnpm install. - In that worktree, run
pnpm lingui:check, thenpnpm lingui:clean. - Stage
packages/locale/locales/*/*.pothere and commit. The hook now extracts from a clean tree. - In your own tree, run
git merge --ff-only i18n-catalogs. A fast-forward creates no commit, so no hook runs. - Remove the worktree and the branch.
After any commit, check its .po diff. A removed msgid that HEAD code still uses means that the extract read a dirty tree.
Applies to: scripts/git-hooks/pre-commit; packages/locale/locales/*/*.po; every workspace that more than one session edits at a time.
One Inngest send carries at most 512 KB, and a rendered email is about 17 KB
Context: notify rendered every recipient's notification email in one step, then sent all the carbon/send-email events with one step.sendEvent (2026-10-09).
Problem: One rendered NotificationEmail is about 16.9 KB, because the event carries the full HTML. Inngest accepts at most 512 KB in one send and 4 MB in one step's output. So email to about 30 recipients or more could fail the send, and about 240 filled the step. A group notification reaches those sizes; a test with one recipient never does.
Rule: Size a fan-out by its bytes, not its count. When each event carries a rendered body, render and send it in chunks (EMAIL_CHUNK in notify.ts), each chunk in its own step with an indexed id (render-emails-${index}). A new step id replays a run in flight at deploy, so a send step that changes id sends again for those runs.
Applies to: packages/jobs/src/inngest/functions/notifications/notify.ts; any job that fans out events with large payloads.
A failed COPY in a plain-text dump can swallow the rest of the restore
Context: On 2026-10-09 a crbn restore of a prod cluster backup ended with ✅. The restored database had no index, constraint, trigger or policy in public, and an empty migration ledger. The trailing migration up --include-all would then have replayed all 1,159 migrations.
Problem: The local stack's auth, storage and realtime tables come from its own service images, and they are older than prod's. Prod's storage.objects has a column (archived_at) that the local table does not have. A COPY that names an unknown column or table fails when psql parses it, so psql never enters copy mode. It then reads the block's data rows as SQL. In that data an unbalanced quote opened a string that never closed, so psql read the rest of the file as part of it. With ON_ERROR_STOP=0, nothing failed. The same drift also reaches DDL. The backup's newer storage.protect_bucket_control_columns trigger reads columns that the local storage.buckets does not have, so every bucket insert failed. Those service-schema objects survive later restores, because a restore drops only public. Separately, a Supabase backup is not one consistent snapshot: it contained payments whose journal it did not hold. So 15 foreign keys could not be validated.
Rule: Do not trust a restore that ran with ON_ERROR_STOP=0 until you verify it by name. scripts/restore-database.sh now does these things:
- It fits each non-public
COPYto the local columns, and drops the block when the local table does not exist. - It skips function definitions owned by the auth, storage and realtime admin roles. Those functions belong to the local service images.
- It checks each
publicindex, constraint, trigger and policy from the dump, and the ledger row count. It re-adds a foreign key that cannot be validated asNOT VALID. - It exits 1 on any shortfall, and
crbn restorethen does not migrate.
A ✓ that a script prints after a step that is allowed to fail is not evidence. Read the state back.
Applies to: scripts/restore-database.sh, packages/dev/src/commands/restore.ts, and any tool that loads a plain-text dump through psql.
A new record type copies its sibling's UI, not the generic archetype
Context: The lessee lease (2026-10-11) shipped a Card form on new.tsx that redirected to a 3-pane workspace, with Draft terms edited in the properties panel. Its siblings — the rental agreement and the AR contract — are set up in a full-page wizard (~/components/Setup). The user called it a big mistake, and the UI was rewritten.
Problem: The plan named the sibling for the server side (post-lease mirrors the rental functions) but not for the UI, and the design skill's "where create opens" rule sent a record with a workspace to a Card form. The setup wizard was documented nowhere, so the subagent that built the UI followed the generic rule faithfully.
Rule: Before designing a record type, name its closest sibling — the record users would call "the same kind of thing" (rental agreement ↔ lease ↔ contract; sales order ↔ purchase order; RMA ↔ supplier return) — and copy its routes and components file for file: new, $id, $id._index, the setup or detail routes, the module's ui/ components. The spec and plan state the sibling and the files copied. A deviation from it is a design decision and is asked about first. When the sibling's pattern is missing from carbon-design, add it there in the same change (Archetype J was added for this one).
Applies to: /spec-writing, /plan, carbon-design, and any subagent prompt that builds UI.
A dropped column breaks string selects that typecheck cannot see
Context: The several-assets change for lessee leases (2026-10-11) moved twelve columns from lease to leaseLine and recreated the leases view.
Problem: Typecheck passed, but the Lease Liabilities report still selected the moved columns from the view through fetchAllFromTable(client, "leases", "id, …, lesseeClassification, …"). The column list is a string, so the report would only have failed at runtime.
Rule: After a migration drops or moves a column, grep every string select of the table and its views (.select("…"), fetchAllFromTable column lists, embeds) for the old name. Do not rely on typecheck for them.
Applies to: any migration that drops, renames or moves a column.
A caller-supplied document number used to leave the counter behind
Context: Documents take their number from get_next_sequence unless the caller supplies one: a custom ID typed into SequenceOrCustomId, or an MCP / API upsert (upsertSalesOrder, upsertQuote, upsertPurchaseOrder, upsertJob, …) whose create path requires the number.
Problem: A supplied number never moved the sequence row. Once the counter reached a number an agent or a user had already used, every new document failed on the unique constraint ("Failed to insert sales order") until someone moved the counter by hand.
Rule: The counter is kept ahead in the database, not in app code: the sync_advance_document_sequence after-interceptor moves sequence.next past any number saved in the sequence's format, on insert and on a number change. A new numbered table must be added to that interceptor's CASE and given the interceptor in attachments.ts; the document-sequence-synced conformance check fails CI for a new counter that is neither covered nor in its EXEMPT_COUNTERS. Never "fix" a collision by retrying get_next_sequence.
Applies to: packages/database/src/event-system/handlers/sync_advance_document_sequence.sql, util.document_sequence_pattern, any table with a readable document number.
An entity in audit.config.ts records nothing until its tables have events: true
Context: Change notice history (the changeOrder audit entity) was empty in the History drawer even with audit logging on (2026-10-08).
Problem: auditConfig.entities.changeOrder listed its 4 tables, and syncAuditSubscriptions created AUDIT subscriptions for them. But packages/database/src/event-system/attachments.ts gave changeOrder only a statement broadcast and the 3 child tables no entry at all, so no async event trigger existed and nothing reached the event queue. Every check looked green: subscriptions present, sweeper succeeding, queue empty.
Rule: When you add an entity to audit.config.ts, give each of its tables events: true in attachments.ts and ship it with pnpm --filter @carbon/database authz migration <name>. To debug an empty audit log, first check pg_trigger for trg_event_async_* on the table.
Applies to: packages/database/src/audit.config.ts, packages/database/src/event-system/attachments.ts.
A foreign key to account must be RESTRICT, and a new one needs a merge policy
Context: The chart of accounts import (2026-10-12) re-points references when it merges accounts and deletes an account nothing uses.
Problem: journalLine.accountId and the order, invoice and supplier quote line FKs were ON DELETE SET NULL. Deleting an account with Draft or Provisional lines succeeded and silently emptied the lines' account; Posted lines only refused by accident, through the immutability trigger. The import also has to know, for every column that names an account, whether a merge may move it.
Rule: Give a new foreign key to account ON DELETE RESTRICT, and classify it in REFERENCE_POLICY (packages/database/src/account-import.ts): repoint, repoint-if-draft, repoint-if-unposted-journal or history. The apply-account-import live-database test fails until it is listed. A soft reference (no FK) goes in SOFT_REFERENCES and the apply's repointReferences.
Applies to: migrations that add a column referencing account; packages/database/src/account-import.ts; applyAccountImport (apps/erp/app/modules/accounting/accounting.service.ts) and its live test apps/erp/test/database/apply-account-import.test.ts.
Committing with the hook off skips Biome too
Context: The chart of accounts import (2026-10-12) committed with git -c core.hooksPath=/dev/null so the Lingui catalogs, which the hook stages into any commit with .ts changes, could land in their own commit.
Problem: The hook also runs lint-staged. Bypassing it skipped Biome's formatter, and a test file reached the branch unformatted. The self-review caught it, not the commit.
Rule: Before a commit with the hook off, run pnpm biome check --write on the staged files and the checks the hook would run (pnpm --silent check:manifest, pnpm --silent db:check:datasets for packages/database, pnpm --silent db:check:backups for migrations). Prefer committing the catalogs last with the hook on.
Applies to: any commit made with --no-verify or core.hooksPath=/dev/null.
RLS does not bound an MCP tool handed db; its declared permission is the only gate
Context: A 2026-10 security disclosure: an OAuth (MCP connector) token for a user with no accounting permission could create draft GL journals through inventory_createInventoryReconciliationJournal.
Problem: Two gaps stacked. The oRPC gate() skipped OAuth callers on the theory that RLS bounds them, but a service whose manifest asks for db gets getDatabaseClient(), the direct connection, which bypasses RLS. And a tool's default permission is its own module plus its verb's action, so the journal tool was gated on inventory:create while the Reconcile screen requires accounting:create. Supplier and customer bank accounts (purchasing/sales vs accounting) and return-order credits (purchasing/sales vs invoicing) had the same mismatch, for API keys as well.
Rule: Every non-session caller (API key AND OAuth) is gated per operation, OAuth on the user's live permissions in the token's company (scopesFromPermissions). When a tool does what an ERP route does, its permission must equal that route's requirePermissions: add @mcp permission where the default differs, regenerate, and pin it in OVERRIDES in mcp-tool-permissions.test.ts. Never reason "RLS will catch it" for a tool whose contextParams include db.
Applies to: apps/erp/app/routes/api+/v1+/lib/base.server.ts, apps/erp/app/routes/api+/mcp+/_index.ts, every @mcp-tagged service taking db: Kysely<KyselyDatabase>.
A constant between /** @mcp read */ and its function drops the MCP tool
Context: Cursor paging (2026-10-13) gave each paged list service an exported *_DEFAULT_SORTS constant. The list registry and the loaders read it, so it sits next to the service function.
Problem: Twice during that work, the constant went between the doc block and the function. TypeScript attaches a doc comment to the declaration directly under it, so the @mcp read tag then belonged to the constant. The generator reads the doc block of exported functions only (getJsDocs() in scripts/lib/service-ast.ts); it skips a constant that is not a function. The function silently stopped being a tool and left tool-manifest.digest.json. Typecheck, tests and the build all passed.
Rule: Put a new constant ABOVE the doc block of a service function, never between the block and the function. After you edit a *.service.ts file, run pnpm run generate:mcp. Then diff the tool names in tool-manifest.digest.json. A tool name that disappears is a displaced tag until you prove otherwise.
Applies to: apps/erp/app/modules/*/*.service.ts, apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json.
A cookie that was only ever written is not a stored preference
Context: The navigation rail's pin toggle (2026-10-13) first restored the pinned state from SidebarProvider's sidebar:state cookie.
Problem: SidebarProvider (packages/react/src/Sidebar.tsx) had written that cookie on every open/close for a long time, but no loader read it. Old sessions already held sidebar:state=true from a SidebarTrigger or ⌘B, so reading it opened the rail for users who had never pinned it.
The write was then removed (nothing reads it), so the rail always starts collapsed.
Rule: Do not start reading a cookie, local-storage key or column that code has only ever written. Its values were never a user's deliberate choice. Give the new preference a new name, or start every user from the default.
Applies to: SidebarProvider and any other write-only client state (document.cookie, localStorage) that a loader or component begins to read.
The manifest-digest hook checks the working tree, not the staged copy
Context: The trial balance PR (2026-10-13) left tool-manifest.digest.json out of a commit, thinking its diff was unrelated drift.
Problem: check:manifest regenerates the digest and compares it with the file on disk. The disk copy was the regenerated one, so the hook passed while the commit carried the stale digest. Only running the check against the committed version showed "2 changed".
Rule: Never leave a regenerated tool-manifest.digest.json unstaged on the assumption that it is drift. Run pnpm --silent check:manifest with the committed copy restored; when it fails, the regenerated digest belongs in the commit.
Applies to: apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json, scripts/git-hooks/pre-commit.
An item left out at the accounting cutover must close in its own sub-ledger
Context: Migration Clearing's Ignore (2026-10-13): an invoice another system already settled is left out of the opening journal.
Problem: Dropping an item from the opening journal alone leaves its document open. The AR/AP readers fall back to the invoice total when no control line exists, so the invoice stays in aging, the tie-out shows a permanent variance, and a later payment is refused ("Target is missing its original control account"). And an invoice Carbon itself settles on or after the cutover posts a payment journal that credits the control account, which then has no opening line to credit.
Rule: Leave an item out only when the sub-ledger can say it is closed: an invoice is marked Paid the day before the cutover by the enable. Refuse it when Carbon settles it on or after the cutover (settledFromCutoverIds). Any other item type (memo, payment, WIP, lease, inventory, fixed asset) has no such state and stays in the opening journal.
Applies to: packages/database/src/accounting-cutover/trial-balance.ts, apps/erp/app/modules/accounting/accounting.service.ts.
A second foreign key between two tables breaks every PostgREST embed between them
Context: The OEE provider work (2026-10-13) added workCenter."loadedJobOperationId" with a foreign key to jobOperation, which already had "workCenterId" → workCenter.
Problem: With two relationships between the same pair of tables, PostgREST cannot pick one, and every existing embed of one from the other (jobOperation → workCenter(name): batches, the batch PDF, notifications) failed at runtime with PGRST201. Typecheck passed, because the generated types still compiled; only a request to an affected screen showed it.
Rule: Before adding a foreign key, grep for embeds between the two tables in both directions (table( inside .select(…) strings). If any exist, either leave the new column without a foreign key and keep it consistent another way (an interceptor that clears it on delete), or disambiguate every embed with table!constraint_name(…) in the same change. When replacing a foreign key (a composite one for tenancy), drop the old one in the same migration, never add beside it.
Applies to: migrations that add a foreign key, especially to widely embedded tables (workCenter, jobOperation, item, job).
One fact, one source: a pointer beside its own history lost the order of loads
Context: The OEE work (2026-10-13) kept the loaded operation twice: the pointer workCenter."loadedJobOperationId" + "loadedAt", and the history table workCenterLoad that the same interceptors wrote.
Problem: The unload cleared loadedAt with the pointer. That timestamp was the only watermark that ordered loads: the rule "an older start never replaces a newer load" compared against it. After an unload there was nothing to compare, so a late event (a start older than the unload) loaded the operation that had been replaced, and opened a history row that overlapped its neighbours. The pointer and the history then disagreed, and the sync gave run time to the wrong operation.
Rule: Keep one source for a fact. When a history exists, the current value is a row of it (here the open workCenterLoad row), not a second column to keep in step. Order writes against the history itself: refuse a write that is older than the newest boundary (any loadedAt or unloadedAt), and back it with constraints (a CHECK that an interval does not end before it starts, a partial unique index for one open row).
Applies to: workCenterLoad and its interceptors (sync_load_work_center_operation, sync_unload_work_center_operation), and any "current pointer + history" pair (statuses with a status log, assignments with an assignment history).
A unique index over a nullable column never deduplicated, and adding a real one breaks silent writers
Context: Employee re-invite (2026-10-15). membership had uq_membership ("groupId", "memberGroupId", "memberUserId"), and every user membership has memberGroupId NULL.
Problem: Under the default NULLS DISTINCT, rows with a NULL in the key never conflict, so the constraint that looked like it deduplicated user memberships never had. Writers inserted duplicates without error. A new unique index on ("groupId", "memberUserId") made those same writers fail: the insert interceptors had no ON CONFLICT, and the employee-type change interceptor moved a membership onto a group the user was already in. Each would have failed the employee, customer-account or supplier-account write that fired it.
Rule: Before adding a unique index, list every writer of the table, interceptors included, and give each one ON CONFLICT … DO NOTHING or a conflict-safe update in the same change. When a composite unique key includes a nullable column, assume it deduplicates nothing for rows where that column is NULL.
Applies to: membership and its interceptors in packages/database/src/event-system/handlers/, and any unique key with a nullable column.
A pick moves a job material's storage unit to lineside, so the line no longer names its Pull From
Context: Strict backflush (2026-10-16) consumed what no pick covered from jobMaterial.storageUnitId.
Problem: Posting a pick calls pointJobMaterialAtLineside, which overwrites jobMaterial.storageUnitId with the lineside bin. After a partial pick, the remainder was checked against lineside (already drawn) instead of the warehouse bin the BoM named. With negative stock prevented it refused a completion the shelf could cover. With it allowed, it drove lineside negative. The TypeScript and SQL paths had the same bug, and no test picked anything.
Rule: Never read jobMaterial.storageUnitId as "the Pull From" once picking may have run. The pick line keeps the source (pickingListLine.storageUnitId). Use the oldest pick line into the line's current bin (pullFromStorageUnit, @carbon/database/strict-backflush). A later list is sourced from the fullest bin, so do not use the newest one. Any test of a bin rule needs a case with a partial pick.
Applies to: strict backflush, and any rule keyed on a job material's bin (picking, returns, lineside credit, consumption).
A module the browser bundles must not reach the Kysely runtime, even through a helper
Context: Strict backflush (2026-10-16). @carbon/database/strict-backflush is imported by BoM UI components and by settings.service.ts, which the module barrel bundles for the browser.
Problem: Using inOrder from @carbon/database/rows there would have imported kysely at runtime into the client bundle; typecheck does not see it. Separately, settings.server.ts gained an import of ~/utils/query, which imports the @carbon/auth barrel. That barrel runs a Lingui msg macro, which plain vitest cannot compile, so 2 unrelated test files stopped loading.
Rule: In a client-bundled module, import only types from kysely and ./client. Run two awaits instead of inOrder. Raw sql belongs in a server-only file. Before adding an import to a file that tests import, check what that import's barrel pulls in, then run the module's tests.
Applies to: @carbon/database subpaths read by UI, {module}.service.ts, {module}.server.ts imported by vitest files.
A Lingui placeholder is named after its expression, so a refactor can silently drop translations
Context: Strict backflush (2026-10-16) changed <Plural value={methodsMissingPullFrom} …> to <Plural value={gaps.methods} …>.
Problem: A member expression has no name, so the message id changed from {methodsMissingPullFrom, plural, …} to {0, plural, …}. lingui:extract --clean then deleted the old id and its 12 translations, and the new id came back untranslated.
Rule: Pass a plain, named variable to Plural, t and Trans placeholders, and keep the name when refactoring. If extract drops translations by mistake, restore the catalogs from git (git checkout HEAD -- packages/locale/locales), fix the name, and extract again.
Applies to: every Plural / t\…${x}`/` with an interpolation.
Guard a state by listing everything that writes it, not by who calls the check
Context: Strict backflush (2026-10-17). Release had to refuse a job with a line that had no storage unit. The check was added where the release check already ran: the Release dialog, bulk release, batch release.
Problem: Two more paths set a job to Ready without any check. The kanban scan with auto-release wrote status: "Ready" straight to the job with the service role. The MCP / API tool production_updateJobStatus wrote any status. A search for callers of the release function cannot find a direct write. A self-review on a fixed file list did not look outside it, and the docs then claimed "every release path".
Rule: To guard a state change, first list every writer of that state: grep for the value being written (status: "Ready", SET status = 'Ready' in SQL) and for every caller of the write function, including MCP tools. Put the check where all writers meet, or give each writer the check. Keep the unchecked write out of the API (no @mcp tag). Do not claim "every path" without that list.
Applies to: release, completion, posting, cancellation — any status a check must gate.
A flash returned with data() from a page loader never shows
Context: The kanban scan (2026-10-19) returned data(result, await flash(request, error(…))) from its loader, and its page then navigated to the job with window.location.
Problem: The message never appeared. The root's flashMiddleware reads and clears the flash on every request. It ran on the scan's own document request and cleared the cookie the loader had just set. Typecheck and unit tests cannot see this; only the browser did.
Rule: To carry a message to another page, throw redirect(path, await flash(request, …)) from the loader or action, as every other route does. Do not return a flash with data() from a page loader and expect a later page to show it.
Applies to: any loader or action that sets a flash for the page it sends the user to.
A flash on a fetcher's redirect back to the same page is never shown
Context: Refusing a receipt post that still misses serial numbers (2026-10-16). The Post dialog submits through useRuleViolations, a fetcher.
Problem: The action threw redirect(path.to.receipt(id), await flash(...)). The redirect lands on the pathname already on screen, so the root's shouldRevalidate (isSearchParamOnlyNavigation) skips the root loader, and the root is what reads the flash and shows the toast. The post was refused correctly, but the user saw nothing happen. The route's older flash errors ("Failed to post receipt") have the same gap.
Rule: An action submitted through a fetcher returns its error as data ({ error: { message } }, which useRuleViolations toasts), not as a flash on a redirect to the current page. A flash is for a redirect that navigates somewhere else.
Applies to: Post / void / approve actions behind a modal or useRuleViolations (receipt+/$receiptId.post.tsx and its siblings).
What a document posts must be what its form shows
Context: Receipt serial entry (2026-10-16). Each serial box saved on blur, keyed on the serial number.
Problem: A box emptied, refused (a duplicate) or pushed out of range by a lower received quantity kept its saved serial. The post check reads what is saved, so the receipt posted a serial the user could no longer see.
Rule: Key a per-field save on the field's position (here the box: receipt line + index), not on its value. An empty value, a refused value and a removed field each clear what is saved for it. And a removal never deletes a record with stock history: a sales return re-tags real shipped units, so those only lose their receipt link (planReceiptSerialRelease).
Applies to: setReceiptLineSerial / saveReceiptSerialBox, updateReceiptLines, ReceiptLines SerialForm, the receipt line split (receiptLineSplit in shared.service.ts), and any autosaved list of tracked values (shipment serials, batch numbers).
A void reverses only what is still where the posting put it
Context: Voiding a posted purchase receipt with serials and batches (2026-10-16).
Problem: The void set every tracked entity back to Available at its received quantity, so a lot that was never received stayed pickable. It also reversed each ledger row at the receipt's bin with only a cost-layer check. A serial moved to another bin, picked to lineside or shipped (Standard and Average cost never draw a layer down) passed that check, so the receipt bin went negative while the unit stayed counted where it went. And the receipt's inspection lot stayed open: Accept made the voided batch Available again, and Reject wrote the reversed stock off a second time.
Rule: A reversal checks, inside its transaction, that the stock it removes is still at the position the posting wrote: per serial or batch for tracked rows. It closes every record that hangs off the document (here the inspection lot) or refuses while one has acted. It drains the document's tracked entities to quantity 0. To keep Rejected at zero, write the status directly: settleQuantity only preserves Scrapped and turns Rejected into Consumed.
Applies to: the postReceipt void (lockPostedReceipt, assertReceivedStockOnHand, assertNoRejectedUntrackedLot in inventory.service.ts), and any other void that reverses item ledger rows (shipments, stock transfers, adjustments).
A text replace on a function name also renames its prefix siblings
Context: The service-function migration (2026-10-16) renamed thousands of call sites with scripts.
Problem: A string or regex replace of getJob also matched getJobs, getJobOperation and every other name that starts with it, and matched the name inside strings and comments. One pass also left a stray suffix on a public name (createSupplierInteractionLineDocumentUploadUrlTool), which renamed an MCP tool without anyone asking for it.
Rule: Rename code through ts-morph references (findReferencesAsNodes, rename), never through text. After a mass rename, diff the published tool names against main (tool-manifest.digest.json) and explain every added and removed name.
Applies to: codemods over apps/erp/app/modules/** and any script that renames exports.
A mock of a function in the same file does not intercept
Context: The migration moved callers into the same module file as the functions they call (2026-10-16).
Problem: vi.mock replaces a module's exports for importers in other files. A call from one function to another inside the same file goes to the real function, so tests that mocked the callee started calling the database, or passed while testing nothing.
Rule: Stub only a real boundary (the Supabase client, fetch, the clock), as .claude/rules/testing.md says. A test that only checks which internal functions were called gets deleted, not repointed.
Applies to: tests under apps/erp/test/ and apps/erp/app/modules/**.
ts-morph re-resolves the whole program after every edit
Context: The barrel-removal codemod (2026-10-16) resolved each import's target, edited it, then resolved the next one.
Problem: Each edit invalidates the type checker, so the next symbol lookup rebuilt the program. The script took many minutes for what should take seconds.
Rule: In a ts-morph codemod, resolve everything first (symbols, targets, references) into plain data, then make all the edits, then save once.
Applies to: scratch codemods using ts-morph over the ERP project.
zsh does not split an unquoted variable into words
Context: Running Biome on a list of changed files held in a shell variable (2026-10-16).
Problem: In zsh, biome check $files passes the whole list as ONE argument. Biome reported "File name too long" and "No files were processed", which reads as a Biome bug, not a shell one.
Rule: Pass file lists through xargs (git diff --name-only | xargs biome check) or use zsh's ${=files}. Don't trust a tool error about a path until you have checked how the shell passed it.
Applies to: every Bash call in this environment (the login shell is zsh).
A function redefinition forked from an old copy reverts every migration between
Context: 20261014171619_receive-consumed-serial-units (2026-10-15) changed one branch of complete_job_to_inventory. Its header says it was "forked from 20261006221601".
Problem: two later migrations had redefined the function: 20261009010412 (every company posts job costing, Provisional before the cutover) and 20261014135003 (lock the production events a completion posts). The fork's CREATE OR REPLACE replaced the whole body, so both changes were silently undone: a company with no cutover got no Job Receipt journal, and a concurrent production-event post could double-post. The SQL tests that would have caught it either predated always-post or failed already and were not run.
Rule: copy a function's body from its NEWEST definition (grep -l "FUNCTION <name>" migrations | tail -1), then diff your body against that one before writing the migration. The function-redefinition-keeps-changes check fails a redefinition that drops lines its predecessor added. Run the SQL tests that call the function (scripts/run-local-accounting-check.ts psql -f …).
Applies to: any migration with CREATE OR REPLACE FUNCTION on a function defined more than once, especially the long posting functions (complete_job_to_inventory, backflush_job_materials).
A server-only value in a route component, or a dropped side-effect import, fails only the production build
Context: The service-function migration (2026-10-16) made every <module>.service.ts server-only: it may import server-only packages (@carbon/auth/auth.server, @carbon/ee/*.server, @carbon/jobs).
Problem: Two mistakes passed typecheck, the tests and the dev server, and broke only react-router build:
- A route component used a value from a
.service.ts(LOCK_PERIOD_TASK_NAMEin a close-period component). React Router strips a route's loader and action from the client build, not its component, so the service file and its server-only imports entered the browser graph and the build failed. - A bare side-effect import (
import "./modules/carbon.server",import "./zod.client") in a package whosepackage.jsonsets"sideEffects": false, or does not list the file. The production bundler dropped the import, so everycarbon()call threw in production andz.config({ jitless: true })never ran. The dev server does not tree-shake, so nothing showed it locally.
Rule: A value the browser uses goes in <module>.utils.ts (or models.ts / types.ts), never in .service.ts or .server.ts. A file imported only for its side effects is listed in its package's sideEffects array. The no-server-code-in-client check (ERP components, hooks, ui/, client-safe module files and the browser half of routes) and the side-effect-import-declared check enforce both. Run pnpm --filter erp build before you call a change to imports or module files done.
Applies to: ERP and MES modules and routes; every package.json that sets sideEffects.
Dev response caches must allow-list, never blanket-cache GETs
Context: Caching Onshape API GETs in Redis during development (ONSHAPE_DEV_CACHE=1) to protect the annual API quota.
Problem: Caching every GET poisoned the translation poll loop: GET /translations/{id} was cached while requestState was still ACTIVE, so waitForTranslation saw the same in-flight state forever and the export never completed. The failure looks like a hung job, not a cache bug.
Rule: A dev-mode response cache must be an explicit allow-list of stable content reads (DEV_CACHEABLE_PATHS in packages/ee/src/onshape/lib/client.ts). Never add a polling or status endpoint. When adding a cacheable path, ask: can two reads of this URL legitimately differ within the TTL?
Applies to: packages/ee/src/onshape/lib/client.ts, any dev-mode HTTP cache in front of a third-party API.
Inngest dev: an event fired before its function's first registration wedges the run
Context: Adding a new Inngest function and firing its event from a route during local development.
Problem: If the event fires before the dev server has registered the new function, the run sits "Running" forever — and per-key concurrency then queues every retry behind the wedged run, so nothing ever executes. The dev server's state is in-memory.
Rule: After adding or renaming an Inngest function, reload the Inngest dev server (crbn reload inngest) before firing its event; if a run is already wedged, cancel it and re-fire. Check http://localhost:<PORT_INNGEST>/runs when a background job seems to do nothing.
Applies to: packages/jobs/src/inngest/, local dev via crbn up.
Scripted source patches must assert their anchors
Context: Applying code changes to large files via scripted string replacement (python/sed) instead of hand editing.
Problem: A .replace() whose anchor doesn't match (e.g. after Biome reformatted the code) is a silent no-op: the script reports success, the file is unchanged, and the missing code later presents as an inexplicable runtime bug. One silent miss cost hours of "stale module" mis-debugging — the client genuinely lacked a branch the server had.
Rule: Every scripted patch must assert the anchor's occurrence count before replacing (assert s.count(old) == 1) and fail loudly on a miss. Never chain a patch script with && after an unasserted step.
Applies to: Any agent or script editing source by string replacement, repo-wide.
One-shot stores: peek for validation, take only for the write
Context: The Onshape panel's plan/apply split stores a reviewed plan in Redis and consumes it with GETDEL so a double-submitted apply cannot write twice.
Problem: Taking the plan before validating the user's edits meant a 422 (one bad field) destroyed the review; the corrected retry hit 410 and forced a fresh Onshape read. The one-shot guarantee and the validation step were fighting over the same read.
Rule: For any GETDEL-style one-shot record, validate against a peek (plain GET) and take the record only immediately before the first write. A rejected request must leave the record exactly as it was.
Applies to: packages/ee/src/onshape/lib/panel-plan-store.ts, any Redis-backed one-shot token/plan/challenge consumed by a request that also validates input.
Never build PostgREST .or() filter strings from external values
Context: Mapping-row deletes used .or(entityId.eq.${id},externalId.eq.${externalId}) where externalId embeds an Onshape part number.
Problem: A part number containing , or ( ) changes the filter's meaning — the value is interpolated into PostgREST's filter grammar unquoted, so the delete can match other rows or fail. Every .in() / .eq() call passes values as parameters and is immune.
Rule: Use .eq() / .in() instead of a hand-built .or() string whenever any operand comes from outside Carbon (CAD part numbers, external ids, user text). Chained filters on one query are AND-ed, so an OR across two columns ("remove mappings matching entityId OR externalId") becomes one parameterized statement PER COLUMN — two separate deletes — never both filters chained onto one delete, which removes only rows matching both and leaves the conflicting row that the next insert trips over.
Applies to: every Supabase client call with .or( whose operands are not literals; apps/erp/app/routes/api+/integrations.onshape.*.
A docs heading is read by the in-app agent, and its length counts against a budget
Context: Adding a billing cycle to rental agreements lengthened two troubleshooting headings in docs/content/docs/reference/rental-agreements.mdx, each quoting every variant of an error message.
Problem: The in-app agent's read_doc returns a long page as its intro plus a link per section, and agent.kb.test.ts caps every page and section read at READ_BUDGET (16,000 characters). Each heading appears twice in that list, as text and inside its anchor URL. About 1,400 characters of heading growth pushed the page over the cap and failed the ERP test suite, far from the docs package.
Rule: Keep a troubleshooting heading to one message. Use … for the part that varies and list the variants in the body. After you edit a long reference page, run apps/erp/app/modules/agent/agent.kb.test.ts as well as the docs checks.
Applies to: docs/content/docs/**, apps/erp/app/modules/agent/agent.kb.ts.
A dynamic .server import fails the client build too
Context: The MES services that call the ERP (operations.service.ts, inventory.service.ts) are also imported by client components, for their client-safe functions. The signing helper they need uses node:crypto.
Problem: React Router's react-router:dot-server plugin checks every resolveId in the client build, static and dynamic. Moving a .server module behind await import(…) does not hide it. The production build still refuses it, and typecheck and the dev server do not show the error.
Rule: A helper that a client-graph module must load is not named .server. Give it a plain name (@carbon/api/internal-call). Load it lazily with await import(…) inside the server function, so the browser never evaluates it. Prove it with the production build of the app.
Applies to: apps/mes/app/services/*.service.ts, apps/erp/app/modules/*/*.service.ts, any package subpath they import.
@carbon/kv answers null for a miss and for an outage
Context: The ERP's internal postings endpoint used redis.set(key, "1", "PX", ttl, "NX") to refuse a nonce it had seen.
Problem: withResilience (packages/kv/src/resilient.ts) turns a Redis failure or a 2-second timeout into the command's fallback, null. SET NX also answers null for a key that exists. The two cases looked the same, so a Redis outage refused every MES posting as a replay.
Rule: Never read a null from @carbon/kv as "the key is there". Read the key back to tell the cases apart. Decide on purpose whether the feature fails open or closed when Redis is down, and log it.
Applies to: every @carbon/kv caller that branches on a command's result.
Type a cross-app call by what the receiver accepts
Context: MES calls ERP postings over HTTP, and the ERP refuses any posting or type value that is not in MES_POSTINGS.
Problem: The first allowlist came from a hand inventory of the MES call sites and missed issue/trackedEntitiesToOperation. Every check passed. The miss would have shown only in production, as a 404 when a user issued tracked entities to an operation.
Rule: Derive the caller's input type from the receiver's allowlist (ErpPostingInput, apps/mes/app/services/erp.ts). Then a value that the receiver refuses fails the caller's typecheck. Keep casts out of those call sites, or check the values behind each cast by hand.
Applies to: apps/mes/app/services/erp.ts, packages/api/src/postings.ts, any other server-to-server contract.
A module first loaded inside a vi.mock factory binds the unmocked module
Context: ERP unit tests mock shared.service with importOriginal and override invokePosting. shared.service.ts imports other module services (resources, sales, production), and they import it back.
Problem: importOriginal evaluates the real shared.service, and that evaluates its imports. A module whose first evaluation happens there binds the real shared.service, because the mock is not built yet. Its calls then skip the mock. A new import edge elsewhere (inventory.service → production.service) changed the load order and broke tests that had passed for weeks.
Rule: Before the module under test, load the service that makes the mocked call: await import("../app/modules/<module>/<module>.service"), with a comment that says why. If a mock does not intercept, check the import order first.
Applies to: apps/erp/test/*.test.ts, apps/erp/app/modules/**/*.test.ts that mock shared.service.
An Inngest wait holds no concurrency slot, and a retry replays memoized steps
Context: runAssemblerJob (packages/jobs/src/inngest/functions/tasks/assembler-client.ts) used to poll the assembler inside one step.run and throw when its budget ran out.
Problem: Two assumptions were wrong. A comment said a waiting run holds a slot of the function's concurrency; step.waitForEvent, step.sleep and step.invoke hold none. And a throw outside a step does not redo the work: the retry replays every memoized step from its stored output, so the same check throws again with the same input.
Rule: Wait with step.waitForEvent in slices, and poll once per slice in its own step. To retry the external work, do it in a new step (a resubmit with a new step id), never by throwing. Charge an action's time budget from when the service starts it, not from the submit.
Applies to: any Inngest function that waits on an external service.
Check a column's default before you filter on NULL
Context: The queue_model_pipeline handler first selected new models WHERE "optimizeStatus" IS NULL.
Problem: modelUpload.optimizeStatus is NOT NULL DEFAULT 'Idle', so the filter matched no row and the handler queued nothing. The insert succeeded and nothing failed.
Rule: Read the column definition in the newest migration (or \d on the local database) before you write IS NULL against it. Test a new handler in a rolled-back transaction and assert the queued net.http_request_queue body.
Applies to: SQL handlers, sweepers and views that pick rows by a status column.
An event sent at commit races every write the caller makes after the insert
Context: New modelUpload rows start model-optimize from a statement handler, and pg_net sends the event when the transaction commits.
Problem: The part and tool forms inserted the row and uploaded the file at the same time (Promise.all). The quote drop inserted the row, then staged the file. In both, the optimise could start before its file existed and fail as "file not found".
Rule: When an insert starts a job, finish everything that job reads before the insert: stage the file, then insert the row. Keep a backstop for an event that is lost (the reaper resends the start once).
Applies to: any table whose statement handler or interceptor sends an Inngest event.
A service-role job must check that a stored path belongs to the row's company
Context: The model jobs found a raw file by the company named in modelUpload.modelPath and read storage as the service role.
Problem: The forms insert modelUpload under RLS, and RLS does not check modelPath. So a row in one company could name another company's staged upload in the shared temp-staging bucket, and the optimise would copy that file into the first company's bucket.
Rule: A job that reads storage as the service role takes the company from the row, never from the path, and refuses a path outside ${companyId}/ (resolveModelSourceBucket). Test it with a real object and a positive control, so the test fails when the guard goes.
Applies to: packages/jobs storage reads keyed by a path a user can write, and every copy that picks a bucket (copyAssetsToBackup took the source bucket from the first path segment until 2026-10-17).
A long poll inside an Inngest step holds a concurrency slot for its whole wait
Context: runAssemblerJob polled the assembler with GET /v1/jobs/{id}?wait=25 inside a step.run.
Problem: Inngest counts an executing step against its function's concurrency key. Each poll held a slot of the shared assembler key for up to 35 seconds, so a burst of uploads filled the key with waits, not work.
Rule: Inside a step, make the request short. Wait between requests with step.waitForEvent or step.sleep, which hold no slot. Treat a 5xx answer as "unreachable", not as a lost job.
Applies to: every Inngest function that polls an external service.
A fetcher's error goes to the boundary above the component that owns it
Context: CarbonProvider (@carbon/auth, rendered by each app's x+/_layout) refreshes the session from a one-minute timer with useFetcher().submit to /refresh-session. In a background tab the POST failed with TypeError: Failed to fetch (the laptop asleep, the connection dropped), and the whole app was replaced by the root "Something broke on our end" screen.
Problem: React Router sends a fetcher's error to findNearestBoundary(state.matches, routeId), where routeId is the route that RENDERED the fetcher, not the route the request was sent to. refresh-session.tsx exports an ErrorBoundary that never runs for this; the shell layout has none, so the root took it. A fetch that gets no response is not a Response, so the boundary showed it as a 500.
Rule: A request a timer or event sends on its own (not one the user started) must not be able to fail into a boundary: skip it while navigator.onLine is false and retry on online. Both error boundaries treat isNetworkError as a lost connection and revalidate when the connection or the tab comes back; a successful revalidation clears state.errors.
Applies to: every useFetcher used from a layout or provider, every background timer that submits or loads, packages/react/src/ErrorBoundary/.
A field edited in a plain textarea must not read its text as Markdown
Context: MCP rich-text inputs (notes, work instructions) are read as Markdown through toTiptapDoc / TiptapText. Contract notes share that input, but the app edits them in a plain TextArea (ContractDetailsForm, ContractProperties) and shows the saved document with TiptapText(doc).toString().
Problem: TiptapText(doc).toString() drops what Markdown turned into structure. "1. Ship" became an ordered list and read back as "Ship"; "abc" read back as "abc". The textarea showed the stripped text at once, and the next save stored it.
Rule: A rich-text field whose UI is a plain textarea read back with TiptapText(doc).toString() stores text as typed: optionalPlainTextDoc / TiptapText(text, { format: "text" }), not optionalTiptapDoc / the Markdown default. Markdown is for fields a rich editor shows, where the formatting survives.
Applies to: apps/erp/app/modules/shared/shared.models.ts (toTiptapDoc, optionalTiptapDoc, optionalPlainTextDoc), contract notes (customerContractValidator, setContractTerm), any new textarea over a json column.
A posting's refusal only reaches the dialog when it is thrown as a 4xx
Context: A refused receipt void showed "Failed to void receipt" with no reason. The guards inside the post-receipt posting said exactly why ("stock received on this receipt was moved, picked or shipped since it was received").
Problem: invokePosting reads a plain Error as status 500 (the posting's default), and the operation passed every failure to serverFnFailure with a fixed message. So every refusal, and every new guard, was reported with the same generic text.
Rule: Throw an authored refusal from a posting as InvalidInputError (or another ServerFnError below 500), never a plain Error. In the operation, below 500 return the error's own message (error.message || <fallback>); keep the generic message for 500, whose detail toError already withholds.
Applies to: every operation that calls invokePosting and every posting body (voidReceipt / postReceipt in inventory.server.ts, adjustInventory follows the same shape).
A skip inside a posting loop does not cover maps built before the loop
Context: Making postReceipt (PO path) ignore a receipt line received at 0 (receipt quantities can start at zero, 2026-10).
Problem: The fix added if (receivedQuantity === 0) continue; to the per-line ledger loop. Three side-effect maps were built earlier from every line: receiptLinesByPurchaseOrderLineId (PO line receivedDate, outside-processing operation status) and trackedEntityUpdates (entity status and the Receive activity). A zero line still stamped its PO line received today, and a batch left on it became Available at its full quantity with no item ledger row. Review caught it, not the tests.
Rule: When a posting must ignore a line, filter it where every per-line collection is built, not only in the loop that writes the ledger. List every map or array derived from the lines and check each. Pin the skipped line's absence in a test: assert the side effects did not happen, not only that the ledger row is missing.
Applies to: postReceipt / postShipment and every posting in inventory.service.ts that builds update maps before its write loop.
Open an OAuth popup in the click, before you fetch its URL
Context: Install and Add account on a workflow piece card (startIntegrationConnect, packages/ee/src/integrations/connect.ts) fetch the consent URL from the connect route, then open it in a popup.
Problem: The old code awaited the fetch and then called window.open. The await can outlive the click's transient user activation, so Chrome blocked the popup without an error, and Install looked like it did nothing.
Rule: Call beginOAuthPopup() (packages/ee/src/oauth-popup.ts) synchronously in the click handler, before any await. Then fetch the URL and call navigate(url) on the handle. If the fetch fails, call close(). If the browser blocked the popup anyway, navigate falls back to the current window.
Applies to: every consent or payment flow that opens a window after a request: the piece cards, the Onshape connect, any new OAuth integration.
One OAuth state mechanism: the cookie helper, consumed by value for a shared callback
Context: The workflow pieces (Slack, Gmail, Google Calendar) signed their own OAuth state with an HMAC helper in settings.service.ts, beside the cookie-bound state that every other integration uses (@carbon/auth/oauth-state.server).
Problem: Two mechanisms meant two sets of binding, expiry and single-use rules to keep correct, and a review had to check both. The pieces share one callback route, so that route cannot know which integration's entry to consume before it reads the state.
Rule: Issue every OAuth state with issueOAuthState. Carry extra facts (mode, name, connectionId) as OAuthStateExtras, never in the query string. Pass the request, so the other integrations' pending entries survive the Set-Cookie. A callback that serves several integrations calls consumeOAuthStateByValue; it finds the entry that holds the value and takes the integration id from that entry. Do not add a second signer.
Applies to: api+/integrations.connections.$piece.connect.ts, api+/integrations.connections.callback.ts, api+/integrations.$id.connect.ts, and any new OAuth connect or callback route.
A header and the get-method copy into it share one transaction
Context: New Version on a make method inserted the makeMethod header through supabase-js, set the source version Active, then ran get-method's makeMethodToMakeMethod copy, which opened its own Kysely transaction. A version change notice and the Onshape panel's Draft did the same in their own code.
Problem: When the copy failed it rolled back only its own rows. The empty Draft stayed, numbered above a source that was now Active and read-only. A first fix deleted them again after the failure; that cleanup could fail too, and it needed a delete the caller may not be allowed to make.
Rule: Put the header insert, any status change and the copy in ONE Kysely transaction and pass the transaction to copyMakeMethod as db. A function that may be handed a transaction opens its own through withTransaction (@carbon/database/client), never db.transaction(): Kysely refuses transaction() on a Transaction. Every get-method body, and createMakeMethodVersion itself, joins that way, so a caller can add its own writes to the same commit (the change notice writes its changeOrderId in the insert; the Onshape Draft adds its line ownership and marker) instead of a second write after the commit that can fail alone. Kysely bypasses RLS, so check the policy's permission through the caller's client first (requireCompanyPermission), as createRevision does.
Applies to: createMakeMethodVersion (items.service.ts) and its callers (createMethodVersion, createChangeNoticeDraftMethod, ensureDraftMakeMethod); any other header insert followed by a get-method copy (quote and job duplication, revisions).
An import wizard enum Default fills every blank cell before the server sees it
Context: The method import (#1977) was made to fill a blank BOM Unit of Measure with the material's own unit and a blank Operation Type with the process's type, as the BOM and BOP editors do.
Problem: fieldMappings in imports.models.ts preset default: "EA" and default: "Process". The wizard writes an enum's Default into every blank and unmapped cell before the import runs, so the server never saw a blank and its fallbacks never ran. The server-side change and its tests looked right; only a run through the wizard showed every line still in EA.
Rule: When the server derives a value for a blank cell, remove that field's default from fieldMappings, and pin the absence in a test (shared.method-import-append.test.ts → "presets no BOM unit and no operation type"). A wizard Default and a server fallback cannot both apply.
Applies to: every table in fieldMappings (apps/erp/app/modules/shared/imports.models.ts) whose importer has a fallback for a blank cell.
A temporary override lives in the thing it overrides, not in its callers
Context: Halloween had to be the theme for everyone while in season (2026-10). The first cut replaced the cookie read in all three apps' getTheme (services/theme.server.ts) with resolveTheme(halloweenTheme.name).
Problem: Undoing it meant rewriting three deleted cookie reads from memory, and nothing pointed at them: deleting halloween-theme.ts would just break the imports. The mesh colors in MeshGradientBackground.tsx (a Record<string, …>, so no compile error) and a test that imported the theme directly had the same shape. The removal checklist went stale twice as pieces were added.
Rule: Put a seasonal or temporary behaviour on the removable unit itself (its available window and mesh on the SeasonalTheme, read by the shared resolver) and keep callers generic, so deleting the unit turns the behaviour off. Test the mechanism on a fixture, not on the instance. Keep ONE removal checklist, next to the code, and make every other comment point to it.
Applies to: packages/utils/src/themes.ts seasonal themes, packages/react/src/Halloween/, any feature flag, promo or seasonal UI.
The theme a page renders is not the theme the user picked
Context: A seasonal theme made getTheme (services/theme.server.ts) return the seasonal name for everyone in season (2026-10).
Problem: The ERP's onboarding theme step and x+/account+/theme.tsx also read getTheme to seed and post back the user's own pick. In season they posted the seasonal name, themeColorValidator refused it, and onboarding could not get past the theme step. The theme pickers meanwhile painted a chosen theme onto <body> while the server kept rendering the seasonal one.
Rule: Keep "what to render" (getTheme → resolveTheme) and "what the user chose" (getStoredTheme → storedTheme) as two reads, and decide the season once, in the root loader (Document renders the name with themeByName). A picker that cannot take effect is disabled and says why (useSeasonalTheme, SeasonalThemeNotice).
Applies to: packages/utils/src/themes.ts, every app's services/theme.server.ts and root.tsx, every theme picker.
Registering on load from entry.client never registers in dev
Context: The ERP and MES service workers were registered from entry.client.tsx with window.addEventListener("load", register), the pattern most guides show (2026-10-22).
Problem: On the dev server React Router imports entry.client late: by the time the module runs, the page has already fired load (document.readyState === "complete"), so the listener never ran and no worker was registered. The offline page never appeared and nothing logged an error.
Rule: Register immediately when document.readyState === "complete", and on load otherwise. Check navigator.serviceWorker.getRegistrations() in the browser after any change to how a worker is registered.
Applies to: apps/erp/app/entry.client.tsx, apps/mes/app/entry.client.tsx; any code in an entry module that waits for load.
A service worker's install-time cache can come out empty and stay empty
Context: The ERP worker saves offline.html when it installs, and installs anyway when the save fails, so push never depends on it (2026-10-22).
Problem: A user toggled offline while an updated worker was installing. The save failed, the new worker activated and deleted the previous cache, and every later offline page load got the browser's "This site can't be reached": the worker had nothing to answer with, and it only reinstalls when its own file changes.
Rule: Never trust that install filled a cache. Re-check it from the fetch handler after a page load that reached the network (ensureOfflinePage), and give the worker a built-in last-resort response (fallbackOfflinePage) so a cache miss never surfaces as the browser's error.
Applies to: apps/{erp,mes}/public/service-worker.js; any worker that precaches on install.
Changing a precached file without bumping the cache name changes nothing
Context: offline.html was edited several times (the game, the text wrapping), and each time existing browsers kept showing the old page (2026-10-22).
Problem: A worker saves the file only when it installs, and it reinstalls only when service-worker.js itself changes. Editing offline.html alone leaves every browser that already has the worker on the old copy, and the self-heal only fills a missing entry, it never replaces one.
Rule: Every change to offline.html bumps the offline cache in both workers (ERP OFFLINE_CACHE, MES SHELL_CACHE). offline-page.test.ts in each app pins the page's hash to the cache name, so a change that skips the bump fails.
Applies to: apps/{erp,mes}/public/offline.html and service-worker.js.
Chrome on macOS drops an installed app's Dock badge when its window closes
Context: The app icon badge is set by the open tab and by each push (setAppBadge in the worker), so it should keep counting while the installed app is closed (2026-10-22).
Problem: In Chrome on macOS the badge shows while the app's window is open and disappears when it closes; a push that arrives later, and setAppBadge run from the worker's own console, both resolve and draw nothing. Chrome's installed app is a helper process that quits with its window, and the badge belongs to it. The badge also needs macOS notification permission with "Badge app icon" on (System Settings → Notifications → the app).
Rule: Do not promise a closed-app badge on macOS Chrome. Test the badge with the app hidden (⌘H), not closed, and test the closed case on a platform meant to keep it (an iPhone Home Screen app) before calling it broken.
Applies to: apps/erp/app/hooks/useAppBadge.ts, apps/erp/public/service-worker.js, the send-push badge count.
A scheduler decision is only stored when every write-back guard agrees
Context: The scheduler balances an operation that has not started onto any work center of its process (F10, 2026-10-26).
Problem: Two separate "never overwrite a stored work center" guards sat between the decision and the database: one in applyWorkCenterSelections, one in the engine's buildWrites. Fixing the first one alone changed nothing in the database. The capacityReservation row named the chosen station while jobOperation.workCenterId kept the old one, and every unit test still passed.
Rule: When you change what the scheduler decides, trace the value to the write (placementWrites, run-overlay.ts). Test the decision and the write together, then remove the write fix and confirm a test goes red.
Applies to: packages/planning/src/scheduling/ — apply-work-center-selections.ts, run-overlay.ts, scheduling-engine.ts.
An SQL test that inserts an employee needs the company's root group first
Context: Seeding employees in a supabase/tests/*.test.sql file (rpc-privileges.test.sql, 2026-10-26).
Problem: The employee insert fires the employee-type group interceptor, which needs the company's "All Employees" root group. A test company made by hand has no root group, so the insert fails. SET session_replication_role is not permitted there.
Rule: Insert the root group first, with the id getGroupId builds: '00000000-0000-' || substr(c,1,4) || '-' || substr(c,5,4) || '-' || substr(c,9,12) for company id c. Then insert the employee type and the employee.
Applies to: SQL tests under packages/database/supabase/tests/ that create employees.
setGenericQueryFilters erases a query's row type
Context: Inventory → Receiving read a view through setGenericQueryFilters and its route annotated the rows with a hand-written type (2026-10-26).
Problem: The helper's signature is typed loosely (it carries @ts-expect-error), so whatever it returns awaits to rows of type any. An annotation on those rows is an unchecked cast: renaming a column in the select string, or dropping it from the view, compiles clean and renders blank. Types in types.ts derived through ReturnType<typeof getX> are any the same way.
Rule: Keep the typed builder. Assign the helper's result back to the query variable (query = setGenericQueryFilters(query, { filters })), which keeps the variable's declared type, then apply the sort and .range() on it directly. Derive the row type from that function in types.ts, and narrow a view's never-null keys once at the loader boundary rather than guarding them in components.
Applies to: list reads in apps/erp/app/modules/*/*.service.ts that call setGenericQueryFilters, and the types.ts row types derived from them.
OCCT keeps every document it opened by path, and refuses to open it again
Context: The optimize ingest gained a PMI pass (read_pmi, crates/occt-bridge/src/pmi.cc) that reads the same .xbf the optimiser had just tessellated with read_xbf (2026-10-26).
Problem: TDocStd_Application::Open(path, doc) registers the document with the application until Close(doc). read_xbf never closes it, so the second open of the same path failed with PCDM_RS_AlreadyRetrieved ("could not open XBF document"). The hermetic converter test passed, because it opened the .xbf only once; only the assembler's ingest test, which runs both passes, showed it.
Rule: A second reader of an .xbf opens it from a stream (Open(std::istream&, doc)), which skips the path check, and calls xcaf_app()->Close(doc) when done. Test any new pass over the ingest's xbf through run_ingest, not only through the converter.
Applies to: crates/occt-bridge/src/*.cc (any function that opens a BinXCAF document), apps/assembler/src/actions/optimize.rs (run_ingest).
A save that reconciles a whole set must be shown the whole set, whatever the page filters
Context: The People board's day editor (PeopleHoursModal → setPeopleDay) saves a person's day: it updates the rows it is sent and DELETES the rows of the save's shift it is not sent (2026-10-28).
Problem: The editor opened with the rows the page showed. The department filter hid rows at other stations, and the shift filter hid rows of other shifts, while the save was scoped to the person's own shift (or every shift, for a person with none). Saving deleted rows the user never saw, or inserted a second row for a station the person already held in another shift.
Rule: A save that reconciles a set (deletes what it is not sent) gets that set from the same scope the server deletes by, never from what the page filtered. Pass the unfiltered rows next to the filtered ones and select the save's scope in one pure helper (editorDayRows, peopleShared.ts), with a test.
Applies to: apps/erp/app/modules/production/ui/Schedule/People/* (Board and Matrix editors), setPeopleDay and any other "make these rows the whole day/week" write in production.service.ts.
A new table handler's generated migration fails locally with "must be owner"
Context: A new statement handler (queue_pmi_inspection_plans) was added to event-system/handlers/ and attachments.ts. pnpm db:migrate synced it, then authz migration wrote the generated migration that ships it (2026-10-27).
Problem: The next pnpm db:migrate failed on that migration with must be owner of function queue_pmi_inspection_plans. The sync had created the function as supabase_admin. Every older handler is owned by postgres, the role the migration runs its CREATE OR REPLACE as. Production never syncs, so only a local database that synced first is affected.
Rule: If the generated migration of a new managed function fails locally with "must be owner", run ALTER FUNCTION public.<name>() OWNER TO postgres; as supabase_admin, then run pnpm db:migrate again. Do not edit the generated migration.
Applies to: packages/database/src/event-system/handlers/*.sql, packages/database/src/event-system/functions/*.sql, pnpm --filter @carbon/database authz migration.
A form validator is not an API contract
Context: production_createJobOperation answered a bare 500 "Failed to insert job operation" to an API caller (2026-10-27).
Problem: Operations moved from routes kept the route's input and error handling. The form sent a fresh client-made id for each new row, so the create input required one and an API caller had to invent it; a reused id failed the insert. The route's toast-only ctx.error("internal", "Failed to …", error) (448 of them) then hid the database's reason, so a duplicate key or a reference to nothing read as our failure.
Rule: A create input leaves the new row's id optional when the table has a default (mcp-create-inputs.test.ts fails otherwise). A database refusal the caller can fix is reported as itself: defineServiceFn maps an internal error whose cause is one (databaseRefusal), so don't swallow the cause. A yes/no field is a real boolean that also parses the form's "true" / "false" (booleanField, shared.models.ts), so the API publishes boolean. A rich-text (JSON) column takes optionalTiptapDoc / requiredTiptapDoc, never z.string() or z.unknown(): a raw string is stored as a JSON scalar the editor cannot read. A JSON value a form posts as text takes jsonInput(schema). Never z.preprocess / z.coerce / z.any() bare in an operation's input: the manifest publishes those as "anything".
Applies to: every defineServiceFn in apps/erp/app/modules/*/*.server.ts, and any validator reused as an operation's input.
Code outside an Inngest step runs again after every step
Context: Printing a Make kanban to a printer printed the Create card only, never Start or Complete (2026-10-28).
Problem: print-job wrote its printJob rows in the function body and called step.sendEvent per job. Each step makes Inngest invoke the function again from the top with the finished steps memoized, so the body ran again: its 30 s duplicate guard found the job the first pass had just written and threw NonRetriableError. Every document with more than one label (kanban cards, a receipt's serials) printed its first label only, and the run read as a "duplicate" rather than a failure.
Rule: In an Inngest function, every database read that decides something and every write goes inside a step.run; the body between steps must be safe to run again. Collect the events in the step and send them with one step.sendEvent after it.
Applies to: packages/jobs/src/inngest/functions/** — any function that writes outside step.run and then calls a step.* method.