# Smart Trade AI — Business Overview

> Last updated: 2026-05-12
> This document is intended for developers and describes the system's business logic, module responsibilities, and data flow.
> For product feature descriptions, see "Project Requirements Document.md".

---

## 1. System Positioning

**In one sentence**: An AI sales assistant for foreign trade companies. Covers the full chain from "lead generation to conversion."

```
Lead Generation (Find Customers)     Conversion (Win Orders)
────────────────────────────         ─────────────────────────────
• B2B Platform Diagnosis/Optimization  • Customer Analysis & Outreach
• Social Media Content Strategy        • AI Senior Salesperson
• LinkedIn Marketing                   • Quoting & Negotiation
• Customs Data Mining
```

**Runtime dependencies**:
- `hermes-agent` (AIAgent engine, tool system, cron)
- LLM API Key (user-provided, configured in `~/.hermes/.env`)

---

## 2. Four Core Business Scenarios

### Scenario 1: Document Q&A (Document Libraries)

Users upload company documents (PDF/Excel/Word/images), and the Agent automatically understands and answers questions about the document content.

```
User: "What is this supplier's MOQ?"
  → Agent reads the document
  → Finds: "MOQ: 500pcs/style"
  → Returns answer + source citation
```

**Supporting modules**:
- `library.py` — manages document libraries (linked to local directory paths)
- `b2b-document` skill — parsing logic for 16 file formats

### Scenario 2: Customer Development (Lead Generation + Conversion)

A user describes a potential customer, and the Agent analyzes and generates a customized outreach email.

```
User: "Help me analyze this customer: https://linkedin.com/in/xxx"
  → Agent extracts company/contact info
  → Determines customer type (price-sensitive/quality-oriented/relationship-based)
  → Generates customized outreach email + follow-up sequence
```

**Supporting modules**:
- `customer.py` — customer CRUD + associated document libraries
- `b2b-lead-generation` skill — Account IQ analysis, cold emails, GAP Selling
- `b2b-linkedin-marketing` skill — LinkedIn content strategy

### Scenario 3: Marketing Content Generation

The Agent, combined with the company's product materials, generates social media content ready for publication.

```
User: "Generate this week's Facebook posting plan"
  → Agent reads company product materials
  → Generates 5 posts (copy + image suggestions + hashtags)
  → User copies and publishes
```

**Supporting modules**: `b2b-social-media` skill (FB/Ins/TikTok/YouTube)

### Scenario 4: Daily Automation

Scheduled tasks execute automatically without human intervention.

```
Every day 09:30  → Agent generates today's LinkedIn Post draft
Every day 17:30  → Agent summarizes today's work → appends to daily report
Every Friday     → Agent generates weekly summary
```

**Supporting modules**: `b2b-daily-automation` skill (7 cron tasks)

---

## 3. Module Architecture

```
server.py (FastAPI entry point, 146 lines)
  │
  ├── init_db()                    # Table creation / v0 migration on startup
  ├── trade_router (mounted at /api/trade/*)
  │     │
  │     └── api.py (846 lines, over limit, needs splitting)
  │           │
  │           ├── companies/          # Company CRUD
  │           │     └── company.py   # Company + trade_companies CRUD
  │           │
  │           ├── libraries/         # Document library CRUD
  │           │     └── library.py   # Document library + customer associations
  │           │
  │           ├── customers/         # Customer CRUD
  │           │     └── customer.py  # Customer + associated document libraries
  │           │
  │           ├── conversations/     # Conversation history
  │           │     └── chat_memory.py  # Conversation saving + Hindsight memory
  │           │
  │           ├── onboarding/        # First-run wizard
  │           │     └── onboarding.py # Wizard state + first company creation
  │           │
  │           ├── chat/              # AI Agent conversation
  │           │     ├── helpers.py   # check_provider / build_query
  │           │     └── prompt.py    # TRADE_SYSTEM_PROMPT
  │           │
  │           └── memory/             # Long-term memory
  │                 └── memory.py    # Hindsight bridge
  │
  └── static/trade_chat.html (SPA frontend, multi-company UI)
```

### Module Responsibility Table

| Module | File | Responsibility | Lines |
|--------|------|---------------|-------|
| Entry | `server.py` | FastAPI startup, version check, DB init | 146 ✅ |
| Router | `api.py` | HTTP endpoints (companies/libraries/customers/chat/onboarding) | **846 ❌** |
| Company | `company.py` | Company CRUD + trade_companies config + data directory creation | ~333 |
| Document Library | `library.py` | Document library CRUD + customer associations | ~200 |
| Customer | `customer.py` | Customer CRUD + associated document libraries | ~260 |
| Conversation | `chat_memory.py` | Conversation history + Hindsight memory | ~200 |
| Onboarding | `onboarding.py` | First-run wizard status detection + atomic company creation | 190 |
| Helpers | `helpers.py` | Provider check + Prompt construction + Agent parameters | 136 ✅ |
| Prompts | `prompt.py` | System prompt (foreign trade sales behavior guidelines) | — |
| Memory | `memory.py` | Hindsight client bridge (optional, degrades gracefully without API) | 220 ✅ |
| Install | `post_install.py` | Skills copy + .trade-template initialization | ~180 |
| Frontend | `static/trade_chat.html` | Multi-company sidebar + chat interface + SSE streaming display | — |

