# Xpace Chat — Build Spec v1.0 (1 Nov 2026)

Working name: **Xpace Chat**. Successor of WA Internal AI Agent (bx_agents) 1.6.0. Everything 1.6.0 does is kept; it changes home, not shape.

## 1. What it is

One inbox per salesperson where WhatsApp customers, follow-ups and internal rooms (WhatsApp groups, WeChat/WeCom) sit side by side. The AI drafts, a person sends. The owner sees everyone. Setup is one QR scan. Runs standalone or inside the CRM (Perfex now, Xpace CRM later) with the same login.

Rules that hold everywhere (from 1.4–1.6):
- The AI never sends and never approves. Exception: the narrow "safe auto-replies" (hours, address, thanks) when an admin switches them on.
- Live by default (0.6.0): there is no test mode and no Go live step. The only dry-run is the developer env switch `XC_DRY_RUN=1`; it is not in the UI.
- Habits stay: quick replies used word for word; salespeople keep the WhatsApp Business app.
- Fact-sheet-only prices; any other ringgit amount marks the draft "check before sending".
- Every outgoing message passes the gate: opt-out, block list, valid number, 24-hour window or approved template, monthly spend cap, live switch.
- Own numbers (part-timers): nothing recorded until they agree; only company customers visible to owner; private "Not sorted" tray; Personal contacts hashed, never stored; unsorted erased after N days.
- Campaign preparer never approves their own; campaigns only to people who agreed to offers.

## 2. Architecture

```
┌──────────────── Xpace Chat (one Docker container) ────────────────┐
│  web/   one-page app (desktop + phone PWA), EN/MS/ZH               │
│  api/   REST + SSE, session auth (local login or CRM SSO token)    │
│  core/  contacts · rooms · messages · drafts · gate · approvals    │
│         follow-ups · bulk sends · tasks · roles · audit · spend    │
│  ai/    brain (fact sheet, quick replies, chats, rules) · drafter  │
│         task-spotter · translator · engines: anthropic | openai    │
│  channels/  whatsapp-link (Baileys, QR, per staff)   [required]    │
│             meta-cloud (templates, campaigns, webhook) [optional]  │
│             wecom (internal rooms, bot)                [optional]  │
│  crm/   bridge interface → perfex adapter (REST) · xpace-crm later │
│  db/    SQLite (better-sqlite3), WAL, migrations, nightly backup   │
└────────────────────────────────────────────────────────────────────┘
          ▲ iframe + SSO                     ▲ webhooks
   Perfex module xpace_chat 1.7.0      Meta / WeCom
```

- **Language:** TypeScript on Node 22. One process, one SQLite file, `docker compose up` or `npx xpace-chat`.
- **Why standalone:** Baileys and WeCom are Node libraries; Perfex is PHP and is being replaced by Xpace CRM. The CRM module becomes a thin bridge.
- **Hosting:** hosted by Xpace IT (zero install) or self-hosted (one Docker command). Both identical.

## 3. Roles (same four as 1.6.0, mapped to CRM roles when bridged)

| Role | Sees | Does |
|---|---|---|
| salesperson | own chats (assigned, unassigned on own number, covering a colleague), own follow-ups, rooms they are in | send/edit/reject drafts, quick-add lead, schedule within rules |
| manager / owner | whole team, every non-private chat, approvals | take over, approve price flags, approve bulk sends, assign |
| admin | Connect, Teach the AI, Settings, Spend, Reports | setup, rules |
| part-timer (own number) | as salesperson + private tray | agree/stop recording, sort Customer/Personal |

Rights are flags: `view_own, view_all, approve_drafts, approve_campaign, create_campaign, schedule_send, manage_followups, manage_autoreply, settings`. Same names as 1.6.0 capabilities.

## 4. Data model (SQLite)

```
staff(id, name, email, phone, role, rights json, lang, on_leave_until, cover_staff_id, active)
channel_account(id, kind whatsapp_link|meta_cloud|wecom, label, phone, owner_kind company|own, staff_id,
                state linked|waiting|disconnected, own_agreed_by, own_agreed_at, meta json, created_at)
contact(id, kind customer|staff|external, name, phone_canon, phone_hash, wechat_id, company, area, source,
        stage, consent_offers, optout_at, blocked, crm_lead_id, crm_customer_id, salesperson_id, notes)
room(id, kind customer|project|team|dm, title, contact_id, crm_project_id, created_by)
room_member(room_id, contact_id|staff_id, channel_account_id, role)
message(id, room_id, channel_account_id, dir in|out|system, from_contact_id|from_staff_id, text, media json,
        msg_type, lang, translation, private 0|1, provider_msg_id, at, read_by json)
draft(id, room_id, to_contact_id, text, original_text, intent, drafter ai|ai_check|ai_failed|ai_budget|mock|human,
      note, status pending|approved|sent|would_send|rejected|scheduled|cancelled, template_name, scheduled_at,
      created_by, decided_by, decided_at, send_log_id)
send_log(id, draft_id, bulk_id, channel_account_id, to_phone, body, mode live|dryrun, status, category, est_cost, provider_msg_id, at)
followup_rule(id, stage, step, days, template_name|message_id, active)
followup(id, contact_id, step, due_at, draft_id, state)
schedule(id, draft_id|bulk_id, run_at, state)
message_template(id, name, kind plain|template, category, language, body, preview, status draft|sent_to_meta|approved|rejected)
bulk(id, name, filters json, message_id, route meta|link, when json, state, prepared_by, approved_by, est_cost, batch_size, batch_gap_min)
bulk_recipient(bulk_id, contact_id, state queued|sent|skipped|failed, skip_reason)
task(id, room_id, title, assignee_staff_id, due_at, state, source_message_id, crm_task_id)
approval(id, kind price|campaign|unknown_sender|other, ref_id, text, state, requested_by, decided_by, at)
brain(singleton json: business_name, facts, chats, quick_replies, handover_topics, never_promise, extra_rules,
      engine, model, api_key_enc, budget_rm, rate_in, rate_out, reply_max_chars, history_messages, max_tokens)
ai_usage(month, calls, fails, tokens_in, tokens_out, est_rm)
setting(key, value json)   -- live, quiet hours, cap, opt words, block list, own_keep_days, batch rules…
ignore(phone_hash, channel_account_id)   -- Personal contacts, hash only
audit(id, actor, action, ref, before, after, at)
```

