Skip to Content
InternalDocsStrategySnapshotsSelf Extending Architecture V1

Self Extending Architecture V1

Source: docs/strategy/snapshots/self-extending-architecture-v1.md

# Self-Extending Rules Architecture for RGL8R **Status:** Proposal **Last Updated:** February 2026 **Inspired By:** Pi agent harness (minimalist primitives, self-extending pattern) --- ## Executive Summary RGL8R can adopt the "self-extending" pattern that made Pi successful: instead of pre-building every compliance rule, the system generates rules on demand from edge cases. Each customer's edge case becomes a rule that benefits all future customers. This creates a compounding moat: the rule corpus becomes the asset, not just the code. --- ## Core Primitives (RGL8R's "Five Tools") Everything composes from five operations. **Corridor is a first-class parameter** — the system is origin/destination agnostic by design. ```typescript VALIDATE(sku, corridor, attribute, source) → { value, confidence, provenance } SCREEN_PRODUCT(sku, corridor, regulation_sets[]) → { outcome, evidence[], risk_score } SCREEN_PARTY(party, corridor, list_types[]) → { outcome, matches[], risk_level } MATCH(sku, corridor, classification_system) → { matches[], confidence } EVIDENCE(entity, action, corridor) → { timestamp, rule_ref, sources[], audit_block } ``` **Key Design Decision:** We split `SCREEN` into `SCREEN_PRODUCT` and `SCREEN_PARTY` because: - Product screening (SIMA, ITAR, EAR) operates on SKU attributes - Party screening (denied parties, sanctions) operates on entity names/addresses - Different data sources, different matching logic, different false positive profiles **Corridor Parameter:** ```typescript type Corridor = { origin: CountryCode; // e.g., "US" destination: CountryCode; // e.g., "CA" // Optional specificity origin_state?: string; // e.g., "CA" (California) destination_province?: string; // e.g., "ON" (Ontario) } ``` **Examples:** - SIMA screening = `MATCH` against SIMA measures + `SCREEN_PRODUCT` with corridor `US→CA` + `EVIDENCE` for audit trail - ITAR screening = `SCREEN_PRODUCT` with corridor `US→*` (any destination) + `EVIDENCE` for State Dept compliance - Denied party check = `SCREEN_PARTY` against OFAC SDN + BIS Entity List + `EVIDENCE` for export compliance - Carrier audit = `VALIDATE` invoice line + `MATCH` against contract + `EVIDENCE` for dispute --- ## Rule Inheritance Model Rules apply at different scopes. The system evaluates from most general to most specific: ``` ┌─────────────────────────────────────────────────────────────────┐ │ UNIVERSAL RULES (apply everywhere) │ │ • Physics: weight can't exceed dims capacity │ │ • Hazmat: UN classification codes (international standard) │ │ • HS codes: First 6 digits harmonized globally │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ ORIGIN RULES (apply to exports FROM this country) │ │ • US: ITAR (defense articles), EAR/ECCN (dual-use), OFAC SDN │ │ • CN: Chinese export controls │ │ • Any: Denied party screening based on exporter jurisdiction │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ DESTINATION RULES (apply to imports TO this country) │ │ • CA: SIMA, CBSA requirements, GST/HST/PST │ │ • US: Section 232 (steel/aluminum), de minimis, FDA, TTB │ │ • UK: Post-Brexit VAT, UK Global Tariff │ │ • EU: TARIC, VAT OSS, CE marking │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ CORRIDOR RULES (apply to specific origin → destination pairs) │ │ • US→CA: CUSMA preferential treatment, de minimis thresholds │ │ • CN→US: Section 301 tariffs (25% on specific HS codes) │ │ • *→US: Section 232 country-specific exemptions/quotas │ │ • US→UK: Post-Brexit trade agreement rules │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ PARTY RULES (apply to specific entities regardless of product) │ │ • OFAC SDN: Blocked for any transaction from US │ │ • BIS Entity List: License required for controlled items │ │ • BIS Denied Persons: Blocked from US exports │ │ • UN Sanctions: Universal prohibition │ │ • Canada SEMA: Canadian sanctions list │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ PRODUCT CATEGORY RULES (apply to regulated product types) │ │ • Alcohol: State/province shipping restrictions, excise taxes │ │ • Cannabis: Jurisdiction-specific legality │ │ • Firearms: Export controls, age verification │ │ • Perfume/Fragrances: Hazmat (flammable), alcohol content │ │ • Pharmaceuticals: FDA, Health Canada, controlled substances │ │ • Food: FDA, CFIA, labeling requirements │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ FINANCE RULES (apply to payment and transaction attributes) │ │ • Payment processor restrictions (Stripe, PayPal policies) │ │ • High-risk merchant categories (MCC codes) │ │ • Currency controls (sanctioned country currencies) │ │ • AML screening thresholds │ │ • Tax nexus triggers by jurisdiction │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ CARRIER RULES (apply to shipping method and carrier) │ │ • Carrier-specific prohibited items (FedEx vs UPS policies) │ │ • Service level restrictions (hazmat can't go air) │ │ • DIM factor and billing rules by carrier │ │ • Accessorial policies (residential, liftgate, etc.) │ └─────────────────────────────────────────────────────────────────┘ ``` ### Rule Evaluation Order When evaluating a shipment, rules are checked in order from universal to specific. A BLOCK at any level stops the transaction: ```typescript async function evaluateShipment( shipment: Shipment, corridor: Corridor ): Promise<ComplianceResult> { const results: RuleResult[] = []; // 1. Universal rules (physics, UN hazmat) results.push(...await evaluateUniversalRules(shipment)); if (hasBlock(results)) return block(results); // 2. Origin rules (ITAR, EAR, denied parties from origin) results.push(...await evaluateOriginRules(shipment, corridor.origin)); if (hasBlock(results)) return block(results); // 3. Destination rules (SIMA, customs requirements) results.push(...await evaluateDestinationRules(shipment, corridor.destination)); if (hasBlock(results)) return block(results); // 4. Corridor rules (trade agreements, specific tariffs) results.push(...await evaluateCorridorRules(shipment, corridor)); if (hasBlock(results)) return block(results); // 5. Party rules (denied party screening) results.push(...await evaluatePartyRules(shipment.parties, corridor)); if (hasBlock(results)) return block(results); // 6. Product category rules (alcohol, hazmat, etc.) results.push(...await evaluateProductRules(shipment.products)); if (hasBlock(results)) return block(results); // 7. Finance rules (payment restrictions, AML) results.push(...await evaluateFinanceRules(shipment.transaction)); if (hasBlock(results)) return block(results); // 8. Carrier rules (carrier-specific policies) results.push(...await evaluateCarrierRules(shipment, shipment.carrier)); return compile(results); } ``` ### Rule Storage with Scope ```sql CREATE TABLE compliance_rules ( id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, version INT NOT NULL, -- Scope definition scope_type VARCHAR(20) NOT NULL, -- universal, origin, destination, corridor, party origin_country VARCHAR(3), -- NULL for universal/destination rules destination_country VARCHAR(3), -- NULL for universal/origin rules -- Rule definition conditions JSONB NOT NULL, action VARCHAR(50) NOT NULL, severity VARCHAR(20) NOT NULL, -- Metadata regulation_source VARCHAR(100), -- e.g., "ITAR", "SIMA", "OFAC" effective_date DATE, expiry_date DATE, -- Lifecycle status VARCHAR(20) DEFAULT 'proposed', created_at TIMESTAMP DEFAULT NOW() ); -- Index for efficient corridor-based lookups CREATE INDEX idx_rules_corridor ON compliance_rules(origin_country, destination_country, scope_type); ``` --- ## Export Controls & Denied Party Screening ### ITAR (International Traffic in Arms Regulations) **What it is:** US export control for defense articles on the US Munitions List (USML). Administered by State Department. **When it applies:** Any export FROM the US of items on the USML, regardless of destination (even to allies). **RGL8R handling:** ```yaml # Origin-based rule (US exports only) rule: id: "itar_usml_screen" scope_type: origin origin_country: US destination_country: null # Applies to ALL destinations conditions: - product_category IN usml_categories - OR hs_code IN itar_controlled_hs_codes - OR description MATCHES itar_keywords action: BLOCK_PENDING_LICENSE severity: CRITICAL evidence_template: | Product {sku} may be controlled under ITAR (USML Category {category}). Export requires State Department license regardless of destination. Consult with export compliance counsel before shipping. ``` ### EAR (Export Administration Regulations) **What it is:** US export control for dual-use items. Administered by Commerce Department (BIS). Uses ECCN (Export Control Classification Number). **When it applies:** US exports of items on the Commerce Control List. License requirements vary by destination country. **RGL8R handling:** ```yaml rule: id: "ear_eccn_screen" scope_type: corridor # Varies by destination origin_country: US conditions: - eccn IS NOT NULL - destination_country IN ear_license_required_countries[eccn] action: FLAG_FOR_REVIEW severity: HIGH evidence_template: | Product {sku} classified as ECCN {eccn}. Export to {destination} requires BIS license review. License exception may apply: {applicable_exceptions}. ``` ### Denied Party Screening **What it is:** Screening all transaction parties (buyer, consignee, end user, freight forwarder) against government prohibited party lists. **Lists to screen (minimum for US exports):** - OFAC SDN (Specially Designated Nationals) - OFAC Consolidated Sanctions - BIS Denied Persons List - BIS Entity List - BIS Unverified List - State Department Debarred List **Additional lists by corridor:** - Canada: SEMA (Special Economic Measures Act) - EU: EU Consolidated Sanctions List - UK: UK Sanctions List - UN: UN Security Council Sanctions **RGL8R handling:** ```typescript // Party screening is separate from product screening async function screenParties( transaction: Transaction, corridor: Corridor ): Promise<PartyScreenResult[]> { const parties = [ transaction.buyer, transaction.consignee, transaction.endUser, transaction.freightForwarder, transaction.intermediateConsignee ].filter(Boolean); // Determine which lists to screen based on corridor const lists = getApplicableLists(corridor); return Promise.all( parties.map(party => screenPartyAgainstLists(party, lists)) ); } function getApplicableLists(corridor: Corridor): DeniedPartyList[] { const lists: DeniedPartyList[] = []; // Universal lists.push('UN_SANCTIONS'); // Origin-based (exporter jurisdiction) if (corridor.origin === 'US') { lists.push('OFAC_SDN', 'OFAC_CONSOLIDATED', 'BIS_DENIED', 'BIS_ENTITY', 'STATE_DEBARRED'); } if (corridor.origin === 'CA') { lists.push('CANADA_SEMA'); } // Destination-based if (corridor.destination === 'CA') { lists.push('CANADA_SEMA'); } return lists; } ``` ### Party Screening Storage ```sql CREATE TABLE party_screenings ( id UUID PRIMARY KEY, tenant_id UUID NOT NULL, transaction_id UUID NOT NULL, -- Party info party_role VARCHAR(50) NOT NULL, -- buyer, consignee, end_user, etc. party_name TEXT NOT NULL, party_address TEXT, party_country VARCHAR(3), -- Screening result lists_checked JSONB NOT NULL, -- ["OFAC_SDN", "BIS_ENTITY", ...] matches_found JSONB, -- Array of potential matches match_score DECIMAL(3,2), -- Fuzzy match confidence outcome VARCHAR(20) NOT NULL, -- CLEAR, POTENTIAL_MATCH, BLOCKED -- Audit screened_at TIMESTAMP DEFAULT NOW(), reviewed_by UUID, review_notes TEXT, INDEX idx_party_outcome (tenant_id, outcome) ); ``` ### False-Positive Triage (Operational Guardrail) Denied-party screening must be tuned for fuzzy-match noise. Suggested default triage: - `match_score < 0.80` -> Auto-clear and store evidence - `0.80 <= match_score < 0.92` -> `POTENTIAL_MATCH`, queue manual review - `match_score >= 0.92` -> `BLOCKED` pending compliance override - Exact identifier hits (sanctions ID, passport, registration number) -> `BLOCKED` regardless of fuzzy score Thresholds should be configurable by list and corridor risk profile. --- ## Section 232 vs Section 301: US Import Tariffs These are both US **destination** rules (apply to imports INTO the US), but they work differently: ### Section 232 (National Security) **What it is:** Tariffs on steel and aluminum under Trade Expansion Act of 1962. Imposed for "national security" reasons. **Current rates (as of 2026):** - Steel: 25% on most imports - Aluminum: 10% on most imports **Exemptions/Modifications:** - Some countries have negotiated quotas or exemptions - CUSMA (Canada/Mexico) has complex provisions - Implementation note: examples below are simplified; production logic must include quota administration and melt-and-pour/derivative rules where applicable - Product exclusions available via Commerce Department **RGL8R handling:** ```yaml rule: id: "section_232_steel" scope_type: destination destination_country: US conditions: - hs_code IN section_232_steel_hs_codes # Chapter 72, 73 - origin_country NOT IN exempt_countries - NOT has_product_exclusion action: ADD_TARIFF tariff_rate: 0.25 # 25% severity: HIGH evidence_template: | Product {sku} (HS {hs_code}) subject to Section 232 steel tariff. Origin: {origin_country}. Rate: 25%. Check for product exclusions or quota allocations. ``` ### Section 301 (Unfair Trade Practices) **What it is:** Tariffs specifically on Chinese goods under Trade Act of 1974. Response to IP theft and forced technology transfer. **Current rates:** 7.5% to 25% depending on product list (Lists 1-4) **RGL8R handling:** ```yaml rule: id: "section_301_china" scope_type: corridor # Specific to CN→US origin_country: CN destination_country: US conditions: - hs_code IN section_301_hs_codes[list_number] action: ADD_TARIFF tariff_rate: section_301_rates[list_number] # 7.5%, 25%, etc. severity: HIGH evidence_template: | Product {sku} (HS {hs_code}) subject to Section 301 tariff. List: {list_number}. Rate: {rate}%. Origin: China. This is a corridor-specific (CN→US) tariff. ``` ### Key Distinction | Attribute | Section 232 | Section 301 | |-----------|-------------|-------------| | Products | Steel, Aluminum | Broad (technology, consumer goods, etc.) | | Origin | Multiple countries | China only | | Scope | Destination (→US) | Corridor (CN→US) | | Rationale | National security | Unfair trade practices | | Exemptions | Product exclusions, quotas | Limited | --- ## Generic Special Tariff Model **Design Principle:** The platform handles ANY tariff regime — SIMA, Section 232, Section 301, EU anti-dumping, future tariffs we haven't seen yet. We don't hardcode specific programs; we model the pattern. ### What ALL Special Tariffs Have in Common Every special tariff (anti-dumping, countervailing, safeguard, etc.) has: 1. **Trigger conditions** — HS codes, origin countries, materials, etc. 2. **Rate structure** — Percentage, per-unit, or mixed 3. **Scope** — Destination-only, corridor-specific, or origin-based 4. **Exemptions** — Product exclusions, quotas, preferential treatment 5. **Effective dates** — Start, end, modification dates 6. **Evidence requirements** — What documentation proves compliance/exemption ### Universal Tariff Schema ```typescript interface SpecialTariff { // Identity id: string; name: string; // "SIMA - Stainless Steel Sinks" program: TariffProgram; // Section232, Section301, SIMA, EUAntiDumping, etc. jurisdiction: CountryCode; // Which government administers this // Scope (determines when this tariff applies) scope: { type: 'destination' | 'corridor' | 'origin'; origin_countries?: CountryCode[]; // NULL = any origin destination_countries?: CountryCode[]; // NULL = any destination hs_codes: string[]; // HS codes or patterns (7324.10.*) hs_chapters?: string[]; // Broader match (Chapter 72, 73) }; // Conditions (additional attribute checks) conditions?: { materials?: string[]; // "stainless steel", "aluminum" intended_use?: string[]; // "commercial", "residential" product_attributes?: Record<string, any>; }; // Rate rate: { type: 'ad_valorem' | 'specific' | 'mixed' | 'variable'; ad_valorem_rate?: number; // 0.25 = 25% specific_rate?: Money; // $0.50/kg rate_schedule?: RateSchedule[]; // For tiered/variable rates minimum?: Money; maximum?: Money; }; // Exemptions exemptions?: Exemption[]; // Lifecycle effective_date: Date; expiry_date?: Date; last_modified: Date; // Evidence evidence_requirements: string[]; // "Certificate of Origin", "Product Exclusion Letter" regulatory_reference: string; // Link to official source } interface Exemption { id: string; type: 'product_exclusion' | 'quota' | 'trade_agreement' | 'de_minimis' | 'end_use'; conditions: Record<string, any>; documentation_required: string[]; } type TariffProgram = | 'SIMA' // Canada anti-dumping/countervailing | 'Section232' // US steel/aluminum (national security) | 'Section301' // US China tariffs (unfair trade) | 'Section201' // US safeguard tariffs | 'EUAntiDumping' // EU anti-dumping duties | 'EUCountervailing' // EU countervailing duties | 'UKTradeDef' // UK trade defense measures | 'Custom'; // Customer-specific or future programs ``` ### Example Implementations **SIMA (Canada Anti-Dumping):** ```yaml tariff: id: "sima_sss_cn" name: "SIMA - Stainless Steel Sinks (China)" program: SIMA jurisdiction: CA scope: type: destination origin_countries: [CN] destination_countries: [CA] hs_codes: ["7324.10.*"] conditions: materials: ["stainless steel", "304 stainless", "316 stainless"] rate: type: variable rate_schedule: - supplier: "Zhongshan Superte" rate: 0.186 # 18.6% - supplier: "Foshan Shunde" rate: 0.241 # 24.1% - supplier: "*" # All others rate: 0.355 # 35.5% exemptions: - type: end_use conditions: { intended_use: "industrial" } documentation_required: ["End Use Certificate"] effective_date: "2019-03-14" regulatory_reference: "https://cbsa-asfc.gc.ca/sima/..." ``` **Section 232 (US Steel/Aluminum):** ```yaml tariff: id: "s232_steel_general" name: "Section 232 - Steel (General)" program: Section232 jurisdiction: US scope: type: destination origin_countries: null # Most countries destination_countries: [US] hs_chapters: ["72", "73"] # Iron and steel rate: type: ad_valorem ad_valorem_rate: 0.25 # 25% exemptions: - type: trade_agreement conditions: { origin_country: [CA, MX], has_quota: true } documentation_required: ["CUSMA Certificate", "Quota Allocation"] - type: product_exclusion conditions: { has_commerce_exclusion: true } documentation_required: ["Commerce Department Exclusion Letter"] effective_date: "2018-03-23" regulatory_reference: "https://ustr.gov/..." ``` **Section 301 (China Tariffs):** ```yaml tariff: id: "s301_list4a" name: "Section 301 - List 4A (China)" program: Section301 jurisdiction: US scope: type: corridor origin_countries: [CN] destination_countries: [US] hs_codes: [...] # Long list of specific HS codes rate: type: ad_valorem ad_valorem_rate: 0.075 # 7.5% (reduced from 15%) exemptions: - type: product_exclusion conditions: { has_ustr_exclusion: true } documentation_required: ["USTR Product Exclusion"] effective_date: "2019-09-01" last_modified: "2020-02-14" # Rate reduced regulatory_reference: "https://ustr.gov/..." ``` ### Tariff Evaluation Engine ```typescript async function evaluateSpecialTariffs( shipment: ShipmentRecord, corridor: Corridor ): Promise<TariffResult[]> { const results: TariffResult[] = []; // Get all potentially applicable tariffs const candidates = await getTariffCandidates( corridor, shipment.products.map(p => p.hs_code) ); for (const tariff of candidates) { for (const product of shipment.products) { // Check scope match if (!matchesScope(tariff, corridor, product)) continue; // Check additional conditions if (!matchesConditions(tariff, product)) continue; // Check exemptions const exemption = await checkExemptions(tariff, shipment, product); if (exemption?.applies) { results.push({ tariff, product, outcome: 'EXEMPT', exemption, evidence_required: exemption.documentation_required }); continue; } // Calculate rate const rate = calculateRate(tariff, product); const duty = product.declared_value * rate; results.push({ tariff, product, outcome: 'APPLIES', rate, duty_amount: duty, evidence_required: tariff.evidence_requirements }); } } return results; } ``` ### Why This Matters 1. **Future-proof:** New tariff programs (trade wars, new anti-dumping cases) = new data, not new code 2. **Self-extending applies:** When we see a new tariff pattern, we add it to the tariff database 3. **Unified reporting:** All special tariffs show up the same way in compliance reports 4. **Exemption tracking:** Same workflow for SIMA exclusions, Section 232 exclusions, quota tracking 5. **Audit trail:** Evidence requirements captured consistently across programs --- ## Unified Documentation & EDI Model **Design Principle:** The same data structure works for any direction. A shipment record doesn't know if it's an "export" or "import" — it just has an origin and destination. ### Unified Shipment Record ```typescript interface ShipmentRecord { // Core identity id: string; tenant_id: string; // Corridor (direction-agnostic) corridor: { origin: { country: CountryCode; state_province?: string; postal_code?: string; }; destination: { country: CountryCode; state_province?: string; postal_code?: string; }; }; // Parties (same structure regardless of direction) parties: { shipper: Party; // Origin side consignee: Party; // Destination side importer_of_record?: Party; exporter_of_record?: Party; customs_broker?: Party; freight_forwarder?: Party; end_user?: Party; // For export controls }; // Products (same structure regardless of direction) products: ProductLine[]; // Values (always in declared currency + USD equivalent) declared_value: Money; freight_cost: Money; insurance_cost: Money; // Classification (applies to both import and export) hs_codes: HSClassification[]; eccn?: string; // For US exports usml_category?: string; // For ITAR // Computed (filled by rule evaluation) compliance_results: ComplianceResult[]; // Documentation references documents: { commercial_invoice?: DocumentRef; packing_list?: DocumentRef; bill_of_lading?: DocumentRef; certificate_of_origin?: DocumentRef; export_license?: DocumentRef; import_permit?: DocumentRef; }; } ``` ### EDI Mapping (Direction-Agnostic) The same shipment record maps to different EDI formats based on context: | EDI Standard | Use Case | Mapped From | |--------------|----------|-------------| | X12 856 (Ship Notice) | Carrier notification | `ShipmentRecord` | | X12 310 (Freight Bill) | Carrier invoice | `ShipmentRecord` + carrier charges | | CUSCAR (Customs Cargo) | Customs declaration | `ShipmentRecord` + `corridor.destination` rules | | AES (Automated Export) | US export filing | `ShipmentRecord` where `corridor.origin = US` | | ACE (Automated Commercial) | US import filing | `ShipmentRecord` where `corridor.destination = US` | | CBSA EDI | Canada import | `ShipmentRecord` where `corridor.destination = CA` | | CDS (formerly CHIEF) | UK import filing | `ShipmentRecord` where `corridor.destination = UK` | | ICS2 / EU Customs | EU import filing | `ShipmentRecord` where `corridor.destination in EU` | **Key insight:** We don't have separate "export shipment" and "import shipment" models. We have ONE model, and the corridor determines which EDI formats and compliance rules apply. ### Example: Same Shipment, Two Perspectives ```typescript // A shipment from US to Canada const shipment: ShipmentRecord = { corridor: { origin: { country: 'US', state_province: 'CA' }, destination: { country: 'CA', state_province: 'ON' } }, // ... rest of record }; // US perspective (export): // - Check ITAR/EAR (origin rules) // - File AES if required (US export filing) // - Apply OFAC screening (US party rules) // Canada perspective (import): // - Check SIMA (destination rules) // - Apply CBSA requirements (destination rules) // - Calculate duties/GST/HST (destination rules) // - File CBSA EDI (Canada import filing) // Both use the SAME shipment record const usCompliance = await evaluateRules(shipment, 'origin'); const caCompliance = await evaluateRules(shipment, 'destination'); ``` ### Document Generation (Direction-Aware) ```typescript // Generate documents based on corridor async function generateDocuments( shipment: ShipmentRecord ): Promise<DocumentSet> { const docs: DocumentSet = {}; // Always generate docs.commercial_invoice = await generateCommercialInvoice(shipment); docs.packing_list = await generatePackingList(shipment); // Origin-specific (export docs) if (shipment.corridor.origin.country === 'US') { if (requiresAES(shipment)) { // Typically required above EEI thresholds or when license conditions apply docs.aes_filing = await generateAESFiling(shipment); } if (requiresExportLicense(shipment)) { docs.export_license_app = await generateExportLicenseApp(shipment); } } // Destination-specific (import docs) if (shipment.corridor.destination.country === 'CA') { docs.cbsa_b3 = await generateCBSAB3(shipment); docs.certificate_of_origin = await generateCOO(shipment, 'CUSMA'); } if (shipment.corridor.destination.country === 'US') { docs.cbp_entry = await generateCBPEntry(shipment); } return docs; } ``` **Implementation note:** `requiresAES()` must enforce EEI filing thresholds and exceptions (for example, generally over $2,500 per Schedule B per destination, plus license-required cases). --- ## The Self-Extending Pattern ### How It Works 1. **Customer hits edge case** → "We're getting SIMA charges on items our rules say are compliant" 2. **System analyzes the gap** → Compares flagged vs missed SKUs, identifies pattern (e.g., "true components") 3. **System proposes rule** → Generates rule definition with conditions and evidence template 4. **Human approves or edits** → Rule goes live 5. **Rule compounds** → Now catches that pattern for all future SKUs, across all customers ### Example: Wayfair True Components (Corridor-Aware) ```yaml # Edge case discovered trigger: "True components slip through country-to-country rules" # System generates rule — NOTE: corridor-scoped generated_rule: id: "sima_true_component_check" name: "True Component SIMA Screening" version: 1 # CORRIDOR SCOPE — This rule only fires for these corridors scope: type: destination destination_country: CA applies_to_corridors: - US→CA - CN→CA - VN→CA description: | Flag SKUs marked as true components that inherit parent COO but ship independently. These can slip through COO rules and trigger SIMA exposure on Canada imports. conditions: - attribute: "component_type" equals: "true_component" - attribute: "ships_independently" equals: true - parent.country_of_origin: in: ["CN", "VN"] # SIMA-relevant origins - hs_code: matches_sima_category: true action: FLAG_FOR_REVIEW severity: RED evidence_template: | True component {sku} inherits COO from {parent_sku} but ships independently. Parent COO: {parent.country_of_origin}. Corridor: {corridor.origin}→{corridor.destination}. SIMA exposure: {sima_category}. metadata: source: "wayfair_dec_2025_spike" created_by: "system_analysis" approved_by: null # Requires human approval coverage_estimate: 622 # SKUs this would have caught corridor_learned_from: "US→CA" # Could apply to other →CA corridors ``` ### Example: ITAR Screening (Origin-Based) ```yaml # Rule that applies to ALL exports from US, regardless of destination generated_rule: id: "itar_defense_article_screen" name: "ITAR Defense Article Screening" version: 1 scope: type: origin origin_country: US destination_country: null # ALL destinations conditions: - OR: - hs_code IN itar_controlled_hs_codes - product_category IN usml_categories - description MATCHES itar_keywords action: BLOCK_PENDING_LICENSE severity: CRITICAL evidence_template: | Product {sku} may be controlled under ITAR. USML Category: {usml_category}. This applies to ALL exports from the US, including to allies. State Department export license required before shipping. ``` ### Example: Denied Party Match (Party-Based) ```yaml # Rule that fires on party match, regardless of product generated_rule: id: "ofac_sdn_block" name: "OFAC SDN Denied Party Block" version: 1 scope: type: party applies_when_origin: US # OFAC applies to US-nexus transactions conditions: - party_name FUZZY_MATCHES ofac_sdn_list - match_score >= 0.85 action: BLOCK severity: CRITICAL evidence_template: | Transaction party "{party_name}" ({party_role}) matches OFAC SDN entry. Match: {matched_entry} (score: {match_score}). All transactions with this party are prohibited. Do not proceed without OFAC license. ``` --- ## Implementation Architecture ### Rule Generation Pipeline ```typescript // 1. Detect gap async function detectRuleGap( missed: SKU[], // SKUs that should have been flagged caught: SKU[], // SKUs correctly flagged context: string // Human description of the gap ): Promise<GapAnalysis> { // Compare attributes between missed and caught const differentiators = await findDifferentiatingAttributes(missed, caught); return { pattern: differentiators, confidence: calculatePatternConfidence(differentiators), sample_size: missed.length + caught.length }; } // 2. Generate rule proposal async function proposeRule( gap: GapAnalysis, context: string ): Promise<ProposedRule> { const rule = await generateRuleFromPattern(gap.pattern, context); return { rule, confidence: gap.confidence, coverage_estimate: estimateCoverage(rule), requires_approval: true, evidence_template: generateEvidenceTemplate(rule) }; } // 3. Human review and approval interface RuleApproval { rule_id: string; approved: boolean; modifications?: Partial<Rule>; approved_by: string; approved_at: Date; } // 4. Activate rule async function activateRule( approval: RuleApproval ): Promise<ActiveRule> { const rule = await applyModifications(approval); await addToRuleset(rule); await rerunOnExistingData(rule); // Catch historical gaps return rule; } ``` ### Rule Storage Schema ```sql CREATE TABLE compliance_rules ( id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, version INT NOT NULL, description TEXT, -- Rule definition conditions JSONB NOT NULL, action VARCHAR(50) NOT NULL, severity VARCHAR(20) NOT NULL, evidence_template TEXT, -- Lifecycle status VARCHAR(20) DEFAULT 'proposed', -- proposed, approved, active, deprecated created_at TIMESTAMP DEFAULT NOW(), approved_at TIMESTAMP, approved_by UUID REFERENCES users(id), -- Provenance source_type VARCHAR(50), -- manual, system_analysis, customer_request source_reference VARCHAR(255), -- e.g., "wayfair_dec_2025_spike" -- Performance times_triggered INT DEFAULT 0, last_triggered_at TIMESTAMP, false_positive_rate DECIMAL(5,4), -- Applicability tenant_scope VARCHAR(20) DEFAULT 'global', -- global, tenant-specific tenant_id UUID REFERENCES tenants(id) ); CREATE INDEX idx_rules_active ON compliance_rules(status) WHERE status = 'active'; CREATE INDEX idx_rules_tenant ON compliance_rules(tenant_id); ``` --- ## The Moat This Creates ### Network Effects ``` Customer A edge case → New rule Rule catches issue for Customer B (before they even know they have it) Customer B edge case → Refined rule Rule library grows with each customer New customers get immediate coverage (rules already exist for common patterns) ``` ### Competitive Advantage | Approach | RGL8R Self-Extending | Competitors | |----------|---------------------|-------------| | Rule creation | System proposes, human approves | Manual rule writing | | Time to new rule | Hours (from edge case detection) | Weeks/months | | Coverage growth | Compounds with each customer | Linear with dev effort | | Edge case handling | Becomes a rule automatically | Requires feature request | --- ## Adoption Path ### Phase 1: Foundation (Current → Q2 2026) - Implement core primitives (VALIDATE, SCREEN_PRODUCT, SCREEN_PARTY, MATCH, EVIDENCE) - Build rule storage and execution engine - Manual rule creation only (no self-extension yet) ### Phase 2: Analysis Layer (Q2-Q3 2026) - Add gap detection: compare expected vs actual flags - Build pattern analysis: what attributes differentiate missed vs caught - Generate rule proposals (system suggests, human writes) ### Phase 3: Self-Extension (Q4 2026+) - Full rule generation from patterns - Human approval workflow - Cross-tenant rule sharing (anonymized patterns) - Rule performance tracking and refinement --- ## Risks and Mitigations | Risk | Mitigation | |------|------------| | Bad rules propagate | Require human approval; track false positive rates | | Over-fitting to one customer | Require minimum sample size; test on holdout data | | Rule conflicts | Priority system; newer rules don't override without review | | Performance degradation | Rule indexing; lazy evaluation for low-probability rules | --- ## What This Unlocks 1. **Faster onboarding** - New customer, new edge cases, rules generated in-session 2. **Network effects** - Every customer's edge case improves the system for everyone 3. **AI-native positioning** - The system improves itself; not just "using AI" 4. **Defensible moat** - The rule corpus is the asset, not just the code --- ## Connection to Pi Principles | Pi Principle | RGL8R Application | |--------------|-------------------| | Five primitives | VALIDATE, SCREEN_PRODUCT, SCREEN_PARTY, MATCH, EVIDENCE | | Self-extending | Rules generated from edge cases, tagged with corridor scope | | Minimal system prompt | Simple rule DSL with corridor parameter, not complex logic | | Composability | Complex compliance = primitive combinations across rule layers | > "AI amplifies structure when structure exists." The self-extending pattern means the structure grows automatically. Each edge case adds structure. The AI gets better not because the model improves, but because the rule corpus compounds. --- ## Phase 1 Implementation Note **The architecture is corridor-agnostic. The Phase 1 implementation is corridor-specific.** Phase 1 focuses on: - **Corridors:** US→CA (primary), CN→CA (for SIMA) - **Rule layers:** Universal, Destination (SIMA/CBSA), Corridor (CUSMA) - **Not yet:** Origin rules (ITAR/EAR), Party rules (denied party screening), Finance rules This is intentional. The primitives accept corridor as a parameter from day one. Phase 1 populates the Canada destination rules. Phase 2+ adds: - Origin rules (US export controls) - Party screening (OFAC, BIS lists) - Additional destination rules (US, UK, EU) - Finance rules (payment processor restrictions) **Why this matters:** A customer using RGL8R for US→CA today will automatically benefit when we add US→UK rules — same SKU data, same primitives, new corridor rules. ``` Phase 1: Populate rules for corridor US→CA ├── SIMA screening (destination: CA) ├── CBSA compliance (destination: CA) └── CUSMA preferential (corridor: US→CA) Phase 2: Add origin rules for US exports ├── ITAR screening (origin: US) ├── EAR/ECCN screening (origin: US) └── Denied party screening (origin: US) Phase 3: Add destination rules for new markets ├── UK destination rules ├── EU destination rules └── US destination rules (for imports TO US) ``` --- **Next Steps:** 1. Review with engineering for feasibility 2. Identify first candidate edge case for pilot 3. Design human approval UX 4. Define rule DSL specification 5. Implement corridor parameter in primitives (Phase 1) 6. Populate Canada destination rules (Phase 1) 7. Add origin rules (ITAR/EAR) and party screening (Phase 2) --- ## Changelog **v1.2 (February 2026):** - Clarified Section 232 (steel/aluminum, national security) vs Section 301 (China, unfair trade) - Added Generic Special Tariff Model (handles ANY tariff program: SIMA, Section 232/301, EU anti-dumping, future programs) - Added Universal Tariff Schema with rate types, exemptions, evidence requirements - Added example implementations: SIMA, Section 232, Section 301 - Added Tariff Evaluation Engine pseudocode - Added Unified Documentation & EDI Model (direction-agnostic shipment records) - Added EDI mapping table (X12, CUSCAR, AES, ACE, CBSA) - Added document generation flow (origin-specific vs destination-specific) **v1.1 (February 2026):** - Added corridor as first-class parameter to all primitives - Split SCREEN into SCREEN_PRODUCT and SCREEN_PARTY - Added Rule Inheritance Model (universal → origin → destination → corridor → party → product → finance → carrier) - Added Export Controls section (ITAR, EAR) - Added Denied Party Screening section - Added corridor-aware examples (Wayfair, ITAR, OFAC) - Added Phase 1 Implementation Note clarifying architecture vs implementation scope