**Split trigger**: `api.py` (846 lines) exceeds the 500-line limit and needs to be split into multiple Router submodules by business domain.

---

## 4. Data Model

```
companies ── 1:N ──► trade_companies  (1:1, is_active and other config)
    │
    └── 1:N ──► libraries      ── N:M ──► customers
                   │                    │
                   └── 1:N ──► conversations
```

**6 data tables**:

| Table | Primary Key | Core Fields | Purpose |
|-------|-------------|-------------|---------|
| `companies` | id | name, slug, contact, is_active | Basic company info |
| `trade_companies` | company_id | data_dir, agent_identity_md, is_active | Trade-specific configuration |
| `libraries` | id | name, root_path, description, company_id | Document library directories |
| `customers` | id | name, contact, note, company_id | Customer records |
| `customer_libraries` | (library_id, customer_id) | — | Many-to-many association table |
| `conversations` | id | query, response, files_read, company_id | Conversation history |

Each table has 3 spare JSON fields (`extra1/2/3`) to avoid future ALTER TABLE operations.

---

## 5. First-Run Flow (Onboarding)

```
User opens http://127.0.0.1:9119/trade for the first time
        │
        ▼
┌─────────────────────────────────┐
│  Frontend GET /api/trade/companies  │
│  → Returns [] (empty)           │
│  → Shows "Please create a company first" guide page │
└─────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────┐
│  POST /api/trade/onboarding/first-company   │
│  Body: {                                    │
│    company_name: "Shenzhen Spark Electronics Co., Ltd.", │
│    contact_name: "Manager Li",              │
│    contact_email: "li@xinghuo.com",         │
│    identity_data: {                         │
│      products: "Smart home products",       │
│      differentiation: "Original factory",   │
│      target_region: "Europe, North America" │
│    }                                        │
│  }                                          │
└─────────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────┐
│  onboarding.create_first_company()           │
│                                              │
│  Step 1: company.create()                   │
│    → Write to companies table               │
│    → Write to trade_companies table         │
│    → Create ~/.trade/{slug}/ directory skeleton │
│                                              │
│  Step 2: Write agent_identity_md            │
│    → DB: trade_companies.agent_identity_md  │
│    → File: ~/.trade/{slug}/                 │
│             agent-identity.md               │
└─────────────────────────────────────────────┘
        │
        ▼
  Frontend navigates to chat interface, ready to use
```

---

## 6. Conversation Flow (Chat)

```
User asks: "Help me analyze this German customer and write an outreach email"
        │
        ▼
┌─────────────────────────────────────────────┐
│  POST /api/trade/chat                       │
│  Header: X-Company-ID: 1                    │
│  Body: {query: "...", library_id?: 3}       │
└─────────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────┐
│  helpers.build_query(company_id, library_id,│
│                      query)                 │
│                                              │
│  1. Inject company identity                 │
│     → trade_companies.agent_identity_md     │
│     → or ~/.trade/{slug}/agent-identity.md  │
│                                              │
│  2. Inject document library context (if library_id provided) │
│     → "The user is asking a question within document library X..." │
│                                              │
│  3. Concatenate TRADE_SYSTEM_PROMPT          │
│     → Foreign trade senior sales behavior guidelines │
│     → Sales scripts, customer type assessment, negotiation techniques │
└─────────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────┐
│  AIAgent.chat(full_query)                  │
│                                              │
│  • quiet_mode=True, max_iterations=90       │
│  • Company data directory → ~/.trade/{slug}/│
│  • Agent Loop: Read file → Analyze → Decide → Act │
│  • Tools: read_file, terminal, web_search... │
└─────────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────┐
│  chat_memory.save_with_context()            │
│  → Write to conversations table             │
│  → Hindsight.retain() (if configured)      │
└─────────────────────────────────────────────┘
        │
        ▼
  Returns {"response": "...", "conversation": {...}}
```

---

## 7. API Endpoint Summary

### Companies

| Method | Path | Description |
|--------|------|-------------|
| GET | `/companies` | List all companies |
| POST | `/companies` | Create a company |
| GET | `/companies/{id}` | Get company details |
| PUT | `/companies/{id}` | Update company |
| DELETE | `/companies/{id}` | Delete company |
| GET | `/companies/{id}/agent-identity` | Get Agent identity |
| PUT | `/companies/{id}/agent-identity` | Update Agent identity |

### Document Libraries

