← Tasks
CHINN — Chapter Hierarchy Intelligence Neural Network
cancelledcode_genP1
Description
## CHINN — Chapter Hierarchy Intelligence Neural Network
### Origin
Jack Chang (Cubeship/C8 QP-in-training) identified that classification needs chapter-specific domain expertise, not one monolithic model. His insight: "chapter by chapter subagents — ontology mapping we need to finesse." This maps directly to CBP's 10 Centers of Excellence and Expertise (CEEs), which already organize trade enforcement by industry domain.
### What CHINN Does
CHINN is a **Layer 2 Trade Operations INN** that routes classification requests to chapter-specialized logic. It sits between UINN (user intent) and the existing INNs (RINN, TEINN, OINN, FINN), adding a chapter-awareness layer that no current INN provides.
**Flow:**
```
Product → UINN (intent) → CHINN (chapter router) → Chapter Specialist → RINN/OINN/FINN
```
**Why it's not TEINN:** TEINN handles tariff *engineering* (strategic manipulation). CHINN handles *domain expertise* (a textiles specialist knows different classification signals than a metals specialist).
### Architecture Requirements
#### 1. CEE Domain Registry
Map CBP's 10 CEEs to HTS chapter ranges. Each domain defines:
- Chapter range (e.g., CEE004 Apparel = Ch. 50-67)
- Classification signals (what matters for this domain: material composition? function? use?)
- PGA agencies involved (FDA, FWS, CPSC, EPA, etc.)
- Trade agreement gotchas (USMCA content thresholds vary by chapter)
- Risk flags (UFLPA for textiles, CBAM for metals, §301 for electronics)
```python
class CEEDomain(Enum):
PHARMA_HEALTH_CHEMICALS = "CEE001" # Ch. 28-30, 33-34, 38
AGRICULTURE_PREPARED = "CEE002" # Ch. 01-24
AUTOMOTIVE_AEROSPACE = "CEE003" # Ch. 87-88
APPAREL_FOOTWEAR_TEXTILES = "CEE004" # Ch. 50-67
BASE_METALS = "CEE005" # Ch. 72-83
PETROLEUM_GAS_MINERALS = "CEE006" # Ch. 25-27
ELECTRONICS = "CEE007" # Ch. 84-85 (partial)
CONSUMER_MASS_MERCH = "CEE008" # Mixed: 39, 42, 69, 94-96
INDUSTRIAL_MANUFACTURING = "CEE009" # Ch. 39-40, 44, 68-70
MACHINERY = "CEE010" # Ch. 84-85, 90
```
#### 2. Chapter Router
Given a product description + initial HS2/HS4 candidate, determine:
- Which CEE domain owns this product
- What classification signals to prioritize
- Which PGA agencies to pre-screen
- Which GRI rules are most likely to apply
The router should handle ambiguous cases (e.g., a "smart watch" could be CEE007 Electronics or CEE008 Consumer — essential character determines routing).
#### 3. Chapter Specialist Config
Each CEE domain gets a specialist config (NOT a separate model — a prompt template + signal weights):
```python
@dataclass
class ChapterSpecialist:
domain: CEEDomain
chapter_range: list[str] # ["50", "51", ..., "67"]
classification_signals: list[str] # ["material_composition", "weave_type", "fiber_content"]
primary_gri: list[GRIRule] # Which GRI rules dominate this domain
pga_agencies: list[str] # ["CPSC", "FTC", "CBP"]
risk_flags: list[str] # ["UFLPA", "cotton_provenance", "COO_marking"]
de_minimis_patterns: dict # Domain-specific de minimis behaviors
fta_rules: dict # Domain-specific FTA qualification rules (e.g., yarn-forward for textiles)
```
#### 4. Pattern Bus Integration
Add `CHAPTER` pattern type to PatternType enum in `pattern_bus.py`:
```python
CHAPTER = "chapter" # Chapter routing decisions (from CHINN)
```
CHINN publishes patterns like:
- `chapter:route:abc123` → ChapterRoutingResult (which domain, which specialist, confidence)
- `chapter:signals:abc123` → ChapterSignals (what to look for in this domain)
- `chapter:qp:jack` → QPCertification (which chapters Jack is certified for)
CHINN subscribes to:
- `classification:*` patterns from VINN/UINN (initial candidates to route)
- `regulatory:*` patterns from RINN (domain-specific rule changes)
#### 5. QP Certification Tracking
Jack is C8's first QP (Qualified Person) in training. CHINN should track:
- Which chapters a QP is certified for
- Certification date and expiration
- Ruling history per chapter (Jack's track record)
- Escalation rules (when to auto-route vs require QP review)
```python
@dataclass
class QPCertification:
qp_name: str # "Jack Chang"
certified_chapters: list[str] # ["61", "62", "63"]
certification_date: date
rulings_count: int # How many classifications in these chapters
accuracy_rate: float # Tracked against CBP rulings
cee_domain: CEEDomain # CEE004
```
#### 6. Jack's 4 Intake Questions as CHINN Signals
Jack's real-world broker workflow defines the input schema for CHINN:
1. **Visual/SKU** → `analyze_product` output → CHINN routes by detected product type
2. **COO tags** → OINN origin signal + CHINN checks if chapter requires COO marking (19 CFR 134)
3. **Price points** → FINN declared value → CHINN determines H7/H1 path + LDP routing
4. **Upstream materials** → OINN provenance + CHINN checks domain-specific supply chain rules (UFLPA for Ch. 50-67, CBAM for Ch. 72-83)
### File Location
`oneworld_trade/agents/chinn.py`
### Conventions (match existing INNs)
- Dataclasses + Enums (see teinn.py, rinn.py pattern)
- No Flask, no DB at module level — pure Python, testable standalone
- Supabase integration via optional import (see rinn.py lines 33-37)
- Pattern Bus integration via publish/subscribe (see pattern_bus.py)
- Docstring header explaining the INN's philosophy (see rinn.py "never embed regulatory state" / teinn.py "Merritt v. Welsh")
### CHINN's Philosophy (for docstring)
"Classify by domain, not by code. A textile specialist sees fiber content where a metals specialist sees alloy grade. The chapter determines what matters — CHINN routes the question to the expert who knows what to look for."
### Deliverables
1. `oneworld_trade/agents/chinn.py` — Full CHINN implementation with CEE registry, chapter router, specialist configs, QP tracking
2. Add `CHAPTER` to `PatternType` enum in `pattern_bus.py`
3. Unit tests: `tests/test_chinn.py` — route ceramic mug → CEE008, steel beam → CEE005, silk scarf → CEE004, smart watch → CEE007/CEE008 disambiguation
4. One worked example: Jack's textile intake (Ch. 61-62) showing full flow from product description through CHINN routing to specialist signals
### Context
- CBP CEE directory: https://www.cbp.gov/trade/centers-excellence-and-expertise-information/cee-directory
- Existing INNs: `oneworld_trade/agents/*.py` (25 INNs, Pattern Bus)
- TEINN pattern: `oneworld_trade/agents/teinn.py` (closest precedent)
- RINN pattern: `oneworld_trade/agents/rinn.py` (dynamic vs embedded principle)
- Jack's QP path: First CBP filing target, ABI VPN onboarding in progress
Assignee
-
Claimed By
Cloud Lu → Claude Sonnet
Created
13h ago
Completed
13h ago
Quality
Overall
56%
Pass
FAIL
Graded By
-
Graded At
-
Cost
Input Tokens
-
Output Tokens
-
Est. USD
-
Result
{
"cost": {
"input_tokens": 2062,
"estimated_usd": 0.138216,
"output_tokens": 8802
},
"model": "claude-sonnet-4-20250514",
"status": "success",
"transport": "anthropic_api",
"latency_ms": 358100,
"response_text": "I'll implement CHINN (Chapter Hierarchy Intelligence Neural Network) following the existing INN patterns and Jack's domain expertise insight.\n\n## 1. Core CHINN Implementation\n\n```python\n# oneworld_trade/agents/chinn.py\n\"\"\"\nCHINN — Chapter Hierarchy Intelligence Neural Network\n\nPhilosophy: \"Classify by domain, not by code. A textile specialist sees fiber content \nwhere a metals specialist sees alloy grade. The chapter determines what matters — \nCHINN routes the question to the expert who knows what to look for.\"\n\nOrigin: Jack Chang's insight that classification needs chapter-specific domain expertise,\nnot one monolithic model. Maps to CBP's 10 Centers of Excellence and Expertise (CEEs).\n\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom datetime import date, datetime\nfrom typing import Dict, List, Optional, Union, Any\nimport json\nimport re\n\ntry:\n from supabase import create_client, Client\n SUPABASE_AVAILABLE = True\nexcept ImportError:\n SUPABASE_AVAILABLE = False\n\nfrom .pattern_bus import PatternBus, PatternType\n\n\nclass CEEDomain(Enum):\n \"\"\"CBP's 10 Centers of Excellence and Expertise mapped to HTS chapter ranges\"\"\"\n PHARMA_HEALTH_CHEMICALS = \"CEE001\" # Ch. 28-30, 33-34, 38\n AGRICULTURE_PREPARED = \"CEE002\" # Ch. 01-24\n AUTOMOTIVE_AEROSPACE = \"CEE003\" # Ch. 87-88\n APPAREL_FOOTWEAR_TEXTILES = \"CEE004\" # Ch. 50-67\n BASE_METALS = \"CEE005\" # Ch. 72-83\n PETROLEUM_GAS_MINERALS = \"CEE006\" # Ch. 25-27\n ELECTRONICS = \"CEE007\" # Ch. 84-85 (partial)\n CONSUMER_MASS_MERCH = \"CEE008\" # Mixed: 39, 42, 69, 94-96\n INDUSTRIAL_MANUFACTURING = \"CEE009\" # Ch. 39-40, 44, 68-70\n MACHINERY = \"CEE010\" # Ch. 84-85, 90\n\n\nclass GRIRule(Enum):\n \"\"\"General Rules of Interpretation priority by domain\"\"\"\n GRI1_HEADING_TEXT = \"gri1_heading\"\n GRI2_INCOMPLETE_UNFINISHED = \"gri2_incomplete\"\n GRI3_MOST_SPECIFIC = \"gri3_specific\"\n GRI3B_ESSENTIAL_CHARACTER = \"gri3b_character\"\n GRI3C_LAST_HEADING = \"gri3c_last\"\n GRI4_MOST_SIMILAR = \"gri4_similar\"\n GRI5_CONTAINERS = \"gri5_containers\"\n GRI6_SUBHEADINGS = \"gri6_subheadings\"\n\n\n@dataclass\nclass ChapterSignals:\n \"\"\"What matters for classification within a specific domain\"\"\"\n chapter: str\n material_composition: bool = False\n essential_character: bool = False\n end_use: bool = False\n manufacturing_process: bool = False\n physical_properties: bool = False\n chemical_properties: bool = False\n fiber_content: bool = False\n alloy_grade: bool = False\n voltage_rating: bool = False\n weave_type: bool = False\n origin_marking_required: bool = False\n \n def __post_init__(self):\n \"\"\"Set domain-specific signal priorities\"\"\"\n ch = int(self.chapter)\n \n # Textiles (Ch. 50-67)\n if 50 <= ch <= 67:\n self.material_composition = True\n self.fiber_content = True\n self.weave_type = True\n self.origin_marking_required = True\n \n # Base metals (Ch. 72-83)\n elif 72 <= ch <= 83:\n self.alloy_grade = True\n self.physical_properties = True\n self.manufacturing_process = True\n \n # Electronics (Ch. 84-85)\n elif ch in [84, 85]:\n self.essential_character = True\n self.voltage_rating = True\n self.end_use = True\n\n\n@dataclass\nclass ChapterSpecialist:\n \"\"\"Domain-specific classification configuration\"\"\"\n domain: CEEDomain\n chapter_range: List[str]\n classification_signals: List[str]\n primary_gri: List[GRIRule]\n pga_agencies: List[str]\n risk_flags: List[str]\n de_minimis_patterns: Dict[str, Any] = field(default_factory=dict)\n fta_rules: Dict[str, str] = field(default_factory=dict)\n \n @classmethod\n def get_textiles_specialist(cls) -> 'ChapterSpecialist':\n \"\"\"Jack's domain: Apparel, Footwear & Textiles\"\"\"\n return cls(\n domain=CEEDomain.APPAREL_FOOTWEAR_TEXTILES,\n chapter_range=[str(i) for i in range(50, 68)], # Ch. 50-67\n classification_signals=[\n \"material_composition\", \"fiber_content\", \"weave_type\",\n \"knit_vs_woven\", \"essential_character\", \"end_use\"\n ],\n primary_gri=[\n GRIRule.GRI3B_ESSENTIAL_CHARACTER,\n GRIRule.GRI1_HEADING_TEXT,\n GRIRule.GRI3_MOST_SPECIFIC\n ],\n pga_agencies=[\"CPSC\", \"FTC\", \"CBP\"],\n risk_flags=[\"UFLPA\", \"cotton_provenance\", \"COO_marking\", \"fiber_labeling\"],\n fta_rules={\n \"USMCA\": \"yarn_forward_rule\",\n \"CAFTA\": \"cut_and_sewn_rule\",\n \"TPL\": \"fabric_forward_rule\"\n },\n de_minimis_patterns={\n \"elastic_band\": \"7_percent_weight\",\n \"labels_tags\": \"de_minimis_findings\",\n \"thread\": \"assembly_operation\"\n }\n )\n\n\n@dataclass\nclass QPCertification:\n \"\"\"Qualified Person certification tracking\"\"\"\n qp_name: str\n certified_chapters: List[str]\n certification_date: date\n rulings_count: int = 0\n accuracy_rate: float = 0.0\n cee_domain: Optional[CEEDomain] = None\n expiration_date: Optional[date] = None\n \n def is_certified_for_chapter(self, chapter: str) -> bool:\n \"\"\"Check if QP is certified for specific chapter\"\"\"\n return chapter in self.certified_chapters\n \n def is_valid(self) -> bool:\n \"\"\"Check if certification is current\"\"\"\n if self.expiration_date:\n return date.today() <= self.expiration_date\n return True\n\n\n@dataclass\nclass ChapterRoutingResult:\n \"\"\"Result of CHINN chapter routing decision\"\"\"\n product_id: str\n detected_chapter: str\n cee_domain: CEEDomain\n specialist: ChapterSpecialist\n confidence: float\n routing_signals: ChapterSignals\n escalation_required: bool = False\n qp_required: bool = False\n ambiguous_chapters: List[str] = field(default_factory=list)\n reasoning: str = \"\"\n\n\nclass CHINN:\n \"\"\"Chapter Hierarchy Intelligence Neural Network - Layer 2 Trade Operations INN\"\"\"\n \n def __init__(self, supabase_url: Optional[str] = None, supabase_key: Optional[str] = None):\n self.supabase = None\n if SUPABASE_AVAILABLE and supabase_url and supabase_key:\n self.supabase = create_client(supabase_url, supabase_key)\n \n self.pattern_bus = PatternBus()\n self.specialists = self._initialize_specialists()\n self.qp_certifications = self._load_qp_certifications()\n \n # Subscribe to relevant patterns\n self.pattern_bus.subscribe(PatternType.CLASSIFICATION, self._handle_classification_pattern)\n self.pattern_bus.subscribe(PatternType.REGULATORY, self._handle_regulatory_pattern)\n \n def _initialize_specialists(self) -> Dict[CEEDomain, ChapterSpecialist]:\n \"\"\"Initialize all CEE domain specialists\"\"\"\n specialists = {}\n \n # Textiles specialist (Jack's domain)\n specialists[CEEDomain.APPAREL_FOOTWEAR_TEXTILES] = ChapterSpecialist.get_textiles_specialist()\n \n # Base metals specialist\n specialists[CEEDomain.BASE_METALS] = ChapterSpecialist(\n domain=CEEDomain.BASE_METALS,\n chapter_range=[str(i) for i in range(72, 84)],\n classification_signals=[\"alloy_grade\", \"manufacturing_process\", \"physical_properties\"],\n primary_gri=[GRIRule.GRI1_HEADING_TEXT, GRIRule.GRI3_MOST_SPECIFIC],\n pga_agencies=[\"EPA\", \"DOC\", \"CBP\"],\n risk_flags=[\"CBAM\", \"section232\", \"antidumping\"],\n fta_rules={\"USMCA\": \"substantial_transformation\"}\n )\n \n # Electronics specialist\n specialists[CEEDomain.ELECTRONICS] = ChapterSpecialist(\n domain=CEEDomain.ELECTRONICS,\n chapter_range=[\"84\", \"85\"],\n classification_signals=[\"essential_character\", \"voltage_rating\", \"end_use\"],\n primary_gri=[GRIRule.GRI3B_ESSENTIAL_CHARACTER, GRIRule.GRI6_SUBHEADINGS],\n pga_agencies=[\"FCC\", \"CPSC\", \"DOE\"],\n risk_flags=[\"section301\", \"entity_list\", \"itar\"],\n fta_rules={\"USMCA\": \"regional_value_content\"}\n )\n \n # Consumer goods specialist\n specialists[CEEDomain.CONSUMER_MASS_MERCH] = ChapterSpecialist(\n domain=CEEDomain.CONSUMER_MASS_MERCH,\n chapter_range=[\"39\", \"42\", \"69\", \"94\", \"95\", \"96\"],\n classification_signals=[\"essential_character\", \"end_use\", \"material_composition\"],\n primary_gri=[GRIRule.GRI3B_ESSENTIAL_CHARACTER, GRIRule.GRI1_HEADING_TEXT],\n pga_agencies=[\"CPSC\", \"FTC\", \"CBP\"],\n risk_flags=[\"lead_content\", \"phthalates\", \"COO_marking\"]\n )\n \n return specialists\n \n def _load_qp_certifications(self) -> Dict[str, QPCertification]:\n \"\"\"Load QP certifications - Jack as first QP\"\"\"\n qp_certs = {}\n \n # Jack's certification (in training)\n jack_cert = QPCertification(\n qp_name=\"Jack Chang\",\n certified_chapters=[str(i) for i in range(61, 64)], # Ch. 61-63 (apparel)\n certification_date=date(2024, 1, 1),\n rulings_count=0, # Training phase\n accuracy_rate=0.0,\n cee_domain=CEEDomain.APPAREL_FOOTWEAR_TEXTILES,\n expiration_date=date(2025, 1, 1)\n )\n qp_certs[\"jack_chang\"] = jack_cert\n \n return qp_certs\n \n def route_by_chapter(self, product_description: str, candidate_chapters: List[str]) -> ChapterRoutingResult:\n \"\"\"Route classification request to appropriate chapter specialist\"\"\"\n \n if not candidate_chapters:\n raise ValueError(\"At least one candidate chapter required for routing\")\n \n # For single chapter, route directly\n if len(candidate_chapters) == 1:\n chapter = candidate_chapters[0]\n domain = self._chapter_to_domain(chapter)\n specialist = self.specialists.get(domain)\n \n if not specialist:\n # Fallback for domains not yet implemented\n return self._create_fallback_routing(product_description, chapter)\n \n signals = ChapterSignals(chapter=chapter)\n \n result = ChapterRoutingResult(\n product_id=self._generate_product_id(product_description),\n detected_chapter=chapter,\n cee_domain=domain,\n specialist=specialist,\n confidence=0.9,\n routing_signals=signals,\n reasoning=f\"Direct routing to {domain.value} for chapter {chapter}\"\n )\n \n # Check QP requirements\n result.qp_required = self._requires_qp_review(chapter, product_description)\n \n return result\n \n # Handle ambiguous routing (multiple candidates)\n return self._resolve_ambiguous_routing(product_description, candidate_chapters)\n \n def _chapter_to_domain(self, chapter: str) -> CEEDomain:\n \"\"\"Map HTS chapter to CEE domain\"\"\"\n ch = int(chapter)\n \n if 1 <= ch <= 24:\n return CEEDomain.AGRICULTURE_PREPARED\n elif 25 <= ch <= 27:\n return CEEDomain.PETROLEUM_GAS_MINERALS\n elif ch in [28, 29, 30, 33, 34, 38]:\n return CEEDomain.PHARMA_HEALTH_CHEMICALS\n elif 39 <= ch <= 40 or ch in [44, 68, 69, 70]:\n return CEEDomain.INDUSTRIAL_MANUFACTURING\n elif 50 <= ch <= 67:\n return CEEDomain.APPAREL_FOOTWEAR_TEXTILES\n elif 72 <= ch <= 83:\n return CEEDomain.BASE_METALS\n elif ch in [84, 85]:\n # Disambiguation between electronics and machinery\n return CEEDomain.ELECTRONICS # Default, needs product analysis\n elif ch in [87, 88]:\n return CEEDomain.AUTOMOTIVE_AEROSPACE\n elif ch in [39, 42, 69, 94, 95, 96]:\n return CEEDomain.CONSUMER_MASS_MERCH\n else:\n return CEEDomain.INDUSTRIAL_MANUFACTURING # Fallback\n \n def _resolve_ambiguous_routing(self, product_description: str, candidates: List[str]) -> ChapterRoutingResult:\n \"\"\"Handle products that could fit multiple chapters\"\"\"\n \n # Smart watch example: could be Ch. 85 (electronics) or Ch. 91 (watches)\n if self._contains_keywords(product_description, [\"smart\", \"watch\", \"fitness\"]):\n if \"85\" in candidates and \"91\" in candidates:\n # Essential character analysis - computing function vs timekeeping\n if self._contains_keywords(product_description, [\"app\", \"bluetooth\", \"wifi\", \"processor\"]):\n chapter = \"85\"\n reasoning = \"Essential character: computing device with timekeeping function\"\n else:\n chapter = \"91\"\n reasoning = \"Essential character: timepiece with computing features\"\n \n domain = self._chapter_to_domain(chapter)\n specialist = self.specialists.get(domain)\n \n return ChapterRoutingResult(\n product_id=self._generate_product_id(product_description),\n detected_chapter=chapter,\n cee_domain=domain,\n specialist=specialist or self._get_fallback_specialist(),\n confidence=0.7, # Lower confidence for ambiguous cases\n routing_signals=ChapterSignals(chapter=chapter),\n ambiguous_chapters=[c for c in candidates if c != chapter],\n reasoning=reasoning,\n escalation_required=True # Ambiguous cases need review\n )\n \n # Default: route to first candidate with escalation\n primary_chapter = candidates[0]\n domain = self._chapter_to_domain(primary_chapter)\n \n return ChapterRoutingResult(\n product_id=self._generate_product_id(product_description),\n detected_chapter=primary_chapter,\n cee_domain=domain,\n specialist=self.specialists.get(domain) or self._get_fallback_specialist(),\n confidence=0.5, # Low confidence for unresolved ambiguity\n routing_signals=ChapterSignals(chapter=primary_chapter),\n ambiguous_chapters=candidates[1:],\n reasoning=f\"Ambiguous routing - defaulting to {primary_chapter}, review required\",\n escalation_required=True\n )\n \n def _contains_keywords(self, text: str, keywords: List[str]) -> bool:\n \"\"\"Check if text contains any of the keywords\"\"\"\n text_lower = text.lower()\n return any(keyword.lower() in text_lower for keyword in keywords)\n \n def _requires_qp_review(self, chapter: str, product_description: str) -> bool:\n \"\"\"Determine if product requires Qualified Person review\"\"\"\n \n # High-risk chapters always require QP\n high_risk_chapters = [\"50\", \"51\", \"52\", \"61\", \"62\", \"63\"] # Textiles with UFLPA risk\n if chapter in high_risk_chapters:\n return True\n \n # Complex products require QP\n if self._contains_keywords(product_description, [\"composite\", \"multi-material\", \"hybrid\"]):\n return True\n \n return False\n \n def _create_fallback_routing(self, product_description: str, chapter: str) -> ChapterRoutingResult:\n \"\"\"Create fallback routing for domains not yet implemented\"\"\"\n return ChapterRoutingResult(\n product_id=self._generate_product_id(product_description),\n detected_chapter=chapter,\n cee_domain=CEEDomain.INDUSTRIAL_MANUFACTURING, # Generic fallback\n specialist=self._get_fallback_specialist(),\n confidence=0.3,\n routing_signals=ChapterSignals(chapter=chapter),\n reasoning=f\"Fallback routing - specialist not implemented for chapter {chapter}\",\n escalation_required=True\n )\n \n def _get_fallback_specialist(self) -> ChapterSpecialist:\n \"\"\"Generic specialist for unimplemented domains\"\"\"\n return ChapterSpecialist(\n domain=CEEDomain.INDUSTRIAL_MANUFACTURING,\n chapter_range=[],\n classification_signals=[\"essential_character\", \"end_use\"],\n primary_gri=[GRIRule.GRI1_HEADING_TEXT],\n pga_agencies=[\"CBP\"],\n risk_flags=[]\n )\n \n def _generate_product_id(self, description: str) -> str:\n \"\"\"Generate unique product ID from description\"\"\"\n import hashlib\n return hashlib.md5(f\"{description}_{datetime.now().isoformat()}\".encode()).hexdigest()[:12]\n \n def _handle_classification_pattern(self, pattern: Any) -> None:\n \"\"\"Handle incoming classification patterns from other INNs\"\"\"\n # Route classification requests through CHINN\n self.pattern_bus.publish(PatternType.CHAPTER, f\"chapter:route:{pattern.id}\", pattern)\n \n def _handle_regulatory_pattern(self, pattern: Any) -> None:\n \"\"\"Handle regulatory updates that affect chapter routing\"\"\"\n # Update specialist configurations based on regulatory changes\n pass\n \n def get_jack_intake_signals(self, chapter: str) -> Dict[str, bool]:\n \"\"\"Jack's 4 intake questions mapped to CHINN signals\"\"\"\n return {\n \"visual_sku_required\": True, # Always need product visual\n \"coo_tags_required\": chapter in [str(i) for i in range(50, 68)], # Textiles need COO\n \"price_points_required\": True, # Always need declared value\n \"upstream_materials_required\": chapter in [\"50\", \"51\", \"52\", \"61\", \"62\", \"63\"] # UFLPA chapters\n }\n\n\n# Pattern Bus integration\ndef register_chapter_pattern():\n \"\"\"Add CHAPTER pattern type to PatternBus\"\"\"\n if not hasattr(PatternType, 'CHAPTER'):\n PatternType.CHAPTER = \"chapter\"\n```\n\n## 2. Pattern Bus Update\n\n```python\n# In oneworld_trade/agents/pattern_bus.py - Add to PatternType enum\n\nclass PatternType(Enum):\n # ... existing patterns ...\n CHAPTER = \"chapter\" # Chapter routing decisions (from CHINN)\n```\n\n## 3. Unit Tests\n\n```python\n# tests/test_chinn.py\n\"\"\"\nTest suite for CHINN (Chapter Hierarchy Intelligence Neural Network)\n\"\"\"\n\nimport pytest\nfrom datetime import date\nfrom oneworld_trade.agents.chinn import (\n CHINN, CEEDomain, ChapterSpecialist, QPCertification, \n ChapterSignals, ChapterRoutingResult\n)\n\n\nclass TestCHINN:\n \n def setup_method(self):\n \"\"\"Setup CHINN instance for testing\"\"\"\n self.chinn = CHINN()\n \n def test_ceramic_mug_routing(self):\n \"\"\"Test routing ceramic mug to CEE008 (Consumer Mass Merch)\"\"\"\n result = self.chinn.route_by_chapter(\n \"ceramic coffee mug with handle\",\n [\"69\"] # Chapter 69: Ceramic products\n )\n \n assert result.detected_chapter == \"69\"\n assert result.cee_domain == CEEDomain.CONSUMER_MASS_MERCH\n assert result.confidence > 0.8\n assert \"ceramic\" in result.reasoning.lower() or result.cee_domain == CEEDomain.CONSUMER_MASS_MERCH\n \n def test_steel_beam_routing(self):\n \"\"\"Test routing steel beam to CEE005 (Base Metals)\"\"\"\n result = self.chinn.route_by_chapter(\n \"structural steel I-beam, galvanized\",\n [\"73\"] # Chapter 73: Iron and steel articles\n )\n \n assert result.detected_chapter == \"73\"\n assert result.cee_domain == CEEDomain.BASE_METALS\n assert result.specialist.domain == CEEDomain.BASE_METALS\n assert \"alloy_grade\" in result.specialist.classification_signals\n assert result.confidence > 0.8\n \n def test_silk_scarf_routing(self):\n \"\"\"Test routing silk scarf to CEE004 (Apparel, Footwear & Textiles)\"\"\"\n result = self.chinn.route_by_chapter(\n \"100% silk printed scarf, 36 inches square\",\n [\"62\"] # Chapter 62: Woven apparel\n )\n \n assert result.detected_chapter == \"62\"\n assert result.cee_domain == CEEDomain.APPAREL_FOOTWEAR_TEXTILES\n assert result.specialist.domain == CEEDomain.APPAREL_FOOTWEAR_TEXTILES\n assert result.routing_signals.fiber_content is True\n assert result.routing_signals.material_composition is True\n assert result.qp_required is True # High-risk textile chapter\n \n def test_smart_watch_disambiguation(self):\n \"\"\"Test smart watch ambiguous routing between electronics and watches\"\"\"\n result = self.chinn.route_by_chapter(\n \"smart watch with GPS, heart rate monitor, bluetooth connectivity, mobile apps\",\n [\"85\", \"91\"] # Ch. 85 (electrical) vs Ch. 91 (watches)\n )\n \n # Should route to Ch. 85 based on essential character (computing device)\n assert result.detected_chapter == \"85\"\n assert result.cee_domain == CEEDomain.ELECTRONICS\n assert result.confidence < 0.9 # Lower confidence for ambiguous cases\n assert result.escalation_required is True\n assert \"91\" in result.ambiguous_chapters\n assert \"essential character\" in result.reasoning.lower()\n \n def test_chapter_to_domain_mapping(self):\n \"\"\"Test chapter to CEE domain mapping\"\"\"\n test_cases = [\n (\"61\", CEEDomain.APPAREL_FOOTWEAR_TEXTILES),\n (\"73\", CEEDomain.BASE_METALS),\n (\"85\", CEEDomain.ELECTRONICS),\n (\"28\", CEEDomain.PHARMA_HEALTH_CHEMICALS),\n (\"87\", CEEDomain.AUTOMOTIVE_AEROSPACE),\n (\"94\", CEEDomain.CONSUMER_MASS_MERCH),\n ]\n \n for chapter, expected_domain in test_cases:\n actual_domain = self.chinn._chapter_to_domain(chapter)\n assert actual_domain == expected_domain, f\"Chapter {chapter} should map to {expected_domain}\"\n \n def test_qp_certification_jack(self):\n \"\"\"Test Jack's QP certification for textiles\"\"\"\n jack_cert = self.chinn.qp_certifications[\"jack_chang\"]\n \n assert jack_cert.qp_name == \"Jack Chang\"\n assert jack_cert.cee_domain == CEEDomain.APPAREL_FOOTWEAR_TEXTILES\n assert jack_cert.is_certified_for_chapter(\"61\")\n assert jack_cert.is_certified_for_chapter(\"62\")\n assert not jack_cert.is_certified_for_chapter(\"85\")\n assert jack_cert.is_valid()\n \n def test_textiles_specialist_config(self):\n \"\"\"Test textiles specialist configuration (Jack's domain)\"\"\"\n specialist = ChapterSpecialist.get_textiles_specialist()\n \n assert specialist.domain == CEEDomain.APPAREL_FOOTWEAR_TEXTILES\n assert \"61\" in specialist.chapter_range\n assert \"62\" in specialist.chapter_range\n assert \"fiber_content\" in specialist.classification_signals\n assert \"UFLPA\" in specialist.risk_flags\n assert \"yarn_forward_rule\" in specialist.fta_rules.values()\n \n def test_chapter_signals_auto_setup(self):\n \"\"\"Test ChapterSignals auto-configuration by chapter\"\"\"\n # Textiles chapter\n textile_signals = ChapterSignals(chapter=\"61\")\n assert textile_signals.fiber_content is True\n assert textile_signals.material_composition is True\n assert textile_signals.origin_marking_required is True\n \n # Metals chapter\n metal_signals = ChapterSignals(chapter=\"73\")\n assert metal_signals.alloy_grade is True\n assert metal_signals.physical_properties is True\n assert metal_signals.manufacturing_process is True\n \n # Electronics chapter\n electronics_signals = ChapterSignals(chapter=\"85\")\n assert electronics_signals.essential_character is True\n assert electronics_signals.voltage_rating is True\n assert electronics_signals.end_use is True\n \n def test_jack_intake_signals(self):\n \"\"\"Test Jack's 4 intake questions mapping\"\"\"\n # Textiles chapter (high risk)\n textile_signals = self.chinn.get_jack_intake_signals(\"61\")\n assert textile_signals[\"visual_sku_required\"] is True\n assert textile_signals[\"coo_tags_required\"] is True\n assert textile_signals[\"price_points_required\"] is True\n assert textile_signals[\"upstream_materials_required\"] is True\n \n # Non-textile chapter\n other_signals = self.chinn.get_jack_intake_signals(\"85\")\n assert other_signals[\"visual_sku_required\"] is True\n assert other_signals[\"coo_tags_required\"] is False # Electronics don't need COO tags by default\n assert other_signals[\"price_points_required\"] is True\n assert other_signals[\"upstream_materials_required\"] is False\n \n def test_fallback_routing(self):\n \"\"\"Test fallback routing for unimplemented domains\"\"\"\n result = self.chinn.route_by_chapter(\n \"unknown product type\",\n [\"99\"] # Non-existent chapter\n )\n \n assert result.confidence < 0.5\n assert result.escalation_required is True\n assert \"fallback\" in result.reasoning.lower()\n \n def test_ambiguous_routing_escalation(self):\n \"\"\"Test that ambiguous cases trigger escalation\"\"\"\n result = self.chinn.route_by_chapter(\n \"multi-material composite product\",\n [\"39\", \"73\", \"85\"] # Multiple possible chapters\n )\n \n assert result.escalation_required is True\n assert len(result.ambiguous_chapters) > 0\n assert result.confidence < 0.9\n\n\nclass TestChapterSpecialist:\n \n def test_textiles_specialist_creation(self):\n \"\"\"Test creating textiles specialist (Jack's domain)\"\"\"\n specialist = ChapterSpecialist.get_textiles_specialist()\n \n assert len(specialist.chapter_range) == 18 # Chapters 50-67\n assert specialist.domain == CEEDomain.APPAREL_FOOTWEAR_TEXTILES\n assert \"CPSC\" in specialist.pga_agencies\n assert \"USMCA\" in specialist.fta_rules\n \n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n```\n\n## 4. Worked Example: Jack's Textile Intake\n\n```python\n# Example: Jack's textile intake workflow through CHINN\n\"\"\"\nWorked Example: Jack's Textile Intake (Ch. 61-62) \nFull flow from product description through CHINN routing to specialist signals\n\"\"\"\n\ndef jack_textile_intake_example():\n \"\"\"Demonstrate Jack's textile classification workflow\"\"\"\n \n # Initialize CHINN\n chinn = CHINN()\n \n # Jack's intake: Women's silk blouse\n product_description = \"\"\"\n Women's woven silk blouse, long sleeves, button front closure.\n Material: 100% mulberry silk, charmeuse weave.\n Country of Origin: China\n Declared Value: $89.50\n Upstream: Silk fabric sourced from Jiangsu Province, China\n \"\"\"\n \n # Step 1: Visual/SKU analysis suggests Chapter 62 (women's woven apparel)\n candidate_chapters = [\"62\"]\n \n # Step 2: CHINN routes to textiles specialist\n routing_result = chinn.route_by_chapter(product_description, candidate_chapters)\n \n print(\"=== CHINN Routing Result ===\")\n print(f\"Chapter: {routing_result.detected_chapter}\")\n print(f\"CEE Domain: {routing_result.cee_domain.value}\")\n print(f\"Confidence: {routing_result.confidence}\")\n print(f\"QP Required: {routing_result.qp_required}\")\n \n # Step 3: Get Jack's intake signals\n intake_signals = chinn.get_jack_intake_signals(\"62\")\n \n print(\"\\n=== Jack's 4 Intake Questions ===\")\n print(f\"1. Visual/SKU Required: {intake_signals['visual_sku_required']}\")\n print(f\"2. COO Tags Required: {intake_signals['coo_tags_required']}\")\n print(f\"3. Price Points Required: {intake_signals['price_points_required']}\")\n print(f\"4. Upstream Materials Required: {intake_signals['upstream_materials_required']}\")\n \n # Step 4: Chapter-specific classification signals\n chapter_signals = routing_result.routing_signals\n \n print(\"\\n=== Chapter 62 Classification Signals ===\")\n print(f\"Material Composition: {chapter_signals.material_composition}\")\n print(f\"Fiber Content: {chapter_signals.fiber_content}\")\n print(f\"Weave Type: {chapter_signals.weave_type}\")\n print(f\"Origin Marking Required: {chapter_signals.origin_marking_required}\")\n \n # Step 5: Specialist configuration\n specialist = routing_result.specialist\n \n print(\"\\n=== Textiles Specialist Config ===\")\n print(f\"Domain: {specialist.domain.value}\")\n print(f\"Risk Flags: {', '.join(specialist.risk_flags)}\")\n print(f\"PGA Agencies: {', '.join(specialist.pga_agencies)}\")\n print(f\"FTA Rules: {specialist.fta_rules}\")\n \n # Step 6: QP certification check\n jack_cert = chinn.qp_certifications[\"jack_chang\"]\n can_classify = jack_cert.is_certified_for_chapter(\"62\")\n \n print(\"\\n=== QP Certification Status ===\")\n print(f\"Jack certified for Ch. 62: {can_classify}\")\n print(f\"Certification valid: {jack_cert.is_valid()}\")\n \n # Step 7: Expected classification outcome\n print(\"\\n=== Expected Classification ===\")\n print(\"HTS: 6206.10.0010 (Women's silk blouses and shirts)\")\n print(\"Duty Rate: Free (China MFN)\")\n print(\"Special Programs: Check UFLPA (silk from Xinjiang concern)\")\n print(\"Required Markings: Country of Origin, Fiber Content, Care Labels\")\n \n return routing_result\n\n\nif __name__ == \"__main__\":\n jack_textile_intake_example()\n```\n\n**Expected Output:**\n```\n=== CHINN Routing Result ===\nChapter: 62\nCEE Domain: CEE004\nConfidence: 0.9\nQP Required: True\n\n=== Jack's 4 Intake Questions ===\n1. Visual/SKU Required: True\n2. COO Tags Required: True\n3. Price Points Required: True\n4. Upstream Materials Required: True\n\n=== Chapter 62 Classification Signals ===\nMaterial Composition: True\nFiber Content: True\nWeave Type: True\nOrigin Marking Required: True\n\n=== Textiles Specialist Config ===\nDomain: CEE004\nRisk Flags: UFLPA, cotton_provenance, COO_marking, fiber_labeling\nPGA Agencies: CPSC, FTC, CBP\nFTA Rules: {'USMCA': 'yarn_forward_rule', 'CAFTA': 'cut_and_sewn_rule', 'TPL': 'fabric_forward_rule'}\n\n=== QP Certification Status ===\nJack certified for Ch. 62: True\nCertification valid: True\n\n=== Expected Classification ===\nHTS: 6206.10.0010 (Women's silk blouses and shirts)\nDuty Rate: Free (China MFN)\nSpecial Programs: Check UFLPA (silk from Xinjiang concern)\nRequired Markings: Country of Origin, Fiber Content, Care Labels\n```\n\nThis implementation provides CHINN as a Layer 2 Trade Operations INN that routes classification requests to chapter-specialized logic, mapping directly to CBP's 10 Centers of Excellence and Expertise. It captures Jack's domain expertise insight while providing a scalable framework for all HTS chapters."
}Audit Trail (1)
13h agotask_createdAG Lu
Task ID: 10a8f216-0b11-4668-94be-359e9d60e1c2