|
1 | | -# FlowPilot Agentic Architecture |
2 | | - |
3 | | -## Phase 1: Skill Registry + Unified Tool Engine ✅ DONE |
4 | | - |
5 | | -### Completed |
6 | | -- **Database tables**: `agent_skills`, `agent_memory`, `agent_activity` with RLS policies |
7 | | -- **Enums**: `agent_scope`, `agent_skill_category`, `agent_activity_status`, `agent_type`, `agent_memory_category` |
8 | | -- **11 built-in skills** seeded: migrate_url, create_page_block, write_blog_post, send_newsletter, create_campaign, add_lead, search_web, book_appointment, check_order, update_settings, analyze_analytics |
9 | | -- **`agent-execute` edge function**: Unified skill executor with scope validation, approval checks, handler routing (edge/module/db/webhook), and activity logging |
10 | | -- **TypeScript types**: `src/types/agent.ts` with full type coverage |
11 | | - |
12 | | -### Verified |
13 | | -- Direct execution works (analyze_analytics returns real page view data) |
14 | | -- Scope validation works (internal skills blocked from chat agent) |
15 | | -- Approval gating works (send_newsletter returns 202 pending_approval) |
16 | | - |
17 | | -## Phase 2: FlowPilot "Operate" Mode ✅ DONE |
18 | | - |
19 | | -### Completed |
20 | | -- Mode switcher (Operate | Migrate) in CopilotPage header using Tabs |
21 | | -- OperateChat component — chat with quick actions, skill badges, and inline results |
22 | | -- ActivityFeed sidebar — shows recent actions with status, duration, approve button |
23 | | -- `agent-operate` edge function — AI router that picks skills via tool calling, executes via agent-execute, summarizes results |
24 | | -- `useAgentOperate` hook — manages messages, skills, activity, and approval flow |
25 | | - |
26 | | -### TODO (refinement) |
27 | | -- [ ] Refactor copilot-action to load tool definitions from agent_skills table |
28 | | - |
29 | | -## Phase 2.5: Active Memory ✅ DONE |
30 | | - |
31 | | -### Completed |
32 | | -- **agent-operate** loads all `agent_memory` entries into system prompt before each AI call |
33 | | -- **memory_write** built-in tool — FlowPilot saves preferences, facts, context to DB |
34 | | -- **memory_read** built-in tool — FlowPilot searches memory by key/category |
35 | | -- Memory tools handled locally in agent-operate (no round-trip to agent-execute) |
36 | | -- Two new skills registered in `agent_skills` table (memory_write, memory_read) |
37 | | -- FlowPilot proactively saves useful info when it learns something new |
38 | | - |
39 | | -## Phase 3.5: Skill Hub Admin UI ✅ DONE |
40 | | - |
41 | | -### Completed |
42 | | -- **SkillHubPage** (`/admin/skills`) with Skills, Activity, and Objectives (placeholder) tabs |
43 | | -- **SkillCard** — card grid with inline enable/disable toggle, scope/category/handler badges |
44 | | -- **SkillEditorSheet** — full CRUD sheet with JSON tool definition editor (CodeMirror) |
45 | | -- **ActivityTable** — filterable activity log with expand for input/output JSON, approve/reject |
46 | | -- **useSkillHub** hook — CRUD for skills, activity queries, approval mutations |
47 | | -- **Sidebar** — "Skill Hub" added to Main group with Bot icon |
48 | | - |
49 | | -## Phase 3: Public Chat Gets Skills ✅ DONE |
50 | | - |
51 | | -### Completed |
52 | | -- **chat-completion** loads external/both skills from `agent_skills` table as OpenAI-compatible tools |
53 | | -- Skills are routed through `agent-execute` edge function (scope validation, approval gating, activity logging) |
54 | | -- `agentSkillNames` map tracks which tool calls are agent skills vs built-in tools |
55 | | -- System prompt dynamically extended with skill usage instructions |
56 | | -- Works for both OpenAI and local AI providers (when tool calling is supported) |
57 | | -- Approval-gated skills return friendly "pending approval" messages to visitors |
58 | | - |
59 | | -## Phase 4: Automation Layer ✅ DONE |
60 | | - |
61 | | -### Completed |
62 | | -- **agent_automations table** with cron/event/signal trigger types and RLS policies |
63 | | -- **AutomationsPanel** — full CRUD UI with trigger-type badges, skill linking, JSON config editor |
64 | | -- **ObjectivesPanel** — full CRUD UI with status management, progress tracking, constraint/criteria JSON |
65 | | -- **FlowPilot skills**: `create_objective` and `create_automation` registered in agent_skills |
66 | | -- **agent-execute** updated with `module:objectives` and `module:automations` handlers |
67 | | -- **5 seed automations** and **4 seed objectives** for onboarding |
68 | | - |
69 | | -### Runtime |
70 | | -- **`automation-dispatcher` edge function** — reads due cron automations, executes via agent-execute, updates run metadata |
71 | | -- **pg_cron** runs dispatcher every minute via pg_net HTTP POST |
72 | | -- Simple cron parser calculates `next_run_at` for common patterns (*/N, daily, weekly) |
73 | | - |
74 | | -- **Event-trigger dispatch** — `send-webhook` now also checks `agent_automations` with matching `event_name` and executes their skills via `agent-execute`, merging event data into arguments |
75 | | -- **Signal-trigger dispatch** — `signal-dispatcher` edge function evaluates dynamic conditions (score thresholds, status changes, field matches, compound logic) against incoming data |
76 | | - |
77 | | -### Signal Integration Points |
78 | | -- `qualify-lead` → emits `lead_score_updated` and `lead_status_changed` signals |
79 | | -- `send-webhook` → emits every webhook event as a signal (e.g. `form.submitted`, `booking.submitted`) |
80 | | -- Signal conditions supported: `score_threshold`, `count_threshold`, `status_change`, `field_match`, `compound` (all/any) |
81 | | - |
82 | | -## Phase 5: Autonomy Unlocks ✅ DONE |
83 | | - |
84 | | -### Completed |
85 | | -- **Multi-tool loop** — up to 6 iterations, all tool_calls processed in parallel per round |
86 | | -- **Approval re-execution** — approved pending actions auto-re-execute with original args |
87 | | -- **Conversation persistence** — sessions saved to chat_conversations/chat_messages |
88 | | -- **Markdown rendering** — assistant messages rendered with react-markdown |
89 | | -- **Multi-skill result tracking** — Response format supports `skill_results[]` array |
90 | | - |
91 | | -## Phase 6: Agent Self-Improvement ✅ DONE |
92 | | - |
93 | | -### Completed |
94 | | -- **skill_create/update/list/disable** — FlowPilot can manage its own skill registry |
95 | | -- **automation_create/list** — Create and view automations |
96 | | -- **reflect** — Introspection: 7-day activity analysis, error rates, improvement suggestions |
97 | | - |
98 | | -## Phase 7: Weekly Business Digest ✅ DONE |
99 | | - |
100 | | -### Completed |
101 | | -- **`business-digest` edge function** — queries 7-day data across all modules (page views, leads, bookings, orders, blog posts, newsletters, chat conversations, form submissions, subscribers) |
102 | | -- **Structured + markdown output** — metrics table, top pages, hot leads, device/referrer breakdown, actionable callouts |
103 | | -- **`weekly_business_digest` skill** — registered in agent_skills with `edge:business-digest` handler |
104 | | -- **Cron automation** — "Weekly Business Digest" scheduled Monday 9:00 AM (disabled by default for safety) |
105 | | -- **Actionable callouts** — hot leads needing follow-up, pending bookings, unpublished drafts, low sentiment alerts |
106 | | - |
107 | | -## Phase 8: Sales Intelligence Pipeline ✅ DONE |
108 | | - |
109 | | -### Completed |
110 | | -- **`prospect-research` edge function** — Replaces n8n ScoutOut workflows (MBA 1-3). Uses Jina Reader (website scraping), Jina Search (market context), Hunter Domain Search (contact discovery), and AI (OpenAI/Gemini) to generate qualifying Q&A. Upserts to `companies` table and creates `leads` entries. |
111 | | -- **`prospect-fit-analysis` edge function** — Replaces n8n ScoutOut workflow 4 + ScoutIn. Loads company profile from `site_settings`, evaluates fit score (0-100), maps prospect problems to services, generates personalized introduction letter + email subject. Uses Hunter Email Finder for decision-maker lookup. |
112 | | -- **Hunter.io integration** — New `HUNTER_API_KEY` secret, added to `check-secrets`, `useIntegrationStatus`, `useIntegrations` (category: Sales Intelligence), and `configure-secrets.sh`. |
113 | | -- **2 new agent skills** — `prospect_research` (edge:prospect-research) and `prospect_fit_analysis` (edge:prospect-fit-analysis) registered in `agent_skills` table, category: crm, scope: internal. |
114 | | -- **Company Profile** — Uses `site_settings` key `company_profile` to store business context (about_us, services, delivered_value, clients, etc.) for AI prompts. |
115 | | -- **Data flow**: Research → `companies` + `leads` tables; Fit score → `leads.score`; Intro letters → `agent_memory`; Research Q&A → `agent_memory`. |
116 | | - |
117 | | -### External APIs (No n8n dependency) |
118 | | -- **Jina Reader**: `https://r.jina.ai/{url}` — free, no key |
119 | | -- **Jina Search**: `https://s.jina.ai/{query}` — free, no key |
120 | | -- **Hunter Domain Search**: `https://api.hunter.io/v2/domain-search` |
121 | | -- **Hunter Email Finder**: `https://api.hunter.io/v2/email-finder` |
122 | | - |
123 | | -### FlowPilot Usage |
124 | | -``` |
125 | | -"Research Acme Corp" → prospect_research skill |
126 | | -"Analyze fit for Acme Corp and draft an intro" → prospect_fit_analysis skill |
127 | | -"Research Acme Corp and prepare an introduction if fit score > 70" → chained execution |
| 1 | + |
| 2 | + |
| 3 | +# FlowPilot Autonomy Upgrade — Implementation Plan |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +Implement 5 missing OpenClaw features: CMS Schema Awareness, Persistent Heartbeat State, Goal-Aware Execution, Token Tracking, and Atomic Task Checkout. |
| 8 | + |
| 9 | +--- |
| 10 | + |
| 11 | +## 1. Database Migration |
| 12 | + |
| 13 | +Add columns to existing tables: |
| 14 | + |
| 15 | +```sql |
| 16 | +-- Atomic Task Checkout: locking on agent_objectives |
| 17 | +ALTER TABLE agent_objectives ADD COLUMN locked_by text DEFAULT NULL; |
| 18 | +ALTER TABLE agent_objectives ADD COLUMN locked_at timestamptz DEFAULT NULL; |
| 19 | + |
| 20 | +-- Token Tracking: on agent_activity |
| 21 | +ALTER TABLE agent_activity ADD COLUMN token_usage jsonb DEFAULT NULL; |
128 | 22 | ``` |
129 | 23 |
|
130 | | -## Phase 9: Autonomous Wiring ✅ DONE |
| 24 | +No new tables needed — heartbeat state uses existing `agent_memory` with key `heartbeat_state`. |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +## 2. `agent-reason.ts` — New Functions |
| 29 | + |
| 30 | +### 2a. `loadCMSSchema(supabase)` (~40 lines) |
| 31 | +Queries `site_settings` for enabled modules + integrations, returns a structured prompt section: |
| 32 | +- Active modules (blog, newsletter, CRM, ecommerce, booking, resume, kb, webinars, forms, pages, global blocks, media) |
| 33 | +- Block types available (hero, text, image, cta, contact, faq, etc.) |
| 34 | +- Integration status (Stripe, Resend, Firecrawl, Unsplash — from `site_settings.integrations`) |
| 35 | +- Table counts for key modules (pages, blog_posts, leads, products, etc.) |
131 | 36 |
|
132 | | -### Completed |
133 | | -- **Cron scheduling fix** — dispatcher picks up NULL `next_run_at` automations and initializes them |
134 | | -- **DB triggers** — Postgres triggers on `leads`, `blog_posts`, `bookings`, `form_submissions`, `orders` fire events + signals via `pg_net` |
135 | | -- **Objective progress auto-tracking** — `agent-execute` links successful skills to matching objectives |
| 37 | +### 2b. `loadHeartbeatState(supabase)` / `saveHeartbeatState(supabase, state)` |
| 38 | +- Load from `agent_memory` where `key = 'heartbeat_state'` |
| 39 | +- State shape: `{ last_run, objectives_advanced, next_priorities, pending_actions, token_usage, iteration_count }` |
| 40 | +- Save after heartbeat completes |
136 | 41 |
|
137 | | -## Phase 10: Agent Self-Evolution ✅ DONE |
| 42 | +### 2c. Token tracking in reasoning loop |
| 43 | +- After each AI response, extract `usage.prompt_tokens` + `usage.completion_tokens` |
| 44 | +- Accumulate in a `tokenUsage` object |
| 45 | +- Add budget check: default 50,000 tokens per heartbeat session |
| 46 | +- Return token usage in `ReasonResult` |
138 | 47 |
|
139 | | -### Completed |
140 | | -- **SOUL/IDENTITY layer** — persistent personality stored in `agent_memory` (soul: purpose/values/tone/philosophy, identity: name/role/capabilities/boundaries), injected into every system prompt |
141 | | -- **`soul_update` tool** — FlowPilot can evolve its own personality, values, and tone over time |
142 | | -- **`instructions` field on `agent_skills`** — rich markdown knowledge (equivalent to OpenClaw's SKILL.md) injected into prompts when skills load |
143 | | -- **`skill_instruct` tool** — FlowPilot can write knowledge/context/examples into any skill, making it smarter |
144 | | -- **Reflect → auto-persist** — `reflect` tool now auto-saves error learnings and suggestions to `agent_memory` as lessons |
145 | | -- **Skill Hub UI** — Instructions field added to SkillEditorSheet for manual editing |
146 | | -- **Memory filtering** — soul/identity excluded from general memory list to avoid duplication in prompts |
| 48 | +### 2d. `checkoutObjective(supabase, objectiveId)` / `releaseObjective(supabase, objectiveId)` |
| 49 | +- Atomic checkout: `UPDATE agent_objectives SET locked_by='heartbeat', locked_at=now() WHERE id=$1 AND (locked_by IS NULL OR locked_at < now() - interval '30 minutes')` |
| 50 | +- Release: `UPDATE agent_objectives SET locked_by=NULL, locked_at=NULL WHERE id=$1` |
| 51 | +- `loadObjectives` filters out locked objectives |
147 | 52 |
|
148 | | -### OpenClaw/NanoClaw Parity |
149 | | -| Concept | OpenClaw | NanoClaw | FlowPilot | |
150 | | -|---------|----------|----------|-----------| |
151 | | -| Personality | SOUL.md file | SOUL.md + IDENTITY.md | `agent_memory` soul + identity entries | |
152 | | -| Skill knowledge | SKILL.md markdown | .claude/skills/SKILL.md | `instructions` column on `agent_skills` | |
153 | | -| Self-modification | Terminal (code rewrite) | Claude Code rewrite | DB tools (skill_create/update/instruct, soul_update) | |
154 | | -| Heartbeat | HEARTBEAT.md config | task-scheduler.ts | `flowpilot-heartbeat` edge fn + pg_cron | |
155 | | -| Learning loop | Manual | Implicit via Claude | reflect → auto-persist to memory | |
| 53 | +--- |
156 | 54 |
|
157 | | -## Architecture Reference |
| 55 | +## 3. `PromptCompilerInput` Updates |
158 | 56 |
|
| 57 | +Add new field: |
| 58 | +```typescript |
| 59 | +cmsSchemaContext?: string; |
| 60 | +heartbeatState?: string; |
| 61 | +tokenBudget?: number; |
159 | 62 | ``` |
160 | | -skill.handler routing: |
161 | | - edge:function-name → supabase.functions.invoke() |
162 | | - module:name → Direct DB operations (blog, crm, booking, etc.) |
163 | | - db:table → DB read/write (settings, analytics) |
164 | | - webhook:n8n → External webhook POST |
| 63 | + |
| 64 | +`buildSystemPrompt` injects CMS schema after Layer 2 (Soul), and heartbeat state into heartbeat mode context. |
| 65 | + |
| 66 | +--- |
| 67 | + |
| 68 | +## 4. `flowpilot-heartbeat/index.ts` Changes |
| 69 | + |
| 70 | +1. Add `loadCMSSchema` and `loadHeartbeatState` to the parallel context load |
| 71 | +2. Pass `cmsSchemaContext` and `heartbeatState` to `buildSystemPrompt` |
| 72 | +3. After reasoning loop: `saveHeartbeatState` with results |
| 73 | +4. Token tracking: accumulate from AI responses, include in activity log |
| 74 | +5. Wrap objective work with checkout/release |
| 75 | + |
| 76 | +--- |
| 77 | + |
| 78 | +## 5. `agent-execute/index.ts` — Goal-Aware Execution |
| 79 | + |
| 80 | +Accept optional `objective_context` in `ExecuteRequest`: |
| 81 | +```typescript |
| 82 | +objective_context?: { |
| 83 | + goal: string; |
| 84 | + step: string; |
| 85 | + why: string; |
| 86 | +} |
165 | 87 | ``` |
166 | 88 |
|
167 | | -## Key Files |
168 | | -| File | Purpose | |
169 | | -|------|---------| |
170 | | -| `supabase/functions/agent-execute/index.ts` | Unified skill executor + objective tracker | |
171 | | -| `supabase/functions/agent-operate/index.ts` | FlowPilot operate mode with SOUL/IDENTITY | |
172 | | -| `supabase/functions/flowpilot-heartbeat/index.ts` | Autonomous 12h heartbeat loop | |
173 | | -| `supabase/functions/automation-dispatcher/index.ts` | Cron automation executor | |
174 | | -| `supabase/functions/signal-dispatcher/index.ts` | Signal condition evaluator | |
175 | | -| `supabase/functions/prospect-research/index.ts` | Sales research pipeline | |
176 | | -| `supabase/functions/prospect-fit-analysis/index.ts` | Fit scoring + intro drafting | |
177 | | -| `src/types/agent.ts` | TypeScript types for skill engine | |
178 | | -| `src/components/admin/skills/SkillEditorSheet.tsx` | Skill editor with instructions field | |
| 89 | +Log it to `agent_activity.input` so every skill execution carries the "why". Skill handlers can access it for smarter decisions. |
| 90 | + |
| 91 | +Update `handleAdvancePlan` in `agent-reason.ts` to pass objective context when calling `agent-execute`. |
| 92 | + |
| 93 | +--- |
| 94 | + |
| 95 | +## Files Changed |
| 96 | + |
| 97 | +| File | Changes | |
| 98 | +|---|---| |
| 99 | +| DB migration | `locked_by`, `locked_at` on `agent_objectives`; `token_usage` on `agent_activity` | |
| 100 | +| `supabase/functions/_shared/agent-reason.ts` | `loadCMSSchema`, heartbeat state load/save, token tracking, atomic checkout, goal-context in `advance_plan`, updated `PromptCompilerInput` + `buildSystemPrompt` | |
| 101 | +| `supabase/functions/flowpilot-heartbeat/index.ts` | Integrate all 5 features into the heartbeat loop | |
| 102 | +| `supabase/functions/agent-execute/index.ts` | Accept `objective_context`, log it | |
| 103 | +| `src/types/agent.ts` | Add `token_usage`, `locked_by`, `locked_at` to TypeScript types | |
| 104 | + |
| 105 | +Estimated: ~250 lines new code across 3 edge functions + 1 migration. |
| 106 | + |
0 commit comments