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.

57.8 KB
Raw Blame

Demo Data Screen Coverage — every screen renders, every engine has run

Status: Implemented (autonomous, uncommitted — awaiting the user's commit) · Date: 2026-09-23 · Branch: feat/demo-data-completeness Follows: .ai/specs/2026-09-22-demo-data-completeness.md (status-matrix pass, committed as bfdfc1de02 + 3f682e8aca). Research: .ai/research/2026-09-23-screen-audit-erp-commercial.md, .ai/research/2026-09-23-screen-audit-erp-operations.md, .ai/research/2026-09-23-screen-audit-mes-quality-resources.md, .ai/research/2026-09-23-screen-audit-erp-settings-people.md, .ai/research/2026-09-23-planning-engine-seeding.md

Reading of the request (autonomous mode)

What: after applying any of the four demo datasets, every ERP and MES screen a user can open shows meaningful, editable data — not just "every status appears somewhere". Why: the user opened the app and found whole screens empty (customer portals, sales rules, MES schedule, Production › Forecast / Priorities, resource and material planning) and only 8 jobs; the previous pass verified status coverage, never screens. Where: the dataset engine + data packs, the dataset wipe, a post-commit planning step (MRP + scheduler) for the two callers that commit (template job, dev CLI), and the commit gate. Who: anyone applying a demo template (onboarding, Settings › Demo Data, pnpm db:seed:dev). Constraints carried over: files excluded, FK integrity, no regressions, invalid demo data blocks the commit, autonomous mode, never commit without asking, never rebuild the DB.

Goals

  1. Every screen classified EMPTY or FILTERED-EMPTY in the five research audits renders rows after a real apply of each dataset, except the documented exclusions (Non-goals).
  2. Planning screens are populated by the real engines: MRP (runMrp) and the scheduler (runLocationSchedule) run once, post-commit, after every template apply and every dev-CLI seed.
  3. The shop floor looks alive: ≥ 18 jobs per dataset with open work due within −3…+21 days of today, spread over every work center, with priorities, assignees, running production events and recent completions.
  4. Three pre-existing apply failures on used companies are fixed (intercompany partners, posted card transactions, model-only step slides); the accounting-period fix stays.
  5. Every new shape is pinned by validateDataset, REQUIRED_* sets and COVERAGE_FLOORS, so a regression blocks the commit.

Non-goals

  • Files (user-excluded): documents, logos, backups, attachments, inspection-plan drawings/balloons, step-slide images.
  • New global user rows (synthetic employees / console operators / portal accounts) — see Autonomous Decision H3.
  • Audit log — needs a per-company DDL table (create_audit_log_table) the wipe cannot manage.
  • API keys — a fake hash would be a non-working credential in a security screen.
  • Integrations, SSO, billing, subsidiaries/ITAR (env- or credential-gated); home "recents" (browser localStorage).
  • Real intercompany / card-transaction data (integration-coupled) — the wipe now refuses such companies instead.
  • Changing app code to make empty-by-design defaults nicer (e.g. maintenance lists defaulting to the first location) — seed around it.

Design

A. Wipe (applies to all callers)

Case Behaviour
accountingPeriod (done, uncommitted) preserved; tier 09 adopts a month's existing period by (fiscalYear, periodNumber), else by startDate
model-only step slides assemblyInstructionStepSlide, methodOperationStepSlide, jobOperationStepSlide, quoteOperationStepSlide deleted before the FK-nulling pass (their content CHECK cannot survive it), like TRANSIENT_MRP_TABLES
intercompany customers/suppliers (intercompanyCompanyId set) refuse up front, before any write: "This company trades with other companies in its group … demo data can only be applied to a company without intercompany partners."
Posted/Voided cardTransaction refuse up front: "This company has posted card transactions, which cannot be deleted …"

Refusals are thrown as a named Seed: error from a preflight inside wipeCompanyBusinessData, so the template job's marker gets failed + the message and nothing is written.

B. Seed data + tier extensions (all four datasets)

Grouped by screen. "Tier" = engine shape to add; everything else is data in data/<key>/.

B1 Production floor (tier 06, production.ts)

  • Open jobs re-dated to due −3…+21 (existing open jobs moved; validator chronology kept).
  • ≥ 10 additional released jobs (Ready/In Progress) of short-routing items per dataset, touching every work center; 1 released job with no due date (Priorities › Unscheduled); 2 make-to-stock jobs (salesOrderId NULL).
  • Distinct job.priority; job.assignee / jobOperation.assignee = applying user on ~6 open items.
  • 3 jobs Completed within the last 3–25 days with Setup/Labor/Machine productionEvents (completion-time + estimates-vs-actuals KPIs); open events (endTime NULL) today on 3–4 work centers.
  • jobOperationStepRecord for done ops; jobOperationParameter / jobOperationTool on a few ops; one Final Inspection op operationType='Inspection' + inspectionDocumentId; ROB-style assembly op linked to the seeded assembly instruction (methodOperation/jobOperation.assemblyInstructionId).
  • One batchable process; an Active jobOperationBatch with ≥ 2 members from different jobs.
  • Procedures: one Active, one Archived, rest Draft (versions); make methods of seeded items Active; assembly instruction published state.
  • pickMethod default shelf per stocked item at the plant.

B2 Planning (tier 12 + post-commit step)

  • Engines run post-commit (Section C) → demandActual/Forecast/supplyActual/Forecast, capacityReservation, op start/due dates, dependencies.
  • peopleAssignment for the current week and a peopleAbsence; shifts created at the plant (not HQ) + workCenterShift links; the applying user's employeeJob upserted (it is a silent no-op today when missing) with location = plant, title, department, shift, start date.

B3 Sales & purchasing (tiers 02, 04, 05)

  • enforcementRule family sales (item-targeted, warn + error) with item assignments; family storage and a work-center rule with assignments.
  • Customer portals: externalLink documentType Customer for 2 customers.
  • approvalRule (PO tiers + supplier) and Pending approvalRequests for the Needs-Approval PO and the Pending supplier.
  • Quote methods: each Make-to-Order quote line gets its item's method copied (quoteMakeMethod/quoteMaterial/quoteOperation) — reverses 2026-09-22 Decision 9.
  • Configurator: one configurable item requiresConfiguration=true, a configurationRule, one configured quote line.
  • assignee on a few open quotes/SOs/POs/RFQs; supplier status on every supplier; createdAt spread over past offsets for quotes/RFQs/supplier quotes; 2 more pricing rules; customer/supplier bank accounts if the table is tenant data.
  • Return orders: memos linked (salesReturnOrderId/purchaseReturnOrderId) with credit lines; nonConformance{Sales,Purchase}ReturnOrderLine.

B4 Invoicing & accounting (tiers 04, 05, 09)

  • postingDate = dateIssued on every non-Draft invoice (fills Receivables/Payables/aging).
  • Posted journals shaped like the posting paths: Sales Invoice (AR/Revenue), Purchase Invoice (Inventory|Expense/AP), Payment (Cash vs AR/AP, payment.journalId set), plus one Opening Balance, with accountingPeriodId set (periods now survive the wipe). Aging spread over Current / 1–30 / 31–60 / 61–90.
  • Draft Receipt + Draft Disbursement payments (apply UI).
  • costLedger rows paired with posted receipt/shipment ledger rows; itemCost.unitCost non-zero.
  • AR/AP billing-address rows.

B5 Quality, maintenance, resources (tiers 07, 10)

  • nonConformanceWorkflow ×3 linked from NCRs; nonConformanceItem on every NCR; NCR assignee; nonConformanceSupplier on a supplier NCR; nonConformanceActionProcess; procedureParameter.
  • QualityData.inspection becomes a list: Passed receipt lot, Pending lot, Job Operation lot.
  • Maintenance: maintenanceDispatchItem.unitCost; a Reactive dispatch on a production-event day; 2 back-dated Completed dispatches; a Scheduled dispatch due today; an In Progress + Down dispatch; workCenterReplacementPart; one HQ work center with a dispatch + schedule.
  • partner rows.

B6 Settings & people (tiers 01, 10)

  • companySettings.timeCardEnabled = true + one open time-card entry today.
  • userAttributeCategory → userAttribute → userAttributeValue for the applying user.
  • itemSerialSequence per serial-tracked item; 3 customFields; printJob history. one active=false webhook — dropped (D66).

C. Post-commit planning step

planDemoCompany({ companyId, userId }) in @carbon/jobs (which already depends on @carbon/planning): runMrp(serviceRole, db, { type: "company", … }), then runLocationSchedule for every location with Ready/In Progress/Paused jobs — the same calls the cron and api+/schedule.ts make. Callers:

  • companyTemplateFunction: a new step.run("plan-template") after apply-template, non-fatal (logs + metadata.planningError; the 3-hourly MRP cron is the backstop). Revert/finalize unchanged.
  • Dev CLI: seed-dev.ts (in @carbon/database, which cannot import @carbon/planning — cycle) spawns pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> after its commit; failure prints a warning and exits 0. --skip-plan opts out.

D. Checks

  • validate.ts: refs for every new slice field; REQUIRED_* for procedure (Draft/Active/Archived), approval request, enforcement-rule family, inspection status list, dispatch shapes; floor rules for "open job due within window", "every work center has open ops", "≥ 18 jobs".
  • coverage.ts: re-measured floors for every newly written table. Engine outputs (MRP tables, capacityReservation) stay OUT of floors (verify.ts rolls back before engines run) and are covered by the screen matrix instead.
  • Screen matrix: a script (scratchpad; evidence in .ai/runs/) that, against a real seeded + planned company, runs one count query per screen data source with the screen's own filters (from the audits) and asserts non-zero for every in-scope screen, for all four datasets.

Design Decisions

# Decision Rationale
1 Engines run post-commit, in-process, non-fatal real engine output, zero drift; in-transaction run impossible (PostgREST reads + own transactions — research §3a)
2 Wipe refuses IC partners and posted card transactions both are immutable by trigger and FK-linked to rows the wipe must delete; preserving them cannot satisfy the trigger
3 Slides deleted before FK nulling CHECK imagePath OR modelUploadId cannot survive nulling; the slide is business data the wipe deletes anyway
4 No new global user rows tenancy + identity safety (H3)
5 Journals authored for posted docs Revenue/AR/AP would otherwise read $0 on every financial report
6 Dates stay DayOffset; engine output uses the engine's own clock engines run "now"; seed anchor is "today" — same day
7 Shifts move to the plant every work center is at the plant; scheduler + resource planning read plant shifts

Acceptance criteria

  1. For each dataset, after pnpm db:seed:dev -- --email [email protected] --dataset <key> (engines included), the screen matrix reports 0 in-scope screens with 0 rows; evidence .ai/runs/2026-09-2x-screen-matrix-<key>.txt.
  2. MES operations board for the applying user shows ops on every plant work center, with start dates within ±3 weeks and ≥ 1 running op on 3+ work centers.
  3. Production › Priorities shows jobs in the current week and ≥ 1 Unscheduled job; Scheduling › Forecast and Resource Planning show reservations/assignments; both Material Planning screens show week columns with demand.
  4. Sales rules, storage rules, customer portals, approval rules, procedures (Active + Archived), configurator all list rows.
  5. Income statement revenue ≠ 0; receivables aging has rows in ≥ 3 buckets.
  6. The four wipe cases in §A behave as specified in a rolled-back apply against a company constructed in each state.
  7. pnpm --filter @carbon/database typecheck, test, pnpm db:check:datasets (all four), turbo typecheck for @carbon/jobs pass; a real re-apply over a seeded company exits 0.
  8. A deliberately broken new ref / removed required status blocks sh .husky/pre-commit.

Autonomous Decisions (high-stakes first)

  • H1 — Reverses 2026-09-22 non-goals. Approval rules, enforcement rules, demand/supply forecasts, printJob and a webhook were out of scope; the user's report puts them in. — Autonomous: in scope — rung 1 (user's stated intent: "every feature visible").

  • H2 — Engines outside the all-or-nothing apply (public behaviour of the template job). Options: (a) run in-transaction (impossible, research §3a), (b) hand-author MRP/scheduler output (drift from the real engine), (c) run post-commit non-fatal. — Autonomous: (c) — rung 2 (the cron and api+/schedule.ts already run the same functions after commit) + rung 5 (real numbers beat plausible ones). Consequence: a planning failure leaves a seeded but unplanned company, healed by the cron.

  • H3 — No synthetic people (narrows the ask). Options: create user+employee rows per template (global identity table, unique emails, the company wipe cannot remove them, rows accumulate per apply, they can never log in) vs keep the applying user as the only person. — Autonomous: no new user rows — rung 5 (tenancy/identity safety outweighs a longer People list). People screens render the applying user fully (job, shift, attributes, timecards, assignments).

  • H4 — Wipe refuses two company states (public contract of apply). Options: preserve, refuse, or force-delete. Force-delete breaks immutability triggers; preserving fails the FK-nulling UPDATE. — Autonomous: refuse with a clear message — rung 5 (reversible, no data loss; demo templates target fresh/test companies).

  • H5 — Journals for posted documents (accounting shape). Options: leave GL empty (Revenue $0), author journals shaped like the posting paths, or run posting functions (impossible in-transaction). — Autonomous: author them, payment.journalId set — rung 2 (tier 09 already hand-authors posted journals in the posting shape). Changes the prior "payments carry journalId NULL / accounting disabled" convention; the rule doc is updated.

  • H6 — Quote methods now seeded (reverses 2026-09-22 Decision 9). — Autonomous: copy item methods into quotes — rung 1 (quote BoM/BoP tabs are screens the user can open).

  • D7 — Audit log, API keys, documents stay excluded — rung 5 (DDL per company / credential / files).

  • D8 — Dev CLI reaches the engines by spawning a @carbon/jobs script, not importing — rung 2 (package graph: @carbon/planning → @carbon/database).

  • D9 — Engine tables stay out of COVERAGE_FLOORS; covered by the screen matrix — rung 5 (verify.ts cannot run engines inside its rollback).

  • D10 — Shifts move to the plant; HQ gets one work center + maintenance so location-defaulted lists aren't empty — rung 5.

  • D11 — Volume: ≥ 18 jobs per dataset (today 8) — rung 4 (research §5.2 load per work center).

  • D12 — Task 2: plan-company.ts loads demo-planning.ts through createRequire, so tsx compiles the graph as CJS; as ESM, @carbon/planning's named imports from @carbon/database (no "type":"module") fail to link (SyntaxError … supersession-pick does not provide an export named buildConsumeFirstHops, reproduced). Rejected: adding a jiti dependency, or "type":"module" on @carbon/database. — rung 2 (packages/jobs/AGENTS.md: bare tsx scripts cannot rely on Vite's interop).

  • D13 — Task 2: seed-dev.ts spawns the planning script with NODE_EXTRA_CA_CERTS=~/.portless/ca.pem when that file exists and the var is unset; without it runMrp's supabase-js reads failed with fetch failed (SELF_SIGNED_CERT_IN_CHAIN) against the portless SUPABASE_URL. The direct CLI's usage text says to set it. — rung 2 (packages/dev/src/services/apps.ts gives the apps the same CA).

  • D14 — Task 2: metadata.planningError is written only while the marker still belongs to this run (snapshot path, ready); on the snapshot: false path the marker is already cleared, and writeTemplateMarker would re-insert it as running, so the failure is only logged. A new apply resets planningError: null. — rung 5 (the plan requires the post-apply status to be unchanged).

  • D15 — Task 3: floor jobs need sales orders (the plan wants only 2 make-to-stock; JobSpec required one). Added two In Progress "floor-load" orders per dataset to data/*/sales.ts releasedOrders (one line per job item); JobSpec.salesOrder/salesOrderLine/customer became an all-or-none triple (none = make-to-stock). — rung 2 (every existing job hangs off an SO line).

  • D16 — Task 3: "the seeded inspection document" is quality's receipt plan for a bought part, but the BOP picker lists only plans whose partId is the item (getInspectionDocumentsForItem). New shape ItemsData.inspectionPlans (file-less plan + features, tier 02) named by BopOperationSpec.inspectionPlan on one Final Inspection op per dataset; copyMethodToJob copies inspectionDocumentId + assemblyInstructionId. — rung 2.

  • D17 — Task 3: reverses the 2026-09-22 "leave Draft so the demo can edit" choices for make methods (authored methods only — buy parts' interceptor methods stay Draft; tier 08 still cuts its Draft versions from the Active base) and the assembly instruction (Published). Procedures: v1 Archived / v2 Active on the first, Active on the second, rest Draft. — rung 1 (plan).

  • D18 — Task 3: completed jobs' actuals are engine-derived (JobSpec.loggedTime {startOffset, efficiency} × makeDurations' unit math per staffed op), not authored events. Setup/Machine events need estimates, so a few ops per dataset gained setupTime/machineTime (precision already had them); a validator rule pins it. Outside-processing ops (no work center) log nothing. — rung 5.

  • D19 — Task 3: robotics CTRL-100 gained op 3 "Cabinet power-up and safety I/O check" at Integration Cell 1 — otherwise that cell had one open op and research caps ROB-2000 jobs at two. — rung 4.

  • D20 — Task 3: validator floor thresholds follow the capability list (≥ 2 open ops per work center, ≥ 4 running work centers incl. the existing open event, ≥ 6 assigned open ops, all open jobs due −3…+21, release ≥ SO order date). Historical release dates stay (picking lists, NCR links and shift events hang off them); only due dates were re-dated, plus the Ready job released at −4. — rung 1 + 5.

  • D21 — Task 3: jobOperationTool/jobOperationParameter come from copying the method's tools/parameters in copyMethodToJob (as get-method's itemToJob does); the batch is authored as ≥ 2 unstarted root ops of released jobs on one process (replacing the one-member batch on a Done op), and that process is flagged batchable. — rung 2 (batch-operations create rules).

  • D22 — Task 3: step records — one row (index 0) per step of every Done op; File steps skipped (needs an upload); Value "OK", List first option, Measurement mid-range, Person = applying user, Timestamp = the op's last event end. Running timers start 06:45–08:15 UTC like the existing open event (in the past for US companies' mornings). — rung 5.

  • D23 — Task 4: the open time card clocks in at 05:57–06:33 UTC today (OpsData.openTimecard), not the plan's "07:00 company TZ". 07:00 local is 11:00–12:00 UTC for the four US plants: after the running production timers (06:45 UTC earliest, D22) and in the future for a seed run before 07:00 local. UTC matches TimecardSpec and D22; the validator pins clockIn ≤ the earliest running timer (incl. the 08:00 open event). — rung 2.

  • D24 — Task 4: peopleAssignment for the applying user on days −2, −1, +1…+4, never today (validator): a today row pre-filters the MES schedule to one work center (apps/mes/app/routes/x+/operations.tsx:217-241, research MES §1.5). One row per day (one person; unique (employee, date, shift)), ≥ 3 work centers, one row with overtime; one peopleAbsence in +7…+13 on a day with no assignment. Dates are anchor-relative, so a row can land on a weekend for a Mon–Fri shift; the board accepts any date (runsOn feeds only the capacity calendar, apps/erp/app/routes/x+/priority+/people.tsx:365). — rung 1 + 2.

  • D25 — Task 4: tier 01 upserts the applying user's employeeJob (plant, title, department, shift, start date, managerId NULL) with ON CONFLICT (id, companyId) DO UPDATE; the company-wide locationId UPDATE stays for other employees (the wipe re-points everyone to HQ). employeeShift now follows employeeJob.shift (was shifts[0]). Proven on dap2gkh860gg2ccl14sg (0 rows for the user) in a rolled-back wipeFirst apply: row created at "Meridian Machining Plant" with First Shift / Machining, 0 rows after ROLLBACK. — rung 2.

  • D26 — Task 4: HQ planning = one make part + one buy part on Fixed Reorder Quantity at HQ (so both Material Planning screens list a row there) + a 4-week demandProjection for the make part (PlanningData.hq). The tier throws when the item has no HQ itemPlanning row instead of a silent 0-row UPDATE. — rung 1 + 5.

  • D27 — Task 4: FoundationData.workCenterShifts is authored per dataset (every work center ≥ 1 shift, validator) rather than every shift × every work center, so second/weekend shifts staff only the cells that plausibly run them. Shifts are created at the plant (D10). — rung 4.

  • D28 — Task 5: five enforcementRules per dataset — sales error (ship-to country in a list, on SO/invoice lines), sales warn (customer type notIn, on quote/SO lines), two item storage rules (storageUnit.locationId = plant; storageUnit.storageTypeId = a type) and one work-center rule (workCenter.active = true on operationStart). Conditions hold for the seeded data (US customers, active work centers) so a demo is never blocked; ids are authored by name ({storageType}, {customerTypes}, {location}) and resolved in tier 02. @carbon/database cannot import @carbon/utils, so validate.ts mirrors the field registry (fields × rule shape × operators × value kind). REQUIRED_ENFORCEMENT_RULE_FAMILIES = sales, storage:item, storage:workCenter, plus both sales severities. — rung 2 + 5.

  • D29 — Task 5: the configured quote line's values are chosen so every configurationRule yields the method's own number: tier 04 copies the method as authored (get-method runs rule code through importTypeScript, which the seed transaction cannot), so any other value would leave the quote's BoM/BoP disagreeing with its configuration. The validator evaluates each rule body (new Function("params", code)) against the line and pins it. Robotics/precision/motor configurations were changed accordingly (sensor/cert/brake off, 60 mm shaft). — rung 2 + 5.

  • D30 — Task 5: approval rules use approverGroupIds = the Admin employee-type group resolved by employeeType."systemType" = 'Admin' plus defaultApproverId = applying user (the "Needs my approval" window check passes without relying on membership). PO finalize asks for approval only at/above the lowest tier, so each dataset's Needs Approval PO was raised over $5,000 (satellite laminate 4→20, robotics billet 120→1200, precision cylinders 2→18, motor bearings 24→160) and given ref po:needs-approval; the request amount is the purchaseOrders view's orderTotal. — rung 2.

  • D31 — Task 5: supplier-return Issues tab — each dataset gets a new Draft return-to-vendor to its supplier NCR's supplier for the NCR's quarantined item/quantity (*-rtv), linked by nonConformancePurchaseReturnOrderLine, instead of linking an unrelated line of an existing return. closeIssue refuses while a linked return is open, so the validator forbids a Closed NCR on an open return. RMA Issues tab: the existing Closed customer-complaint NCR links its own customer's RMA line. — rung 2 + 4.

  • D32 — Task 5: return Credits tabs get new memos in the Issue Credit shape (helpers/return-credit.ts), only on Completed returns (the app caps credit at received/shipped): the RMA credit is Posted, the supplier-return debit memo Draft. The research's "re-link CR-…-000001" was not followed: that memo is an invoice credit a payment applies (tier 09), so re-purposing it would break its settlement. Posted return memos keep journalId NULL like tier 09's (journals are Task 6). — rung 2.

  • D33 — Task 5: every quote carries createdOffset (validator: required, ≤ 0, after its RFQ, not after its order, before expiry, ≥ 2 in the last 30 days); sales and purchasing RFQs take createdAt from rfqDate, supplier quotes from quotedDate — no new field. — rung 2.

  • D34 — Task 5: "open" for assignees = the dashboards' own status lists (sales+/_index.tsx, purchasing+/_index.tsx); the validator rejects an assignee on a closed document and wants ≥ 2 assigned per quote / sales RFQ / SO / PO / purchasing RFQ (tier 05's Draft lifecycle RFQ counts) / supplier quote. — rung 2.

  • D35 — Task 5: customerBankAccount / supplierBankAccount are tenant data (companyId, PK (id, companyId)), so seeded: 4 + 4 per dataset incl. a EUR supplier account; account numbers and bank codes start DEMO-, SWIFT DEMO… (validator) — nothing resembles a real account. — rung 1 + 5.

  • D36 — Task 5: PricingRuleSpec generalized (type, amount type, customer | customer type | items scope, minQuantity, priority); each dataset adds a Markup rule and a quantity-break rule; the validator requires both rule types and a break. — rung 1.

  • D37 — Task 6: document journals are generated in tier 09 from the seeded rows, not authored — through the edge functions' own pure builders (buildSalesPostingLines, buildPaymentJournal, buildMemoJournal) and copies of post-purchase-invoice / post-receipt / post-shipment's inline line shapes (helpers/posting-journals.ts, DB side helpers/post-documents.ts); the validator re-derives every one from the literals with the same helper. journalLineReference = <journalEntryId>-<group> instead of a nanoid. — rung 2.

  • D38 — Task 6: journals are written whether or not companySettings.accountingEnabled is on (production default off; the posting functions gate on it), so the demo GL agrees with its documents the moment accounting is enabled; the manual journals were already unconditional and get_ar_open_by_customer reads the AR lines with the same totals either way. — rung 5.

  • D39 — Task 6 (widens the plan's list): Posted credit/debit memos (D32 deferred them here) and posted PO receipts / SO shipments are journaled too (DR inventory / CR GR/IR; DR COGS / CR inventory), so GR/IR clears and COGS/Inventory are not $0. Other inventory postings (RMA receipt, returns, job, adjustments, opening stock) still carry no GL; opening stock value sits in the Opening Balance entry. — rung 1 (research gap 11: "COGS and inventory") + 5.

  • D40 — Task 6: the plan's "Purchase Invoice (Inventory or Expense / AP)" is the direct-invoice path; seeded invoices bill PO lines, whose real path is DR GR/IR Clearing / CR AP (accrual for the unreceived share). Tier 05 now sets purchaseInvoiceLine.purchaseOrderLineId (unset before, which reads as a direct invoice that would also create a receipt). Received share = posted receipts of the line on/before the invoice date; the validator requires the invoice to bill at the receipt price (no PPV / layer-adjustment branch). — rung 2.

  • D41 — Task 6 (re-apply contract): posted journals survive the wipe and cannot be deleted, so the wipe now voids every Posted journal linked to a document it deletes — a negated Posted "VOID …" entry today, original left Posted, exactly as post-*-invoice / post-payment void (the tie-out and aging RPCs count status = 'Posted' only). journalEntry is excluded from resetSequences (a rewound counter collides with preserved journals: the user's company dap2gkh860gg2ccl14sg holds JE-2026-09-000001 with its counter at 0), and nextJournalEntryId skips taken ids. Rejected: adopt-and-skip (GL of the previous dataset after a cross-dataset apply) and Reversed-status reversals (tie-out excludes Reversed originals but counts the reversal — tried first; the scratch company keeps that interim run's journals, so its tie-out is off by that run: AR 1307.5 / AP 982.5). Proven in a rolled-back satellite → precision → precision apply: AR and AP tie-out variance 0 after each. — rung 2 + 5.

  • D42 — Task 6: one authored Posted Opening Balance per dataset (JE-SEED-006, offset −242: cash, raw materials, finished goods, plant, accumulated depreciation, term loan, capital, retained earnings); a company's existing Posted Opening Balance is adopted (unique index journal_one_posted_opening_balance_per_company). — rung 2.

  • D43 — Task 6: make parts carried standardCost: 0; now 55 % of their unitSalePrice (BOM roll-ups were implausible, e.g. satellite ADCS 114 k cost vs 95 k price), and createItem writes itemCost.unitCost = standardCost (FIFO valuation and calculateCOGS fall back to it); a change-order revision starts at its predecessor's cost. Validator: every stocked item has standardCost > 0. — rung 5.

  • D44 — Task 6: two more Overdue sales invoices per dataset (issued −75 / due −45, issued −105 / due −75) so receivables aging fills Current, 1–30, 31–60 and 61–90; REQUIRED_AR_AGING_BUCKETS pins all four (stronger than "≥ 3"). A Voided invoice's VOID journal is dated its issue date (the data has no void date). — rung 1.

  • D45 — Task 6: the Draft Receipt / Disbursement are unapplied (no settlements) and name a party with an open posted invoice, which the apply table lists; pre-staged Draft settlements would enter the settlement-vs-status checks for nothing. — rung 5.

  • D46 — Task 6: AR / AP billing addresses = the company address with reserved .example mailboxes, upserted by tier 09 (keyed id = companyId, outside the company wipe); floors counted through COVERAGE_SCOPES id = $1. — rung 2.

  • D47 — Task 7: QualityData.inspections holds 4 lots per dataset: the existing Partial receipt lot (NCR-linked), a Passed and a Pending receipt lot, and a Job Operation lot. No dataset had a second posted untracked receipt line with n ≤ 5 (precision/motor had none), so each gained one "To Invoice" PO whose receipt posted −1/−2 (satellite/robotics: a repeat bare-board delivery; precision: PTFE bushings + replacement HK1512s from Midway; motor: terminal blocks + replacement Nomex from Copperline). Lots of one item share its one Receipt-usage plan (itemInspectionDocumentAssignment PK (itemId, usage)), so the validator requires identical drawing / aql / features and tier 07 creates the document once per item. — rung 2 + 5.

  • D48 — Task 7: the Job Operation lot mirrors getOrCreateJobOperationInspection on the floor job's root Inspection op (plan = its items.inspectionPlans document, lot = operation quantity). Satellite/robotics: In Progress with 1 of n=2 samples, and that op's override moved Waiting → In Progress (no timer); precision/motor: Pending, no samples (their Inspection op follows an outside-processing op still Waiting). Dispositioned job-op lots are rejected (their productionQuantity postings are not authored); "Failed" left the type (it was already rejected). REQUIRED_INSPECTION_STATUSES = Pending/Passed/Partial, REQUIRED_INSPECTION_SOURCES = Receipt/Job Operation. — rung 2 + 5.

  • D49 — Task 7: NonConformanceSpec.items is now required and non-empty; dispositions come from the picker's active subset. A Closed NCR's rows are Use As Is / Rework only (other dispositions make closeIssue post inventory value the seed does not author) and it carries no assignee (close clears it); supplier-escape rows are Return to Supplier (D31's Draft RTV). Two open NCRs per dataset are assigned to the applying user. — rung 2.

  • D50 — Task 7: 3 issue workflows per dataset (supplier escape, customer complaint, incoming hold), each linked from one NCR (3 linked). A linked NCR must carry the workflow's source, required actions (same order) and MRB, which the new-issue form copies; priority stays free (the form lets it be edited). — rung 2.

  • D51 — Task 7: "nonConformanceSupplier in the current month" = the incoming-lot-hold NCR (opened −5/−6) now names its lot's supplier; the validator window is the last 28 days (the supplier KPI's default is the last month; DayOffsets cannot pin a calendar month). The motor seed shows it on 2026-09-18. — rung 5.

  • D52 — Task 7: nonConformanceActionProcess links the supplier escape's In Progress Root Cause Analysis task to a process some BOP operation uses (validator: open task, process in use). — rung 1.

  • D53 — Task 7 maintenance shapes, per dataset: a Scheduled Assigned dispatch planned today 14:00 UTC (same local day at all four US plants — MES Today tab, Open Scheduled tile) from the Daily schedule, which now runs weekends (weekends: false dropped) so "due today" holds on any anchor weekday, next due tomorrow; an In Progress + Down Reactive dispatch (takesWorkCenterOffline, planned end +1) on a plant work center with no In Progress operation and few open ops (satellite TIG Welder Cell 3, robotics Harness Bench 7, precision Wire EDM Cell 3, motor Lamination Press 8) — the scheduler subtracts only actualStart…plannedEnd, and the real motor seed + schedule step placed Lamination Press ops from +1; a Completed Reactive dispatch created on a shift-event day at that event's work center (MTBF); 2 Completed dispatches finished −40…−53 (one Scheduled with a spare part, one Reactive Down); an Open Reactive dispatch + a schedule at the HQ work center. The validator pins each shape (BACKDATED_COMPLETION_WINDOW, MAX_DOWN_OUTAGE_DAYS, event-day match). — rung 1 + 2.

  • D54 — Task 7: maintenanceDispatchItem.unitCost = the item's standard cost (tier throws on 0; validator requires standardCost > 0). Satellite CN-GREASE-001 opening stock 2 → 3 so the back-dated re-grease draws one while the "next kit is short of Krytox" story holds (net 0). — rung 2.

  • D55 — Task 7: workCenterReplacementPart from OpsData.replacementParts — ≥ 3 rows on ≥ 2 work centers, one on a work center with an open dispatch — using existing items (no new items or thumbnails); satellite lists VLV-SOLENOID-LP2, the current revision, not the superseded valve. — rung 5.

  • D56 — Task 7: FoundationData.hqWorkCenter is created at ctx.locationId with no shift, process or operations (kept out of the floor and shift rules); schedules and dispatches now take their work center's location instead of always the Plant; an HQ dispatch may not issue spare parts (the shelves are at the plant). — rung 2 (D10).

  • D57 — Task 7: FoundationData.partners — id = the supplier's supplierLocation (so the supplier needs a supplierContact), ability, hours/week; ≥ 2 per dataset, shown by the partners view. — rung 2.

  • D58 — Task 7: ProcedureSpec.parameters are written on every version row, as creating a version copies them; ≥ 2 procedures per dataset carry them. — rung 2.

  • D59 — Task 8: every B6-remainder shape lives in OpsData / tier 10 (userAttributeCategories, customFields, serialSequences, printJobs, webhook) — print jobs reference receipts, jobs and shelves, which only exist after tiers 01–06. — rung 2.

  • D60 — Task 8 (re-apply contract for preserved tables): userAttributeCategory and customField are in the wipe's PRESERVED_TABLES, and userAttribute / userAttributeValue have no companyId so the wipe never sees them. All four are seeded and ADOPTED on re-apply, then updated to the dataset's values: category by (companyId, name), attribute by (category, name), value ON CONFLICT (userAttributeId, userId), customField ON CONFLICT (table, name, companyId) (the webhook was dropped, D66). tableView is NOT seeded (saved list views are the user's own; no B6 screen needs one). A cross-dataset apply leaves the previous dataset's category and fields, like its journals — rows in these tables may be the user's, so the seed never deletes them. Proven: two consecutive applies in one rolled-back transaction ×4 datasets, and two real robotics seeds — every new row exactly once. (A same-transaction double apply needs HQ's createdAt nudged back first: buildCtx picks HQ by ORDER BY "createdAt", id, and one transaction gives the plant the same now(); separate real applies are unaffected.) — rung 2 + 5.

  • D61 Superseded by D66. — Task 8: the webhook's sync interceptor (sync_webhook_subscription) raises "Not authorized to manage event subscriptions" for the seed's session (no auth.role(), no auth.uid()), even with every event off. Tier 10 raises request.jwt.claim.role to service_role with set_config(…, true) for that one statement and restores the previous value; the interceptor then creates the eventSystemSubscription inactive (dispatch_event_batch only fans out active = TRUE). URL is https on a reserved .example host and active = false always (validator). Rejected: disabling the trigger (DDL), session_replication_role (also skips FKs), an event-less webhook (still raises; the app's validator requires one event). — rung 2 + 5.

  • D62 — Task 8: one public attribute category per dataset with four attributes (Date, List, User, Yes/No) valued for the applying user; the User attribute names the applying user, the only person the seed may name (H3). REQUIRED_USER_ATTRIBUTE_TYPES = Date/List/User. — rung 1.

  • D63 — Task 8: serial sequences continue each dataset's seeded pattern (<CODE>-SN- + 4 digits). next is the last counter issued (get-next-serial-number hands out next + step), so the validator scans every string in the dataset matching prefix + counter + suffix and requires next ≥ its counter; every Serial-tracked item needs exactly one sequence (motor's MTR-4500, with no seeded serials, starts at 0). — rung 2.

  • D64 — Task 8: five print jobs per dataset on foundation.printerRoute: completed/auto Receipt label (the latest posted receipt), completed/manual Job label (a Completed job), completed/manual storage-unit label, failed/auto Job label (3 attempts, delivery timeout) and its queued reprint today at ≤ 08:00 UTC. Content is a small ZPL label built by the tier (a reprint needs content); completedAt = createdAt. Window −20…0 because the cleanup job deletes completed jobs after 30 days. Seeded queued rows are inert: delivery is triggered by an event (print-job-deliver), never polled. — rung 2 + 5.

  • D65 — Task 8: custom field VALUES (the customFields JSON on part / customer / job rows) are not seeded — the plan asks for the three field definitions, which is what Settings › Custom Fields lists; the fields render empty on the entity forms. — rung 1 (plan scope).

  • D66 — Task 8 (supersedes D61; narrows H1): webhook not seeded — seeding it required spoofing the service_role claim to bypass the interceptor's authorization guard; the Webhooks settings screen stays empty by design (developer infrastructure, which the wipe preserves on purpose). The scratch company's one seeded webhook and its subscription were removed. — rung 5 (security).

  • D67 — Task 9 (matrix scope): Reports › saved report views (reportView) are EXCLUDED — user-owned saved views, like tableView, which D60 already leaves unseeded; the Reports hub itself renders its catalog. — rung 2 (D60 precedent).

  • D68 — Task 9 (matrix method): GL checks (tie-out control lines, journals without accountingPeriodId) count only the journals written by the apply under test (journal.createdAt ≥ the plant's createdAt — one apply is one transaction, one now()). The scratch company keeps immutable Posted journals from runs before Task 6 (period-less JE-SEED-00x, the interim run's reversals, D41) that no apply can remove; on a fresh company the unscoped and scoped counts are equal. — rung 5.

  • D69 — Task 9: assembly detail › units (assemblyUnit) EXCLUDED — "plan as one component" overrides are input to the assembler planner (loadPlanUnits, packages/jobs plan-units.ts), whose plan/plan job are already a non-goal (integration). Step materials, step tools and component mappings are seeded instead (D76). — rung 2 + spec Non-goals.

  • D70 — Task 9 (batch detail › events): the Active batch now runs — ProductionData.batch.running (type + UTC start today) puts a batch-tagged open productionEvent on the first member (MES event.tsx shape: jobOperationBatchId set, sliced at completion) and every member operation In Progress; the validator requires member jobs "In Progress", earlier root operations Done, and counts the lead's work center as running and its start in the open-time-card rule. Data: member jobs moved Ready → In Progress; precision's turning ops before the deburr batch are Done; motor's batch moved from the lamination press (Down for maintenance, D53) to the two terminal-box jobs at the CNC turning cell. — rung 2.

  • D71 — Task 9 (Reports › Scrap was EMPTY): tier 09 journals each scrapped lot as post-inventory-adjustment's Scrap does — a Negative Adjmt. Direct Cost costLedger row drawn FIFO like shipments, and an Inventory Adjustment journal (CR inventory / DR accountDefault.scrapAccount, line documentType Scrap, documentId = the ledger row). The wipe now also voids Posted Inventory Adjustment journals whose lines point at item-ledger rows it deletes (D41's re-apply contract; proven: a re-apply nets the scrap account to the current dataset's write-off only). Validator: the scrap journal balances, sits in an open period, and ≥ 1 scrap falls in the report's trailing six months. ScrapReason dimension tags are not written (the report shows the amount under "Unassigned"). Refines D39. — rung 2.

  • D72 — Task 9 (MES operation › issue actions was EMPTY): get_action_tasks_by_item_and_process matches the operation's make-method item, so D52's link to a process could never show on a bought part's issue. Each supplier-escape NCR now also lists the WIP item built from the suspect lot (satellite PROP-001, robotics DRV-J2-MOD, precision MCH-HSG-PUMP, motor COIL-9000; disposition Pending), and satellite's task process moved Welding → Clean Room Assembly (where PROP-001 is built). New validator rule: an open task's process runs on an open root operation of a released job building one of the issue's items. — rung 2 + 4 (containment extends to WIP).

  • D73 — Task 9 (motor MES assembly 3D was FILTERED-EMPTY): motor's only MTR-9000 job has its Assembly operation Done, so a make-to-stock "service-pool" MTR-9000 job (Ready, due +19, priority 15) was added; validator: some released job of the instruction's item has its Assembly operation still open. — rung 2.

  • D74 — Task 9 (job › Quantities tab): recently completed jobs record a Production quantity for the full operation quantity on every logged operation, as the operator does at the end of a run (the interceptor then fills jobOperation.quantityComplete, which read 0 on Done operations). — rung 2.

  • D75 — Task 9 (item › Purchasing › batch properties was EMPTY): ItemsData.batchProperties — per-lot attributes (heat number, date code, list grades, …) on every Batch-tracked item; validator: Batch-tracked item, unique label, listOptions exactly for list (≥ 2), every Batch-tracked item has one. — rung 1.

  • D76 — Task 9 (assembly detail step panels / BOM tree were EMPTY): AssemblyStepSpec.materials / tools and AssemblySpec.componentMappings (leaf geometryHash of the bundled graph → a component of the assembly item's BOM, confidence high). The bundled models are stand-ins (a radial engine for SAT-1000, …), so mappings pair each item with the model part that plays it in the build sequence. Validator: materials on the item's BOM, tools are Tool items, hashes are leaf hashes of the graph, ≥ 2 materials, ≥ 1 tool, ≥ 2 mappings. — rung 2 + 5.

  • D77 — Task 11: the demo-data docs page quotes both wipe refusals verbatim (with N for the count) in a reader-visible Callout — the review card shows the raw job error — and again as <AgentContext> troubleshooting entries; it states that only MRP has a 3-hourly backstop (the cron runs runMrp only, scheduled/mrp.ts), not scheduling. — rung 2.

  • D78 — Task 11: generate:agent-kb writes manifest.json unformatted (660 lines of array-wrapping churn against HEAD); biome format --write on it restores the committed shape, leaving only the demo-data entry changed. — rung 2 (the committed manifest is biome-formatted).

  • D79 — R1 (review #8/#12/#13): one method copier, helpers/method-copy.ts (copyMethodToJob / copyMethodToQuoteLine / copyMethodToMethod), replaces job-method.ts, quote-method.ts and tier 08's cloneMethodRows. Operation rows copy every column the target shares with methodOperation (via sharedColumns), so workInstruction / procedure / inspection / assembly links cannot drift from a migration. — rung 2 (get-method's own ...operation spread).

  • D80 — R1: per-operation children follow get-method exactly — tools always; method parameters only without a procedure; a JOB operation with a procedure takes the procedure's steps, parameters and content (as workInstruction); quotes and method→method copies take nothing from the procedure. Outside rates: named supplier process, else the process's supplier-process average, else 0 (getRatesFromSupplierProcesses); a quote keeps the method's own operationMinimumCost (get-method overrides it after the spread). — rung 2.

  • D81 — R1: kept on purpose where get-method differs: job operationUnitCost is still copied (itemToJobMakeMethod copies it, itemToJob does not — get-method is inconsistent with itself); work-center rates stay by-id (no process-average fallback); no assembly-instruction step expansion and no methodOperationStep copy (no dataset authors either — adding them would change jobOperationStep/Tool counts beyond R1's scope); materials keep their existing column set. A missing root/child make method, an absent interceptor row, a BOM cycle, an unmapped material operation or a cross-tenant procedure now THROW (the job copy used to skip silently). — rung 4 (smallest change that closes the reviewed drift).

  • D82 — R1 (#13): assembly moved from ProductionData to ItemsData and seedAssembly from tier 06 to tier 02, where it links the Assembly methodOperation before release; tier 06 no longer mutates a released method, and quote operations now carry the link. Validator messages read items.assembly; its job-parameter floor now counts procedure parameters for procedure operations. — rung 2 (review M8's own restructure).

  • D83 — R2 (review #2): datasets/types.ts is gone, with no barrel — every importer names the precise module (types/<slice>.ts, types/primitives.ts, types/dataset.ts, types/engine.ts, context.ts). A barrel would keep two ways to import the same type; the rewrite was mechanical (84 sites) and each data file imports exactly its own slice. Package entry points are unchanged: datasets/index.ts still re-exports Ctx / Dataset / DatasetKey / resolveCompanyTimeZone, and seed-workflows keeps its value exports (no consumer imported its types). — rung 4 (smallest consistent shape).

  • D84 — R2: the Ctx / SeedRefs / ItemRef / Tier types live in types/engine.ts, not context.ts: sql.ts needs Ctx and context.ts needs sql.ts, so a Ctx in context.ts would keep the type-level cycle the review flagged. Runtime ctx construction (emptyRefs, resolveCompany, resolveCompanyTimeZone, buildCtx, Resolved) is context.ts. Spec types that lived in implementation files moved with their doc comments: ItemSpec / MaterialClassificationSpec / MethodType / OperationType from helpers/items.ts and ItemType to types/items.ts; SeedWorkflow / Node / Edge from tiers/workflow-definitions.ts to types/workflows.ts; DayOffset from dates.ts and InstantSpec (shared by ops + workflows) to types/primitives.ts. Declarations moved verbatim except the "Slice shapes" banner. madge --circular on src/datasets: 10 cycles before, 0 after. — rung 2 (review B1's own restructure).

  • D85 — R3 (review #1): datasets/validate.ts (6,742 lines) is datasets/validate/: dataset-index.ts builds every projection once (named ref sets behind need(kind, where, id), document refs, the on-hand ledger, the tracked-lot registry, BOM walks, floor state), and 22 rules/<slice>.ts modules only read it (largest 546 lines). The four cross-slice registries that forced the slice order — registerRef, addOnHand, trackedEntityQty / receiptLotIds, validateFloor's returned active set — are projections now; RULES in index.ts is report order only. Message strings were copied by line range, not retyped; need() replaced an inline check only where the message is exactly unknown <label> "<id>". Public API: validateDataset + MIN_JOBS; REQUIRED_* moved intact to validate/required.ts for R4; every other constant is module-private. — rung 2 (review A-B1's own restructure).

  • D86 — R3: kept exact, not simplified: a document ref is visible to a reader only if registered before it in tier order (an RMA / job / NCR sees refs up to its own registration, risks the whole quality slice, workflow runs everything through accounting — document-refs.ts seenBy), because that is what ctx.refs.documents holds when the tier resolves it; coarse per-slice phases would have accepted forward refs the old code rejected. One deliberate change: "duplicate document ref" violations are now all listed at the start of the sales slice (the old code listed each where it was registered). Proof: the 116 validator calls of the old test file give identical ordered arrays; 12,008 seeded random mutations old vs new — 11,984 identical, 9 differ only in that ordering (all duplicate refs), 15 are type-invalid inputs (a required array deleted) on which both versions throw; 5,248 targeted ref-visibility probes identical. — rung 2.

  • D87 — R3 (review #3): validate.test.ts → validate/validate.test.ts, one CASES table ([name, dataset, mutate in place, expected], expected may be a list or a function of the mutated dataset) run by it.each on cloneDataset, a recursive copy that keeps functions (structuredClone rejects workflows.build); the every-dataset test also validates each clone. 108 negative cases before and after; each builds a byte-identical mutated dataset (JSON sha1) to its original test and gets the identical violation array. — rung 2 (review A-M6's own shape).

  • D88 — R4 (review #4): the ~55 REQUIRED_* arrays are one COVERAGE table in validate/required.ts, each entry { values, missing }. An enum-backed set is enumValues(<generated enum>, { <value>: "<reason>" }) over Constants.public.Enums (the generated DB types), so every exclusion carries its reason, a renamed enum value breaks typecheck, and a new enum value fails every dataset until one exhibits it or it is excluded. Nine sets whose columns are free text stay explicit (AR aging buckets, close-task / workflow-run / print-job statuses, print origins, user-attribute types, custom fields as table|dataType, rule shapes, sales-rule severities). One loop, checkCoverage(fail, exhibited): rule modules still collect what they exhibit while they walk and call it where their old loop sat, so the cross-slice report order D86 proved is unchanged (one end-of-run pass would have reordered it). 28 loops and the per-slice mini-registries are gone. Proof: 6,816 old-vs-new validator runs (1,500 random mutations per dataset plus every string key blanked dataset-wide): every coverage message is byte-identical; within one set the order is now the enum's (8 order-only diffs); the one changed text is "no Active training covers every trainingQuestionType (…)", which now lists the types in enum order. — rung 2 (review A-M2's restructure; per-module call sites chosen to keep D86's order).

  • D89 — R4 (review #6): one GL sign rule: signedNet(lines) in helpers/posting-journals.ts = round(Σ debit(accountTypeFromClass(class), amount)) over lib/utils.ts's canonical helpers; postingImbalance and the validator's journalImbalance both use it, and both DEBIT_CLASSES copies are gone. The validator's manual-journal tolerance is EPSILON (was 0.01): stricter than the app's manual-journal 0.001 (accounting.service.ts JOURNAL_BALANCE_TOLERANCE) because authored amounts are exact, so any residual is an authoring error (one comment says so). cents() (Math.round) is precision.round(x, USD_DECIMALS), with the decimals read from the bootstrap USD row rather than a literal; messages that printed cents / 100 print the rounded value. A type-invalid accountClass now throws Unknown GL account class instead of reporting an imbalance. — rung 2.

  • D90 — R4 (review #7): the pure verdict core (parseSpecNumber, valuateMeasurement, deriveSampleStatus, computeLotStatus) is supabase/functions/shared/inspection-verdict.ts (no kysely, no I/O). quality.ts imports it and re-exports valuateMeasurement, so @carbon/database/quality is unchanged for ERP/MES; no new package subpath, because nothing else needs one (sampling-engine's re-export exists for app consumers). helpers/inspection.ts is two thin adapters over it (a seeded feature is a numeric Measurement), and dead openLotStatus is deleted. Drift fixed to the engine's behaviour: a lot with no features never passes a sample, an unparseable nominal gives Pending rather than judging against 0, and a missing reading value is Pending rather than Failed. No seeded value changes: all 60 seeded readings valuate identically and every dataset still validates. Proof of the engine: quality.server.test.ts (6) plus the new src/inspection-verdict.test.ts. — rung 2 (review A-M4's restructure).

  • D91 — R4 (review #9): bootstrapIdByName(ctx, table, name) is the one lookup of a company-scoped row by name. It replaced scrapReasonIdByName (tier 06), taxonomyId (tier 01, which also interpolated the table name without quote()), failureModeId (tier 10) and the pterm: / cstatus: / rreason: / mat*: preloads. helpers/items.ts resolves a material classification through it too. userAttributeCategory's adopt-by-name stays as it is, because it is an adopt-or-insert (ORDER BY "createdAt") and not a lookup. Its error now reads Seed: no <table> named "<name>". — rung 2 (review B-M4's restructure).

  • D92 — R4 (reviews #10, #11): both drift tests live on the canonical side, because @carbon/database cannot import either package without a cycle. RULE_FIELDS moved to validate/rule-fields.ts, exported as @carbon/database/dataset-rule-fields (type-only imports, so it loads nothing at runtime). packages/utils/src/field-registry.test.ts asserts that every field × shape exists in the builder's list for that shape (getFieldsForSalesRules / getFieldsForTargetType) and every operator is in its availableOperators (15 cases). packages/ee/src/workflows/seed-workflows.test.ts asserts that each EVENT_SOURCES entry equals the catalog event's match (table + operation, or null for a moment) and that every seeded trigger event has a source. Both were red-checked by a temporary edit, then restored. utils and ee already depended on @carbon/database, so no new package edge. — rung 3 (the step's stated fallback).

  • D93 — R4 (review #21): helpers/memo.ts insertMemo is the one memo writer (tier 09's invoice memos and seedReturnCredit). It stamps post-memo's postingDate, 16:00 postedAt and postedBy on a Posted memo, and resolves post-memo's reason account (return order's, else the party side's discount account); a missing default now throws there instead of surfacing later in postMemos. The false "no journal (accounting disabled)" comment is gone. seedReturnCredit now follows createSalesReturnOrderCredit / createPurchaseReturnOrderCredit: it reads the return order's currencyCode / exchangeRate and each line's unitPrice / restockFeePercent back from the rows tier 04/05 wrote, and sets restockFee = gross × percent, amount = round(Σ gross − fee, the currency's decimalPlaces ?? 2). The tiers no longer pass line prices. No seeded value changes: the returns are USD with a 0% fee, and all 8 credits' amounts are already exact. — rung 2.

Open Questions (audit trail — all resolved autonomously)

  • Run MRP inside the seed? — Autonomous: no; post-commit (H2).
  • Fake employees? — Autonomous: no (H3).
  • IC partners / card transactions: preserve or refuse? — Autonomous: refuse (H4).
  • Seed GL for posted docs? — Autonomous: yes (H5).
  • How does the dev CLI reach @carbon/planning? — Autonomous: spawn a jobs-package script (D8).
  • Cover engine output in floors? — Autonomous: no; screen matrix (D9).

Changelog

  • 2026-09-23 — Spec written from five screen audits; approved autonomously.
  • 2026-09-23 — Implemented autonomously (D12–D78; plan Tasks 1–9 and 11 ticked, Task 10 full-verification box still open when this entry was written): wipe refusals + slide pre-delete + journal voiding, post-commit planDemoCompany for the template job and dev CLI (--skip-plan), B1–B6 data and tier shapes across all four datasets, validator/coverage floors (213 → 255 tables), screen matrix FAIL 0 ×4 (.ai/runs/2026-09-23-screen-matrix-*.txt), docs + agent KB. Uncommitted — awaiting the user's commit.
  • 2026-09-23 — Task 10 verified by the orchestrator: typecheck 0, 119/119 tests, db:check ✓×4, @carbon/jobs typecheck 2/2, biome 0 errors; real re-apply robotics → satellite (MRP ✓, Schedule ✓, 0 robotics items left); screen matrix on the final satellite seed FAIL 0 (204 PASS, 16 EXCLUDED); wipe probes re-run on final code (satellite + motor); pre-commit drill blocked; baselines refreshed; structural sums from a fresh rolled-back company (0 unbalanced journals). Evidence: .ai/runs/2026-09-23-screen-coverage-verification.txt.