Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

docs(specs): sales rules — sales-document rule engine spec and research (#1368)

Naveen Kashyapbdd507335a56
diff --git a/.ai/plans/2026-08-15-merge-rule-tables.md b/.ai/plans/2026-08-15-merge-rule-tables.md
new file mode 100644
index 0000000000..ef16eb8eb9
--- /dev/null
+++ b/.ai/plans/2026-08-15-merge-rule-tables.md
@@ -0,0 +1,114 @@
+# Implementation plan — Sales Rules on a unified `enforcementRule` table
+
+- Date: 2026-08-15
+- Spec: `.ai/specs/2026-08-11-item-rules.md`
+- Scope of this plan: the **data model and code layer** — create the unified rule table, move the shipped Storage Rules onto it, and build the sales family on top. The sales enforcement gates, notifications, and acknowledgment evidence are specified in the spec's Phase 1–3 and planned separately.
+
+## Starting point
+
+`storageRule`, `storageRuleItemAssignment`, and `storageRuleWorkCenterAssignment` are **live in production** with customer data. The engine (`@carbon/utils`), the evaluator shape (`@carbon/ee`), and the violation modal already exist and work.
+
+What does not exist yet: any sales-family table, column, or code.
+
+So the work is: build the unified table, migrate the one shipped family onto it, then add the second family. There is no intermediate per-family sales table at any point — building one and then folding it in would mean two production table transitions instead of one.
+
+## Design decisions
+
+| # | Decision | Choice |
+|---|----------|--------|
+| D1 | Table name | `enforcementRule` — "enforcement" is the word the spec and code already use (enforcement gates, evaluate → violations → block/acknowledge). Rejected: bare `rule` (collides conceptually with `configurationRule`/`pricingRule`/`approvalRule`), `businessRule` (vague). UI labels stay "Storage Rules" / "Sales Rules". |
+| D2 | Discriminator | `family enforcementRuleFamily NOT NULL` — enum `('storage','sales')`. |
+| D3 | Surfaces | One `enforcementRuleSurface` enum: the 11 transaction values + `quoteLine`, `salesOrderLine`. Cross-family subscription is blocked by per-family CHECK (`surfaces <@ ARRAY[…]`) rather than by the column type. `transactionSurface` is dropped once nothing references it. TS keeps per-family unions in `@carbon/utils`, independent of the DB enum. |
+| D4 | PK / ids | House composite PK `("id","companyId")`, `DEFAULT id()`. Existing `xid()` storage ids are TEXT and carry over unchanged. |
+| D5 | Storage-only columns | `targetType` (enum `enforcementRuleTargetType`, values `item`/`workCenter`) NOT NULL DEFAULT `'item'`; `appliesToAll` NOT NULL DEFAULT FALSE. CHECK pins sales rows to `targetType='item'`, `appliesToAll=false`. |
+| D6 | Item filters | `filteredItemTypes`/`filteredItemGroupIds` TEXT[] NOT NULL DEFAULT `'{}'`, `filteredItemMatchAll` NOT NULL DEFAULT FALSE. The shipped storage columns are nullable, so the migration normalizes with COALESCE. |
+| D7 | Uniqueness | `UNIQUE (companyId, family, name)` — the same name may exist once per family. |
+| D8 | Assignments | Two tables, not one polymorphic: `enforcementRuleItemAssignment` (PK `(itemId, ruleId)`, **both** families) and `enforcementRuleWorkCenterAssignment` (PK `(workCenterId, ruleId)`, storage only). A polymorphic `targetId` cannot carry a real FK, and losing `ON DELETE CASCADE` from `item`/`workCenter` would leave orphaned pins. Both get composite FK `(ruleId, companyId) → enforcementRule(id, companyId)` CASCADE. |
+| D9 | Assignment RLS | Each family keeps the permission its shipped table required — storage item pins `parts_*`, work-center pins `resources_*`, sales pins `sales_*` — so no caller's authorization changes. The item table serves both families, so its policies resolve the pinned rule's family with an EXISTS. Normalizing storage item pins to `inventory_*` is deliberately NOT part of this work: it would revoke access from any role holding `parts` but not `inventory`. Recorded as a separate follow-up. |
+| D10 | Rule RLS | SELECT: `get_companies_with_employee_role()`. INSERT/UPDATE/DELETE: `(family='storage' AND companyId ∈ inventory_<action>) OR (family='sales' AND companyId ∈ sales_<action>)`. UPDATE needs both `USING` and `WITH CHECK` so a row cannot be edited into a family the actor lacks. |
+| D11 | Acknowledgment | `enforcementRuleAcknowledgment`, written by the sales family only; `documentType` CHECK widens later if storage ever persists evidence. |
+| D12 | customFieldTable | PK is `("table")`, so the unified table gets ONE registry row — rename the shipped `('storageRule','Storage Rule','Items')` row to `('enforcementRule','Rule','Items')`, which carries every company's existing storage-rule custom-field definitions across via `ON UPDATE CASCADE`. **Product tradeoff: one shared custom-field namespace across both rule editors.** Per-family custom fields would be a UI filter, not a schema change. |
+| D13 | Unchanged | Plan keys `STORAGE_RULES`/`SALES_RULES`, the `@carbon/utils` engine, `RuleViolationModal`/`useRuleViolations`, all routes/URLs/sidebars, exported service function names. |
+
+## Tasks
+
+### T1 — Migration: unified schema
+
+`pnpm db:migrate:new enforcement-rules-table`
+
+1. `CREATE TYPE "enforcementRuleFamily"` and `"enforcementRuleSurface"` (13 values, D3).
+2. `ALTER TYPE "storageRuleTargetType" RENAME TO "enforcementRuleTargetType"` — same two values, generalized name.
+3. `CREATE TABLE "enforcementRule"` per D2–D7: house template (composite PK, `companyId` FK CASCADE, audit columns incl. `updatedBy`, `customFields`), indexes on `companyId`, `createdBy`, and partial `(companyId, family)` / `(companyId, targetType)` where `active`.
+ - CHECKs: severity, surfaces non-empty, the two per-family surface subsets, and the sales-shape constraint.
+4. Assignment tables per D8; acknowledgment table per D11.
+5. RLS per D9/D10 — four policies each, named exactly `SELECT`/`INSERT`/`UPDATE`/`DELETE`, schema-qualified, helper results cast `::text[]`.
+ - **Trap to avoid:** in the item-assignment `EXISTS`, an unqualified `"companyId"` binds to the *inner* rule table, making the tenant correlation a tautology. Qualify the outer row: `r."companyId" = "enforcementRuleItemAssignment"."companyId"`.
+
+### T2 — Migration: move the shipped storage rules, drop the old schema
+
+`pnpm db:migrate:new migrate-storage-rules-into-enforcement-rules`
+
+One transaction, every insert `ON CONFLICT DO NOTHING` so a partial re-run is a no-op:
+
+1. `INSERT INTO "enforcementRule" … SELECT …, 'storage'::"enforcementRuleFamily", …, "surfaces"::text[]::"enforcementRuleSurface"[], COALESCE("filteredItemTypes",'{}'), … FROM "storageRule"`.
+2. Item pins from `storageRuleItemAssignment`; work-center pins from `storageRuleWorkCenterAssignment`.
+3. `customFieldTable` rename per D12 (the `customField` rows follow via `ON UPDATE CASCADE`).
+4. `DROP TABLE` the three old tables (assignments first), then `DROP TYPE "transactionSurface"`.
+
+Then `pnpm db:migrate` → `pnpm run generate:types`.
+
+**Verify the data move with real rows before trusting it** — seed a rule with a NULL filter trio, a multi-surface rule, a work-center-target rule with `appliesToAll`, and a pin; confirm after migration that the trio normalized, the surface array cast, the target fields survived, and the pin landed.
+
+### T3 — `@carbon/ee` evaluator/service layer
+
+- `rules/storage/service.ts` + `server.ts` — point every query at `enforcementRule` / the new assignment tables and add `.eq("family","storage")`; stamp `family` on inserts.
+- New `rules/sales/` — `service.ts`, `server.ts` (`evaluateSalesRuleLines`), `context.ts` (`buildSalesRuleLineContext`), `index.ts`, mirroring the storage structure.
+- **The item pin table is shared, so a pin does not identify a family.** Resolve pinned rules against a family-filtered rule fetch in a second pass — not a PostgREST embed, which would return the other family's rule. This applies to both families.
+- Keep family-neutral helpers (`isBlocked`, `dedupeViolations`, the item-filter matcher, the itemCost-embed flattener) at the `rules/` root, not inside `storage/` — otherwise `sales/` has to reach into the storage evaluator for them, and a third family would too.
+
+### T4 — ERP module layer
+
+- Write the admin CRUD **once**, parametrized by family, in `~/modules/shared` (`getEnforcementRules`, `getEnforcementRule`, `upsertEnforcementRule`, `deleteEnforcementRule`, `getEnforcementRuleAssignmentCounts`). Duplicating it per module means two copies of the same query drifting apart.
+ - The `family` argument is a union rather than a literal, which drops PostgREST's inferred row type to `any` — state the return type explicitly so callers get a real row.
+- Point the storage-rules routes at it with `"storage"`; build the sales-rules routes with `"sales"`.
+- Custom-field hooks in both rule editors key off `"enforcementRule"` (D12), not a per-family table name.
+
+### T5 — Regenerate artifacts
+
+`pnpm run generate:types`, `pnpm -w run generate:mcp`, and the swagger schema. If the local Supabase CLI ships a newer PostgREST than the committed schema was generated with, a full regen will churn thousands of unrelated lines — splice only the affected table keys instead and verify the untouched keys are byte-identical.
+
+### T6 — Tests
+
+- Family-filter assertions in the `@carbon/ee` service/evaluator tests; fixture rows gain `family`.
+- **Cross-family isolation test** — a pin pointing at the other family's rule must never enter evaluation. Cover both directions; the guard is query-level now, so nothing structural catches a regression.
+- Mutation-check the isolation test: remove the guard, confirm the test fails, restore it. A test that cannot fail is not protection.
+
+### T7 — Docs
+
+- `modules/inventory/AGENTS.md` + `modules/sales/AGENTS.md`: shared table, family filtering, shared CRUD, and the "resolve pins against a family-filtered fetch" rule.
+- `packages/utils/AGENTS.md`, `packages/ee/AGENTS.md`.
+- `.claude/rules/inventory-system.md` — the rule-table lineage and the family-filter requirement.
+- Any comment or docstring naming `transactionSurface`, `storageRuleTargetType`, or a per-family rule table is stale the moment T2 lands.
+
+## Verification
+
+```bash
+pnpm db:migrate && pnpm run generate:types
+pnpm exec turbo run typecheck --filter=@carbon/utils --filter=@carbon/ee --filter=@carbon/database --filter=@carbon/jobs --filter=erp --filter=mes
+pnpm --filter @carbon/utils test && pnpm --filter @carbon/ee test && pnpm --filter @carbon/jobs test
+pnpm run lint
+# no code may still reference the dropped tables:
+git grep -nE '\.from\("storageRule' -- apps packages
+git grep -n "storageRuleItemAssignment\|storageRuleWorkCenterAssignment" -- apps packages ':!packages/database/supabase/migrations' ':!packages/database/src'
+```
+
+Then, with a rebuilt dev stack and a logged-in user: a storage rule blocks a receipt post, a sales rule blocks a quote line, and the assignments drawer works on a part for both families. **The RLS policies cannot be verified any other way** — typecheck, tests, and a schema diff all pass on a policy whose tenant correlation silently does nothing.
+
+## Risks
+
+- **Production data migration.** This moves a shipped table with customer data. Mitigations: rules are low-volume config rows, the move is one transaction, inserts are idempotent, the enum array converts via `::text[]::new[]`, and nothing in the migration depends on app code — self-hosted instances run it unattended.
+- **RLS is the hardest part to review.** Per-family OR-predicates plus an EXISTS-correlated assignment policy replace four flat per-table policies. Read the policy SQL in T1 more carefully than anything else in the change.
+- **Query-level isolation replaces structural isolation.** With one table and one shared pin table, nothing in the schema stops a family leak — only the `family` predicate on every read does. That is what T6's isolation test exists to hold.
+- **Shared custom-field namespace** (D12) is a visible behavior change for any company that has storage-rule custom fields today.
+- **One enum now grows on both axes.** `enforcementRuleSurface` gains values for warehouse and sales work alike; accepted knowingly as the cost of the single table.
+- Generated types lose per-table narrowing (`surfaces` becomes the 13-value union on every row); TS narrowing by `family` compensates in `@carbon/ee`.
diff --git a/.ai/research/2026-08-11-item-rules.md b/.ai/research/2026-08-11-item-rules.md
new file mode 100644
index 0000000000..0a8459f2dc
--- /dev/null
+++ b/.ai/research/2026-08-11-item-rules.md
@@ -0,0 +1,49 @@
+# Item Rules — codebase research for a sales-document rule engine
+
+**Date:** 2026-08-11
+**Question:** How should Carbon implement "item rules" — configurable *if-condition-then-error/warn* rules that fire when items are added to quotes and sales orders (e.g. "if item type is X and customer location is Y, block") — with one common error interface so multiple checks never stack separate modals? What existing infrastructure should it build on, and what data is available at the enforcement points?
+
+Unlike most research files, this one surveys Carbon's own codebase rather than competitors: the request explicitly said "base it off storage rules," so the research questions were (1) what the storage-rules engine actually is, (2) how customer/location data reaches sales documents, and (3) what interstitial-check patterns already exist at line-add time. All findings verified against source; file references are the citations.
+
+## 1. The storage-rules engine — and the naming surprise
+
+The feature to clone began life under the exact name being requested: the original migration is `packages/database/supabase/migrations/20260507120000_item-rules.sql` creating a table `itemRule`, later renamed `itemRule → customRule → storageRule` (`20260603130000`). The underlying engine is a **generic predicate engine**, not storage-specific. Three layers:
+
+**Pure engine** (`packages/utils/src/storage-rules.ts` + `field-registry.ts`, client-safe, no I/O):
+- Condition AST: `{ kind: all|any|none, conditions: [{ field, op, value }] }`; operators `eq, neq, in, notIn, isSet, isNotSet, gt, lt` (`storage-rules.ts:16-24, 91-107`).
+- JIT-compiled predicates with an FNV-1a-keyed 256-entry LRU (`compileRule`/`compileWithCache`, `:269/:317`).
+- **Required-field semantics**: any non-presence condition whose field resolves empty emits "`{label}` is required" *before* predicate evaluation (`findFirstMissingRequiredField`, `:430-448`) — rules double as presence checks.
+- Message `{token}` interpolation incl. `{condition[n].name}` id→label resolution (`interpolateMessage`, `:377-417`).
+- A field registry (`FIELD_REGISTRY`) declaring exactly what rules may reference, with per-surface context availability (`SURFACE_CONTEXT_AVAILABILITY`, `:566`) enforced by validator and an anti-drift test. `item.customFields.*` paths are synthesized dynamically (`field-registry.ts:319-333`) — the extensibility valve.
+- Item-scoped broadcast filtering: `filteredItemTypes`/`filteredItemGroupIds`/`filteredItemMatchAll` + `itemRuleAppliesToItem` (`:518-535`).
+
+**Server evaluator** (`packages/ee/src/storage-rules/server.ts`): `evaluateLinesForSurface()` (`:323`) loads rules (explicit assignments + filtered broadcasts), batch-loads context rows, compiles, evaluates, dedupes. `isBlocked(violations, acknowledged)` (`:56`): any `error` blocks unconditionally; `warn`s block until acknowledged. Runs with `getCarbonServiceRole()` (RLS bypassed) from route actions — the route's `requirePermissions` is the action gate. Plan-gated via `packages/ee/src/plan.ts` `FEATURE_PLANS` — which, notably, **already contains an `ITEM_RULES` key** (`plan.ts:12`).
+
+**The common error interface** (`packages/ee/src/storage-rules/violation-modal.tsx` + `use-violations.tsx`): one modal grouping all violations into Errors/Warnings; confirm disabled on any error; warnings-only shows "Acknowledge & continue" which re-posts the same FormData with `acknowledged=true`. Call sites swap `fetcher.submit` for `rules.submit` and render `<rules.ViolationModal/>`. Canonical server wiring: `apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx:34-111`.
+
+**The gap:** the surface enum covers only inventory + MES surfaces; `RuleContext` has no customer root. Those are the two extension points — everything else is reusable as-is.
+
+## 2. Customer classification and ship-to country
+
+- `customer.customerTypeId` → `customerType`; `customer.customerStatusId` → `customerStatus` (`20230123004612_suppliers-and-customers.sql:206-233`). Both nullable FKs.
+- Ship-to country: `customerLocation.addressId → address.countryCode`. **Countries are alpha-2 codes app-wide**: migration `20240928155702_country-codes.sql` dropped `country.id` and made **`alpha2` the primary key**, with `address.countryCode` TEXT referencing it. The shared `Country` selector already uses alpha2 values (`~/components/Form/Country.tsx:31-34`); tax views join on it; CSV import documents it (`imports.models.ts:584`). ⇒ rule ASTs store alpha2; evaluation is a direct string comparison.
+- Quote and salesOrder headers both carry `customerId` + nullable `customerLocationId`. Quotes have a ready country view (`quoteCustomerDetails.customerCountryCode`, `20240715135710`); sales orders resolve via the `getCustomerLocation` embed (`sales.service.ts:580-591`).
+- `customerLocationId` being nullable is a design point, not an obstacle: a rule referencing `customer.location.countryCode` on a document without a ship-to hits the engine's required-field semantics → "Customer location is required," inheriting the rule's severity (fail closed, helpfully).
+
+## 3. Line-add flows and existing interstitials
+
+- Create actions: `x+/quote+/$quoteId.new.tsx` (validate → `upsertQuoteLine`) and `x+/sales-order+/$orderId.new.tsx` (validate → `upsertSalesOrderLine`); edit actions in the `$lineId.details.tsx` siblings. Both forms read the document header from route data, so `customerId` is in scope client-side at line-add time.
+- **No competing blocking modal exists on sales-line add today.** The only interstitials: the inline, non-blocking supersession notice in the shared `Item` selector (`~/components/Form/Item.tsx:398-433`) and the quote-only `ConfiguratorModal`. There is no credit-hold, MOQ, price-floor, or "not sellable" check anywhere in the sales module — the one-modal goal is achievable by simply routing the new check through the existing violation interface.
+- Item type is available on the submitted line (`quoteLine.itemType`; `salesOrderLine.salesOrderLineType`, a wider enum incl. Comment) and client-side via the `useItems()` store; the evaluator re-verifies from `item.type` server-side.
+
+## 4. What becomes possible beyond the motivating rule
+
+With item + customer + line context, one engine covers a family of otherwise-bespoke features: export control (item flag × customer country), customer-on-hold (a credit-hold feature for free), obsolescence warnings folded into the same modal, tracking-discipline warnings, unreleased-revision warnings, and document-hygiene required-field rules. Custom fields on item and customer make any company-defined flag rule-able with zero code change. Future surfaces (purchasing/AVL — subcontracting a controlled part *is* an export; margin floors once price/qty context is added) reuse the same machinery.
+
+## 5. Design conclusion (carried into the spec)
+
+Separate `itemRule` table + Items-module home (clean `parts_*` permissions, own sidebar entry, own DB enum `itemRuleSurface` — do not extend the storage `transactionSurface` enum), **shared** pure engine, evaluator pattern, and violation modal. Service-role evaluation like storage rules. Enterprise plan gate on the existing `ITEM_RULES` key. Alpha-2 country values. Missing ship-to → required-field semantics. Notifications through the existing notify fan-out plus a persisted `itemRuleAcknowledgment` table — an improvement over storage rules, where acknowledgments are only a transient form flag. Naming: `item-rules`, following the established storage-rules / pricing-rules / approval-rules family; the configurator's `$itemId.rule` routes are a known collision to steer around.
+
+Two stale-doc findings for whoever touches the engine: `packages/utils/AGENTS.md` described `storage-rules.ts` as "Supabase storage bucket access policies" (it is the rule engine), and older references to a `db:build` script are dead.
+
+**Spec:** `.ai/specs/2026-08-11-item-rules.md`
diff --git a/.ai/research/2026-08-12-item-rules-enforcement-surface.md b/.ai/research/2026-08-12-item-rules-enforcement-surface.md
new file mode 100644
index 0000000000..4b0cd3fb49
--- /dev/null
+++ b/.ai/research/2026-08-12-item-rules-enforcement-surface.md
@@ -0,0 +1,103 @@
+# Item Rules — enforcement surface audit
+
+**Date:** 2026-08-12
+**Question:** Item rules fire when an item is added to a quote line or sales order line. Where *else* can an item reach a sales document, and what events should force re-evaluation? This audit exists to decide where enforcement belongs before more call sites are added one at a time.
+
+Like the 2026-08-11 research file, this surveys Carbon's own codebase rather than competitors. Every claim below is cited to source; the citations are the evidence. Findings were produced by six parallel code audits (ERP write paths, edge functions and background jobs, external/API surfaces, context-drift triggers, the sales pipeline, and architecture options) and the load-bearing ones were re-verified by hand.
+
+## 1. What is enforced today
+
+`evaluateItemRuleLines` (`packages/ee/src/rules/item/server.ts:72`) is called from **exactly four places in the repo**, all ERP route actions:
+
+| Route | Surface |
+|---|---|
+| `x+/quote+/$quoteId.new.tsx:77` | `quoteLine` create |
+| `x+/quote+/$quoteId.$lineId.details.tsx:200` | `quoteLine` update |
+| `x+/sales-order+/$orderId.new.tsx:86` | `salesOrderLine` create |
+| `x+/sales-order+/$orderId.$lineId.details.tsx:152` | `salesOrderLine` update |
+
+There are no DB triggers, no RLS involvement, and no service-layer checks. `itemRuleSurface` has exactly two values (`20260810214426_item-rules-sales.sql:4`), so no other surface is even expressible.
+
+## 2. The write surface is non-exhaustible
+
+**14 entry points can put an `itemId` on a sales line; 4 are enforced.** Collapsed by underlying writer — 9 writers, 2 enforced:
+
+| Writer | Reached from | Enforced |
+|---|---|---|
+| `upsertQuoteLine` (`sales.service.ts:3788`) / `upsertSalesOrderLine` (`:5528`) | the 4 line routes | route only |
+| `convert` edge fn — quote→SO (`convert/index.ts:691`) | `$quoteId.convert.tsx:72`; **unauthenticated** `api+/sales.digital-quote.$id.tsx:92` | no |
+| `convert` edge fn — RFQ→quote (`convert/index.ts:1231`) | `sales-rfq+/$rfqId.convert.tsx:25` | no |
+| `get-method` — `quoteToQuote` (`get-method/index.ts:5724`) | `$quoteId.duplicate.tsx:29` | no |
+| `upsertQuoteLine` via CAD drag (`$quoteId.drag.tsx:157`) | mints a part, then a line | no |
+| `insertSalesOrderLines` (`sales.service.ts:1955`) | **MCP only — no in-app caller** | no |
+| Paperless Parts (`packages/ee/src/paperless-parts/lib/lib.ts:2770`, `:3022`) | inbound webhook → Inngest, service role | no |
+
+Two of these are structural, not incidental:
+
+**The MCP executor makes route-level enforcement unsound.** `apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts:84` resolves *any named export* of `sales.service.ts` and invokes it under an OAuth or `carbon-key` identity. The blocklist (`mcp-blocked-tools.ts:5-12`) has three entries, none sales-related, so `sales_upsertQuoteLine`, `sales_upsertSalesOrderLine`, `sales_insertSalesOrderLines`, and `sales_convertQuoteToOrder` are all callable. The same function the enforced route protects is reachable unprotected. That `insertSalesOrderLines` has no in-app caller and exists only because MCP exposes it is the clearest evidence that writer #10 is a matter of time.
+
+**The digital-quote accept path has no employee session.** `api+/sales.digital-quote.$id.tsx:92` runs service-role with `userId` spoofed to `quote.createdBy`; the only credential is the share-link id. Whatever runs there cannot be warn-and-acknowledge — there is nobody to show a modal to.
+
+### Related pipeline findings
+
+- **A standalone sales invoice reaches GL revenue with no upstream document.** `x+/sales-invoice+/new.tsx:42` has a default branch creating an invoice with no source document; `$invoiceId.new.tsx:71` then adds item-bearing lines (`itemId` required for Part/Service/Material/Tool/Consumable, `invoicing.models.ts:266`), guarded only by `requireUnlocked` + `create: "invoicing"`.
+- **RFQ→quote conversion auto-creates item master rows.** `convert/index.ts:967-1017` mints an `item` for every RFQ line without one (`type: "Part"`, `active: false`, hardcoded defaults), back-fills `salesRfqLine.itemId`, then inserts quote lines from them. These items carry no `itemRuleAssignment` rows, so assignment-based rules cannot match and attribute-based rules see placeholder values. Quote→SO then flips them `active: true` (`convert/index.ts:695`).
+- **Shipment lines are safe by construction.** There is no add-line route and no shipment line form; every insert is edge-function-derived from a sales order line. An item cannot reach a shipment without an SO line.
+
+## 3. Three paths execute no Carbon TypeScript at all
+
+This is what decides the architecture. App-layer enforcement **cannot be made complete** as currently architected:
+
+1. **Direct PostgREST.** The documented integration model is a supabase client with a `carbon-key` header (`README.md:443-471`); the published OpenAPI dump advertises `POST /quoteLine` (`swagger-docs-schema.ts:1650`); and Carbon's own shipped example does `client.from("quoteLine").insert(...)` (`contrib/building/examples/quote-configurator/app/lib/carbon.server.ts:259`). The only gate is RLS (`20260228000000_rls-refactor-3.sql:1639`), which understands `companyId` and `sales_create` and nothing else. A service-role key has no RLS at all.
+2. **`SECURITY DEFINER` RPCs with weaker guards than the tables they write.** `create_rfq_from_models_v2` (`20250314184246_opportunity-refactor.sql:298-302`) is guarded by `has_role('employee') OR has_valid_api_key_for_company()` with **no scope check**, is never `REVOKE`d, and is published at `swagger-docs-schema.ts:85486`. A zero-scope API key can create sales RFQs.
+3. **Service-role paths with no user session** — the digital-quote accept route and the Paperless Parts Inngest job. RLS is off by construction; the only guards are hand-written in each handler.
+
+Unrelated but found en route: five tables still carry the legacy blanket API-key policy from `20240821150639_api-key-all-tables.sql` (including `quoteOperationWorkInstruction`), which ignores scopes entirely.
+
+## 4. Defects in the shipped implementation
+
+Independent of any scope decision. The first two were hand-verified.
+
+- **Drop shipments evaluate the wrong destination.** The evaluator reads `salesOrder.customerLocationId` (`$orderId.new.tsx:95`), but a drop shipment's real ship-to is `salesOrderShipment.customerLocationId`, required when `dropShipment` is set (`sales.models.ts:757-776`). A country rule can clear an order that ships elsewhere — no bypass required. This defeats the motivating export-control use case.
+- **`acknowledged` is client-supplied with no server-side state.** The server reads `formData.get("acknowledged") === "true"` (`$quoteId.new.tsx:76`) and nothing records that a violation was ever displayed; the client replays the original FormData with the flag appended (`use-violations.tsx:150-160`). A crafted first submit skips every `warn` gate. Errors still block unconditionally (`isBlocked`, `rules/storage/server.ts:55-64`), so the blast radius is warnings only. The MES picking route defends against the analogous hazard (`apps/mes/.../picking.$pickingListId.status.tsx:65-93`); the rules layer does not.
+- **Quantity rules are dead on quotes.** Both quote call sites hardcode `quantity: 1` (`$quoteId.new.tsx:85`, `$quoteId.$lineId.details.tsx:208`); the real quantity is first chosen at conversion, which is unenforced.
+- **`itemRuleAcknowledgment` has six writers and no reader.** The evidence log is never queried, surfaced, or reported on.
+
+## 5. The verdict is point-in-time and never revisited
+
+Context is resolved live at write (`rules/item/server.ts:91-114`) and never snapshotted. Drift vectors:
+
+- **Ship-to is editable after lines exist.** The only guard is a status lock, and `isSalesOrderLocked` (`sales.models.ts:963-971`) leaves Draft, In Progress and Needs Approval editable. Live paths: `x+/quote+/update.tsx:88-104`, `x+/sales-order+/update.tsx:95-112`.
+- **Addresses are shared by reference.** `customerLocation` is a thin join to `address`; editing a location mutates the shared `address` row in place (`sales.service.ts:2998-3003`), retroactively changing the resolved country for every document pointing at it. CSV import does this in bulk (`import-csv/index.ts:629-634`).
+- **Deletes silently null the inputs.** Deleting a customer type or status nulls the customer field (`ON DELETE SET NULL`, `20230123004612:222-223`); deleting a location nulls `customerLocationId` (`20241205165946:5,14`), converting a country rule into a required-field violation.
+- **Rule authorship has no backfill.** No trigger, no Inngest event, no matview. A line saved before a rule existed renders clean forever.
+- **Supersession diverges from the sales line.** Production-side paths redirect to the successor item (job explosion `get-method/index.ts:6112-6128`, MRP, picking `inventory.service.ts:3352-3358`) while the sales line keeps the original `itemId` — so a Make-to-Order line can build a different item than the rule cleared.
+
+## 6. Precedent: Carbon already has terminal-gate validation
+
+`x+/shipment+/$shipmentId.post.tsx` is the reference implementation, and the pattern is running in seven places (receipt post, shipment post, stock transfer status, warehouse transfer status, inventory adjustment, plus MES). The shape:
+
+1. `requirePermissions` for the actor, then a **service-role** client so the check sees full truth (`:36`)
+2. read `acknowledged` off the form (`:33`)
+3. load **every line on the document** (`:37-44`)
+4. accumulate violations across surfaces into one array (`:68-99`)
+5. `dedupeViolations` → `isBlocked(deduped, acknowledged)` — any error blocks; warns block until acknowledged
+6. **return** (not throw) `{ violations, ruleNames }` (`:102-109`)
+7. client: `useRuleViolations` + `RuleViolationModal`, acknowledge re-posts with the flag
+
+`getOverReceiptViolations` (`packages/utils/src/receiving.ts:24-68`) shows the same envelope carrying a *synthetic* violation with a pseudo rule id — the precedent for injecting non-configurable checks into the shared modal with zero new UI.
+
+Notably absent: there is **no credit-limit, customer-hold, or approval mechanism** anywhere in Carbon. `customerStatus` is a plain lookup whose only functional role is as an item-rule condition. Item rules *are* the intended mechanism for "this customer shouldn't be sold anything."
+
+## 7. Decisions taken (2026-08-12)
+
+- **Gate at lifecycle transitions, not at every write.** Item rules are a compliance control, and compliance fails at the document, not the line. A gate re-reads the whole document, so it covers writers nobody instrumented *and* catches staleness. Per-line checks stay for early feedback.
+- **Add item rules to shipment posting.** It is the last physical checkpoint, the plumbing already exists in that exact file, and it is the first moment a real shipped quantity exists.
+- **No nightly sweep.** Drafts are a scratchpad — users should be free to experiment, and the confirm gate catches it before it counts. Dropping it removes a cron, a new violation-state table, and notification-fatigue tuning. Accepted residual: rules authored *after* an order is confirmed are caught at shipment post rather than immediately.
+- **No rule-impact preview** ("what does my new rule break?"). Explicitly declined.
+- **No invoice-post gate for service-only orders — known gap.** Services are `Non-Inventory` items (`items.service.ts:4825`) that are never shipped, so a service-only order skips shipment entirely and goes straight to `To Invoice` (`convert/index.ts:552-560`). Shipment post therefore never fires for them. Deferred until a rule actually needs to apply to a service; invoice posting is the hook if so.
+- **No Postgres trigger for now.** Revisit only if a real bypass survives the gates — a UI/DB disagreement is worse than a known gap for a compliance feature.
+
+## 8. Carried into the spec
+
+Phase 3 (enforcement completeness): gates at quote finalize, sales order confirm, both conversion routes, and shipment post; hard-error checks pushed into `upsertQuoteLine`/`upsertSalesOrderLine` with `sales_insertSalesOrderLines` blocklisted in MCP; the three defects in §4 fixed; `Violation` extended with line attribution so a document-level modal can attribute and deep-link; engine relocated to `supabase/functions/shared/` with `export *` barrels (following `packages/database/src/sampling.ts:1-5`) to foreclose future hand-copying — `shared/tiptap.ts` has already drifted to 27 lines against 197.
diff --git a/.ai/specs/2026-08-11-item-rules.md b/.ai/specs/2026-08-11-item-rules.md
new file mode 100644
index 0000000000..87970c26c3
--- /dev/null
+++ b/.ai/specs/2026-08-11-item-rules.md
@@ -0,0 +1,343 @@
+# Sales Rules — commercial & compliance checks on sales documents
+
+- Status: **Ready to implement** (all design questions resolved)
+- Date: 2026-08-11
+- Research: `.ai/research/2026-08-11-item-rules.md`, `.ai/research/2026-08-12-item-rules-enforcement-surface.md`
+- Scope: Phase 1 (data model + engine extensions + admin UI + sales-line enforcement) · Phase 2 (notifications + acknowledgment evidence) · Phase 3 (enforcement completeness — terminal gates through invoice post, unbypassable hard errors)
+
+## Problem
+
+Carbon cannot enforce commercial or compliance restrictions when an item is added to a quote or sales order — e.g. *"if the item type is X and the customer's ship-to country is Y → block"*. Manufacturers need this for export control, distributor-only parts, and customer-status gating.
+
+Two constraints shape the design:
+
+1. **One combined error interface.** All violations on a submission must resolve into a single dialog — never stacked modals, never one dialog per rule.
+2. **This is a compliance control, not a hint.** It has to hold at the points that matter, not only where the UI happens to call it — including the paths that skip the normal flow. Carbon lets a user raise a sales invoice with no upstream quote or order at all, so a control that only guards the quote→order→shipment path can be walked around by invoicing the customer directly.
+
+## Design in one paragraph
+
+Carbon already has a working predicate-rule engine behind **Storage Rules** (warehouse/MES transaction surfaces). Sales Rules is the *second family* of rules on that same engine, not a second engine. Both families share one condition-AST compiler, one evaluator shape, one violation modal, and — as of this work — **one table**, `enforcementRule`, discriminated by a `family` column. The sales family adds a customer context root, three sales-document surfaces (quote line, sales order line, sales invoice line), and a set of enforcement gates on the sales lifecycle.
+
+## Data model
+
+One rule table serves both families. The alternative — a table per family — was rejected: the two schemas are 90% identical, and a second table would duplicate the schema, the RLS, the CRUD, and every future column.
+
+### Enums
+
+```sql
+CREATE TYPE "enforcementRuleFamily" AS ENUM ('storage', 'sales');
+
+-- One surface catalog spanning both families.
+CREATE TYPE "enforcementRuleSurface" AS ENUM (
+ -- storage family (warehouse / MES transaction events)
+ 'receipt', 'shipment', 'stockTransfer', 'warehouseTransfer', 'inventoryAdjustment',
+ 'place', 'pick', 'operationStart', 'operationFinish', 'materialIssue', 'materialReceive',
+ -- sales family (sales-document lines)
+ 'quoteLine', 'salesOrderLine', 'salesInvoiceLine'
+);
+
+CREATE TYPE "enforcementRuleTargetType" AS ENUM ('item', 'workCenter');
+```
+
+**A rule must not be able to subscribe to another family's surface** — a storage rule listening on `quoteLine` would silently never fire. With one shared enum the column type can no longer be the guard, so two CHECK constraints take over (below). This is the deliberate cost of the single table: *structural* isolation becomes *constraint + query* isolation.
+
+### `enforcementRule`
+
+```sql
+CREATE TABLE "enforcementRule" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "family" "enforcementRuleFamily" NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "message" TEXT NOT NULL, -- violation text, {token} interpolation
+ "severity" TEXT NOT NULL CHECK ("severity" IN ('error', 'warn')),
+ "conditionAst" JSONB NOT NULL, -- {kind: all|any|none, conditions:[{field,op,value}]}
+ "surfaces" "enforcementRuleSurface"[] NOT NULL,
+ -- storage-family shape; sales rows are pinned to the defaults by CHECK
+ "targetType" "enforcementRuleTargetType" NOT NULL DEFAULT 'item',
+ "appliesToAll" BOOLEAN NOT NULL DEFAULT FALSE, -- workCenter-target broadcast toggle
+ -- item scoping, both families (empty arrays = every item)
+ "filteredItemTypes" TEXT[] NOT NULL DEFAULT '{}',
+ "filteredItemGroupIds" TEXT[] NOT NULL DEFAULT '{}',
+ "filteredItemMatchAll" BOOLEAN NOT NULL DEFAULT FALSE, -- false = OR, true = AND across the two dimensions
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "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,
+ "customFields" JSONB,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+
+ CONSTRAINT "enforcementRule_surfaces_nonempty" CHECK (array_length("surfaces", 1) >= 1),
+ CONSTRAINT "enforcementRule_storage_surfaces" CHECK (
+ "family" <> 'storage' OR "surfaces" <@ ARRAY[/* the 11 transaction surfaces */]::"enforcementRuleSurface"[]
+ ),
+ CONSTRAINT "enforcementRule_sales_surfaces" CHECK (
+ "family" <> 'sales' OR "surfaces" <@ ARRAY[
+ 'quoteLine','salesOrderLine','salesInvoiceLine'
+ ]::"enforcementRuleSurface"[]
+ ),
+ CONSTRAINT "enforcementRule_sales_shape" CHECK (
+ "family" <> 'sales' OR ("targetType" = 'item' AND "appliesToAll" = FALSE)
+ )
+);
+
+ALTER TABLE "enforcementRule" ADD CONSTRAINT "enforcementRule_companyId_family_name_key"
+ UNIQUE ("companyId", "family", "name");
+```
+
+Name uniqueness is **per family** — the same rule name may legitimately exist once in each family.
+
+Indexes: `companyId`, `createdBy`, and two partial indexes on `(companyId, family)` and `(companyId, targetType)` where `active`.
+
+### Assignment tables
+
+Two tables, not one polymorphic table: a polymorphic `targetId` cannot carry a real foreign key, and losing `ON DELETE CASCADE` from `item`/`workCenter` would leave orphaned pins.
+
+- **`enforcementRuleItemAssignment`** — PK `(itemId, ruleId)`, serves **both** families.
+- **`enforcementRuleWorkCenterAssignment`** — PK `(workCenterId, ruleId)`, storage family only.
+
+Both carry `companyId`, audit columns, and a composite FK `(ruleId, companyId) → enforcementRule(id, companyId) ON DELETE CASCADE`.
+
+Because the item table is shared, **a pin alone does not tell you the family**. Every reader must resolve pinned rules against a family-filtered rule fetch — never a PostgREST embed, which would happily return the other family's rule.
+
+### `enforcementRuleAcknowledgment`
+
+Append-only override/block evidence, one row per deduped violation:
+
+`id`, `companyId`, `ruleId` (**soft reference, no FK**), `ruleName` (denormalized), `documentType` (`'quote'|'salesOrder'|'salesInvoice'`), `documentId`, `documentLineId`, `itemId`, `severity`, `outcome` (`'blocked'|'acknowledged'`), `message`, audit columns.
+
+`ruleId` deliberately has no FK so a rule delete can neither cascade evidence away nor be blocked by it; the denormalized `ruleName` plus the verbatim rendered `message` keep each row self-contained. Retiring a rule that has fired should be a deactivation (`active = false`), but deletion stays available without audit loss.
+
+### Company setting
+
+```sql
+ALTER TABLE "companySettings"
+ ADD COLUMN "salesRuleNotificationGroup" text[] NOT NULL DEFAULT '{}';
+```
+
+### Custom fields
+
+The merged table registers **one** `customFieldTable` row (`'enforcementRule'`, `'Rule'`). Both rule editors therefore share a custom-field namespace — an accepted product tradeoff; per-family custom fields would be a UI filter, not a schema change.
+
+## Permissions & RLS
+
+Each family keeps the permission its own domain implies. **Read** is any employee of the company; **writes** are per-family:
+
+| Table | SELECT | INSERT / UPDATE / DELETE |
+|---|---|---|
+| `enforcementRule` | any employee | `family='storage'` → `inventory_*` · `family='sales'` → `sales_*` |
+| `enforcementRuleItemAssignment` | any employee | resolved through the pinned rule's family: storage → `parts_*`, sales → `sales_*` |
+| `enforcementRuleWorkCenterAssignment` | any employee | `resources_*` |
+| `enforcementRuleAcknowledgment` | any employee | INSERT via `sales_create`; **no UPDATE/DELETE policies** (append-only) |
+
+Two requirements that are easy to get wrong:
+
+- The rule table's UPDATE policy needs **both** `USING` and `WITH CHECK` with the same per-family predicate, or a row could be edited into a family the actor lacks permission for.
+- The item-assignment policies correlate to the pinned rule with an `EXISTS`. Inside that subquery an **unqualified** `"companyId"` binds to the *inner* table, silently making the tenant correlation a tautology. Qualify the outer row explicitly: `r."companyId" = "enforcementRuleItemAssignment"."companyId"`.
+
+## Engine (`@carbon/utils`)
+
+The engine is family-neutral and lives in `packages/utils/src/rules.ts` (+ `rule-filters.ts`, `field-registry.ts`, and the zod AST mirror `rules-schema.ts`):
+
+- `ConditionAst = {kind: all|any|none, conditions: [{field, op, value}]}`; operators `eq, neq, in, notIn, isSet, isNotSet, gt, lt`.
+- `compileRule` / `compileWithCache` (LRU), `evaluateRules`, `interpolateMessage` (`{token}` support), and required-field semantics — a condition referencing an empty field emits "{label} is required" at the rule's severity.
+- `ItemFilter` / `ruleAppliesToItem` / `toItemFilter` — the broadcast item-scoping matcher, shared by both families (`rule-filters.ts`).
+- Surface catalogs and per-surface context-availability maps for each family.
+
+Sales additions: a `customer` root on `RuleContext` (`{ id, typeId, statusId, location: { countryCode }, customFields }`), the three sales surfaces, and field-registry entries for **customer type**, **customer status**, and **ship-to country** (alpha-2, matching the app-wide convention) plus synthesized `customer.customFields.*`. Storage-rule behavior is unchanged.
+
+TypeScript keeps the per-family surface unions independent of the DB enum, so the one engine can evaluate either family while each form still offers only its own surfaces.
+
+## Evaluator (`@carbon/ee/rules`)
+
+`packages/ee/src/rules/` holds `storage/` and `sales/` evaluator directories with the shared violation modal + hook at the root. Package exports: `./rules` (client-safe services/UI) and `./rules.server` (both evaluators, `isBlocked`, `dedupeViolations`).
+
+The sales evaluator mirrors the storage one:
+
+- `service.ts` — cross-app queries: active rules for items (incl. broadcasts + filters), assignments for an item, list, assign/unassign.
+- `server.ts` — `evaluateSalesRuleLines({ client, companyId, userId, surface, lines, customerId, customerLocationId })` → `{ violations, ruleNames }`. `userId` is required because the service-role client cannot infer the acting user; it lands in `transaction.userId`.
+- `context.ts` — builds one `RuleContext` per line: item fields batch-loaded (incl. `customFields`, flattened `itemPostingGroupId`), customer context resolved once per document (`customerTypeId`/`customerStatusId`/`customFields` + `customerLocation.addressId → address.countryCode`).
+
+**Rule selection contract.** Every active rule of the family is a broadcast; empty filters match all items; `filteredItemMatchAll` chooses OR (false) or AND (true) across the type/group dimensions; an explicit pin bypasses the broadcast filters. Per line, pins and broadcasts merge by `ruleId` before evaluation; violations dedupe on `ruleId` + message (+ `lineId` for document-level gates). A line whose item row fails to load matches explicit pins only.
+
+Non-negotiables:
+
+- **Service-role client** (`getCarbonServiceRole()`) — the check must see full truth regardless of the acting user's read permissions. The route's `requirePermissions` remains the action gate.
+- **Tenant isolation below the service-role boundary.** RLS is bypassed on this client, so *every* query — rules, pins, items, customer, customerLocation — carries an explicit `companyId` predicate. These predicates ARE the isolation; a service-role query without one is a defect, not a style choice.
+- **Family isolation.** Every read filters `family`; pins resolve against a family-filtered fetch. Lock it with a test that fails when the guard is removed.
+- **Plan gate** — the existing `SALES_RULES` feature key (`packages/ee/src/plan.ts`, Business/Partner). Evaluation returns no violations when the gate is off.
+- **A failed load must not read as "no rules".** A query error that silently yields zero rules or zero items turns enforcement off. Fail loud rather than proceed.
+- **Reuse `useRuleViolations` + `RuleViolationModal`** — they are generic over `Violation`. Do not fork the violation UI.
+- Missing ship-to: rules referencing `customer.location.countryCode` rely on the engine's required-field semantics — empty → "Customer location is required" at the rule's severity.
+
+## ERP placement
+
+A rule family is not its own ERP domain — it lives inside the domain module it gates. Storage rules live in `~/modules/inventory`; sales rules live in `~/modules/sales`. Neither gets a standalone `~/modules/*` directory.
+
+- `sales.models.ts` — `salesRuleValidator` (surfaces restricted to the two sales surfaces; `.superRefine` rejects a condition on a field whose context the evaluator won't populate for every selected surface), `salesRuleAssignmentValidator`.
+- **Admin CRUD is shared, not per-family.** One parametrized implementation in `~/modules/shared` (`getEnforcementRules`, `getEnforcementRule`, `upsertEnforcementRule`, `deleteEnforcementRule`, `getEnforcementRuleAssignmentCounts`); callers pass their family. Duplicating it per module would be two copies of the same query drifting apart.
+- Cross-app queries are imported from `@carbon/ee/rules` **directly at the call site**, not re-exported through the module barrel — the package boundary should be visible where it is used.
+- `ui/SalesRules/` — `SalesRuleForm.tsx` (ModalDrawer + ValidatedForm) and `SalesRulesTable.tsx`. Reuse the props-driven builder components from the storage UI (`RuleBuilder`, `ConditionRow`, `SurfacesField`, `SeveritySelect`, `MessageWithTokens`, `ItemFilterSelector`) by deep import; parameterize rather than copy, and keep any parameterization additive so storage behavior is preserved. These components must never import a module *barrel* — that would create a cycle.
+- The plan-gate upgrade overlay chrome is shared (`~/components/RulesUpgradeOverlay`); each family supplies only its preview table, fixtures, and copy.
+
+## Routes & wiring
+
+- `x+/sales+/sales-rules.tsx` (list), `.new.tsx`, `.$id.tsx`, `.$id.delete.tsx`, plus `sales-rules.assign.$itemId.tsx` / `sales-rules.unassign.$itemId.$ruleId.tsx`. Write routes: `requirePlan({ feature: "SALES_RULES" })` + `create/update/delete: "sales"`.
+- Path helpers in `apps/erp/app/utils/path.ts`; react-query key `salesRulesQuery`.
+- Sidebar: "Sales Rules" in the Sales → Configure group (`useSalesSubmodules`), beside Pricing Rules.
+- Part detail → Inventory tab: a "Sales rules" card beneath the storage-rules card, listing explicit + broadcast rules with assign/unassign.
+- Settings → Sales: a "Sales Rule Violations" notification-group card.
+- Sales invoice: the two line-write routes (`x+/sales-invoice+/$invoiceId.new.tsx`, `$invoiceId.$lineId.details.tsx`) and the post route (`$invoiceId.post.tsx`) gain the check; the post modal (`SalesInvoicePostModal`) gains the `acknowledged` field and the shared violation modal, which it does not have today.
+- Naming discipline: `salesRule*` / `storageRule*` for the family-specific pieces, `enforcementRule*` for the shared table and shared CRUD; never a bare `rule`. The configurator's `configurationRule*` is unrelated.
+
+## Enforcement
+
+### Phase 1 — line-level, for fast feedback
+
+- `x+/quote+/$quoteId.new.tsx` — after validation, before `upsertQuoteLine`: read `acknowledged` from formData, evaluate on surface `quoteLine` with the header's `customerId`/`customerLocationId`, and on `isBlocked` return `{ violations, ruleNames }`.
+- `x+/sales-order+/$orderId.new.tsx` — same, before `upsertSalesOrderLine`, surface `salesOrderLine`.
+- Line **edit** actions (`$quoteId.$lineId.details.tsx`, `$orderId.$lineId.details.tsx`) — same evaluation, so an edit cannot dodge a rule.
+- **Item-only guard:** lines with no `itemId` (e.g. `Comment` sales-order lines) skip evaluation entirely — the guard wraps the evaluation block, never the action.
+- Client: `QuoteLineForm` / `SalesOrderLineForm` submit through `useRuleViolations({ action })` and render the shared modal. Coexists with the inline supersession notice and the ConfiguratorModal.
+
+Reference wiring already in production: `x+/shipment+/$shipmentId.post.tsx` (read `acknowledged` → evaluate → dedupe → `isBlocked` → return `{violations, ruleNames}` on block).
+
+### Phase 3 — where the guarantee actually lives
+
+Line-level checks are the right place for *feedback* and the wrong place for *the guarantee*: 14 entry points can put an `itemId` on a sales line, and three of them (direct PostgREST with an API key, `SECURITY DEFINER` RPCs, service-role paths such as the unauthenticated digital-quote accept) execute no Carbon TypeScript at all. The MCP executor resolves any named export of `sales.service.ts` by name, so the very function the enforced route protects is reachable unprotected.
+
+**Principle: a compliance control fails at the document, not the line.** Per-write enforcement must be exhaustive to be worth anything, and this write surface is provably non-exhaustible. Per-*gate* enforcement only has to cover the transitions — and because a gate re-reads the whole document, it catches lines from writers nobody instrumented, plus staleness (rule authored later, ship-to changed, item attributes changed) for free.
+
+| Gate | Route | Note |
+|---|---|---|
+| Sales order confirm | `x+/sales-order+/$orderId.confirm.tsx` | cleanest — already returns objects rather than redirecting |
+| Quote finalize / send | `x+/quote+/$quoteId.finalize.tsx` | add the returned-violations branch **before** the existing `throw redirect(...)` paths |
+| Quote → order convert | `x+/quote+/$quoteId.convert.tsx` | gate in the route, before `convertQuoteToOrder`. Also the natural place to evaluate quantity rules — quote quantity is not meaningful until conversion |
+| RFQ → quote convert | `x+/sales-rfq+/$rfqId.convert.tsx` | same; evaluate the resulting quote lines' items |
+| Shipment post | `x+/shipment+/$shipmentId.post.tsx` | last physical checkpoint; catches orders confirmed before a rule existed. Add sales violations to the array the storage loop already builds |
+| **Sales invoice post** | `x+/sales-invoice+/$invoiceId.post.tsx` | the revenue checkpoint, and the only gate that covers an invoice raised with no upstream document — see below |
+
+Gating the two convert routes **in the route** is deliberate: it achieves the same protection as a Deno-side evaluator with none of the cost. The engine is portable, but the evaluator imports `companyHasPlan` → `@carbon/auth` (module-load `process.env`) → `react-router`, and CI runs zero `deno` invocations, so a Node/Deno divergence would be silent. Do not port the evaluator.
+
+`api+/sales.digital-quote.$id.tsx` is **hard-block-on-error only** — there is no employee session, nobody may acknowledge, and internal compliance text must not reach the customer. Log and proceed on warns.
+
+**Unbypassable hard errors.** Move the *error-severity* half of the check into `upsertQuoteLine` and `upsertSalesOrderLine` so the MCP surface is covered — an `error` violation throws. Warn handling stays in the route actions, where `acknowledged` and the modal live. Blocklist `sales_insertSalesOrderLines` (no in-app caller).
+
+**Drop-ship ship-to.** A drop shipment's real destination is `salesOrderShipment.customerLocationId`, not the header's. Resolve the effective ship-to — drop-ship location when present, else header — before evaluating, or a country rule clears orders that ship to the restricted country.
+
+**Supporting change.** `Violation` is `{ruleId, severity, message}` with no line reference. A document-level gate needs per-line attribution so the modal can group violations and deep-link to the offending line — extend it with `lineId` and key the modal by line.
+
+### Sales invoices — closing the "skip the order" bypass
+
+An invoice is where revenue is actually recognised, and Carbon lets you raise one
+**without any upstream document**: `x+/sales-invoice+/new.tsx` falls through to a
+blank form when no `?sourceDocument` is given, and lines are then added freely
+against it. Every other gate in this spec sits on the quote→order→shipment path,
+so a restricted item invoiced directly would reach revenue having passed nothing.
+
+**The invoice-line surface.** `salesInvoiceLine` joins `quoteLine` and
+`salesOrderLine`, with the same line-level check on the two write routes
+(`$invoiceId.new.tsx`, `$invoiceId.$lineId.details.tsx`) and a terminal gate at
+post.
+
+**Ship-to is the whole design problem, and it resolves cleanly.** A sales invoice
+has **no customer ship-to**. `salesInvoice.customerId` is NOT NULL, so customer
+type/status/custom fields resolve exactly as elsewhere — but the only customer
+address on the invoice is `invoiceCustomerLocationId`, which is the **bill-to**,
+and both `salesInvoice.locationId` and `salesInvoiceShipment.locationId` are
+*Carbon's own* warehouse locations, not customer addresses. So:
+
+- **Line came from a sales order** (`salesInvoiceLine.salesOrderId` /
+ `salesOrderLineId` are set — the convert path always populates them): resolve
+ the ship-to through `resolveSalesOrderShipTo`, exactly as the order gate does.
+ Drop-ship handling comes along for free, and re-evaluating here catches
+ staleness — a rule authored after the order was confirmed.
+- **Standalone line** (`salesOrderLineId IS NULL`): there is no ship-to to
+ resolve, and none may be invented. Pass `customerLocationId: null` and let the
+ engine's required-field semantics do their job — any rule referencing
+ `customer.location.countryCode` raises "Customer location is required" at that
+ rule's severity.
+
+That second case *is* the bypass fix, and it is the right shape rather than a
+consolation prize: an invoice raised with no order **cannot demonstrate where the
+goods went**, so a destination-restricted item does not quietly pass — it blocks
+(severity `error`) or demands an acknowledgment (`warn`), and either way the
+attempt lands in the evidence table. The bypass path carries strictly *less*
+information than the path it skips, so it fails closed instead of open. Rules
+that never mention the ship-to — customer status, customer type, item group —
+evaluate at full strength on a standalone invoice with no degradation.
+
+**Never substitute the bill-to for the ship-to.** `invoiceCustomerLocationId` is
+a different address and frequently a different country; using it would clear a
+rule that should have blocked. This is the same failure the drop-ship defect
+produced, and it is the one shortcut a future implementer is most likely to take.
+(Note `salesInvoiceLocations` looks like it offers a country: it joins
+`customerLocation` against *company*-location ids, so its `customerCountryCode`
+and `shipmentCountryCode` branches do not resolve for invoices created by either
+`insertSalesInvoice` or `convert`. Only its bill-to branch resolves. Do not read
+a ship-to from that view.)
+
+**Where the gate goes, and what it does not cover.** Posting is a Deno edge
+function (`post-sales-invoice`), so — per the same reasoning that keeps the
+convert gates in the route — the check goes in the **route action**
+(`$invoiceId.post.tsx`) *before* it invokes the function. Two implementation
+details that will bite otherwise: the route optimistically writes
+`status = 'Pending'` before invoking, so the gate must run **before** that write
+or a blocked post strands the invoice in `Pending`; and the customer email is
+sent later in the same action, after the edge function has committed, so a gate
+that runs first also prevents the email. A service-role caller invoking the edge
+function directly still bypasses this — the same residual hole the other gates
+have, and the same reason the error-severity backstop below matters.
+
+**Void is never gated.** Voiding is corrective; blocking it would trap a bad
+invoice in a posted state.
+
+**MCP and the unbypassable half.** The MCP backstop currently maps only
+`sales_upsertQuoteLine` and `sales_upsertSalesOrderLine` and returns null for
+everything else, so every invoicing tool is unchecked. Add
+`invoicing_upsertSalesInvoiceLine` → `salesInvoiceLine` to that map, and move the
+error-severity check into `upsertSalesInvoiceLine` itself so it holds for callers
+that never touch a route.
+
+## Notifications + acknowledgment evidence (Phase 2)
+
+- `packages/notifications`: `NotificationEvent.SalesRuleViolation` (topic Sales; in-app + email).
+- `packages/jobs` notify handler: recipients from `companySettings.salesRuleNotificationGroup`. The payload is a **document-level summary**, not a per-violation fan-out: a compound document id (`<quote|salesOrder>:<documentId>:<blocked|acknowledged>` — the JobOperation compound-id precedent; the notify payload's own `documentType` is a narrower DB enum that cannot carry quote/salesOrder) plus the acting user. The handler resolves document reference and customer name for rendering. Per-violation detail deliberately does not ride the notification — the notification is the pointer, the evidence table is the record.
+- **Scope & idempotency:** one notification per enforcement-action outcome. A repeated blocked attempt re-notifies deliberately — repeat attempts are signal for compliance, not noise. Violations within one action are already deduped before the single notify fires. A durable per-document dedup key is a recorded follow-up, not v1.
+- **Evidence persistence (both outcomes):** insert one `enforcementRuleAcknowledgment` row per deduped violation on **blocked** returns (`outcome: 'blocked'`, `documentLineId` null — no line exists) and on **acknowledged** proceeds. On create actions the acknowledged-path insert runs after the line write so `documentLineId` captures the new line's id; edit actions pass the route's `lineId`.
+- **Evidence atomicity:** best-effort, never blocking. A blocked return writes only evidence. On an acknowledged proceed, an evidence-insert failure is logged and the sale proceeds — the business action must never fail because the audit write did. Duplicate rows from client retries are acceptable in an append-only table.
+
+## Known gaps, accepted
+
+- **`acknowledged` is client-supplied.** It is read from FormData with no server-side record that a violation was displayed, so a crafted first submit can skip every `warn`. Errors are unaffected — they block unconditionally. Accepted for v1.
+- **The acknowledgment table has writers and no reader.** It is write-only audit until a surface is built for it.
+- **Service-only orders skip the shipment checkpoint.** Services are `Non-Inventory` items that are never shipped, so a service-only order goes straight to `To Invoice`. The invoice-post gate now covers them, so this is no longer a hole — but it means the invoice gate, not shipment post, is the last checkpoint for a service.
+- **No nightly sweep.** Drafts are a scratchpad — users must be free to experiment, and the confirm gate catches it before it counts. Avoids a cron, a violation-state table, and notification-fatigue tuning.
+- **No Postgres trigger.** It could enforce only the error-severity subset (no warn/acknowledge, no interpolated messages), and plan gating has no DB precedent while `CarbonEdition`/`STRIPE_BYPASS_COMPANY_IDS` are invisible to Postgres. A second evaluator in a second language that disagrees with the first is worse than a known gap.
+- **No rule-impact preview** ("what does my new rule break?").
+- **A service-role caller invoking `post-sales-invoice` directly** bypasses the invoice gate, exactly as one invoking `convert` bypasses the conversion gates. The error-severity check inside `upsertSalesInvoiceLine` is what covers that path; there is no gate inside the edge function itself, because a second evaluator in Deno that disagrees with the first is worse than a known gap.
+
+## Out of scope
+
+Line-value (price/qty/date) context; purchasing surfaces / AVL; supersession fold-in; export-licence entity; MES surfaces. Configurator rules untouched; storage rules untouched except for the shared table, shared CRUD, and shared-component parameterization.
+
+## Also in scope
+
+- Update `apps/erp/app/modules/sales/AGENTS.md` and `apps/erp/app/modules/inventory/AGENTS.md` (shared table, family filtering, shared CRUD), plus `packages/{utils,ee}/AGENTS.md` and affected `.claude/rules` files.
+- Tests: context building (customer root, alpha-2 country), field-registry additions, evaluator happy path, required-field (missing ship-to), acknowledged flow, and **cross-family isolation** — a pin pointing at the other family's rule must never enter evaluation.
+- Invoice-specific tests: an order-derived invoice line resolves the ship-to through its source order (including drop-ship), and a **standalone** line with a country rule produces the required-field violation rather than passing. The second is the bypass this feature exists to close, so it should fail loudly if someone later "fixes" it by falling back to the bill-to.
+
+## Verification
+
+```bash
+pnpm db:migrate && pnpm run generate:types
+pnpm exec turbo run typecheck --filter=@carbon/utils --filter=@carbon/ee --filter=@carbon/database --filter=erp --filter=mes
+pnpm --filter @carbon/utils test && pnpm --filter @carbon/ee test
+pnpm run lint
+```
+
+Beyond the gates: exercise the RLS policies with a real authenticated request. The per-family predicates and the assignment-table `EXISTS` correlation cannot be verified by typecheck, tests, or a schema diff — only by a logged-in user hitting the routes.