# Facebook Operator Redesign

## Target Product

The project should become an intelligent Facebook operator controlled by OpenClaw. OpenClaw receives the user's natural-language command, then calls this project through MCP. This project owns planning, execution, evidence, lead data, customer replies, and analysis.

The target operating loop is:

```text
User command -> OpenClaw -> Facebook-auto MCP -> operator planner -> task queue -> browser/CDP executor -> Facebook -> evidence/data -> AI analysis -> OpenClaw summary
```

## Current Gap

The current project is still a task console prototype. It can queue browser actions, publish drafts, collect some comments, and expose MCP tools, but it does not yet behave like an autonomous operator.

Major gaps:

- No daily operating plan object. Existing campaign plans are content drafts, not a full day plan with priorities, statuses, dependencies, and evidence.
- No unified task orchestration. Tasks are simple JSON records; there is no durable queue, retry policy, rate limit per task class, or dependency chain.
- No customer conversation memory. Messenger messages are individual review items, not threaded customer records with status, intent, source, and next action.
- No real knowledge base. Customer reply has a placeholder RAG path, but there is no document store, chunking, retrieval, citation, or answer policy.
- Lead discovery is not table-first. Lead candidates exist, but the project lacks a normalized one-row-per-commenter table with source channel, post, comment, profile, AI fields, and follow-up status.
- Search channels are incomplete. Search currently focuses on posts; groups, pages, Marketplace, videos, and group post discovery need channel-specific collectors.
- Browser execution lacks a high-level operator state machine. It can run actions, but not yet decide, sequence, validate, retry, and summarize an entire business workflow.
- Observability is incomplete. There are screenshots and logs, but no trace that links user command -> MCP call -> browser steps -> raw data -> AI decision -> final result.

## Target Modules

### 1. Operator Planner

Converts a user requirement into an executable plan.

Examples:

- "每天帮我运营 Facebook" -> create today's operation plan.
- "Disposable Ice Pop Bags 搜索客户" -> create a lead discovery plan across posts, groups, Marketplace, and related surfaces.
- "给这个群组发信息" -> create a guarded group post task.

Required data model:

- `OperatorPlan`
  - `id`
  - `date`
  - `goal`
  - `status`
  - `summary`
  - `createdFromCommand`
  - `items`
- `OperatorPlanItem`
  - `id`
  - `planId`
  - `type`
  - `channel`
  - `targetUrl`
  - `brief`
  - `status`
  - `scheduledAt`
  - `taskId`
  - `evidence`
  - `resultSummary`

### 2. Publishing Operator

Publishes or prepares content for:

- Facebook feed/new status.
- Target groups.
- Future page support if page permissions are available.

Safety policy:

- Draft by default.
- `autoPublish=true` only when explicitly requested.
- Daily publish limit.
- Diagnose target page before publishing.
- Save evidence after fill/submit/failure.

MCP tools needed:

- `facebook_auto_create_daily_plan`
- `facebook_auto_queue_publish_feed_post`
- `facebook_auto_queue_publish_group_post`
- `facebook_auto_run_operator_plan`

### 3. Messenger / Customer Service Operator

Detects new customer messages, drafts replies, and can send only after policy allows it.

Required capabilities:

- Thread-level customer memory.
- Message classification: inquiry, objection, pricing, logistics, spam, follow-up.
- Knowledge-base retrieval before answering.
- Reply draft with citations/source snippets.
- Human approval mode and optional trusted auto-send mode.

Required data model:

- `CustomerThread`
  - `id`
  - `platformThreadId`
  - `threadUrl`
  - `customerName`
  - `profileUrl`
  - `status`
  - `intent`
  - `lastMessageAt`
  - `nextAction`
- `KnowledgeDocument`
  - `id`
  - `title`
  - `source`
  - `content`
  - `createdAt`
- `KnowledgeChunk`
  - `id`
  - `documentId`
  - `text`
  - `embedding`

### 4. Lead Discovery Operator

Discovers leads from keywords across multiple Facebook surfaces.

Target channels:

- Posts search.
- Group search.
- Group posts.
- Marketplace search.
- Videos/Reels when comments are visible.
- Direct post/permalink URLs.

The output must be a normalized table, not just a loose candidate list.

Required data model:

- `LeadDiscoveryRun`
  - `id`
  - `keyword`
  - `channels`
  - `status`
  - `startedAt`
  - `completedAt`
  - `summary`
