Skip to content

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.

51.2 KB
Raw Blame

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

  1. Every user-reachable status enum value of every major document type appears in every dataset (matrix in Design §B).
  2. 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).
  3. 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.
  4. All four industries stay in rough volume parity (the existing coverage contract), enforced structurally by required (non-optional) slice fields.
  5. 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; existing demandProjection seeding 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

  1. 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 ?? null only where the column is nullable and the spec omitted the key on purpose (typed as optional).
  2. Posted docs carry their ledger. Hand-authored itemLedger/journal/invoiceSettlement rows 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).
  3. Sequences respected. All new readable-id documents go through the existing sequence machinery; insertion order rules (opportunities → statusOrders → releasedOrders) preserved and extended.
  4. Interceptors respected. New inserts follow the adopt-don't-duplicate pattern (jobMakeMethod, itemCost) wherever a sync interceptor creates the row.
  5. Wipe compatibility. All new tables are companyId-scoped → wipeCompanyBusinessData discovers them automatically; verify none belong in PRESERVED_TABLES (only period (global) and bootstrap-owned config do). Re-apply (second template onto same company) must stay clean — covered by acceptance test.
  6. Timezone/dates: all offsets via DayOffset + resolveDate; previousMonthEnd for period ends; no JS Date.

D. Validation (the commit gate)

  1. 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 vs rfqQuantityBreaks); journal lines balance; end-state on-hand non-negative per item; promisedDateOffset within the 48-week horizon; componentNodeIds ⊆ bundled graph.json; every slice non-empty; supersession pairs reference distinct existing items. Runs (a) first inside check-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) so pnpm test covers it.
  2. verify.ts gains 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.
  3. Hook semantics unchanged (trigger path, skip env var, DB-down warning for the DB layer, clear block message). The pure layer never skips.
  4. 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

    1. pnpm db:check:datasets passes 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 ref ST-050-BOGUS → ✗ satellite … unknown item exit 1, and floor drill → pickingList: expected ≥ 3, got 2 exit 1, both in .ai/runs/2026-09-23-demo-data-verification-drills.txt.
    1. Pure validator: pnpm --filter @carbon/database test includes dataset validation; breaking a ref fails the test AND blocks git commit even with the DB stopped. — Evidence: validate.test.ts runs validateDataset on 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 through check-datasets, not vitest; vitest's ref coverage is the negative cases.
    1. 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).
    1. 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.ts fixes in Autonomous Decision 15.
    1. 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).
    1. Every seeded journal balances; no (item, shelf) on-hand goes negative (validator-enforced). — Evidence: validate.ts journal-balance and net on-hand checks run on every commit; structural baseline shows JE-SEED-001…005 each with debit − credit = 0.
    1. pnpm exec turbo run typecheck --filter=@carbon/database green; Biome green. — Evidence: pnpm --filter @carbon/database typecheck exit 0 (Task 15 re-run); Biome 0 errors at Task 14.
    1. .claude/rules/onboarding-company-templates.md + packages/database/src/datasets/AGENTS.md updated (new slices, validator, baselines). — Evidence: Task 15; also packages/database/AGENTS.md, .claude/rules/workflow-run-history.md, docs/content/docs/platform/demo-data.mdx (+ regenerated agent KB).

