```markdown
# EcoBe Bot — Developer Reference

**Version:** v2026.04.13  
**WhatsApp Career Coaching Platform**

## Architecture Overview

EcoBe is a WhatsApp-based career coaching bot that manages the full lifecycle of a job seeker — from onboarding through daily job delivery. It runs on **Node.js** using **Baileys** (WhatsApp Web protocol), **OpenAI GPT-4.1** for all AI tasks, and a PHP/Node backend on `vianexu.com`.

### Main Components

- **Coach Interface**: Private WhatsApp chat. Create clients, search jobs, update profiles, trigger reports.
- **Group Interface**: Per-client WhatsApp group. Onboarding form, CV generation, daily jobs, application tracking.
- **Sync Layer**: Dual-write: API first, always local mirror. Queue-based retry on failure.
- **Admin Site**: `vianexu.com/clients/ecobe/admin` — profile viewer/editor for coaches. Reads `cvmaster.json` + `form.json`.

### Directory Structure

```bash
# Project root: /home/administrator/ecobot/
index.js                    # Entry point — coach chat + routing
lib/
  groupHandler.js           # Group orchestration (all phases)
  groupForm.js              # 28-question onboarding form
  groupCvmaster.js          # CV Master + Career Strategy generation
  groupJobs.js              # Daily job scheduler + dispatcher
  groupJobResponse.js       # Client job interaction handling
  groupCvBuilder.js         # Per-job CV + cover letter generation
  sync.js                   # Dual-write local+API with queue
  viaweb.js                 # API client for vianexu.com backend
  jobSearch.js              # Job search (TheirStack + PHP) + AI triage
  report.js                 # Report generation + group creation
  documents.js              # PDF/DOCX download + text extraction
  transcription.js          # WhatsApp audio → text (Lemonfox API)
  journey.js                # Onboarding phase + event tracking
training/
  jobsearch.txt             # Coach chat system prompt
  group.txt                 # Group bot system prompt
  cvmaster.txt              # CV Master generation prompt
  strategy.txt              # Career Strategy generation prompt
mentees/{slug}/             # All per-client data (canonical store)
json/numbers.json           # Authorized WhatsApp numbers
bots/{BOTID}/               # Baileys session, chat logs, sync queue, pause flag
```

### Models Used

| Task                                      | Model            |
|-------------------------------------------|------------------|
| All coach chat, job search, form questions, intent detection | `gpt-4.1-mini` |
| CV Master generation, Career Strategy generation | `gpt-4.1`      |
| Per-job CV and cover letter generation    | `gpt-4.1-mini` |

## Environment Variables

| Variable            | Used By              | Description                              |
|---------------------|----------------------|------------------------------------------|
| `OPENAI_KEY`        | index.js             | OpenAI API bearer token                  |
| `BOT_API_TOKEN`     | viaweb.js, sync.js   | Bearer token for vianexu.com admin API   |
| `THEIRSTACK_KEY`    | jobSearch.js         | Primary TheirStack job search API key    |
| `THEIRSTACK_KEY2`   | jobSearch.js         | Secondary key (credit exhaustion fallback) |

Set in `.env` at `/home/administrator/ecobot/bots/351923199040/.env`. Loaded via `dotenv` at startup.

## Config Files

### json/numbers.json — Authorized Numbers

Only these WhatsApp numbers can interact with the bot in private chat. Numbers are also used to classify group participants as coach vs. client.

```json
[
  { "number": "15503...", "name": "Vitor", "role": "administrator" },
  { "number": "23890...", "name": "Anna", "role": "coach" }
]
```

### bots/{BOTID}/jobs-paused.flag

When this file exists, the job scheduler skips all dispatches (daily run + catchup). No bot restart needed — checked at runtime.

```bash
# Pause job delivery
touch ~/ecobot/bots/351923199040/jobs-paused.flag