- `LeadSource`
  - `id`
  - `runId`
  - `channel`
  - `sourceUrl`
  - `sourceTitle`
  - `sourceAuthor`
  - `sourceAuthorUrl`
  - `commentCountHint`
- `LeadComment`
  - `id`
  - `runId`
  - `sourceId`
  - `commenterName`
  - `commenterProfileUrl`
  - `commentText`
  - `commentUrl`
  - `commentedAt`
  - `collectedAt`
  - `dedupeKey`
- `LeadAnalysis`
  - `id`
  - `commentId`
  - `score`
  - `intent`
  - `need`
  - `budgetSignal`
  - `urgency`
  - `recommendedAction`
  - `reason`
  - `status`

### 5. AI Analysis Table

The lead table should support:

- Per-row AI score.
- Reason and recommended next action.
- Filtering by score, channel, keyword, intent, and status.
- Export to CSV/XLSX.
- Save selected rows to CRM.
- Queue add-friend tasks from selected rows.

MCP tools needed:

- `facebook_auto_create_lead_discovery_run`
- `facebook_auto_run_lead_discovery`
- `facebook_auto_analyze_lead_table`
- `facebook_auto_export_lead_table`
- `facebook_auto_queue_friend_requests_from_analysis`

### 6. Browser Session Manager

OpenClaw should not inspect the desktop. The project must expose browser state through MCP.

Required capabilities:

- List CDP tabs.
- Pick active Facebook/Messenger tab.
- Snapshot current page.
- Identify page type: home, group, post, search, Marketplace, Messenger, login, checkpoint.
- Return actionable blockers.

Existing `facebook_auto_health` and `facebook_auto_browser_snapshot` are the start of this module.

### 7. Durable Queue And Tracing

The prototype JSON store is acceptable for early testing, but the target system needs a durable queue and trace.

Recommended production path:

- Database: SQLite first, then PostgreSQL when needed.
- Queue: BullMQ + Redis, or a SQLite-backed queue if Redis should be avoided.
- Trace: local trace table first, Langfuse-compatible later.

Each trace should link:

```text
command -> MCP tool -> plan -> task -> browser snapshot -> browser actions -> raw records -> AI analysis -> final summary
```

## Recommended Implementation Phases

### Phase 1: Reframe The Current App

Goal: make the project data model match the desired product.

Deliverables:

- Add operator plan types and local store fields.
- Add normalized lead discovery tables.
- Add knowledge-base document/chunk types.
- Add MCP tools for daily plan, lead run, lead analysis, and snapshot.
- Update UI labels from "prototype task console" to "Facebook operator".

### Phase 2: Fix Lead Discovery Properly

Goal: make keyword discovery produce a clean table.

Deliverables:

- Channel-specific collectors for posts, groups, Marketplace, and direct post URLs.
- Source table plus one-row-per-comment table.
- Strong dedupe by profile + source + text.
- AI analysis endpoint for the table.
- CSV export.

### Phase 3: Customer Reply With Knowledge Base

Goal: answer customers with retrieved business context.

Deliverables:

- Knowledge document upload/edit UI.
- Basic chunking and keyword retrieval first.
- Optional embeddings later.
- Messenger thread model.
- Draft reply with retrieved snippets.
- Approval/send workflow.

### Phase 4: Daily Operator

Goal: let OpenClaw ask the project to create and execute daily work.

Deliverables:

- `create_daily_plan` MCP tool.
- `run_operator_plan` MCP tool.
- Morning plan generation.
- Publish draft -> dry-run evidence -> explicit approval flow.
- `create_publish_dry_run_for_task` and `approve_publish_task` MCP tools.
- Progress summaries back to OpenClaw.
- End-of-day report.

### Phase 5: Production Reliability

Goal: make it dependable for daily use.

Deliverables:

- Durable queue.
- Rate limits per task type.
- Retry/backoff policy.
- Full traces.
- Selector pack.
- Regression tests against saved snapshots.

## Immediate Decision

Do not keep expanding isolated features first. The next code work should start with Phase 1 and Phase 2:

1. Add the new operator/lead/knowledge data model.
2. Add MCP tools that map to the desired product language.
3. Make lead discovery save normalized source/comment rows.
4. Add AI table analysis and export.

After that, daily plan and customer service will have a solid base instead of sitting on loose task records.