Autonomous Decisions (high-stakes first)

  1. 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.)

  2. 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".)

  3. 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.)

  4. 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.)

  5. 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.)

  6. Branch/workflow: work directly on feat/demo-data-completeness in this checkout; no commits without explicit user permission (standing user rule overrides ship-it's commit steps).

  7. 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.

  8. Cluster C4 (Task 6) resolutions:

    • The no-quote reason column is salesRfq.noQuoteReasonId (not quote/quoteLine — updateSalesRFQStatus writes it), so it is wired as SalesRfqSpec.noQuoteReason on the Closed RFQ that pairs with each dataset's Lost quote; tier 01 now registers nqr:<name> refs.
    • SalesInvoiceSpec.key is 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.salesOrder sits at the HEADER (schema: salesReturnOrder.salesOrderId; the line-level column is salesOrderLineId, which the seed leaves null). returnReason is a header field applied to every line's returnReasonId (per-line in schema).
    • A Completed RMA mirrors post-receipt's "Sales Return Order" branch fully: a Posted receipt (sourceDocument "Sales Return Order") + receiptLine rows + one "Positive Adjmt." / "Sales Return Receipt" itemLedger row per line into the line's toShelf. salesReturnOrderCreditLine is NOT seeded — its memoId is 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 eventsJobKey job.
  9. 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: trackedEntity with 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 with trackedEntityId. No trackedActivity rows — 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) + shipmentLine rows + one "Negative Adjmt." / "Purchase Return Shipment" itemLedger row per line out of the line's fromShelf. PurchaseReturnSpec.lines[].unitPrice was 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 create edge function's outside-processing branch: an ordinary direct PO with purchaseOrderType: "Outside Processing" whose line is the PROCESSED MAKE PART (the jobMakeMethod item) priced at the operation's operationUnitCost; jobId/jobOperationId stay 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, exchangeRateUpdatedAt stamped at the order date the way insertPurchaseOrder does), 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).
  10. 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.note is plain TEXT, not TipTap — the MES operation Chat writes/reads bare strings (Chat.tsx renders {m.note} in a <p>), so the seed authors plain sentences and does NOT use RICH(). The plan's "likely TipTap" guess was wrong; code wins.
  • jobOperationBatch links members via jobOperation.jobOperationBatchId (no child table). Seeded the way the batch-operations edge function creates one: readableId from the jobOperationBatch sequence (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.
  • rework is fully satisfiable (jobId, quantity, reason, requestedById, target/triggeredAt operation ids) — seeded OPEN (completedAt null) 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's storageUnitId into toStorageUnitId. The lineside destination is the floor storage unit (isWorkCenterDefault) of the work center on the job's first root operation with a work center (no toWorkCenter spec field).
  • pickingListLine.jobMaterialId is 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 of items.methods).
  • A "No Deadline" job carries no dueDate (dueDateOffset now 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.quantities REPLACES 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 in ctx.refs.misc, never module scope, which would leak across the drift check's four companies).
  • The open MES event is a Setup productionEvent with endTime: null for ctx.userId at resolveTimestamp(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 root quoteMakeMethod rows exist to adopt, and sync_insert_quote_material_make_method mints child rows exactly like the job-side interceptor copyMethodToJob already adopts.
  1. Cluster C7 (Task 9) resolutions:
  • NCR tasks mirror the create edge function's "nonConformanceTasks" case, not free-standing rows: nonConformance.requiredActionIds lists the bootstrap nonConformanceRequiredAction ids in order and each becomes a nonConformanceActionTask (actionTypeId, 1-based sortOrder); approvalRequirements = ["MRB"] yields one nonConformanceApprovalTask plus 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 type resolves by name against the company's bootstrap nonConformanceType rows (shared cached helper helpers/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 (+ TipTap content, as the edge function derives it), dueDateOffset, closeDateOffset (required iff Closed).
  • Associations write the exact shapes insertIssue / the association modal write: nonConformanceSupplier (its sync_create_nc_external_link interceptor 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 register te:<readableId> (ctx.refs.misc) for every seeded lot; tier 05 registers poline:<poRef>:<item> and rline:<receiptRef>:<item> (ctx.refs.documents).
  • Inspection graph is fully seedable without files. inspectionSamplingPlan is NOT an item-level AQL plan (the plan text was stale — itemSamplingPlan was dropped 2026-07-26): it is per (inspection lot, inspectionFeature), and features hang off an inspectionDocument, whose storagePath is nullable — the app's own "new inspection plan" form creates one with no file. So each dataset seeds, mirroring post-receipt: a file-less inspectionDocument (AQL default rule, ANSI_Z1_4 / II / Normal) with 2 Measurement inspectionFeatures, the Receipt-usage itemInspectionDocumentAssignment, the lot inspection (plan snapshot resolved by the real resolveSamplingPlan), one inspectionSamplingPlan per feature, n samples + measurements, and the disposition's inspectionHistory row. 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-nonconformance write-off (itemLedger + GL) the seed does not author. Sample/measurement statuses are derived with the engine's rules (helpers/inspection.ts duplicates valuateMeasurement — @carbon/database/quality imports 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); gaugeCalibrationRecord carries Pass/Fail (inspectionStatus). The tier replays records the way upsertGaugeCalibrationRecord does (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 gets lastCalibrationStatus Out-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 (the gauges view also shows Inactive as Out-of-Calibration).
  • riskRegister links follow each entity's RiskRegisterCard: sourceId = customer/supplier/item/job/work-center id; Item risks also set itemId, Job risks set itemId = 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.
  • nonConformanceWorkflow skipped (out of scope per plan; no need for a workflow link to demo NCR depth).
  1. 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.affectedItems stays 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 mirror setChangeNoticeActionTasks: actionTypeId + the template's name, 1-based sortOrder; changeOrder.requiredActionIds is not written (the app derives the selection from the tasks).
  • Validator pins all six changeOrder statuses AND all four changeOrderTaskStatus values per dataset.
  1. Cluster C9 (Task 11) resolutions:
  • Payments mirror post-payment with accounting disabled: Posted payment (USD, rate 1, bankAccount = accountDefault.bankCashAccount, journalId NULL) + invoiceSettlement rows with appliedAmount (base) = sourceAmount (principal), rates 1, fx 0, sourcePaymentId NULL. 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, the applyCreditsToInvoices shape; payment_totalAmount_check allows 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, not exchangeRate: exchangeRate is 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. No exchangeRateHistory table 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 accountingPeriod rows (anchor month back 11), (fiscalYear, periodNumber) computed from fiscalYearSettings.startMonth exactly like resolveAccountingPeriod, 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 so journal_check_period_open vets 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 accountingPeriodId NULL: journal/journalLine survive the dataset wipe but accountingPeriod does not, and the wipe's FK-nulling pass would UPDATE a Posted journal — which journal_posted_immutable rejects. 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 mirroring reverseJournalEntry (original inserted Posted then flipped Posted→Reversed with reversedById, the one UPDATE the immutability trigger allows; reversal Posted with reversalOfId and 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 — job has no projectId column (only purchaseInvoiceLine and cardTransactionLine carry 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 journalLineDimension tags: 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 unique journalLineReference.
  • Close checklist: 3 periodCloseTask rows on the Locked period (Done / Skipped+reason / Open), snapshotted from the bootstrap definitions like getPeriodCloseChecklist; 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 monthly fixedAssetUsageLog rows. Its run line is exactly what buildDepreciationLines computes from the log whose periodEnd equals 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).
  1. Cluster C10 (Task 12) resolutions:
  • Notes hang on the person, not a job/customer. The note table is read by exactly one screen: getNotes(client, documentId) (apps/erp/app/modules/shared/shared.service.ts) called from x+/person+/$personId.notes.tsx. A note keyed to a job or customer id would be written and never shown, so both seeded notes use documentId = ctx.userId and 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): a maintenanceDispatchItem plus an itemLedger row entryType "Consumption", documentType "Maintenance Consumption", documentId = dispatch, documentLineId = the item line, negative quantity. The plan guessed Negative 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's load step (unpublished / not entitled) via finishRun (packages/jobs/src/workflows/engine/log.ts), which sets status, statusReason, completedAt, durationMs — claimRun never ran, so no startedAt and no trigger step. Succeeded/Failed runs carry the trigger step (sequence 0, Succeeded) plus the action_assign step. 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's UNPUBLISHED constant. Note for Task 15: .claude/rules/workflow-run-history.md says Skipped runs never set completedAt — 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 requires at.offset ≥ the order's orderDateOffset and < 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, robotics ncr:drive-fault, precision ncr:bore, motor ncr: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 five trainingQuestionTypes, ≥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.
  1. Tasks 13–14 (floors + full verification) resolutions:
  • Row-count floors (datasets/coverage.ts, checked in verify.ts before the ROLLBACK, one UNION ALL query, every shortfall listed as table: 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/dimensionValue are counted by the scratch company's companyGroupId rather 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 global period table 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) purchasingRfq Draft + Closed — new purchasing.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) trackedEntity Scrapped — 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 carrying scrapReasonId), with the shelf's opening stock raised by the lot so available stock is unchanged; no GL, like every other seeded inventory posting. (3) itemRevisionStatus Prototype + 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 in items.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) the prevent_posted_{sales,purchase}_invoice_deletion sync interceptors refuse deleting any non-Draft invoice and run even under app.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) invoiceSettlement holds ON DELETE RESTRICT FKs to its target invoice/memo, so it is deleted before the invoice headers; (c) payment and memo carry 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 hosted company-template job. (Rung: spec §C5 — re-apply must stay clean; acceptance #4.)
  • Pre-existing leak fixed on the same path: the customer/supplier interceptors mint one group per partner (org groups, id = the partner id) and per customer/supplier type, and nothing deletes them; group is 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 their getGroupId id; employee-type groups are untouched.
  • Documented, deliberately unchanged: journal/journalLine survive the wipe (posted immutability), and tier 09 adopts JE-SEED-00x by journalEntryId, so after a cross-dataset re-apply the FIRST dataset's journal text remains (verified: robotics over satellite kept the five satellite entries); dimension/dimensionValue are 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.ts debit/credit: asset/expense debit = +, liability/equity/revenue credit = +), so a raw Σamount is 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 ops slice, 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 completedAt claim corrected; user docs + agent KB). Status → Implemented. The tier 07 NCR job-operation continue flagged during docs review was converted to a named Seed: throw (orchestrator), consistent with Decision 4.

§13a Correction after C9 review (orchestrator)

  • EUR rate direction fixed. C5 seeded the EUR PO at exchangeRate: 1.08 and C9 pinned the override at 1.0852 to match. Both columns are "units of the foreign currency per 1 unit of base" (exchangeRateOverride migration 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.)