Source
## 2. CTR Optimization ### CTRify Campaign Setup (7-Phase System) Derived from ctr-ops skill and chat context. **Account rule:** All Google platforms (GSC, GA) must use `team@merlinomarketing.com`. **Phase sequence:** 1. GSC verification — URL prefix method, HTML tag, paste only the `content="..."` value (not full meta tag) 2. GA property — under "CTRify Sites" parent account, stream name "CTRify Website", www prefix on domain 3. Website design — every site must have unique theme/colors/header/footer; never reuse defaults across sites 4. SEO settings + author — niche-matched AI-generated bio + AI profile image 5. Sitemap submission — use `sitemapindex.xml` over plain `sitemap.xml`; may need 2–3 resubmits 6. Alpha Index Checker — `Sitemap Extractor` → scrape all URLs → enable "Send to Omega Indexer" toggle → create campaign 7. Omega Indexer — receives URLs from Alpha; monitor: In Queue → Processing → Indexed; target 7–15 days **Key analogy:** Alpha = breadcrumbs (Google discovers pages). Omega = noise + activity (Google pays attention and indexes). **Anti-patterns:** - Using domain property in GSC instead of URL prefix - Pasting full `<meta>` tag instead of just the code value - Same default design across multiple CTRify sites - Not enabling "Send to Omega Indexer" in Alpha campaigns - Skipping GA↔GSC linking (organic search data won't appear) - Author bio not matching the site niche ### CTR Signal Strategy (4-Pillar Campaign Model) Derived from ctr-mastery skill. **The cardinal rule:** Quality > quantity. 20 clicks @ 3 min dwell time beats 200 bounced clicks. **Volume formula:** ``` Daily Traffic Target = (Monthly Search Volume × 0.10) / 30 Start at 50% of target; scale 20% weekly if rankings improve ``` | Threshold | Action | |-----------|--------| | < 10% of search volume | Safe, conservative | | 10–20% | Optimal range | | 20–30% | Aggressive, monitor closely | | > 30% | DANGER — reduce immediately | **4 Pillars:** 1. **Branded Traffic (Weeks 1–2):** Brand name, brand + city, brand + phone/reviews/hours/directions. 10–20 clicks/day. Dwell 2–4 minutes, navigate 2–3 internal pages, click-to-call or get directions. 2. **Entity Integration (Weeks 3–4):** Brand + service, brand + industry entity, city + service + brand. 20–40 clicks/day. 3. **Keyword Expansion (Weeks 5–8):** "best [service] in [city]", "[service] near me", "top rated [service] [city]", emergency/affordable variants. 30–75 clicks/day. Vary positions clicked (not always #1). 4. **Authority Domination (Ongoing):** Maintain consistent volume, seasonal adjustments. ### Google Patents — CTR as a Ranking Signal Key patents confirmed from research (2026-01-10): **US8738436B2** (Yahoo/2014) — CTR prediction as a ranking input. 12-feature model including: appearance, attention capture, freshness, branding, position. Documents with similar titles, authors, publishers, and types used to normalize CTR. **US10229166B1** — Long click to short click ratio (LC|C metric). Position-independent measure of dwell time given click-through. Short clicks = dissatisfaction signal. **US20080275882A1 / US7899815B2** — Pogo-sticking benchmarks. Pre-pogosticking (results clicked before) and post-pogosticking (results clicked after) tracked. Used to adjust search algorithm ranking. Average rates measured per search result, per rank position. **US20180011854A1** — User engagement signal types: - Long dwell clicks: >30s general, 2s images, 15s mail - Reformulation-based negative signals - Abandonment-based signals - Normalized + aggregated scores for ranking models **Click fraud detection thresholds (US20080162475A1):** - 15 clicks/minute (singular) triggers alert - 8 clicks/minute (extended) triggers alert - 500 clicks/day threshold - Three fraud types: competitor click abuse, self-clicking, incentivized users **Bot detection signals (US20230316124A1):** Session-based click activity, topology-aware anomaly detection, distinguishing human vs. automated behavioral patterns. ---
ExtractFactmerlin
May 9, 05:25 AM
# Dan Architecture Insights > Extracted from chat backup archive: Agent-Soul-System, Coding-Projects, Claude-Tools, Oliver-Orchestrator, ClaudeClaw > Source: ~300+ chat transcripts spanning 2025-11 through 2026-05 > Extracted: 2026-05-09 ---
ExtractDecisiondanoliver
May 9, 05:25 AM
## 2. Engineering Patterns ### 2.1 /prime Command -- Context Acquisition Before Work **Pattern:** Every project session starts with `/prime` which reads project structure, CLAUDE.md, package.json, brand assets, git context, and outputs a Project Context Summary card. **Why:** Agents without context produce garbage. The prime command is the single most important step -- it loads everything the agent needs before touching code. **How it works:** Reads key files in parallel (git ls-files, README, package.json, brand guide, env examples), identifies tech stack and project type, outputs a formatted reference card. **Status:** Mature. Evolved from basic session recap to full "Context Acquisition + Reasoning Engine." ### 2.2 Quality Gates System **Pattern:** Phase-gated development where each phase has explicit checklist criteria that must pass before advancing. **Why:** Prevents cascading failures. Found in micro-saas-orchestrator and aka-orchestrator but originally missing from the universal Oliver template. **Example gates:** Phase 1 (PRD reviewed, architecture documented, schema designed, API endpoints defined) -> Phase 2 (project bootstrapped, DB tables created, RLS in place, dev environment working). **Status:** Identified as critical missing feature in Jan 2026 template audit. Being retrofitted. ### 2.3 HANDOFF.json for Session Continuity **Pattern:** Structured JSON file capturing exact project state for cross-session handoffs: completed tasks, remaining tasks, blockers, human actions pending, decisions made, uncommitted files, next action. **Why:** Claude Code sessions are ephemeral. Without structured handoffs, context is lost between sessions. HANDOFF.json is machine-readable, enabling automated resume workflows. **Evidence:** ClaudeClaw project uses this extensively. GSD framework's `/gsd:resume-work` command reads HANDOFF.json + .continue-here.md to reconstruct state. **Status:** Active pattern. Complemented by .continue-here.md (human-readable summary) and STATE.md (broader project state). ### 2.4 3-Agent Auto-Scaffold Pipeline **Pattern:** credential-provider -> infrastructure-initializer -> new-project-orchestrator. Three agents that handle new project creation end-to-end. **Why:** Manual project setup (copying .env files, creating Supabase projects, configuring Clerk) is repetitive and error-prone. The pipeline reads from MASTER_API_KEYS_COLLECTION.env and creates project-specific configs automatically. **Evidence:** Built in Feb 2026 session. Oliver says "create a micro-SaaS with Supabase + Clerk + Stripe" and the pipeline handles everything. **Status:** Built. Three agent files + command reference + bootstrapping guide created. ### 2.5 Multi-Access Pattern for Tools **Pattern:** Each tool/skill can be accessed as Agent (persistent, context-retaining), Skill (one-shot command), or Dashboard Tool (form-based UI) depending on the use case. **Why:** Different interaction patterns serve different needs. A blog monitor needs persistent context (agent mode), but a quick RSS check is a one-shot command (skill mode), and feed configuration benefits from a form UI (dashboard mode). **Classification matrix:** Each of 9 core tools was rated for primary/secondary/tertiary access patterns based on: complexity of input, need for visual output, context retention requirements, real-time interaction needs. **Status:** Designed in Feb 2026. Classification matrix created. ### 2.6 Agent-to-Skill Conversion Pattern **Pattern:** Community agent templates (full personality + JSON protocol + inter-agent references) are converted to skill files by: stripping agent personality/greeting instructions, removing JSON communication protocol payloads, removing inter-agent references, adding proper frontmatter (name, description, category, tags), adding "When to Use" / "When NOT to Use" routing sections, preserving all technical content verbatim. **Why:** Community templates are designed as standalone agents. Mike's system needs them as reference skills that other agents can invoke. The conversion preserves knowledge while fitting the ecosystem's access pattern. **Evidence:** Mar 2026 session converting python-pro and golang-pro agent templates to skills. Systematic process applied across multiple conversions. **Status:** Active pattern. Applied to 60+ community templates. ### 2.7 GSD Framework (Get Shit Done) **Pattern:** 12-agent framework with specialized roles: codebase-mapper, debugger, executor, integration-checker, nyquist-auditor, phase-researcher, plan-checker, planner, project-researcher, research-synthesizer, roadmapper, verifier. Each has a corresponding workflow skill. **Why:** Breaks down complex project work into discrete, specialized phases. Each agent has a narrow scope with clear inputs/outputs. **Key insight:** Most gsd-* skill names listed in agent frontmatter do NOT exist as actual skill directories -- they are orphaned skill references. The workflow definitions need to be built. **Status:** Framework defined, partially implemented. Workflow skills are the gap. ### 2.8 Blueprint Engine Pattern **Pattern:** Structured workflow definitions (JSON blueprints) that match incoming tasks to predefined step sequences. Steps can be: agent (spawn a specialist), code (execute a script), or gate (require human approval). **Why:** Moves from free-form "Oliver figures it out" to structured, repeatable execution paths. Blueprint matching enables consistent quality for common task types (build client site, run SEO audit, do keyword research). **How it works:** Task feeder polls for new tasks -> matches against blueprint library -> if match, runs structured blueprint with step executor (retry logic, expertise writeback) -> if no match, falls back to free-form Oliver. **Status:** Deployed. Three starter blueprints (build-client-site, seo-audit, keyword-research). Runner on VPS. ### 2.9 Smart Chunking by File Type for RAG **Pattern:** Different file types require different chunking strategies for effective vector search: - Python/JS: chunk by function/class boundaries - Markdown/transcripts: chunk by headers/sections/paragraphs - YAML configs: keep whole or chunk by top-level keys - JSON: chunk by top-level objects **Why:** Naive chunking (fixed character count) produces garbage fragments. A function split in half is useless. A YAML file split mid-key breaks context. Smart chunking preserves semantic units. **Status:** Designed, partially implemented as part of RAG pipeline. ---
ExtractFactdanolivermerlin
May 9, 05:25 AM
## 3. Agentic Infrastructure ### 3.1 Agent Ecosystem Scale **Inventory (as of Mar 2026):** - 202 agent definition files in ~/.claude/agents/ - 693 skill directories in ~/.claude/skills/ - ~160 agents reference skills; 28 agents spawn subagents - 284 skills referenced by agents (41%); 409 orphaned skills (59%) **Team structure:** - Core Team (Oliver's direct staff): 8 agents - Revenue (Sally's team): 5 agents - Marketing (Cole's team): 15 agents - SEO (Ghost's team): 18 agents - Dev (Merlin's team): 7 agents - GSD Framework: 12 agents - Builder/Specialist: 60+ agents **Key finding:** 59% skill orphan rate. More than half of all skills are not referenced by any agent. This is either dead weight or untapped capability. ### 3.2 ClaudeClaw -- Claude Code on Your Phone **What it is:** Not a chatbot wrapper. Spawns the actual `claude` CLI on Mac/Linux and pipes results back to Telegram. Everything that works in terminal -- skills, tools, context -- works from phone. **Architecture:** TypeScript core (bot.ts, agent.ts, config.ts, dashboard.ts, discord.ts, scheduler.ts, memory.ts, voice.ts). SQLite for state. War room (Python) for multi-agent voice interface. Dashboard on port 3141 via Tailscale Funnel. Discord integration with per-agent bots. **Key components:** Telegram bot, Discord multi-bot, dashboard HTML, scheduler (cron-based), vector memory, Obsidian integration, Slack integration, WhatsApp bridge, voice pipeline. **Status:** Active development. 7/10 setup tasks complete. Dashboard live, 18/19 Discord bots online. ### 3.3 Mission Control + Task Feeder Architecture **Pattern:** Convex backend (real-time dashboard) -> Task Feeder on VPS polls for new tasks -> Blueprint matching -> Blueprint Runner executes structured workflows OR free-form Oliver handles unmatched tasks -> Results written back to Convex. **Components:** - Convex schema: blueprints table (workflow definitions) + blueprintRuns table (execution history) - task-feeder-v3.py: Blueprint-aware poller - blueprint-runner.py: Step executor with agent/code/gate types, retry logic, expertise writeback - push-blueprints.py: Seeds blueprint definitions from JSON **Status:** Deployed on Hostinger VPS. ### 3.4 Memory Architecture Layers **Hierarchy (most to least frequently accessed):** 1. Always-loaded: MEMORY.md (agent memory index), soul files 2. Structured files: RECENT_CONTEXT.md, daily logs 3. Expertise YAMLs: smart-routed by CWD 4. Vector search: on-demand via agent-memory.py 5. Hindsight bank: cross-session recall by tags **Key principle:** Project state lives in the project (CLAUDE.md, .planning/STATE.md). Global = identity only. Never duplicate project state in global memory. ### 3.5 Hooks Infrastructure **Three hook types observed:** - context-guardian.js: Monitors context window usage, prevents overflow - damage-control.js: Prevents destructive operations - provenance-logger.py: JSONL session logging for audit trail **Problem found:** `$CLAUDE_PROJECT_DIR` environment variable doesn't expand properly on Windows, causing hooks to block file operations. Workaround: use Bash tool which has explicit permissions. ### 3.6 FastMCP for Custom MCP Servers **Decision:** FastMCP (Python framework) is the tool for building custom MCP servers. **Why:** Handles all protocol plumbing. Decorate Python functions to create MCP tools. Powers ~70% of MCP servers. 1M+ downloads/day. Versions: v1.0 merged into official SDK, v2.0 standalone with client support, v3.0+ current. **Status:** Available. Used for Context7 browser tools, Supabase, and other MCP integrations. ---
ExtractFeedbackdanoliver
May 9, 05:25 AM
## 4. Anti-Patterns ### 4.1 Oliver Doing Work Instead of Delegating **What happened:** Oliver would write code, create content, run deploys -- doing specialist work instead of orchestrating. **Why it's wrong:** Violates the orchestra model. Oliver should write the brief score, not play every instrument. When Oliver does work, it burns context on tasks a specialist agent could handle better. **Fix:** Hard rule: "If you catch yourself about to DO work instead of DISPATCHING -- STOP." Enforced via soul file. ### 4.2 Embedding Everything in the Template **What happened:** Early Oliver template versions embedded all 48+ agent definitions, all skill references, all standards directly in the template. **Why it's wrong:** Creates maintenance nightmare. Every project has its own stale copy. Updates don't propagate. Bloats context for every session. **Fix:** Thin template + centralized library. Template is bootstrap only; everything else loaded from library at runtime. ### 4.3 Oliver Writing Domain-Specific Workstreams **What happened:** Oliver would write detailed implementation plans for frontend, SEO, content -- domains owned by leads. **Why it's wrong:** "The drummer writes the drumming part." Oliver doesn't have domain expertise. Detailed plans from a generalist are worse than brief scores that let specialists plan their own work. **Fix:** Oliver's plans are BRIEF: objective, constraints, which leads, done-when. No workstreams, no implementation steps, no technical plans. ### 4.4 Supabase pgvector at Scale **What happened:** Considered using existing Supabase pgvector for full D: drive RAG (thousands of files). **Why it's wrong:** pgvector is NOT purpose-built for vector search at scale. SQL-based filtering is slower than native vector DBs. No built-in chunking or hybrid search. Scaling past 500K vectors gets painful. **Fix:** Moved to Pinecone (purpose-built, serverless, scales to millions). Supabase pgvector is fine for small RAG but not for "dump my entire drive." ### 4.5 Orphaned Skill References **What happened:** 59% of skills (409 of 693) have zero agent references. GSD framework agents reference workflow skills that don't exist as actual skill directories. **Why it's wrong:** Dead references waste scanning time, create false expectations, and make the skill ecosystem harder to navigate. **Fix:** Audit and either: (a) wire orphaned skills to appropriate agents, or (b) archive/delete truly unused skills. Build missing GSD workflow skills. ### 4.6 Missing Quality Gates in Universal Template **What happened:** Domain-specific orchestrators (micro-saas, aka, kanban, sugar) had quality gates, status templates, decision trees, execution checklists -- but the universal Oliver template had none of these. **Why it's wrong:** The universal template was "significantly more basic" than specialized orchestrators. Projects using the universal template had no phase gates, no structured status reporting, no complexity assessment framework. **Fix:** Retrofit all missing patterns from specialized orchestrators into the universal template: quality gates, status reporting, task complexity assessment, orchestration patterns library, decision trees, pre/during/post checklists, metrics tracking. ### 4.7 Teams for Everything **What happened:** Before the Apr 2026 revision, Teams were used for tasks that subagents could handle. **Why it's wrong:** Teams are ~5x more expensive. Persistent parallel sessions bill continuously while alive. Inter-teammate SendMessage reloads burn tokens. For most tasks, subagents (spawn, work, die) achieve identical results at a fraction of the cost. **Fix:** Subagents are the default. Teams only when Mike explicitly says "team" or for long-horizon parallel campaigns requiring live peer-to-peer messaging. ### 4.8 $CLAUDE_PROJECT_DIR on Windows **What happened:** Hooks using `$CLAUDE_PROJECT_DIR` failed on Windows because the environment variable doesn't expand in the hook's execution context. **Why it's wrong:** Blocks file operations silently. The hook error is "non-blocking" in theory but actually prevented writes from going through. **Fix:** Use Bash tool (has explicit permissions) or fix the env variable expansion for Windows. This is a known Claude Code platform issue. ---
ExtractDecisiondanolivermerlin
May 9, 05:25 AM
## 5. Key Technical Debt / Open Questions ### 5.1 59% Skill Orphan Rate 409 of 693 skills are unreferenced by any agent. Need a systematic audit: which are valuable but unwired? Which are dead code? Which GSD workflow skills need to be built from scratch? ### 5.2 GSD Workflow Skills Don't Exist 12 GSD agents reference workflow skills (gsd-mapper-workflow, gsd-planner-workflow, etc.) that don't exist as actual skill directories. The framework is defined at the agent level but the execution infrastructure is missing. ### 5.3 RAG Pipeline Completion Pinecone + OpenAI embedding pipeline is designed but not fully deployed. Smart chunking logic per file type needs implementation. Re-indexing on file change needs automation. ### 5.4 ClaudeClaw Remaining Setup 3 of 10 ecosystem tasks remain: fix 4 failing Discord bots (manual portal work), test Skool scraper first run, consolidate Mark Kashef content. Blocked on Discord Developer Portal manual configuration. ### 5.5 Blueprint Library Expansion Only 3 starter blueprints exist (build-client-site, seo-audit, keyword-research). The system can handle any structured workflow -- needs more blueprints for common task types across all team domains. ### 5.6 Hook Platform Compatibility Windows hook execution has env variable issues ($CLAUDE_PROJECT_DIR). Needs cross-platform fix or Windows-specific hook implementations. ### 5.7 Quality Gates Retrofit Universal Oliver template needs quality gates, status templates, complexity assessment, and execution checklists from specialized orchestrators. This was identified in Jan 2026 but implementation status is unclear. ### 5.8 Agent Memory File Consistency Many agents have memory files; many don't. No consistent pattern for which agents get persistent memory and which rely on session context only. Needs a clear rule: when does an agent warrant its own memory file? ### 5.9 Skill Discovery / Registry With 693 skills, agents need a better way to discover relevant skills at runtime. Current approach is frontmatter listing, but 59% orphan rate suggests the registry/discovery mechanism is broken. Consider: searchable skill index, automatic skill matching by task description, or skill tagging with semantic search. ### 5.10 Compounding Engineering Integration The "Every Marketplace" compounding engineering plugin was explored (Nov 2025) but integration status is unclear. Its 17-agent review system and plan/work/review workflow are strong patterns. Question: has this been absorbed into the GSD framework, or is it a separate track?
ExtractPatternpicassofrankie
May 9, 05:25 AM
## 1. Architecture Decisions ### 1.1 Orchestra Model for Agent Orchestration **Decision:** Adopt a composer/conductor/section-leader/musician hierarchy instead of flat agent dispatch. **Why:** Flat dispatch (Oliver routes directly to 50+ specialists) created a routing nightmare -- too many agents to reason about, too many handoff errors. The orchestra model separates concerns: Oliver writes the brief score (what, who, constraints), Carlos conducts (sequencing, dependencies, parallel safety), leads plan their own domain, specialists execute. **Evidence:** Multiple sessions show Mike correcting Oliver for writing overly detailed workstreams ("the drummer writes the drumming part"). Oliver's scope was explicitly narrowed to brief scores: objective, constraints, which leads, done-when. **Status:** Active. Enforced in oliver-soul.md. ### 1.2 Subagents Over Teams as Default **Decision:** Use Claude Code Agent tool (subagents) instead of Teams for all work unless Mike explicitly says "team." **Why:** Teams are ~5x more expensive (persistent parallel sessions billing continuously). Subagents spawn, do work, die. Same memory capability via backup stack. Teams only justified for long-horizon parallel campaigns or peer-to-peer messaging scenarios. **Evidence:** Apr 11 2026 revision in oliver-soul.md. Prior sessions showed unnecessary Team spawning burning tokens on simple tasks. **Status:** Active. Hard rule. ### 1.3 Thin Template + Centralized Library **Decision:** Oliver template is a minimal bootstrap shell; all agents, skills, scripts, standards live in a centralized "Library of Claude Codeia." **Why:** Duplicating 50+ agents and 693+ skills across every project creates maintenance hell. Central library means updates propagate instantly, no duplication, single source of truth. Template just has config pointers + hooks + session memory. **Evidence:** Feb 2026 session where Mike corrected the approach: "the whole point of my template is [not to embed everything]." Template reads library path from config, dynamically loads at runtime. **Status:** Architectural principle. The library lives at `D:\ClaudeDev\0_GITHUB\Tools\Library of Claude Codeia`. ### 1.4 Pinecone + OpenAI Embeddings for Drive-Wide RAG **Decision:** Selected Pinecone (serverless) + OpenAI text-embedding-3-large over Supabase pgvector, ChromaDB, Weaviate, or Qdrant for full D: drive RAG. **Why:** Zero infra management (enough servers to babysit already). Namespace per folder category. Metadata filtering for file-type-specific search. Scales to millions without thinking. Supabase pgvector is fine for small RAG but not purpose-built for "dump my entire drive" scale. ChromaDB is prototyping-grade. Weaviate and Qdrant are strong alternatives but add infra burden. **Evidence:** Mar 2026 Agent-Soul-System session with full comparison matrix. Estimated 2-hour build time for ingestion pipeline. **Status:** Decision made, pipeline partially built. Key insight: smart chunking by file type is the hard part -- code chunks by function boundaries, markdown by headers, YAML keeps whole. ### 1.5 Convex for Mission Control Backend **Decision:** Use Convex (real-time backend) for the mission control / blueprint engine. **Why:** Provides real-time reactivity for dashboard state, structured schema with indexes, HTTP routes with CORS, and serverless execution. Blueprint engine stores structured workflow definitions (blueprints) that match incoming tasks to predefined step sequences. **Evidence:** Mar 2026 session deploying blueprint engine -- Convex schema + functions for blueprints + blueprintRuns tables, 6 HTTP endpoints, Python runner on VPS. **Status:** Deployed. Blueprint-aware task feeder polls Convex, matches incoming tasks to blueprints, runs structured execution or falls back to free-form Oliver. ### 1.6 One Discord Bot Per Agent (Not Channel Routing) **Decision:** Each of Mike's 19 core agents gets its own Discord bot identity, not a single bot routing messages by channel. **Why:** Mike wants each agent to have its own identity, DMs, and presence in Discord. Individual presence matters more than implementation simplicity. **Evidence:** ClaudeClaw setup session, Apr 2026. 18/19 bots brought online; remaining needed Discord Developer Portal manual fixes (Message Content Intent). **Status:** Implemented. Blocked on manual Discord portal configuration for 3 bots. ### 1.7 Tailscale Funnel Over Cloudflare Tunnel **Decision:** Use Tailscale Funnel for permanent dashboard URLs instead of Cloudflare tunnel. **Why:** merlinoai.com is on Namecheap not Cloudflare. Funnel works immediately with no DNS changes. Zero configuration overhead. **Evidence:** ClaudeClaw session, explicit decision logged in HANDOFF.json. **Status:** Active. Dashboard accessible via Tailscale Funnel URL. ### 1.8 Next.js + Supabase + Clerk as Default Stack **Decision:** Default application stack: Next.js (App Router) + Tailwind CSS + ShadCN + Supabase (Postgres + Auth + Storage) + Clerk for auth when needed. **Why:** Standardization across all client and internal projects. Deploys to Vercel. Mike knows the stack. Every agent knows the stack. Reduces context-switching costs. **Evidence:** Multiple project scaffolding sessions (ADHD todo, SEO SaaS suite, GMB tools). Consistent across CLAUDE.md global instructions. **Status:** Active default. Override only when Mike specifies. ---
ExtractPatterndancarlosoliver
May 9, 05:25 AM
## Deployment & DevOps ### Vercel Deployment Checklist 1. `.gitignore` before first commit — never commit `.env.local` 2. `vercel.json` with `{ "framework": "nextjs" }` minimum config 3. `output: 'standalone'` in `next.config.js` for container deployments (remove for standard Vercel) 4. Env vars: set in Vercel dashboard, NOT in `vercel.json` 5. For monorepos: set Root Directory to `apps/web` in Vercel project settings 6. Domains: add all custom domains to `APP_HOSTS` env var or equivalent ### Supabase Migration Execution Preferred methods (in order): 1. `npx supabase db push` — requires Supabase CLI 2. `psql` with direct PostgreSQL connection string (database password required) 3. Supabase Dashboard → SQL Editor → paste combined SQL 4. Node.js with `pg` package + PostgreSQL connection string Never use: Supabase REST API for DDL (doesn't support it), `supabase.rpc()` for raw SQL migrations. ### Environment Variable Pattern ```bash # .env.local (never committed) NEXT_PUBLIC_SUPABASE_URL=https://xxx.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ... SUPABASE_SERVICE_ROLE_KEY=eyJ... NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... ANTHROPIC_API_KEY=sk-ant-... ``` Routing rule: `NEXT_PUBLIC_` prefix for anything accessed client-side. Service role key is server-only. ### VitePress Static Docs Site Pattern Used for SOP sites (ghl-sop, tac-sop, openclaw-docs, skill-agent-reference): ```javascript // docs/.vitepress/config.js export default { title: "Site Name", themeConfig: { nav: [{ text: "Section", link: "/section/" }], sidebar: { "/section/": [{ text: "Topic", link: "/section/topic" }] } } } ``` Build: `npx vitepress build docs` → output to `docs/.vitepress/dist/`. Deploy as static site on Vercel. ---
ExtractDecisionmerlin
May 9, 05:25 AM
## Database & Data Patterns ### Supabase Schema — Core Conventions 1. **UUID primary keys**: `id UUID DEFAULT gen_random_uuid() PRIMARY KEY` 2. **Timestamps**: `created_at TIMESTAMPTZ DEFAULT now()`, `updated_at TIMESTAMPTZ DEFAULT now()` 3. **Auto-update trigger** (apply to every table): ```sql CREATE OR REPLACE FUNCTION update_updated_at() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER tablename_updated_at BEFORE UPDATE ON tablename FOR EACH ROW EXECUTE FUNCTION update_updated_at(); ``` 4. **Soft delete**: Use `deleted_at TIMESTAMPTZ` column + filter queries with `WHERE deleted_at IS NULL` ### Supabase Schema — Self-Referencing Hierarchy ```sql CREATE TABLE folders ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, name TEXT NOT NULL, icon TEXT DEFAULT '📁', color TEXT DEFAULT '#6B7280', description TEXT, parent_id UUID REFERENCES folders(id) ON DELETE CASCADE, sort_order INTEGER DEFAULT 0, created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now() ); CREATE INDEX idx_folders_parent ON folders(parent_id); ``` Design rule: `ON DELETE CASCADE` for folder hierarchy, `ON DELETE SET NULL` for bookmarks (move to Inbox). `sort_order INTEGER DEFAULT 0` — items sort by `created_at` until reordered. `NULL folder_id` = virtual "Inbox". ### Supabase Schema — Full-Text Search ```sql CREATE INDEX idx_bookmarks_search ON bookmarks USING gin( to_tsvector('english', coalesce(title, '') || ' ' || coalesce(url, '') || ' ' || coalesce(description, '')) ); ``` For simple substring search without FTS, use Supabase `.or()` with `ilike`: ```typescript supabase.from("bookmarks").select().or(`title.ilike.%${q}%,url.ilike.%${q}%,tag.ilike.%${q}%`) ``` ### Supabase Schema — Junction Tables ```sql CREATE TABLE bookmark_tags ( bookmark_id UUID REFERENCES bookmarks(id) ON DELETE CASCADE, tag_id UUID REFERENCES tags(id) ON DELETE CASCADE, PRIMARY KEY (bookmark_id, tag_id) ); ``` Initial implementation: use single `tag TEXT` column on the main table. Normalize to junction table only when multi-tag support is needed. ### Supabase RLS Policy Patterns Standard pattern for user-owned data: ```sql -- Read own rows CREATE POLICY "users_read_own" ON tablename FOR SELECT USING (user_id = auth.uid()); -- Write own rows CREATE POLICY "users_write_own" ON tablename FOR INSERT WITH CHECK (user_id = auth.uid()); -- Service role bypass (for webhooks, triggers, server-side ops) CREATE POLICY "service_role_all" ON tablename FOR ALL USING (auth.role() = 'service_role'); ``` Reference data (achievements, public configs): use `FOR SELECT` to authenticated users, `service_role` for writes. ### Supabase Migration Numbering ``` 20260131_001_initial_schema.sql -- core tables + indexes 20260131_002_triggers.sql -- database functions + triggers 20260131_003_rls_policies.sql -- all RLS policies 20260131_004_seed_achievements.sql -- static reference data ``` Never run DDL via Supabase REST API — it doesn't support DDL. Use `pg` client with PostgreSQL connection string, Supabase CLI (`npx supabase db push`), or Dashboard SQL editor. ### Supabase Client Utilities Standard file structure: ``` lib/supabase/ ├── server.ts -- createServerComponentClient (Server Components) ├── client.ts -- createBrowserClient (Client Components) ├── admin.ts -- createClient with service_role key (API routes needing bypass) └── middleware.ts -- createMiddlewareClient (middleware.ts) ``` ### Supabase Embedded Aggregates Count related rows without a separate query: ```typescript const { data } = await supabase .from("folders") .select("*, bookmarks(count)") .order("sort_order", { ascending: true }); // data[0].bookmarks[0].count is the bookmark count for each folder ``` ### Database Schema — ADHD App (8-table Gamification Pattern) Useful reference for user-owned SaaS with gamification: | Table | Purpose | |-------|---------| | users | Clerk user ID → Supabase user mapping | | user_stats | Denormalized score/streak (fast reads) | | tasks | Core user data (soft-deletable) | | achievements | Reference data (public, service-role writes) | | user_achievements | Junction: which achievements user earned | | points_history | Audit trail for point transactions | | streak_history | Daily streak tracking | | notifications | Real-time user alerts | Key functions: `initialize_user_stats()` (trigger on user insert), `handle_task_completion()` (points + streak + notification), `check_and_unlock_achievements()` (post-stats-update trigger). ### Convex Schema Pattern (Mission Control) 11-table real-time dashboard schema: ```typescript // convex/schema.ts pattern defineSchema({ agents: defineTable({ name: v.string(), role: v.string(), emoji: v.string(), status: v.union(v.literal("idle"), v.literal("active"), v.literal("error")), lastHeartbeat: v.optional(v.number()), }).index("by_status", ["status"]), activities: defineTable({ agent: v.string(), action: v.string(), timestamp: v.number(), }).index("by_timestamp", ["timestamp"]), approvals: defineTable({ agent: v.string(), tool: v.string(), status: v.union(v.literal("pending"), v.literal("approved"), v.literal("denied")), decidedBy: v.optional(v.string()), }), }) ``` Gotchas: `v.map()` and `v.set()` not supported. `undefined` is invalid — use `null`. Unbounded `.collect()` loads entire table. `.filter()` without index scans full table. Never call external APIs in mutations — use actions. ### Convex HTTP Endpoints ```typescript // convex/http.ts import { httpRouter } from "convex/server"; const http = httpRouter(); http.route({ path: "/api/ops/heartbeat", method: "POST", handler: httpAction(async (ctx, req) => { // ... return new Response(JSON.stringify({ ok: true })); }), }); export default http; ``` ---
ExtractPatternmerlin
May 9, 05:25 AM
## API & Backend Patterns ### Next.js App Router Route Design Standard 9-route REST pattern for resource management: ``` GET /api/folders -- list all (with embedded counts via select("*, bookmarks(count)")) POST /api/folders -- create GET /api/folders/[id] -- single + related data PATCH /api/folders/[id] -- partial update (only send changed fields) DELETE /api/folders/[id] -- delete PUT /api/folders/reorder -- bulk sort_order update POST /api/bookmarks/bulk -- multi-action: move | delete | star based on `action` field POST /api/import -- bulk insert with 201 on success, 207 (multi-status) on partial failure POST /api/seed -- one-time migration from static data to DB ``` - Use `await params` for dynamic route params in Next.js 15 App Router (params are now async) - All routes use `NextResponse.json()` with explicit HTTP status codes - Bulk endpoints: accept `{ ids: string[], action: string, ...options }` shape - Partial updates: return 400 if no fields are provided - Seed/migration endpoints collect errors without stopping — return 207 multi-status on partial failures ### API Proxy Pattern (Third-Party APIs) Thin proxy routes that forward to external APIs — keep business logic out of the proxy layer: ```typescript // Pattern: wrap external API call, forward query params, throw on error export async function GET(req: NextRequest) { try { const params = req.nextUrl.searchParams; const qs = new URLSearchParams(); if (params.get("accountId")) qs.set("accountId", params.get("accountId")!); if (params.get("startDate")) qs.set("startDate", params.get("startDate")!); const query = qs.toString() ? `?${qs.toString()}` : ""; const data = await externalApiGet(`/endpoint${query}`); return NextResponse.json(data); } catch (e) { return NextResponse.json({ error: (e as Error).message }, { status: 500 }); } } ``` ### External API Client Pattern (TypeScript) Centralized API client with typed error handling: ```typescript const BASE_URL = "https://api.example.com/v1"; function headers() { return { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json", }; } export async function apiGet(path: string) { const res = await fetch(`${BASE_URL}${path}`, { headers: headers() }); if (!res.ok) { const text = await res.text(); throw new Error(`API ${res.status}: ${text}`); } return res.json(); } export async function apiPost(path: string, body?: Record<string, unknown>) { const res = await fetch(`${BASE_URL}${path}`, { method: "POST", headers: headers(), body: body ? JSON.stringify(body) : undefined, }); if (!res.ok) { const text = await res.text(); throw new Error(`API ${res.status}: ${text}`); } return res.json(); } ``` Real example: `src/lib/late.ts` in Brand Media Manager (`LATE_API_KEY` → `BMM_API_KEY` after rebrand). ### Auth Pattern: Clerk + JWT Dual-Auth Brand Media Manager 3-tier pattern: - **Super Admin** (`/admin`): Clerk middleware protects server-side. Use `clerkMiddleware()` with `auth.protect()` only on `/admin` routes. - **Partner** (`/partner/[slug]`): JWT-based. `/api/partner-auth` returns JWT, stored client-side. - **Client** (`/d/[orgSlug]`): JWT-based. `/api/client-auth` returns JWT. - **API routes**: NOT protected by middleware — self-guard with JSON 401 responses (not Clerk HTML 404). Clerk middleware config: ```typescript // src/middleware.ts import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"; const isProtected = createRouteMatcher(["/admin(.*)"]); export default clerkMiddleware((auth, req) => { if (isProtected(req)) auth().protect(); }); export const config = { matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"], }; ``` Public routes: `/sign-in`, `/sign-up`, `/d/*`, `/partner/*`, `/connect/*`, all API routes. ### Parallel API Call Pattern (React) Fire multiple independent requests simultaneously on tab activate: ```typescript // Load data for analytics tab — 4 parallel calls async function loadAnalytics(range: number) { const endDate = new Date().toISOString().split("T")[0]; const startDate = new Date(Date.now() - range * 86400000).toISOString().split("T")[0]; const [daily, posts, bestTimes, followers] = await Promise.all([ fetch(`/api/analytics/daily?startDate=${startDate}&endDate=${endDate}`).then(r => r.json()), fetch("/api/analytics").then(r => r.json()), fetch("/api/analytics/best-time").then(r => r.json()), fetch("/api/analytics/followers").then(r => r.json()), ]); // Handle multiple response formats defensively setDailyMetrics(Array.isArray(daily) ? daily : daily.data ?? daily.metrics ?? []); } ``` Trigger with `useEffect` watching `activeTab` and any relevant range/filter state. ### Rate Limiting Pattern Serverless-safe rate limiter (no in-process state that dies per cold start): - Use a distributed store (Supabase, Redis, KV) or Upstash Rate Limit for serverless - Key by IP: `req.headers.get("x-forwarded-for")` or `req.ip` - For Vercel: `@upstash/ratelimit` + `@upstash/redis` - API key rotation strategy: rotate before expiry, never in-flight ---
ExtractPatternmerlin
May 9, 05:25 AM
# Merlin Dev Insights > Extracted from chat backup archives: Coding-Projects, Web-Dev, Claude-Tools, Side-Projects, Strata-Ai > Date: 2026-05-09 | Author: Merlin (Dev Lead) ---
ExtractFactmerlin
May 9, 05:25 AM
## AI/LLM Integration ### Claude API Client Pattern (TypeScript) ```typescript import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); // Streaming for long responses (prevents timeout) const stream = client.messages.stream({ model: "claude-opus-4-6", max_tokens: 8096, thinking: { type: "adaptive" }, messages: [{ role: "user", content: prompt }], system: systemPrompt, }); const message = await stream.finalMessage(); return message.content[0].type === "text" ? message.content[0].text : ""; ``` ### Multi-Model AI Gateway (Docker Pattern) Unified API gateway routing to multiple models via Docker Compose: - Gateway on port 8000 - Endpoints: `GET /health`, `GET /models`, `POST /chat` - Services: separate containers per model provider (Kimi, Gemini, Codex, Minimax) - Requires Docker Desktop running before startup - Health endpoint check: 2-3 minutes after `docker-compose up -d` for first run ### LLM-Powered Agent Pattern (3 tiers) 1. **Simple ReAct**: Think → Act → Observe loop. Single-domain sequential tasks. 2. **Orchestrator-Worker**: Planner decomposes into subtasks, workers run parallel. 3. **Router**: Classify input → route to specialized sub-agents. Multi-domain apps. All agents need: input validation, max iteration limits, timeouts, human-in-the-loop for sensitive actions, audit logging on every tool call. ### RAG Pipeline Pattern Chunk documents (~500 tokens, 50-token overlap) → embed with Voyage AI `voyage-3` → store in pgvector/Supabase → hybrid search (semantic + BM25 via Reciprocal Rank Fusion) → rerank → augment prompt with top-K context → generate with citations. Always verify context fits token limits before sending. ### Trigger.dev Lead Gen Pattern Scheduled job (cron) with parallel city/lead workers: ```typescript // Runs every Monday 8am // Fans out: 5 cities × 5 leads = 25 leads/run // Each city batch = 1 parallel worker call // Each lead creation = 1 parallel task (25 concurrent) // Deduplication: check before every write — same lead never added twice ``` Required keys: `SERPAPI_KEY`, `CLICKUP_API_TOKEN`, `CLICKUP_LIST_ID`, `TRIGGER_SECRET_KEY`. ### Multi-Platform Social API Integration (LATE/BMM) ```typescript export const PLATFORMS = [ { id: "twitter", name: "X (Twitter)", color: "#000000" }, { id: "instagram", name: "Instagram", color: "#E4405F" }, { id: "facebook", name: "Facebook", color: "#1877F2" }, { id: "linkedin", name: "LinkedIn", color: "#0A66C2" }, { id: "tiktok", name: "TikTok", color: "#000000" }, { id: "youtube", name: "YouTube", color: "#FF0000" }, { id: "pinterest", name: "Pinterest", color: "#BD081C" }, { id: "reddit", name: "Reddit", color: "#FF4500" }, { id: "bluesky", name: "Bluesky", color: "#0085FF" }, { id: "threads", name: "Threads", color: "#000000" }, { id: "googlebusiness", name: "Google Business", color: "#4285F4" }, { id: "telegram", name: "Telegram", color: "#26A5E4" }, { id: "snapchat", name: "Snapchat", color: "#FFFC00" }, ] as const; export type PlatformId = (typeof PLATFORMS)[number]["id"]; ``` ---
ExtractPatternmerlin
May 9, 05:25 AM
## Browser Automation ### Firecrawl API Usage (Python) Direct API for scraping when MCP is unavailable: ```python import requests FIRECRAWL_API_KEY = "fc-..." def scrape_url(url: str) -> dict: response = requests.post( "https://api.firecrawl.dev/v1/scrape", headers={"Authorization": f"Bearer {FIRECRAWL_API_KEY}"}, json={"url": url, "formats": ["markdown"]} ) return response.json() def crawl_site(url: str, limit: int = 50) -> dict: response = requests.post( "https://api.firecrawl.dev/v1/crawl", headers={"Authorization": f"Bearer {FIRECRAWL_API_KEY}"}, json={"url": url, "limit": limit, "formats": ["markdown"]} ) return response.json() ``` Note: Firecrawl v1 API (not v0). MCP version is preferred when available. ### Playwright Quick Reference ```bash # Viewport screenshot npx playwright screenshot <url> out.png # Full-page screenshot npx playwright screenshot --full-page <url> out.png # Reuse auth session npx playwright open --save-storage=auth.json <url> npx playwright open --load-storage=auth.json <url> ``` Browser tool selection: - Local screenshots / repro: Playwright (default) - Annotated snapshots: agent-browser (Rust CLI) - Anti-bot needed: Steel.dev (`STEEL_API_KEY`) - Need video proof: Hyperbrowser (`HYPERBROWSER_API_KEY`) - Just content, no browser: Firecrawl ---
ExtractPatternmerlin
May 9, 05:25 AM
## Anti-Patterns ### Never Run DDL via Supabase REST API Supabase's REST API (`supabase.rpc()`) cannot execute CREATE TABLE, ALTER TABLE, or migration SQL. Attempts result in errors or no-ops. Use `pg` + connection string or Supabase CLI. ### Never Use `output: 'standalone'` for Vercel `output: 'standalone'` in `next.config.js` is for Docker/container deployments. Vercel handles its own output. Leaving it in causes deployment issues. ### Avoid `@clerk/nextjs` Blocking All API Routes Clerk middleware v5+ can silently block API routes that don't have auth. If API routes need to be public, explicitly match and skip them in middleware. API routes should self-guard with JSON 401, not rely on Clerk redirects (which return HTML 404 instead of JSON). ### Avoid Monolithic Dashboard Files A single `page.tsx` of 3,000-6,500 lines duplicating interfaces, constants, and UI patterns across 3 dashboards was identified as a critical refactor target. The refactor order: types → tokens → icons → atoms → layouts. Always build + verify between phases. ### Avoid Silent Pagination Failures in Supabase Supabase default page size is 1,000 rows. Unbounded `.select()` on large tables silently returns only the first 1,000. Always add `.range(0, n-1)` or use server-side pagination. ### Don't Mix `async/await` with `.then()` Chains Inconsistently Parallel fetch calls using `Promise.all([...])` should return consistent data shapes. Always handle multiple response formats defensively: `Array.isArray(data) ? data : data.data ?? data.metrics ?? []`. ### Never Batch Behavioral + Structural Changes Security middleware addition (behavioral change) should be a separate commit from component extraction (structural). Mixed commits make rollback impossible and testing ambiguous. ### Don't Trust `create-next-app` in Existing Directories `create-next-app` fails with errors if the target directory already has files. Create the project structure manually: `package.json` → install deps → create `app/layout.tsx`, `app/page.tsx`, `next.config.ts`, `tsconfig.json`. ---
ExtractPatternmerlin
May 9, 05:25 AM
## Reference Architectures ### Micro SaaS Stack (Clerk + Supabase + Stripe) - **Auth**: Clerk (Org-aware for agencies) - **DB**: Supabase PostgreSQL + RLS - **Payments**: Stripe subscription management - **Real-time**: Supabase Realtime subscriptions - **Background jobs**: Supabase Edge Functions (5 functions: daily checker, analyzers, AI recommender) - **API integrations**: SerpAPI, DataForSEO, TextRazor, Claude, Firecrawl - **Pricing tiers**: Free (1 entity) → Pro ($99/mo) → Enterprise ($499/mo) - **Security**: RLS on all tables, webhook signature validation, rate limiting, Zod input validation ### Multi-Tenant Dashboard (3-Tier) ``` Super Admin ← Clerk auth → /admin Partner ← JWT auth → /partner/[slug] End Client ← JWT auth → /d/[orgSlug] ``` 13 Supabase tables, 27 API routes, 3 separate dashboard files (target: extract to shared components). Live: brandmediamanager.com ### Real-Time Agent Dashboard (Convex) ``` Next.js 15 + Convex + React 19 ├── 11 tables (agents, tasks, activities, metrics, revenue, buildQueue, leads, actionLogs, approvals, costEntries, chat) ├── HTTP endpoints for agent heartbeats + ops APIs ├── Real-time via Convex useQuery reactive subscriptions ├── Stripe revenue sync via Convex action └── Supabase optional (for Ops Kernel) ``` Live: Mission Control template at `D:/Codeland2026/Templates/mission-control-MASTER/`
ExtractArchitecturemerlin
May 9, 05:25 AM
## Frontend Patterns ### Next.js App Router Layout — Two-Panel Dashboard ``` app/layout.tsx -- root layout, fonts, global CSS app/page.tsx -- Server Component, fetches initial data app/components/ -- all UI components Sidebar.tsx -- left panel navigation MainContent.tsx -- right panel data display app/api/ -- API routes (route.ts) app/hooks/ -- SWR data hooks app/lib/ -- utilities, DB clients ``` Server Component fetches initial data → passes to Client Component orchestrator → Client Component manages state and mutations. ### SWR Hook Pattern ```typescript // hooks/useBookmarks.ts import useSWR from "swr"; const fetcher = (url: string) => fetch(url).then(r => r.json()); export function useBookmarks(folderId?: string, searchQuery?: string) { const url = searchQuery ? `/api/search?q=${encodeURIComponent(searchQuery)}` : folderId === "starred" ? "/api/bookmarks?starred=true" : folderId === "inbox" ? "/api/bookmarks?folder_id=inbox" : folderId && folderId !== "all" ? `/api/bookmarks?folder_id=${folderId}` : "/api/bookmarks"; const { data, error, isLoading, mutate } = useSWR(url, fetcher); const createBookmark = async (bookmark: Partial<Bookmark>) => { await fetch("/api/bookmarks", { method: "POST", body: JSON.stringify(bookmark), headers: { "Content-Type": "application/json" } }); mutate(); // revalidate SWR cache }; return { bookmarks: data, error, isLoading, mutate, createBookmark, updateBookmark, deleteBookmark, toggleStar }; } ``` ### Folder Tree Builder (Flat Array → Nested Tree) ```typescript function buildFolderTree(folders: Folder[]): Folder[] { const map = new Map<string, Folder & { children: Folder[] }>(); const roots: (Folder & { children: Folder[] })[] = []; folders.forEach(f => map.set(f.id, { ...f, children: [] })); folders.forEach(f => { const node = map.get(f.id)!; if (f.parent_id && map.has(f.parent_id)) { map.get(f.parent_id)!.children.push(node); } else { roots.push(node); } }); return roots; } ``` ### TypeScript Interface Patterns Keep dashboard interfaces in shared files: ```typescript // src/types/dashboard.ts export interface DailyMetric { date: string; impressions: number; reach: number; likes: number; comments: number; shares: number; saves: number; clicks: number; views: number; posts?: number; platforms?: Record<string, PlatformMetrics>; } export interface BestTimeSlot { day: number; // 0-6 (Sunday-Saturday) hour: number; // 0-23 avgEngagement: number; postCount: number; } ``` Design tokens in `src/components/ui/tokens.ts` — FONT, ACCENT, COLORS, button style factories, CHAR_LIMITS. Extract once, import everywhere. ### Component Extraction Priority (from monolithic dashboard lessons) When a single page.tsx hits 3,000+ lines, extract in this order: 1. **Shared types** — interfaces across dashboards → `src/types/` 2. **Design tokens** — constants, colors, font names → `src/components/ui/tokens.ts` 3. **Icon components** — SVG strings → React components → `src/components/ui/icons.tsx` 4. **Stateless atoms** — StatusBadge, Toast (identical across pages) → `src/components/ui/` 5. **Layout shells** — Sidebar, DetailPanel (props: navItems, activeKey, onSelect) → `src/components/layout/` Rule: build + verify between each phase. Never batch structural refactoring with behavioral changes. ### Vercel Deploy Config ```json // vercel.json { "framework": "nextjs", "buildCommand": "npm run build", "outputDirectory": ".next" } ``` For monorepos (Turborepo): deploy individual apps, not the root. Point Vercel to `apps/web` as the root directory. ---
ExtractPatternmerlin
May 9, 05:25 AM
## Brand Visual Decisions ### Client Color Palettes Documented | Client | Primary | Accent | Light / Background | Notes | |---|---|---|---|---| | MDW Aesthetics Miami | #1A1A1A (Deep Charcoal) | #C9A96E (Champagne Gold) | #F5F0EB (Warm Cream) | Medical spa, luxury tier | | Karma Movers St Pete | #1B4D3E (Forest Green) | #F2A922 (Warm Amber) | — | Brand colors pulled from karmamovers.com | | Flat Fee Movers Sarasota | #1B4D3E (forest green) + orange-to-gold gradient | — | white/mint gradients | Poppins + Montserrat | | Sparkle Cleaning | #00084D (Navy) | #3AAA35 (Green) | #6AE2FF (Cyan) | Sign suite client | ### MDW Aesthetics Font Stack (medical spa — luxury) - Display/Headings: Playfair Display - Body: Inter - Accents / pull quotes: Cormorant Garamond ### Flat Fee / Karma Movers Font Stack (service business — trustworthy) - Headings: Poppins (via next/font/google) - Body: Montserrat - Loaded via Google Fonts CDN in globals.css @import ### Typography Rules - Heading weights: 700 for H1, 600 for H2 - Body: 400 regular, 500 medium - Gradient text on key stat numbers, headlines, hero hooks — use `<span className="gradient-text">` with CSS utility class - Avoid flat colored text on stats — use gradient text instead ### Color Assignment Rules - Primary = CTAs, buttons, links, icons - Accent = hover states, highlights, secondary buttons - Cream/light = section alternate backgrounds - Never use solid color section backgrounds — use `section-gradient`, `section-gradient-reverse`, or `section-dark` with radial overlays ---
ExtractFactpicasso
May 9, 05:25 AM
## Anti-Patterns (Rejected Approaches) ### Absolute Hard Rules — Never Break | Anti-pattern | Correct approach | |---|---| | Unsplash, Pexels, Pixabay, Stocksnap, any stock photo service | Google Gemini AI-gen, client assets, or CSS gradient placeholders | | Google AI API for images | Returns watermarks — use Gemini REST API directly or Nano Banana | | Dark mode or dark-themed sites | Mike only likes white/light theme — never ship dark mode | | Solid color section backgrounds | Use gradients with texture, white, or real images | | Same icon/image for all services on a page | Each service needs a unique, niche-specific image or icon | | Generating images at the end of a build | Generate DURING the build (Phase 4-5), not post-build | | CSS utilities directly in TSX | Named CSS classes in globals.css only (Tailwind 4 pattern) | ### Quality Gates — Site Must Pass Before "Done" Failures found in production that led to quality gate additions: - Colors don't match brand (verify against real site before building) - Logo not rendering (always pull from existing site or CDN) - Generic icons/images for all service pages (must be niche-specific) - Thin content pages (especially service pages) - No GMB map embed (Google Maps iframe via CID — always required) - No social links in footer - Repetitive / similar images across pages - "Ugly blocky colors" — always use gradient-based section design - Prompt missing "NO logos, NO watermarks" → reference images bleed branded elements into B/A images ### Prompt Anti-Patterns - Keyword lists instead of narrative paragraphs - No "no text" instruction when text-free image needed - No "same camera angle" instruction in B/A prompts (produces mismatched views) - Using relative file paths (always use absolute paths in all scripts) ---
ExtractFacteinstein
May 9, 05:25 AM
## Template & Mockup Patterns ### Website Starter Template - Location: `D:\Codeland2026\Templates\website-starter\` - Stack: Next.js App Router, TypeScript, Tailwind CSS 4 - Contains: globals.css base system, layout.tsx, brand.ts shell, FloatingCTA component - All sites copy this template, then customize brand.ts and globals.css ### Mission Control Dashboard Template - Full agency dashboard: agent cards, kanban, activity feed, revenue tracker, lead pipeline - Component styling: color-coded status dots (emerald = active, pulsing), scanline CSS header effect - MetricsBar: 5 metrics with emojis + icons, `tabular-nums` font for number alignment - Glass morphism on header: `backdrop-filter: blur(16px)` - Status pulse animations: agent active states use pulsing color-coded dots ### Self-Contained HTML Gallery Pattern - For design reviews: single HTML file with `@import` for fonts, all CSS inline - 8 unique font families to keep mockup options visually distinct - Used for client design approval flow before building in Next.js ### BeforeAfterSlider Component - React component for drag-to-compare before/after images - Service page placement: between Description section and What's Included section - `beforeAfterMap` TypeScript Record maps service slug → `{ slug: string; title: string }` - Image files: `public/images/before-after/{slug}-before.png` and `-after.png` ### infographicMap Pattern (Blog Posts) ```typescript const infographicMap: Record<string, string> = { 'blog-slug': 'infographic-filename', // ... }; // Render between article content and FAQ: // <Image src={`/images/infographics/${infographicMap[slug]}.png`} width={1080} height={1350} /> ``` ---
ExtractPatternpicassooliver
May 9, 05:25 AM
# Picasso Design Insights — Mined from Chat Archives **Source folders:** Templates-Master, Web-Dev, Creatify-Video **Extracted:** 2026-05-09 **Method:** Chat backup mining across Nov 2025 – Mar 2026 ---
ExtractFactpicasso
May 9, 05:25 AM
## Design Systems ### CSS Variables — Standard Design System Structure All Next.js sites use `src/app/globals.css` with CSS custom properties: ```css :root { /* Colors */ --color-primary: [hex]; --color-primary-dark: [hex]; --color-accent: [hex]; --color-accent-light: [hex]; --color-cream: [hex]; /* or --color-bg-alt */ /* Gradients */ --gradient-dark: linear-gradient(...); --gradient-accent: linear-gradient(...); --gradient-card: linear-gradient(...); /* Shadows */ --shadow-glow-accent: 0 0 20px rgba([accent-rgb], 0.3); --shadow-glow-primary: 0 0 20px rgba([primary-rgb], 0.2); --shadow-sm / --shadow-md / --shadow-lg / --shadow-xl; /* Fonts */ --font-display: [family]; --font-body: [family]; /* Spacing */ --space-xs through --space-3xl; /* Radius */ --radius-sm / --radius-md / --radius-lg / --radius-full; /* Max Widths */ --max-width: 1200px; --max-width-narrow: 768px; --max-width-wide: 1440px; } ``` ### Utility Classes Required in globals.css | Class | Purpose | |---|---| | `.gradient-text` | orange-to-gold gradient on text (for hero headlines, stats) | | `.gradient-text-blue` | light blue gradient text | | `.section-gradient` | white-to-mint section transition | | `.section-gradient-reverse` | mint-to-white section transition | | `.section-dark` | dark gradient section with radial overlay + ambient light | | `.trustbar` | top-of-page trust indicators with shimmer animation | | `.btn-accent` | gradient background + glow shadow on CTA button | | `.icon-card::after` | gradient hover fill overlay | | `.review-card::before` | large decorative quote mark | | `.faq-item::before` | left border animation | | `.site-header` | glass morphism: backdrop-filter blur(16px) | | `.float-phone` | glowPulse keyframe animation on floating phone CTA | | `.deco-dots` / `.deco-ring` / `.deco-line` | decorative SVG-replacement elements | | `.section-divider` | gradient line utility between sections | | `.cta-banner` | with radial gradient `::before` and top line `::after` | ### Homepage Sections — Standard Order 1. Trust bar (top, with shimmer) 2. Hero (gradient overlay, gradient text headline, status badge, deco elements) 3. Stats bar (icon + gradient number + label, on dark gradient bg) 4. Problem/Solution (color-coded cards: red #FEF2F2 problems, green solutions) 5. Process steps (visual connector line between steps, gradient numbered badges) 6. Services grid (gradient icon backgrounds) 7. Before/After showcase 8. Reviews / testimonials (review-card with avatar gradient) 9. Areas served 10. FAQ 11. CTA banner ### Animation Patterns - `@keyframes trustShimmer` — trust bar shimmer - `@keyframes glowPulse` — floating phone button - `@keyframes glowFade` — icon hover glow - `hidden md:block absolute` — desktop-only process connector line ### Single Source of Truth Pattern All client data lives in `src/lib/brand.ts`: - Business name, phone, address, hours, social links - Service list with slugs - Areas served list - Testimonials array - Asset CDN URLs (hero images, logo URL) - CTA config ---
ExtractPatternpicasso
May 9, 05:25 AM
## AI Image Generation ### Tool Stack (Approved — in priority order) 1. **Gemini 3 Pro Image API** (REST) — primary for all AI generation - Endpoint: `https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent` - Model (fast): `gemini-2.5-flash-image` — ~$0.04/image - Model (quality/4K/text): `gemini-3-pro-image-preview` — advanced text rendering, 4K resolution - Model (legacy scripts): `gemini-2.0-flash-exp-image-generation` — used in older mjs scripts - Auth: `x-goog-api-key` header - Always set `responseModalities: ['TEXT', 'IMAGE']` - Always prefix prompts with `"Generate an image: "` in older scripts (workaround for API behavior) 2. **Nano Banana** (Gemini CLI extension) — quick generation via CLI - `gemini --yolo "/generate 'prompt'"` — basic generation - `--count=N` for multiple variants, `--preview` to auto-open - Default model: gemini-2.5-flash-image 3. **Banana Squad** (5-agent PaperBanana pipeline) — highest quality, multi-variant - Architecture: Lead → Research Agent → Prompt Architect → Generator Agent → Critic Agent - Generates 5 variants per request: Faithful, Enhanced, Alt Composition, Style Variation, Bold/Creative - Critic scores each on 4 KPIs: Faithfulness, Conciseness, Readability, Aesthetics (1-10) - Key insight from PaperBanana paper: critique loops improved accuracy from 45.1% to 55%+ - Reference images teach structure better than fine-tuning — always provide references - Style transfer matters more than topic match — generic good structure transfers well 4. **FAL AI** — backup when Gemini credits depleted 5. **Creatify API** — video generation (lipsync), not static images ### NEVER Use - Google AI API (watermarks on output) - Unsplash, Pexels, Pixabay, Stocksnap, or any free stock service ### Gemini API Configuration Patterns ```python # Standard config config = types.GenerateContentConfig( response_modalities=['TEXT', 'IMAGE'], image_config=types.ImageConfig( aspect_ratio="16:9", image_size="2K", ), ) # Vertical social (TikTok/Reels) image_config=types.ImageConfig(aspect_ratio="9:16", image_size="2K") # Instagram feed image_config=types.ImageConfig(aspect_ratio="4:5", image_size="2K") # Square image_config=types.ImageConfig(aspect_ratio="1:1", image_size="2K") ``` Sizes: 1K, 2K, 4K (uppercase K required in API) Aspect ratios supported: 1:1, 4:5, 9:16, 16:9, 21:9 + 8 more ### Prompt Engineering Rules - Write **narrative paragraphs**, never keyword lists - Include: subject, environment, lighting, camera angle, mood, textures, colors, composition - For photorealistic: use photography terms (lens type, depth of field, bokeh) - For text rendering: state exact text, use descriptive font terminology - For products: specify studio lighting, camera specs, surface details - Add "no text" if you don't want rendered text in the image - Add "NO logos, NO watermarks, NO branding" in before/after prompts - Warning: reference images with logos may bleed through even when told not to ### Image Prompt Template — Photorealistic Service Business ``` Create a photorealistic [subject] shot from [camera angle] at [time of day]. [Describe environment: flooring, walls, furniture, props]. [Describe lighting: source direction, quality, shadows]. [Describe mood: colors, feeling, atmosphere]. [Specify state: before = worn/damaged/dirty, after = pristine/clean/new]. [Camera details: 50mm equivalent, shallow depth of field, natural bokeh]. No text, no logos, no watermarks. [Aspect ratio] orientation. ``` ### Before/After Image System Standard templates for B/A image types: **Vertical (U/D — TikTok, IG Reels, YT Shorts):** ``` Create a photorealistic BEFORE and AFTER comparison image with a vertical split layout. TOP HALF — labeled 'BEFORE' in large bold white text: [dirty/damaged state] BOTTOM HALF — labeled 'AFTER' in large bold white text: [clean/repaired state] A thin horizontal dividing line separates the halves. Same subject, same camera angle. 9:16 aspect ratio, photorealistic. NO logos, NO watermarks. ``` **Horizontal (L/R — YouTube, website hero):** ``` Create a photorealistic side-by-side BEFORE and AFTER comparison image. LEFT SIDE — labeled 'BEFORE' in large bold white text: [damaged state] RIGHT SIDE — labeled 'AFTER' in large bold white text: [repaired state] A thin vertical dividing line separates the halves. Same camera angle. 16:9 aspect ratio. NO logos, NO watermarks. ``` **Layout decision tree:** - TikTok / IG Reels / YT Shorts → 9:16 + U/D (up-down) - YouTube standard → 16:9 + L/R (left-right) - Instagram feed → 4:5 + U/D - Website hero → 16:9 + L/R - Facebook feed → 4:5 U/D or 1:1 L/R - Square social → 1:1 + L/R **B/A naming convention:** `{service-slug}-before.png` / `{service-slug}-after.png` Examples: `local-move-livingroom-before.png`, `packing-kitchen-after.png` **BeforeAfterSlider component:** Drag-to-compare React component. Place between Description section and What's Included section on service pages. ### Image Gen Rate Limits - Gemini API 429 rate limit happens in batch runs — build in 60-second retry cooldown - Generate site images DURING the build, not at the end — integrate in Phase 4/5 of site builder - For batch of 6 infographics: expect 1 retry needed (rate limit on ~4th image) ### Site Images Generated Per Project (typical) - 34 images: Karma Movers site - 42 images: Flat Fee Movers site - 8 before/after images: 4 service pairs per site - 6 infographics: 1 per blog post (mapped to specific slugs) ---
ExtractFacteinstein
May 9, 05:25 AM
## Video & Thumbnail Design ### Creatify API — Video Generation - Service: Creatify lipsyncs_v2 API - Auth: `X-API-ID` + `X-API-KEY` headers - API credentials stored in `D:\Ecosystem\secrets\MASTER_API_KEYS.env` - Typical use: one video per site build, placed on the highest-value service page (e.g., long-distance moving) - Avatar used: "Dan" (professional male, Home Improvement category) - Duration: 40 seconds typical - Output size: ~10.7MB MP4 - Integration: HTML5 video element with poster image, placed on specific slug (conditional render) ### Video Embed Pattern (Next.js) ```tsx {slug === 'long-distance-moving' && ( <section> <video controls poster="/images/site/long-distance-hero.webp"> <source src="/videos/long-distance-moving.mp4" type="video/mp4" /> </video> </section> )} ``` ### AI Image Prompt — Cinematic / Video Ad Style The `ai-video-image-prompts` skill defines required elements per image: 1. Character (appearance, demographics, expression) 2. Action/Pose (what they're doing) 3. Shot Type (wide, medium, close-up, over-shoulder, POV, aerial) 4. Environment (location, time of day, weather) 5. Color Palette (warm/cool, brand colors) 6. Motion Hint (for video gen: "hands moving forward", "gentle breeze") Style modifiers by category: - Trade/Service: photorealistic, golden hour, action-oriented - E-commerce: studio lighting, clean background, product-focused - Emotional: soft bokeh, warm tones, close-up face - Before/After: split frame, same angle both sides ---
ExtractFactdanpicasso
May 9, 05:25 AM
## Infographic & Data Visualization ### Infographic Generation via Nano Banana / Gemini - Tool: `scripts/nano-banana.mjs` — customized per project with brand colors - Output format: 1080x1350 vertical (portrait) for blog post embeds - Typical batch: 6 infographics per site (1 per blog post in the first tier) - Infographic map: TypeScript Record linking blog slugs to infographic filenames - Placement: Between article content and FAQ section on blog post pages ### Brand-Colored Infographic Script Variables Update these per project in nano-banana.mjs: ```js const BRAND_PRIMARY = '#1B4D3E'; // forest green (Karma Movers example) const BRAND_DARK = '#143A2F'; const BRAND_ACCENT = '#F2A922'; const BRAND_NAME = 'Karma Movers'; const BRAND_PHONE = '(727) 328-4448'; const BRAND_DOMAIN = 'karmamovers.com'; ``` Always change ALL color references in the prompt body — not just the variables. ### CSS Donut Charts - `conic-gradient` creates convincing donut charts without SVG or JS - Use for simple percentage data visualizations in HTML deliverables ### Excalidraw Diagrams - Architecture and flow diagrams use Excalidraw JSON format - Output: `[topic]-diagram.excalidraw.json` - Import at excalidraw.com via Open > Load from file - Default styling: dark stroke #1e1e1e, light blue nodes #e8f4f8, gray secondary #f0f0f0 - All elements on 20px grid for clean alignment ---
ExtractPatternpicassoeinstein
May 9, 05:25 AM
## Workflow Notes ### Image Generation Pipeline Order (Site Builds) 1. Phase 0: Pull existing site assets + CDN images to `public/images/site/` 2. Phase 4-5 (parallel with content): Generate Gemini site images 3. Phase 6: Map CDN URLs → local paths, verify alt text, zero stock photos 4. Generate before/after pairs: `scripts/generate-before-after.mjs` 5. Generate infographics: `scripts/nano-banana.mjs` 6. Generate Creatify video (optional, one per site, flagship service page) 7. Wire all media into pages before final build ### Banana Squad Usage Pattern - Invoke when: client wants high-quality hero image, OG image, or brand visual — not routine site images - Solo mode works identically to team mode — same quality, no team setup needed - After generation: Critic ranks all 5 variants → user picks → iterate on winner - Shutdown immediately after presenting results (token cost) ### Rate Limit Handling - Gemini 429: wait 60 seconds, retry - Never parallelize more than ~3 concurrent Gemini image requests - Space batch requests with small delay between calls
ExtractDecisionpicassooliver
May 9, 05:25 AM
## OpenClaw Channel Config Reference ### Discord - Required: `DISCORD_BOT_TOKEN` env var OR `channels.discord.token` in config - Intents: Message Content Intent, Server Members Intent - `groupPolicy`: `"open"` | `"allowlist"` | `"disabled"` - `dmPolicy`: `"pairing"` | `"allowlist"` | `"open"` | `"disabled"` - VPS1 handles Discord bots (Mac has Discord disabled) ### Telegram - Setup: `openclaw channels login --channel telegram` from VPS terminal (not from inside Telegram) - BotFather creates bot, generates token - Pairing: bot sends pairing code to new users; `openclaw pairing approve telegram <CODE>` ### WhatsApp - `dmPolicy: "pairing"` — unknown senders get pairing code prompt, expires 1 hour - `allowFrom` array for E.164 phone numbers - If QR code login fails: delete `~/.openclaw/whatsapp-auth` and re-login - Mac uses WhatsApp (VPS1 does not) ### Slack - Socket Mode (default): appToken `xapp-...`, botToken `xoxb-...` - HTTP mode: requires public URL + signingSecret - Required scopes: `app_mentions:read`, `chat:write`, `im:history`, `im:read`, `im:write` - Mac uses Slack ### Signal - Requires `signal-cli` binary - Link via QR code: `signal-cli link -n "openclaw"`, scan with Signal app - `dmPolicy: "pairing"` recommended ---
ExtractFactoliver
May 9, 05:25 AM
## Infrastructure Patterns Summary ### Merlino Agency VPS Architecture ``` Internet | Cloudflare (DNS, Zero Trust Access) | [Tailscale mesh] | | | VPS1 VPS2 VPS3 (Primary) (Secondary) (srv1319524) OpenClaw Secondary Additional Gateway workload workload 18789 | [systemd services] OpenClaw (openclaw.service) agent-deck (agentdeck tmux / needs systemd) cloudflared (cloudflared.service) ``` ### Deployment Decision Tree - New public-facing site → Vercel (zero ops) - Agent/bot infrastructure → VPS + systemd - Persistent background process → systemd (not tmux) - Internal tool / admin UI → Tailscale-only, no public port - Multi-model gateway → Docker Compose on VPS - Need public HTTPS on VPS service → cloudflared tunnel (not open firewall port)
ExtractArchitectureknoxmerlin
May 9, 05:25 AM
# Knox — Infrastructure & Security Insights **Compiled:** 2026-05-09 **Source:** Chat backups from System-Admin, OpenClaw-VPS, ClaudeClaw **Coverage:** Nov 2025 – May 2026 ---
ExtractFactknox
May 9, 05:25 AM
## Secrets & Env Management ### Current State Audit (Feb 2026) **Critical issues found across codebase:** - 15+ files with plain text secrets in deployment scripts (fresh-deploy.js, deploy-env.js, etc.) - docker-compose.yml files with hardcoded API keys (MOONSHOT, GEMINI, OPENAI, MINIMAX) - WEBHOOK_SECRET defined in lbm_webhook_receiver.py but NOT implemented in validation logic - No pre-commit hooks or CI checks for secret scanning - No key rotation mechanisms **Specific exposed keys (all rotated/test keys):** - VERCEL_TOKEN hardcoded in 10+ deployment scripts - CLERK_SECRET_KEY, STRIPE_SECRET_KEY, OPENAI_API_KEY in docker-compose ### VisionClaw Security Finding (2026-04-24) Secrets.kt in Android app committed to git with: - Gemini API key: `AIzaSyAz5Yoap-803-P_fbsrrCWy2l45yvxgcrY` - OpenClaw gateway token: `62dae5c14272d5bbb3c37c1617a72ab865812925c44daf05700616a6a5f0a125` - OpenClaw host IP: `192.168.4.21` All exposed publicly. Must be rotated. ### Proper Patterns **GitHub Secrets (CI/CD):** ```yaml env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} permissions: issues: write contents: read ``` **Docker env_file pattern (correct):** ```yaml services: app: env_file: .env ``` Never inline secrets in docker-compose.yml values. **Application code:** ```javascript const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {...}) ``` Never: `const TOKEN = 'hardcoded-value'` **Two-tier pattern:** - Tier 1: GitHub Secrets → Docker build args → baked into image (build-time, immutable) - Tier 2: Volume-mounted `.env` files for runtime configuration ### Webhook Security Gap `process.env.X || ""` pattern allows empty-string bypass. Found in 3 API routes. Fix: reject when env var is falsy, not just undefined. HMAC signature verification should be implemented for all webhooks — not just defined. ### Master Secrets File Location: `D:\Ecosystem\secrets\MASTER_API_KEYS.env` Proxy configs also at: `D:\Ecosystem\secrets\` ### OpenClaw Gateway Token - Required field, set during initial provisioning - Store in systemd env on VPS, never in openclaw.json - Treat like a root password ---
ExtractFactoliverknox
May 9, 05:25 AM
## Incident Response ### Lockout Recovery (UFW blocking access - 2026-03-12) Root cause: UFW enabled without whitelisting Tailscale interface first. Recovery path: 1. Use VPS provider console (Hostinger panel) to get out-of-band terminal access 2. Disable UFW: `ufw disable` 3. Add Tailscale interface: `ufw allow in on tailscale0` 4. Re-enable: `ufw enable` Prevention: always run interface scan before `ufw enable`. ### Cloudflare Tunnel DNS Conflict Recovery Symptom: `cloudflared tunnel route dns` fails on existing subdomain. Recovery: 1. Cloudflare Dashboard → DNS → delete old A/CNAME record for the subdomain 2. Re-run: `cloudflared tunnel route dns <tunnel-id> <subdomain>` ### Node High Memory (Claude Code / Next.js) Symptom: 3.6GB V8 heap, `/heapdump` warning in status bar. Diagnosis: `tasklist /FI "IMAGENAME eq node.exe"` or PowerShell `Get-Process node` Causes: Large Claude Code context window, Next.js dev server, Convex CLI, memory leak in running service. Fix: `/clear` in Claude Code resets context; restart the process. ### Cloudflare API Auth Error (403) Symptom: Every API call returns `{"code":10000,"message":"Authentication error"}`. Cause: Token scope missing `Access: Apps and Policies → Edit` permission. Fix: Regenerate token in `dash.cloudflare.com/profile/api-tokens` with correct scope. ### Credential Exposure Response 1. Immediately rotate all exposed keys (Stripe, CLERK, VERCEL, OpenClaw tokens) 2. Audit git history for committed secrets (`git log --all --full-history -- "*.env"`) 3. If pushed to public repo: assume compromised, rotate before removing from history ### Python paramiko on Windows paramiko not in PATH after `pip install` — wrong Python env. Fix: ```bash python3 -m pip install paramiko # or find correct pip: which pip3 ``` Windows CP1252 encoding crashes on systemd bullet characters — cosmetic only, service still ran. ---
ExtractEventknoxdan
May 9, 05:25 AM
## SSH & Access Control ### SSH Config Hardening (applied to /etc/ssh/sshd_config) ``` PubkeyAuthentication yes PermitRootLogin no PasswordAuthentication no MaxAuthTries 3 ``` Always backup before editing: `cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak` Validate before restart: `sshd -t && systemctl restart ssh` ### Non-Root User Creation ```bash adduser --disabled-password --gecos "" deploy usermod -aG sudo deploy mkdir -p /home/deploy/.ssh chmod 700 /home/deploy/.ssh cp /root/.ssh/authorized_keys /home/deploy/.ssh/authorized_keys chown -R deploy:deploy /home/deploy/.ssh chmod 600 /home/deploy/.ssh/authorized_keys ``` Critical: verify non-root login works BEFORE disabling root. Never lock root out until non-root SSH is confirmed. ### SSH Key Management - Key type: `ssh-keygen -t ed25519` - Agent key: `oliver-nopass` (ssh-ed25519) — was rejected due to wrong username; server is user-specific - Tailscale key for Mac: `~/.ssh/tailscale_mac` → `merlino@100.127.161.25` - Default key path: `~/.ssh/id_ed25519` ### SSH Aliases (~/.ssh/config) ``` Host vps1 HostName 76.13.111.220 User mike IdentityFile ~/.ssh/id_ed25519 Host vps2 HostName 76.13.120.111 User mike IdentityFile ~/.ssh/id_ed25519 ProxyJump vps1 Host vps3 HostName srv1319524 User root IdentityFile ~/.ssh/id_ed25519 Host mac HostName 100.127.161.25 User merlino IdentityFile ~/.ssh/tailscale_mac ``` Use aliases, never raw IPs. Different users and keys per host. ### Tailscale Networking - VPS1 Tailscale IP: 100.70.90.63 - VPS2 Tailscale IP: 100.123.201.50 - Mac Tailscale IP: 100.127.161.25 - Tailscale is the control plane. Verify identity and 2FA before relying on firewall rules. - Mac drops off Tailscale intermittently — always verify connectivity before SSH operations. - agent-deck web UI runs on Tailscale-only (no public UFW rule): `http://100.70.90.63:8420` ### Cloudflare Tunnel (cloudflared) - Used when public HTTPS endpoint is needed without opening ports - Tunnel ID for openclaw: `d90339c8-87bf-4046-8627-82c828d2464e` - Config path: `/etc/cloudflared/config.yml` pointing to `http://localhost:18789` - Service: systemd unit `cloudflared.service` - Auth flow: `cloudflared tunnel login` generates auth URL → browser authorize → cert.pem lands at `/root/.cloudflared/cert.pem` - DNS conflict pattern: if `ai.imerlino.com` already has A/CNAME, delete old record in Cloudflare before running `cloudflared tunnel route dns` - Python scripts using paramiko hit CP1252 encoding issue with systemd bullet characters — cosmetic only, service still starts ### Cloudflare Zero Trust Access - API token requires: `Account - Access: Apps and Policies → Edit` - Account ID: `d605531f909d2d56ad73f59f2be5d018` - Token missing scope returns 403 with `{"code":10000,"message":"Authentication error"}` ---
ExtractArchitectureknox
May 9, 05:25 AM
## Docker & Containers ### Clawdbot Docker Stack (microservices pattern) Services orchestrated via docker-compose: - Gateway (Port 8000): API router to all model services - Kimi (Port 3001): Moonshot K2.5 - Gemini (Port 3002): Google Gemini 1.5 Pro - Codex (Port 3003): OpenAI GPT-4 Turbo - Minimax (Port 3004): Minimax - Prometheus (Port 9090): Metrics Key patterns from this stack: - Docker network isolation: `clawdbot-network` with `driver: bridge` - Health checks implemented on all services - Service profiles for selective startup - CRITICAL FLAW: API keys hardcoded in docker-compose.yml (MOONSHOT_API_KEY, GOOGLE_GEMINI_API_KEY, etc.) — should use `env_file:` directive with a `.env` file ### Claude-Docker Dockerfile Patterns Non-root user with matching host UID/GID: ```dockerfile RUN adduser --uid ${HOST_UID} --gid ${HOST_GID} --disabled-password claude-user COPY .env /app/.env COPY .claude.json /tmp/.claude.json RUN cp /tmp/.claude.json /home/claude-user/.claude.json && \ chown -R claude-user /home/claude-user USER claude-user ``` Issue: `.env` baked into image at build time — acceptable for throwaway containers, not for persistent services. ### Mission Control (abhi1693/openclaw-mission-control) Enterprise control plane stack: FastAPI + Postgres + Redis + RQ workers + Next.js - Auth: Local bearer token or Clerk JWT - Deployment: Docker Compose on VPS - Connects to OpenClaw gateway via WebSocket - Provides approval workflows, audit logs, org/board/task management - vs. custom Convex template (push model, Vercel): the GitHub repo is a pull-based enterprise ops layer ### Container Security Checklist - Non-root user with specific UID/GID - No secrets in ENV vars or build layers (use `env_file:` + `.env`) - Read-only root filesystem where possible - Capabilities dropped: `--cap-drop ALL --cap-add NET_BIND_SERVICE` - Health checks on all services - Disable inter-container communication where not needed: `icc: false` in daemon.json - daemon.json hardening: `no-new-privileges`, `userns-remap`, log rotation, `live-restore` ---
ExtractArchitectureoliver
May 9, 05:25 AM
## Deployment Infrastructure ### OpenClaw VPS Deployment (Hostinger auto-deploy path) 1. Hostinger VPS plan → Deploy → OpenClaw auto-installs via Docker Manager 2. On config screen: save the OpenClaw Gateway Token (treat like a password) 3. Add API keys via Hostinger's Visual Editor → Environment section (not in config JSON) 4. Redeploy after env var changes 5. Dashboard access via tunnel or SSH port forward (never public) ### OpenClaw Manual Install (npm path) ```bash export PATH="$HOME/.npm-global/bin:$PATH" mkdir -p ~/.npm-global npm config set prefix ~/.npm-global curl -fsSL https://opencloud.ai/install.sh -o /tmp/oc_install.sh bash /tmp/oc_install.sh ``` Post-install: configure provider, model, gateway port. ### OpenClaw Config (openclaw.json) Key Fields ```json5 { gateway: { bind: "lan", // not "0.0.0.0" — use alias port: 18789, token: "..." // never in config; load from env: OPENCLAW_GATEWAY_TOKEN }, models: [ { id: "model-id", name: "Display Name", input: 0.0, contextWindow: 200000, maxTokens: 8096 } // array of objects — NOT just strings ], contextPruning: { cacheTtl: 3600, softTrim: true, hardClear: false }, compaction: { memoryFlush: true } } ``` - `openclaw doctor` auto-migrates config: strips comments, converts bind aliases, converts model strings to objects - Run `openclaw doctor` to validate after manual edits - `description` field on agent list items is invalid (gets stripped) - `isolatedSession` in heartbeat defaults is invalid (gets stripped) ### OpenClaw Systemd Service (VPS1) Environment vars injected via systemd unit: - `OPENCLAW_GATEWAY_TOKEN` - `OPENAI_API_KEY` - `DISCORD_BOT_TOKEN` Never store tokens in openclaw.json — always via env. ### PM2 / tmux for Process Persistence - tmux survives SSH disconnect; does NOT survive reboots - For reboot persistence: use systemd unit (see above) - agent-deck runs in tmux session "agentdeck" on VPS1 - Multi-agent setup: `tmux new-session -s agents` + `CLAUDE_CODE_AGENT_TEAMS=1` env var ### OpenClaw Dashboard Access Pattern - Never expose gateway port publicly in UFW - Access via SSH tunnel: `ssh -L 3000:localhost:3000 user@server` - Or via Tailscale-only access - Cloudflare tunnel as alternative for permanent HTTPS endpoint ### Vercel Deployment - CLI deploy auto-names project from directory name (e.g. "site") - Not linked to GitHub for auto-redeploy unless `vercel link` is run - Env vars must be set separately via `vercel env add` or Vercel dashboard - Default deployment URL pattern: `project-name.vercel.app` ---
ExtractFactknox
May 9, 05:25 AM
## Security Hardening ### Linux VPS Hardening Procedure (full sequence) 1. Test SSH as root first 2. Run apt update/upgrade 3. Harden sshd_config (key-only, no root, max 3 retries) 4. Create non-root user with sudo 5. Copy authorized_keys to non-root user 6. Restart SSH 7. VERIFY non-root login works in a new terminal 8. Install fail2ban 9. DETECT Tailscale/cloudflared/ngrok tunnels BEFORE enabling UFW 10. Configure UFW deny-all with whitelist for needed ports + tunnel interfaces 11. Enable unattended-upgrades 12. Run port audit: `ss -tlnp` ### UFW Critical Lesson (2026-03-12) ALWAYS detect and whitelist Tailscale/cloudflared/ngrok BEFORE enabling UFW. Skipping this locked the operator out of mission-control (VPS1). Pre-UFW scan: `ss -tlnp`, `ip route`, `ip link show` to identify all active interfaces. Whitelist: `ufw allow in on tailscale0` before `ufw enable`. ### fail2ban Required on any internet-facing SSH. SSH brute force is the #1 attack vector. ```bash apt install fail2ban -y systemctl enable fail2ban systemctl start fail2ban ``` ### unattended-upgrades ```bash apt install unattended-upgrades -y dpkg-reconfigure --priority=low unattended-upgrades ``` ### Windows Firewall Hardening - Block all inbound by default, enable all profiles - Add inbound rules only for specific ports with known processes - Port check: `netstat -ano | findstr :<port>` - Kill by PID: `taskkill /PID <pid> /F` - PowerShell rule: `New-NetFirewallRule -DisplayName "Name" -Direction Inbound -Port 3000 -Protocol TCP -Action Allow` ### Port Audit Tools - Linux: `ss -tlnp` - Windows: TCPView (Sysinternals), CurrPorts (NirSoft), `resmon` Network tab - Windows port forwarding (WSL2): `netsh interface portproxy add v4tov4 ...` ---
ExtractDecisionknox
May 9, 05:25 AM
## VPS Configuration ### Server Inventory | Host | IP (Public) | IP (Tailscale) | Provider | Spec | SSH User | |------|------------|----------------|----------|------|----------| | VPS1 (primary) | 76.13.111.220 | 100.70.90.63 | Hostinger KVM2 | Ubuntu 24.04 | mike@ | | VPS2 (secondary) | 76.13.120.111 | 100.123.201.50 | Hostinger | Ubuntu | hop via VPS1 | | VPS3 | srv1319524 (alias) | — | Hostinger | — | root@ | | Proxmox (legacy) | 173.214.163.190 | — | — | — | root@ | ### Hostinger VPS Initial Setup Pattern 1. Provision KVM2 plan (2 vCPU, 4GB RAM recommended minimum) 2. Select Ubuntu 24.04 as OS 3. Enable IPv4 during provisioning; add SSH public key in the UI before first boot 4. Skip auto-backups unless heavy workload planned 5. Choose server region closest to primary user base 6. After provisioning: SSH as root, immediately run hardening (see Security Hardening section) ### OS Baseline - Ubuntu 24.04 LTS on all production VPS - System update on every fresh deploy: `apt-get update -y && apt-get upgrade -y` - Non-root service account (`deploy` or `mike`) created with sudo rights - Root SSH login disabled after initial setup ### Node.js / npm on VPS - npm global bin path: `~/.npm-global/bin` - Set prefix: `npm config set prefix ~/.npm-global` - Add to PATH in `~/.bashrc`: `export PATH="$HOME/.npm-global/bin:$PATH"` ---
ExtractFactknoxdan
May 9, 05:25 AM
## Anti-Patterns | Pattern | Problem | Fix | |---------|---------|-----| | Root SSH left enabled after setup | Lateral movement if any key is compromised | `PermitRootLogin no` + verify non-root SSH works first | | UFW enabled without tunnel whitelist | Locks out Tailscale/cloudflare/SSH access | Scan interfaces, whitelist before `ufw enable` | | API keys in docker-compose.yml values | Keys visible in `docker inspect`, logs, CI output | Use `env_file:` with `.env` | | Hardcoded secrets in deploy scripts | Keys in version control, visible to all contributors | Use env vars, GitHub Secrets, or Vault | | `process.env.X \|\| ""` for auth | Empty string passes auth checks | Reject when env var is falsy | | WEBHOOK_SECRET defined but not checked | Webhook endpoint is effectively open | Implement HMAC verification or reject | | Running OpenClaw on daily-use machine | Broad permissions conflict with personal use | Isolated VPS only | | Opening gateway port in public firewall | Gateway exposed to internet | SSH tunnel or Tailscale-only | | Reusing same API key across agent instances | Breach of one exposes all | One key per agent instance | | tmux for reboot persistence | tmux dies on reboot | systemd service unit | | Single API key without credit limits | Runaway scripts exhaust budget | Create secondary key with /day credit limit | | Committing Secrets.kt / .env with real keys | Public exposure | Gitignore + pre-commit secret scan hook | | Credentials in CLAUDE.md | Plaintext passwords in version control | Happened in domain-portfolio-dashboard; never again | ---
ExtractFactknoxcarlos
May 9, 05:25 AM
## SEO Strategies & Frameworks ### AKA Content Framework Every content piece is classified as Authority, Knowledge, or Answer: - **Authority** — builds brand entity signals; schema-heavy, linked to About/team pages - **Knowledge** — topical depth content; service guides, how-to, comparison pages - **Answer** — PAA-format posts that directly answer searcher questions Internal linking strategy follows AKA hierarchy: Authority pages link down, Answer pages link up to Knowledge and service pages. ### Trio Prompt / Content Optimization System A 3-phase quality-gate content production system: - Quality Gate 0: Pre-writing approval (competitive analysis, gap ID, angle selection) - Quality Gate 1: Blueprint approval (minimum 80/100 score) - Quality Gate 2: Content review (minimum 55/70) - Quality Gate 3: Final publication approval (minimum 85/100) Each gate includes SERP competitive analysis, intent mapping, and AKA architecture integration before writing begins. Prevents publishing substandard content at scale. ### Stealth Code / 6 Core Local SEO Elements (Elias & Mike framework) 1. Schema markup 2. Semantic triples 3. PAAs (People Also Ask) 4. Landmarks hacking 5. AI Share Buttons 6. Social URLs Advanced tactics layer: DAS (Domain Authority Stacking), GMB Sniper, GMB Blast, RYB, Cloud Stacking, Wiki Wizard, RD-100. ### Content Tier Structure (Moving/Service Niche) Blog content organized into tiers to prevent topical confusion: - Tier 1: Core informational (what, how, why) - Tier 2: Service + location combination posts - Tier 3: Cost and comparison posts (buyer decision stage) - Tier 4: Specialty and niche service posts - Tier 5: Trust and education posts - Tier 6: Hyper-local/neighborhood-specific posts This tiering ensures complete topical coverage without cannibalization. ### Results-Over-Rankings Philosophy Rankings are a vanity metric. Conversion and revenue attribution is the actual goal. - GMB posts drive real-time conversions; often more valuable than blog posts for immediate lead generation - UTM tags on ALL GMB links (non-negotiable) — Google Search Console is the authoritative attribution source, not Google Analytics - Track GMB traffic in GSC separately from organic to prove GMB ROI ### Single Variable Testing Test one SEO element at a time. Document exact inputs and outputs per client. Build case studies from results. Never push multiple changes simultaneously when trying to measure what moved. ### The Cost Principle (Koray/Topical Authority) The cost of ranking a website CANNOT be higher than the cost of NOT ranking it. Topical authority is measured by the depth of semantic coverage relative to competitors, not by domain authority scores. Quality threshold must exceed current top-ranking pages. ---
ExtractArchitectureeinsteinmerlin
May 9, 05:25 AM
## Link Building & Authority ### Tiered Link Building Structure Tier 1 (main target) → Tier 2 → Tier 3 - For every outbound link, 100 inbound links (RD-100 principle, used with SEO Neo) - Expired domains used for faster authority buildup - Press release stacking: multiple releases linking to different assets - Domain Authority Stacking (DAS): build authority before targeting main keywords ### Link Sources (Mastermind-Validated) - Press releases: Press Advantage, Link Daddy - Podcast syndication: SoundCloud, Podbean, Spotify, iHeartRadio (authority from audio platforms) - Wiki stacking techniques - Topical relevance requirement: links from relevant industry sites perform better than generic directories - Citation strategy: NAP consistency across all platforms before link building begins - Turbo Subdomains: fast-ranking subdomain stacking tactic ### PBN Pattern (2016 SEO-Rockstars) Carolyn Holzman's Weebly 301 Redirect strategy: using Web 2.0 properties with 301 redirects to consolidate link equity. 22,000+ backlinks documented in case study. High risk but established methodology in conference record. Use with caution under current Penguin/SpamBrain environment. ---
ExtractPatterneinsteinmerlin
May 9, 05:25 AM
## Entity & Semantic SEO ### Entity Authority Hierarchy For local businesses, entity signals stack in this order: 1. GMB listing (primary entity anchor) 2. Schema.org Organization/LocalBusiness with sameAs links 3. NAP consistency across all platforms 4. Author entities (Person schema) on all content pages 5. Wikidata entry (if sufficient notability) 6. Wikipedia/external editorial mentions ### Credential Siloing Problem (Common Client Failure) The most common E-E-A-T failure observed: authority credentials exist on About pages but are completely absent from blog posts and service pages where they would actually influence rankings. Example: Client had ARCSI membership, Chamber of Commerce membership, Herald-Tribune feature, 15,000+ homes cleaned, OSHA certification, 80% referral rate — ALL present only on About page, ZERO presence in blog posts. Fix: Inject authority signals into every page via: - Author bylines with credentials - Sidebar trust badges - In-line mentions ("As ARCSI members, we follow...") - Schema `hasCredential` and `memberOf` properties ### Branded Methodology = Entity Signal Competitors who create a branded methodology name (e.g., "Detail-Clean Rotation System" by The Cleaning Authority) gain an entity-level signal that generic companies lack. Proprietary named systems create: - Topical authority markers - Quotable, citable concepts - Differentiation from commodity competitors Actionable: Help clients name their process (e.g., "The Flat Fee 50-Point Clean," "Gulf Coast Cleaning Protocol"). ### Schema Stacking Priority (Confirmed through audits) 1. Q&A Schema — results in hours 2. FAQ Schema — 1-3 days 3. LocalBusiness + @ID — days-weeks (always combined with AggregateRating) 4. AggregateRating — 1-2 weeks (third-party ratings only, never self-hosted) 5. VideoObject — 1-2 weeks (on video-embedded pages) @ID field is mandatory — link to GMB URL or Knowledge Graph ID on every local schema deployment. ### AI/LLM Schema Discoverability Checklist From schema-stack skill + observed best practices: - JSON-LD format only (not Microdata or RDFa) - Server-rendered in HTML source (not JS-injected — Google Dec 2025 guidance) - `knowsAbout` property on Organization schema (3+ topics = GEO signal) - `sameAs` links to 5+ platforms (Wikidata first, then Wikipedia, LinkedIn, YouTube, social) - `speakable` property on articles (CSS selectors pointing to summary/key takeaways) - `@id` cross-referencing between schemas on same page via `@graph` ---
ExtractArchitectureeinsteinmerlin
May 9, 05:25 AM
## AI/LLM Visibility ### AI Visibility Monitoring Framework Test these query patterns regularly across ChatGPT, Perplexity, Gemini, Claude: - "[service] in [city]" — are you mentioned? - "best [service] company in [city]" — are you recommended? - "how much does [service] cost in [city]" — is your data cited? - "[business name]" — what does AI know about you? ### Benchmark: Roto-Rooter Sarasota Temperature Zero audit score: 17/30 AI visibility. Finding: national brand entity strong, local franchise entity weak. Franchises inherit national entity but not local signals. Each franchise location needs its own local entity strategy layered on top of the national brand. ### AI Citation Optimization (Per Engine) | Engine | Prefers | |--------|---------| | Google AI Overviews | Direct answer in first 150 words, data in tables, FAQ schema, JSON-LD | | ChatGPT Browse | Direct answers, original first-party data, citation density (1+ per 500 words) | | Perplexity | Original data, precise stats with units (5+ per piece), expert credentials | | Claude | Evidence-backed claims, reasoning transparency, limitations acknowledged | ### Quotable Statement Templates (AI Citation Targets) AI systems cite standalone, fact-first statements. Templates: - Statistic: "According to [Source], [metric] is [value] as of [year]." - Definition: "[Term] is [category] that [primary function], [key characteristic]." (25-50 words) - Comparison: "Unlike [A], [B] [specific difference], which means [implication]." - Process: "To [achieve goal], [step 1], then [step 2], then [step 3]. Total time: [estimate]." Rule: no qualifiers (avoid "typically," "usually," "can"). Start with number or direct fact. ### AI Visibility Gap (Market Opportunity) - 84% of brands are blind to their AI visibility status - Only 42% overlap between ChatGPT/Perplexity/Claude/Gemini recommendations - LLM visitors worth 4.4x traditional organic traffic - Gartner prediction: 50% search traffic shift to AI by 2028 - ChatGPT queries up 212% in 18 months (as of Jan 2026 data) ### Author Persona for AI Machines SEED + Growth methodology for creating AI-recognizable author entities: - SEED: Gather 60 sub-topics, famous publications, certifications, historical figures, statistics, regulatory associations in the niche - Growth: Create robust author persona with industry origin story, education, named certifications, career positions at niche-specific businesses, named publications, personal interests connecting to expertise Key rules: - Never mention "writing background" (positions as practitioner, not writer) - Always include business phone + website in CTAs - Write with professional informative tone with wit - Keep content focused on what matters to buyers ### llms.txt Must be hand-crafted, not plugin-generated. Must match schema authority signals. Plugin-generated llms.txt files lack the precision needed for AI crawler alignment. ---
ExtractPatterneinsteinmerlin
May 9, 05:25 AM
## Tools & Technologies (Validated in Client Work) ### Primary Stack (Einstein + Team) - **DataForSEO** — keyword/SERP data, batch to 1000/request at $0.075/task - **Google Search Console** — primary traffic attribution (not Analytics) - **SEO Neo** — proprietary tool for GMB management, content, link building - **LowFruits / SEO Minion** — PAA identification - **LibreCrawl** — self-hosted on-page crawler at `D:/ClaudeDev/00_GITHUB/LibreCrawl/` - **Google NLP API** — sentiment analysis on text and reviews - **Google Vision AI** — image entity/sentiment analysis - **Local Viking / Local Brand Manager** — GMB management for SABs ### Content Production Stack - Pictory — AI video creation - Haygen — AI video avatar creation - Notebook LLM — create podcasts from written content - N8N — blog-to-podcast automation - Canva — template-based image/design creation ### Tracking & Attribution - UTM tags (mandatory on all GMB links) - Google Search Console (primary source) - CallRail or equivalent for phone lead attribution - Single variable testing methodology --- *Compiled from SEO-Research (Jan-Feb 2026), SEO-Rockstars (Dec 2025), Local-SEO-Sites (Nov 2025 - Feb 2026) chat archives.* *File count scanned: 150+ chat backup files across 3 source folders.*
ExtractPatterneinsteinmerlin
May 9, 05:25 AM
## Anti-Patterns ### SEO Approaches That Fail or Were Abandoned **Generic stock photos** Never use Unsplash, Pexels, Pixabay on any client site. Google Vision AI reads image content. Stock photos provide zero entity signal and may actually dilute brand entity recognition. **Google Analytics as primary attribution source** Mike Merlino: "Google Analytics is a piece of shit. Search Console is where the real data is." GA has sampling issues and misattributes GMB traffic. GSC is the authoritative source for traffic attribution. **Third-party SEO tool dependency (Ahrefs, SEMrush)** For small/medium local SEO, these tools are largely redundant when using DataForSEO for keyword/SERP data + GSC for performance. Reduces cost without significant capability loss. **Content spinning** Ongoing debate in mastermind community. Risk: Google's SpamBrain can detect spin patterns. When used, must be at very high quality threshold — minor rewordings, not content farm output. **Vague GMB categories** Generic categories (e.g., "Contractor" instead of "Roofing Contractor") fail to capture specific service intent queries. Always use the most specific category available. **GMB post frequency: more than once/week** Overposting (more than 1x/week) risks triggering GMB penalties/suspensions. 2-3 posts/week for active campaigns is the upper safe limit. **Building on rented platforms without backup** Web 2.0 properties (Weebly, Tumblr, etc.) used as tier-2 link sources can be deindexed or shut down. Primary site authority should never be dependent on third-party platform availability. **Keyword difficulty as primary ranking signal** The Koray methodology explicitly rejects keyword difficulty. The real question: can you exceed the quality threshold set by current top-ranking pages? Quality threshold > competition score. **Misaligned internal linking anchor text** Generic "click here" or "learn more" anchors provide zero topical signal. "Get Your Free Quote" appearing on 8+ pages as the only internal anchor text is an over-reliance failure. Every anchor should describe the destination content using target keywords. **Credential siloing** Authority signals on About pages not present anywhere else on the site. This is the single most common and damaging E-E-A-T failure pattern in local service site audits. Every credential must appear in blog posts, service pages, and schema markup — not just the About page. **JS-injected schema** Schema markup injected via JavaScript faces delayed processing (Google Dec 2025 guidance). Schema must be server-rendered in HTML source for immediate AI and Google crawler access. **Data inconsistency across pages** Review counts, insurance amounts, years in business, homes served — any factual claim that differs between pages destroys the Trust dimension of E-E-A-T. Single source of truth pattern required in codebase (brand config file). ---
ExtractFacteinsteinmerlincarlos
May 9, 05:25 AM
## Keyword & Content Patterns ### PAA = Customer Phone Call Questions PAA questions are the exact questions customers ask when they call. Answer them everywhere: - GMB posts (EVENT or OFFER type, link to blog PAA posts) - Service pages (FAQ section with JSON-LD) - Standalone blog posts (one post per PAA cluster) - Social media posts PAA identification tools: LowFruits, SEO Minion, Keywords Everywhere. Geographic modifiers added to PAA questions for local relevance. ### Keyword Clustering Pattern (Service Niche) Separate content buckets by service type AND location to avoid topical entity confusion. Do not mix services within content. Each cluster gets its own content silo. Example for house cleaning: - "recurring house cleaning sarasota" cluster → dedicated service page + 2-3 blog posts + PAA posts + FAQs - "deep cleaning sarasota" cluster → separate silo, same structure - "move-out cleaning sarasota" cluster → separate silo ### Service + Neighborhood Content Pattern [Service] + [Neighborhood] keyword combinations outperform generic [Service] + [City]: - Start with core city, expand to top neighborhoods (Siesta Key, Lakewood Ranch, Longboat Key) - Separate service pages per neighborhood OR embedded neighborhood sections on service pages - Include specific street names, landmarks, local context (not just city name) ### Competitive Keyword Minimum (Sarasota House Cleaning) Observed competitor tier structure: - Tier 1: National franchise brands (Molly Maid, Maids, Merry Maids, MaidPro) — national brand authority - Tier 2: Local established brands (Star Maid Service, The Cleaning Authority) — 5-10+ years tenure, branded methodology - Tier 3: Independent locals (Flat Fee, Green World, Maid Brigade) — competing on transparency, specialization **Gaps in competitive landscape (actionable):** - Limited comprehensive cleaning frequency benefit guides - Minimal neighborhood history/local context content - Lack of "maintenance between visits" detailed guides - Insufficient team/expertise content for trust-building ### Content Length from SERP Blog word count must match #1 ranking + 10-20%. Do not use arbitrary floors (no "minimum 1,500 words"). Audit the top-ranking page and match or slightly exceed. ---
ExtractArchitectureeinsteinmerlin
May 9, 05:25 AM
## E-E-A-T Optimization Tactics ### Dimensional Scoring (1-10 per dimension, audited against real pages) **Experience (E1) — most commonly underscored** - Generic first-person phrases ("In our experience...") score 5/10 — not enough - Specific job narratives with client names, locations, outcomes score 8-9/10 - Seasonal/operational observations from direct experience score 8-9/10 - Before/after photo documentation (real, not stock) score 8+/10 **Expertise (E2)** - Accurate pricing aligned to market data scores 6/10 - Edge cases addressed (what the service WON'T do, when to refer) scores 8+/10 - Industry certifications referenced + woven into content (not just About page) scores 9/10 - Technical distinction between methodologies scores 8-9/10 **Authoritativeness (A) — second most commonly underscored** - No individual author byline = automatic 4/10 cap - Author bio with credentials + external citations = 7-8/10 - Industry press mentions + association memberships actively referenced = 9/10 **Trustworthiness (T) — typically the best-performing dimension** - Full contact info + schema = 7/10 - Transparent limitations disclosed ("We don't do X") = +1 point - Third-party review citations embedded in content = +1 point - Data consistency across all pages is critical — conflicting review counts or insurance amounts actively damage T score ### Data Consistency Rule Any factual claim (review count, insurance amount, years in business, homes cleaned) must be identical across ALL pages. Inconsistencies are a direct Trust signal failure. Example failure found: "200 reviews" on blog vs "500+ reviews" on About page; "$1M insurance" on About vs "$2M insurance" on blog. Either reading of the inconsistency damages credibility. ### Honest Limitations = Trust Multiplier The single strongest trust signal available to service businesses: explicitly stating what you DON'T do or what's outside your scope. - "We don't perform licensed mold remediation. If we discover mold beyond surface level, we refer you to a certified remediation specialist." - "Hoarding situations require a specialized initial assessment before flat-fee pricing." - "Heavily stained carpets or damaged drywall go beyond cleaning scope." These statements signal professional boundaries, not weakness. ### Competitor E-E-A-T Benchmarks (House Cleaning, Sarasota) What top-ranking competitors do that most clients don't: - **Named customer testimonials with locations** (Jane, Sarasota — not just "5 stars") - **Proprietary branded methodology** (The Cleaning Authority's Detail-Clean Rotation System) - **National franchise brand authority** (Molly Maid — decades of operational history) - **Location-specific cost breakdowns with cited data sources** ### E-E-A-T to Score Lift (Observed Estimates) Implementing Tier 1 + Tier 2 E-E-A-T improvements elevates content from ~5.5/10 to ~7.5-8/10 composite score, which is on par with or above top-ranking local service competitors in mid-size markets. ---
ExtractArchitectureeinsteinmerlin
May 9, 05:25 AM
# Einstein SEO Insights **Extracted:** 2026-05-09 **Sources:** SEO-Research, SEO-Rockstars, Local-SEO-Sites chat archives **Agent:** Einstein (SEO Lead) ---
ExtractEventeinstein
May 9, 05:25 AM
## Local SEO Tactics ### GMB (Google My Business) Core Rules From Green Grid Goblins mastermind (Mike Merlino principles): - **UTM tags on ALL GMB links** — non-negotiable; allows attribution in GSC - **Post type:** EVENT or OFFER (not "What's New") - **Post duration:** 1 year for evergreen content - **Post title:** Keyword-first (not brand name first) - **Post frequency:** 2-3 posts/week for large clients, 1/week minimum; never more than once/week to avoid penalties - **GMB Blast:** Weekly blasts for visibility maintenance (Neo tool) - **Category specificity:** Avoid vague categories; use specific service names - **Link destination:** Link GMB posts to blog articles answering PAAs, not just homepage ### Image Optimization for Local SEO Every image that hits the internet must contain: - Business logo - NAP (Name, Address, Phone) - Website URL - Primary keyword - Service type Google Vision AI and Google NLP API read images. Image sentiment analysis affects rankings. Use before/after imagery for conversions. ### Service Area Business Strategy - Separate strategies for storefront vs. service area businesses - Multi-location GMB management at scale requires tools (Local Viking, Local Brand Manager, Yext) - Proximity vs. targeting balance: SABs must optimize for service area keywords, not just proximity - 220+ GMBs in client database = significant local pack coverage ### Local Site Architecture - One page per major service per location - Location landing pages (LLPs) = service + location combination - Homepage links TO location pages (not the reverse) - H1s on local pages should link to GMB CIDs (confirmed pattern across roofing sites) - Pricing visibility on service pages: SEO + UX benefit - Avoid entity pollution: don't mix service topics on single pages ### Content Minimum for Local Presence Minimum viable content footprint for local ranking: - 4 service pages - 5 GEO posts - 16 PAA posts = 25 total pages to establish topical presence in a local market ### Review Strategy Reviews with keywords + photos > links for local pack rankings. - Ask customers to mention specific services by name - Encourage location mentions in reviews - Request outcome-focused language ("Got my full deposit back") - Respond to every review mentioning specialties and location - Sentiment in reviews is analyzed by Google — positive sentiment signals outweigh raw entity optimization for local pack ### Local Schema Pattern (Confirmed Through Build Audits) Technically sound local schema for Flat Fee Movers Sarasota (100% passing score): - `robots.ts` with correct Allow/Disallow - Sitemap with 84+ URLs, correct priorities (Homepage 1.0, Services 0.9, Blog 0.8, Areas 0.7, Utility 0.6) - Every page: unique meta title <60 chars, unique meta description <155 chars, primary keyword + location in H1 - `metadataBase` configured in root layout - Canonical + OG + Twitter card on every page - Single H1 per page, no skipped heading levels ---
ExtractPatterneinsteinmerlin
May 9, 05:25 AM
## Internal Linking Strategy ### Common Internal Linking Failures (Documented Through Audits) **Failure pattern:** Sites rely almost entirely on header/footer navigation for all internal linking. Body content interlinking is nearly absent. For a 16-page site, approximately 85-100 strategic internal links were missing across: - Blog-to-blog: 0 of 12-18 needed - Service-to-blog: 0 of 6-9 needed - Homepage-to-blog: 0 of 2-3 needed - Pricing-to-service: 0 of 3 needed - FAQ-to-service/blog: 0 of 4-6 needed - Area-to-service: 0 of 36+ needed ### Link Depth Rule All blog posts should be max depth 2 from homepage. Key money pages (service pages, pricing) should be depth 1. About and FAQ (if orphaned) must be linked from at least one body content page. ### Orphan Page Pattern High-priority pages most commonly orphaned: - About page (only reachable via header nav) - FAQ page (only reachable via header nav) Fix: Homepage should body-link to both, service pages should link to relevant FAQ answers. ### Anchor Text Best Practices (Observed Failures) - Over-reliance on generic CTAs: "Get Your Free Quote" appearing on 8+ pages as the only anchor text to /contact - "View Pricing" used identically across all service cards (should be descriptive and varied) - Keyword-rich descriptive anchor text is far more effective: "recurring cleaning sarasota" vs. "View Service" - Older blog posts that only have breadcrumb anchors (Home > Blog) have zero SEO-valuable link equity ---
ExtractPatternfrankiepicasso
May 9, 05:25 AM
## Video and Multimedia Content ### Ranking Reels System (Validated Production Pipeline) Source: VidForge / Ranking Reels project, March 2026 **Three-mode architecture:** 1. **Creatify API (MODE 1)** — Batch video generation via REST API. Cost: 20-40 credits/video (aurora_v1_fast). Best for: automation and scale. 2. **Creatify Browser (MODE 2)** — Template design, brand kit setup. Must precede API use. Templates created here are reusable via API. 3. **FFmpeg Post-Processing (MODE 3)** — Stamp per-client branding onto any video. Cost: $0. Primary branding approach at scale. **Validated production flow:** 1. Design template in Creatify editor (one-time per template) 2. Generate raw video via API 3. Stamp client logo + CTA bar via FFmpeg branding pipeline **Visual style selection guide:** | Template | Best for | |----------|---------| | FullScreenTemplate | Service businesses with no product to showcase | | AvatarBubbleTemplate | Commentary, reviews, explainers | | SideBySideTemplate | Before/after, comparisons | | GreenScreenEffectTemplate | Talking head, avatar-presenter | | QuickTransitionTemplate | High-energy social ads | | ScribbleTemplate | Educational, tutorials | **Critical technical note:** Pre-resize all images to 1080x1920 before API upload to eliminate blur bars. This was the unlock for MDW Aesthetics v3 production quality (AvatarBubbleTemplate issue). **Video script framework (Chad Michael Framework):** - Hooks get 40-60% of writing time - 30-second scripts optimized for 9x16 vertical - Platform target: Instagram and TikTok primary **Pricing model for Ranking Reels as a service:** | Package | Videos | Cost to produce | Client price | Margin | |---------|--------|----------------|-------------|--------| | Single Video | 1 | ~$1-4 | $250-$500 | 97%+ | | SEO Batch | 5 | ~$5-20 | $1,500-$2,500 | 97%+ | | Full Assault | 15/mo | ~$15-60 | $3,500-$5,000 | 97%+ | ### Video Content Topics (PAA-Driven) Proven PAA-to-video pipeline: take the top-scoring PAA questions from local service research, generate scripts answering each question (30s), produce via Creatify, and publish as SEO-named social videos. 16 videos produced for MDW Aesthetics Miami using 4 PAA topics × 4 versions in a single production day. ### Video SEO / Schema - Video schema recommended alongside every video asset - Title: exact PAA question match - Description: 40-60 word quick answer block (matches featured snippet target in written content) ---
ExtractArchitectureshakespeare
May 9, 05:24 AM
## Social Media Patterns ### Platform-Specific Formats (Validated in Production) **X/Twitter:** - Under 280 characters - Include direct blog URL - 2-3 brand hashtags per post - Punchy, direct copy with a value hook - No fluff openers **Facebook:** - 150-250 words - Open with a question hook to drive engagement - Conversational tone, practical advice - Include blog link + phone number - No hook line (per brand voice standard) - Short paragraphs, no em dashes, emojis inline (not as decorative bullets) - End with CTA **Instagram:** - 150-200 word captions for image posts - No links in caption — "link in bio" only - 15 hashtags: blend brand tags with discovery tags - Format with line breaks for readability in-app - Lists work better than flowing prose **LinkedIn:** - Professional/industry insight angle - 100-200 words - Include direct blog link - Position the brand as a knowledgeable industry voice - Use data, bullet points, structured formatting - Avoid casual language that works on other platforms ### Social Post Production Standard - 40 posts total across 4 platforms per blog batch (10 per platform) - Quick reference tracking table included in the social posts file - All URLs verified against production site before file delivery - Zero AI stop words - Consistent brand details embedded in every post (not just sometimes) ### PAA Infographic Pipeline - 6 infographics per client batch is the documented production unit - Source questions: PAA data for primary service area keywords - Output format: 9x16 for social, titled by PAA question - Naming convention: `[topic-slug]-[city]` (e.g., `movers-cost-st-petersburg`) - Rate limiting: 3-second pauses between API calls; fall back to 60-second pauses after any 429 error - Gemini API used for infographic generation (10 req/min quota on flash model) ---
ExtractPatternshakespeare
May 9, 05:24 AM
## Brand Voice and Tone ### Donald Atkinson Voice (Buy the Hour Movers Brooklyn) - Direct, practical, Brooklyn-born authority - First-person "I" voice throughout - Never corporate speak ("leverage," "utilize," "synergy," "holistic," "seamless") - Specific brand details embedded consistently: $55-$75/hr, 2-mover crew, 5.0 stars, 58+ Google reviews - Every social post carries the same voice — no drift across platforms ### Mike Merlino Voice Profile - Direct, no fluff, ADHD-friendly formatting - Bullets over paragraphs - Expert in local SEO, call tracking, agent automation - Speed + directness valued over completeness - Teaches through Green Grid Goblins mastermind ### AI Stop Words — BANNED LIST Never use in any client content: delve, crucial, navigate, multifaceted, embark, "in today's digital landscape," leverage, utilize, synergy, robust, holistic, seamless, cutting-edge, best-in-class, game-changing, comprehensive (when hollow), "it's important to note that," "furthermore," "moreover" ### Humanization Principles (from Content Humanizer skill) - Show don't tell: "Teams cut reporting from 4 hours to 40 minutes" beats "our product is effective" - One-paragraph minimum of opinion or personal observation per 500 words - Sentence burstiness: short punchy sentences + longer contextual ones in alternation - Every bullet must complete a task or give a specific insight — no orphan bullets naming a concept - Mini-stories: 2-3 per article minimum with named character + situation + outcome - CTA placement: soft mid-article, hard at close - Paragraph max: 4 sentences ### Local Voice Rules - Always reference actual neighborhoods by name, not just the city - Florida-specific environmental factors belong in cleaning and home service content: humidity, mold, salt air, hard water, snowbird season - Specific seasonal patterns signal practitioner knowledge: "March through May is when we see the worst pollen buildup on lanais" ---
ExtractPatternshakespeare
May 9, 05:24 AM

Showing 51100 of 115