# Universal Vehicle Identification & Origin Decoding Engine (UVI-ODE)
## Complete Software Architecture & Technical Specification

> **Project Target**: `D:\xampp\htdocs\uvi`  
> **Source Specification**: [Gemini Architecture Document](https://share.gemini.google/xlaVFoEEyQmX)  
> **Classification**: Automotive Systems Architecture / VIN Origin Resolution  

---

## Table of Contents
1. [Executive Summary & Technical Strategy](#part-1-executive-summary--technical-strategy)
2. [Case Study: Toyota Multi-Layer Assembly Resolution](#part-2-case-study-toyota-multi-layer-assembly-resolution)
3. [System Specification (UVI-ODE)](#part-3-system-specification-uvi-ode)
   - [1. System Scope & Regulatory Standards Matrix](#1-system-scope--regulatory-standards-matrix)
   - [2. Architecture & Component Decomposition](#2-architecture--component-decomposition)
   - [3. Component 1: Ingestion, Normalization & Classification Pipeline](#3-component-1-ingestion-normalization--classification-pipeline)
   - [4. Components 2 & 3: Standard 17-Character ISO Engine & Validation](#4-components-2--3-standard-17-character-iso-engine--validation)
   - [5. Component 4: Domestic & Non-Standard Chassis Engine (JDM & Legacy)](#5-component-4-domestic--non-standard-chassis-engine-jdm--legacy)
   - [6. Component 5: Data Access & Local Persistence Layer](#6-component-5-data-access--local-persistence-layer)
   - [7. Component 6: External Enrichment Adapters (NHTSA / OEM)](#7-component-6-external-enrichment-adapters-nhtsa--oem)
   - [8. Component 7: Origin Resolution & Confidence Scoring Engine](#8-component-7-origin-resolution--confidence-scoring-engine)
   - [9. Component 8: API Layer & Error Catalog](#9-component-8-api-layer--error-catalog)
   - [10. Core Decoding Implementation Logic (Pseudocode Reference)](#10-core-decoding-implementation-logic-pseudocode-reference)
   - [11. Verification & Testing Matrix](#11-verification--testing-matrix)

---

# Part 1: Executive Summary & Technical Strategy

**Executive Summary**
This report outlines the architecture and implementation strategy for a VIN-based country of manufacture lookup tool. The core challenge in vehicle origin decoding is distinguishing the **World Manufacturer Identifier (WMI)**—which denotes the manufacturer's corporate or regional origin—from the **Actual Assembly Plant**, which may be located in a completely different country. The recommended solution is a Hybrid approach leveraging a local WMI SQLite database for fast, offline manufacturer-country mapping, coupled with the NHTSA vPIC API to definitively identify the actual assembly country when available.

## I. VIN System & Data Ecosystem

**1. The VIN System and Origin Identification**
The 17-character VIN standard, governed globally by ISO 3779 and ISO 3780, and regionally by standards like the NHTSA 49 CFR Part 565, is divided into three sections:   

* 

**World Manufacturer Identifier (WMI) (Positions 1–3):** The first character identifies the geographic region and country of the manufacturer (e.g., `1`, `4`, `5` for USA; `J` for Japan; `W` for Germany). The second character identifies the manufacturer, and the third specifies the vehicle type. For low-volume manufacturers (fewer than 500 vehicles/year), the third character is `9`, and positions 12–14 identify the specific manufacturer.   

* 

**Vehicle Descriptor Section (VDS) (Positions 4–9):** Details the vehicle model, engine, and body style. In North America, position 9 is a mandatory mathematically calculated Check Digit.

* 

**Vehicle Indicator Section (VIS) (Positions 10–17):** Position 10 indicates the model year. **Position 11 indicates the assembly plant**. Positions 12–17 act as a sequential serial number.   

*The Origin Discrepancy:* The WMI country represents where the manufacturer is headquartered or registered. It does **not** guarantee the physical assembly location. A vehicle with a Japanese WMI (`J`) might have its final assembly in the US, and its position 11 plant code will reflect the specific US factory. Furthermore, the character at position 11 is manufacturer-defined; there is no universal ISO map linking position 11 directly to a country without the manufacturer's specific plant code dictionary.

**2. Available Data Sources**

* 

**NHTSA vPIC API (Official):** A free, public API provided by the US Department of Transportation. The `/api/vehicles/DecodeVinValues/{VIN}` endpoint returns structured JSON including `PlantCountry`, `PlantCity`, and `Manufacturer`,. It is highly reliable for vehicles sold in North America but lacks complete plant data for grey-market or older European/Asian domestic vehicles. It requires no API key and allows commercial use.   

* 

**WMI Registries (ISO/SAE):** SAE International manages the global WMI registry. While authoritative, access to the full database is heavily commercialized and expensive. Public domain WMI-to-country mapping tables provide excellent, free static coverage for the first two characters.

* 

**Commercial APIs (DataOne, MarketCheck, Carfax):** Provide exhaustive global plant-level decoding, build sheets, and history. They are highly accurate but cost per decode, making them cost-prohibitive for a free, high-volume MVP.

## II. Architecture & Lookup Strategy

**3. Recommended Technical Approach: Option C (Hybrid System)**
Relying strictly on a local database (Option A) fails because position 11 plant codes are proprietary and cannot be reliably mapped to countries without massive, constantly updated manufacturer datasets. Relying solely on a commercial API (Option B) introduces unnecessary costs for simple WMI lookups.

* 

**The Hybrid Solution:** Build a local WMI-to-Country mapping database (using the first 2–3 characters) to instantly provide the *Manufacturer's Origin Country*. Then, asynchronously query the free NHTSA vPIC API to extract the `PlantCountry` field.

* 

**Conflict Resolution:** If the WMI indicates "Japan" but vPIC returns `PlantCountry: "United States"`, the application clearly separates the two facts in the UI, elevating the vPIC assembly plant as the actual origin with a "High" confidence score.

**4. VIN Lookup Logic (Algorithm)**

* 

**Sanitization:** Strip whitespace, hyphens, and convert to uppercase.

* 

**Format Validation:** Ensure the length is exactly 17 characters. Reject illegal characters (`I`, `O`, `Q`). For North American vehicles, validate the Check Digit at position 9.   

* 

**WMI Extraction & Local Lookup:** Extract characters 1-3. Query the local SQL database to identify the manufacturer name and WMI registered country.

* 

**Assembly Plant API Query:** Submit the full VIN to `[https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/](https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/){VIN}?format=json`.

* 

**Parsing & Confidence Scoring:**

Extract `PlantCountry`, `PlantCity`, and `ErrorCode`.

* 

*If `PlantCountry` is populated:* Return actual assembly country (Confidence: High).

* 

*If `PlantCountry` is null/empty but API returns 200 OK:* Return WMI Country only, with a disclaimer (Confidence: Moderate - Assembly unknown).

* 

*If API returns an ErrorCode > 0:* Return local WMI data only (Confidence: Low).

**5. Software Architecture**

* 

**Frontend (MVP):** React.js (Next.js) or plain HTML/Vanilla JS for maximum portability.

* 

**Backend API:** Node.js (Express) or Python (FastAPI). The backend acts as a proxy to call vPIC (to prevent frontend CORS issues and manage rate limiting) and queries the local WMI SQLite database.

* 

**Database:** SQLite. A single table `wmi_codes` (`wmi_pattern` VARCHAR, `region` VARCHAR, `country` VARCHAR, `manufacturer` VARCHAR).

* 

**Caching & Security:** Redis cache mapping full VINs to vPIC JSON responses for 30 days, minimizing external API calls. Implement IP-based rate limiting to prevent abuse.

## III. Implementation & Interface Design

**6. User Interface Design**
The UI must prevent false assumptions by visually separating the corporate HQ from the physical assembly line.

* 

**Input Area:** A prominent text field with real-time length/character validation and a "Decode Origin" button.

* 

**Result Panel Layout:**

**VIN Summary:** `1HGCM82633AXXXXXX` — Validated

* 

**Vehicle Identity:** Make: Honda | Year: 2003 (Sourced from vPIC)

* 

**Manufacturer Origin (WMI):** Japan (Code: `JHM` - Sourced from Local WMI DB)

* 

**Actual Assembly Location:** Marysville, Ohio, United States (Code: `A` at Pos 11 - Sourced from NHTSA vPIC)

* 

**Confidence Level:** High (Verified via official registry).

* 

**Edge Case Message:** If `PlantCountry` is null: *"Note: Official records do not specify the final assembly plant for this vehicle. The country shown reflects the manufacturer's corporate registration."*

**7. Implementation Roadmap**

* 

**Phase 1: Research & DB Construction (1 Week):** Aggregate a public domain WMI CSV covering major global codes.

* 

**Phase 2: Core Logic (1 Week):** Build the regex validation, check-digit algorithm, and local SQLite lookup.

* 

**Phase 3: API Integration (1 Week):** Connect the Node.js backend to NHTSA vPIC, handle JSON parsing, and implement the fallback logic for empty `PlantCountry` fields.

* 

**Phase 4: Frontend UI (1 Week):** Develop the React interface with distinct WMI vs. Assembly visual hierarchy.

* 

**Phase 5: QA & Edge Testing (1 Week):** Test low-volume manufacturers, grey-market imports, and pre-1981 non-standard VINs.

* 

**Phase 6: Deployment:** Containerize via Docker, deploy backend to AWS, frontend to Vercel.

* 

**Phase 7: Maintenance:** Monitor false country assignments and update the WMI SQLite dictionary biannually.

## IV. Testing, Compliance & Final Deliverables

**8. Testing and Accuracy**
Testing must isolate the disparity between WMI and Assembly:

* 

*Valid Match Test:* US-built Ford (`1FADP...`). WMI = USA, Assembly = USA.

* 

*Discrepancy Test:* Mexican-built Volkswagen (`3VW...`). WMI = Mexico, Assembly = Puebla, Mexico (Check against German HQ expectation).

* 

*Invalid Char Test:* Input containing `O` instead of `0`.

* 

*Low-Volume Test:* VIN with `9` in position 3 and manufacturer code in 12-14.   

* 

*Metric:* Track the percentage of lookups where vPIC returns a null `PlantCountry` to determine if a paid API integration is eventually necessary for the target market.

**9. Legal, Licensing, and Operational Considerations**

* 

**Data Licensing:** NHTSA vPIC is public domain and free for commercial use, but you cannot claim their data as your own intellectual property.

* 

**Privacy:** A VIN by itself is not strictly PII, but it becomes PII if linked to an individual's name or address. Since this application only decodes vehicle hardware and origin—and does not query DMV ownership records or store user IP-to-VIN logs—it carries very low regulatory risk.

* 

**Disclaimer:** The application must include Terms of Service stating that origin data is for informational purposes and relies on third-party government filings that may contain gaps.

**10. Final Deliverables Summary**
This report serves as the foundation for development, providing the WMI structural breakdown, evaluating the NHTSA vPIC API as the optimal data source, and outlining a scalable React/Node.js architecture. By executing the Hybrid logic strategy, the resulting software will deliver cost-effective, evidence-based origin decoding that honestly reflects gaps in public data.

---

# Part 2: Case Study: Toyota Multi-Layer Assembly Resolution

Yes, the hybrid architecture would work perfectly for Toyota. In fact, Toyota is one of the best case studies for why this dual-layer (WMI + Assembly API) approach is absolutely necessary.

Because Toyota manufactures vehicles globally, assuming a Toyota is made in Japan simply because of the brand name is a common error that this architecture prevents.   

Here is exactly how the proposed system handles Toyota vehicles:

### 1. WMI Processing (Positions 1–3)

The local database will instantly identify the region of manufacture based on Toyota's diverse World Manufacturer Identifier (WMI) codes. For example, the system will accurately map:   

* 

**`JT3`, `JTD`, `JTE`:** Japan   

* 

**`4T1`, `5TD`:** United States   

* 

**`2T3`:** Canada   

* 

**`3TM`:** Mexico

* 

**`SB1`:** United Kingdom

* 

**`MR0`:** Thailand

### 2. Assembly Plant Decoding (Position 11)

Toyota rigorously uses the 11th character of the VIN to identify the exact physical assembly plant. Because Toyota officially files these codes with the US government every year, the NHTSA vPIC API seamlessly decodes them.
When the system queries the API, it will translate Toyota's internal plant codes into actual geographic locations, such as:   

* 

**`0` through `9`, `J`:** Japanese plants (e.g., Takaoka, Tsutsumi, Tahara)   

* 

**`U`:** Georgetown, Kentucky, USA

* 

**`C`:** Cambridge, Ontario, Canada   

* 

**`S`:** Princeton, Indiana, USA

* 

**`X`:** San Antonio, Texas, USA

* 

**`M`:** Baja California, Mexico

If you input a Toyota built in Kentucky (`4T1...U...`), the system successfully verifies both layers: WMI = USA, Assembly = USA.

### 3. Graceful Fallback for Overseas Toyotas

If a user enters a VIN for a Toyota Hilux built in Thailand for the Australian market, the NHTSA vPIC API might not have the 11th-digit plant code on file (since it wasn't built for the US market).

* 

**The system's response:** The API query will return a null `PlantCountry`.

* 

**The fallback:** The system relies on its local database to read the `MR0` WMI code, reporting Thailand as the origin with a "Moderate" confidence score, noting that the specific assembly plant couldn't be verified.

### 4. The One Exception: JDM Vehicles

The only scenario where this system fails for a Toyota is with **Japanese Domestic Market (JDM)** vehicles built strictly for sale within Japan. Japan does not mandate the 17-character ISO VIN standard for domestic cars. Instead, they use a shorter Chassis/Frame Number (e.g., `ZN6-012345`).

Because step 2 of our logic strictly enforces a 17-character limit, the system will reject JDM frame numbers as "Invalid Format" before attempting to decode them. If your target audience imports JDM vehicles, you would need to add a bypass rule that recognizes standard Japanese chassis formats.

---

# Part 3: System Specification (UVI-ODE)

# System Specification: Universal Vehicle Identification & Origin Decoding Engine (UVI-ODE)

## 1. System Scope & Regulatory Standards Matrix

The Universal Vehicle Identification & Origin Decoding Engine (UVI-ODE) is an engine designed to deterministically resolve the manufacturer, geographic origin, and physical assembly plant of motor vehicles across all international jurisdictions.

The engine evaluates input strings against the regulatory frameworks outlined in the matrix below:

| Jurisdiction / Market | Governing Regulatory Standard | String Length & Type | Mandatory Check Digit | Plant Identification Mechanism |
| --- | --- | --- | --- | --- |
| Global / International | ISO 3779:2009, ISO 3780:2009 | 17 Characters (Alphanumeric, excl. `I`, `O`, `Q`) | No (Position 9 is manufacturer-discretionary or VDS) | Position 11 (VIS Position 2) — Manufacturer assigned |
| North America (USA/Canada) | 49 CFR Part 565 (NHTSA), CMVSS 115 (Transport Canada) | 17 Characters (Alphanumeric, excl. `I`, `O`, `Q`) | Yes (Position 9, Modulo 11 with weights [ 8 … 2 ] ) | Position 11 (VIS Position 2) — Registered plant code filed with agency |
| China | GB 16735-2004, GB 7258-2017 | 17 Characters (Alphanumeric, excl. `I`, `O`, `Q`) | Yes (Position 9, identical algorithm to North America) | Position 11 (VIS Position 2) — MIIT filed plant code |
| European Union | Regulation (EU) 2019/2144, ISO 3779 | 17 Characters (Alphanumeric, excl. `I`, `O`, `Q`) | No (Pos 9 frequently represents internal descriptor) | Position 11 (VIS Position 2) — Plant-specific |
| Australia / New Zealand | ADR 61/02, ISO 3779 | 17 Characters (Alphanumeric, excl. `I`, `O`, `Q`) | No (Permissive ISO rules) | Position 11 — Manufacturer defined |
| Japan Domestic Market (JDM) | MLIT Road Transport Vehicle Act (Chassis/Frame No.) | Variable (9–14 Characters, e.g., `FD3S-102345`, `CBA-R35-012345`) | No (Chassis format: Model Code + `-` + Serial) | Model prefix determines assembly series; Country = `JPN` (100% domestic assembly) |
| Pre-1981 Legacy (Global) | Non-standardized manufacturer serials | Variable (5–14 Characters, e.g., `136379K123456`) | No | Non-standard; requires manufacturer build-sheet lookup |

## 2. Architecture & Component Decomposition

The system is organized into decoupled, isolated components with strict interface boundaries:

`

```
[ Client / Calling Layer ]
           │
           ▼
[ Component 1: Ingestion, Normalization & Classification Pipeline ]
           │
    ┌──────┴───────────────────────────────────────┐
    ▼                                              ▼
[ Standard 17-Char Identifier ]             [ Non-Standard / Domestic Chassis ]
    │                                              │
    ├─► [ Component 3: Validation Engine ]         └─► [ Component 4: Domestic Engine ]
    │   (Check Digit: NA / China / Relaxed ISO)        (JDM / Legacy Frame Lookup)
    │                                                          │
    ▼                                                          │
[ Component 2: 17-Char ISO Decoding Engine ]                   │
    │   (WMI Lookup, ISO Year Cycle, VIS Extraction)           │
    │                                                          │
    └──────────────────────┬───────────────────────────────────┘
                           │
                           ▼
[ Component 5: Data Access & Local Persistence Layer ]
                           │
                           ▼
[ Component 6: External Enrichment Adapters (NHTSA / OEM APIs) ]
                           │
                           ▼
[ Component 7: Origin Resolution & Confidence Scoring Engine ]
                           │
                           ▼
[ Component 8: API Presentation & Contract Delivery ]
```

3. Component 1: Ingestion, Normalization & Classification Pipeline3.1 Input Specifications & PreprocessingEvery input string must pass through the following deterministic transformation pipeline before reaching any decoding engine:Encoding Sanitization: Convert string to UTF-8. Strip zero-width spaces (\u200B`), non-breaking spaces (`\u00A0`), control characters, and leading/trailing whitespace.
* 

**Casing Normalization:** Transform all characters to ASCII uppercase (`a-z` → `A-Z`).

* 

**Delimiter Handling:**

If length >17 and contains hyphens or spaces, strip hyphens (`-`) and spaces (` `).

* 

If length ≤14 and contains exactly one hyphen, retain the hyphen for JDM Chassis processing.

### 3.2 Classification Rules (Regex Routing)

`

```
Pipeline Classifier:
  IF Input MATCHES Regex_ISO_Standard:
      Route to Component 3 (Validation) -> Component 2 (ISO Engine)
  ELSE IF Input MATCHES Regex_JDM_Chassis:
      Route to Component 4 (Domestic Engine)
  ELSE IF Input MATCHES Regex_Pre1981_Legacy:
      Route to Component 4 (Domestic Engine: Legacy Mode)
  ELSE:
      Throw MALFORMED_IDENTIFIER_ERROR (Code: 4001)
```

Regex_ISO_Standard`:
`^[A-HJ-NPR-Z0-9]{17}$`
*(Strict exclusion of `I`, `O`, `Q` to prevent optical confusion with `1` and `0`)*
* 

**`Regex_JDM_Chassis`**:
`^[A-Z0-9]{2,7}-[0-9]{5,8}$`
*(Captures all certified Japanese Domestic chassis marks: e.g., `E-BCNR33-001234`, `ZN6-012345`)*

* 

**`Regex_Pre1981_Legacy`**:
`^[A-Z0-9]{5,15}$`
*(Alphanumeric strings that fail ISO length and lack the JDM hyphen)*

## 4. Component 2 & 3: Standard 17-Character ISO Engine & Validation

### 4.1 Check Digit Mathematical Verification (Position 9)

Mandatory for North American (WMI starting with `1`, `2`, `3`, `4`, `5`) and Chinese (WMI starting with `L`) vehicles. Permissive for ISO/EU vehicles.

#### Transliteration Value Map (V)

Letters are mapped to numerical values:

A=1J=1S=2​B=2K=2T=3​C=3L=3U=4​D=4M=4V=5​E=5N=5W=6​F=6P=7X=7​G=7R=9Y=8​H=8Z=9​

Digits 0 through 9 retain their literal values (0…9).

#### Weight Array (W)

Positional weights for indices i=1 to 17:

W=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2]

#### Algorithm

* 

Compute the weighted sum:

S=i=1∑17​(V(VIN[i])×W[i])
* 

Compute the remainder:

R=S(mod11)
* 

Resolve the expected character:

Expected={"X",str(R),​if R=10if R<10​
* 

Compare Expected with VIN[9]:

**If match:** Flag `check_digit_valid = TRUE`.

* 

**If mismatch AND WMI indicates NA/China:** Flag `check_digit_valid = FALSE`, error status `INVALID_CHECKSUM`.

* 

**If mismatch AND WMI indicates Europe/Rest-of-World:** Flag `check_digit_valid = NULL`, classification `ISO_NON_CHECK_DIGIT_COMPLIANT`. Do not abort execution.

### 4.2 ISO 3780 Geographic Character Table (Positions 1 and 2)

The geographic region and country are resolved by comparing positions 1 and 2 against the following international allocation:

`

```
[A-H] AFRICA
  AA-AH: South Africa      CA-CE: Benin            EA-EE: Ethiopia
  AJ-AN: Ivory Coast       CF-CK: Madagascar       EF-EK: Mozambique
  BA-BE: Angola            CL-CR: Tunisia          FA-FE: Ghana
  BF-BK: Kenya             DA-DE: Egypt            FF-FK: Nigeria
  BL-BR: Tanzania          DF-DK: Morocco          FL-FR: Madagascar
                           DL-DR: Zambia

[J-R] ASIA
  JA-JT: Japan             MA-ME: India            PA-PE: Philippines
  KL-KR: South Korea       MF-MK: Indonesia        PF-PK: Singapore
  L0-L9, LA-LZ: China      ML-MR: Thailand         PL-PR: Malaysia
                           MS-M0: Myanmar          RA-RE: UAE
                           NA-NE: Iran             RF-RK: Taiwan
                           NF-NK: Pakistan         RL-RR: Vietnam
                           NL-NR: Turkey           RS-R0: Saudi Arabia

[S-Z] EUROPE
  SA-SM: United Kingdom    TJ-TP: Czech Republic   VA-VE: Austria
  SN-ST: Germany (East)    TR-TV: Hungary          VF-VR: France
  SU-SZ: Poland            TW-T1: Portugal         VS-VW: Spain
  S1-S4: Latvia            UH-UM: Denmark          VX-V2: Serbia / Croatia
  TA-TH: Switzerland       UN-UT: Ireland          WA-W0: Germany
                           UU-UZ: Romania          XA-XE: Bulgaria
                           U5-U7: Slovakia         XF-XK: Greece
                           XL-XR: Netherlands      YS-YW: Sweden
                           XS-XW: Russia / USSR    ZA-ZR: Italy
                           YA-YE: Belgium          ZX-Z2: Slovenia
                           YF-YK: Finland          Z3-Z5: Lithuania

[1-5] NORTH AMERICA
  1A-10: United States     3A-3W: Mexico
  2A-20: Canada            3X-37: Costa Rica
  4A-40: United States     38-30: Cayman Islands
  5A-50: United States

[6-7] OCEANIA
  6A-6W: Australia         7A-7E: New Zealand

[8-9] SOUTH AMERICA
  8A-8E: Argentina         8X-82: Venezuela        9F-9K: Colombia
  8F-8K: Chile             9A-9E: Brazil           9L-9R: Paraguay
  8L-8R: Ecuador           9S-9W: Uruguay          93-99: Brazil
  8S-8W: Peru
```

4.3 Low-Volume Manufacturer Rule (Position 3 = 9`)

* 

If character 3 is `'9'`, the vehicle is produced by a low-volume manufacturer (<500 units/year).

* 

In this condition, the true manufacturer identifier is determined by combining positions 1–3 with positions 12, 13, and 14 (`WMI_EXTENDED = VIN[1..3] + VIN[12..14]`).

* 

The system must query the WMI database using the 6-character composite identifier to identify the manufacturer.

### 4.4 Model Year Cycle Resolution (Position 10)

ISO 3779 specifies a 30-year character cycle for position 10 (excluding `I`, `O`, `Q`, `U`, `Z`).

| Code | Cycle 1 | Cycle 2 | Code | Cycle 1 | Cycle 2 | Code | Cycle 1 | Cycle 2 | Code | Cycle 1 | Cycle 2 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| A | 1980 | 2010 | L | 1990 | 2020 | Y | 2000 | 2030 | 7 | 2007 | 2037 |
| B | 1981 | 2011 | M | 1991 | 2021 | 1 | 2001 | 2031 | 8 | 2008 | 2038 |
| C | 1982 | 2012 | N | 1992 | 2022 | 2 | 2002 | 2032 | 9 | 2009 | 2039 |
| D | 1983 | 2013 | P | 1993 | 2023 | 3 | 2003 | 2033 |  |  |  |
| E | 1984 | 2014 | R | 1994 | 2024 | 4 | 2004 | 2034 |  |  |  |
| F | 1985 | 2015 | S | 1995 | 2025 | 5 | 2005 | 2035 |  |  |  |
| G | 1986 | 2016 | T | 1996 | 2026 | 6 | 2006 | 2036 |  |  |  |
| H | 1987 | 2017 | V | 1997 | 2027 |  |  |  |  |  |  |
| J | 1988 | 2018 | W | 1998 | 2028 |  |  |  |  |  |  |
| K | 1989 | 2019 | X | 1999 | 2029 |  |  |  |  |  |  |

*Disambiguation Rule:* Position 7 distinguishes the cycle. In passenger cars complying with North American regulations, if position 7 is a letter, the year falls in Cycle 2 (2010–2039). If position 7 is numeric, the year falls in Cycle 1 (1980–2009). For non-NA vehicles, external enrichment is required to lock the epoch.

## 5. Component 4: Domestic & Non-Standard Chassis Engine (JDM & Legacy)

### 5.1 Japanese Domestic Market (JDM) Processing Engine

When input satisfies `Regex_JDM_Chassis`, standard 17-character validation is bypassed:

* 

**Extraction:**

Split string by `-`.

* 

Left token = `Model_Prefix` (e.g., `E-BCNR33`, `FD3S`, `ZN6`).

* 

Right token = `Production_Serial` (e.g., `001234`).

* 

**Deterministic Geography:**

Country of Assembly: **Japan** (`JPN`).

* 

Geographic Region: **Asia** (`ASI`).

* 

Source: **MLIT Type Designation Certificate Register**.

* 

Confidence Level: **High (Deterministic)**.

* 

**Manufacturer Mapping Table (Model Prefix Index):**

| Prefix Token Regex | Manufacturer Identity | Common Models | Domestic Plant Origin |
| --- | --- | --- | --- |
| `^(DBA-)?ZN6.*` | Toyota / Subaru JV | 86 / BRZ | Gunma Main Plant, Ota, Japan |
| `^(E- | GF-)?FD3S.*` | Mazda Motor Corporation | RX-7 |
| `^(E- | GF-)?BCNR33.*` | Nissan Motor Co., Ltd. | Skyline GT-R |
| `^(ABA-)?AP[12].*` | Honda Motor Co., Ltd. | S2000 | Takanezawa / Suzuka, Japan |
| `^(CBA-)?R35.*` | Nissan Motor Co., Ltd. | GT-R | Tochigi Plant, Japan |
| `^(GH-)?CT9A.*` | Mitsubishi Motors | Lancer Evolution | Mizushima Plant, Japan |

## 6. Component 5: Data Access & Local Persistence Layer

The database schema (PostgreSQL 14+ / SQLite 3.38+) stores the core WMI tables, plant overrides, and external cache entries:

`SQL

```
-- Table: Geographic Regions (ISO 3166-1 alpha-3 compliant)
CREATE TABLE geo_countries (
    iso_alpha2 CHAR(2) PRIMARY KEY,
    iso_alpha3 CHAR(3) NOT NULL UNIQUE,
    country_name VARCHAR(100) NOT NULL,
    continent_code CHAR(2) NOT NULL
);

-- Table: WMI Registry
CREATE TABLE wmi_registry (
    wmi_code VARCHAR(3) NOT NULL,
    is_low_volume BOOLEAN DEFAULT FALSE,
    wmi_extended VARCHAR(3) NULL, -- For Pos 12-14 when is_low_volume = TRUE
    manufacturer_name VARCHAR(150) NOT NULL,
    country_code CHAR(2) NOT NULL REFERENCES geo_countries(iso_alpha2),
    vehicle_type VARCHAR(50) NOT NULL,
    PRIMARY KEY (wmi_code, COALESCE(wmi_extended, '000'))
);
CREATE INDEX idx_wmi_code ON wmi_registry(wmi_code);

-- Table: Known Assembly Plants (Internal Dictionary)
CREATE TABLE assembly_plants (
    id SERIAL PRIMARY KEY,
    wmi_code VARCHAR(3) NOT NULL,
    plant_code CHAR(1) NOT NULL,
    plant_name VARCHAR(150) NOT NULL,
    city VARCHAR(100) NOT NULL,
    state_province VARCHAR(100) NULL,
    country_code CHAR(2) NOT NULL REFERENCES geo_countries(iso_alpha2),
    active_from_year INT NULL,
    active_to_year INT NULL,
    UNIQUE (wmi_code, plant_code)
);
CREATE INDEX idx_assembly_plant_lookup ON assembly_plants(wmi_code, plant_code);

-- Table: VIN Cache & Query Audit
CREATE TABLE vin_cache (
    vin_normalized VARCHAR(17) PRIMARY KEY,
    input_format VARCHAR(20) NOT NULL, -- 'ISO_17', 'JDM_FRAME', 'LEGACY'
    wmi_country_code CHAR(2) NOT NULL,
    actual_plant_country_code CHAR(2) NULL,
    plant_city VARCHAR(100) NULL,
    confidence_level VARCHAR(20) NOT NULL, -- 'HIGH_DETERMINISTIC', 'HIGH_ENRICHED', 'MODERATE_WMI_ONLY', 'UNKNOWN'
    raw_api_payload JSONB NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL
);
CREATE INDEX idx_vin_cache_expiry ON vin_cache(expires_at);
```

7. Component 6: External Enrichment AdaptersWhen an ISO 17-character VIN is decoded locally, the Assembly Plant code (Position 11) is ambiguous unless matched against known manufacturer records. The external enrichment adapter resolves Position 11 dynamically.7.1 Primary Open Adapter: NHTSA vPIC EndpointBase URL: [https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/](https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/){VIN}?format=json`
* 

**Transport:** HTTPS GET, Timeout: 2500ms, Retries: 1 with exponential backoff.

* 

**Authentication:** None (Public Domain, US Federal Agency).

* 

**Extraction Field Path:**

Actual Assembly Country: `Results[0].PlantCountry`

* 

Actual Assembly City: `Results[0].PlantCity`

* 

Manufacturer Name: `Results[0].Make` / `Results[0].Manufacturer`

* 

Error Check: `Results[0].ErrorCode` (Must be `"0"` or evaluate to non-fatal)

### 7.2 Secondary Commercial Adapter Specification (Fallback Interface)

To support commercial enterprise upgrades (e.g., DataOne, Carfax, or AutoCheck) without altering domain logic, external adapters implement the following interface contract:

`TypeScript

```
interface ExternalEnrichmentProvider {
  decodeAssembly(vin: string): Promise;
}

interface EnrichmentResult {
  isSuccessful: boolean;
  actualPlantCountryIso2: string | null;
  actualPlantCity: string | null;
  manufacturerName: string | null;
  rawPayload: Recordstring, unknown>;
  errorCode: string | null;
}
```

8. Component 7: Origin Resolution & Confidence Scoring EngineThe origin resolution engine executes the following arbitration matrix to resolve the difference between the corporate WMI Country and the actual Physical Assembly Plant:

```
┌────────────────────────────────────────┐
                  │ Evaluate Input & Local WMI Lookup Data │
                  └───────────────────┬────────────────────┘
                                      │
              ┌───────────────────────┴───────────────────────┐
              ▼                                               ▼
      [ JDM Chassis Match ]                       [ Standard 17-Char VIN ]
              │                                               │
   Country: JPN (Japan)                                       ▼
   Plant: Determined from Prefix               Query Local Assembly Plant DB
   Confidence: HIGH_DETERMINISTIC                             │
                                              ┌───────────────┴───────────────┐
                                              ▼                               ▼
                                       [ Match Found ]                 [ Cache Miss ]
                                              │                               │
                                     Set Plant Country                        ▼
                                     Confidence: HIGH              Query External API (vPIC)
                                                                              │
                                                              ┌───────────────┴───────────────┐
                                                              ▼                               ▼
                                                     [ PlantCountry Found ]         [ PlantCountry Null ]
                                                              │                               │
                                                     Set Plant Country               Plant Country: UNKNOWN
                                                     Confidence: HIGH                WMI Country: Valid
                                                                                     Confidence: MODERATE
```

8.1 Confidence Scoring RulesHIGH_DETERMINISTIC`:

* 

Evaluated for JDM frame codes successfully verified against the chassis index.

* 

Or 17-character VIN where the assembly plant code at Position 11 is definitively resolved via local validated plant database or government filing.

* 

**`HIGH_ENRICHED`**:

Resolved via external API adapter with matching validation status.

* 

**`MODERATE_WMI_ONLY`**:

WMI is valid and maps to a recognized country, but the specific plant at Position 11 cannot be resolved from either local databases or external adapters.

* 

**System Output Rule:** The system outputs the WMI manufacturer country and explicitly flags the assembly plant as `"UNVERIFIED_ASSEMBLY_LOCATION"`.

* 

**`LOW_INSUFFICIENT_DATA`**:

Pre-1981 non-standard VIN, or WMI country is resolved but check digit fails on North American/Chinese registrations.

* 

**`INVALID`**:

Unparseable characters, invalid lengths, illegal characters (`I`, `O`, `Q`).

## 9. Component 8: API Layer & Error Catalog

### 9.1 RESTful Endpoint Specification

* 

**Route:** `POST /api/v1/vin/decode`

* 

**Content-Type:** `application/json`

#### Request Payload

`JSON

```
{
  "identifier": "4T1B11HK5EU123456",
  "options": {
    "allow_relaxed_iso": true,
    "force_refresh_cache": false
  }
}
```

Response Payload (Assembly Mismatch Example)JSON

```
{
  "status": "SUCCESS",
  "data": {
    "input_identifier": "4T1B11HK5EU123456",
    "format_classification": "ISO_17_STANDARD",
    "validation": {
      "is_valid": true,
      "check_digit_calculated": "5",
      "check_digit_actual": "5",
      "check_digit_status": "MATCH"
    },
    "origin": {
      "wmi_registered_country": {
        "iso_alpha2": "US",
        "iso_alpha3": "USA",
        "name": "United States",
        "region": "North America"
      },
      "actual_assembly_plant": {
        "is_verified": true,
        "country": {
          "iso_alpha2": "US",
          "iso_alpha3": "USA",
          "name": "United States"
        },
        "city": "Georgetown",
        "state_province": "Kentucky",
        "plant_identifier_character": "U"
      },
      "origin_discrepancy_detected": false
    },
    "vehicle_attributes": {
      "wmi": "4T1",
      "manufacturer": "Toyota Motor Manufacturing, Kentucky, Inc.",
      "model_year": 2014,
      "is_low_volume_manufacturer": false
    },
    "meta": {
      "confidence_level": "HIGH_ENRICHED",
      "evidence_sources": [
        "LOCAL_WMI_DATABASE_V1",
        "NHTSA_VPIC_API"
      ],
      "resolved_at": "2026-10-09T14:52:00Z"
    }
  }
}
```

Response Payload (JDM Example)JSON

```
{
  "status": "SUCCESS",
  "data": {
    "input_identifier": "ZN6-012345",
    "format_classification": "JDM_CHASSIS_NUMBER",
    "validation": {
      "is_valid": true,
      "check_digit_status": "NOT_APPLICABLE"
    },
    "origin": {
      "wmi_registered_country": {
        "iso_alpha2": "JP",
        "iso_alpha3": "JPN",
        "name": "Japan",
        "region": "Asia"
      },
      "actual_assembly_plant": {
        "is_verified": true,
        "country": {
          "iso_alpha2": "JP",
          "iso_alpha3": "JPN",
          "name": "Japan"
        },
        "city": "Ota",
        "state_province": "Gunma",
        "plant_identifier_character": null
      },
      "origin_discrepancy_detected": false
    },
    "vehicle_attributes": {
      "manufacturer": "Subaru / Toyota JV",
      "model_designation": "Toyota 86 / Scion FR-S",
      "model_year": null
    },
    "meta": {
      "confidence_level": "HIGH_DETERMINISTIC",
      "evidence_sources": [
        "MLIT_JDM_CHASSIS_REGISTRY"
      ],
      "resolved_at": "2026-10-09T14:52:00Z"
    }
  }
}
```

9.2 Error Code RegistryError CodeHTTP StatusError Type IdentifierTriggering Condition4001`400`MALFORMED_IDENTIFIER`Input string contains invalid characters (e.g., `I`, `O`, `Q` in ISO mode) or invalid length (<5 or >17).**`4002`**422`CHECKSUM_FAILED`Position 9 check digit recalculation failed on a mandatory market (US/Canada/China).**`4004`**404`UNKNOWN_WMI`Characters 1–3 do not match any allocated ISO 3780 manufacturer country block.**`5002`**502`UPSTREAM_ADAPTER_ERROR`External enrichment service returned 5xx status or connection timed out after retries.

## 10. Core Decoding Implementation Logic (Pseudocode Reference)

This pseudocode specifies the business logic for the engine's coordinator service:

Python

```
class UniversalVinDecoder:
    def decode(self, raw_input: str, allow_relaxed_iso: bool = True) -> DecodeResult:
        # Step 1: Normalize
        clean_str = self.normalize(raw_input)
        
        # Step 2: Route by Classification
        if Regex_ISO_Standard.match(clean_str):
            return self.process_iso_17(clean_str, allow_relaxed_iso)
        elif Regex_JDM_Chassis.match(clean_str):
            return self.process_jdm(clean_str)
        elif Regex_Pre1981_Legacy.match(clean_str):
            return self.process_legacy(clean_str)
        else:
            raise ValidationError(code=4001, message="Malformed identifier")

    def process_iso_17(self, vin: str, allow_relaxed: bool) -> DecodeResult:
        # Check digit verification
        is_na_or_china = vin[0] in ['1', '2', '3', '4', '5', 'L']
        check_digit_valid = self.verify_check_digit(vin)
        
        if is_na_or_china and not check_digit_valid:
            raise ChecksumError(code=4002, message="Invalid North American or Chinese check digit")
        
        # WMI Lookup
        wmi_code = vin[0:3]
        if vin[2] == '9': # Low volume manufacturer
            wmi_extended = vin[11:14]
            wmi_record = Database.lookup_wmi(wmi_code, wmi_extended)
        else:
            wmi_record = Database.lookup_wmi(wmi_code, None)
            
        if not wmi_record:
            # Fallback: extract generic country from ISO 3780 position 1-2 block
            wmi_record = Iso3780Table.lookup_country(vin[0:2])
            
        # Position 11 Assembly Plant Extraction
        plant_char = vin[10]
        plant_record = Database.lookup_plant(wmi_code, plant_char)
        
        if plant_record:
            return BuildResult(wmi=wmi_record, plant=plant_record, confidence="HIGH_DETERMINISTIC")
            
        # External Enrichment Fallback
        enrichment = ExternalEnricher.fetch_nhtsa(vin)
        if enrichment.has_assembly_plant:
            return BuildResult(wmi=wmi_record, plant=enrichment.plant, confidence="HIGH_ENRICHED")
            
        # Moderate fallback: WMI known, assembly plant unverified
        return BuildResult(
            wmi=wmi_record, 
            plant=None, 
            plant_status="UNVERIFIED_ASSEMBLY_LOCATION", 
            confidence="MODERATE_WMI_ONLY"
        )
```

## 11. Verification & Testing Matrix

The implementation will be verified against the following test suite:

```
[TEST-01: US Assembly, Matching WMI]
Input: 1FA6P8CF5H5XXXXXX (Ford Mustang)
Expected: WMI Country = USA, Assembly Plant = Flat Rock, USA. Check Digit = Valid.

[TEST-02: Transnational Assembly Discrepancy]
Input: 3VWDP7AJ9HMXXXXXX (Volkswagen Jetta)
Expected: WMI Country = Mexico (3VW), Assembly Plant = Puebla, Mexico. Check Digit = Valid.
Discrepancy: False (VW German brand, but WMI correctly shows Mexican subsidiary).

[TEST-03: Domestic Brand Assembled Abroad]
Input: 2T3C1RFV9MCXXXXXX (Toyota RAV4)
Expected: WMI Country = Canada (2T3), Assembly Plant = Cambridge, Ontario, Canada.
Verification: Confirms Japanese brand assembled in Canada.

[TEST-04: European Relaxed Check Digit Mode]
Input: WBA3A5C50DFXXXXXX (BMW 3 Series - German Domestic Market)
Expected: Check digit validation skipped/relaxed. WMI Country = Germany.

[TEST-05: JDM Chassis Input]
Input: FD3S-102345 (Mazda RX-7)
Expected: Classification = JDM_CHASSIS_NUMBER, Assembly Country = Japan, City = Hiroshima.

[TEST-06: Low-Volume Manufacturer Identification]
Input: WP0ZZZ99ZTSXXXXXX (Pos 3 = '9')
Expected: Triggers 6-character composite lookup (WP0 + digits 12-14).
```
