Company Brain — architecture map

A local AI layer that learns: an orchestrator and several specialist models, each with its own system prompt and rules, a memory layer, and a CRM — one app, one UI. Today the AI part is done by EMODA AI and the CRM by Compass; these maps show the target. High level: no technology is chosen yet. Details in the README.

people / UIorchestrator / explorationspecialist modelsCRM (from Compass)customer sourcesmemory layer: prompts, rules, knowledgeplatformoffline training / reinforcement
Solid arrow: request or data moving forward · dashed arrow: result coming back · coloured arrow: CRM, memory or offline flow.

1 · The whole system

Flow 1 (a question), Flow 5 (the AI using the CRM), Flows 2–3 (onboarding a source), Flow 4 (nightly reinforcement) and the shared training and promotion.

DAYTIME · FLOW 1 — a question, end to end · FLOW 5 — the AI working in the CRMFLOWS 2–3 · ONBOARDING A SOURCE (once per source)FLOW 4 · NIGHTLY REINFORCEMENT (asynchronous)TRAINING & PROMOTION — Flow 3 (v0) and Flow 4Domain owner / staffapprove rules · review sourcesUserone app, nothing to selectUnified UI — one appchat: streaming · votes · corrections · exportsCRM pages: leads · deals · projects · tasksConversation logevery turn: question, calls,results, answer, votesOrchestratorown system prompt + rules · toolsplan · route · bounded loop · composeanswers only from data read in the turnCRM APIleads · deals · finances · projectstasks · hours · historygrant-only permissionsCRM databasethe brain's own data,read and written throughthe CRM API onlyMEMORY LAYER (map 4)Prompts & rulesa system prompt per modelrules by scope: orchestrator,each specialist, review modelproposed → active → integratedKnowledgedefinitions · aliases · known namesglossary · formula hintssource documentationRAG over documents & filesfacts · entitiesSPECIALIST MODELS — one per source, own prompt + rulesDB→ SQL forits schemaCustomer CRM→ its APIcallsERP→ its APIcallsOther toolsClickUp, Office…→ API callsFiles→ search andread documentsGuard / executorread-only · allowed tables, endpoints, foldersuser's permissions · size and time limitsConnectorsdatabase · API · file share · cloud driveCUSTOMER SOURCES (read-only)Databases / BIcustomer schemasCustomer CRMvia APIERPvia APIClickUp · Office · …any system with an APILocal filesfile sharesCloud filesDrive and similarapprovalsquestion · vote · correctionanswer (streamed)CRM pagesquestion + recent turnsanswer + table + record linkssaves every turnCRM toolsreads / writessystem prompt + rulesproposed rules (corrections)tools: definitions, aliasessub-questionrows / docs + summaryproposed actionresult · error → one retryvalidated actionrows / documentsquery · request · readindexed for RAG② Automatic explorationDB: tables, columns, keys, relations, samplesAPI: endpoints, auth, filters, pagination, rate limitsfiles: folders, formats, update frequencyDomain expert reviewwhat is real, what it means,which rules are fixedSource contract + docswhat can be asked, what returns,fixed rules, access examples③ Training examplesquestion → correct actionverified by running them③ Test benchquestions + expected resultsnever used for trainingreads structuresource documentationReview model (large, slow)~200B, fits the 128 GB at nightown system prompt + review rulesre-reads every turn of the dayjudges each call, checks figureson the source, blames the rightcomponent: specialist, orchestrator,memory, prompt or ruleMemory updatesaliases, definitions,rule proposalsPositive examplesconfirmed good callsCorrected exampleswrong call + right oneExample pool per specialistde-duplicated · checked against active rulesthreshold not reached → wait next nightturns + votes + implicit signalsmemory updatesTrainingsmall base model fine-tunedprevious dataset + new examplesreproducible: same data, same modelEvaluationtest bench (Flow 3)replay of real past chats (Flow 4)score per rule and question typePromote or discardonly if better on both0.0 → 0.x pilot → 1.x productionfail → revise examplesModel registryevery version of every modelactive one per specialistolder kept for rollbackexamplesbenchthreshold reachedactive version served to the specialists

2 · Where each part comes from today

EMODA AI already runs the AI loop for one customer; Compass already is the CRM. The Company Brain merges them into one app and generalises the AI to any source.