| Method | Path | Description |
|--------|------|-------------|
| GET | `/libraries` | List current company's document libraries (requires X-Company-ID) |
| POST | `/libraries` | Create a document library |
| GET | `/libraries/{id}` | Get document library details |
| PUT | `/libraries/{id}` | Update document library |
| DELETE | `/libraries/{id}` | Delete document library |

### Customers

| Method | Path | Description |
|--------|------|-------------|
| GET | `/customers` | List current company's customers (requires X-Company-ID) |
| POST | `/customers` | Create a customer |
| GET | `/customers/{id}` | Get customer details |
| PUT | `/customers/{id}` | Update customer |
| DELETE | `/customers/{id}` | Delete customer |
| POST | `/customers/{id}/libraries/{lib_id}` | Associate document library |
| DELETE | `/customers/{id}/libraries/{lib_id}` | Disassociate document library |
| GET | `/customers/{id}/libraries` | List customer's associated document libraries |

### Conversations

| Method | Path | Description |
|--------|------|-------------|
| GET | `/conversations` | List current company's conversation history |
| POST | `/conversations` | Save a conversation |
| GET | `/conversations/{id}` | Get a single conversation |

### Chat

| Method | Path | Description |
|--------|------|-------------|
| POST | `/chat` | Normal conversation (returns full response) |
| POST | `/chat/stream` | Streaming conversation (SSE, real-time tool call display) |

### Onboarding

| Method | Path | Description |
|--------|------|-------------|
| GET | `/onboarding/status` | Check if onboarding is complete |
| POST | `/onboarding/first-company` | Atomically create company + Agent identity |

### Other

| Method | Path | Description |
|--------|------|-------------|
| GET | `/memory/status` | Hindsight memory status |
| GET | `/memory/recall?q=` | Search long-term memory |
| GET | `/models/providers` | List available LLM providers |

---

## 8. Data Isolation Strategy

```
Every request must carry the X-Company-ID Header

X-Company-ID: 1
    → Query companies WHERE id=1
    → Verify is_active=True
    → All DB operations automatically filter by company_id=1
    → Agent data directory → ~/.trade/{slug}/

Switching companies:
    → Frontend dropdown change → update sessionStorage['trade_company_id']
    → All subsequent requests automatically carry the new X-Company-ID
    → Clear current conversation, load new company data
```

---

## 9. Skills System

11 B2B industry skills installed into `~/.hermes/skills/`, auto-discovered by the Hermes Agent:

| Skill | Trigger Keywords | Function |
|-------|-----------------|----------|
| `b2b-document` | analyze document, extract content, PDF | 16 file format parsing |
| `b2b-platform` | Alibaba International Station, platform diagnosis | Store optimization recommendations |
| `b2b-social-media` | Facebook, Instagram, post | Content calendar generation |
| `b2b-linkedin-marketing` | LinkedIn, outreach email | Profile optimization + content strategy |
| `b2b-lead-generation` | customer analysis, cold email, outreach | Account IQ + follow-up sequence |
| `b2b-customs-data` | customs data, importer | Buyer screening and analysis |
| `b2b-onboarding` | new company deployment, startup | Full marketing plan |
| `b2b-customer-mgmt` | customer management, quotation | Lifecycle management |
| `b2b-daily-automation` | daily tasks, scheduled | 7 cron tasks |
| `b2b-data-directory` | data directory, ~/.trade/ | Directory structure initialization |
| `b2b-doc-generation` | generate document, PPTX, contract | Professional document generation |
| `b2b-email-intel` | email background check, 120+ platforms | Customer authenticity verification |

---

## 10. Known Gaps and TODOs

| Priority | Issue | Description |
|----------|-------|-------------|
| 🔴 High | `api.py` 846 lines exceeds limit | Needs to be split into four Router sub-files: companies/libraries/customers/chat |
| 🔴 High | No customer management UI in frontend | Docs mention "B2B Frontend Customer Management UI" but not actually implemented |
| 🟡 Medium | Windows compatibility not tested | Docs explicitly marked "pending test" |
| 🟡 Medium | macOS compatibility not tested | Docs explicitly marked "pending test" |
| 🟡 Medium | No messaging platform integration | Telegram/WeChat/Feishu integration in planning |
| 🟢 Low | `api.py` still has unused `import os` | Not caught by lint |

---

## 11. Startup Dependency Chain

```
python server.py
    │
    ├─ Hermes version check (_check_hermes_version)
    │     └─ Failure → exit 1
    │
    ├─ load_hermes_dotenv() loads ~/.hermes/.env
    │
    ├─ init_db() table creation/migration
    │     └─ Create data/trade.db
    │
    ├─ Mount /api/trade/* routes
    │
    └─ uvicorn.run(port=9119)
          │
          └─ http://127.0.0.1:9119/trade  (Frontend)
              http://127.0.0.1:9119/api/trade/* (API)
```
