# Project Memory & Architecture

## Core
- Stack: React+Vite SPA, Tiptap, Supabase. React Query, React Router.
- Module bootstrap har circuit breaker: `bootstrap_runs`-tabell + `get_bootstrap_health()`. 3+ consecutive failures → degraded → kräver `force=true`. Se mem://architecture/bootstrap-circuit-breaker.
- Coding Agent alters code. FlowPilot alters DB/content via skills. FlowPilot cannot create React components.
- Tool Calls: Always use explicit `tool_calls`. Never simulate actions in text.
- Unified Reasoning: `chat-completion` is the sole reasoning loop. FlowChat (always-on chat surface) drives it reactively; FlowPilot (opt-in agent layer ON TOP of FlowChat) drives the same loop autonomously via heartbeat. No shadow brains in edge functions.
- Content Models: `content_json` for Pages is blocks array. For Blogs is Tiptap doc (`type: 'doc'`).
- Strict CRUD Limits: `DEDICATED_SKILL_TABLES` block generic CRUD. Use domain skills (e.g., `place_order`).
- Module states are controlled by flags: `requiresFlowPilot`, `enhancedByFlowPilot`, `requiresAI`.
- MCP = platform-level. Skills seedas alltid med mcp_exposed=true när modul aktiveras, oberoende av FlowPilot. Skills-UI bor i /admin/developer.
- FlowChat (web-CLI shell) gateas ALDRIG på flowpilot.enabled. När FP off: bara FP-interna built-ins (objectives/soul/reflect/planning/automations-exec) strippas; skills + platform built-ins (memory/workflows/a2a/skill-packs) körs vidare. FlowPilot = optional operator-lager med samma access som extern OpenClaw + interna vertikal-perks (in-process tools, lägre latens, heartbeat). Se mem://architecture/flowpilot-as-optional-operator-layer.
- Bridge polling: ALLTID `since_id=0` vid "läs bridge" — hela tråden, inte bara nyaste. Visa råa msgs vid tvekan.
- Modules = real Odoo-style SaaS (real tables/RLS/admin-UI) that expose skills for agent operation. NEVER build sandbox/simulation/demo modes.
- Skill schemas MUST use FLAT top-level (OpenAI gpt-4.1 strict-mode kräver det). Per-action required → `x-action-required` extension, INTE `allOf/if-then`. Guardrail-test enforcer detta.
- Generic CRUD i agent-execute har TABLE_ALIASES + COLUMN_ALIASES per tabell + ACTION_ALIASES (list_pending etc) — externa agenter får använda naturliga namn.
- MCP exposure invariants: (1) `mcp_exposed=true → enabled=true` (inga orphan tools); (2) utility-skills (migrate_url, scrape_url, search_web, extract_pdf_text, sla_check, process_signal, competitor_monitor) är ALLTID MCP-exposade så externa operatörer kan köra t.ex. site-migration utan FlowPilot. Operator-internal skills (a2a_*, openclaw_*, dispatch_claw_mission) förblir ej-MCP. Se mem://architecture/mcp-exposure-invariants.
- Agent Contract Integrity = paraplyprincip: 4 lager (arg-mapping, NOT NULL-täckning, värde-domän/enums, modul-registrering) MÅSTE vara guardrail-verifierade innan en skill släpps. Se mem://architecture/agent-contract-integrity.
- Composite MCP groups (`marketing`, `sales`, `operations`) i mcp-server expanderar till flera kategorier — externa department-claws frågar `?groups=marketing` och får hela toolkit:en utan att veta intern taxonomi. Mall för fler departments finns. Se mem://federation/marketing-claw-department-pattern.
- Lifecycle events: 11 DB-triggers emittar `invoice.paid`, `quote.accepted`, `contract.signed`, `subscription.created/churned`, `shipment.dispatched`, `return.received`, `expense.approved`, `application.received`, `employee.hired`, `ticket.resolved`. Se mem://architecture/lifecycle-event-emitters.
- NEVER point a skill at `rpc:mcp_X(args jsonb)` wrapper — agent-execute spreader `p_*`-fält, inte ett jsonb-objekt → tyst trasig skill. Repointa till underliggande `p_*`-arg RPC. Se mem://constraints/no-mcp-jsonb-wrapper-rpcs.
- Module Tiers: varje modul har tier (core/standard/extended/experimental). `core` har hard budget = 8 (idag: 4), höjs bara via RFC. Vitest-guardrail enforcer. Bias nya verticals till `extended`. Se mem://architecture/module-tiers.
- Process + Maturity on Manifest: varje `defineModule()` deklarerar `processes: ProcessId[]` + `maturity: 'L1'..'L5'` från `src/lib/processes.ts`. Guardrail enforcar + kräver att varje ProcessId har ≥1 ägare. Driver `/admin/process-coverage`. Se mem://architecture/process-and-maturity-on-manifest.