## 5. Channel interface

```ts
interface Channel {
  kind: 'whatsapp_link' | 'meta_cloud' | 'wecom';
  connect(account): AsyncIterable<ConnectEvent>;   // qr(dataUrl) | linked | disconnected | error
  send(account, to, payload, ctx): Promise<SendResult>; // human-paced for whatsapp_link
  onInbound(handler(InboundMessage)): void;
  capabilities(): { templates: boolean; bulk: boolean; after24h: boolean; groups: boolean };
}
```
- **whatsapp_link**: Baileys multi-session, auth per `channel_account` in `data/auth/<id>/`, QR streamed over SSE to Connect page, reconnect with backoff, logged-out → state `waiting`. Sender: 1 message / 3–8 s per account, max 30 proactive messages/day/account, only to contacts with prior inbound. Reads group messages for team rooms.
- **meta_cloud**: port of 1.5.0 Connect (embedded signup, provider relay, paste key), templates fetched from Meta, webhook `/hooks/meta` with signature check, `smb_message_echoes`.
- **wecom**: bot via WeCom AI bot SDK (callback URL + token); creates project groups; posts relays; inbound from internal staff/external designers where their admin allows. Fallback: 群机器人 webhook (post-only).

Route choice for bulk: `meta_cloud` when connected and message is an approved template; else `whatsapp_link` slow send only to prior-inbound contacts within the daily cap; cold lists refused.

## 6. AI

- Drafter = port of `Xw_ai_drafter` (system prompt, tool `write_reply`, intents, price check, injection guard, holding reply, budget). Engines: anthropic (default claude-haiku-5-5), openai.
- Task-spotter: on internal room messages, propose tasks `{title, assignee, due}` and customer notices; never auto-create.
- Translator: zh↔en/ms lines for WeChat rooms; stored in `message.translation`.
- Summariser: room "Summarise today", customer AI summary panel.
- Owner brief 08:00, team brief 17:30 (settings).

## 7. API (REST, JSON; SSE at /events)

`/auth/login`, `/auth/sso` (HMAC token from CRM) · `/me` · `/rooms?filter=` · `/rooms/:id/messages` · `/rooms/:id/send` · `/drafts/:id/{approve,reject,schedule,edit}` · `/followups` · `/followup-rules` · `/bulk` (+ `/preview`, `/submit`, `/approve`, `/pause`, `/cancel`) · `/templates` · `/tasks` · `/approvals` · `/connect/accounts` (+ `/qr` SSE, `/agree`, `/stop`) · `/brain` (+ `/try`) · `/settings` · `/spend` · `/reports` · `/tray` (own numbers) · `/hooks/meta`, `/hooks/wecom`.

## 8. Web app

One page, routes by hash: `#inbox`, `#room/:id`, `#followups`, `#bulk`, `#internal`, `#team`, `#connect`, `#teach`, `#settings`. Mobile: bottom bar Inbox · Follow-ups · Internal · Me; list→chat→details. PWA manifest + service worker (shell only). Languages EN/MS/ZH from 1.6.0 language files.

## 9. CRM bridge

`crm/Bridge` interface: `staff()`, `leads(filter)`, `lead(id)`, `createLead()`, `addNote()`, `setStage()`, `tasks()`, `createTask()`, `projects()`. Perfex adapter uses the BX Integration API module (existing) / Perfex REST. Perfex module **xpace_chat 1.7.0**: sidebar items (Inbox, Internal, Team, Connect) → iframe of Xpace Chat with SSO token; activates with one click; no PHP business logic left except SSO and the importer.

**Importer (1.6.0 → Xpace Chat):** numbers → channel_account; staff/approvers/cover → staff; brain options → brain; xw_msg/xw_send_log → message; xw_draft → draft; xw_followup/xw_schedule → followup/schedule; xw_message/xw_campaign(+recipient) → message_template/bulk; xw_consent/xw_optout/xw_ignore → contact fields/ignore; settings → setting. Repeat-safe.

## 10. Phases

1. **Core + WhatsApp Link + Inbox + Teach + Connect + Follow-ups** (this build) — salesperson can scan, see chats, get drafts, send; owner sees team; follow-ups prepared.
2. **Meta Cloud + Bulk send + Templates** (port of 1.5/1.3.2) — campaigns.
3. **WeCom + Internal rooms + tasks + briefs**.
4. **Perfex module 1.7.0 + importer**; Xpace CRM adapter when Xpace CRM exists.

## 11. Non-goals

No personal-WeChat web protocols (ban risk). No cold-list sending on any route. No AI auto-send beyond safe auto-replies.
