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.
MRP v2: Live Planned-Order MRP — Generation, Cascade, Capacity & Simulation
Status: phased — Phase 1 implemented (PR #1601); Phases 2+ designed, not started Author: Brad Barbin (with Claude) Date: 2026-08-22 (re-scoped into phases 2026-09-08) Scope: now phased. Originally written as a single "game-changer v1" that shipped everything at once. As of 2026-09-08 (Brad) it is re-scoped into delivery phases so the highest-value, lowest-complexity slice ships first:
- Phase 1 — Planning Action Messages & Buyer/Planner Assignment (ships first; fully specified in §P1 below). MRP stops emitting only "Order": it emits a full set of assignable, dismissible planning actions —
Order,Make,Expedite,Defer,Cancel,Increase,Decrease— persisted in a focusedplanningActiontable and routed to a responsible buyer/planner via an inheritance ladder. Built on the current per-item netting; no planned-order cascade, no Firm lifecycle, no capacity/simulation. This is the 80/20.- Phases 2+ — the full planned-order vision (everything from "## TLDR" / "Proposed Solution" onward, now DEFERRED). The multi-level planned-order cascade + lot-sizing, the Planned→Firm→Released lifecycle, pegging, continuous regen, rough-cut capacity, what-if/CTP, the self-explaining plan, programmable release, and the calm-by-default layer (§9). All of that design is preserved below as the phase-2+ record; Phase 1's
planningActiontable is forward-compatible with it (see §P1.9).Read §P1 first for what ships now. Everything after "## TLDR" describes Phases 2+ unless §P1 cites it.
§P1 — Phase 1: Planning Action Messages & Buyer/Planner Assignment (ships first)
This is Phase 1 — the slice that ships now. Resolved with Brad on 2026-09-08 (run record:
.ai/runs/2026-09-08-mrp-planning-actions.md; research:.ai/research/mrp-planning-actions.md— SAP, Dynamics 365 SCM + Business Central, NetSuite, Epicor, Infor SyteLine/LN). Everything from "## TLDR" onward is the Phase 2+ vision, deferred.
P1.0 TLDR
Today MRP emits exactly one suggestion — Order — computed live in SQL
(calculate_quantity_to_order) and thrown away on every page load. Phase 1 makes MRP
emit the full set of planning actions every ERP has — Order, Make, Expedite,
Defer, Cancel, Increase, Decrease — persists them in a focused
planningAction table, and routes each to a responsible buyer/planner resolved
through an inheritance ladder (item → item group → location → company). A buyer opens
the planning page filtered to "my actions" and works a queue: one-click apply on
uncommitted supply, review-on-document for anything already sent to a supplier.
Phase 1 deliberately builds on the current per-item netting. It does not include the multi-level planned-order cascade, the Planned→Firm→Released lifecycle, rough-cut capacity, or what-if/CTP — those are Phases 2+ (the rest of this spec). This is the 80/20: the whole user-visible outcome (a full, assignable action worklist) at a fraction of the full-vision build.
P1.1 Scope — what Phase 1 does and does not do
Does:
- Emit and persist the seven
planningActionTypevalues as assignable, dismissible rows, refreshed each MRP run (diff-write). - Compute change actions (Expedite/Defer/Cancel/Increase/Decrease) by comparing real open POs/jobs against net requirements — the SAP "reschedule/cancel on a firmed receipt" model.
- Resolve a
responsibleEmployeeper action via the inheritance ladder, stamp it as the row's assignee, and let a lead reassign per row (bulk-capable). - Let a buyer act on a message: apply directly on uncommitted supply, navigate to the document on committed supply.
- Gate reschedule noise with a single company tolerance.
Does NOT (deferred to Phases 2+):
- The multi-level planned-order cascade (a parent's reorder need generating child demand before a job exists — the original MRP-v2 problem statement). Phase 1 Order/Make actions come from the current per-item reorder + demand netting, unchanged.
- The Planned → Firm → Released lifecycle, pegging tables,
planningRun/planningState, continuous event-driven regen, rough-cut capacity, what-if/CTP, programmable release, and the §9 calm-by-default layer. - A dedicated advisory/warning channel (below-safety-stock alerts, excess-stock,
master-data-broken). Phase 1 is actionable-only; urgency is a flag, conditions live
in each action's
reason/triggerValues.
P1.2 Data model
One new table, two new enums, four new responsibleEmployee columns, one tolerance
column. Standard Carbon conventions (composite PK, id('…') default, audit columns, four
RLS policies, companyId scoping; RLS uses get_companies_with_employee_role() /
get_companies_with_employee_permission()).
CREATE TYPE "planningActionType" AS ENUM
('Order', 'Make', 'Expedite', 'Defer', 'Cancel', 'Increase', 'Decrease');
CREATE TYPE "planningActionStatus" AS ENUM ('Open', 'Dismissed', 'Actioned');
CREATE TABLE "planningAction" (
"id" TEXT NOT NULL DEFAULT id('pla'),
"companyId" TEXT NOT NULL,
"itemId" TEXT NOT NULL,
"locationId" TEXT NOT NULL,
"periodId" TEXT NOT NULL, -- weekly bucket (get-or-create)
"type" "planningActionType" NOT NULL,
"status" "planningActionStatus" NOT NULL DEFAULT 'Open',
"suggestedQuantity" NUMERIC NOT NULL, -- lot-sized order qty (Order/Make) or target qty (Increase/Decrease)
"suggestedDate" DATE NOT NULL, -- recommended due date for the action
"isASAP" BOOLEAN NOT NULL DEFAULT false, -- urgency: release/need date already in the past
-- Target of a CHANGE action (exactly one set; both NULL for Order/Make):
"purchaseOrderLineId" TEXT,
"jobId" TEXT,
"requiresManualAction" BOOLEAN NOT NULL DEFAULT false, -- target committed (sent PO / released job) → "Review on document"
-- Suggestion attribution (the "why"; computed today, discarded today):
"supplierId" TEXT, -- resolved/preferred supplier for an Order
"policyName" TEXT,
"reason" TEXT,
"triggerValues" JSONB, -- {projectedStock, safetyStock, reorderPoint, reorderQuantity, lotSize, leadTime}
-- Assignment:
"assignee" TEXT REFERENCES "user"("id"), -- resolved responsibleEmployee snapshot; overridable
"assigneeOverridden" BOOLEAN NOT NULL DEFAULT false, -- true once a human reassigns; regen won't re-resolve it
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
-- + CHECK: purchaseOrderLineId/jobId both NULL for Order|Make; exactly one set otherwise
);
CREATE INDEX "planningAction_companyId_idx" ON "planningAction" ("companyId");
CREATE INDEX "planningAction_assignee_idx" ON "planningAction" ("companyId", "assignee");
CREATE INDEX "planningAction_item_loc_idx" ON "planningAction" ("companyId", "itemId", "locationId");
CREATE INDEX "planningAction_status_idx" ON "planningAction" ("companyId", "status");
-- Deterministic regen identity (diff-write): one non-terminal action per
-- (item, location, type, period, target document)
CREATE UNIQUE INDEX "planningAction_natural_key_idx" ON "planningAction"
("companyId", "itemId", "locationId", "type", "periodId",
COALESCE("purchaseOrderLineId", "jobId", ''))
WHERE "status" <> 'Actioned';
Ownership ladder (tree: company default → location → location-specific item group → item) + the tolerance scalar:
ALTER TABLE "itemPlanning" ADD COLUMN "responsibleEmployee" TEXT REFERENCES "user"("id"); -- per item+location (most specific leaf)
ALTER TABLE "location" ADD COLUMN "responsibleEmployee" TEXT REFERENCES "user"("id"); -- per location
ALTER TABLE "companySettings" ADD COLUMN "defaultResponsibleEmployee" TEXT REFERENCES "user"("id"); -- company default (all)
ALTER TABLE "companySettings" ADD COLUMN "rescheduleToleranceDays" INTEGER NOT NULL DEFAULT 7
CHECK ("rescheduleToleranceDays" >= 0); -- negative would make every gap actionable
-- The "location > item group" tier. Item-group ownership is LOCATION-SPECIFIC — the
-- same group can have a different owner at each location — so it is NOT a column on
-- itemPostingGroup; it is a sparse per-(location, group) assignment table (the printer
-- AssignmentsCard tree: location default → per-work-center override, here location →
-- per-item-group override). Rows exist only for configured cells.
CREATE TABLE "itemPostingGroupResponsibility" (
"id" TEXT NOT NULL DEFAULT id('pgr'),
"companyId" TEXT NOT NULL,
"locationId" TEXT NOT NULL,
"itemPostingGroupId" TEXT NOT NULL,
"responsibleEmployee" TEXT REFERENCES "user"("id"),
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
-- Composite-FK prerequisites (verified 2026-09-11): "location" already has
-- UNIQUE ("id","companyId") (20260905132037_job-operation-batching.sql), but
-- "itemPostingGroup"'s PK is ("id") ALONE (parts.sql:69) — the migration must first
-- add an idempotent UNIQUE ("id","companyId") on itemPostingGroup or this FK fails.
CONSTRAINT "itemPostingGroupResponsibility_location_fkey"
FOREIGN KEY ("locationId", "companyId") REFERENCES "location"("id", "companyId") ON DELETE CASCADE,
CONSTRAINT "itemPostingGroupResponsibility_group_fkey"
FOREIGN KEY ("itemPostingGroupId", "companyId") REFERENCES "itemPostingGroup"("id", "companyId") ON DELETE CASCADE,
CONSTRAINT "itemPostingGroupResponsibility_unique" UNIQUE ("companyId", "locationId", "itemPostingGroupId")
);
itemPostingGroupResponsibility has RLS explicitly enabled
(ALTER TABLE ... ENABLE ROW LEVEL SECURITY; — policies are inert without it) plus the
four standard policies (SELECT via get_companies_with_employee_role(); writes via
settings_update, since it is configured on the settings screen).
planningAction gets the four standard RLS policies — SELECT via
get_companies_with_employee_role(), writes via production_*/purchasing_* (mirroring
the two planning pages). Any view surfacing itemPostingGroup/location/itemPlanning
is DROP/recreated with SELECT * to pick up the new column (per the view-redefinition
convention).
P1.3 Ownership resolution (the inheritance ladder)
responsibleEmployee for an item+location resolves most-specific first. Drawn as a
tree it is all → location → item group, with a per-item leaf override on top (and the
per-message assignee override on top of that):
itemPlanning.responsibleEmployee -- this item at this location (leaf override)
?? itemPostingGroupResponsibility[location, group] -- the item's group AT THIS LOCATION
?? location.responsibleEmployee -- this location
?? companySettings.defaultResponsibleEmployee -- company default (all, the root)
?? NULL -- Unassigned
itemPostingGroupIdlives onitemCost(notitem), so the resolver joinsitem → itemCost.itemPostingGroupId, then looks upitemPostingGroupResponsibilityby(companyId, locationId, itemPostingGroupId)— the item-group tier is location-specific (same group, potentially different owner per location).- It is a hierarchical inheritance tree, not a free classification matrix. Although
the item-group tier is keyed by
(location, group), it is the exact shape of the printerAssignmentsCardtree (location default → per-work-center override): a sparse set of configured cells that each fall back up the tree, resolved by one shared function. This is deliberately different from the removed N×M posting-group matrix (20260229000000_drop-posting-groups.sql), which was an independent customer-type × item-group cross-product with no inheritance. Here every tier inherits from the tier above and returns the first non-null. - The engine stamps the resolved value onto each
planningAction.assigneeat write time. A human reassignment (P1.7) setsassigneeOverridden = true; subsequent regens leave that row's assignee alone.
One unified responsibleEmployee covers both buy and make — the item's
replenishmentSystem decides which worklist (purchasing vs production) an action shows
on; the owner is the same person either way. Configured in a new settings screen cloned
from the printer AssignmentsCard (P1.7).
P1.4 Engine changes (runMrp)
runMrp already computes period-phased net requirements per (item, location). Phase 1
adds a generation step that diff-writes planningAction rows in its own atomic
Kysely transaction, immediately after the Phase-7 transaction commits (it reads the
planning RPCs, which see only committed data, so it cannot live inside Phase-7 itself).
A generation failure propagates to the caller — runMrp reports the run failed
rather than succeeding with stale actions; the already-committed forecasts are correct
and the actions self-heal on the next successful run. For each (item, location, period):
- No open supply covers the net requirement →
Order(Buy item) orMake(Make item).suggestedQuantity= the lot-sized reorder quantity (the same number the grid shows today, via the shared sizing function — P1.8 "sizing home");suggestedDate= the need date;supplierId= preferred supplier for Buy. - An open PO-line/job covers it on the wrong date, gap strictly greater than
rescheduleToleranceDays(a gap ≤ tolerance is suppressed; the same>comparison is used everywhere — engine, tests, acceptance) →Expedite(needs to be earlier) orDefer(later).suggestedDate= the recommended new date; the target ref points at the open document. - An open order's quantity no longer matches the requirement (after lot/order-multiple
rounding) →
IncreaseorDecrease. - An open order has no remaining requirement →
Cancel. - One action per target document. Date and quantity rules can both match the same open PO-line/job; the engine emits only the single highest-priority action per target: Cancel (no remaining requirement — mutually exclusive with the rest) → Expedite/Defer (date) → Increase/Decrease (quantity). A target needing both a date and a qty change gets the date action; the qty change surfaces on a later run once the date is fixed (SAP folds qty into reschedule the same way). This is MRP-v2's "single highest-priority message on the line" rule applied to Phase 1.
Each row carries the resolved assignee (P1.3), the reason/policyName/triggerValues
attribution (computed by the sizing logic, discarded today), the isASAP urgency flag
(start/need date already past), and requiresManualAction (target already committed —
P1.5).
Diff-write, never delete-and-recreate (assignment + dismissal state must survive a
run). On the natural key (item, location, type, period, target document):
- a matched Open row is updated in place (suggested qty/date/reason refreshed;
assigneere-resolved only whenassigneeOverridden = false); - a matched Dismissed row stays dismissed unless the suggestion changed materially
(qty beyond rounding, or date beyond
rescheduleToleranceDays), in which case it re-opens; - an unmatched Open or Dismissed row whose need has vanished is deleted (retired) — a dismissal suppresses a persisting need; once the need disappears the row must not linger, or its natural key would block a fresh Open row if the same need returns later. A returning need is a new situation and re-surfaces as a new Open row;
- Actioned rows are terminal and ignored — if the same need recurs, a fresh row is created.
Two consecutive unchanged runs are therefore idempotent (no churn of assignments or
dismissals). The current unconditional supplyForecast delete stays as-is for now
(Phase 2 removes it); the live quantityToOrder SQL suggestion is superseded on the
suggestion path (P1.6) while the weekly projection columns (week1…weekN) stay live.
P1.5 Acting on a message
The planningAction row is a recommendation; the existing owning subsystem executes
it. No new execution engine.
| Type | On apply |
|---|---|
| Order | Reuse the existing planning.update "order" path (group by supplier+period, find-or-create a Planned PO, merge lines); stamp the assignee onto the PO. |
| Make | Reuse the existing production planning.update job-creation path. |
| Expedite / Defer | Uncommitted target — PO line: update requiredDate. Job: update the job's demand target via updateJob({ dueDate: suggestedDate }), then notifyScheduleInputsChanged(companyId, "reorder", reason, jobId) so the scheduler re-plans. Never updateJobOperationDueDate (that pins an operation need-by and sets manuallyScheduled — a different input) and never direct jobOperation date writes. |
| Increase / Decrease | Uncommitted — update purchaseQuantity (PO) or the job qty via existing services. |
| Cancel | Uncommitted — cancel/remove the PO line, or cancel the job, via existing services. |
Commitment gate. A change action's target may be committed — a PO already sent to
the supplier, or a job already released to the floor. Then the action is flagged
requiresManualAction = true: the message still surfaces the recommendation ("this sent
PO should pull in to Sep 12") but does not silently edit the document. Acting on it
navigates the buyer to the PO/job to handle through the existing workflow (reopen +
renegotiate + notify supplier); the UI shows "Review on PO/Job" instead of one-click
apply. An automated reopen + supplier-notification / change-order flow is explicitly
deferred — a separate feature.
Apply binds to the persisted action (IDOR guard). The apply route receives only a
planningActionId. The server loads the planningAction by id + companyId, requires
status = 'Open', and executes from the row's stored type, target reference, and
proposal values — never from client-supplied targets or quantities. Mismatched or
non-Open requests are rejected; every target lookup and mutation is companyId-scoped.
Applied → the row flips to Actioned (next run won't recreate it). A buyer may also
Dismiss (won't recur until the underlying need changes materially). Both are
available in bulk.
Commitment-gate facts (verified): "sent to supplier" =
isPurchaseOrderLocked(status)(PURCHASE_ORDER_LOCKED_STATUSES= To Receive / To Receive and Invoice / To Invoice / Completed / Closed,purchasing.models.ts). Do not gate onorderDate—insertPurchaseOrderdefaults it to today, so it is set even on freshly planned POs and would flag every onerequiresManualAction. Jobs are committed at statusReadyor later (Ready/In Progress/Paused);Draft/Plannedare uncommitted. A reopen path exists (reopenPurchaseOrderAsRevision) for the manual flow.
P1.6 Noise gating
A single company-level rescheduleToleranceDays (default 7 = one weekly bucket)
gates Expedite/Defer. Canonical boundary: a message fires only when the date gap is
strictly greater than the tolerance (gap > rescheduleToleranceDays); a gap ≤ tolerance
is suppressed. The same comparison is used in the engine, the tests, and the acceptance
criteria — at exactly 7 days, nothing fires. The column carries a CHECK (>= 0) (a
negative value would make every gap actionable) and the settings mutation validates
0–365.
Because Carbon already buckets planning by week, sub-week noise is invisible anyway. No
separate quantity dampener in Phase 1 — Carbon's existing orderMultiple/lotSize/
min-max-OQ rounding absorbs trivial qty deltas; a dampener is a later add if churn
appears. (In/out split and per-item tolerance overrides are later refinements.)
P1.7 UI
Extend the two existing planning pages — no new module or page. Files:
apps/erp/app/routes/x+/{purchasing,production}+/planning.tsx,
apps/erp/app/modules/{purchasing,production}/ui/Planning/.
- Planning pages: keep the live 48-week projection grid; the suggestion/action column
now reads persisted
planningActionrows. New columns: action type, suggested date/qty, reason (fromtriggerValues), assignee, status, urgency flag. Each row's primary control is Apply (one-click; bulk via the existing multi-select) — exceptrequiresManualActionrows, which show "Review on PO/Job" and navigate. - Filters: assignee (default "my actions" = current user — the buyer's cockpit), plus action type and status. Bulk assign and bulk accept/dismiss via the existing multi-select.
- Assignment control: the existing
Assigneecomponent per row, pre-filled from the resolvedresponsibleEmployee, reassignable inline (setsassigneeOverridden). - Settings — one new screen cloned from the printer
AssignmentsCard(settings/ui/Printing/): a company-default row, a list of all locations, and a list of all item groups, each with anEmployeepicker and an inherited-placeholder ("inherits {default}") when unset. Per-item override lives on the item's existing Planning tab (responsibleEmployee). - Deferred: a unified cross-module "all my actions" cockpit (each page filtered to the user already is their queue).
Suggestions are as-fresh-as-the-last-run (3-hour cron + the existing manual "Recalculate" button), not recomputed per page load — the correct ERP model and the prerequisite for persistence/assignment.
P1.8 Phase 1 Design Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Persistence | New focused planningAction table (not the Phase-2 plannedOrder lifecycle) |
Assignment + dismissal require persistence; the full planned-order lifecycle is deferred. All action types in one table so the worklist is uniform. |
| Firm lifecycle | None in v1 | Carbon converts a suggestion straight into a real Planned PO/job; no unfirmed tier needed for action messages. Planned→Firm→Released is Phase 2. |
| Action enum | Order|Make|Expedite|Defer|Cancel|Increase|Decrease (directional, user-facing) |
Direction-in-the-type reads best for a buyer (SAP/D365/Epicor); Increase/Decrease included per Brad. Advisory/warning types excluded (actionable-only). |
| Change-action source | Real open POs/jobs vs net requirement | SAP's reschedule/cancel-on-firmed-receipt model; needs no planned-order layer. |
| Assignment | Unified responsibleEmployee inheritance tree all → location → location-specific item group → item, + per-row assignee override |
Auto-routes on day one (SAP MRP-controller / Epicor Buyer-ID). The item-group tier is location-specific (sparse itemPostingGroupResponsibility table), mirroring the printer AssignmentsCard tree — an inheritance hierarchy, not the removed N×M classification matrix. |
| Acting | Recommendation; existing subsystem executes. Apply on uncommitted supply; navigate on committed | Committed = external commitment (sent PO / released job); silent edits there are wrong. Change-order/notify automation deferred. |
| Noise gating | One company rescheduleToleranceDays (7), no qty dampener |
80/20 — date reschedules are the dominant noise; qty deltas already partly rounded. |
| Suggestion source of truth | Persisted planningAction; keep live projection columns |
Grid and worklist can't disagree; refreshes per run (assignment prerequisite). |
| Reorder-sizing home | Pure TS function shared by engine + client (four existing policies) | The engine must produce the Order/Make quantity the grid shows; today the logic is duplicated in SQL (calculate_quantity_to_order) + client (calculateOrders). Aligns with the Phase-2 computePlannedOrderQuantity decision; POQ not required for Phase 1. |
| UI | Extend the two existing planning pages + one printer-style settings screen | Copy precedent; no new module. |
P1.9 Relationship to the Phase 2 planned-order model
Phase 1 is forward-compatible with the plannedOrder design below:
- Phase 2's
plannedOrder.exceptionType(Release/Expedite/DeExpedite/Cancel/…) is the same action vocabulary; Phase 1'splanningActionTypeuses user-facing names for the same concepts (Order/Make≈Release+ planned-order generation;Defer≈DeExpedite). - When Phase 2 lands the cascade + lifecycle, a
planningActioncan gain an optionalplannedOrderIdreference (an Order/Make action becomes "release this planned order"), while change actions keep targeting real open documents. The assignment ladder, worklist, filters, and acting-on-messages built in Phase 1 are reused unchanged. - Nothing in Phase 1 has to be torn out for Phase 2.
P1.10 Phase 1 Acceptance Criteria
- An MRP run writes
planningActionrows: a Buy item short of coverage yields an Order (qty = the grid's lot-sized quantity,supplierId= preferred); a Make item yields a Make. - An open PO due later than the net requirement (gap >
rescheduleToleranceDays) yields an Expedite withsuggestedDate; an open PO due too early yields a Defer; both reference thepurchaseOrderLineId. - An open order whose qty falls short / exceeds the requirement yields Increase / Decrease; an open order with no remaining requirement yields Cancel.
- A date mismatch ≤
rescheduleToleranceDaysyields no message; a mismatch strictly greater fires (boundary test at exactly the tolerance value). -
responsibleEmployeeresolves item → item-group → location → company; the engine stamps the resolved user asassignee; an unset ladder leaves the action Unassigned. Setting the item-group employee routes all that group's actions to them; a per-item override wins. - Reassigning an action in the UI sets
assigneeOverridden; the next run does not overwrite that assignee, but still refreshes suggested qty/date. - Two consecutive runs with unchanged inputs produce byte-identical
planningActionrows (diff-write); a Dismissed action stays dismissed across a run unless its suggestion changes materially; an Actioned action is not recreated. - Applying an Order on an uncommitted plan creates/merges a
PlannedPO (the existing behavior) and flips the action to Actioned; applying Expedite on a Draft/Planned PO line edits itsrequiredDate. - A change action whose target PO is already sent is flagged
requiresManualAction; the worklist shows "Review on PO" and navigates to the PO instead of editing it. - The planning pages render the new columns; the "my actions" filter defaults to the current user; bulk apply/assign/dismiss work via multi-select.
- The settings screen lists company default + every location + every item group with
inherited-placeholders; the item Planning tab has a
responsibleEmployeefield. - Gates:
pnpm --filter @carbon/ee test(action-message generation + resolver + sizing) green; scoped ERP typecheck green;pnpm run generate:typescommitted; browser verification of the worklist + settings on the satellite dataset.
P1.11 Phase 1 Open Questions
All resolved with Brad 2026-09-08 (run record:
.ai/runs/2026-09-08-mrp-planning-actions.md). Kept as the decision record.
- Scope vs the full MRP-v2 build? — Phased. Ship action messages + assignment first (Phase 1); defer the planned-order cascade/lifecycle/capacity/ simulation to Phases 2+ of this spec.
- Persistence: full plannedOrder lifecycle or focused table? — Focused
planningActiontable, no Firm lifecycle, diff-write, all types persisted. - Assignment axis? — Unified
responsibleEmployeeinheritance tree all → location → location-specific item group → item + per-row assignee override (2026-09-09 refinement: the item-group tier is per-location, stored in a sparseitemPostingGroupResponsibilitytable — a printer-style inheritance tree, not the removed N×M matrix). - Enum names + Increase/Decrease in v1? —
Order|Make|Expedite|Defer|Cancel| Increase|Decrease; Increase/Decrease included. - Advisory exceptions in v1? — Actionable-only; urgency is a flag, conditions
in
reason/triggerValues; warning channel deferred. - Tolerance? — One company
rescheduleToleranceDays(7), no qty dampener. - Acting on committed vs uncommitted supply? — Apply on uncommitted; navigate ("Review on document") on committed; automated reopen+notify deferred.
- Keep or replace the live grid? — Keep projection columns; persisted
planningActionis the suggestion source of truth (refresh per run). - UI surface? — Extend the two existing planning pages + one printer-style settings screen; unified cockpit deferred.
Everything below is the Phase 2+ vision — the full planned-order MRP. Preserved as the design record; not what ships in Phase 1. Where Phase 1 diverges, §P1 above is authoritative.
TLDR
Carbon's "MRP" today only nets existing demand against supply per item and suggests a reorder quantity for each item independently. It does not generate planned orders, and it does not cascade a parent's replenishment need down the BOM. A Make item whose only need comes from its reorder policy (e.g. COMMS-001, "Make 5") produces zero dependent demand for its components (ANT-PATCH-01) until a human physically creates the parent job.
This spec moves Carbon to MRP v2: a first-class, disposable planned-order layer generated by the engine in one low-level-code (LLC) sweep — each item's net requirement becomes a lot-sized planned order whose components explode into the next level's gross requirements, with dates, pegging, and a Planned → Firm → Released lifecycle.
And it goes past parity. Every system in the research runs MRP as a batch report
planners learn to distrust. Carbon's engine now runs a full company in ~0.3–0.5 s
(.ai/research/2026-08-12-mrp-findings.md), lives in the same Node process and
package as the finite scheduler (@carbon/planning), and sits next to a
customer-programmable workflow engine and an in-app agent whose data-tool mechanism
is already built. v1 therefore ships MRP that is:
- Live — regenerated within ~30 s of any demand/supply change (the scheduler's debounced-wave pattern, cloned), with the 3-hour cron demoted to a drift backstop.
- Capacity-honest — open-job supply is netted at the scheduler's
projectedCompletionAt(the simulated truth), not the due date; and every regenerated plan is priced against work-center hours (rough-cut capacity), so overload is an exception, not a surprise. - Simulatable — a what-if mode runs the whole engine against a hypothetical demand line with zero writes and returns the plan delta + promise date: capable-to-promise from the quote screen.
- Self-explaining — every planned order carries its lot-sizing derivation, the worklist shows what changed since the planner's last review and why, and the in-app agent can answer "why is it telling me to order 50?" over live plan data.
- Programmable — planned orders are a workflow trigger entity with a release operation, so each shop writes its own auto-release guardrails.
All of it is wrapped in calm-by-default mechanics (§9), because a live, message-emitting planner is only a feature if it is pleasant under pressure: the primary action is one-click Release (the old "Make" muscle memory, preserved); the worklist never reorders under the planner's hands (plan updates arrive as a banner, not a rug-pull); exceptions computed from defaulted or unmaintained inputs are confidence-gated instead of screaming; capacity problems are attributed to the bucket that caused them, not painted across ten rows; and automation ships paused-by-default with a dry-run mode, a release cap, and a daily ledger.
The one-line pitch: every competitor's MRP is a nightly batch report; Carbon's is a live simulation you can interrogate — and it stays calm while being live.
Problem Statement
The engine only cascades actual demand
explodeBom (packages/database/supabase/functions/lib/mrp-engine.ts:171, reached
from Node via the @carbon/database/mrp-engine barrel) is a correct multi-level
explosion: it computes low-level codes, walks items level-by-level, nets each against
on-hand, and explodes the shortfall to children with lead-time offset. But it only
cascades what is already in grossDemand, and grossDemand is seeded
(packages/planning/src/mrp/mrp.ts, Phase 4) from exactly three actual
sources:
openSalesOrderLines— sales-order demandopenJobMaterialLines— materials of already-created jobs (Planned/Ready/In Progress/Paused)demandProjection— planner-entered forecasts
A reorder-policy need is not among them. COMMS-001's "Make 5" is computed
independently, at display time, in SQL — calculate_quantity_to_order(...) inside
the get_production_planning / get_purchasing_planning RPCs — and never flows back
into the engine as demand. So the engine sees grossDemand = 0 for COMMS-001, nets
nothing, explodes nothing, and ANT-PATCH-01 stays at 0.
Reproduction (verified against Carbon Development, 2026-08-22)
- Planning grid: ANT-PATCH-01 demand = 0.
- "Make 5" on COMMS-001 → creates a real Planned job
J000010(qty 5) whose material lines are TXRX-SBAND ×5, ANT-PATCH-01 ×10 (BOM qty 2), MAT-KAPTON ×2.5. - Next MRP run reads those job materials via
openJobMaterialLines→ ANT-PATCH-01 demand = 10.
The dependent demand is arithmetically correct (2 antennas × 5 subsystems) but it only appears after the parent job is materialized — the requirement is manufactured before its dependency is ever computed.
Secondary defects this exposes
- Explosion uses raw net requirement, not the lot-sized order quantity
(
mrp-engine.ts:269,child.quantity * netRequirement). Once planned orders are lot-sized (make 5 to hit a reorder qty when only 3 are needed), children must be exploded against the order quantity (5), or they are under-demanded. - No planned-order persistence. "Make" immediately materializes a real Planned
job; MRP then deletes allsupplyForecastrows every run (Phase 7,mrp.ts:903-1019, unconditional, noforecastMethodfilter) because there is no durable planned-order layer to reconcile against. There is no "review the plan, then release it" state — the plan and reality are the same object. - Lot-sizing logic is duplicated. It lives in SQL (
calculate_quantity_to_order) and is already hand-mirrored on the client (apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx:236, comment: mirrorscalculate_quantity_to_order"exactly"). Adding a third copy in the engine without a shared pure function guarantees drift.
Why parity is not the target
Even fixed, a textbook MRP inherits the three failures that make SMBs abandon MRP:
- Staleness — a 3-hourly plan is wrong for up to 3 hours after every change; planners route around it. (Dynamics went regenerative-only because its engine got fast enough to rerun during office hours; ours reruns in under a second.)
- The fixed-lead-time lie — MRP dates open-job supply at the due date; the finite
scheduler knows the real projected finish (
job.projectedCompletionAt, dual dates, this branch). Netting against the polite fiction produces reschedule messages the planner can see are wrong. - Black-box distrust — a suggestion with no derivation, no diff since yesterday, and no way to ask "why" gets ignored. Pegging alone (an audit table) does not fix this; a rendered explanation does.
And a fourth failure this spec explicitly designs against, because a live MRP amplifies it: exception fatigue on dirty inputs. Every real MRP rollout drowns in past-due and reschedule messages computed from defaulted lead times, unmaintained routings, and stale open POs. A system that is confidently wrong at high frequency is worse than a dumb one. §9 is the answer.
Carbon is the only system in the survey whose MRP and finite scheduler share a process, a language, and a package. v1 exploits that.
Research:
.ai/research/mrp-v2-planner-ui.md(SAP, Oracle, NetSuite, Dynamics 365, Infor LN/M3, Katana, MRPeasy, Fishbowl, + canonical APICS). The eight systems are near-unanimous on the data/workflow model (planned order → firm → release, LLC single-pass explosion of the lot-sized qty, pegging, action messages, the six-row time-phased record) — we adopt it and its standard terminology verbatim. They diverge on UI: the SMB tools hide the time-phased grid behind a single stockout / order-by date and present each shortage as a dated, urgency-sorted, decision-ready row with one-click Make/Buy → draft → approve. We take the enterprise model, lead the UI with the SMB dated-decision pattern, and go past both with the live/capacity/simulation/explainability layer above. Note the research also warns that the SMB tools deliberately expose no firm flag — their audience does not think in APICS lifecycle terms. §9's progressive disclosure is how we keep the enterprise model without making SMB users learn it. Engine findings:.ai/research/2026-08-12-mrp-findings.md.
Proposed Solution
1. The engine algorithm (one LLC sweep = N levels)
MRP v2 is inherently multi-level: a Make parent's planned order releases demand for
its Make children, recursively, until the branch bottoms out at Buy items or on-hand
coverage. A single sweep in strict low-level-code order is provably sufficient for
acyclic BOMs, because LLC guarantees every item is visited only after all its
parents (across all BOMs) have deposited their dependent demand. explodeBom's
existing for (level = 0..maxLevel) loop already is that N-level sweep; cycles are
already broken deterministically (mrp-engine.ts:189-211, cycle members planned last
as leaves).
What changes: at each item, when the sweep reaches its level, do the full APICS netting-and-release step, not just "explode pre-existing demand":
for level in 0..maxLevel:
for each (location, item) at this level, in LLC order:
grossReq = dependent demand exploded from parents (already accumulated)
+ independent demand (sales orders, demand projections)
+ reorder-policy requirement # NEW: seed reorder need here
scheduledReceipts = open jobs/POs + Firm/Released planned orders
# open-JOB receipt date = job.projectedCompletionAt ?? dueDate # NEW: simulated truth
# open-PO receipt date = promised/required date (as today)
netReq = max(0, grossReq - onHand - scheduledReceipts) # period-phased
if netReq > 0:
{ orderQty, trace } = computePlannedOrderQuantity(netReq, policy, params) # NEW: lot-size + trace
dueDate = period need date
releaseDate = workingDayOffset(dueDate, -leadTime, locationCalendar) # NEW: calendar math
emit plannedOrder(item, orderQty, dueDate, releaseDate, trace,
confidence = f(input readiness flags)) # NEW: §9c
record pegs (plannedOrder ← the demand rows it covers, incl. job materials)
if item is Make:
for each child in BOM(item):
childReq = child.quantity * orderQty # NEW: explode ORDER QTY, not netReq
grossDemand[child, releaseDate period] += childReq
record peg (child demand ← this plannedOrder)
carry running on-hand forward (orderQty is supply for this item; leftover stocks)
after the sweep:
roughCutCapacity(plannedMakeOrders) # NEW: RCCP pass (see §3) — bucket-attributed
deriveActionMessages(plannedOrders, openJobs, openPOs) # confidence-gated (§9c)
Key correctness points, all settled:
- Explode the lot-sized order quantity, not
netReq— fixes the under-demand defect. The single most important engine change. - Reorder need is injected at the item's own level, after parent demand has accumulated, so an item's total requirement is complete before it is planned once.
- Open-job supply is dated at
projectedCompletionAt(fallbackdueDatewhen the scheduler hasn't projected it). This is what makes Delay/Expedite messages simulation-derived: "SO-1042 will be short because J000010 is projected 4 days late" is computed from the forward simulation, not date arithmetic. POs keep their promised/required date. - Firm/Released planned orders are fixed supply — not regenerated, but a Make firm
order still explodes its components. Released orders' supply comes from the real
job/PO (
openProductionOrders/openPurchaseOrderLines); the planned-order row is retired. - Dates are working-day dates.
releaseDate(and every backward offset in the cascade) is computed over the location calendar using the same availability-ladder day math the scheduler's need-by pass uses (calendar-utils/resolveLocationWindows, same package) — never naive day subtraction. An order-by date never lands on a day the plant is closed. For Buy items, supplier lead time remains calendar days (that is the purchasing convention), but the resulting release date snaps backward to the nearest working day. - Lot-sizing is one pure function —
computePlannedOrderQuantity(netReq, policy, params)covering the five policies (Manual / Demand-Based / Fixed Reorder Quantity / Maximum Quantity / Period-of-Supply (POQ), net-new) and min/max OQ,orderMultiple,lotSize,maximumInventoryQuantity. It lives in a client-safe, dependency-free module (recommend@carbon/utils, next to the precision helpers it uses — whole-unit ceils viaround(x, 0, Up)), unit-tested in vitest, imported by the engine and the client preview. It returns{ quantity, trace }— the trace is the ordered list of steps that produced the number (policy branch → raw need → each modifier applied → final), persisted on the order and rendered in the UI (§6). The existing SQLcalculate_quantity_to_orderstays for the live grid; a parity test pins the two.
2. Continuous planning — the plan is never stale
Clone the scheduler's proven notify → debounce → regen pattern
(notifyScheduleInputsChanged → carbon/schedule.inputs.changed →
scheduleReplanWaveFunction, debounce 30 s, concurrency 1 per company):
- Emitter:
notifyPlanningInputsChanged(companyId, kind, reason, entityId?)inproduction.service.ts,kind ∈ salesOrder | purchaseOrder | job | inventory | bom | itemPlanning | demandProjection | plannedOrder.reasonis human-readable ("SO-1042 quantity changed") and lands on the run record for the diff banner (§6). - Call sites (chokepoints, not triggers): SO line create/update/delete + SO status
transitions; PO line create/update/delete + status; job status transitions and
quantity/date edits; receipt/shipment/adjustment posting (inventory moved);
methodMaterialwrites (BOM changed);itemPlanning/itemReplenishmentedits;demandProjectionedits; planned-order Firm/Release actions (re-peg around them). - Inngest listeners (MARK/WAVE, exactly like the scheduler):
markPlanningStaleFunction— immediate, no debounce: upserts the one-row-per- companyplanningState(lastInputAt,lastInputKind,lastInputReason) so every surface can honestly show "Plan updating — SO-1042 changed" during the debounce window instead of pretending to be current.planningRegenFunction— debounce 30 s, concurrency 1 per company — callsrunMrp(serviceRole, getJobDatabaseClient(), { type: "company", ... })in-process. At ~0.3–0.5 s per run, the worst case (a busy company saturating the debounce) is ~2 runs/minute — negligible.
- The 3-hour cron stays as the drift backstop (an emitter call site can be missed;
time passes and periods roll), exactly as
nightly-replan.tsbackstops the scheduler's event path. - The planning time fence (§ Data Model) is the nervousness guard that makes
continuous regen safe: inside the firm horizon (a location-wide default with a
per-item
itemPlanningoverride) the engine auto-firms, so near-term rows stop churning no matter how often the plan regenerates. The two features justify each other. - Every run writes a
planningRunrow (trigger kind + reason, timing, diff counts, capacity summary). The worklist header shows "Plan updated 2 min ago — cause: SO-1042 quantity changed". The manual Recalculate button stays (it now also serves as "run it right now, skip the debounce").
Continuous does not mean restless. The regen updates the database; it never updates a worklist the planner is looking at. See §9b — plan updates reach open sessions as a banner, not a re-render.
3. Rough-cut capacity (RCCP) — overload is an exception, not a surprise
After the sweep, price the plan against real machine hours. Both inputs are already in this package:
- Work content per planned Make order = the item's active routing operation times (setup + max(labor, machine) per op, the scheduler's own duration convention) × order quantity, bucketed into the order's release→due window per work center.
- Available hours per work center per week = the availability ladder
(
resolveWorkCenterWindows:alwaysOn→workCenterShift→ location shifts → stock week), minus maintenance-dispatch downtime — the exact windows the finite scheduler places against.
Overload is attributed to the bucket, never sprayed across orders. Where
cumulative planned work content + already-reserved hours (capacityReservation work
hours for live jobs) exceed available hours, the run's loadSummary records one
capacity exception per (work center, week) — "CNC-1, week of Sep 7: 14 h over" —
with the contributing orders listed inside it. The worklist's capacity strip renders
those bucket rows; contributing planned orders get only a secondary
capacityConstrained badge (a column, never their primary exceptionType), so one
missing shift is one red row, not ten. One problem = one row = one fix.
This is deliberately rough-cut: no sequencing, no operation dependencies, no
labor gating — those belong to the finite scheduler after Release. RCCP's job is the
planner-level early warning, and the UI labels it "rough-cut" wherever it appears.
Scenario-mode finite scheduling of planned orders (capacityReservation.scenarioId
is already reserved for this) is explicitly deferred.
4. What-if / capable-to-promise — the plan is a simulator
runMrp gains a simulation mode: runPlanningWhatIf(client, db, { companyId, locationId, hypothetical: { itemId, quantity, dueDate, salesOrderLineId? } }) runs
the identical sweep + RCCP against live inputs plus the hypothetical demand line,
persists nothing, and returns:
- the plan delta — planned orders that would be created/changed vs the live plan (the diff is cheap because planned orders have deterministic identities, §5);
- the promise date — the hypothetical's cascade-feasible completion: longest release→due chain through the exploded tree on real calendars, honoring on-hand and scheduled receipts;
- the capacity impact — RCCP buckets that flip into overload;
- the estimated cost — Σ (buy orders × last/supplier price) + (make orders × standard cost estimate) for the net-new orders;
- the assumption list — rendered verbatim in the result panel: "assumes current plan is released on time; material + rough-cut capacity feasible; shop queue not simulated". The promise is labeled plan-based everywhere it appears; the finite-schedule answer post-release remains the expedite what-if.
This is the runExpediteWhatIf pattern (run-schedule.ts:159 — simulate with
persist: false, return the projection) applied to planning. Surfaced from the quote
line and sales-order line (§10) and as POST api/planning/what-if.
5. Persisted planned-order layer — durable, diffable, idempotent
A new plannedOrder table is the engine's durable output; plannedOrderPeg records
supply→demand links for two-way pegging; planningRun records each regeneration.
supplyForecast is superseded by plannedOrder on the Make/Buy planning path; the
unconditional supplyForecast delete goes away with it.
Regen is a diff-write, not delete-and-recreate. Each generated order carries a
deterministic natural key (companyId, itemId, locationId, orderType, periodId, splitIndex) (splitIndex > 0 only when max-OQ splitting produces multiple orders in
one bucket). The Phase-7 transaction upserts on that key: matched Planned rows are
updated in place only when a value actually changed (id and createdAt stable,
updatedAt bumps only on real change), unmatched Planned rows are deleted, new rows
inserted. Firm rows are left untouched (re-pegged around); Released rows are never
touched. This one mechanism buys four features:
- Idempotency — two consecutive runs with unchanged inputs produce byte-identical rows (the acceptance test), not new ids that merely look the same.
- Plan diffing — "changed since your last review" = rows with
updatedAt/createdAt > reviewedAt, plus the run's deleted-count; theplanningRunrow storescreated/updated/deleted/unchangedcounts and the trigger reason. - Workflow-trigger hygiene — the event-system record triggers on
plannedOrderonly fire for genuine changes, so continuous regen does not spam customer workflows. - Optimistic concurrency — a mutation submitted from a stale worklist is detected
by comparing the row's
updatedAt(§9b) instead of silently acting on changed data.
6. A plan that explains itself
Three deterministic layers plus the agent:
- Lot-sizing trace —
plannedOrder.quantityTrace(JSONB, written from the pure function'strace) renders in the drawer as e.g. "Net requirement 3 → Fixed Reorder Quantity 5 → order multiple 5 → 5". No AI involved; it is the function's own arithmetic, shown. - Peg popover — "why does this exist?" (up: the demand rows it covers, including job materials and reorder policy) / "what does it drive?" (down: child planned orders), with lot-sizing surplus surfaced as a labeled "quantity without source" node so over-production is explainable.
- Plan diff banner — the worklist header reads the latest
planningRunvs the planner'sreviewedAtmarks: "Since your last review: 3 new, 2 rescheduled in, 1 canceled — latest cause: SO-1042 quantity changed." Nervousness becomes something planners watch, not fear. - Ask the plan (agent data tools) — the gated data tools were REMOVED from the agent on
2026-09-30 (they had never shipped); restore them from the commit that deleted them
(
git log -S AGENT_DATA_TOOLS_ENABLED) rather than flipping a flag. As they were built:search_tools/describe_tool/call_toolexecute READ-classified MCP tools via the direct executor. v1 work: ensure the new planning reads (getPlannedOrders,getPlannedOrderCascade,getItemTimePhasedPlan,getPlanningRun) are READ-classified in the MCP tool metadata, and add a planning page to the docs → agent KB so the assistant knows the standard terminology. The flagship question — "why is it telling me to order 50 of ANT-PATCH-01?" — is answered from pegs + trace, in prose.
7. Programmable release — planned orders × the workflow engine
- Trigger entity: register
plannedOrderin the workflow catalog (packages/workflows/src/catalog/entities.ts— it is a real table, so record events work; watch columnsstatus,exceptionType,dueDate,quantity) and regen the catalog. The diff-write regen (§5) keeps these events meaningful. - Moment:
planning.exceptionRaised— raised (viaraiseMoment) when a row transitions into an exception state during regen, carrying order + exception outputs, for shops that want to react to messages rather than row changes. - Operations: add
releasePlannedOrderandfirmPlannedOrderworkflow operations (catalog/operations.ts), so a customer can author: "when a Buy planned order is created with estimated cost < $500, supplier is approved, and release date is within 7 days → release it and Slack #purchasing." This is the progressive-autopilot path: suggestion → guardrailed auto-release → per-category autopilot, authored by the shop, not hard-coded by us. - Safety rails are not optional — every planning automation runs inside the pause/dry-run/cap controls of §9f, and everything autopilot does lands in a daily ledger. Automation you can't instantly stop is automation nobody enables.
- Notifications: new
NotificationEvent.PlanningExceptions— a digest of normal-confidence Past-due/Delay exceptions and newly overloaded capacity buckets per location planner, following theJobsProjectedLatedigest precedent (InApp default; Email/Slack opt-in — note: channels are InApp/Email/Slack; there is no SMS). Low-confidence messages (§9c) never notify. A second event,NotificationEvent.PlannedOrdersAwaitingRelease, backs the cross-team handoff (§9g).
8. Suggested demand projections — feed the cascade, refuse to guess
demandProjection is today 100% manual, which caps the quality of everything
downstream. v1 adds suggested projections — never auto-applied:
getSuggestedDemandProjection(client, { itemId, locationId })computes a trailing 13-week weekly average (+ simple trend) fromdemandActualhistory (sourceType = 'Sales Order'), reusing the usage stats machinery (usageLast30Days/usageLast90Daysalready exist onget_inventory_quantities).- The honesty gate: when history is intermittent/lumpy (coefficient of variation
above a single named constant — recommend
SUGGESTION_MAX_CV = 0.8), the service returns a refusal, and the UI shows the history sparkline with "demand is too irregular for a simple average — no suggestion" instead of a number. A refusal preserves trust; a bad number spends it. (Croston-style intermittent-demand models are the deferred upgrade, not a v1 hack.) DemandProjectionFormshows accepted suggestions as a ghost row per week with one-click Apply (per week / per quarter). Applied rows are ordinarydemandProjectionrows withforecastMethod = 'suggested'andconfidencepopulated (the column already exists and has never been used).
9. Calm by default — the annoyance guards
The five differentiators make the planner louder; this section is what keeps it calm. Every mechanism here is deterministic product mechanics — no AI involved.
a. One-click Release; the lifecycle is progressive disclosure. The worklist row's
primary button is Release and it does what "Make 5" did: creates the job/PO
immediately from the planned values — no drawer, no draft step. The draft-review
drawer interposes only when the order carries warnings (lowConfidence,
capacityConstrained, or a Cancel/Decrease exception); a "Release & edit…" secondary
action opens it on demand. Firm never appears as an unprompted verb: editing a
Planned order's qty/date in the drawer asks once, in plain language — "Keep your
numbers through plan updates?" — and yes = Firm (firmedBy = the user). The status
chip still says "Firm" (standard terminology stays in the data and power surfaces);
nobody is required to learn it before it applies to them.
b. The worklist never moves under the planner. The worklist does not
live-revalidate. Data loads once; regens happen underneath; a lightweight watcher
on planningRun (+ planningState for the in-debounce window) drives a quiet
banner — "Plan updating — SO-1042 changed" → "Plan updated — 3 changes ·
Refresh". Rows never reorder, appear, or change value except on explicit refresh
(the GitHub "branch was updated" pattern; SAP ships MD05-vs-MD04 for the same
reason). Mutations (release, firm, batch ops) submit with the loaded rows'
updatedAt and the server rejects drifted rows individually — the response
reconciles explicitly: "2 of 12 selected orders changed since you loaded — review
these 2; the other 10 succeeded." Never silent, never all-or-nothing.
c. Confidence-gated exceptions + the readiness preflight. An exception computed
from a guess is a guess. During each run the engine computes per-item readiness
flags from data that already exists: lead time never maintained
(itemReplenishment.updatedBy IS NULL on the default), routings with zero times,
Make items with no active BOM/routing, and demand/supply rows pinned on stale open
POs (due > 60 days past). Orders and messages derived from flagged inputs get
lowConfidence = true + a confidenceNote ("computed from the default 7-day lead
time"). Low-confidence messages are excluded from the default worklist filter and
from every notification digest — visible only in an "All messages" view, badged
with their reason. A Planning readiness panel (linked from the worklist header
and shown before the first-ever run) summarizes the company-wide counts — "34 items
on the default lead time · 14 open POs older than 60 days · 6 routings with no
times" — each deep-linking to a pre-filtered list where the existing edit/close
actions fix the input. Day one is a to-do list, not a wall of red.
d. Capacity blames the bucket — specified in §3: one exception per (work center,
week) in the capacity strip; contributing orders get only the secondary
capacityConstrained badge. 'Overload' is deliberately not a value of
plannedOrderException.
e. Auto-firmed orders can't become zombies. Firm rows carry provenance
(firmedBy = userId or 'system', firmedAt). Each regen re-pegs Firm rows; a Firm
order whose pegged demand has vanished gets exceptionType = 'Cancel', and the
worklist offers a one-click sweep — "Return N orphaned orders to planning"
(unfirm + delete; the next regen recreates only what's still needed). The sweep
defaults to system-firmed rows; user-firmed orphans show the Cancel message but are
never swept without the owner.
f. Autopilot ships with rails. Three company-level settings gate the planning
workflow operations (releasePlannedOrder/firmPlannedOrder):
planningAutomationsPaused (one switch stops everything, instantly),
planningAutomationsDryRun (default ON — the operation logs what it would
have done to workflow run history as Skipped-with-reason, so a new rule earns trust
before it spends money), and planningAutomationMaxReleasesPerRun (cap per regen
cycle; excess queues with a notice). Everything autopilot actually does appears in a
daily autopilot ledger section of the PlanningExceptions digest: "Auto-released
7 buy orders totaling $1,840 under rule 'small fasteners'."
g. Chain release is a handoff, not a half-working button. Releasing a cascade
that crosses the make/buy permission boundary: the whole chain is firmed in one
transaction (the decision is locked), the caller's permitted side is released, and
the remaining Firm orders notify the counterpart team
(PlannedOrdersAwaitingRelease) with a deep link to their worklist pre-filtered to
that chain. Segregation of duties as a feature: production decides the plan is real;
purchasing controls the spend.
h. One number everywhere. The planning grid RPCs read plannedOrder as the plan
source; for an item with a current planned order, quantityToOrder is the
planned-order total — the live SQL recompute (calculate_quantity_to_order) fills
only items with no planned order (e.g. newly demanded since the last regen). While
planningState.lastInputAt > planningRun.completedAt, every planning surface shows
the same "Plan updating…" indicator instead of letting two numbers disagree silently.
i. Suggestions refuse to guess — specified in §8 (the CV gate).
10. UI: quantity-sorted worklist → live, pegged, date-driven plan
Design principle from the research: the row is a dated decision, not a number. The default surface is decision-ready and urgency-sorted; the enterprise time-phased grid is a drill-down for when a planner needs to see why.
Routes: apps/erp/app/routes/x+/production+/planning.tsx (+ purchasing) and the
components under apps/erp/app/modules/{production,purchasing}/ui/Planning/.
- Plan worklist (new default). One row per
plannedOrder(make and buy): item, supplier/work center (resolved), shortage qty, a single stockout / order-by date, suggested (lot-sized) qty, estimated cost, status, and one action chip. Sorted by urgency (order-by date), not quantity; default filter = action-needed rows at normal confidence (§9c). Primary action: one-click Release (§9a); secondary: "Release & edit…", Firm (via the plain-language lock prompt), batch-select ≤ 50 (Katana), mark-reviewed. Header: the live banner (§9b: "Plan updating…" / "Plan updated — N changes · Refresh"), the plan-diff banner (§6), the capacity strip (bucket rows fromloadSummary, labeled "rough-cut", §3/§9d), and a readiness link when readiness counts are non-zero (§9c). Saved views: "Action messages", "All messages" (includes low-confidence, badged), "Orphaned firm orders" (§9e). - Cascade / pegging tree. Indented, rooted at independent demand → planned order → dependent planned orders → buys, reusing the existing job/method BOM-tree rendering. Each level shows its order-by date pointing at the child planned order or linked PO. Row action: Release the whole chain (with the §9g handoff across the make/buy boundary). Peg popover per §6; "quantity without source" nodes labeled.
- Item time-phased matrix (expert drill-down). The full six canonical rows per bucket — Gross Requirements / Scheduled Receipts / Projected Available Balance / Net Requirements / Planned Order Receipts / Planned Order Releases — plus a SAP-style running-available-balance line view. Never the landing page.
ProductionPlanningOrderDrawer— opens on "Release & edit…", row click, or a warning-bearing Release; contains Firm/unfirm (lock prompt), cascade-release, mark-reviewed, the lot-sizing trace,confidenceNotewhen low-confidence, and the peg popover; edits act on planned orders.- Planning readiness panel (§9c) — worklist-header link + first-run interstitial; counts with deep links to pre-filtered fix-it lists.
- Capable-to-promise entry — a "Can we make it?" action on the quote line and sales-order line drawers → panel showing promise date, the would-be order tree, capacity impact, estimated cost, and the assumption list (§4), labeled plan-based.
- Suggested projections in
DemandProjectionFormper §8, including the too-lumpy refusal state with sparkline. - Automation settings — the pause/dry-run/cap controls (§9f) on the production settings page, plus the autopilot ledger in the digest.
Make/buy stay on two pages for v1, cross-linked across the boundary in the cascade tree (and bridged by the §9g handoff).
Pegging semantics: plannedOrderPeg is soft pegging (a supply may serve many
demands). Carbon already carries the hard-peg case — an MTO job.salesOrderLineId
dedicates supply to one demand — which the tree renders as a fixed link.
Design Decisions
| Decision | Choice | Rationale |
|---|---|---|
Planned order = new entity vs reuse supplyForecast |
New plannedOrder table |
supplyForecast is a period-bucketed aggregate with no identity, status, dates, or pegging. A planned order must be individually firmable, releasable, peggable, and diffable. |
| Single LLC sweep vs N fixpoint passes | Single LLC sweep | LLC guarantees parents-before-children; the existing for level loop already provides the N-level walk. Cycles are broken deterministically today; that logic is reused unchanged. |
| Explosion quantity | Lot-sized order quantity, not raw net requirement | A reorder round-up (make 5, need 3) must pull 5× the component qty. Fixes mrp-engine.ts:269. |
| Lot-sizing home | Pure TS fn in @carbon/utils returning {quantity, trace}; keep SQL calculate_quantity_to_order |
Engine + client preview import one dependency-free, unit-tested function; the trace powers the explain panel for free. SQL stays for the live grid; a parity test pins them. |
| Materialize on plan vs on release | Planned orders are disposable; real job/PO created only on Release |
Enables "review then commit," removes the supplyForecast wipe, and lets regen own the plan. The core behavioral shift. |
| Release UX | One-click Release from the row (old "Make" muscle memory); draft drawer interposes only on warnings | The lifecycle is a data-model asset, not a UI toll. The research's SMB cluster has no lifecycle because their audience won't pay ceremony; progressive disclosure keeps both audiences. |
| Firm exposure | Firm is entered via a plain-language lock prompt on edit; firmedBy/firmedAt provenance; chip keeps the standard term |
Standard terminology survives in data and power surfaces; nobody must learn APICS to keep an edit. Provenance separates system auto-firm from human intent (enables §9e). |
| Regen write strategy | Diff-write on a deterministic natural key (itemId, locationId, orderType, periodId, splitIndex), partial-unique on Planned rows |
One mechanism buys idempotency (stable ids), plan diffing (updatedAt is honest), workflow-trigger hygiene (no event spam), and optimistic concurrency for stale-session mutations. Delete-recreate would break all four. |
| Worklist freshness model | No live revalidation; planningRun/planningState watcher banner; explicit Refresh; per-row updatedAt optimistic concurrency with explicit reconciliation |
A live plan must not mean a moving worklist. SAP splits MD04/MD05 for this exact reason; we get both surfaces from one table by controlling revalidation. |
| Run cadence | Event-driven continuous (carbon/planning.inputs.changed, MARK stamp + debounce 30 s WAVE, concurrency 1/company) + 3-hour cron as drift backstop |
The engine costs ~0.3–0.5 s/company; the scheduler's MARK/WAVE pattern is proven on this branch. Staleness is MRP's #1 practical failure; we can simply delete it. |
| Open-job supply dating | job.projectedCompletionAt (fallback dueDate) |
Dual dates exist on this branch; netting against the simulated finish makes Delay/Expedite messages true. The scheduler stays the owner of job dates. |
| Capacity in the plan | Rough-cut in every run; exceptions attributed per (work center, week) bucket in loadSummary; contributing orders get a secondary capacityConstrained badge, never their primary exception |
One capacity problem must render as one row with one fix, not ten red orders. Full scenario finite-scheduling (scenarioId) is deferred — RCCP is the planner-level early warning, honestly labeled. |
| Exception confidence | Readiness flags computed per run; messages from flagged inputs are lowConfidence + confidenceNote, excluded from default filters and all digests; a Planning readiness panel drives fixing the inputs |
A live MRP on dirty data is confidently wrong at high frequency — the worst failure mode. Gating by input quality turns day one from a wall of red into a to-do list, without hiding anything (the "All messages" view keeps it inspectable). |
| What-if / CTP | runPlanningWhatIf — full sweep + RCCP with a hypothetical demand line, persist: false, returns plan delta + promise date + capacity impact + cost + explicit assumption list |
The runExpediteWhatIf pattern applied to planning. v1 promise = material + rough-cut feasible, labeled "plan-based", assumptions rendered verbatim so the number can't silently become a guarantee. |
| Firm order semantics | Firm survives regen, counts as fixed supply, still explodes its BOM; editable qty/date; orphaned Firm rows get a Cancel exception + one-click return-to-planning sweep (system-firmed by default) | Standard firm-planned-order behavior, plus a way out: auto-firm without orphan cleanup manufactures zombie orders nobody owns. |
| Buy items | Also get planned orders (planned PO) | The cascade crosses make→buy on every branch; unified model required for end-to-end pegging. |
| Transfer orders | 'Transfer' reserved in plannedOrderType now; generation deferred |
Every surveyed system types make/buy/transfer; warehouseTransfer is the natural release target. Reserving the enum value now avoids a migration later; DRP-style multi-location netting is real scope and explicitly deferred. |
| Pegging storage | plannedOrderPeg (polymorphic demand source, including jobId for job-material demand) + convenience parentPlannedOrderId |
openJobMaterialLines is one of the three real demand seeds — without a job source, pegging breaks on day one for any shop with open jobs. Mirrors demandForecastSource (which has jobId). |
| Date math | Working-day offsets over the availability ladder (calendar-utils day math, location calendar), never naive day subtraction |
An order-by date on a closed day is an instant credibility loss; the need-by calculator already does this math in the same package. Buy lead times stay calendar days, release date snaps to a working day. |
| Cross-permission cascade release | Firm the whole chain, release the permitted side, notify the counterpart team (PlannedOrdersAwaitingRelease) with a pre-filtered link |
A half-working button is worse than a handoff. Segregation of duties (production decides, purchasing spends) is what enterprise buyers expect anyway. |
| Automation safety | Company-level pause switch, dry-run mode (default ON), per-run release cap; daily autopilot ledger in the digest | A customer's bad rule + a fat-fingered projection must not create 40 POs overnight. Dry-run-by-default means every new rule earns trust before it spends money. |
| Plan vs grid coherence | Grid quantityToOrder = the planned-order total when a plan exists; live SQL only fills no-plan rows; a shared "Plan updating…" indicator from planningState |
Two numbers for the same item is a screenshot-and-file-a-bug generator. One number, one staleness signal, everywhere. |
| Run scope | Full company regenerative run (event + cron + manual) | Regenerative-only is the industry direction (Dynamics); the engine is fast enough. Scoped/incremental regen is unnecessary complexity at 0.3 s. |
| Freshness of the SQL grid | Keep calculate_quantity_to_order + RPCs in v1 (bounded by the coherence rule above) |
The live-recompute grid keeps "reload and it's right" for no-plan rows while the planned-order surfaces take over; retiring it is deferred. |
| Terminology | Adopt standard MRP terms verbatim — planned order, firm planned order, release, low-level code, gross-to-net, planned order receipt/release, pegging (single/full, soft/hard), action message | All eight systems + APICS agree; planners recognize them. Progressive disclosure (§9a) keeps the terms from becoming homework. |
| Action-message model | v1: full standard set (Release / Expedite / De-expedite / Cancel / Increase / Decrease / Past-due / Delay), computed over planned orders and real open jobs/POs; single highest-priority message on the line; capacity is bucket-level, not a message value | Research §6: the plan is worked as a message queue; reschedule/cancel apply to open orders. Job messages are simulation-derived (projected supply dating). |
| Planning time fence / auto-firm | v1: full auto-firm inside a firm horizon resolved per item — itemPlanning."planningTimeFenceDays" (nullable override) else location."planningTimeFenceDays" else 0 — evaluated on release/start date; auto-firms carry firmedBy='system' for the orphan sweep |
The nervousness guard that makes continuous regen safe. Per-item fence placement is the enterprise standard (SAP material master, Oracle item attribute, Dynamics coverage group); the location default is the flat-default-plus-override shape Carbon config prefers. Dynamics' order-date-vs-due-date firming is a documented trap — fence on release date. |
| Time-phased matrix vs derived date | Lead with a single stockout/order-by date; full six-row matrix is a drill-down | SMB pattern; the grid stays for power users. |
| Lot-sizing policies | v1: the four existing reorderingPolicy values mapped to standard names + period-of-supply/POQ |
Manual→Manual, Demand-Based→lot-for-lot, Fixed Reorder Qty→FOQ, Maximum Quantity→min/max, + POQ (TS-only, no SQL parity row). |
| Explainability | Deterministic first (trace + pegs + diff), agent on top | The trace and diff are free byproducts of the pure function and the diff-write; the agent data-tool mechanism already exists behind AGENT_DATA_TOOLS_ENABLED and planning reads are READ-class. |
| Programmable release | plannedOrder as a workflow trigger entity + planning.exceptionRaised moment + releasePlannedOrder/firmPlannedOrder operations, all inside the §9f rails |
The shop authors its own auto-release guardrails; we never hard-code release policy. Catalog is table-driven; plannedOrder is a real table so record events work. |
| Demand suggestions | Trailing-average suggested demandProjection rows, planner-applied, forecastMethod='suggested', confidence populated; CV gate refuses lumpy history |
A visible, editable average the planner approves beats an opaque model — and a refusal beats a bad number. No statistical library in v1. |
| Worklist quality-of-life | v1: mark-reviewed, batch-release, exception digest notifications | SAP "accept results", Katana batch-release, Fishbowl alerts — via Carbon's notification system. |
Data Model Changes
Four new tables/objects + one enum value + one location column + three settings
columns. (RLS uses the current get_companies_with_employee_role() /
get_companies_with_employee_permission() helpers — the template's has_role() is
deprecated.)
-- Order type includes Transfer (reserved; not generated in v1)
CREATE TYPE "plannedOrderType" AS ENUM ('Make', 'Buy', 'Transfer');
CREATE TYPE "plannedOrderStatus" AS ENUM ('Planned', 'Firm', 'Released');
-- NOTE: no 'Overload' value — capacity exceptions are bucket-level (planningRun.loadSummary)
CREATE TYPE "plannedOrderException" AS ENUM (
'Release', 'Expedite', 'DeExpedite', 'Cancel', 'Increase', 'Decrease',
'PastDue', 'Delay'
);
-- The MRP-generated planned order. Disposable when status = 'Planned'.
CREATE TABLE "plannedOrder" (
"id" TEXT NOT NULL DEFAULT id('plo'),
"companyId" TEXT NOT NULL,
"itemId" TEXT NOT NULL,
"locationId" TEXT NOT NULL,
"orderType" "plannedOrderType" NOT NULL,
"status" "plannedOrderStatus" NOT NULL DEFAULT 'Planned',
"quantity" NUMERIC NOT NULL, -- lot-sized order quantity
"quantityTrace" JSONB, -- lot-sizing derivation (from computePlannedOrderQuantity)
"dueDate" DATE NOT NULL, -- receipt must land by
"releaseDate" DATE NOT NULL, -- working-day offset of dueDate - leadTime
"periodId" TEXT NOT NULL, -- weekly bucket (get-or-create; part of natural key)
"splitIndex" INTEGER NOT NULL DEFAULT 0, -- >0 when max-OQ splits one bucket into N orders
"lowLevelCode" INTEGER NOT NULL DEFAULT 0,
"parentPlannedOrderId" TEXT, -- cascade convenience pointer (nullable)
"exceptionType" "plannedOrderException", -- highest-priority action message (nullable)
"suggestedDate" DATE, -- engine's recommended new date for Expedite/De-expedite
"capacityConstrained" BOOLEAN NOT NULL DEFAULT false, -- secondary badge; bucket detail lives in planningRun.loadSummary
"lowConfidence" BOOLEAN NOT NULL DEFAULT false, -- derived from readiness flags on its inputs (§9c)
"confidenceNote" TEXT, -- e.g. 'computed from the default 7-day lead time'
"reviewedAt" TIMESTAMP WITH TIME ZONE, -- planner "accepted/marked reviewed"
"firmedBy" TEXT, -- userId, or 'system' for time-fence auto-firm
"firmedAt" TIMESTAMP WITH TIME ZONE,
-- Set when Released:
"jobId" TEXT,
"purchaseOrderLineId" TEXT,
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
);
CREATE INDEX "plannedOrder_companyId_idx" ON "plannedOrder" ("companyId");
CREATE INDEX "plannedOrder_item_loc_idx" ON "plannedOrder" ("companyId", "itemId", "locationId");
CREATE INDEX "plannedOrder_status_idx" ON "plannedOrder" ("companyId", "status");
CREATE INDEX "plannedOrder_parent_idx" ON "plannedOrder" ("parentPlannedOrderId");
CREATE INDEX "plannedOrder_createdBy_idx" ON "plannedOrder" ("createdBy");
-- Deterministic regen identity: uniqueness enforced only for engine-owned rows
CREATE UNIQUE INDEX "plannedOrder_natural_key_idx" ON "plannedOrder"
("companyId", "itemId", "locationId", "orderType", "periodId", "splitIndex")
WHERE "status" = 'Planned';
-- Pegging: which demand a planned order covers. Polymorphic demand source, exactly one set.
CREATE TABLE "plannedOrderPeg" (
"id" TEXT NOT NULL DEFAULT id('peg'),
"companyId" TEXT NOT NULL,
"plannedOrderId" TEXT NOT NULL, -- the supply
"quantity" NUMERIC NOT NULL, -- how much of the order is for this demand
-- exactly one of:
"salesOrderLineId" TEXT,
"jobId" TEXT, -- job-material demand (mirrors demandForecastSource)
"parentPlannedOrderId" TEXT, -- dependent demand from a parent order
"demandProjectionId" TEXT,
"reorderPolicy" BOOLEAN, -- true = reorder-point/safety-stock-driven (independent)
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
-- + CHECK: exactly one demand source set (five-way)
);
CREATE INDEX "plannedOrderPeg_companyId_idx" ON "plannedOrderPeg" ("companyId");
CREATE INDEX "plannedOrderPeg_order_idx" ON "plannedOrderPeg" ("plannedOrderId");
CREATE INDEX "plannedOrderPeg_createdBy_idx" ON "plannedOrderPeg" ("createdBy");
-- One row per regeneration: freshness, cause, diff counts, rough-cut load.
CREATE TABLE "planningRun" (
"id" TEXT NOT NULL DEFAULT id('prun'),
"companyId" TEXT NOT NULL,
"trigger" TEXT NOT NULL, -- 'event' | 'cron' | 'manual'
"triggerKind" TEXT, -- emitter kind (salesOrder, job, ...)
"triggerReason" TEXT, -- human-readable cause for the banner
"startedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"completedAt" TIMESTAMP WITH TIME ZONE,
"ordersCreated" INTEGER NOT NULL DEFAULT 0,
"ordersUpdated" INTEGER NOT NULL DEFAULT 0,
"ordersDeleted" INTEGER NOT NULL DEFAULT 0,
"ordersUnchanged" INTEGER NOT NULL DEFAULT 0,
"loadSummary" JSONB, -- RCCP: per (workCenterId, weekStart) {available, reserved, planned, contributingOrderIds}
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
);
CREATE INDEX "planningRun_companyId_idx" ON "planningRun" ("companyId", "createdAt" DESC);
-- Retention: keep the newest N (e.g. 200) runs per company; prune in the regen function.
-- One row per company: input freshness for the "Plan updating…" indicator (§9b/§9h).
-- Maintained by markPlanningStaleFunction (MARK) and cleared/compared against
-- planningRun.completedAt. System-written; SELECT-only for employees.
CREATE TABLE "planningState" (
"companyId" TEXT NOT NULL,
"lastInputAt" TIMESTAMP WITH TIME ZONE,
"lastInputKind" TEXT,
"lastInputReason" TEXT,
PRIMARY KEY ("companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
);
Automation rails (§9f) — three columns on companySettings:
ALTER TABLE "companySettings"
ADD COLUMN "planningAutomationsPaused" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "planningAutomationsDryRun" BOOLEAN NOT NULL DEFAULT true, -- safe by default
ADD COLUMN "planningAutomationMaxReleasesPerRun" INTEGER NOT NULL DEFAULT 25;
All new tables need the four standard RLS policies (plannedOrder: SELECT via
get_companies_with_employee_role(), writes via production_* / purchasing_*; the
peg and run tables mirror it; planningState is SELECT-only for employees,
service-role-written). plannedOrder additionally gets the event-system
record-change trigger (attach dispatch_event_batch) so workflow record events fire.
Planning time fence (auto-firm) — location default, per-item override. Two columns:
ALTER TABLE "location" ADD COLUMN "planningTimeFenceDays" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "itemPlanning" ADD COLUMN "planningTimeFenceDays" INTEGER; -- NULL = inherit location
itemPlanning is already the per-(item, location) planning-behavior home
(reorderingPolicy, demandAccumulationPeriod, demandReschedulingPeriod), so the
fence completes that field family, and the engine reads itemPlanning per item for
lot-sizing anyway. The engine resolves
COALESCE(itemPlanning."planningTimeFenceDays", location."planningTimeFenceDays", 0)
per item. Inside the resolved horizon it auto-firms planned orders (firmedBy = 'system') and does not create/reschedule freely, evaluated on the order's release
date, not its due date (the documented Dynamics trap). 0 = manual-firm-only — and
an explicit per-item 0 opts a volatile item out of a location-wide fence. This
placement mirrors the enterprise standard (SAP: material master; Oracle: item
attribute; Dynamics: the item's coverage group) while the location default keeps
zero-config shops from maintaining it per item. Manual firm/unfirm remains
available. Orphaned auto-firms are handled by the §9e sweep.
Action messages span open orders (v1). Expedite / De-expedite / Cancel /
Increase / Decrease apply not just to Planned orders but to real open jobs/POs
whose dates/quantities no longer match net requirements — derived per run from the
plan (not persisted per open order); plannedOrder.exceptionType carries them for
planned orders. Because open-job supply is dated at projectedCompletionAt, a job
message means "the simulation says this will actually be late/early", not "the due
date differs". Messages derived from low-readiness inputs are confidence-gated
(§9c). Applying a job reschedule routes through notifyScheduleInputsChanged /
updateJobOperationDueDate — the finite scheduler owns
jobOperation.startDate/projectedCompletionAt and job.projectedCompletionAt; a
PO reschedule edits the PO line's promised/required date. The message is MRP's
recommendation; the owning subsystem executes it.
Relationship to existing planning tables: demandForecast (BOM-derived child
demand) remains the engine's demand output, now pegged to a parent plannedOrder.
plannedOrder supersedes supplyForecast on the planning path; the Make/Buy
planning.update routes stop writing supplyForecast, and MRP's unconditional
supplyForecast delete (Phase 7) is removed. demandActual/supplyActual (real
docs) are unchanged. demandProjection gains no columns (suggestions are ordinary
rows with forecastMethod = 'suggested').
API / Service Changes
Engine (packages/planning/src/)
- New
lot-sizingin@carbon/utils: purecomputePlannedOrderQuantity(netRequirement, policy, params): { quantity, trace }— five policy branches (four ported fromcalculate_quantity_to_order+ POQ), plus min/max OQ,orderMultiple,lotSize,maximumInventoryQuantity. Parity test vs the SQL fn on a fixture matrix (POQ is TS-only). explodeBom→ extended (or a newgeneratePlannedOrders) to run the fused net→lot-size→release→explode step per LLC level; explode the order quantity; date open-job supply atprojectedCompletionAt ?? dueDate; compute release dates via working-day offsets over the location calendar (sharedcalendar-utilsday math); emitplannedOrder+plannedOrderPeg(includingjobIdpegs); treat Firm/Released as fixed supply; stamplowConfidence/confidenceNotefrom the readiness flags.- New
readiness.ts: computes the per-item readiness flags (default lead time viaitemReplenishment.updatedBy IS NULL, zero-time routings, missing BOM/routing for Make items, stale open POs > 60 days past due) — used by the engine for confidence gating and bygetPlanningReadinessfor the panel. - New
rough-cut-capacity.ts: prices planned Make orders (routing durations × qty) plus livecapacityReservationhours againstresolveWorkCenterWindowsbuckets; returns the bucket-level load table (with contributing order ids) + thecapacityConstrainedorder set. Pure over injected inputs; vitest-tested. - New
action-messages.ts: derives the standard message set over planned orders and open jobs/POs; single highest-priority message per line; confidence-gated. runMrpPhase-7 write: within the existing atomic Kysely transaction, diff-writeplannedOrderon the natural key (update-if-changed / insert / delete-unmatched Planned rows + their pegs), keep Firm/Released (re-peg; orphan-flag), write theplanningRunrow (+ prune old runs), drop thesupplyForecastdelete.- New
runPlanningWhatIf(client, db, params): the sweep + RCCP with an injected hypothetical demand line,persist: false; returns{ promiseDate, planDelta, capacityImpact, estimatedCost, assumptions }. - All relocated/new value-bearing math stays under
@carbon/checkscoverage (packages/planning/srcis already in the TS source set on this branch); no scale literals, whole-unit ceils viaround(x, 0, Up).
Jobs (packages/jobs)
- New Inngest functions on
carbon/planning.inputs.changed:markPlanningStaleFunction(immediate; upsertsplanningState) andplanningRegenFunction(debounce 30 s, concurrency 1 per company; callsrunMrpin-process). The existing 3-hour cron stays as backstop. - New event
carbon/planning.inputs.changedinpackages/lib/src/events.ts; emitternotifyPlanningInputsChangedinproduction.service.ts(pattern:notifyScheduleInputsChanged), called from the chokepoints listed in §2.
ERP services (apps/erp/app/modules/production + purchasing)
releasePlannedOrder(client, { id, ... })— Make →insertJob+upsertJobMethod(the current Make path) and mark the orderReleased/linkjobId; Buy → create PO line. One-click from the row (no draft) unless warnings (§9a).releasePlannedOrderCascade(rootId)— firm the whole chain in one transaction, release the caller's permitted side, notify the counterpart (PlannedOrdersAwaitingRelease) for the rest (§9g).firmPlannedOrder/unfirmPlannedOrder(set/clearfirmedBy/firmedAt),updatePlannedOrder(qty/date on Firm),markPlannedOrdersReviewed(ids),returnOrphanedFirmOrdersToPlanning(ids?)(the §9e sweep; defaults to system-firmed orphans).- All planned-order mutations take the caller's loaded
updatedAtper row and reject drifted rows individually with a reconciliation payload (§9b). getPlannedOrders(worklist,GenericQueryFilters; default filter excludeslowConfidence),getPlannedOrderCascade(rootId)(peg tree),getItemTimePhasedPlan(itemId, locationId)(the MRP matrix),getLatestPlanningRun(locationId?),getPlanDiffSince(reviewedAt),getPlanningReadiness(companyId)(the §9c panel),getPlanningState(companyId).getSuggestedDemandProjection(client, { itemId, locationId })(§8, with the CV refusal shape).- Replace the drawer's
planning.update"order" action semantics: it firms/edits/releases planned orders rather than creating jobs +supplyForecast. - New route
POST api/planning/what-if→runPlanningWhatIf(permissionview: "production"orview: "sales"for the quote-side entry).
Workflow catalog (packages/workflows)
entities.ts: addplannedOrder(watch:status,exceptionType,dueDate,quantity— deliberately NOTcapacityConstrained/lowConfidence, which flip on regen); regen + check the catalog.moments.ts: addplanning.exceptionRaised+ itsraiseMomentcall site in the regen path (CI enforces the pairing).operations.ts: addreleasePlannedOrder,firmPlannedOrder(wrapping the ERP services above). Both check the §9f rails first: paused → skip with reason; dry-run → log the would-be action to workflow run history as Skipped-with-reason; cap → release up to the cap, queue the rest with a notice.
Notifications (packages/notifications + packages/jobs)
NotificationEvent.PlanningExceptions(topic: Planning) — digest of normal-confidence PastDue/Delay exceptions + newly overloaded capacity buckets + the daily autopilot ledger (§9f); InApp default, Email/Slack opt-in.NotificationEvent.PlannedOrdersAwaitingRelease(topic: Planning) — the §9g cross-team handoff, deep link to the pre-filtered worklist.
Agent (apps/erp/app/modules/agent)
- Restore the agent data tools (removed 2026-09-30, see "Ask the plan" above) and enable
them (READ-only classification + blocklist enforced in the tool itself). Verify the new planning service reads are
READ-classified in
tool-metadata.json(regen viapnpm run generate:mcp); add a planning-concepts docs page so the KB regeneration teaches the agent the standard terminology.
RPCs: get_production_planning / get_purchasing_planning read plannedOrder
as the supply/plan source (still union real supplyActual); for items with a current
planned order, quantityToOrder is the planned-order total, and
calculate_quantity_to_order computes only for items with no current plan (§9h).
UI Changes
Covered in §10. Files: apps/erp/app/routes/x+/production+/planning.tsx (+
purchasing), apps/erp/app/modules/{production,purchasing}/ui/Planning/,
ProductionPlanningOrderDrawer, DemandProjectionForm, quote/SO line drawers (CTP
entry), the planning readiness panel, the automation settings (production settings
page), and the worklist's live/diff banners + capacity strip. No new top-level routes
except api+/planning.what-if.ts.
Acceptance Criteria
Core cascade
- With COMMS-001 on a reorder policy and no job created, an MRP run produces a
plannedOrderfor COMMS-001 (qty per lot-sizing) and a pegged dependentplannedOrder/demand for ANT-PATCH-01 (×2) and its downstream materials — visible before any job exists. - The cascade is correct to full depth: COMMS (Make) → ANT-PATCH-01 (Make) → MAT-CF-LAM / MAT-KAPTON (Buy), each pegged to its parent.
- Explosion uses the lot-sized order quantity: a reorder round-up on the parent
pulls the rounded quantity of each component (regression test for
mrp-engine.ts:269). - Firm a planned order → it survives the next regen and still explodes its components; Planned orders are diff-written each run.
- Release a planned order → creates the real
job/PO, marks the orderReleased, and the next run does not double-count it. -
computePlannedOrderQuantityunit tests cover all five policies + min/max OQ,orderMultiple,lotSize,maximumInventoryQuantity; the parity test matchescalculate_quantity_to_orderon the fixture matrix; every result includes a trace whose steps recompute to the final quantity. - Planning time fence: with a non-zero
location.planningTimeFenceDays, planned orders whose release date falls inside it are auto-firmed withfirmedBy='system'and survive regen; a per-itemitemPlanning.planningTimeFenceDayswins over the location default in both directions (longer fence, and an explicit0exempting the item); resolved 0 = manual-firm-only. - Action messages over open orders: a live open job/PO due earlier/later than
its net requirement surfaces an Expedite/De-expedite/Cancel message; applying a
job reschedule routes through
notifyScheduleInputsChanged/updateJobOperationDueDate; a PO reschedule edits the PO line date. - Pegging completeness: a planned component order covering an existing job's
material line carries a
jobIdpeg (fixture: open job + component shortage).
Identity, idempotency, atomicity
- Two consecutive runs with no input changes produce byte-identical
plannedOrderrows including ids (diff-write proof), and zero workflow record events fire on the second run. - A failed run leaves the prior plan intact (atomic transaction, fault-injection test as in the 2026-08-12 hardening).
-
releaseDatenever lands on a non-working day for the location (fixture with a weekend-spanning lead time); Buy lead time offsets in calendar days then snaps backward to a working day.
Live plan
- Editing a sales-order line quantity triggers
carbon/planning.inputs.changed;planningStateis stamped immediately (MARK); within the debounce window a newplanningRunrow exists withtrigger='event',triggerReasonnaming the SO; the worklist banner shows both states ("Plan updating…" → "Plan updated"). - The 3-hour cron still runs and records
trigger='cron'runs. -
planningRundiff counts match a hand-computed fixture (N created, M updated, K deleted, rest unchanged).
Calm & control (§9)
- One-click Release: a warning-free row's Release button creates the job/PO
with no intermediate drawer; a
lowConfidenceorcapacityConstrainedrow opens the drawer instead. - Stable worklist: with the worklist open, a regen that changes 5 rows causes
zero visible row changes; the banner appears; Refresh shows the new state.
Releasing a row whose
updatedAtdrifted returns the reconciliation payload (browser test: edit an SO mid-session, then batch-release — 10 succeed, 2 reported as drifted). - Confidence gating: an item on the never-maintained default lead time
produces orders/messages with
lowConfidence = true+confidenceNote; they are absent from the default worklist filter and from the digest; visible and badged in "All messages". Setting a real lead time clears the flag on the next run. - Readiness panel: on the satellite dataset with seeded defects (default lead times, one stale PO, one zero-time routing), the panel shows correct counts and each deep link lands on the pre-filtered list.
- Bucket-attributed capacity: a fixture whose planned Make orders exceed one
work center's ladder hours in one week produces exactly ONE capacity exception
row (that work center + week) in the capacity strip with the contributing
orders listed inside; those orders get
capacityConstrained = truebut keep theirexceptionTypeuntouched; adding aworkCenterShiftclears both on the next run. - Orphaned firm sweep: cancel the demand behind a system-firmed order → next
regen flags it
Cancel; the sweep returns it to planning and the subsequent regen does not recreate it. A user-firmed orphan shows the message but is not swept by default. - Autopilot rails: with dry-run ON (the default), an auto-release workflow logs Skipped-with-reason and creates nothing; with dry-run OFF and a cap of 2, a regen producing 5 qualifying orders releases 2 and queues 3 with a notice; the pause switch stops the operation entirely; the digest's autopilot ledger lists what was released.
- Chain handoff: a production user without
purchasing_createreleases a mixed cascade → make orders release, the buy orders become Firm, and purchasing receivesPlannedOrdersAwaitingReleasewith a deep link showing exactly those orders. - One number: an item with a current planned order shows the same quantity in
the planning grid (
quantityToOrder) and the worklist; during the debounce window both surfaces show the "Plan updating…" indicator.
Capacity honesty
- Open-job supply is dated at
projectedCompletionAtwhen present: a job the scheduler projects 1 week late produces a Delay message on the dependent demand even though itsdueDateis on time.
Simulation / CTP
-
runPlanningWhatIfwith a hypothetical SO line returns a promise date, the net-new planned-order tree, capacity impact, estimated cost, and the assumption list — and writes nothing (row counts acrossplannedOrder/plannedOrderPeg/planningRun/forecast tables identical before/after). - The quote-line "Can we make it?" panel renders the what-if result — including the assumptions, verbatim — end-to-end in the browser.
Explainability
- The drawer renders the lot-sizing trace for a Fixed-Reorder-Quantity + order-multiple fixture exactly as the pure function's trace states it.
- Mark-reviewed persists (
reviewedAt); the diff banner counts only changes after the newestreviewedAt. - With data tools enabled, the in-app agent answers "why is there a planned order for ANT-PATCH-01?" using the planning reads (browser verification; READ-only — an attempted write tool call is refused by classification).
Programmable release + notifications
- A workflow on
plannedOrder.createdwith conditions (orderType Buy, cost threshold, release window) that callsreleasePlannedOrderauto-releases the fixture order (rails permitting) and is visible in workflow run history; the diff-write prevents re-fires on unchanged regens. -
planning.exceptionRaisedfires when an order transitions into PastDue on a fixture; catalog check (pnpm run check:workflow-catalog) is green. - A
PlanningExceptionsdigest reaches the planner (InApp) when new normal-confidence exceptions or overloaded buckets appear; low-confidence messages never notify.
Suggested projections
-
getSuggestedDemandProjectionmatches a hand-computed trailing-13-week average on steady fixture history; applying a suggestion writesdemandProjectionrows withforecastMethod='suggested'and populatedconfidence; the next run consumes them like any projection. - On a lumpy fixture (CV >
SUGGESTION_MAX_CV), the service returns the refusal and the UI shows the sparkline + "too irregular" state, with no number.
Gates
-
pnpm --filter @carbon/ee test(engine + readiness + RCCP + what-if + lot-sizing) andpnpm --filter @carbon/utils testgreen; scoped ERP + jobs typecheck green;pnpm run generate:typescommitted; catalog + MCP metadata regenerated. - Browser: worklist (live banner, diff banner, capacity strip, readiness link, one-click release, stable-under-regen behavior), cascade tree (incl. the cross-team handoff), time-phased matrix, drawer (trace, confidence note, firm/release, mark-reviewed), readiness panel, CTP panel, automation settings, and suggested projections render for the satellite dataset; Release/Firm/batch- release work end-to-end.
Risks
| Risk | Severity | Mitigation |
|---|---|---|
| Continuous regen churns the near-term plan ("nervousness") | Med-High | The planning time fence auto-firms inside the horizon; the worklist never re-renders under the user (§9b) — churn reaches sessions only as a banner; the diff banner makes it visible and attributed; debounce 30 s + concurrency 1/company caps run frequency. |
| Confidence gating hides a real problem behind a "low confidence" badge | Med | Nothing is deleted — the "All messages" view shows everything, badged with the reason; the readiness panel actively drives fixing the inputs that cause gating; gating criteria are few, explicit, and deterministic. |
| Regen ↔ workflow event feedback loop (a workflow's release triggers a regen which fires events…) | Med | Release/firm are terminal for the row (Firm/Released rows are never regenerated); watch columns are limited (and exclude the regen-flipped flags); the diff-write emits nothing for unchanged rows; the §9f cap bounds any loop's blast radius. Add a loop test: auto-release workflow + regen converges in one cycle. |
| RCCP over/under-states load (no sequencing, no labor gating) | Med | It is rough-cut by design and labeled so in the UI; bucket attribution keeps a miss localized to one row; it uses the same ladder windows and reservation hours as the scheduler, so the direction is right. Finite scenario scheduling is the deferred upgrade path. |
| CTP promise date read as a guarantee | Med | The assumption list is part of the API result and rendered verbatim; the label is "plan-based promise" everywhere; post-release the expedite what-if gives the finite answer. |
Lot-sizing drift between the TS fn and SQL calculate_quantity_to_order |
Med | One pure fn + parity test over a fixture matrix; TS is canonical, SQL is the mirror; §9h shrinks the SQL path to no-plan rows only. |
| Behavior change: "Make" no longer instantly creates a job | Low-Med | §9a: one-click Release from the row IS the old behavior for warning-free orders; the drawer only interposes when the system has something to say. Release notes cover the status chip. |
| Plan row-count explosion (every BOM level of every item) | Med | Default filters (normal-confidence action rows), pagination; the peg tree is opt-in drill-down; diff-write keeps table growth bounded (rows are reused, not re-minted). |
| Scheduler interaction (MRP recommends, scheduler owns job dates) | Med-High | Hard boundary: MRP writes planned-order dates only; job reschedules route through notifyScheduleInputsChanged/updateJobOperationDueDate; integration test covers the loop (MRP Delay message → apply → wave regen → next run sees new projectedCompletionAt). |
Netting on projectedCompletionAt makes MRP output depend on scheduler freshness |
Med | Fallback to dueDate when no projection; the scheduler's own event-driven wave + nightly replan keep projections fresh; planningRun records staleness cause if needed. |
| Customer automation misfires (bad rule, fat-fingered forecast) | Med | §9f: dry-run default ON, per-run cap, instant pause, daily ledger. Worst case with defaults is a log entry, not a purchase. |
| Agent data exposure | Low-Med | The direct executor already enforces READ classification + blocklist; planning reads are read-only; no write tools are exposed in v1. |
Migrating off supplyForecast breaks the grid mid-flight |
Med | Sequence: land plannedOrder + engine + grid read first; remove supplyForecast writes/delete last, same PR series. |
| Performance of the fused sweep + RCCP + readiness at scale | Low-Med | The 8M-row tenant runs in ~0.3 s today; RCCP and readiness are O(orders × ops) / O(items) over in-memory data; batch writes (500/chunk) as Phase-7 does; the findings doc's benchmark harness re-verifies. |
| Cycle handling regressions | Low | Reuse the existing cycle-as-leaf logic (mrp-engine.ts:189-211) unchanged; keep its regression tests. |
Deferred (explicitly post-v1)
- Scenario finite scheduling of planned orders — simulate the released plan
through the full scheduling engine under
capacityReservation.scenarioId(the column is already reserved for this). RCCP is the v1 capacity answer. - Planned Transfer generation (DRP) — the
'Transfer'enum value is reserved andwarehouseTransferis the release target, but multi-location netting logic is its own spec. - Statistical forecasting beyond trailing average (seasonality, Croston for intermittent demand — the principled answer to the CV-gate refusals) — the suggested-projection plumbing is the v1 foundation.
- Unified make+buy plan page — two cross-linked pages in v1, bridged by the §9g handoff.
- Retiring the SQL live grid (
calculate_quantity_to_order+ week-column RPCs) — §9h already shrinks it to no-plan rows; full retirement once the planned-order surfaces have fully taken over.
Open Questions
All resolved 2026-08-22 (Brad accepted the recommendations). Kept as the decision record.
Note (2026-09-08): the questions in this section belong to the Phase 2+ vision. Phase 1's open questions and their resolutions live in §P1.11.
- Materialize-on-release vs keep materialize-on-Make? — Resolved: true
planned-order layer. Real
job/PO created only on Release; Planned orders are disposable. Removes thesupplyForecastwipe. - Buy planned orders in v1? — Resolved: include Buy. Pegging is incomplete without it.
- Make/Buy: unified plan page or two cross-linked pages? — Resolved: two pages for v1, cross-linked in the cascade tree.
- Retire the live SQL grid recompute? — Resolved: keep in v1, bounded by the §9h coherence rule.
- Firm-order editability — Resolved: editable qty/date (Firm = "I own this order").
- Reorder-policy netting parity — Resolved: the parity fixture matrix is the acceptance gate.
Raised by the research pass — resolved 2026-08-22 (robust v1: all included)
- Planning time fence / auto-firm — Resolved: full auto-firm in v1,
evaluated on release date,
firmedBy='system'. Placement revised 2026-08-22 (Brad):itemPlanning.planningTimeFenceDaysper-item override +location.planningTimeFenceDaysdefault, matching the enterprise per-item standard anditemPlanning's existing planning-behavior field family. - Action messages on real open jobs/POs — Resolved: in v1, with the
scheduler-interaction path via
notifyScheduleInputsChanged. - Period-of-supply / POQ lot-sizing — Resolved: in v1 (TS-only fifth policy).
- Worklist quality-of-life — Resolved: all in v1 (mark-reviewed, batch-release, exception notifications).
Raised by the game-changer review — resolved 2026-08-22 (Brad: build these in v1)
- Continuous event-driven regen vs cron-only? — Resolved: continuous in
v1.
carbon/planning.inputs.changed+ MARK/WAVE (stamp + debounce 30 s + concurrency 1/company), cron demoted to backstop. Justified by the measured ~0.3–0.5 s full-company run. - Net open-job supply at due date or projected completion? — Resolved:
projectedCompletionAt(fallbackdueDate). Dual dates exist on this branch; simulation-derived Delay/Expedite messages are the point. - Capacity in v1: none, rough-cut, or full scenario scheduling? — Resolved: rough-cut in v1; scenario engine deferred.
- What-if/CTP in v1? — Resolved: yes —
runPlanningWhatIf(persist: false, plan delta + plan-based promise date), surfaced on quote/SO lines. - Delete-recreate vs diff-write regen? — Resolved: diff-write on a deterministic natural key — required by idempotency, plan diffing, workflow-trigger hygiene, and optimistic concurrency simultaneously.
- Peg sources — Resolved: add
jobId(job-material demand, mirroringdemandForecastSource); five-way exactly-one CHECK. - Transfer order type — Resolved: reserve
'Transfer'in the enum now; generation deferred. - Date math — Resolved: working-day offsets over the availability ladder, shared with the scheduler's need-by calculator; never naive day subtraction.
- Explainability scope — Resolved: trace + pegs + diff banner in v1; agent data tools enabled in v1 (mechanism already built, READ-only enforced).
- Workflow integration scope — Resolved:
plannedOrdertrigger entity +planning.exceptionRaisedmoment + release/firm operations in v1. - Suggested demand projections in v1? — Resolved: yes, trailing-average suggestions, planner-applied; statistical models deferred.
Raised by the annoyance review — resolved 2026-08-22 (Brad: implement the fixes)
- Does the review lifecycle tax the old one-click flow? — Resolved: one-click Release from the row is the primary action; the draft drawer interposes only on warnings; Firm is entered via a plain-language lock prompt.
- Does the live plan move under the planner? — Resolved: no live
revalidation on the worklist.
planningRun/planningStatewatcher banner + explicit Refresh; per-row optimistic concurrency with explicit reconciliation on batch ops. - How do we avoid the day-one wall of red? — Resolved: confidence-gated exceptions + the planning readiness panel. Low-confidence messages are excluded from defaults and digests, never deleted.
- Order-attributed vs bucket-attributed overload? — Resolved: bucket.
One exception per (work center, week) in
loadSummary; orders carry only a secondarycapacityConstrainedbadge;'Overload'removed from the exception enum. - Auto-firm zombie orders? — Resolved:
firmedByprovenance + Cancel exception on orphaned Firm rows + one-click return-to-planning sweep (system-firmed by default). - Automation blast radius? — Resolved: company-level pause / dry-run (default ON) / per-run cap + daily autopilot ledger.
- Cascade release across the make/buy permission boundary? — Resolved:
firm the chain, release the permitted side, notify the counterpart
(
PlannedOrdersAwaitingRelease). - Two numbers during the debounce window? — Resolved: grid reads the
planned order when one exists; live SQL only for no-plan rows; shared "Plan
updating…" indicator from
planningState. - Bad suggestions on lumpy demand? — Resolved: CV gate refuses with the sparkline instead of suggesting; Croston-class models deferred.
- CTP over-trust? — Resolved: the assumption list is part of the API result and rendered verbatim; "plan-based" label everywhere.
Changelog
2026-08-22: Created; all open questions resolved with Brad (recommendations accepted).
2026-08-22: Reconsidered against research (
.ai/research/mrp-v2-planner-ui.md, 8 systems + APICS). Adopted standard terminology; expanded the action-message model; added planning-time-fence/auto-firm andsuggestedDate/reviewedAt; reframed the UI to the SMB dated-decision worklist with the six-row matrix as drill-down; documented soft-vs-hard pegging and "quantity without source".2026-08-22: Renamed
real-mrp→mrp-v2. Scoped to robust v1 per Brad — pulled every deferral into v1 (time fence, open-order action messages, POQ, worklist QoL).2026-08-22: Game-changer rewrite (Brad: "build these in v1"). Added the five differentiators to v1: continuous event-driven regen (+
planningRun), capacity-honest netting (projectedCompletionAt) + rough-cut capacity,runPlanningWhatIf/CTP, self-explaining plan (trace, diff-write identity + diff banner, agent data tools), programmable release (workflow entity/moment/operations,PlanningExceptionsdigest). Fixed from the code review:jobIdpeg source,'Transfer'reserved, working-day date math,splitIndex+ partial-unique natural key, suggested demand projections. Updated all file references to the@carbon/planningextraction. Added the Deferred list.2026-08-22: Calm-by-default layer (Brad: "implement the annoyance fixes"). New §9 + supporting schema: one-click Release with warnings-only draft interposition and plain-language Firm prompt (
firmedBy/firmedAt); no-revalidation worklist withplanningState(new table) +planningRunbanner and per-row optimistic concurrency; confidence-gated exceptions (lowConfidence/confidenceNote) + planning readiness panel; bucket-attributed capacity (dropped'Overload'fromplannedOrderException, addedcapacityConstrained); orphaned-firm Cancel + return-to-planning sweep; autopilot rails (companySettingspause/dry-run/cap, dry-run default ON, autopilot ledger); cross-permission cascade handoff (PlannedOrdersAwaitingRelease); plan/grid number coherence (§9h); suggestion CV gate; CTP assumption list in the API result. Expanded acceptance criteria ("Calm & control" group) and risks accordingly.2026-08-22: Time fence placement revised (Brad): the fence lives on
itemPlanning.planningTimeFenceDays(per-item/location override, NULL = inherit) withlocation.planningTimeFenceDaysas the plant default — SAP/Oracle/Dynamics all fence per item, anditemPlanningalready owns the planning-behavior fields (reorderingPolicy, accumulation/rescheduling periods).2026-09-08: Re-scoped into phases (Brad). The single "game-changer v1" is split so the 80/20 slice ships first. Added §P1 — Phase 1: Planning Action Messages & Buyer/Planner Assignment: a focused persisted
planningActiontable (enumsplanningActionType= Order/Make/Expedite/Defer/Cancel/Increase/Decrease,planningActionStatus), a unifiedresponsibleEmployeeinheritance ladder (item → item-group → location → company; new columns onitemPlanning,itemPostingGroup,location,companySettings) with per-row assignee override, a singlecompanySettings.rescheduleToleranceDays(default 7) noise gate, diff-write regen, commitment-gated apply (auto-apply on uncommitted supply, "Review on document" on sent POs / released jobs), the two existing planning pages extended with a "my actions" worklist, and one printer-style ownership settings screen. All Phase-1 open questions resolved with Brad (§P1.11). The prior "game-changer v1" (planned-order cascade + Planned→Firm→Released lifecycle, pegging, continuous regen, rough-cut capacity, what-if/CTP, self-explaining plan, programmable release, §9 calm-by-default) is retained below as Phases 2+, deferred. Research:.ai/research/mrp-planning-actions.md; run record:.ai/runs/2026-09-08-mrp-planning-actions.md.2026-09-09: Ladder refinement (Brad): the item-group tier is now location-specific — the tree is all → location → item group (per-item leaf + per-message assignee still on top). Item-group ownership moves off a column on
itemPostingGroupinto a sparseitemPostingGroupResponsibilitytable keyed(companyId, locationId, itemPostingGroupId), mirroring the printer AssignmentsCard inheritance tree. Updated §P1.2 (data model), §P1.3 (resolver), §P1.8, §P1.11.2026-09-11: CodeRabbit review round (PR #1601) folded in. Generation runs in its own atomic transaction after Phase-7 and failures propagate (no swallow); one action per target precedence (Cancel → Expedite/Defer → Increase/Decrease); vanished Dismissed rows are deleted (retired) so the natural key can't block a returning need; tolerance boundary fixed as strictly
>withCHECK (>= 0)+ 0–365 validation; commitment gate keys onisPurchaseOrderLocked(status)only (NOTorderDate, which defaults to today on insert); apply binds to the persisted action by id+companyId withstatus='Open'(IDOR guard); job Expedite/Defer =updateJob({dueDate})+notifyScheduleInputsChanged("reorder"), never operation-date writes;itemPostingGroupneedsUNIQUE ("id","companyId")before the responsibility FK (verified: PK is("id")alone); explicitENABLE ROW LEVEL SECURITYonitemPostingGroupResponsibility; scheduled runs'userId: "system"is a real seeded user row (20230123004317_companies-rls.sql).2026-09-11:
demandProjectionnow DOES gain a column —consumedQuantity(forecast consumption, migration20261006130001), superseding this spec's "demandProjection gains no columns" scope note (§ suggested projections, ~line 1230; that section's own scope is unchanged — suggestions still write ordinary rows). Design + rationale:.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md.2026-10-04: Phase 1 (§P1, planning action messages + responsible-employee assignment) implemented on
mrp-action-suggestions(PR #1601; plan.ai/plans/2026-09-08-mrp-planning-actions.md12/12). The same branch also ships the planning horizon / time fence (.ai/plans/2026-10-01-planning-horizon.md) and a company-chosen daily MRP run time. Phases 2+ are unchanged and not started, so this spec stays out ofimplemented/.