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.
Client query cache and realtime broadcast — implementation plan
Spec: .ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md Research: .ai/research/2026-10-01-client-cache-on-react-router.md Branch: claude/tanstack-query-caching-realtime-54567c
Progress
- Task 1: Install dependencies and prove broadcast on the local stack
- Task 2: Add the realtime table lists
- Task 3: Add the three broadcast functions and the
realtime.messagespolicies (authz manifest) - Task 4: Write the attach migration
- Task 5: Apply the migrations and regenerate types
- Task 6: Add the database tests
- Task 6b: Move event triggers and interceptor bodies out of migrations (user, 2026-10-05)
- Task 7: Add the
realtime-table-has-triggercheck - Task 8: Add the private option to
useRealtimeChannel - Task 9: Add
cachedClientLoaderand the company id value - Task 10: Add the invalidation middleware to both roots
- Task 11: Convert the 27 cached
clientLoaderexports - Task 12: Delete the invalidation-only
clientActionexports - Task 13: Add
useRealtimeanduseRouteRealtimeto@carbon/react - Task 14: Move the ERP lists to
useLiveList - Task 15: Move the MES lists and remove nanostores
- Task 16: Move notifications and the implementation hub
- Task 17: Declare
handle.realtimeon the routes and convert the subscribers - Task 18: Add
useLoaderQueryand migrate the.load()call sites (13 event-driven sites stay onuseFetcher: Linear and Jira issue search, the Onshape sync steps, the Stripe customer lookup, the 2 report drill-downs, the MES issue-material modal) - Task 19: Add
useActionand migrate the submit call sites (98 single-condition effects; the 133 effects with several branches are a follow-up PR, user decision 2026-10-05) - Task 20: Update the rules, the lessons and the
AGENTS.mdfiles - Task 21: Run the full verification and the browser tests
Dependencies
- Task 1 gates everything. If it fails, stop.
- Tasks 2 → 3 → 4 → 5 → 6 run in order (database).
- Task 7 needs Task 2.
- Tasks 8, 9 are independent of the database tasks.
- Task 10 needs Task 9. Tasks 11 and 12 need Task 10.
- Task 13 needs Tasks 5, 8 and 10. Tasks 14, 15, 16 and 17 need Task 13.
- Task 18 needs Task 11. Task 19 is independent of Task 18.
- Tasks 11, 12, 18 and 19 are codemod sweeps. Run each sweep one module folder at a time.
Rules for every task:
- Run each typecheck alone:
pnpm exec turbo run typecheck --filter=<pkg> --concurrency=1. - Start each new source file with its SPDX header:
pnpm --filter @carbon/checks license-headers. - Never run
pnpm db:migrate. The user runs it. - Never push. Commit only through
/check-and-commit.
Task 1: Install dependencies and prove broadcast on the local stack
Depends on: none Files:
- Create:
<scratchpad>/broadcast-spike.sql,<scratchpad>/broadcast-spike.mjs(not committed)
Steps:
- Ask the user to approve
pnpm installin this worktree. Run it with no--filter. - Ask the user to start the stack with
crbn up, if it is not running. - In
psql, runSELECT to_regprocedure('realtime.send(jsonb,text,text,boolean)');. - If step 3 returns NULL, STOP and report. Do not improvise.
- Write the spike script. It signs in as the
DEV_BYPASS_EMAILuser with supabase-js. - The script joins
company:<companyId>:spikewith{ config: { private: true } }. - Before the policy exists, confirm that the join returns
CHANNEL_ERROR. - In a
psqltransaction, create the company policy from the spec. Do not commit it. - Run
SELECT realtime.send('{"op":"INSERT"}'::jsonb, 'INSERT', 'company:<companyId>:spike', true);. - Confirm that the script prints the message.
- Roll the transaction back.
Verify:
node <scratchpad>/broadcast-spike.mjs
# Expected: "CHANNEL_ERROR" without the policy; "received INSERT" with it
Out of scope: any change to a tracked file. If Realtime v2.89.0 does not deliver the message, STOP and report.
Task 2: Add the realtime table lists
Depends on: Task 1 Files:
- Create:
packages/database/src/realtime-tables.ts - Create:
packages/database/src/realtime-tables.test.ts - Modify:
packages/database/package.json— add the export./realtime-tables - Copy from (precedent):
packages/database/src/supersession-pick.ts(a client-safe module with its own export)
Steps:
- Export
REALTIME_TABLESas aconstarray of table names, typedkeyof Database["public"]["Tables"]. - Put these 66 names in it:
assemblyPlanJob,changeOrder,customField,customer,documentExtraction,documentTemplate,employee,implementationCheckState,implementationFieldValue,implementationHub,implementationRow,inspection,inventoryCount,item,itemLedger,itemStockQuantities,itemSupersession,job,jobMakeMethod,jobMaterial,jobOperation,jobOperationNote,jobOperationStep,jobOperationStepRecord,journal,maintenanceDispatch,material,materialForm,materialSubstance,modelUpload,nonConformance,nonConformanceActionTask,part,pickingList,pickingListLine,printJob,productionEvent,productionQuantity,purchaseInvoice,purchaseInvoiceLine,purchaseOrder,purchaseOrderLine,purchaseReturnOrder,purchasingRfq,quote,quoteLine,quoteMaterial,quoteOperation,receipt,receiptLine,salesInvoice,salesInvoiceLine,salesOrder,salesOrderLine,salesReturnOrder,salesRfq,salesRfqLine,shipment,shipmentLine,stockTransfer,supplier,supplierQuote,trackedEntity,warehouseTransfer,workflowRun,workflowStepRun. - Export
REALTIME_REFERENCE_TABLESwith these 20 names:ability,customerContact,customerLocation,customerType,itemPostingGroup,location,materialType,nonConformanceType,paymentTerm,procedure,process,qualityDocument,shippingMethod,storageUnit,supplierContact,supplierLocation,supplierProcess,supplierType,unitOfMeasure,workCenter. - Export
REALTIME_USER_TABLES = ["notification"] as const. - Export the type
RealtimeTableas the union of the first list. - In the test, assert that the three lists share no name and hold no duplicate.
- For each name, run
SELECT relkind FROM pg_class WHERE oid = '"<name>"'::regclass;. If one is notr, STOP and report.
Verify:
pnpm --filter @carbon/database exec vitest run src/realtime-tables.test.ts
# Expected: 1 file passed
Out of scope: a table for a settings or admin page. Task 17 may add a name here only when a route in the spec's folder list needs it.
Task 3: Add the three broadcast functions and the realtime.messages policies
Depends on: Task 2 Files:
- Create:
packages/database/src/event-system/functions/broadcast_table_changes.sql - Create:
packages/database/src/event-system/functions/broadcast_user_changes.sql - Create:
packages/database/src/event-system/functions/broadcast_reference_changes.sql - Modify:
packages/database/src/event-dispatch.test.ts— check the ignored-column list in the 3 new files - Modify:
packages/database/src/authz/rules.ts,sync.ts,migration.ts,manifest.ts— the manifest owns"realtime.messages" - Modify:
packages/checks/src/conformance/no-authz-ddl-in-migrations.ts— flag a policy on therealtimeschema - Copy from (precedent):
packages/database/src/event-system/functions/dispatch_event_batch.sql
Steps:
- Read
.claude/rules/authz-manifest.md→ "Event-system functions" before you write a file. - Write
broadcast_table_changes.sqlwith the function body from the spec's Data Model section. - Write
broadcast_user_changes.sql. Use the same body. Group byc->>'userId'. Send to'user:' || user_id || ':' || TG_TABLE_NAME. - Write
broadcast_reference_changes.sql. Use the same body. Send{ table, op }to'company:' || company_id || ':reference'. - In each file, declare
ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];on one line. - In
event-dispatch.test.ts, run the existing constant check for each of the 4 files in a loop. - Add
locate(key)andexternal()torules.ts. A key with a dot names<schema>.<table>. - Add the
"realtime.messages"entry with the 2 policies tomanifest.ts. - Make
sync.tsandmigration.tsread the schema from the key. Keep thepublicoutput byte for byte. - Run
pnpm --filter @carbon/database authz migration realtime-broadcast. - If the timestamp is older than the newest migration on
main, rename the file to a later timestamp. - Do not edit the content of the generated migration.
- When the local stack runs, run
pnpm --filter @carbon/database authz syncand thesync.test.tsfile.
Verify:
pnpm --filter @carbon/database exec vitest run src/event-dispatch.test.ts src/authz
# Expected: all files passed; the generated migration lists the 3 function names
Out of scope: dispatch_event_batch.sql and attach_statement_handler.sql. If authz sync refuses a file, STOP and report.
Task 4: Write the attach migration
Depends on: Task 3 Files:
- Create:
packages/database/supabase/migrations/<timestamp>_realtime-broadcast-attach.sqlthroughpnpm db:migrate:new realtime-broadcast-attach - Copy from (precedent):
packages/database/supabase/migrations/20260812002454_item-stock-quantities-incremental.sql(theattach_statement_handlercall)
Steps:
- Run
pnpm db:migrate:new realtime-broadcast-attach. - Confirm that its timestamp is later than the generated migration of Task 3.
- Write no policy in this file. The generated migration of Task 3 ships the 2 policies.
- Add one
SELECT attach_statement_handler('<table>', ARRAY['broadcast_table_changes']);line for each name inREALTIME_TABLES, exceptitemLedger. - For
itemLedger, passARRAY['apply_item_stock_quantities', 'broadcast_table_changes']. - Add one line with
ARRAY['broadcast_reference_changes']for each name inREALTIME_REFERENCE_TABLES. - Add the line for
notificationwithARRAY['broadcast_user_changes']. - Query
pg_publication_tablesforsupabase_realtime. Add one guardedALTER PUBLICATION supabase_realtime DROP TABLEfor each row. - Wrap each drop in a
DOblock that checkspg_publication_tablesfirst, so the migration is idempotent. - Add
CREATE OR REPLACE FUNCTION public.list_checksums(p_company_id TEXT)from the spec, with the fifth rowmesItems. - The
mesItemsrow hashesid, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, active, thumbnailPathand the model'sthumbnailPath. - Add
REVOKE ALL ON FUNCTION public.list_checksums(TEXT) FROM PUBLIC, anon;andGRANT EXECUTE ... TO authenticated;. - Run
pnpm --filter @carbon/checks clobbers.
Verify:
grep -c "attach_statement_handler(" packages/database/supabase/migrations/*_realtime-broadcast-attach.sql
# Expected: 87 (66 + 20 + 1)
pnpm --filter @carbon/checks exec vitest run src/conformance/no-authz-ddl-in-migrations.test.ts
# Expected: passed
Out of scope: any CREATE POLICY. The check rejects a policy on public or realtime in a hand-written migration.
Task 6b: Move event triggers and interceptor bodies out of migrations
Depends on: Task 5 Files:
- Create:
packages/database/src/event-system/attachments.ts— the triggers of 141 tables - Create:
packages/database/src/event-system/attachments-sync.ts,attachments-sync.test.ts - Create:
packages/database/src/event-system/handlers/*.sql— 64 functions, read from the database withpg_get_functiondef - Create:
packages/database/src/event-system/functions/set_event_triggers.sql - Create:
packages/database/supabase/migrations/20261004193811_drop-stale-interceptor-overload.sql - Create:
packages/database/supabase/migrations/20261004194527_event-attachments.sql(generated) - Modify:
packages/database/src/authz/sync.ts,migration.ts,cli.ts,helpers.ts - Modify:
packages/database/src/realtime-tables.ts— the 3 lists derive fromattachments.ts - Modify:
packages/database/supabase/migrations/20261004192633_realtime-broadcast-attach.sql— no attach call stays - Modify:
packages/checks/src/conformance/no-authz-ddl-in-migrations.ts— reject attach calls
Steps:
- Read the live triggers of each table from the local database. Write them to
attachments.ts. - Read each attached function with
pg_get_functiondef. Write each one tohandlers/<name>.sql. - Make
authz synccompare the live triggers withattachments.ts. - Make
authz migrationwrite oneSELECT set_event_triggers(...)for each changed table. - Run
pnpm --filter @carbon/database authz migration event-attachments. - Ask the user to run
pnpm db:migrate.
Verify:
SUPABASE_DB_URL=<local url> pnpm --filter @carbon/database exec vitest run src/authz src/event-system
# Expected: all passed; `authz check` reports 0 helpers, 0 tables, 0 event triggers
Out of scope: a change to what a trigger does. The takeover ships the triggers and the bodies as the database has them.
Task 5: Apply the migrations and regenerate types
Depends on: Task 4 Files:
- Modify:
packages/database/src/types.ts(generated) — gainslist_checksums
Steps:
- Ask the user to run
pnpm db:migrate. Wait for the user. - Run
pnpm run generate:types. - Run
EXPLAIN ANALYZE INSERTonjobOperationin a rolled-back transaction. Record the trigger time in.ai/runs/2026-10-04-realtime-broadcast.md. - Run
EXPLAIN ANALYZE SELECT * FROM list_checksums('<companyId>'). Record the time in the same file.
Verify:
psql "$SUPABASE_DB_URL" -c "SELECT count(*) FROM pg_publication_tables WHERE pubname = 'supabase_realtime';"
# Expected: 0
pnpm exec turbo run typecheck --filter=@carbon/database --concurrency=1
# Expected: 0 errors
Out of scope: hand edits to types.ts.
Task 6: Add the database tests
Depends on: Task 5 Files:
- Create:
packages/database/supabase/tests/realtime-broadcast.test.sql - Copy from (precedent):
packages/database/supabase/tests/rpc-privileges.test.sql
Steps:
- Copy the fixture block: 2 companies, 2 users, all inside one rolled-back transaction.
- Assert: an
INSERTintoitemfor company A adds 1 row torealtime.messageswith topiccompany:<A>:item. - Assert: an
UPDATEthat changes onlyupdatedAtadds 0 rows. - Assert: an
UPDATEof 150 rows adds 1 row withidsnull. - Assert: an
INSERTintonotificationadds 1 row with topicuser:<userId>:notification. - Assert: an
INSERTintocustomerTypeadds 1 row with topiccompany:<A>:reference. - Assert: as user A, a
SELECTonrealtime.messageswithrealtime.topicset tocompany:<B>:itemreturns 0 rows. - Assert: as user B, the topic
user:<A>:notificationreturns 0 rows. - Assert:
list_checksumsas user A for company B returns hashes of empty lists. - Assert:
list_checksumschanges after a customer rename and after an item delete.
Verify:
pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/realtime-broadcast.test.sql
# Expected: exit 0, ends with ROLLBACK
Out of scope: committed fixture rows.
Task 7: Add the realtime-table-has-trigger check
Depends on: Task 2 Files:
- Create:
packages/checks/src/conformance/realtime-table-has-trigger.ts - Create:
packages/checks/src/conformance/realtime-table-has-trigger.test.ts - Modify:
packages/checks/src/index.ts,packages/checks/src/run.ts— register the check - Copy from (precedent):
packages/checks/src/conformance/index-redirect-before-loaders.ts
Steps:
- Scan each file under
apps/{erp,mes}/appforrealtime: [in ahandleexport and foruseRealtime("…"). - Report a violation for each table name that
REALTIME_TABLESlacks. - Report a violation for each
"postgres_changes"string literal inapps/orpackages/react/src. - In the test, cover 3 cases: a listed table passes, an unlisted table fails, a
postgres_changesliteral fails.
Verify:
pnpm --filter @carbon/checks exec vitest run src/conformance/realtime-table-has-trigger.test.ts
# Expected: 3 tests passed
Out of scope: a baseline entry. The check must end with zero findings after Task 17.
Task 8: Add the private option to useRealtimeChannel
Depends on: Task 1 Files:
- Modify:
packages/react/src/hooks/useRealtimeChannel.ts— newprivate?: booleanoption and anonSubscribed?: (isReconnect: boolean) => voidoption
Steps:
- Pass
{ config: { private: true } }tocarbon.channel(topic, …)whenprivateis true. - Call
onSubscribed(true)on eachSUBSCRIBEDstatus after the first one. CallonSubscribed(false)on the first. - Add
privateto the effect dependencies.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/react --concurrency=1
# Expected: 0 errors
Out of scope: the retry schedule and the toast behavior.
Task 9: Add cachedClientLoader and the company id value
Depends on: Task 1 Files:
- Modify:
apps/erp/app/utils/react-query.ts— addLOADER,LOADER_GC_TIME,loaderQueryKey,cachedClientLoader,setCompanyId - Modify:
apps/erp/app/utils/react-query.test.ts— new cases - Modify:
apps/erp/app/routes/x+/_layout.tsx— callsetCompanyId(company.id)before the first child renders
Steps:
- Add
export const LOADER = "loader";andconst LOADER_GC_TIME = 1000 * 60 * 30;. - Replace the cookie read in
getCompanyIdwith a module variable thatsetCompanyIdwrites. - Add
loaderQueryKey(url: string). It returns[LOADER, companyId, pathname, search]. - Add
cachedClientLoaderwith the body from the spec. - Test: 2 concurrent calls for one URL call
serverLoader1 time. - Test: a call after
invalidateQueries({ queryKey: [LOADER] })callsserverLoaderagain. - Test: with no company id, the function calls
serverLoaderand writes no cache entry. - Test: the returned function has
hydrate === true.
Verify:
pnpm --filter erp exec vitest run app/utils/react-query.test.ts
# Expected: all tests passed
Out of scope: the existing key factories. Task 12 deletes the unused ones.
Task 10: Add the invalidation middleware to both roots
Depends on: Task 9 Files:
- Create:
packages/auth/src/middleware/invalidate.client.ts - Create:
packages/auth/src/middleware/invalidate.client.test.ts - Modify:
apps/erp/app/root.tsx— add the middleware toclientMiddleware - Modify:
apps/mes/app/root.tsx— store the client onwindow.clientCache; add the middleware - Modify:
apps/mes/app/types/global.d.ts(create it if absent) — declarewindow.clientCache - Copy from (precedent):
packages/auth/src/middleware/flash.client.ts
Steps:
- Export
createInvalidationMiddleware({ getCache, skipPaths }). - After
await next(), return ifrequest.methodisGET. - Return if
skipPathsholds the request pathname. - Call
getCache()?.invalidateQueries({ queryKey: ["loader"] }). - In each root, pass
skipPaths: [path.to.refreshSession]. - In the MES root, copy the ERP
useStateinitializer that reuseswindow.clientCache. - Test 3 cases: a
GETinvalidates nothing, aPOSTinvalidates, aPOSTto/refresh-sessioninvalidates nothing.
Verify:
pnpm --filter @carbon/auth exec vitest run src/middleware/invalidate.client.test.ts
# Expected: 3 tests passed
Out of scope: flashClientMiddleware. @carbon/auth gets no dependency on @tanstack/react-query; type the cache as { invalidateQueries(filter: { queryKey: unknown[] }): unknown }.
Task 11: Convert the 27 cached clientLoader exports
Depends on: Task 10 Files:
- Modify: each file that
grep -rlE "export (async function|const) clientLoader" apps/erp/app/routes/api+prints (27 files)
Steps:
- In each file, replace the
clientLoaderfunction and its.hydrateline withexport const clientLoader = cachedClientLoader<typeof loader>();. - If the old code passed a
staleTimeother thanRefreshRate.Low, pass the samestaleTime. - Remove the imports that the file no longer uses.
inventory.storage-units.tsandinventory.storage-units-with-quantities.tsshared one key. Confirm that their URL keys now differ.
Verify:
grep -rLE "cachedClientLoader<typeof loader>" $(grep -rlE "clientLoader" apps/erp/app/routes/api+) | wc -l
# Expected: 0
pnpm exec turbo run typecheck --filter=erp --concurrency=1
# Expected: 0 errors
Out of scope: the server loader of each file.
Task 12: Delete the invalidation-only clientAction exports
Depends on: Task 10 Files:
- Modify: each file that
grep -rlE "export (async function|const) clientAction" apps/erp/app/routesprints (78 files) - Modify:
apps/erp/app/utils/react-query.ts— delete each export with zero importers - Modify:
apps/erp/app/components/Form/Item.tsx,Form/Account.tsx,Form/EmailRecipients.tsx,components/Selectors/UserSelect/useUserSelect.ts— movecachedApiQuerycallers toloaderQueryKey(url)
Steps:
- Read each
clientAction. If it only invalidates or nulls a key and callsserverAction(), delete the export. - If it does other work, keep that work and delete the cache lines.
- Change
cachedApiQuery(query, url)to take onlyurl. Key it withloaderQueryKey(url). - Delete
invalidateUserSelectQueriesandinvalidateInspectionDocuments, and their callers. - For each export left in
react-query.ts, rungrep -rn "<name>" apps/erp/app. Delete the export if only its definition matches. - Keep
ITEM_QUANTITIES_QUERY_KEYanditemQuantitiesQuery.
Verify:
grep -rn "setQueryData\|getQueryData" apps/erp/app/routes | wc -l
# Expected: 0
pnpm exec turbo run typecheck --filter=erp --concurrency=1
# Expected: 0 errors
Out of scope: the server action of each file.
Task 13: Add useRealtime and useRouteRealtime to @carbon/react
Depends on: Tasks 5, 8, 10 Files:
- Create:
packages/react/src/hooks/useRealtime.ts— exportsuseRealtime,useDebouncedRealtime,useRealtimeRevalidator,useRouteRealtime,matchesIdFilter - Create:
packages/react/src/hooks/useRealtime.test.ts - Modify:
packages/react/src/hooks/index.ts— export them - Modify:
apps/erp/app/hooks/useRealtime.tsx,apps/erp/app/hooks/useDebouncedRealtime.ts,apps/mes/app/hooks/useRealtime.tsx— re-export from@carbon/react - Modify:
apps/erp/app/routes/x+/_layout.tsx,apps/mes/app/routes/x+/_layout.tsx— calluseRouteRealtime(company.id) - Copy from (precedent):
apps/mes/app/hooks/useRealtime.tsx(useRealtimeRevalidator)
Steps:
- Move
useRealtimeRevalidatorfrom the MES file. It skips the revalidation while a fetcher is submitting. - Change it to run the skipped revalidation when the fetcher returns to
idle. - Write
matchesIdFilter(filter, ids). It parsesid=eq.<id>andid=in.(<ids>). - If the filter names another column,
matchesIdFilterreturns true. - If
idsis null,matchesIdFilterreturns true. - Write
useRealtime(table: RealtimeTable, filter?, debounceMs = 300). It takescompanyIdfrom aRealtimeContextthat the shell provides. useRealtimesubscribes tocompany:<companyId>:<table>withprivate: trueand event"*"on"broadcast".- On a matching message, it restarts the debounce timer. When the timer ends, it invalidates
["loader"]and revalidates. - Write
useRouteRealtime(companyId). It readshandle.realtimefromuseMatches()and subscribes for each unique table. useRouteRealtimealso subscribes tocompany:<companyId>:reference. On a message it invalidates["loader"]only.- On
onSubscribed(true), both hooks invalidate and revalidate one time. - Test
matchesIdFilterwith 5 cases:id=eq,id=in, a parent column, null ids, no filter.
Verify:
pnpm --filter @carbon/react exec vitest run src/hooks/useRealtime.test.ts
# Expected: 5 tests passed
pnpm exec turbo run typecheck --filter=@carbon/react --concurrency=1
# Expected: 0 errors
Out of scope: callers of useRealtime. Task 17 converts them. @carbon/react reads the cache from window.clientCache; it gets no new dependency in this task.
Task 14: Move the ERP lists to useLiveList
Depends on: Task 13 Files:
- Create:
packages/react/src/hooks/useLiveList.ts,packages/react/src/hooks/useLiveList.test.ts - Modify:
packages/react/package.json— add@tanstack/react-queryat the version the apps use (5.97.0) - Modify:
apps/erp/app/stores/items.ts,customers.ts,suppliers.ts,people.ts— hooks read the query cache - Modify:
apps/erp/app/components/RealtimeDataProvider.tsx— 4useLiveListcalls and theitemStockQuantitieslistener - Copy from (precedent):
apps/erp/app/components/RealtimeDataProvider.tsx(the column lists and the IndexedDB keys)
Steps:
- Add the dependency with a bare
pnpm install. Checkgit diff --stat pnpm-lock.yamlfor unrelated changes. - Write
defineLiveList({ name, table, view?, columns, sort, enrich? }). It returns the definition and the key["live", companyId, name]. - Write the pure function
applyBroadcast(rows, { op, ids }, fetched, sort). Test it with 4 cases: insert, update, delete, duplicate insert. - Write
useLiveList(definition, companyId). It does the cold-load steps 1 to 6 of the spec. - It subscribes to the definition's topic. On a message it does the broadcast steps 1 to 5 of the spec.
- It calls
list_checksumsone time for all lists that mount in the same tick. - Store each list in IndexedDB as
{ rows, checksum }under<name>:<companyId>. - If a stored value is a bare array (the old format), treat the checksum as absent.
- The items definition sets
enrichto mergeitemSupersessionrows. It also listens to theitemSupersessiontopic and resyncs. - The people definition reads the
employeesview and listens to theemployeetopic. A message always resyncs. - In each store file, export the hook as
() => [rows, setRows].setRowscallssetQueryDataon the list key. - Change
useParts,useTools,useServices,useMaterialstouseQuerywith aselectfilter. - Keep
upsertIntoListStoreandlatestRevisionByReadableId. - In the provider, on an
itemStockQuantitiesmessage, invalidate the queries whose key starts withITEM_QUANTITIES_QUERY_KEY.
Verify:
pnpm --filter @carbon/react exec vitest run src/hooks/useLiveList.test.ts
# Expected: 4 tests passed
pnpm exec turbo run typecheck --filter=erp --concurrency=1
# Expected: 0 errors, with no change to a file that calls useItems, useCustomers, useSuppliers or usePeople
Out of scope: the about 200 consumer files. If a consumer fails the typecheck, fix the hook's return type, not the consumer.
Task 15: Move the MES lists and remove nanostores
Depends on: Task 14 Files:
- Modify:
apps/mes/app/stores/items.ts,apps/mes/app/stores/people.ts,apps/mes/app/components/RealtimeDataProvider.tsx - Delete:
packages/react/src/hooks/useNanoStore.ts - Modify:
packages/react/src/hooks/index.ts,apps/erp/app/hooks/index.ts,apps/mes/app/hooks/index.ts— removeuseNanoStore - Modify:
apps/erp/package.json,apps/mes/package.json,packages/react/package.json,pnpm-workspace.yaml— removenanostoresand@nanostores/react
Steps:
- Define the MES item list with name
mesItemsand the MES column list. - Define the MES people list with the same definition as the ERP.
- Replace the MES provider body with 2
useLiveListcalls. - Delete
useNanoStoreand its exports. - Remove the 2 packages from each
package.jsonand from the catalog. Run a barepnpm install.
Verify:
grep -rl "nanostores" apps packages --include="*.ts" --include="*.tsx" --include="package.json" | grep -v node_modules | wc -l
# Expected: 0
pnpm exec turbo run typecheck --filter=mes --concurrency=1
# Expected: 0 errors
Out of scope: localforage. The topbar search keeps its own keys.
Task 16: Move notifications and the implementation hub
Depends on: Task 13 Files:
- Modify:
apps/erp/app/hooks/useNotifications.tsx - Modify:
apps/erp/app/hooks/useImplementationRealtime.tsx
Steps:
- In
useNotifications, subscribe touser:<userId>:notificationwithprivate: true. - On
INSERTorUPDATE, read the rows with.in("id", ids).eq("companyId", companyId). Use the select string of the initial load. - Apply the existing
digestedIntorules to each row. - On
DELETE, remove the rows whose_idis inids. - If
idsis null, run the initial load again. - In
useImplementationRealtime, replace the 4postgres_changeslisteners with 4useRealtimecalls.
Verify:
grep -rn "postgres_changes" apps/erp/app/hooks/useNotifications.tsx apps/erp/app/hooks/useImplementationRealtime.tsx | wc -l
# Expected: 0
pnpm exec turbo run typecheck --filter=erp --concurrency=1
# Expected: 0 errors
Out of scope: markMessageAsRead and the digest loader.
Task 17: Declare handle.realtime on the routes and convert the subscribers
Depends on: Task 13 Files:
- Modify: each route layout or page under the folders in the spec's "Operational routes" list
- Modify: each route under
apps/mes/app/routes/x+that has aloaderand a default export - Modify: the 41 files that
grep -rlE "useRealtime\(|useDebouncedRealtime\(|useRealtimeChannel\(" appsprints - Modify:
apps/erp/app/types/— addrealtime?: RealtimeTable[]to theHandletype
Steps:
- For each route, list the tables that its
loaderreads. Follow each service function to its.from("…")call. - If the loader reads a view, list the base tables that the page must follow.
- Add
realtime: [...]to the route'shandle. Merge it with an existingbreadcrumbormodulekey. - If a table is not in
REALTIME_TABLES, add it there and add itsattach_statement_handlerline to a new migrationrealtime-broadcast-attach-2. - Set the ERP job layout
x+/job+/$jobId.tsxto["job", "jobOperation", "jobMaterial", "jobMakeMethod", "jobOperationStep", "jobOperationStepRecord", "productionEvent", "pickingListLine", "modelUpload"]. - For each of the 41 subscriber files: if the file is a route, delete its
useRealtimecall and usehandle.realtime. - If the file is a component that only revalidates, keep
useRealtime(table, filter). - If the file reads
payload.neworpayload.old, read the rows byidsthroughcarbon.from(table).select().in("id", ids). JobBillOfProcess.tsxhas 3 channels. Convert theproductionEventandjobOperationNotechannels by step 8. Delete thebop-stepschannel.- Delete each
companyIdguard on a payload row. The topic carries the company. - Run the check of Task 7. Fix each finding.
Verify:
grep -rn "postgres_changes" apps packages --include="*.ts" --include="*.tsx" | grep -v node_modules | grep -v "realtime-table-has-trigger" | wc -l
# Expected: 0
pnpm --filter @carbon/checks exec vitest run
# Expected: all passed, 0 findings for realtime-table-has-trigger
pnpm exec turbo run typecheck --filter=erp --concurrency=1
pnpm exec turbo run typecheck --filter=mes --concurrency=1
# Expected: 0 errors each
Out of scope: routes under settings, users, account, accounting, people, resources, documents, templates and workflows that have no subscription today. If step 4 adds more than 15 tables, STOP and report the list.
Task 18: Add useLoaderQuery and migrate the .load() call sites
Depends on: Task 11 Files:
- Create:
packages/react/src/hooks/useLoaderQuery.ts - Modify: each file that
grep -rlE "\.load\(" apps/erp/app apps/mes/appprints (137 call sites)
Steps:
- Write
useLoaderQuery<L>(url: string | null, options?). It callsuseQuerywith the key["loader", companyId, pathname, search]. - The
queryFnfetches<url>with.datahandling equal tofetcher.load: usefetch(url)andres.json()forapi+routes. - If
urlis null, setenabled: false. - Migrate one module first:
apps/erp/app/components/Form/(the pickers). Run the browser check of Task 21 step 2 on it. - Then migrate each remaining call site where the URL is under
path.to.api. - Replace
fetcher.datawithdata, andfetcher.state === "loading"withisPending. - Leave a call site on
useFetcherif its URL is a page route. Add no comment.
Verify:
grep -rnE "\.load\(path\.to\.api" apps/erp/app apps/mes/app | wc -l
# Expected: 0
pnpm exec turbo run typecheck --filter=erp --concurrency=1
# Expected: 0 errors
Out of scope: suspense variants and refetchInterval. If an api+ route returns a turbo-stream body that res.json() cannot read, STOP and report.
Task 19: Add useAction and migrate the submit call sites
Depends on: Task 13 Files:
- Create:
packages/react/src/hooks/useAction.ts,packages/react/src/hooks/useAction.test.tsx - Modify: each file that
grep -rlE "fetcher\w*\.submit\(" apps/erp/app apps/mes/appprints
Steps:
- Write
useAction<A>({ onSuccess?, onError?, key? }). It wrapsuseFetcher<A>({ key }). - Return
{ submit, Form, data, isPending, pending }.pendingisfetcher.formData. - Call
onSuccess(data)one time when the state returns toidlewith data whosesuccessis not false. - Call
onError(data)one time when the data hassuccess === falseor anerrorkey. - Hold the callbacks in refs, so a new closure on each render fires nothing.
- Test 3 cases with
createRoutesStub: success, error, and a second submit that firesonSuccessagain. - Migrate
apps/erp/app/modules/salesfirst. Run its playbooks under.ai/playbooks/before you continue. - Then migrate each file where an effect reads
fetcher.dataorfetcher.stateto close, toast or navigate. - Delete the effect. Move its body into
onSuccessoronError. - Leave a call site on
useFetcherif no effect reads its result.
Verify:
pnpm --filter @carbon/react exec vitest run src/hooks/useAction.test.tsx
# Expected: 3 tests passed
pnpm --filter @carbon/checks exec vitest run src/conformance/no-unguarded-submit.test.ts
# Expected: passed
pnpm exec turbo run typecheck --filter=erp --concurrency=1
pnpm exec turbo run typecheck --filter=mes --concurrency=1
# Expected: 0 errors each
Out of scope: ValidatedForm and packages/form. Optimistic cache writes. The MES "Complete Batch" fetcher owner (.ai/lessons.md line 1994) keeps its place in JobOperation.
Task 20: Update the rules, the lessons and the AGENTS.md files
Depends on: Tasks 12, 15, 17, 19 Files:
- Modify:
.claude/rules/clientAction-patterns.md— rewrite forcachedClientLoaderand the middleware - Modify:
.claude/rules/coding-conventions.md— the State section - Create:
.claude/rules/realtime-system.md— topics, the 3 functions,handle.realtime,useLiveList, the check - Modify:
.claude/rules/event-system.md,.claude/rules/authz-manifest.md— the 3 new managed functions (37 → 40) - Modify:
.ai/lessons.md— 2 lessons - Modify:
packages/react/AGENTS.md,packages/database/AGENTS.md,AGENTS.md(Task Router row for realtime) - Modify: the spec — status
implemented, changelog entry
Steps:
- Write the lesson "a subscription to an unpublished table fails silently" in the
Context → Problem → Rule → Applies toformat. - Write the lesson "
getCompanyId()read an httpOnly cookie and always returned null". - In each rule, describe committed code only.
- Do the STE-80 review pass on the spec after the edit.
Verify:
grep -rn "window.clientCache?.setQueryData\|nanostores\|postgres_changes" .claude/rules | wc -l
# Expected: 0
Out of scope: product docs under docs/. The change adds no user-facing feature that needs a page.
Task 21: Run the full verification and the browser tests
Depends on: all tasks Files:
- Create:
.ai/playbooks/realtime-broadcast.md(through/test) - Modify:
.ai/runs/2026-10-04-realtime-broadcast.md— results
Steps:
- Run
pnpm run lint,pnpm run test, and the 5 scoped typechecks of the spec, one at a time. - Run
/auth, then/testwith these 8 checks: - Complete an operation in the MES. The ERP job page shows it as complete within 3 seconds, with no reload.
- Add a customer type in tab A. The picker in tab B shows it within 3 seconds.
- Reload with no data change. The network log shows 1
list_checksumscall and 0 calls toitem,supplier,customer,employees,itemSupersession. - Rename a customer in tab A, close tab B first, then open tab B. The log shows a
customerfetch only. - Send a notification to the user. The bell shows it within 3 seconds.
- Switch company. No item, customer or cached list of the first company shows.
- Run the MES "Complete Batch" flow. The redirect to the operations page happens.
- Open the ERP job page, the sales order page and the MES operations page. The console shows 0 realtime errors.
- Run
/self-review.
Verify:
pnpm run lint && pnpm run test
# Expected: exit 0
Out of scope: a push or a pull request. Ask the user before each one.