EMODA AI — todayCompany Brain — target blockCompass — todayAI over one customer's BI · Rust, Loco, llama-server · on-premise DGX Sparkdashed outline = new, built by neitheradvanced CRM · Rust, Loco, PostgreSQL · compass.hawkings.itUnified UI — one appchat + CRM pages, one layout, one loginChat UISSE streaming · votes · full table · exportsstaff pages: users, rules, SQL console, syncServer-rendered UI25 pages over one layout · Kanban boardsside panels saving one field at a timeAccounts & permissionswho may see and do what, in UI and AIAccountsusers and staff · signed session · CSRFstaff see non-staff chats, write only their ownGrant-only permissionsorganisations · nested groups · per-project grantsAPI tokens act as their person · TOTPOrchestrator + toolsplans, calls tools and specialists, composesOrchestrator with toolsQwen3-30B-A3B · interroga_db · cerca_valoredefinizioni · export · proponi_regola · ≤ 8 stepsCRM tools for the AIthe AI uses CRM functions as toolsMCP server — 15 toolsprojects · deliverables · tasks · bulk actionthin calls on the HTTP API · stdio + HTTPCRM module (API + database)the brain's own read/write dataCRM domain + HTTP APIDiscovery → Lead → Deal → Project · taskshours · instalments · expenses · lead historyMemory layer — prompts & rulesa system prompt + rules for every modelPrompts & learned rulesorchestrator_system.txt · db_system.txtrules by scope, author, keywords · statesMemory layer — knowledgedefinitions · aliases · RAG · source docsGlossary, checks, lookup fieldsdefinitions · formula hints · fuzzy name lookupdomain views v_movimenti · v_sellout · …Specialist modelsone per source, trained on itFine-tuned query modelft-xi-db: LoRA on XiYanSQL-QwenCoder-7Bwrites the SQL for that one databaseGuard / executorvalidates and runs every actionSQL guard + patchesSELECT only · allowed tables and columnsread-only transaction · 60 s timeoutConnectors & syncdatabases · APIs · files · webhooksBI syncMS SQL → PostgreSQL mirror, every morningfull · window · incrementalWebhooks & scheduled jobsCal.com bookings · GitHub READMEstimed rules (advance bookings)Credentials & settingssecrets sealed · settings without redeployCredential vault + settingsAES-256-GCM under one installation keysettings table · notifications · reportsTraining & evaluationexamples · bench · replay · promotionTraining & benchmarkdeterministic LoRA (seed 42) · 767 versioned testsreplay of real chats before productionModel registryevery version of every modelModels kept for rollbackprevious GGUFs in /opt/emoda/modelsone llama-server unit per modelNightly review modeljudges the day's chats, writes examplesSource exploration & contractsFlows 2–3 for any new source

3 · Flow 5 — the AI working in the CRM

One question that needs both the CRM and a customer database, the system prompt and rules each model receives, and how a correction becomes a rule.

User asks in the unified UI“Which deals in negotiation have an overdue instalment,what did those customers buy last season? Follow them up.”Unified UI — chat + CRM pagessame login and permissions for chat and CRManswer links open the CRM records in placeOrchestratorloads its system prompt + active rulesplans: CRM tools for deals and finances,DB specialist for last season's purchasesKnowledge (memory layer)definitions: “overdue” = due date passed, unpaidaliases: customer names in CRM ↔ in the ERPglossary · formula hints · source docsread through tools, never pasted wholelookupsPROMPTS & RULES (memory layer)Orchestratorsystem prompt + rules of scope orchestratorDB specialistsystem prompt + rules of scope DBEvery other specialistown system prompt + rules of its scopeReview modelsystem prompt + review rulesa rule reaches its author first, everyone once approvedprompt + rulesCRM tools (from Compass)search deals by stage · read financescreate a task · update a recordCRM APIacts with the asking user's permissionswrites: confirmation policy openCRM databaseleads · deals · instalments · projects · tasksoverdue deals · create follow-up tasksrecordsDB specialist“purchases of these customerslast season” → SQLGuard / executorread-only · allowlists · limitsCustomer database / BIsales, orders, sell-outreal namesrows + summaryanswer + table + record linksRULE LIFECYCLE — how a correction becomes a rule, then training (from EMODA)Correction in chat“overdue means unpaidafter the due date”Proposedorchestrator calls propose_ruleauthor accepts, edits or rejectsActive for its authorin that model's promptfor that user at onceActive for everyonestaff approve with one click(staff corrections: at once)Integratedabsorbed by a training,rule switched offside states: trial (only in the replays that test it) · rejectedactive rules

4 · The memory layer

Ten parts: levels, typed items, entity graph, context assembler, conversation state, episodic memory, memory tools, nightly consolidation, effect measurement, permissions. The numbers match the README.

writes into memory →chat correctionssource contractsdocuments → RAGsources → entitiesOrchestratoruses the memory toolsand gets an assembled promptSpecialist modelsget their slice: schema docs,rules of their scope, aliasesReview model (nightly)gets its prompt + review rules⑦ Memory toolsrecall(query, scope) · remember(fact)propose_rule(text, scope) · resolve(name)the orchestrator decides when to look up④ Context assemblercollects the candidates for this callranks: scope · entities · similarity ·recency · how often it helpedfits the model's token budgetlogs what went in, and why⑩ Permission filtera memory inherits its source's permissionsdropped if the asking user may not see itpromptread / writecandidatesallowed onlyMEMORY STORE① Levels — the most specific winsturn — what this call is aboutconversation — focus, summaryuser — preferences, personal rulesteam — rules approved for a groupcompany — definitions, fixed rules, factssource — contracts, schemas, docs② Typed memory itemtype: rule · definition · alias · fact · preferenceprovenance: correction · staff · review · documentscope (level + model) · confidencevalid from – to · versionstate: proposed · trial · active · integrated · expiredpermissions inherited from its source③ Entity graphone customer, product, store across sources:CRM id ⇄ ERP code ⇄ DB name ⇄ filealiases and misspellings are edges“that customer” resolves across turns⑤ Conversation statefocus: entities · period · filterslast query and its result“and last year?” → same focus,period moved back one year⑥ Episodic memorysolved cases: question → calls → approved answersimilar ones become examples in the promptand training data for Flow 4System prompts — one per modelorchestrator · every specialist · review modelversioned, edited without a release; rules and knowledge are added per call by ④NIGHTLY — keeping the memory clean (part of Flow 4)Conversation logevery turn: calls, results,answer, votes, signals+ the assembler's log ④⑧ Consolidationmerges duplicates · finds contradictionspromotes often-used memories up a levelretires integrated, unused or expired onesrebuilds the entity graph from the sourcesStaff review queuecontradictions to settlepromotions to team or companyrules proposed by the review⑨ Effect measurementreplay real chats with and withouteach rule or memory itemno effect or worse → retire itbetter → keep, candidate for trainingmerge · promote · retiredecisionskeep / retire