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.
Demo Templates, Anytime — implementation plan
Spec: .ai/specs/2026-08-18-demo-templates-anytime-revert.md
Branch: feat/onboarding-templates
Progress
- Task 1: Replace
applyDataset'sbeforeTiershook with awipeFirstoption - Task 2: Add the snapshot flag and the two new events to
@carbon/lib - Task 3: Export
wipeAndLoad,getCompanyGroupIdand a scope helper fromcompany-restore.ts - Task 4: Rework
company-template.ts— snapshot, phases,readymarker - Task 5: Add the template finalize and revert Inngest functions
- Task 6: Pass
snapshot: truefrom onboarding - Task 7: ERP service + server trigger wrappers for demo data
- Task 8: The
Settings → Demo Dataroute, path helper and nav entry - Task 9: The status poll API route
- [~] Task 10: Demo Data UI components — components done;
JobProgressModalreuse NOT done (see Blocker below) - Task 11: Update the rules and AGENTS.md that this work makes stale
- Task 12: End-to-end verification — blocked on user (needs permission to reseed + browser run)
Blocker: Task 10 step 3 (JobProgressModal)
The plan said "add the three new phase keys to PHASE_ORDER/PHASE_LABELS". That badly
understated the work. JobProgressModal is not a generic component:
- its mode union is literally
"export" | "restore" | "revert"; - it hardcodes its poll URL as
/api/settings/backup-restore-status/${runId}; - its status fetcher is typed to the restore endpoint's
{ status, rows, error, progress, startedAt }shape, not this feature's{ run }.
Reusing it means widening the mode union, parameterising the status URL, and adapting the response shape — surgery on a shipped component the Backups page depends on, which Task 8 lists as out of scope.
Shipped instead: the review row renders "applying…" / "reverting…" with a spinner, and the
loader/endpoint already carry full { phase, done, total } progress. So the DATA is there;
only the phased progress bar is missing.
Two ways forward, for the user to choose:
- Leave as-is. Complete and safe; a phased bar becomes a follow-up.
- Parameterise
JobProgressModal(status URL + mode + response adapter) and reuse it, re-verifying the Backups page.
Dependencies
- Task 4 needs Tasks 1, 2, 3.
- Task 5 needs Tasks 2, 3, 4.
- Task 6 needs Task 2.
- Task 7 needs Task 4 (marker shape).
- Tasks 8, 9 need Task 7.
- Task 10 needs Task 8.
- Tasks 1, 2, 3 are independent of each other and may run in parallel.
- Tasks 6 and 7 are independent of each other.
- Task 11 is independent of everything but should land in the same change.
- Task 12 is last.
Task 1: Replace applyDataset's beforeTiers hook with a wipeFirst option
Depends on: none
Files:
- Modify:
packages/database/src/datasets/index.ts— swap the option - Modify:
packages/database/src/seed-dev.ts— migrate the one call site - Modify:
packages/database/AGENTS.md— correct the "dev-only" claim aboutwipe.ts
Steps:
In
packages/database/src/datasets/index.ts, add this import next to the existing./sql.tsimport:import { wipeCompanyBusinessData } from "./wipe.ts";In the
applyDatasetoptions type (currently lines 56-65), delete thebeforeTiersproperty and its comment, and add in its place:/** * Clear the company's existing business data before the tiers run, inside * the same transaction. Preserves everything bootstrap created (chart of * accounts, unitOfMeasure, sequences, locations, paymentTerm) because the * tiers require that config to exist — this is NOT the restore engine's * tabula-rasa wipe. */ wipeFirst?: boolean;In the destructure (currently lines 67-75), replace
beforeTierswithwipeFirst = false.Replace the line
if (beforeTiers) await beforeTiers(ctx);(currently line 92) with:if (wipeFirst) { log("Wiping existing business data..."); await wipeCompanyBusinessData(ctx); }In
packages/database/src/seed-dev.ts, replace the wholebeforeTiers: async (ctx) => {...}property in theapplyDatasetcall (currently lines 64-72, including the// Dev-only, and must share the tiers' transaction.comment) with:wipeFirst: !skipWipeThen delete the now-unused
wipeCompanyBusinessDataimport from that file, and add aconsole.log("Skipping wipe (--skip-wipe).")immediately before theapplyDatasetcall, guarded byif (skipWipe), so the CLI keeps printing that line.In
packages/database/AGENTS.md, find the sentence under Dev Seed reading "pnpm db:seed:devrunssrc/seed-dev.ts(the dev CLI);cli.tsparses its args,bootstrap.tssets up the company andwipe.tsclears prior data. All three are dev-only and are never reachable from the shared engine or from onboarding." Replace the second sentence with: "cli.tsandbootstrap.tsare dev-only.wipe.tsis reached from the shared engine viaapplyDataset'swipeFirstoption, which both the dev CLI and thecompany-templatejob use; it is not exported on its own."Also update the
./datasetsrow of the Key Exports table so theapplyDatasetsignature shown there includeswipeFirst.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: exits 0, no TS errors. `beforeTiers` must appear nowhere:
grep -rn "beforeTiers" packages/ apps/ --include=*.ts --include=*.tsx
# Expected: no output.
Out of scope: Do not change anything inside packages/database/src/datasets/wipe.ts
itself, and do not add a ./datasets/wipe subpath to package.json. The wipe stays
un-exported; wipeFirst is the only way to reach it.
Task 2: Add the snapshot flag and the two new events to @carbon/lib
Depends on: none
Files:
- Modify:
packages/lib/src/events.ts— extendcarbon/company-template, add two events - Modify:
packages/lib/src/trigger.ts— add two entries totaskToEvent - Copy from (precedent): the
carbon/company-restore-finalizeandcarbon/company-restore-revertentries in the same two files
Steps:
In
packages/lib/src/events.ts, add a field to the existing"carbon/company-template"data block (it currently holdscompanyId,userId,datasetKey,templateRunId):/** * Snapshot the company before wiping, and leave the run parked on a * keep/revert decision instead of clearing the marker. Onboarding and the * Settings page both set this; absent means the legacy fire-and-forget * behaviour. */ snapshot?: boolean;Directly below that block, add:
// Keep an applied demo template — drop the pre-apply snapshot and the marker. "carbon/company-template-finalize": { data: { companyId: string; templateRunId: string; }; }; // Undo an applied demo template — wipe and reload the pre-apply snapshot. "carbon/company-template-revert": { data: { companyId: string; userId: string; templateRunId: string; }; };In
packages/lib/src/trigger.ts, add two entries totaskToEvent, keeping the alphabetical order of the existing keys (immediately after"company-template"):"company-template-finalize": "carbon/company-template-finalize", "company-template-revert": "carbon/company-template-revert",
Verify:
pnpm exec turbo run typecheck --filter=@carbon/lib
# Expected: exits 0, no TS errors.
Out of scope: Do not touch the carbon/company-import block above it, including its
templateIndustryId comment about _templates/ — that is the dormant archive design and
is unrelated to this work.
Task 3: Export wipeAndLoad, getCompanyGroupId and a scope helper from company-restore.ts
Depends on: none
Files:
- Modify:
packages/jobs/src/inngest/functions/tasks/company-restore.ts
Steps:
Add the
exportkeyword toasync function wipeAndLoad((currently line 47) and toasync function getCompanyGroupId((currently line 238). Change nothing about their bodies or signatures.Read the block that currently computes the restore scope (around lines 415-426 —
targetGroupId,groupCompanyCount,includeGroup). Extract it verbatim into a new exported module-level function placed immediately aftergetCompanyGroupId:/** * Which scope a wipe-and-load should cover for this company. Group-scoped tables * (the shared chart of accounts) are only in scope when this company is the sole * member of its group — otherwise the wipe would reach another tenant's data. * Shared by the restore path and the demo-template path so the two can never * disagree about what a revert is allowed to touch. */ export async function resolveRestoreScope( client: ServiceRole, companyId: string ): Promise<{ targetGroupId: string | null; includeGroup: boolean }> { // ...moved body: compute targetGroupId via getCompanyGroupId, then the // company count for that group, then includeGroup = groupCompanyCount === 1 }Use the exact same queries the inline block uses — do not re-derive them. Then replace the inline block in
companyRestoreFunctionwith a call to the new function, so there is one implementation, not two.If the inline block turns out to depend on local variables that are not available at module scope (anything beyond
clientandcompanyId), STOP and report — do not improvise a different scope rule.Add a one-line comment above each newly-exported symbol noting that
company-template.tsis now a second caller, so a future reader does not assume the restore path is the only consumer.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exits 0, no TS errors.
Out of scope: Do not change wipeAndLoad's behaviour, its progress reporting, or the
session_replication_role handling. This task is exports and one extraction only.
Task 4: Rework company-template.ts — snapshot, phases, ready marker
Depends on: Tasks 1, 2, 3
Files:
- Modify:
packages/jobs/src/inngest/functions/tasks/company-template.ts - Copy from (precedent):
packages/jobs/src/inngest/functions/tasks/company-restore.tslines 440-566 (the snapshot-then-wipe-then-ready sequence and its idempotent snapshot reuse)
Steps:
Widen the marker types (currently lines 13-21):
type TemplateStatus = "running" | "ready" | "failed" | "reverting"; type TemplateMeta = { templateRunId: string; status: TemplateStatus; datasetKey?: string; startedAt?: string; error?: string | null; /** Folder name of the pre-apply snapshot in this company's bucket. */ snapshotPath?: string; /** Scope the forward apply covered, so a revert undoes exactly that. */ includeGroup?: boolean; progress?: { phase: string; done: number; total: number }; };Add these imports (all relative, all from sibling files in the same directory):
import { getJobDatabaseClient } from "../../../db"; import { backupAssetsDir, backupDir, getCompanyTableCatalog, readBackup, removeStoragePrefix, restoreAssetsFromBackup, writeBackupManifest } from "./company-backup"; import { buildCompanyBackup } from "./company-export"; import { resolveRestoreScope, wipeAndLoad } from "./company-restore";Confirm each of these is actually exported before relying on it.
getJobDatabaseClientlives inpackages/jobs/src/db.ts; check the correct relative depth fromfunctions/tasks/and fix the path if it differs. If any symbol is not exported, STOP and report — do not add exports beyond the three named in Task 3.Add a progress reporter alongside the existing marker helpers, modelled on
makeProgressReporterincompany-restore.ts:function makeTemplateProgress( client: ServiceRole, args: { companyId: string; userId: string; templateRunId: string } ) { return async (progress: { phase: string; done: number; total: number }) => { await writeTemplateMarker(client, { ...args, patch: { progress } }); }; }Destructure
snapshotfromevent.dataincompanyTemplateFunction:const { companyId, userId, datasetKey, templateRunId, snapshot: takeSnapshot = false } = event.data;Delete the entire
item-count guard block (currently lines 142-169, from the// A template is a one-shot on a fresh company.comment through the closing brace of theif ((existingItems.count ?? 0) > 0) {block). Its idempotency job is now done bywipeFirstplus snapshot reuse.Replace it with a refusal that protects an unresolved review row:
// A pending keep/revert owns the only snapshot of the user's real data. // Applying again would overwrite it, so refuse until it is resolved. const existing = await readTemplateMarker(client, companyId); if ( existing && existing.metadata.templateRunId !== templateRunId && existing.metadata.status !== "failed" ) { throw new NonRetriableError( "A demo data change is already pending — keep or revert it first." ); }After the existing
runningmarker write, and onlyif (takeSnapshot), add the snapshot step. Mirrorcompany-restore.ts:469-500exactly, including its idempotent reuse comment:const db = getJobDatabaseClient(1); const report = makeTemplateProgress(client, { companyId, userId, templateRunId }); const { includeGroup } = await resolveRestoreScope(client, companyId); let snapshotPath = existing?.metadata.snapshotPath ?? undefined; if (takeSnapshot && !snapshotPath) { await report({ phase: "snapshot", done: 0, total: 1 }); snapshotPath = `_pre-template-${templateRunId}`; const snap = await buildCompanyBackup(client, db, { companyId, userId, label: `Pre-template ${templateRunId}`, includeStorage: "all", name: snapshotPath }); await writeBackupManifest(client, companyId, snapshotPath, snap.manifest); await writeTemplateMarker(client, { companyId, userId, templateRunId, patch: { snapshotPath, includeGroup } }); await report({ phase: "snapshot", done: 1, total: 1 }); }The snapshot must be taken inside the existing
trythat writes thefailedmarker, so a snapshot failure is visible rather than leaving the marker onrunning.Pass
wipeFirst: takeSnapshotto theapplyDatasetcall, and bracket it with phase reports:await report({ phase: "wipe", done: 0, total: 1 }); await applyDataset(pgClient, { companyId, userId, dataset, timeZone, wipeFirst: takeSnapshot, log: (message) => logger.info(message, { companyId, templateRunId }) }); await report({ phase: "apply", done: 1, total: 1 });Note
wipeFirstis tied totakeSnapshotdeliberately: wiping without a snapshot would be unrecoverable, so the two are never allowed to diverge.Replace the terminal
clearTemplateMarker(currently line 220) with a branch:if (takeSnapshot) { // Parked on keep/revert — the marker holds the snapshot until the user // decides. Clearing here would strand the snapshot with nothing pointing // at it. await writeTemplateMarker(client, { companyId, userId, templateRunId, patch: { status: "ready", progress: undefined } }); } else { await clearTemplateMarker(client, companyId); }Update the doc comment on
writeTemplateMarker(currently lines 49-55) — it says "Cleared on success", which stops being true for the snapshot path.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exits 0, no TS errors.
grep -n "existingItems" packages/jobs/src/inngest/functions/tasks/company-template.ts
# Expected: no output (the item-count guard is gone).
Out of scope: Do not change the function's concurrency config, the
NonRetriableError on an unknown dataset key, or the dedicated
getPostgresConnectionPool(2) and its finally { pgClient?.release() }.
Task 5: Add the template finalize and revert Inngest functions
Depends on: Tasks 2, 3, 4
Files:
- Modify:
packages/jobs/src/inngest/functions/tasks/company-template.ts— two new exports - Modify:
packages/jobs/src/inngest/functions/tasks/index.ts— re-export them - Modify:
packages/jobs/src/inngest/index.ts— register them - Copy from (precedent):
packages/jobs/src/inngest/functions/tasks/company-restore.tslines 586-617 (companyRestoreFinalizeFunction) and lines 619-715 (companyRestoreRevertFunction)
Steps:
In
company-template.ts, addcompanyTemplateFinalizeFunction, copying the shape ofcompanyRestoreFinalizeFunctionverbatim and substituting: idcompany-template-finalize, eventcarbon/company-template-finalize, concurrency key"'company-template-' + event.data.companyId"withscope: "env"andlimit: 1, and the marker helpersreadTemplateMarker/clearTemplateMarker. It readsmarker.metadata.snapshotPath, callsremoveStoragePrefix(client, companyId, backupDir(snapshotPath))when set, then clears the marker.Add
companyTemplateRevertFunction, copyingcompanyRestoreRevertFunctionand substituting the same id/event/marker helpers. It must:- read the marker; if there is no
snapshotPath, log and return{ templateRunId, reverted: false }without touching data; - write
status: "reverting"; readBackup(client, companyId, snapshotPath),getCompanyTableCatalog(db), thenwipeAndLoad(db, catalog, snapshot, { companyId, userId: "", remap: false, includeGroup: marker?.metadata.includeGroup ?? false, targetGroupId, onProgress: report })wheretargetGroupIdcomes fromresolveRestoreScope;restoreAssetsFromBackupfrombackupAssetsDir(snapshotPath)withsrcBucket: companyId;removeStoragePrefixthe snapshot folder, then clear the marker;- on a throw, write
status: "failed"witherror: \Revert failed: ${message}`` and leave the snapshot path on the marker so the user can retry. This is the same failure contract as restore's revert; do not clear the marker in the catch.
- read the marker; if there is no
Widen the concurrency key on the existing
companyTemplateFunctionso all three share it, matching how restore does it. Keep the existing unkeyed{ limit: 2 }entry alongside it:concurrency: [ { limit: 2 }, { key: "'company-template-' + event.data.companyId", scope: "env", limit: 1 } ]Add both new functions to the
./company-templateexport line inpackages/jobs/src/inngest/functions/tasks/index.ts, keeping the existingcompanyTemplateFunctionexport.Register both in
packages/jobs/src/inngest/index.tsin the same two placescompanyTemplateFunctionalready appears (the import list and the functions array — currently around lines 71 and 118).
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exits 0.
grep -c "companyTemplateFinalizeFunction\|companyTemplateRevertFunction" packages/jobs/src/inngest/index.ts
# Expected: 4 (each name appears in both the import and the registration array).
Out of scope: Do not modify companyRestoreFinalizeFunction or
companyRestoreRevertFunction — copy from them, leave them alone.
Task 6: Pass snapshot: true from onboarding
Depends on: Task 2
Files:
- Modify:
apps/erp/app/services/onboarding.server.ts— one field on the trigger payload
Steps:
In
startCompanyTemplate(currently lines 100-117), addsnapshot: trueto thetrigger("company-template", { ... })payload alongside the existingcompanyId,userId,datasetKeyandtemplateRunId.Update the function's doc comment to record why: a signup-time template is snapshotted too, so it stays revertible from Settings later. The company is nearly empty at this point, so the snapshot is cheap.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exits 0.
grep -n "snapshot: true" apps/erp/app/services/onboarding.server.ts
# Expected: one match inside startCompanyTemplate.
Out of scope: Do not change the re-entry path's call at onboarding.server.ts:183-185
in any other way, and do not touch provisionCompanyData's three-way branch.
Task 7: ERP service + server trigger wrappers for demo data
Depends on: Task 4
Files:
- Create:
apps/erp/app/modules/settings/demoData.service.ts - Create:
apps/erp/app/modules/settings/demoData.server.ts - Modify:
apps/erp/app/modules/settings/index.ts— addexport * from "./demoData.service"; - Copy from (precedent):
apps/erp/app/modules/settings/backups.service.ts(getCompanyRestoreRuns,getCompanyExportRun) andapps/erp/app/modules/settings/backups.server.ts(startCompanyRestore,finalizeCompanyRestore,revertCompanyRestore)
Steps:
demoData.service.tsexports one reader:export async function getCompanyTemplateRun( client: SupabaseClient<Database>, companyId: string );It selects
entityId, metadata, createdAtfromexternalIntegrationMappingwhereintegration = "company-template"andcompanyId = companyId, with.maybeSingle()— one marker row per company, exactly likegetCompanyExportRundoes for"company-export". Return the raw{ data, error }; do not throw. Type the metadata locally in this file (templateRunId,status,datasetKey,startedAt,error,snapshotPath,progress) rather than importing from@carbon/jobs— the app must not pull job internals into its bundle.demoData.server.tsexports three thin trigger wrappers, matching the shape ofbackups.server.ts:export async function startCompanyTemplate(args: { companyId: string; userId: string; datasetKey: string }): Promise<{ templateRunId: string }>; export async function finalizeCompanyTemplate(args: { companyId: string; templateRunId: string }): Promise<void>; export async function revertCompanyTemplate(args: { companyId: string; userId: string; templateRunId: string }): Promise<void>;startCompanyTemplatemintstemplateRunIdwithnanoid()(same asonboarding.server.ts:107does) and triggers"company-template"withsnapshot: true. The other two trigger"company-template-finalize"and"company-template-revert". Keep these in a.server.tsfile, not the service — the existingbackups.server.tscomment explains this is to keepBufferout of the client bundle.Add only the service to the module barrel (
index.ts)..server.tsfiles are not barrelled in this module — check howbackups.server.tsis imported at its call sites and follow that exactly.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exits 0.
Out of scope: Do not add demo-data functions to backups.service.ts or
backups.server.ts, and do not modify settings.service.ts.
Task 8: The Settings → Demo Data route, path helper and nav entry
Depends on: Task 7
Files:
- Create:
apps/erp/app/routes/x+/settings+/demo-data.tsx - Modify:
apps/erp/app/utils/path.ts— add the path - Modify:
apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx— nav entry + gate - Copy from (precedent):
apps/erp/app/routes/x+/settings+/backups.tsx(loader at lines 104-113, the intent-dispatch action, the concurrent-run refusal at lines 179-185, and the optimisticresolvedRunIdshiding at lines 346-351)
Steps:
In
apps/erp/app/utils/path.ts, add to thepath.toobject in its existing alphabetical position (betweencustomFieldsanddeactivateIntegration, whereverdemoDatasorts):demoData: `${x}/settings/demo-data`,In
useSettingsSubmodules.tsx, add a route entry to the System group (the array starting at line 153), keeping the group's alphabetical order — it belongs betweenCustom Fieldsand the next entry:{ name: t`Demo Data`, to: path.to.demoData, role: "employee", icon: <LuFlaskConical /> },Import
LuFlaskConicalfromreact-icons/lualongside the file's existingLu*imports. If that icon name does not exist in the installedreact-iconsversion, useLuBeaker; if neither exists, STOP and report rather than picking an unrelated icon.Add
path.to.demoDatato the existinglocalOrInternalRoutesset (line 37):const localOrInternalRoutes = new Set<string>([path.to.backups, path.to.demoData]);This is what hides the nav entry from non-internal users on real deployments.
Create
demo-data.tsxwithhandle(breadcrumbmsg\Demo Data`,to: path.to.demoData`), a loader and an action. Both start with:const { client, companyId, email } = await requirePermissions(request, { update: "settings" }); requireBackupAccess(email);requireBackupAccessis imported from~/utils/backups— reuse it as-is rather than writing a second gate, so the two pages can never drift apart.The loader returns
{ run, datasets }whereruncomes fromgetCompanyTemplateRun(client, companyId)anddatasetsis derived in the loader fromDATASETS/datasetKeys()in@carbon/database/datasets, mapping each to{ key, label }using the dataset's ownlabelfield ("Aerospace & Satellite","Robotics OEM","Precision Manufacturing","Motor Assembly").A route loader is server-only and tree-shaken out of the browser bundle, and
onboarding+/industry.tsx:6already imports from@carbon/database/datasetsthis way — so this costs nothing client-side. Reading the labels from source rather than hardcoding them means a fifth dataset appears on this page automatically and the two lists can never drift.(Revised during execution: the original step hardcoded a four-entry list and carried a "STOP if a key is missing" escape hatch. Reading
DATASETSmakes that condition unreachable, so the hatch is gone.)The action dispatches on
formData.get("intent")with four branches —apply(readsdatasetKey, callsstartCompanyTemplate),keep(finalizeCompanyTemplate),revert(revertCompanyTemplate),dismiss(deletes the failed marker; reuse the patterndismissCompanyExportFailureuses inbackups.server.ts). Follow theaccounting.tsx:84-166idiom of returning{ success, message }per branch.Before the
applybranch does anything, refuse a concurrent run, mirroringbackups.tsx:179-185:if (run && run.status !== "failed") { return data( { success: false }, await flash(request, error(null, "Finish your current demo data change — keep or revert it — first.")) ); }
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exits 0.
pnpm exec biome check apps/erp/app/routes/x+/settings+/demo-data.tsx apps/erp/app/utils/path.ts apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
# Expected: no error-severity findings (pre-existing warnings elsewhere are fine).
Out of scope: Do not modify backups.tsx. Do not remove or weaken
canAccessBackups / requireBackupAccess.
Task 9: The status poll API route
Depends on: Task 7
Files:
- Create:
apps/erp/app/routes/api+/settings.demo-data-status.$templateRunId.ts - Copy from (precedent):
apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
Steps:
Copy the precedent file verbatim and change: the param name to
templateRunId, the reader togetCompanyTemplateRun, and the returned shape to the template marker's metadata.Keep both safety properties of the precedent exactly:
companyIdcomes fromrequirePermissions, never from the URL, so a user cannot poll another company's run; and a failed access gate throwsnew Response("Not found", { status: 404 })rather than a 403, so the endpoint's existence is not disclosed.Return
null(not a 404) when there is no marker for that company — "no run" is a normal state the poller must be able to read.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exits 0.
grep -n "404" apps/erp/app/routes/api+/settings.demo-data-status.\$templateRunId.ts
# Expected: at least one match (the access-gate response).
Out of scope: Do not add a new poll endpoint for the finalize or revert jobs — they report through the same marker and therefore the same endpoint.
Task 10: Demo Data UI components and progress phase labels
Depends on: Task 8
Files:
- Create:
apps/erp/app/modules/settings/ui/DemoData/TemplateCards.tsx - Create:
apps/erp/app/modules/settings/ui/DemoData/TemplateReviewRow.tsx - Create:
apps/erp/app/modules/settings/ui/DemoData/index.ts - Modify:
apps/erp/app/modules/settings/ui/index.ts— export the new folder - Modify:
apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx— phase labels - Copy from (precedent):
apps/erp/app/modules/settings/ui/Backups/RestoreReviewRow.tsx(lines 49-61 for the button set) andapps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx(lines 17-41 for the phase maps, 184-216 for the polling effects)
Steps:
TemplateCards.tsxrenders one card per dataset from the loader'sdatasetslist, each with an Apply button that submitsintent=applyand a hiddendatasetKey. Buttons are disabled while a run is pending. Card copy, verbatim:"Replace this company's data with a demo dataset — snapshotted first, so you can revert."
Follow
backups.tsx:433-437for card structure. There is deliberately no typed-confirmation modal: the safety story is reversibility, exactly as it is for restore (BackupChoices.tsx:71-74submits a destructive restore with a plain Submit).TemplateReviewRow.tsxmirrorsRestoreReviewRow.tsx: onstatus === "ready"render[Keep]and a destructive[Revert]; onstatus === "failed"render a secondary[Dismiss]plus the error text. Handlersfetcher.submit({ intent, templateRunId }, { method: "post" })back topath.to.demoData.Section copy for the review card, verbatim:
"Demo data was applied to this company. Keep it, or revert to put back exactly what was here before."
In
BackupProgressModal.tsx, add the three new phase keys toPHASE_ORDERandPHASE_LABELS(lines 17-41). The template forward run usessnapshot | wipe | apply; its revert reuses the existingwipe | load | files. Labels: "Snapshotting", "Clearing data", "Applying template". Add them as a separate ordered list keyed by mode rather than appending to the restore list — the modal picks its order from the mode it is given, and mixing the two would render phantom steps on a restore.In the route component, wire the polling exactly as
BackupProgressModal.tsx:184-216does: a 500 mssetInterval+useFetcher.loadagainst/api/settings/demo-data-status/{templateRunId}while a run is active, and a 2.5 suseRevalidatorotherwise. Hide a resolved review row optimistically with theresolvedRunIdstrick frombackups.tsx:346-351so it does not linger while the async finalize lands.Mark every user-visible string with Lingui macros —
<Trans>in JSX anduseLingui().tin components, per.claude/rules/i18n-lingui-system.md. Neverimport { t } from "@lingui/core/macro"in app code; that throws at runtime here.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exits 0.
pnpm exec biome check apps/erp/app/modules/settings/ui/DemoData apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
# Expected: no error-severity findings.
Out of scope: Do not run pnpm lingui:extract — on this branch it produces roughly
120k lines of unrelated .po churn. Leave catalog extraction to a separate deliberate
commit.
Task 11: Update the rules and AGENTS.md that this work makes stale
Depends on: none (but land it with the rest)
Files:
- Modify:
.claude/rules/onboarding-company-templates.md - Modify:
.claude/rules/company-backup-restore.md
Steps:
In
onboarding-company-templates.md, add a section covering: theSettings → Demo Dataentry point, the snapshot / keep / revert lifecycle, thesnapshotflag on the event, the two new events, and the two-wipes distinction (dev-seed wipe preserves bootstrap config and is what a template apply uses; the restore wipe is a tabula rasa and is what a revert uses). Correct the "Two callers, one code path" section — there are now two callers of the job, andapplyDatasettakeswipeFirst.In
company-backup-restore.md, record thatwipeAndLoad,getCompanyGroupIdandresolveRestoreScopeare now exported and have a second caller incompany-template.ts.Fix two pre-existing stale lines in
company-backup-restore.mdwhile you are in it, per.claude/rules/keep-sources-in-sync.md(the code wins):- it claims
STORAGE_PATH_COLUMNSholds "modelPath,thumbnailPath";company-backup.ts:54has onlythumbnailPath, and the comment above it saysmodelPathis excluded on purpose. - it says "
satelliteis the only one today";DATASETShas four keys.
- it claims
Verify:
grep -n "modelPath" .claude/rules/company-backup-restore.md
# Expected: any remaining mention describes it as EXCLUDED, not as a member of the set.
grep -n "wipeFirst" .claude/rules/onboarding-company-templates.md
# Expected: at least one match.
Out of scope: Do not rewrite either rule wholesale. Targeted corrections only.
Task 12: End-to-end verification
Depends on: Tasks 1-11
Steps:
Scoped typecheck of every touched package, then lint and unit tests:
pnpm exec turbo run typecheck --filter=@carbon/database --filter=@carbon/lib --filter=@carbon/jobs --filter=erp pnpm exec biome check apps/erp/app packages/jobs/src packages/database/src packages/lib/src pnpm run testDo not run a whole-repo
typecheck— it OOMs on this repo.Prove the dev CLI is unchanged by the
beforeTiers→wipeFirstmigration. Ask the user before running this — it rebuilds a company's data, and the project rule is never to rebuild the database without the user:pnpm db:seed:dev -- --email [email protected] --dataset satelliteDiff the printed
Seeded row countsblock against.ai/runs/2026-08-13-seed-baseline.txt, and the structural sums against.ai/runs/2026-08-13-seed-baseline-structural.txt. Any difference means the wipe migration changed behaviour — STOP and report, do not adjust the baseline.Manual browser verification, with the user's permission, using the
/testskill. Walk the acceptance criteria in the spec, at minimum:- apply
roboticsto a company that already has data; confirm the item list holds only robotics parts; - revert; confirm the pre-apply item / salesOrder / job counts come back;
- apply again, then Keep; confirm the review row disappears and the snapshot folder is gone from the company's bucket;
- while a run is pending, confirm a second apply is refused with the exact copy "Finish your current demo data change — keep or revert it — first.";
- confirm a non-internal user on a non-local deployment cannot see the nav entry or reach the route.
- apply
Report results with actual command output. Do not claim the feature works without having run these.
Out of scope: Do not commit. The user commits; a plan file is not authorization.