## Claws & Integration
- Claws (external agents) use `?openai_safe=true` for compatibility. Schemas are now flat in the DB, so this flag is a no-op but remains supported for existing configurations.
- MCP best practices: Anthropic Sept 2025-guidance applied (self-describing tools, `Use when:`/`NOT for:`, composite high-impact tools). Gaps: ingen `response_format`-enum än, ingen per-tool token-budget. Se mem://architecture/anthropic-mcp-best-practices-applied.
- MCP-dokumentation: docs/architecture/mcp-overview.md är operational reference (endpoints, auth, schemas, gruppfiltrering, caching). docs/architecture/mcp-as-platform.md = arkitektoniskt varför.
- [Pricelist Auto-Resolution on Lines](mem://ecommerce/pricelist-auto-resolution-on-lines) — Sprint 3: invoice/quote-rader med product_id resolvas automatiskt via resolve_pricelist_price RPC, locked rows och free-text-rader passerar oförändrat
- [AI Task Hub](mem://architecture/ai-task-hub) — Sprint 4: konsoliderar tunna AI-edge-functions till en `ai-task` router. Nya AI-arbetsflöden = TaskSpec i `tasks.ts`, INTE ny edge function.
- [ai-task pattern (Klass 2a)](mem://architecture/ai-task-pattern) — `ai-task:<name>` skills = SaaS-lager AI-endpoints (load → tool-call → apply). Inte FlowPilot-beroende; kallbara från admin-UI/automations(platform)/MCP/FlowPilot. 5 tasks: score_candidate, analyze_receipt, qualify_lead_summary, generate_blog_from_webinar, ticket_triage.
- [New Module Checklist](mem://development/new-module-checklist) — Mandatory PR-checklista. Scaffolding via `bun run new:module <id>`. Konsoliderad doc: `docs/contributing/building-a-module.md`.
- [Copilot Builder as MCP Skill](mem://federation/copilot-builder-as-mcp-skill) — `copilot-action` (admin /admin/copilot site-builder loop) exponerad som MCP-skill `build_site_step`. En implementation, två konsumenter (admin UI + externa claws).
- [Webinar Lifecycle & Lead Loop](mem://erp/webinar-lifecycle-and-lead-loop) — 5 lifecycle RPCs + anonymous `register_for_webinar` with auto lead-link/score boost, `webinar_tick` cron every 5 min, all skills MCP-exposed, admin UI has lifecycle buttons + attendance toggle, events `webinar.{published,live,completed,cancelled,registered,attended}`.
- [Webinar Reminders & Content Loop](mem://erp/webinar-reminders-and-content-loop) — Sprint 5: `webinar_reminder_tick` cron (15 min) emits `webinar.reminder.{confirm,t24,t1,post}` events deduped via marker columns; ai-task `generate_blog_from_webinar` inserts blog draft from completed webinar; MCP composite groups expanded with `support`, `success`, `finance`.
- [Department Claws Playbooks](mem://federation/department-claws-playbooks) — 6 playbooks (marketing/sales/support/success/finance/operations) i docs/agents/ med end-to-end JSON-RPC-loop, approval gating per skill, och vad som INTE exponeras. En claw per department per site.
- [MCP Invariant CI Guardrail](mem://architecture/mcp-invariant-ci-guardrail) — `scripts/verify-mcp-invariant.ts` + `npm run verify:mcp-invariant`, körs i mcp-regression-workflowet (kräver SUPABASE_SERVICE_ROLE_KEY secret). Blockerar deploy vid orphan tools (mcp_exposed=true + enabled=false).
- [Global Search ⌘K](mem://features/global-search-cmd-k) — `global_search()` RPC + GIN-index över 16 entiteter (companies/leads/deals/orders/invoices/quotes/tickets/contracts/documents/kb/products/pages/blog/employees/vendors/projects). Admin-only, websearch_to_tsquery + ILIKE-fallback. AdminSearchCommand (⌘K) listar ranked hits ovanför nav. MCP-skill `global_search` (handler `rpc:mcp_global_search`) seedad via `developerModule.skillSeeds`.
- [Multi-Currency & FX](mem://erp/multi-currency-fx) — L1 currency/exchange_rate-kolumner på invoices/quotes/orders/POs/expenses (default SEK, rate 1). L2 `currencies`+`exchange_rates`-tabeller, `fetch-fx-rates` edge pollar ECB XML dagligen 06:15 UTC, cross-rates derivas om base ≠ EUR. L3 `revalue_open_balances` bokar FX-delta på öppna AR/AP till BAS 3960/7960. UI `/admin/currencies`. 3 MCP-skills.
- [Fixed Assets & Depreciation](mem://erp/fixed-assets-depreciation) — `fixed_assets` + `depreciation_entries` (UNIQUE per asset+period). 3 RPCs MCP-exposed: register (Dt 1210/Cr 1930), run_monthly_depreciation (Dt 7832/Cr 1219, idempotent, auto fully_depreciated), dispose (gain 3970/loss 7970). Cron 1:a 03:00 UTC. UI `/admin/fixed-assets`. Modul `fixedAssets`.
- [Payroll SE MVP](mem://erp/payroll-se-mvp) — `payroll_runs` (period UNIQUE) + `payroll_lines` + `payroll_components`. 5 RPCs MCP-exposed via `mcp_*`: create_payroll_run (snapshot+compute), approve_payroll_run (Dt 7210+7510 / Cr 2710+2731+2890), mark_payroll_paid (Dt 2890/Cr 1930), list_runs, list_lines. SE defaults: 31.42% social fee, 30% PAYE schablon (per-employee override). Modul `payroll`, UI `/admin/payroll`. AGI/FORA/pension/multi-locale = nästa iter.
- [Clawable Internal Cockpit](mem://features/clawable-internal-cockpit) — Modul `clawable` (skills:[]) + `/admin/clawable`-UI för att chatta med externa operator-peers via `clawable-chat` → peer.url+/v1/responses. Aldrig MCP-exponerad — det är ett FlowWink-internt cockpit, inte en business capability. Programmatisk peer-trafik går via federation-modulens directional connections.
- [FlowChat Internal Operator Surface](mem://features/internal-flowchat-and-noise-separation) — `/admin/flowchat` platform-layer chat (admin sidebar + sessions + OperateChat), oberoende av FlowPilot-modulen. Tesla-modell: chat funkar även när Autopilot är av. Stoppade `chat_messages`-writes från agent-execute (notify trust) och signal-ingest. `loadConversations` filtrerar på role='user' så stale `Session — *` försvinner. Briefing kvar.
- [FlowWink as Business OS](mem://architecture/flowwink-as-business-os-three-shells) — Mental model: Platform=kernel, Admin UI / FlowChat (web-CLI) / MCP (stdin för agenter) = tre shells över samma skills. FlowPilot är operatör, inte shell. Stärker BOS-positionen.
- [Edge Supabase Client Factory](mem://architecture/edge-supabase-client-factory) — `_shared/supabase-clients.ts` är single source of truth för createClient() i edge functions. Helpers: getServiceClient/getUserClient/getAnonClient/resolveCaller. Nya functions ska använda dem; existerande migreras opt-in.
- [Manifest Namespacing](mem://architecture/manifest-namespacing) — `defineModule()` accepterar både namespaced (`agent`/`ui`/`data`) och flat shape; normaliseras + speglas så gamla läsare funkar. UI/data är reserverade placeholders.
- [Doc-drift Guardrail](mem://development/doc-drift-guardrail) — `bun run check:doc-drift` + CI-step (warn-only) som verifierar att varje registrerad modul har `docs/modules/<id>.md`. Backlog: multiCurrency, fixedAssets, payroll.
- Event bus reference: `docs/architecture/event-bus.md` är kanonisk katalog över emittade events, payloads och executor-modell. Lägg till nytt event där samtidigt som du seedar emit.
- [FlowChat vs FlowPilot Roles](mem://architecture/flowchat-vs-flowpilot-roles) — FlowChat = hand (reaktiv platform-feature), FlowPilot = hjärna (proaktiv operator). Hårda gränser: FlowChat får inte ha heartbeats/long-term memory/proactive actions; FlowPilot får inte bygga egna pipelines. Båda kallar samma skills via samma MCP. Se docs/concepts/flowchat-vs-flowpilot.md.
