# Lead router: classify inbound leads with Claude before they reach your CRM (Cloudflare Worker)

One file, `src/index.js`. It holds the Worker, the **system prompt** (`SYSTEM_PROMPT`, with `[PLACEHOLDERS]` you edit) and the **tool schema** (`TOOL`) as labelled exported constants.

The video used n8n. This template is the same logic as one Worker: webhook in, normalize, Claude, route.

**Tested with simulated API responses only; not yet run against live Claude, HubSpot or Slack.**

## What it does
1. Your web form POSTs JSON `{name, email, company, role, message}` to the Worker. If `FORM_SECRET` is set, the form must send it in the `x-form-secret` header, otherwise 401. Bad JSON or a missing/invalid email gives 400 (never 5xx).
2. Fields are trimmed, the email is lowercased, the domain is extracted, and common free-mail domains (gmail, outlook, ...) are flagged.
3. One Claude Messages API call with a single tool, `classify_lead` (`strict: true`, `additionalProperties: false`): `category` (qualified_buyer, nurture, partner, support, job_seeker, vendor, spam), `fit_score` (0-100 integer), `confidence` (0-1), `owner_team`, `reason`.
4. Routing:
   - confidence below `CONFIDENCE_THRESHOLD` (default 0.7): Slack message to the **review** channel, nothing in the CRM.
   - `qualified_buyer`: HubSpot contact + Slack message to the rep, including the reason.
   - `nurture`: HubSpot contact only.
   - `support`, `partner`, `job_seeker`, `vendor`: Slack to a separate webhook (skipped if `SLACK_OTHER_WEBHOOK_URL` is unset).
   - `spam`: nothing.
5. Every lead's input and the model output are written with `console.log` as one JSON line (`step: "lead"`). **Wire that to your log table** (Workers Logs / Logpush, or add a write to your own database in the `log()` helper). The log contains lead data (names, emails, messages); treat it as personal data.

## Safety behaviour you should know
- `tool_choice` is `{"type":"auto"}`. Current Claude models (Opus 5.5, Sonnet 5.5) return HTTP 400 on forced tool use, so the prompt asks for the tool and the code checks the reply.
- No `temperature`, `top_p` or `top_k` is sent (Sonnet 5.5 returns 400 on them).
- `strict: true` is required for the schema guarantee; the code validates the fields again anyway.
- If the reply has no `classify_lead` call, the fields fail validation, the Claude call fails, or the call times out, the lead goes to **human review** and is never auto-routed or written to the CRM.
- The lead text is passed to Claude as JSON data, and the prompt tells the model to treat it as data, not instructions. This reduces, not removes, prompt-injection risk; the review path and the CRM rules limit the damage.
- A HubSpot "contact already exists" (409) is treated as success. Other HubSpot or Slack failures return 502 and are logged (step and HTTP status only).
- No retry or de-duplication: if your form retries on 502, a Slack message may be sent twice.

## Setup
1. `npm install`
2. `cp wrangler.toml.example wrangler.toml`
3. Secrets, one by one (`npx wrangler secret put NAME`): `ANTHROPIC_API_KEY`, `HUBSPOT_TOKEN` (a HubSpot private app token with permission to create contacts), `SLACK_REVIEW_WEBHOOK_URL`, `SLACK_REP_WEBHOOK_URL`. Optional: `FORM_SECRET`, `SLACK_OTHER_WEBHOOK_URL`.
4. Optional vars in `wrangler.toml`: `CLAUDE_MODEL` (default `claude-haiku-5-5`), `CONFIDENCE_THRESHOLD` (default `0.7`).
5. `npx wrangler deploy`
6. Point your form's webhook at the Worker URL. If you set `FORM_SECRET`, send it as the `x-form-secret` header. Set it: without it anyone who finds the URL can trigger Claude calls and Slack/CRM writes. Do not put the secret in public browser code; send the form through your backend or a form tool that sets headers server-side.

## Edit the profile
Open `src/index.js` and edit `SYSTEM_PROMPT`: replace every `[SQUARE BRACKET]` placeholder with your company, product, ideal customer, buying signals, and the team names. Keep the category names as they are, or change them in three places together: `CATEGORIES`, the prompt, and the routing in `decide()`.

Prompt caching: the system prompt carries `cache_control`, but caching only kicks in once the cached prefix is at least 512 tokens on Haiku 5.5. A short prompt still works, it is just not cached, and no error tells you. Keep the profile detailed (which also tends to help classification).

## Test on your past leads
1. Export 50-200 past leads to a CSV with the header `name,email,company,role,message,label`. `label` is what a human decided (one of the 7 categories). See `sample-leads.csv`.
2. Run against your deployed Worker. This calls `/classify-only`, a dry-run endpoint that returns the classification and the routing decision but **does not write to HubSpot or Slack**:
   ```
   WORKER_URL=https://lead-router.<you>.workers.dev FORM_SECRET=... node scripts/eval.mjs leads.csv
   ```
   `/classify-only` answers 403 until `FORM_SECRET` is set, so strangers cannot spend your Claude credits through it.
3. It prints each lead with the human label and the model category, then the agreement percentage and how many leads would go to human review. Read the disagreements, edit the profile, redeploy, repeat.
Agreement on a small sample is a rough signal, not a guarantee. Note that `/classify-only` still makes one Claude call per lead and logs the lead, so use real past data only if you are allowed to send it to Claude.

## Tests
`npm test` (vitest, `fetch` is mocked, no network, no API keys) and `npm run check`. They cover: bad input, secrets, each category's routing, low confidence and invalid output going to review, the request shape (`strict`, `tool_choice` auto, no sampling params, default model), and the eval script.

## Cost
One Claude call per lead, billed per token (input and output). What drives it: how many leads you get, the length of the system prompt and of the message (messages are capped at 4000 characters per field), and the model you choose. Prompt caching can reduce the repeated system-prompt part once it is eligible (see above). Current prices: https://platform.claude.com/docs/en/about-claude/pricing. HubSpot, Slack and Cloudflare usage depends on your own plans; check their pages. This README gives no price figures on purpose.

## What it does NOT do
- No enrichment (company size, funding), no duplicate-lead merging, no scoring against your CRM history.
- No retry queue and no idempotency key.
- No HubSpot owner assignment or deal creation: it creates the contact only.
- Slack uses incoming webhooks, so each webhook posts to one channel.
- Not tested against live Claude, HubSpot or Slack (simulated responses only).
