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 Completeness — every feature, every state
Status: Implemented (autonomous mode — user-delegated; uncommitted on the branch, awaiting the user's commit) · Date: 2026-09-22 · Branch: feat/demo-data-completeness
Research: .ai/research/2026-09-22-demo-data-current-coverage.md, .ai/research/2026-09-22-app-feature-surface.md, .ai/research/2026-09-22-demo-data-validation-gate.md
Reading of the request (autonomous mode)
What: Expand the demo-data datasets (packages/database/src/datasets/) so a company seeded from any of the four industry templates exercises every major feature and reachable state of the ERP + MES apps — every list screen has rows, every detail screen opens, every status enum value a user can encounter appears somewhere. Why: demo data is the primary way prospects, staff and developers experience Carbon; today it covers ~40% of the app (no returns, no inspections, no maintenance, no picking, no posted documents, no payments, no HR, …). Where: the dataset engine (tiers), the dataset type, all four industry data packs, and the pre-commit validation. Who: anyone applying a demo template (Settings → Demo Data, onboarding, pnpm db:seed:dev). Explicit user constraints: leave out files (no document/file uploads); everything else in; be maximally thorough; no regressions; keep FK integrity; validation must block commits on invalid demo data with a clear message.
Goals
- Every user-reachable status enum value of every major document type appears in every dataset (matrix in Design §B).
- Every module's list screens are non-empty and detail screens open: Sales (incl. RMA), Purchasing (incl. returns), Production (incl. batches, scrap/rework), Inventory (incl. picking, transfers, counts, tracked-entity states, supersession), Items (incl. taxonomy, revisions), Quality (incl. inspections, gauges, quality docs, risks, NCR depth), Resources (incl. maintenance, training, HR links), People (timecards, holidays), Invoicing (payments, memos, settlement states), Accounting (posted journals, periods, exchange rates, projects, FA lifecycle incl. disposal), Workflows (incl. run history), MES (queue, active work, picking, maintenance, batches, inspection).
- Posted/partial document states exist with hand-authored, internally consistent downstream effects (item ledger, journals, settlements) — same pattern tier 3 already uses for opening stock.
- All four industries stay in rough volume parity (the existing coverage contract), enforced structurally by required (non-optional) slice fields.
- Validation: a commit with invalid demo data is blocked with a clear, actionable message — including when the local DB is down (new pure-TS layer).
Non-goals
- Files/uploads (user-excluded):
document*, storage objects, slide/file attachments. Notes and tags are data, not files — they are IN scope (light). - Integrations config (
integration,companyIntegration,webhook,apiKey,oauth*), SSO/passkeys/ITAR, notifications, agent threads, implementation hub, saved table views,printJob. - Multi-company / intercompany / consolidation.
- EE-entitlement-authored data: approval rules, enforcement rules, demand/supply forecasts (
demandForecast*are also wiped as transient; existingdemandProjectionseeding stays). - Card transactions (Ramp-integration-coupled).
- New CAD models/thumbnails (existing bundled assets stay as-is).
- Derived/deprecated job statuses (
Overdue,Due Today) — deliberate existing exclusion. - CI enforcement (pre-commit remains the gate; CI was previously declined on cost).
Design
A. Engine extensions (tiers + types)
The Dataset stays pure data; every new capability is a tier feature + a slice field. New/changed per tier:
| Tier | Extension |
|---|---|
| 01 foundation | Party currency (currencyCode per customer/supplier), per-party payment terms, supplier statuses (Active/Inactive/Pending/Rejected), holidays, equipment (if table is UI-live; verify at plan), employee links for the applying user (employeeAbility, employeeShift), crews (1), material taxonomy rows (materialType/Form/Grade/Substance/Finish/Dimension) + classification on material items, tags |
| 02 items | itemSupersession (one live Consume First pair per industry), customerPartToItem, customerItemPriceOverride(+breaks), pricingRule, configuration parameters (+group, one rule) on one configurable item, methodOperationTool/Parameter (light), procedure step types extended to the full set the builder supports, item revision statuses (Design/Prototype/Production/Obsolete) via extra revisions of one item |
| 03 inventory | Posted inventory count (+adjustment ledger rows) alongside the Draft one; authorable count lines; tracked-entity states (Reserved via job stays; add On Hold, Rejected, Scrapped); itemShelfLife + expiring lots; kanban Make + Transfer cards; pickingList (In Progress w/ Pending lines; Completed w/ Picked lines + transfer ledger rows); stockTransfer (Draft/Released/Completed); warehouseTransfer (Draft/To Ship/Completed + ledger for completed) |
| 04 sales | Full quote/RFQ/SO status matrix; No Quote line + noQuoteReason; posted + partial + voided shipments (with Sale ledger rows); sales invoice lifecycle (Submitted/Overdue/Paid/Partially Paid/Voided/Credit Note Issued); salesReturnOrder (Draft/To Receive/Completed + credit lines); salesOrderStatusHistory; favorites for the applying user; customer portal row if table exists (verify at plan) |
| 05 purchasing | Full PO status matrix incl. Planned/Closed/Rejected/Needs Approval/To Review; Outside Processing PO; posted + partial receipts (+receiptLineTracking for batch items, Purchase ledger rows); purchase invoice lifecycle (Open/Overdue/Paid/Partially Paid/Voided/Debit Note Issued); purchaseReturnOrder (Draft/To Ship/Completed); supplier-quote status authorable (Draft/Active/Expired/Declined); purchaseOrderStatusHistory |
| 06 production | Per-operation status overrides (unlock In Progress/Waiting); scrap + rework productionQuantity rows (+ scrapReason); one jobOperationBatch (Active); jobOperationNote; authorable deadlineType; one open production event for the applying user (MES “Active”); quote-line methods (quoteMakeMethod fill via copyMethodToQuote analog) — verify feasibility at plan, else record as engine ceiling |
| 07 quality | NCR full depth: authorable type, Closed status, all priorities/sources, tasks (investigation/action/approval/review), associations (supplier, customer, PO line, SO line, tracked entity); inboundInspection on the posted receipt (Passed + Failed samples w/ measurements); itemSamplingPlan (AQL); qualityDocument (Draft/Active/Archived); gauges + calibration records (all calibration statuses); riskRegister (all statuses, Risk+Opportunity, varied sources) |
| 08 change orders | Add Start / Engineering Complete / Cancelled statuses; task rows (changeOrderTaskStatus variety) if table supports (verify at plan) |
| 09 accounting | Posted + Reversed journals across all five account classes; accountingPeriod rows (trailing 12 months; one prior period Locked/Closed + periodCloseTask states); exchangeRate (+history) for EUR; one EUR-currency supplier PO/invoice (document currency, unpaid); payments (Receipt + Disbursement) + invoiceSettlement for Paid/Partially Paid invoices; memo (posted credit + debit); projects (2, one linked to a job); dimensionValue + journalLineDimension (light); FA: add Disposed (+fixedAssetDisposal), Units of Production asset + usage log; keep Draft depreciation run, add a Posted one only if postable without the edge path (verify at plan) |
10 ops (NEW slice ops) |
Maintenance: schedules (+items) per work center, dispatches in all 5 statuses × varied severity/source/priority, failure modes, one spare-part issue; training courses (+questions of all 5 types, assignment states for the applying user); timecard entries (past week, applying user); suggestions (2); notes on a job/customer |
| 11 workflows | Seed workflowRun + workflowStepRun history for the published workflow (Succeeded / Failed / Skipped runs, terminal, isTest=false) |
| 12 planning | Silent skips → throws (need()); no data change beyond what sales-matrix needs |
Ledger-consistency invariant (new, load-bearing): on-hand per (item, shelf) derived from all seeded itemLedger rows must remain ≥ 0 at every point and end equal to what pickable/genealogy flows assume. The authoring convention: opening balances stay the baseline; posted receipts add; posted shipments/picks subtract only from items with sufficient opening stock. The pure validator (D) checks the end-state non-negativity per item/shelf from the dataset alone.
B. Coverage matrix (per dataset — all four industries)
Every enum value marked ✱ is newly reachable. Counts are minimums per dataset.
- salesRfq: Draft✱, Ready for Quote, Quoted, Closed✱ (4)
- quote: Draft✱, Sent, Ordered, Partial✱, Lost✱, Cancelled✱, Expired✱ (7); line statuses all 4 (No Quote✱, In Progress✱, Not Started✱)
- salesOrder: all 11 (Needs Approval✱, Invoiced✱, To Invoice✱ added)
- salesReturnOrder✱: Draft, To Receive, Completed (3)
- shipment: Draft, Posted✱ (one full, one partial✱), Voided✱
- salesInvoice: Draft, Submitted✱, Overdue✱, Paid✱, Partially Paid✱, Voided✱, Credit Note Issued✱
- purchasingRfq: Draft✱, Requested, Closed✱
- supplierQuote: Draft✱, Active, Expired✱, Declined✱
- purchaseOrder: all 10 statuses; types Purchase + Outside Processing✱
- receipt: Draft, Posted✱ (full + partial✱), Voided✱
- purchaseInvoice: Draft, Open✱, Overdue✱, Paid✱, Partially Paid✱, Voided✱, Debit Note Issued✱
- purchaseReturnOrder✱: Draft, To Ship, Completed
- job: all 8 seedable (existing) + deadlineType variety✱; jobOperation: all 7 (In Progress✱, Waiting✱); productionQuantity: Production, Scrap✱, Rework✱; one Active jobOperationBatch✱
- tracked entities: Available, Consumed, Reserved, On Hold✱, Rejected✱, Scrapped✱; expiring lot✱
- pickingList✱: In Progress + Completed; lines Pending/Picked/Short
- stockTransfer✱ / warehouseTransfer✱: 3 states each
- inventoryCount: Draft + Posted✱
- NCR: Registered, In Progress, Closed✱; priorities all 4; sources both; with task/association depth✱
- inboundInspection✱: Passed + Failed samples; qualityDocument✱ ×3 statuses; gauge✱ + calibrations (3 statuses); riskRegister✱ ≥4 rows
- changeOrder: all 6 statuses (Start✱, Engineering Complete✱, Cancelled✱ added)
- fixedAsset: Draft, Active, Fully Depreciated, Disposed✱
- journal: Draft, Posted✱, Reversed✱; accountingPeriod✱ + one closed period✱
- payment✱ ×2 types; memo✱ ×2 directions; exchangeRate✱ EUR
- maintenanceDispatch✱: all 5 statuses; maintenanceSchedule✱ ≥3
- training✱ ≥2 courses; timeCardEntry✱ ≥5; holiday✱ ≥2; employeeAbility/Shift✱ for applying user
- workflowRun✱ ≥3 terminal runs
- itemSupersession✱ 1 live pair; material taxonomy✱ classified materials; item revisions across 4 revision statuses✱
C. Data integrity strategy
- Refs are loud. Every cross-reference resolved via
need(); the silent-skip/null-coalesce sites in tiers 01/03/04/06/09/12 (list in validation research) become throws. Genuine authored-optional fields keep?? nullonly where the column is nullable and the spec omitted the key on purpose (typed as optional). - Posted docs carry their ledger. Hand-authored
itemLedger/journal/invoiceSettlementrows accompany every posted/paid state, balanced (assertBalanced-style check in the validator for journals; non-negative on-hand check for ledgers). GL account resolution stays class-based (extended to all 5 classes). - Sequences respected. All new readable-id documents go through the existing sequence machinery; insertion order rules (opportunities → statusOrders → releasedOrders) preserved and extended.
- Interceptors respected. New inserts follow the adopt-don't-duplicate pattern (
jobMakeMethod,itemCost) wherever a sync interceptor creates the row. - Wipe compatibility. All new tables are companyId-scoped →
wipeCompanyBusinessDatadiscovers them automatically; verify none belong inPRESERVED_TABLES(onlyperiod(global) and bootstrap-owned config do). Re-apply (second template onto same company) must stay clean — covered by acceptance test. - Timezone/dates: all offsets via
DayOffset+resolveDate;previousMonthEndfor period ends; no JSDate.
D. Validation (the commit gate)
- New
datasets/validate.ts— pure, no DB. Validates each dataset: every string ref resolves within the dataset (items, customers, suppliers, processes, work centers, shelves, warehouses, job keys, SO keys, price-break arity vsrfqQuantityBreaks); journal lines balance; end-state on-hand non-negative per item;promisedDateOffsetwithin the 48-week horizon;componentNodeIds⊆ bundledgraph.json; every slice non-empty; supersession pairs reference distinct existing items. Runs (a) first insidecheck-datasets.ts— before the DB connection, so a broken dataset blocks the commit even with the DB down; (b) as a vitest suite (datasets.test.ts) sopnpm testcovers it. verify.tsgains row-count floors. After tiers, assert per-table minimum counts from a small manifest (e.g.job ≥ 8,pickingList ≥ 2,nonConformance ≥ 3…). Catches silent 0-row tiers. Still always rolls back.- Hook semantics unchanged (trigger path, skip env var, DB-down warning for the DB layer, clear block message). The pure layer never skips.
- Baselines re-captured (
.ai/runs/), structural sums extended (add itemLedger sum, journal balance), rule doc + datasets AGENTS.md updated.
Design Decisions
| # | Decision | Choice | Rationale |
|---|---|---|---|
| 1 | Posted/partial documents | Hand-authored downstream rows in-transaction | Edge functions can't run inside the seed transaction (architectural); tier 3 already sets the precedent; the alternative (post-commit edge calls) breaks all-or-nothing apply and verify rollback |
| 2 | New capability placement | Extend existing slices + one new ops slice for tier 10 |
Tier 10 was reserved for exactly this (its own comment); keeps tier ordering contract intact |
| 3 | Industry parity | All four datasets get full new data | Volume is the coverage contract; onboarding shows all four; required (non-optional) type fields enforce parity at compile time |
| 4 | Silent skips | Become need() throws |
A demo dataset is first-party data; a typo should fail the gate, not degrade. Data fixed in same change, so no behavior break |
| 5 | Pure validator placement | check-datasets.ts pre-DB + vitest |
Closes the "DB down → warn+pass" hole without changing the deliberate DB-layer skip |
| 6 | EE-gated features (approvals, enforcement, forecasts) | Excluded | Seeding data behind an entitlement gate is invisible in community/self-hosted demos; forecasts additionally wiped as transient |
| 7 | Files/documents module | Excluded | Explicit user instruction |
| 8 | Card transactions, intercompany | Excluded | Integration-coupled / multi-company out of scope |
| 9 | Quote-line methods (quoteMakeMethod fill) |
Attempt; fall back to documented ceiling if job-helper reuse isn't clean | Quote costing screens are a major demo surface, but the helper was built for jobs; plan verifies feasibility first |
| 10 | Workflow run history | Seed terminal runs directly | Rows are read-only history for the UI; engine never re-reads terminal runs |
| 11 | Open MES production event | One open Setup event for the applying user | Makes MES “Active”/timecard live; bounded risk (one row, user can end it) |
| 12 | CI check | Not added | Previously declined on cost; pre-commit + vitest suffice |
Acceptance criteria
-
pnpm db:check:datasetspasses for all four datasets on a migrated local DB (< ~15s total), and fails with a named, actionable error when a ref key is deliberately broken (tested once, then reverted). — Evidence: ✓×4 in 3.6s wall (Task 15 re-run, 2026-09-23); broken refST-050-BOGUS→✗ satellite … unknown itemexit 1, and floor drill →pickingList: expected ≥ 3, got 2exit 1, both in.ai/runs/2026-09-23-demo-data-verification-drills.txt.
-
- Pure validator:
pnpm --filter @carbon/database testincludes dataset validation; breaking a ref fails the test AND blocksgit commiteven with the DB stopped. — Evidence:validate.test.tsrunsvalidateDataseton every key plus negative cases (unknown BOM item, unbalanced journal, …) — 43/43 pass; drills 6a (DB unreachable → exit 1) and 6b (hook run with the broken file staged → "Commit blocked by the demo-dataset check") in the drills file. The broken-ref drill was run throughcheck-datasets, not vitest; vitest's ref coverage is the negative cases.
- Pure validator:
-
pnpm db:seed:dev -- --dataset satellite(and robotics) completes; the printed row counts match new baselines. — Evidence: all four seeded exit 0; row counts captured as.ai/runs/2026-09-23-seed-baseline-{satellite,robotics,precision,motor}.txt+-satellite-structural.txt(untracked until the user commits).
-
- Re-apply is clean: applying a second dataset over a seeded company leaves exactly one demo story. — Evidence: every baseline header records "re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0"; plan Task 14 records "sat→rob→sat both 229/231 tables = clean apply". Required the
wipe.tsfixes in Autonomous Decision 15.
- Re-apply is clean: applying a second dataset over a seeded company leaves exactly one demo story. — Evidence: every baseline header records "re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0"; plan Task 14 records "sat→rob→sat both 229/231 tables = clean apply". Required the
-
- Status-matrix audit lists DISTINCT statuses per document table and matches §B for every ✱ value. — Evidence:
.ai/runs/2026-09-23-demo-data-status-audit.txt— 264 present, 103 absent all classified, 0 open gaps (3 gaps found and fixed, Decision 15).
- Status-matrix audit lists DISTINCT statuses per document table and matches §B for every ✱ value. — Evidence:
-
- Every seeded journal balances; no (item, shelf) on-hand goes negative (validator-enforced). — Evidence:
validate.tsjournal-balance and net on-hand checks run on every commit; structural baseline shows JE-SEED-001…005 each with debit − credit = 0.
- Every seeded journal balances; no (item, shelf) on-hand goes negative (validator-enforced). — Evidence:
-
pnpm exec turbo run typecheck --filter=@carbon/databasegreen; Biome green. — Evidence:pnpm --filter @carbon/database typecheckexit 0 (Task 15 re-run); Biome 0 errors at Task 14.
-
.claude/rules/onboarding-company-templates.md+packages/database/src/datasets/AGENTS.mdupdated (new slices, validator, baselines). — Evidence: Task 15; alsopackages/database/AGENTS.md,.claude/rules/workflow-run-history.md,docs/content/docs/platform/demo-data.mdx(+ regenerated agent KB).
Autonomous Decisions (high-stakes first)
Seeding posted documents with hand-authored ledger/settlement effects (Decision 1) — bypasses the posting engines; mitigated by balance/non-negativity validation and per-table acceptance checks. (Rung: codebase precedent — tier 3/tier 6 already write ledger + genealogy rows directly.)
Scope exclusions (Decisions 6–8, non-goals list) — narrows "every feature" to features that are demoable in a community, single-company, no-files context. (Rung: product judgement + user's own "leave out files".)
Making silent skips throw (Decision 4) — a behavior change in the shared seed path; safe only because all four data packs are fixed in the same change. (Rung: user's stated intent — validation must catch invalid data.)
New required slice/fields → compile-breaking Dataset shape (Decision 3) — any out-of-tree dataset would break; none exist. (Rung: codebase precedent — DatasetKey is already a closed union.)
Pure validator wired before the DB layer in the pre-commit path (Decision 5) — commits can now be blocked with no DB running, which is precisely the user's requirement. (Rung: user's stated intent.)
Branch/workflow: work directly on
feat/demo-data-completenessin this checkout; no commits without explicit user permission (standing user rule overrides ship-it's commit steps).Smaller calls: open MES event (D11), workflow run history (D10), quote-methods attempt (D9), notes/tags in scope but light, crews/equipment pending plan-time table verification.
Cluster C4 (Task 6) resolutions:
- The no-quote reason column is
salesRfq.noQuoteReasonId(not quote/quoteLine —updateSalesRFQStatuswrites it), so it is wired asSalesRfqSpec.noQuoteReasonon the Closed RFQ that pairs with each dataset's Lost quote; tier 01 now registersnqr:<name>refs. SalesInvoiceSpec.keyis OPTIONAL (sinv:<key>in ctx.refs.misc) so the pre-existing Draft invoices stay byte-identical; all six new lifecycle invoices carry keys (C9 settles "paid"/"partial").SalesReturnSpec.salesOrdersits at the HEADER (schema:salesReturnOrder.salesOrderId; the line-level column issalesOrderLineId, which the seed leaves null).returnReasonis a header field applied to every line'sreturnReasonId(per-line in schema).- A Completed RMA mirrors post-receipt's "Sales Return Order" branch fully: a Posted
receipt(sourceDocument "Sales Return Order") +receiptLinerows + one "Positive Adjmt." / "Sales Return Receipt" itemLedger row per line into the line'stoShelf.salesReturnOrderCreditLineis NOT seeded — itsmemoIdis NOT NULL, so credit rows cannot precede C9's memos. - Posted shipments write
entryType: "Negative Adjmt."(not "Sale") with documentType "Sales Shipment" — that is what post-shipment actually inserts. - Validator: quote lines with status "No Quote" are the one case allowed zero price breaks; REQUIRED_* status-coverage constants exported from validate.ts pin the C4 matrix per dataset ("Pending" shipment/invoice and "Cancelled" RMA are transient/out-of-scope and excluded); net-on-hand check moved below the sales slice so posted shipments/completed returns participate.
- Conventions (no per-dataset data): status history = Draft→Confirmed→In Progress on the first order with status "In Progress"; quoteFavorite = the Sent quote; salesOrderFavorite = first released order; jobFavorite (tier 06) = the
eventsJobKeyjob.
- The no-quote reason column is
Cluster C5 (Task 7) resolutions:
- Posted receipts write
entryType: "Positive Adjmt."with documentType "Purchase Receipt" — the plan text said entryType "Purchase", but post-receipt's Purchase Order branch actually inserts "Positive Adjmt." (itemLedgerType "Purchase" is the COST ledger's type). Code wins. - The batch receipt lot mirrors
update_receipt_line_batch_tracking+ the posting flip:trackedEntitywith sourceDocument "Item" (NOT "Receipt" — that enum value belongs to inspections/activities), sourceDocumentId = the item, readableId = the lot number, attributes{"Receipt Line", "Receipt", "Supplier"}, status "Available" (no Receipt-usage inspection plan is seeded), ledger row stamped withtrackedEntityId. NotrackedActivityrows — the minimal coherent shape; tier 06's genealogy owns activities. - A Completed purchase return mirrors post-shipment's "Purchase Return Order" branch: a Posted
shipment(sourceDocument "Purchase Return Order", supplierId set) +shipmentLinerows + one "Negative Adjmt." / "Purchase Return Shipment" itemLedger row per line out of the line's fromShelf.PurchaseReturnSpec.lines[].unitPricewas added beyond the plan's minimum shape (mirrors SalesReturnLineSpec; a $0 debit basis reads as fake data). No child delivery/payment tables exist for purchaseReturnOrder. - OSP POs mirror the
createedge function's outside-processing branch: an ordinary direct PO withpurchaseOrderType: "Outside Processing"whose line is the PROCESSED MAKE PART (the jobMakeMethod item) priced at the operation'soperationUnitCost;jobId/jobOperationIdstay null (jobs are seeded in tier 06, after purchasing). Validator requires the supplier to hold a foundation supplierProcess. - FX discipline is validator-pinned: exactly one direct PO carries
currencyCode: "EUR"(rate 1.08,exchangeRateUpdatedAtstamped at the order date the wayinsertPurchaseOrderdoes), on the C1 EUR supplier, childless, status "To Invoice"/"Draft"; every other PO stays base-currency. - Standalone supplier quotes get no
externalLink— finalize mints that, and none of the Draft/Expired/Declined quotes were finalized. Suppliers must be Active with a supplierContact (the quote row needs contact + supplier-location refs). - Purchasing documents may only name Active suppliers (validator-enforced) — the C1 status-showcase suppliers exist for the supplier list, not order flow.
- Conventions (no per-dataset data): purchaseOrderStatusHistory = Draft→To Review→To Receive on the first direct PO whose receipt posted; timeline rules order ≤ receipt ≤ invoice enforced in the validator; completed purchase returns are dated after the posted inventory count so its snapshot stays the opening balance.
- Lot-id registry extended: posted receipt lotNumbers join onHandTracked + genealogy inputs + the genealogy assembly serial in one collision check; REQUIRED_PURCHASE_* status sets exported ("Pending" receipt/invoice, "Return" invoice, "Cancelled" return/quote are transient or flow-only and excluded).
- Posted receipts write
Cluster C6 (Task 8) resolutions:
- Spec fields address job operations by 1-based position among the job's ROOT operations sorted by
"order"(operationOverrides,quantities,operationNotes,openEvent,batch,rework) — robust to methods numbered 10/20/30, and the same key tier 06's existing root-op queries use. jobOperationNote.noteis plain TEXT, not TipTap — the MES operation Chat writes/reads bare strings (Chat.tsxrenders{m.note}in a<p>), so the seed authors plain sentences and does NOT useRICH(). The plan's "likely TipTap" guess was wrong; code wins.jobOperationBatchlinks members viajobOperation.jobOperationBatchId(no child table). Seeded the way thebatch-operationsedge function creates one: readableId from thejobOperationBatchsequence (BAT…), processId/workCenterId from the member operation, status "Active",mergeOutput: false, then UPDATE the operation. One batch per dataset on the events job's first root op, per the plan.reworkis fully satisfiable (jobId, quantity, reason, requestedById, target/triggeredAt operation ids) — seeded OPEN (completedAtnull) with target upstream of the triggering op, mirroring trigger-rework's back-path semantics; validator enforces target ≤ triggeredAt.- The picking-list status trigger (
update_picking_list_status, migration 20260601143527) fires only on UPDATE of pickingListLine — seeded INSERTs never recompute the header, so the tier inserts the final header status directly (probe-verified: Completed and In Progress both stick). - Picked moves mirror the post-picking edge function byte-for-byte: paired itemLedger rows
entryType "Transfer",documentType "Direct Transfer", documentId = pickingList row id, out of the line'sstorageUnitIdintotoStorageUnitId. The lineside destination is the floor storage unit (isWorkCenterDefault) of the work center on the job's first root operation with a work center (notoWorkCenterspec field). pickingListLine.jobMaterialIdis NOT NULL — lines resolve the job's jobMaterial row by (jobId, itemId), which is why the validator requires each picked item to be a component of the job item's method TREE (recursive walk ofitems.methods).- A "No Deadline" job carries no dueDate (
dueDateOffsetnow optional; validator: required for every other deadlineType, forbidden for "No Deadline"). Deadline spread by status: Draft=No Deadline, Ready=ASAP, Planned=Soft Deadline, rest Hard. JobSpec.quantitiesREPLACES the tier's legacy per-op Production-1 rows for that job (other jobs keep today's behavior); Scrap rows must name a bootstrap scrapReason (Defective/Damaged/Quality — validated against seed.data.ts, resolved by name at runtime and cached inctx.refs.misc, never module scope, which would leak across the drift check's four companies).- The open MES event is a Setup
productionEventwithendTime: nullfor ctx.userId atresolveTimestamp(anchor, 0, "08:00:00"), on the op overridden to "In Progress" (validator-pinned to the openEvent order). - Net-on-hand ≥ 0 assertion moved BELOW the production slice — completed picking lists now consume from their fromShelf bins.
- Quote methods (Decision 9): NOT implemented in C6 per the task directive — feasibility analysis recorded in the run report instead. Short version: feasible; tier 04 quote lines are already
methodType: "Make to Order"so interceptor-minted rootquoteMakeMethodrows exist to adopt, andsync_insert_quote_material_make_methodmints child rows exactly like the job-side interceptor copyMethodToJob already adopts.
- Cluster C7 (Task 9) resolutions:
- NCR tasks mirror the
createedge function's "nonConformanceTasks" case, not free-standing rows:nonConformance.requiredActionIdslists the bootstrapnonConformanceRequiredActionids in order and each becomes anonConformanceActionTask(actionTypeId, 1-basedsortOrder);approvalRequirements = ["MRB"]yields onenonConformanceApprovalTaskplus the two reviewer rows the function seeds ("Engineering" + "Quality") — the plan said "1 reviewer", code wins. Validator: a Registered NCR holds only Pending tasks; a Closed NCR none open. "In Progress" tasks/approvals/reviewers are assigned to the applying user (someone owns active work). - NCR
typeresolves by name against the company's bootstrapnonConformanceTyperows (shared cached helperhelpers/bootstrap-lookup.ts, also used for gauge/CO lookups); omitted = the legacy first-row query, so the pre-C7 NCRs are unchanged. New fields:description(+ TipTapcontent, as the edge function derives it),dueDateOffset,closeDateOffset(required iff Closed). - Associations write the exact shapes
insertIssue/ the association modal write:nonConformanceSupplier(itssync_create_nc_external_linkinterceptor mints the externalLink — verified),nonConformancePurchaseOrderLine(+ PO id/readable id),nonConformanceCustomer,nonConformanceSalesOrderLine(+ SO id/readable id),nonConformanceTrackedEntity,nonConformanceInspection. Validator pins the PO's supplier = the NCR's supplier and the SO line's customer = the NCR's customer. New refs: tier 03/05 registerte:<readableId>(ctx.refs.misc) for every seeded lot; tier 05 registerspoline:<poRef>:<item>andrline:<receiptRef>:<item>(ctx.refs.documents). - Inspection graph is fully seedable without files.
inspectionSamplingPlanis NOT an item-level AQL plan (the plan text was stale —itemSamplingPlanwas dropped 2026-07-26): it is per (inspection lot, inspectionFeature), and features hang off aninspectionDocument, whosestoragePathis nullable — the app's own "new inspection plan" form creates one with no file. So each dataset seeds, mirroring post-receipt: a file-lessinspectionDocument(AQL default rule, ANSI_Z1_4 / II / Normal) with 2 MeasurementinspectionFeatures, the Receipt-usageitemInspectionDocumentAssignment, the lotinspection(plan snapshot resolved by the realresolveSamplingPlan), oneinspectionSamplingPlanper feature, n samples + measurements, and the disposition'sinspectionHistoryrow. No balloons (file-bound). Escape hatch not needed. - Inspected line must be untracked (Inventory) with a resolved sample size ≤ 5, and the dataset authors EXACTLY n samples; lot status Partial (the brief allowed Partial/Failed). Failed is validator-forbidden: a rejected untracked lot posts a
post-nonconformancewrite-off (itemLedger + GL) the seed does not author. Sample/measurement statuses are derived with the engine's rules (helpers/inspection.tsduplicatesvaluateMeasurement—@carbon/database/qualityimports kysely at runtime) and the validator pins authored sample status = derived. Standard is the company default ANSI_Z1_4. - Gauge calibration status lives on
gauge(gaugeCalibrationStatus+lastCalibrationStatus, last/next dates);gaugeCalibrationRecordcarries Pass/Fail (inspectionStatus). The tier replays records the wayupsertGaugeCalibrationRecorddoes (no records ⇒ Pending; latest Pass ⇒ In-Calibration; latest Fail ⇒ Out-of-Calibration; next = last + interval months via CalendarDate). A gauge ending Out-of-Calibration also getslastCalibrationStatusOut-of-Calibration — the state the nightly cleanup leaves after notifying — so a fresh demo company fires no stale alert. Story: Active Master (2 Pass), Active Standard never calibrated (Pending), Inactive Standard retired after a Fail (thegaugesview also shows Inactive as Out-of-Calibration). riskRegisterlinks follow each entity'sRiskRegisterCard:sourceId= customer/supplier/item/job/work-center id; Item risks also setitemId, Job risks setitemId= the job's item; General has neither. Five risks per dataset cover all five statuses and sources Customer/Supplier/Item/Job/General, with the General one an Opportunity.- Quality documents: an Archived v1 + Active v2 of the same name (the archive-on-activate interceptor fires on UPDATE only, so inserting both is stable) + a Draft v0 of another document; the Active one has Checkbox/List/Measurement steps (Measurement steps require a bootstrap UoM — schema CHECK). No File steps.
nonConformanceWorkflowskipped (out of scope per plan; no need for a workflow link to demo NCR depth).
- Cluster C8 (Task 10) resolutions:
- The three new notices (Start / Engineering Complete / Cancelled) carry no affected items: every change type (Version/Revision/New Part/Replacement Part) spins or re-points a method draft in the app, and the status route has no affected-item gate, so a lifecycle-only notice is a legal, realistic state and keeps structural sums untouched.
ChangeOrderSpec.affectedItemsstays required (authored[]). - New optional fields:
changeOrderType(bootstrap name →changeOrderTypeId),priority,dueDateOffset,reasonForChange(TipTap),nonConformance(NCR ref →changeOrder.nonConformanceId; the Engineering Complete notice links the external supplier NCR),actionTasks. Tasks mirrorsetChangeNoticeActionTasks:actionTypeId+ the template'sname, 1-basedsortOrder;changeOrder.requiredActionIdsis not written (the app derives the selection from the tasks). - Validator pins all six changeOrder statuses AND all four
changeOrderTaskStatusvalues per dataset.
- Cluster C9 (Task 11) resolutions:
- Payments mirror post-payment with accounting disabled: Posted
payment(USD, rate 1,bankAccount=accountDefault.bankCashAccount,journalIdNULL) +invoiceSettlementrows withappliedAmount(base) =sourceAmount(principal), rates 1, fx 0,sourcePaymentIdNULL. No payment/memo journals: posting journals needs the invoices' own AR/AP control lines (post-payment reads them), and the C4/C5 invoices were seeded without GL — a lone payment journal would unbalance the subledger tie-out. There is no payment-line/allocation table; settlements ARE the allocation. - Invoice views derive status/balance from settlements (
salesInvoices/purchaseInvoices, migration 20260916143022): ΣCOALESCE(sourceAmount, appliedAmount)over Posted payments/memos vs the LINE total. Base status "Paid" forces balance 0; "Partially Paid" / Credit/Debit Note Issued show total − settled. Probe-verified per dataset. The validator pins it: Paid and Credit/Debit Note Issued fully settled, Partially Paid strictly between with a pre-today payment, every other status unsettled (else the view would re-derive it). - Memos have no invoice column: the tie is
memo.reference= the invoice readable id plus a credit application carried by a zero-cash Posted payment (invoiceSettlement.memoId+appliedViaPaymentId, theapplyCreditsToInvoicesshape;payment_totalAmount_checkallows 0). Without it the AR/AP aging (excludes only Draft/Pending/Voided) would double-count the invoice and the unapplied memo. Each memo credits its invoice in full;reasonAccount= what post-memo stamps with no return order (salesDiscountAccount / supplierPaymentDiscountAccount). So each dataset has 6 payments: paid + partial per side, plus one credit application per side. - Exchange rates →
exchangeRateOverride, notexchangeRate:exchangeRateis the platform-GLOBAL market-rate store (no companyId, service-role writes, every tenant reads it); a tenant template writing it would leak fake rates to all companies. NoexchangeRateHistorytable exists. Seeded one company-scoped EUR override at 1.0852 — same direction as the C5 EUR PO's 1.08 snapshot (EUR per USD, the document convention); validator requires ±5% of the PO rate. The "3 history points" are dropped (no company-scoped history exists). Note for review: 1.08 EUR/USD is the inverse of the real-world ~0.92 — a C5 data choice this cluster follows for consistency. - Periods: 12 trailing monthly
accountingPeriodrows (anchor month back 11),(fiscalYear, periodNumber)computed fromfiscalYearSettings.startMonthexactly likeresolveAccountingPeriod, upserted on that unique key. Months −11/−10 Closed (sequential close), −9 Locked, rest Open, anchor month Active; lock/close stamps set. Periods are seeded BEFORE journals sojournal_check_period_openvets every seeded posting date. Proven bounds (checked over 8 years of anchors): offsets ≥ −273 never land in a Closed month (existing Draft JE at −256 is safe), ≥ −242 always land in an Open one — validator enforces −273 for Draft journals and −242 for posted journals/payments/memos/disposals. - Journals keep
accountingPeriodIdNULL: journal/journalLine survive the dataset wipe but accountingPeriod does not, and the wipe's FK-nulling pass would UPDATE a Posted journal — whichjournal_posted_immutablerejects. The period trigger resolves a NULL period from postingDate. - Journal lines name an account by bootstrap CoA number (
account: "6060") or, for the legacy line form, by class (first account of the class by number — the original revenue entry is byte-identical). New per dataset: payroll accrual (6060 / 2150), license amortization (6310 / contra 1420 credit, negative), and a Reversed pair mirroringreverseJournalEntry(original inserted Posted then flipped Posted→Reversed withreversedById, the one UPDATE the immutability trigger allows; reversal Posted withreversalOfIdand negated lines, sourceType Manual). The amortization targets an intangible, not a registered fixed asset, so it cannot contradict the Draft depreciation run. - Projects link via
purchaseInvoiceLine.projectId—jobhas no projectId column (onlypurchaseInvoiceLineandcardTransactionLinecarry project coding). One project per dataset codes the paid purchase invoice's first line. - Dimensions: bootstrap seeds no Custom dimension, so each dataset creates one (Mission Phase / Product Line / Work Cell / Motor Family) with 2 values; dimension/dimensionValue are companyGroup-scoped (never wiped) so the tier looks up before inserting. The payroll accrual's expense line carries TWO
journalLineDimensiontags: the bootstrap entity-backed Project dimension (valueId = project id, as post-card-transaction writes it) and the custom value. Tags re-attach on re-apply (journalLineDimension IS wiped while journals are not), found by a uniquejournalLineReference. - Close checklist: 3
periodCloseTaskrows on the Locked period (Done / Skipped+reason / Open), snapshotted from the bootstrap definitions likegetPeriodCloseChecklist; the other definitions materialize lazily on first view (unique key makes that idempotent). - Fixed assets: one Disposed (Sale) asset per dataset with
fixedAssetDisposal(NBV = cost − accumulated, gainLoss = proceeds − NBV, journalId NULL) — two gains, two losses across datasets; one Units of Production asset with 2 monthlyfixedAssetUsageLogrows. Its run line is exactly whatbuildDepreciationLinescomputes from the log whoseperiodEndequals the run's (monthsBack 1); the older month's usage is its opening accumulated depreciation. Validator recomputes the UoP charge. Existing assets insert the identical column set (new columns are undefined → dropped).
- Cluster C10 (Task 12) resolutions:
- Notes hang on the person, not a job/customer. The
notetable is read by exactly one screen:getNotes(client, documentId)(apps/erp/app/modules/shared/shared.service.ts) called fromx+/person+/$personId.notes.tsx. A note keyed to a job or customer id would be written and never shown, so both seeded notes usedocumentId = ctx.userIdand render on the demo user's Notes tab. (Rung: codebase precedent — overrides the plan's "one job, one customer".) - Spare-part issue mirrors
issue→maintenanceDispatchInventory(supabase/functions/issue/index.ts): amaintenanceDispatchItemplus an itemLedger rowentryType "Consumption",documentType "Maintenance Consumption",documentId= dispatch,documentLineId= the item line, negative quantity. The plan guessedNegative Adjmt.; the code wins. Untracked consumables only (tracked items need per-entity consumption). Each Completed dispatch issues its dataset's grease/fluid (satellite CN-GREASE-001 ×2 @ A1-L3, robotics CN-GREASE-EP ×2 @ A1-L2, precision CN-COOLANT-55 ×1 @ B3-L1, motor CN-BRG-GREASE ×2 @ A2-L2), and the validator counts that draw in the same per-(item, shelf) on-hand balance as every other cluster. - A Skipped run has no step rows and no
startedAt. A run-level Skip only happens at the engine'sloadstep (unpublished / not entitled) viafinishRun(packages/jobs/src/workflows/engine/log.ts), which setsstatus,statusReason,completedAt,durationMs—claimRunnever ran, so nostartedAtand no trigger step. Succeeded/Failed runs carry the trigger step (sequence 0, Succeeded) plus theaction_assignstep. The Failed step's error is the update action's real message (actions/update.ts: "The assignee you chose is not in this company."); the Skipped reason is the engine'sUNPUBLISHEDconstant. Note for Task 15:.claude/rules/workflow-run-history.mdsays Skipped runs never setcompletedAt— false for load-time skips. - Runs fire on their sales order's order date (
salesOrder.created): each dataset's three runs target the To Ship (−14), To Invoice (−28) and To Ship and Invoice (−21) released orders. Validator requiresat.offset≥ the order'sorderDateOffsetand < 0. - Volume: 5 schedules (one per frequency), 5 dispatches (one per status, together covering every severity/priority/source/OEE impact; the Non-Conformance one links an existing NCR — satellite
ncr:txrx-tvac, roboticsncr:drive-fault, precisionncr:bore, motorncr:fan-noise), 3 trainings (Active "Once" with all five question types + a Completed assignment, Active "Annual" with a Pending assignment, Draft), 6 timecards over days −5…−1 (lunch split on −1), 2 suggestions, 2 notes. A completion is only authored on a "Once" training: a recurring one counts only when its period is the current one, which a day offset cannot guarantee. - Validator (
validateOps) pins: ≥3 schedules over ≥3 frequencies; the full dispatch status/severity/source/OEE sets; Scheduled ⇔ schedule on the same work center; Non-Conformance ⇔ a known NCR; bootstrap failure modes; actualStart/actualEnd/spare parts/actualFailureMode only in the statuses that stamp them; chronology; Active + Draft trainings, one Active training covering all fivetrainingQuestionTypes, ≥1 Completed + ≥1 Pending assignment; ≥5 timecards inside −7…−1 with no overlaps; ≥2 suggestions (ERP/x/paths) and notes; runs Succeeded/Failed/Skipped present, workflow published, step nodeIds ⊆ the definition's non-trigger node ids, Skipped ⇔ no steps ⇔ statusReason.
- Tasks 13–14 (floors + full verification) resolutions:
- Row-count floors (
datasets/coverage.ts, checked inverify.tsbefore the ROLLBACK, one UNION ALL query, every shortfall listed astable: expected ≥ N, got M). The table list was MEASURED, not grepped: rolled-back runs counted every companyId table after bootstrap and again after the tiers for all four datasets — 210 tables grow in every dataset (208 companyId tables — direct inserts plus interceptor rows such as itemCost / jobMakeMethod / quoteMakeMethod / jobOperationStep — and the 2 group-scoped dimension tables), plus the three user-scoped favorites = 213 floors. Floor = the smallest count any dataset produced; volume tables (smallest ≥ 20) get floor(min × 0.8). Counts are absolute, so bootstrap rows are included for group / location / eventSystemSubscription / dimension. Scoping:dimension/dimensionValueare counted by the scratch company'scompanyGroupIdrather than excluded — the drift check mints a fresh group per run, so the count is exact, and the custom dimension is a C9 deliverable worth guarding;jobFavorite/quoteFavorite/salesOrderFavorite(no companyId) are counted through their parent document; the globalperiodtable is skipped. The check-datasets failure advice now names the floors. (Rung: plan Task 13 + codebase precedent —assertWipeClean's UNION ALL.) - Three §B gaps found by the status audit and fixed in all four datasets: (1)
purchasingRfqDraft + Closed — newpurchasing.lifecycleRfqs; Closed mirrors the app's cancel action (purchasing-rfq+/$rfqId.cancel.tsx: Closed, assignee cleared) taken before quotes were requested, so there are no supplier quotes to cancel. (2)trackedEntityScrapped — Task 5 had dropped it with only a validator comment ("would need a paired scrap ledger row from a job"), which ground rule 9 forbids; it now mirrors post-inventory-adjustment's full-entity Scrap (entity Scrapped and keeps its quantity, a "Scrap" trackedActivity + input, a "Negative Adjmt." / "Scrap" itemLedger row carryingscrapReasonId), with the shelf's opening stock raised by the lot so available stock is unchanged; no GL, like every other seeded inventory posting. (3)itemRevisionStatusPrototype + Production — Task 4 assumed the ladder item's active revision was "Production-equivalent", but the column defaults to Design; tier 02 now promotes it to Production (the released revision — an app-level BOM/BOP lock initems.server.ts, no DB trigger, and no change order edits the ladder items) and every ladder's next rung is Prototype. Validator pins all three (REQUIRED_PURCHASING_RFQ_STATUSES,REQUIRED_TRACKED_ENTITY_STATUSES, a Prototype-rung rule) with five new vitest cases. Every other absent enum value is classified, with a citation, in.ai/runs/2026-09-23-demo-data-status-audit.txt— notably a Completed RMA whose lines keep disposition Pending is a real app state (setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and disposition is a post-receipt decision). - Re-apply was broken by this branch's lifecycle data (found by the Task 14 re-apply step): the wipe could not clear a company holding the demo's posted documents. Fixed in
wipe.ts, all inside the one apply transaction: (a) theprevent_posted_{sales,purchase}_invoice_deletionsync interceptors refuse deleting any non-Draft invoice and run even underapp.sync_in_progress, so the wipe first returns the company's invoices to Draft — a re-seed clear, not an app-level delete of a posted document; (b)invoiceSettlementholds ON DELETE RESTRICT FKs to its target invoice/memo, so it is deleted before the invoice headers; (c)paymentandmemocarry a customer-XOR-supplier CHECK that the FK-nulling pass would break, so they are deleted with the settlements.session_replication_role = 'replica'(the restore wipe's approach) was rejected: it needs superuser, and this wipe also runs in the hostedcompany-templatejob. (Rung: spec §C5 — re-apply must stay clean; acceptance #4.) - Pre-existing leak fixed on the same path: the customer/supplier interceptors mint one
groupper partner (org groups, id = the partner id) and per customer/supplier type, and nothing deletes them;groupis preserved, so every re-apply left ~25 orphan groups named after the previous story's partners in the group pickers. The wipe now deletes org/type groups whose owner is gone, keeping bootstrap's "All Customers"/"All Suppliers" roots by theirgetGroupIdid; employee-type groups are untouched. - Documented, deliberately unchanged:
journal/journalLinesurvive the wipe (posted immutability), and tier 09 adoptsJE-SEED-00xbyjournalEntryId, so after a cross-dataset re-apply the FIRST dataset's journal text remains (verified: robotics over satellite kept the five satellite entries);dimension/dimensionValueare companyGroup-scoped and a company wipe must never delete them (sibling companies share them), so each distinct dataset applied adds its own name-keyed custom dimension — bounded at one per dataset. - Baseline method notes: the 2026-08-13 structural file's methodOperation columns are (laborTime, setupTime, machineTime) — its 263.75 | 0 | 0 matches laborTime exactly; the journal balance metric is natural-balance signed (
lib/utils.tsdebit/credit: asset/expense debit = +, liability/equity/revenue credit = +), so a raw Σamountis non-zero by design and the per-journal debit-minus-credit is what must be 0.
Open Questions (audit trail — all resolved autonomously)
- How can posted/paid states exist without edge functions? — Autonomous: hand-authored downstream rows (Decision 1).
- One flagship dataset or all four? — Autonomous: all four (Decision 3).
- Where do maintenance/HR/training live? — Autonomous: new
opsslice, tier 10 (Decision 2). - Should validation fail when the DB is down? — Autonomous: the new pure layer always runs; the DB layer keeps its deliberate skip (Decision 5).
- EE-gated demo data? — Autonomous: excluded (Decision 6).
- Row-count regression guard? — Autonomous: verify.ts floors manifest + baselines (§D2).
- Quote costing methods? — Autonomous: attempt with fallback (Decision 9).
- What does "leave out files" exclude exactly? — Autonomous: the Documents module + any storage uploads; notes/tags stay (they are rows, not files).
Changelog
- 2026-09-22: Spec written (autonomous mode, per user instruction); proceeds directly to plan.
- 2026-09-23: Tasks 13–14 — row-count floors, status audit (3 gaps fixed), re-apply repaired, baselines re-captured (Autonomous Decision 15).
- 2026-09-23: Task 15 — docs synced (onboarding rule: 12 slices, two-layer drift check, wipe pre-steps, new "Posted documents" section, new baselines; datasets + database AGENTS.md; workflow-run-history
completedAtclaim corrected; user docs + agent KB). Status → Implemented. The tier 07 NCR job-operationcontinueflagged during docs review was converted to a namedSeed:throw (orchestrator), consistent with Decision 4.
§13a Correction after C9 review (orchestrator)
- EUR rate direction fixed. C5 seeded the EUR PO at
exchangeRate: 1.08and C9 pinned the override at 1.0852 to match. Both columns are "units of the foreign currency per 1 unit of base" (exchangeRateOverridemigration comment;toBaseAmount(documentAmount, foreignPerBaseRate)divides), so 1.08 meant 1 USD = 1.08 EUR — inverted. Changed to PO 0.92 / override 0.9215 in all four datasets, and the validator now fails any EUR rate outside (0.5, 1) with an "is it inverted?" message. (Rung: codebase precedent — the precision rule and the migration define the direction.)