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 Data Screen Coverage — implementation plan
Spec / source: .ai/specs/2026-09-23-demo-data-screen-coverage.md
Branch: feat/demo-data-completeness (checkout /Users/aashu/work/carbon/carbon)
Research (per-screen sources, filters, exact tables to seed):
.ai/research/2026-09-23-screen-audit-erp-commercial.md(sales, purchasing, invoicing, accounting).ai/research/2026-09-23-screen-audit-erp-operations.md(production, items, inventory).ai/research/2026-09-23-screen-audit-mes-quality-resources.md(MES, quality, resources, workflows).ai/research/2026-09-23-screen-audit-erp-settings-people.md(settings, users, people).ai/research/2026-09-23-planning-engine-seeding.md(MRP + scheduler)
Ground rules for every task (read once, apply always)
- Working dir
/Users/aashu/work/carbon/carbon. Alwayspnpm, nevernpm. Never commit, stash, reset or checkout — the user commits. Never use.claude/worktrees. Never rebuild the database. Never write to the DB outside (a) rolled-back transactions and (b)pnpm db:seed:dev -- --email [email protected] …(the scratch companydapnjkh860gjckkl52t0). Companydap2gkh860gg2ccl14sgbelongs to the user — SELECT only. - Engine idiom (unchanged from the 2026-09-22 plan): tiers use
insertRow/insertId/insertMaybefromdatasets/sql.ts; refs vianeed(map, key, label)— nevermap[key]!or a silentcontinue; dates ONLY viaDayOffset+resolveDate/resolveTimestamp(datasets/dates.ts) — no JSDate, noCURRENT_DATE; every query carries acompanyId(orcompanyGroupId) predicate; never a literal primary key; never write global tables (user,exchangeRate,periodexcept tier 12's locked insert). - Before inserting into a table for the first time, read its
Inserttype inpackages/database/src/types.tsand its CHECK constraints (psql … -c "select pg_get_constraintdef(oid) from pg_constraint where conrelid='\"<table>\"'::regclass and contype='c'"). Check for sync interceptors that already create the row (adopt-and-UPDATE on unique violation, as tier 02 does foritemCost). - All four data packs move together: new
Datasetfields are REQUIRED (compile-enforced parity). Authordata/satellite/first, then robotics / precision / motor with industry-appropriate content of the same shape and volume. Keep each industry's story voice. - Every new shape gets, in the same task: a
validate.tsrule (refs resolve; required variety via aREQUIRED_*set where it is a status/family/type) + a negative case invalidate.test.ts. - Verification loop after every task (all must be green before the next task):
pnpm --filter @carbon/database typecheck # Expected: no output, exit 0 pnpm --filter @carbon/database test # Expected: all tests passed pnpm --silent db:check:datasets # Expected: ✓ satellite ✓ robotics ✓ precision ✓ motor - Floors: after a task adds rows to a table, add/raise its entry in
datasets/coverage.tsCOVERAGE_FLOORS(floor = min count across the 4 datasets, ×0.8 for volume tables). Engine outputs (demandActual,demandForecast,demandForecastSource,supplyActual,supplyForecast,capacityReservation,jobOperationDependency) stay OUT of the floors. - If an assumption in a task turns out false (missing column, CHECK shape differs, interceptor conflict, screen filter different from the research), re-decide via the ship-it resolution ladder, record it in the spec's Autonomous Decisions section, and continue. Improvising silently or silently dropping coverage is forbidden.
- Comments: only where a future dev needs the why; one line by default. No task/cluster tags in code comments.
Progress
- Task 1: Wipe — model-only slides + refusal preflight
- Task 2: Post-commit planning step (MRP + scheduler) for both callers
- Task 3: Production floor (B1)
- Task 4: Planning inputs, people & time (B2 + B6 time cards)
- Task 5: Sales & purchasing surfaces (B3)
- Task 6: Invoicing & accounting (B4)
- Task 7: Quality, maintenance, resources (B5)
- Task 8: Settings & people remainder (B6)
- Task 9: Screen matrix — script, real seeds ×4, fix loop
- Task 10: Full verification + evidence
- Task 11: Docs
Dependencies
Task 1 and Task 2 are independent of each other and of the data tasks. Tasks 3–8 run sequentially (all touch types.ts, validate.ts, coverage.ts). Task 4 needs Task 3 (assignments reference the new jobs). Task 9 needs 1–8. Task 10 needs 9. Task 11 needs 10.
Task 1: Wipe — model-only slides + refusal preflight
Depends on: none Files:
- Modify:
packages/database/src/datasets/wipe.ts - Precedent:
TRANSIENT_MRP_TABLEShandling in the same file (delete beforenullNullableReferences).
Steps:
- Add
const MODEL_SLIDE_TABLES = ["assemblyInstructionStepSlide", "methodOperationStepSlide", "jobOperationStepSlide", "quoteOperationStepSlide"]with a one-line why (theirimagePath OR modelUploadIdCHECK cannot survive the FK-nulling pass). Delete each (if indeleteSet) right after theTRANSIENT_MRP_TABLESloop. - Add
async function assertWipeable(ctx)called first inwipeCompanyBusinessData, before any write. It runs one query per case, scoped bycompanyId:SELECT count(*) FROM customer WHERE "companyId"=$1 AND "intercompanyCompanyId" IS NOT NULL(+ same forsupplier) → throwSeed: this company trades with other companies in its group (N intercompany customer/supplier record(s)). Demo data can only be applied to a company without intercompany partners.SELECT count(*) FROM "cardTransaction" WHERE "companyId"=$1 AND status <> 'Draft'→ throwSeed: this company has N posted or voided card transaction(s), which cannot be deleted. Demo data can only be applied to a company without posted card transactions.
- Keep the accounting-period change already in the working tree (PRESERVED
accountingPeriod, tier 09 period adoption).
Verify: a scratchpad probe (not committed) that, per case, inside BEGIN … ROLLBACK on company dap2gkh860gg2ccl14sg (user eeb03435-d6ca-4665-8c0d-bde873fe3b7e), creates the state and calls applyDatasetTiers(…, wipeFirst: true):
- IC customer:
UPDATE customer SET "intercompanyCompanyId"='dapnjkh860gjckkl52t0' WHERE id=(first customer)→ expected error startsSeed: this company trades with other companies - Posted card: insert Draft
cardTransaction(cardAccountId = a Liability account of the company group) then UPDATE to Posted with postingDate/postedAt/postedBy → expectedSeed: this company has 1 posted or voided card transaction - Model-only slide: insert
modelUpload(modelPath)+assemblyInstructionStepSlide(stepId=a seeded step, modelUploadId)→ expectedAPPLY OK - Baseline →
APPLY OKPlace the probe atpackages/database/src/zz-probe.ts(tsx must resolve./client.ts; runpnpm exec tsx src/zz-probe.tsfrompackages/database) and DELETE it afterwards. Save output to.ai/runs/2026-09-23-wipe-probes.txt. Then the standard loop. Out of scope: changing the triggers themselves.
Task 2: Post-commit planning step (MRP + scheduler) for both callers
Depends on: none Files:
- Create:
packages/jobs/src/demo-planning.ts—planDemoCompany - Create:
packages/jobs/src/scripts/plan-company.ts— CLI (precedent:packages/jobs/src/scripts/check-backups.ts) - Modify:
packages/jobs/package.json— script"plan:company": "tsx --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/scripts/plan-company.ts" - Modify:
packages/jobs/src/inngest/functions/tasks/company-template.ts— new step afterapply-template - Modify:
packages/database/src/seed-dev.ts(+datasets/cli.tsif args live there) — spawn the script;--skip-plan - Precedents:
packages/jobs/src/inngest/functions/scheduled/mrp.ts:86(runMrp call),apps/erp/app/routes/api+/schedule.ts(runLocationSchedule call)
Steps:
planDemoCompany({ companyId, userId }): Promise<{ mrp: "ok" | string; schedule: { locationId: string; result: "ok" | string }[] }>:const client = getCarbonServiceRole(); const db = getJobDatabaseClient();await runMrp(client, db, { type: "company", id: companyId, companyId, userId })in try/catch → record message.- Locations to schedule:
SELECT DISTINCT "locationId" FROM job WHERE "companyId"=$1 AND status IN ('Ready','In Progress','Paused') AND "locationId" IS NOT NULL(Kysely). For each:await runLocationSchedule({ db, client, locationId, companyId, userId })in try/catch. - Never throws; returns the per-step outcome.
- Template job: after the
apply-templatestep returns successfully,await step.run("plan-template", () => planDemoCompany({ companyId, userId })); log failures; writeplanningErrorinto the marker's metadata only if a sub-step failed (read how the marker metadata is updated in the same file and reuse that helper). A planning failure must not change the marker status from its post-apply value. - CLI
plan-company.ts:parseArgs--company,--user(required) →planDemoCompany→ print one line per step (MRP ✓/MRP ✗ <msg>,Schedule <locationId> ✓/✗); exit 0 even on failure (planning is best-effort), exit 1 only on bad args. seed-dev.ts: after the seed commits, unless--skip-plan,spawnSync("pnpm", ["--silent", "--filter", "@carbon/jobs", "plan:company", "--", "--company", companyId, "--user", userId], { stdio: "inherit", cwd: <repo root> }); on non-zero status print⚠ Planning step failed — run it later with: pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id>. Document--skip-planin the CLI usage text. Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs # Expected: Tasks: N successful
pnpm --filter @carbon/database typecheck # Expected: exit 0
pnpm db:seed:dev -- --email [email protected] --dataset robotics # Expected: exit 0, "MRP ✓", "Schedule … ✓"
psql postgresql://postgres:postgres@localhost:57312/postgres -At -c "select (select count(*) from \"demandActual\" where \"companyId\"='dapnjkh860gjckkl52t0'),(select count(*) from \"capacityReservation\" where \"companyId\"='dapnjkh860gjckkl52t0')"
# Expected: both > 0
If runMrp/runLocationSchedule need env not present locally (service key/URL), re-decide per ground rule 8.
Out of scope: changing engine code; the carbon/mrp event (nothing consumes it).
Task 3: Production floor (B1)
Depends on: none (sequential with 4–8)
Files: datasets/types.ts, tiers/06-production.ts, data/*/production.ts, data/*/items.ts (if short-routing items are needed), validate.ts, validate.test.ts, coverage.ts
Screens to fill (research: operations §Production, MES §5): Priorities (week + Unscheduled), MES operations board (all plant work centers), MES Assigned, work-center displays, production KPIs (completion time, estimates vs actuals), job Steps tab, batches, MES inspection op, MES assembly 3D, procedures lifecycle, make-method status, pickMethod.
Capabilities:
- Re-date existing open jobs (Ready/In Progress/Paused/Planned) to due −3…+21; keep document chronology valid (validator).
- ≥ 10 new released jobs per dataset (mix Ready / In Progress), short routings, every plant work center gets ≥ 2 open ops; 1 Ready job with
dueDateNULL; 2 make-to-stock jobs (no sales order). JobSpec.priority(distinct 1…n) andassignee: "self"→ctx.userId; op-levelassigneeon ~6 open ops.- 3 Completed jobs finished −25…−3 with
releasedDateand Setup/Labor/MachineproductionEvents whose durations roughly match estimates; openproductionEvent(endTimeNULL, start today) on 3–4 more work centers with those opsIn Progress. jobOperationStepRecordfor done ops with steps;jobOperationParameter,jobOperationToolon ≥ 3 ops (read tables first).- One item's Final Inspection method op:
operationType='Inspection'+inspectionDocumentId(the seeded inspection document); copied to its jobs bycopyMethodToJob(extend the helper if it drops those columns). - Link the seeded assembly instruction to the assembly op (
methodOperation.assemblyInstructionId+ job copy). - One process
batchable=true; an ActivejobOperationBatchwith ≥ 2 member ops from different jobs. - Procedures: versions so the set shows Draft, Active and Archived; make methods of seeded items
Active; assembly instruction in its published/active status (read the enum). pickMethoddefault shelf per stocked item at the plant.- Validator:
REQUIRED_PROCEDURE_STATUSES = {Draft, Active, Archived}; ≥ 18 jobs; every plant work center has ≥ 1 open op; ≥ 1 open job due within 0…+7; ≥ 1 released job without due date. Verify: loop (ground rule 6) + floors updated. Out of scope: capacityReservation / op dates (the scheduler writes them — Task 2).
Task 4: Planning inputs, people & time (B2 + B6 time cards)
Depends on: Task 3
Files: types.ts, tiers/01-foundation.ts, tiers/10-ops.ts, tiers/12-planning.ts, data/*/foundation.ts, data/*/ops.ts, data/*/planning.ts, validator, floors
Capabilities:
- Shifts created at the plant location (today
ctx.locationId= HQ,01-foundation.ts:43-47) +workCenterShiftfor every plant work center;employeeShiftpoints at a plant shift. - Upsert the applying user's
employeeJob(today an UPDATE that no-ops when the row is missing,01-foundation.ts:117-122):locationId= plant,title,departmentId,shiftId,startDate,managerIdNULL. Do NOT modify theuserrow. peopleAssignmentfor the applying user across the current week (not only today — today's row pre-filters the MES board to one work center; research MES §4; pick days −2…+4 excluding today OR today on the work center with the most ops, and record which), + 1peopleAbsencenext week.companySettings.timeCardEnabled = true; one opentimeCardEntry(clockIn today 07:00 company TZ, clockOut NULL) unless it conflicts with an existing open entry rule (read constraints).- Planning setup at HQ too (one reorder policy + projection) so the location picker on HQ is not empty. Verify: loop.
Task 5: Sales & purchasing surfaces (B3)
Depends on: Task 4
Files: types.ts, tiers/02-items.ts, tiers/04-sales.ts, tiers/05-purchasing.ts, data/*/items.ts, data/*/sales.ts, data/*/purchasing.ts, validator, floors; new helper if needed helpers/quote-method.ts (precedent: helpers/job-method.ts copyMethodToJob)
Capabilities:
enforcementRulefamiliessales(item-targeted; CHECK: targetType 'item', appliesToAll false, surfaces ⊂ quoteLine/salesOrderLine/salesInvoiceLine, severity warn|error),storage, and a work-center rule; assignments viaenforcementRuleItemAssignment/enforcementRuleWorkCenterAssignment. Read the condition JSON shape frompackages/ee/src/rules/models before authoring.REQUIRED_ENFORCEMENT_RULE_FAMILIEScovers every family the UI lists.- Customer portals:
externalLinkdocumentTypeCustomerfor 2 customers (documentId = customerId), id minted by default (never literal). approvalRule(purchaseOrder ≥ 5000, ≥ 25000; supplier) withapproverGroupIds= the company's Admin employee-type group (resolve by query, never a literal); PendingapprovalRequestfor the Needs-Approval PO and the Pending supplier (readpackages/ee/src/approvals/for the request shape).- Quote methods: copy each Make-to-Order quote line's item method into
quoteMakeMethod/quoteMaterial/quoteOperation(adopt interceptor-createdquoteMakeMethodlike tier 06 adoptsjobMakeMethod). - Configurator: one configurable item
requiresConfiguration=true, oneconfigurationRule, one quote line with a configuration. assignee= applying user on ≥ 2 open quotes, SOs, POs, RFQs;statuson every supplier;createdAtof quotes/RFQs/supplier quotes spread over past offsets (a new optionalcreatedOffset); 2 morepricingRules; customer/supplier bank-account rows only if the table is company-scoped tenant data (check).- Return orders: memos linked via
salesReturnOrderId/purchaseReturnOrderId+ their credit lines;nonConformanceSalesReturnOrderLine/nonConformancePurchaseReturnOrderLine. Verify: loop.
Task 6: Invoicing & accounting (B4)
Depends on: Task 5
Files: types.ts, tiers/04-sales.ts, tiers/05-purchasing.ts, tiers/09-accounting.ts, data/*/accounting.ts, data/*/sales.ts, data/*/purchasing.ts, validator, floors; .claude/rules/onboarding-company-templates.md (payments convention changes)
Capabilities:
postingDate=dateIssuedon every non-Draft sales/purchase invoice.- Posted journals shaped like the posting paths — read
packages/database/supabase/functions/post-sales-invoice,post-purchase-invoice,post-payment(or their current names) for account defaults and linedocumentType/documentId:sourceTypeSales Invoice(AR debit / Revenue credit),Purchase Invoice(Inventory or Expense / AP),Payment(Cash vs AR/AP; setpayment.journalId); oneOpening Balance.accountingPeriodIdset from the adopted period for the posting date. Every journal balances (validator already checks authored journals — extend to the generated ones by deriving them in data, or generate them in the tier from the invoice specs and assert balance in the tier). - Invoice dates spread so receivables aging hits Current, 1–30, 31–60, 61–90.
- Draft Receipt + Draft Disbursement payments.
costLedgerrows paired with posted receipt/shipmentitemLedgerrows (shape frompost-receipt/post-shipment);itemCost.unitCostnon-zero for stocked items.companyAccountsReceivableBillingAddress/companyAccountsPayableBillingAddress(id = companyId). Verify: loop +psqlspot check in a real seed is Task 9's job.
Task 7: Quality, maintenance, resources (B5)
Depends on: Task 6
Files: types.ts, tiers/07-quality.ts, tiers/10-ops.ts, tiers/01-foundation.ts (partners, HQ work center), data/*/quality.ts, data/*/ops.ts, data/*/foundation.ts, helpers/inspection.ts if inspection math changes, validator, floors
Capabilities:
nonConformanceWorkflow×3 linked from ≥ 2 NCRs;nonConformanceItemon every NCR; NCRassignee;nonConformanceSupplieron a supplier NCR dated in the current month;nonConformanceActionProcesslinking an open task to a process in use;procedureParameteron ≥ 2 procedures.QualityData.inspection→inspections: InspectionSpec[]with ≥ 3 entries: Passed receipt lot, Pending lot, Job Operation lot (keephelpers/inspection.tssample math shared with the validator).- Maintenance:
maintenanceDispatchItem.unitCost; Reactive dispatch on a production-event day; 2 Completed dispatches at −55…−35; a Scheduled dispatch due today; an In Progress dispatch with the work center Down;workCenterReplacementPart; one HQ work center with 1 dispatch + 1 schedule. partnerrows (read the table first). Verify: loop.
Task 8: Settings & people remainder (B6)
Depends on: Task 7
Files: types.ts, tiers/01-foundation.ts or tiers/10-ops.ts, data/*/foundation.ts / data/*/ops.ts, validator, floors
Capabilities:
userAttributeCategory→userAttribute(Date, List, User data types) →userAttributeValuefor the applying user.itemSerialSequencefor every serial-tracked item; 3customFieldrows (part Text, customer User, job Yes/No — resolvedataTypeIdby name from the lookup table);printJobhistory (completed, failed, queued) against a printer route.one— dropped (spec D66). Verify: loop.webhookactive=false
Task 9: Screen matrix — script, real seeds ×4, fix loop
Depends on: Tasks 1–8 Files:
- Create (scratchpad, not committed):
…/scratchpad/screen-matrix.ts(or.sql) - Create:
.ai/runs/2026-09-23-screen-matrix-{satellite,robotics,precision,motor}.txtSteps:
- From the five research files, list every screen classified EMPTY/FILTERED-EMPTY that is in scope, plus the previously-OK core lists as regression guards. For each, write ONE count query reproducing the loader's source and filters for the applying user (RPCs called inside
BEGIN … ROLLBACK). - For each dataset:
pnpm db:seed:dev -- --email [email protected] --dataset <key>(includes Task 2's planning), then run the matrix for companydapnjkh860gjckkl52t0; write<screen> | query | count | PASS/FAILto the evidence file. - Any FAIL → fix in the owning tier/data (ground rules apply), re-run the loop, re-seed, re-run the matrix. Repeat until 0 FAIL for all four datasets.
Verify: each evidence file ends with
FAIL: 0.
Task 10: Full verification + evidence
Depends on: Task 9 Steps / Verify:
pnpm --filter @carbon/database typecheck # exit 0
pnpm --filter @carbon/database test # all pass
pnpm --silent db:check:datasets # ✓ ×4
pnpm exec turbo run typecheck --filter=@carbon/jobs # all successful
pnpm exec biome check packages/database/src packages/jobs/src # 0 errors
- Real re-apply over an existing seeded company: seed robotics then satellite onto
[email protected]; both exit 0; no robotics items remain. - Re-run Task 1 probes (now also against the final code).
- Pre-commit drill: break one new ref in
data/satellite/*.ts, stage only that file,sh .husky/pre-commit→Commit blocked; restore the file byte-identical (checksum before/after); unstage. - Refresh
.ai/runs/2026-09-23-seed-baseline-*.txt(row counts) and the status audit if statuses changed. Record everything in.ai/runs/2026-09-23-screen-coverage-verification.txt.
Task 11: Docs
Depends on: Task 10
Files: .claude/rules/onboarding-company-templates.md (planning step, wipe refusals, slides, payments now journaled, shifts at plant, volume), packages/database/src/datasets/AGENTS.md, packages/database/AGENTS.md (dev CLI --skip-plan), packages/jobs/AGENTS.md if it lists scripts/functions, docs/content/docs/platform/demo-data.mdx (user-facing: what the demo includes, that planning runs after apply, the two refusal messages) then regenerate the agent KB exactly as the previous pass did (find the generator in .claude/rules/agent-knowledge-base.md), spec status → Implemented + changelog.
Verify: grep -n "plan:company\|planDemoCompany" .claude/rules/onboarding-company-templates.md packages/database/AGENTS.md shows both; KB manifest regenerated without diff noise outside demo-data.