# Resume job delivery
rm ~/ecobot/bots/351923199040/jobs-paused.flag
```

## index.js — Coach Private Chat

Entry point. Runs as `node index.js` from inside `bots/{BOTID}/`.

### Session State

```js
sessions[chatId] = {
  lastJobs: [],                    // Last search results (for SENDTOGROUP)
  shownUrls: Set,                  // Deduplication of shown job URLs
  processing: false,               // Lock to prevent concurrent processing
  lastClient: null,                // { name, slug, profile }
  pendingUpload: null,             // Document awaiting SAVECV
  pendingLead: null,               // Set by LEADDATA
  awaitingLinkedinCv: null         // Set after SAVECV("personal")
}
```

### Main Commands (dispatched after AI response)

- `LEADDATA({leadName, email?, phone?, shortDescription?})` — Create new mentee
- `SAVECV("personal"|"linkedin")` — Save uploaded document as CV
- `UPDATEDATA("slug", {...})` — Merge-update career strategy
- `CLIENTSEARCH("name")` — Search jobs for a client
- `MULTISEARCH(["role1","role2"], "location"[, "7d"|"24h"])`
- `SEARCHJOBS("role", "location"[, "7d"|"24h"])`
- `SENDTOGROUP("name")` — Send last search results to client's group
- `CAREERSTRATEGY("name")` — Display client profile
- `GENERATEREPORT()` / `GENERATEREPORTFOR("name")`

### Watchdog

Runs every 30 seconds. Automatically retries unanswered messages (5s–10min old) to prevent silent failures.

## Core Modules

### groupHandler.js

Orchestrates all group activity and manages the phase machine:

**Phases:** `waiting` → `form` → `cvmaster` → `active`

### groupForm.js

Handles the 28-question onboarding form with CV-aware suggestions and confirmation logic.

### groupCvmaster.js

Generates `cvmaster.json` and `career-strategy.json` using GPT-4.1 after form completion.

### groupJobs.js

Daily job scheduler (runs 06:00–06:59 Swiss time). Supports catchup and pause flag.

### groupJobResponse.js

Handles client interactions with proposed jobs (interest, CV review, status updates).

### groupCvBuilder.js

Generates per-job ATS-optimized CVs and cover letters as HTML (with PDF export).

## Support Modules

- **sync.js + viaweb.js**: Dual-write (API first, local mirror) with retry queue
- **jobSearch.js**: Job search via TheirStack + PHP backend + AI triage
- **report.js**: Generates coaching report + creates WhatsApp group
- **documents.js**: Downloads and extracts text from PDF/DOCX
- **transcription.js**: WhatsApp audio transcription via Lemonfox AI
- **journey.js**: Tracks phases and events for analytics

## Data Models

- `career-strategy.json` — Main client profile and strategy
- `form.json` — Onboarding form answers
- `cvmaster.json` — Structured CV master data
- `group.json` — Group metadata and current phase
- `jobtracking.json` — All jobs sent + status history
- `journey.json` — Phase transitions and events

## Training Prompts

Located in `/training/`:
- `jobsearch.txt` — Coach private chat
- `group.txt` — Group bot persona
- `cvmaster.txt` — CV Master generation
- `strategy.txt` — Career Strategy generation

## Full Client Lifecycle

1. **Lead Creation** (Coach chat): Upload CV → LEADDATA + SAVECV
2. **Report Generation**: AI report + PDF + WhatsApp group creation
3. **Waiting Phase**: Coach and client join group
4. **Form Phase**: 28-question onboarding (CV-aware)
5. **CV Master Phase**: Generate `cvmaster.json` + `career-strategy.json`
6. **Active Phase**: Daily personalized job delivery + application support

## Job Interaction Flow

**Proposed** → **Interested** → **CV Review** → **CV Ready** → **Cover Review** → **Cover Ready** → **Applied** → **Interview / Offer / Rejected**

---

This is the complete README.md version of the original HTML developer reference, converted to clean, readable Markdown in English.
```
