Mongodb Data Architecture Analysis
Documentation for Architecture
MongoDB Data Architecture Analysis
Date: 2026-02-21 | Session: 133.4 | Author: Claude Code (Opus 4.6)
This document provides a comprehensive analysis of the GoGrab platform's MongoDB data architecture across all three backends, the MCP server, and the Vitto intelligence system. It maps every database, collection, and data pipeline — identifying what's working, what's broken, and what needs fixing.
Table of Contents
- Cluster & Database Inventory
- Three Intelligence Systems
- Empty Collection Classification
- Root Cause: The Outcome Detection Lynchpin
- Dead Code Inventory
- User-Type Segregation Analysis
- Data Flow Diagrams
- Frontend Route -> Data Source Mapping
- Performance & Architecture Assessment
- Prioritized Recommendations
1. Cluster & Database Inventory
1.1 Three Atlas Clusters
The platform uses 3 separate MongoDB Atlas clusters sharing the same credentials but hosting different workloads:
| Cluster | Host | Env Var | Backends | Total Size |
|---|---|---|---|---|
| gograbspace | gograbspace.dgajj2t.mongodb.net |
MONGODB_CONNECTION_STRING |
backend-api, backend-ai-api | ~238 MB |
| gograb-docs | gograb-docs.z422vsq.mongodb.net |
MONGODB_CONNECTION_STRING_DOCS |
backend-docs-api | ? |
| vitto | vitto.urgh5aw.mongodb.net |
VITTO_MONGODB_URI |
backend-vitto-api | ~8.6 MB |
Config files:
.env.local(lines 47-62) — all connection stringslibs/libs-api/backend-core/src/lib/config/database-names.config.ts— database name constantslibs/libs-api/backend-core/src/lib/config/mongodb.factory.ts— connection factory with pool sizes
1.2 gograbspace Cluster (~238 MB)
backend-ai-api opens 5 simultaneous connections to this cluster, each targeting a different database:
ai-agents (31 MB, 26 collections)
Primary database for AI agent orchestration.
| Collection | Documents | Status | Purpose |
|---|---|---|---|
decisions |
11,924 | Active | Core MCP decision log (11,761 editor2 + 163 gspace1) |
golden_decisions |
200 | Active | Curated high-quality decisions |
generated-modules |
152 | Active | AI-generated modules (144 published, 8 draft) |
chat_sessions |
13 | Active | AI panel chat sessions (12 dashboard, 1 unknown) |
training_jobs |
6 | Broken | All 6 FAILED — mock OpenAI integration |
platform_agents |
4 | Active | Module Gen Expert, Widget Creator, Platform Architect, Code Quality Expert |
tenant_user_profiles |
2 | Minimal | T2/T3 user AI profiles |
agent_routed_knowledge |
2 | Minimal | Agent-specific knowledge routing |
space_builder_preferences |
1 | Minimal | Space builder preferences |
space_agent_tasks |
1 | Minimal | Space-specific agent tasks |
agent_patterns |
0 | Broken | Pattern mining depends on outcome detection |
agent_calibrations |
0 | Broken | Calibration depends on outcome detection |
agent_outcome_correlations |
0 | Broken | Outcome correlation depends on outcomes |
agent_tasks |
0 | Not yet activated | Task decomposition |
agent_processes |
0 | Not yet activated | Agent execution state |
agent_metrics |
0 | Not yet activated | Aggregated metrics |
agent_knowledge |
0 | Not yet activated | Agent-specific knowledge |
platform_patterns |
0 | Not yet activated | Platform-wide patterns |
builder_profiles |
0 | Not yet activated | Space builder profiles |
tenant_user_interactions |
0 | Not yet activated | T2/T3 user tracking |
deployment_snapshots |
0 | Not yet activated | Module deployment versioning |
configuration_sessions |
0 | Not yet activated | Configuration workflows |
workspace_configs |
0 | Not yet activated | Workspace registry (v12.0) |
mcp_projects |
0 | Correctly empty | External project registry |
test-modules |
0 | Dead code | Migration leftover |
agent_embeddings |
0 | Dead code | Embeddings live in ai-memory instead |
Decisions breakdown by type:
- bugfix: 6,233 (52.3%)
- architecture: 4,818 (40.4%)
- implementation: 717 (6.0%)
- refactor: 57, convention: 28, pattern: 27, milestone: 19, fix: 12, documentation: 11, testing: 1, system-optimization: 1
Decisions with outcomes: 441 / 11,924 (3.7%) — the rest have NO outcome data.
ai-memory (189 MB, 2 collections)
Largest database. Separated for vector search performance optimization.
| Collection | Documents | Status | Purpose |
|---|---|---|---|
agent_embeddings |
8,151 | Active | Decision embeddings (text-embedding-3-small, 1536 dims) |
golden_embeddings |
200 | Active | Curated embeddings for high-quality decisions |
Performance justification: At 189 MB (6x larger than ai-agents), keeping vector embeddings in a separate database with dedicated connection pool (maxPoolSize: 20) is architecturally correct. Vector search queries are computationally expensive and would compete with regular CRUD on ai-agents.
ai-mcp-dev (5 MB, 18 collections)
MCP development session management, learning pyramid, and agent coordination.
| Collection | Documents | Status | Purpose |
|---|---|---|---|
agents |
2,844 | Active (data quality issue) | Agent registry. ALL have agentType: null — schema has platform field, not agentType |
learned_patterns |
563 | Active | Middle of Intelligence Pyramid (479 general, 84 architecture) |
sessions |
455 | Active | Development sessions (434 active, 21 completed; 260 editor2, 191 gspace1) |
simulations |
337 | Active | Mental simulations for planning |
trigger_states |
159 | Active | Adaptive learning triggers |
handoffs |
130 | Active | Inter-agent task delegation (80 completed, 36 expired, 14 rejected) |
core_rules |
10 | Active | Top of Intelligence Pyramid (6 angular, 3 build, 1 backend) |
reflections |
3 | Active | Post-task reflections |
causal_nodes |
3 | Active | Causal reasoning nodes |
causal_edges |
2 | Active | Causal relationships |
causal_graphs |
1 | Active | Causal knowledge container |
session_counter |
1 | Active | Atomic session ID counter |
episodes |
0 | Broken | Method signature mismatch in EpisodicMemoryService |
curiosity_triggers |
0 | Not yet activated | Active learning triggers |
learning_requests |
0 | Not yet activated | Agent-initiated learning |
knowledge_gaps |
0 | Not yet activated | Knowledge gap detection |
mcp_config |
0 | Correctly empty | Per-session MCP config |
mcp_usage |
0 | Not yet activated | API usage tracking |
Intelligence Pyramid (live data):
┌──────────────┐
│ CORE RULES │ 10 rules (confidence 0.95-1.0)
│ (ai-mcp-dev)│ 6 Angular, 3 Build, 1 Backend
└──────┬───────┘
│ promoted from
┌──────┴───────┐
│ PATTERNS │ 563 learned patterns
│ (ai-mcp-dev)│ 479 general, 84 architecture
└──────┬───────┘
│ clustered from
┌──────┴───────┐
│ DECISIONS │ 11,924 decisions
│ (ai-agents) │ 52% bugfix, 40% architecture
└──────────────┘
ai-archive (0.08 MB, 4 collections)
Cold storage — never activated. All collections empty.
archive_policies,archived_decisions,archived_embeddings,archive_jobs
ai-backups (5.8 MB, 3 collections)
Pre-v11 migration backup.
| Collection | Documents | Purpose |
|---|---|---|
decisions_pre_v11 |
11,585 | Backup of decisions before v11 schema migration |
sessions_pre_v11 |
137 | Backup of sessions |
golden_decisions_pre_v11 |
200 | Backup of golden decisions |
Needs: Retention policy. Data is 2+ months old.
ai-context (1 MB, 5 collections)
AI generation context and usage tracking.
| Collection | Documents | Purpose |
|---|---|---|
aiusages |
478 | AI API usage records |
ai_generations |
58 | Generation history |
ai_mappings |
24 | AI field mappings |
ai_theme_context |
5 | Theme generation context |
ai_usage |
0 | Legacy usage tracking |
Other gograbspace databases
| Database | Size | Collections | Notes |
|---|---|---|---|
gograb-api |
2.8 MB | spaces (65), universes (63), users (4), + 28 more | Main platform data |
gograb-core |
0.4 MB | core_properties (19), core_property_templates (15), core_widgets (7) | Platform core |
gograb-analytics |
0.14 MB | Analytics | Usage analytics |
space-agents_default |
0.47 MB | user_profiles (5), user_interactions (0), patterns (0), preferences (0) | Per-space AI |
space-agents_external |
0.61 MB | decisions (7) | External space AI |
space_chrome-space-1_* |
1.23 MB | Per-space data | Chrome extension space |
space_default-space |
0.06 MB | Per-space data | Default space |
space_test-space-123 |
0.15 MB | Per-space data | Test space |
SpaceAIDatabaseService IS working — it has successfully created per-space agent databases (space-agents_default, space-agents_external) with the correct schema.
1.3 vitto Cluster (8.6 MB)
Single database: vitto-mind
vitto-mind (8.6 MB, 35 collections)
| Collection | Documents | Status | Purpose |
|---|---|---|---|
proactive-alerts |
2,031 | Over-alerting | 1,725 critical + 306 warning. Needs noise reduction. |
vitto-memories |
210 | Active | 112 learning, 68 conversation, 26 task, 3 system, 1 BI |
routing-decisions |
157 | Active | LLM routing (115 claude, 42 openai) |
codebase-index |
139 | Active | NX monorepo project index (auto-reindexed every 6h) |
autonomy-checkpoints |
46 | Active | Decision approval checkpoints |
security-audit-logs |
38 | Active | SOC 2 compliance audit trail |
execution-traces |
26 | Active | All 26 successful executions |
dead-letter-entries |
11 | Active | Failed task retry queue |
spending-records |
6 | Active | Cost tracking per task |
vitto-personas |
5 | Active | 5 built-in personas (Professional, Friendly, Technical, Concise, Creative) |
vitto-workflows |
3 | Active | Workflow definitions |
user-budgets |
2 | Active | Per-user token/cost budgets |
strategy-memories |
1 | Broken | Should update on every task |
autonomy-config |
1 | Active | Singleton global config |
vitto-channels |
1 | Active | Communication channels |
user-patterns |
0 | Broken | No population code |
agent-performance |
0 | Broken | recordAgentOutcome() never called |
vitto-skills |
0 | Broken | No trigger for skill generation |
schedule-executions |
0 | Broken | No endpoint to create schedules |
agent-sessions |
0 | Not yet activated | Session 132 feature |
sub-agent-definitions |
0 | Not yet activated | Manual setup via API |
customer-sessions |
0 | Correctly empty | End-user chat not built |
encrypted-secrets |
0 | Correctly empty | Manual activation |
approval-requests |
0 | Correctly empty | Tool security gates not wired |
active-tasks |
0 | Not yet activated | In-flight task persistence |
user-notification-prefs |
0 | Dead code | Not registered in module |
channel-user-links |
0 | Not yet activated | Channel system |
vitto-webhooks |
0 | Not yet activated | Webhook system |
vitto-webhook-events |
0 | Not yet activated | Webhook events |
vitto_webhook_subscriptions |
0 | Not yet activated | Webhook subscriptions |
vitto_webhook_deliveries |
0 | Not yet activated | Webhook deliveries |
vitto-connectors |
0 | Not yet activated | Connector system |
vitto-schedules |
0 | Not yet activated | Schedule definitions |
vitto-audit-trail |
0 | Not yet activated | Audit trail |
skill-versions |
0 | Correctly empty | No skills exist yet |
Vitto memories breakdown:
| Type | Count | Description |
|---|---|---|
| learning | 112 | Auto-learned from MCP decisions (via sourceDecisionId) |
| conversation | 68 | Chat interactions summaries |
| task_execution | 26 | Task outcome + lessons |
| system | 3 | System-level knowledge |
| business_intelligence | 1 | Business analytics |
Memory layer distribution: developer: 209 (99.5%), platform_builder: 1 (0.5%), customer: 0
Embedding coverage: 208/210 memories have 1536-dim vector embeddings (text-embedding-3-small)
1.4 MCP File-Based Storage (Active)
The MCP server at MCP/mcp-gograb-ai/ uses a dual-write strategy: write to local JSON files first, then sync to MongoDB via REST API (backend-ai-api).
| File | Size | Content | Status |
|---|---|---|---|
.cursor/ai-memory/hot-memory.json |
46 KB | 21 recent decisions (working set) | Active |
.cursor/ai-memory/outcome-tracker.json |
163 KB | 113 validated + 2 pending outcomes | Active |
.cursor/ai-memory/conventions.json |
5 KB | 6 learned conventions | Active |
.cursor/ai-memory/working-memory.json |
2.8 KB | Session 133, 10 summaries | Active |
.cursor/ai-memory/pending-events.json |
206 KB | Sync queue events | CORRUPTED (invalid JSON) |
.cursor/ai-memory/tool-usage.log |
47 KB | MCP tool usage log | Active |
.cursor/ai-memory/development-memory.json.backup |
22 MB | Historical backup | Stale |
sessions/manifests/S*.json |
varies | Session manifests (S109-S133) | Active |
sessions/history.json |
28 KB | Session source of truth (996 lines) | Active |
2. Three Intelligence Systems
The platform has three independent intelligence systems that partially cross-pollinate:
System 1: MCP Intelligence (Developer-Time)
What it is: Real-time learning system for Cursor/Claude Code agents during development sessions.
Data stores:
- Local:
.cursor/ai-memory/hot-memory.json(21 decisions),conventions.json(6 conventions),outcome-tracker.json(113 validated outcomes) - Remote:
ai-agents.decisions(11,924),ai-mcp-dev.learned_patterns(563),ai-mcp-dev.core_rules(10)
Data flow:
Developer uses Cursor/Claude Code
↓
LLM calls MCP tool: log_decision()
↓
MCP Server (mcp-gograb-ai)
├──→ [1] In-memory store (prepend to decisions array)
├──→ [2] Local JSON file (.cursor/ai-memory/hot-memory.json)
└──→ [3] REST API → backend-ai-api → ai-agents.decisions
(works when backend running, fails silently otherwise)
Status: Working end-to-end. 11,924 decisions successfully synced to remote MongoDB.
System 2: AI Infrastructure Intelligence (Backend)
What it is: Server-side learning system with pattern mining, calibration, episodic memory, and causal reasoning.
Data stores:
ai-agents: decisions, golden_decisions, generated-modules, chat_sessions, platform_agentsai-mcp-dev: learned_patterns, core_rules, agents, sessions, handoffs, simulations, trigger_statesai-memory: agent_embeddings (8,151), golden_embeddings (200)
Status: Partially working. Decisions are stored and patterns are extracted to the learning pyramid. But agent_patterns mining, calibration, and episodic memory are blocked by missing outcome detection.
System 3: Vitto Mind (Orchestrator)
What it is: Vitto's operational intelligence — memory, strategy, performance tracking, security.
Data stores:
vitto-mind: vitto-memories (210), routing-decisions (157), execution-traces (26), proactive-alerts (2,031), personas (5)
Cross-pollination:
- 112 of 210 Vitto memories have
sourceDecisionId— they were auto-created from MCP decisions - Vitto's
OutcomeFeedbackServicesends execution outcomes to backend-ai-api's learning pipeline - Backend-ai-api's
BackendAiClientServicequeries vitto-mind for strategy context
Status: Growing but several pipelines broken (user-patterns, agent-performance, strategy-memories, skills).
Overlap Matrix
| Concept | System 1 (MCP) | System 2 (AI Infra) | System 3 (Vitto Mind) | Overlap? |
|---|---|---|---|---|
| Decisions | 21 in hot-memory | 11,924 in ai-agents.decisions | 112 learning memories (narrative form) | YES — linked via sourceDecisionId |
| Patterns | 6 conventions (JSON) | 563 learned_patterns + 10 core_rules | 1 strategy-memory | Different purpose |
| Embeddings | None | 8,151 decision embeddings (ai-memory) | 208 memory embeddings (vitto-mind) | Same model, justified separation |
| Agent Registry | Agent mesh state (in-memory) | 2,844 agents (ai-mcp-dev) | Sub-agent definitions (0) | Different scope |
| Sessions | Session manifests (JSON) | 455 sessions (ai-mcp-dev) | 0 agent-sessions | Different session types |
| Outcomes | 113 validated (JSON) | 441 with outcomes (ai-agents) | 26 execution traces | Partial sync |
3. Empty Collection Classification
Broken Pipelines (should have data, code exists but doesn't work)
| Database | Collection | Root Cause | Fix Priority |
|---|---|---|---|
| ai-agents | agent_patterns |
Pattern mining cron queries outcome.wasSuccessful=true, but only 441/11,924 decisions have outcomes |
Critical |
| ai-agents | agent_calibrations |
CalibrationService queries outcomes. Also: curves computed in-memory, never persisted to MongoDB | Critical |
| ai-agents | agent_outcome_correlations |
Depends on outcome detection | Critical |
| ai-mcp-dev | episodes |
decision.service.ts calls storeEpisode() but EpisodicMemoryService has recordEpisode() — method name mismatch |
High |
| vitto-mind | user-patterns |
getUserPattern() only reads, no recordUserPattern() or write code exists |
High |
| vitto-mind | agent-performance |
recordAgentOutcome() method exists in MindService but is never called from delegation flow |
High |
| vitto-mind | strategy-memories (1 doc) |
Should update on every task completion, only 1 suggests recordExecution() rarely completes |
High |
| vitto-mind | vitto-skills |
Skill generation requires explicit "teach intent" detection, no automatic trigger | Medium |
| vitto-mind | schedule-executions |
Task scheduler service has checkDueTasks() cron but no endpoint to create schedules |
Medium |
Not Yet Activated (code exists, prerequisites not met)
| Database | Collection | What's Needed |
|---|---|---|
| ai-agents | agent_tasks |
Task decomposition flow needs to be wired |
| ai-agents | agent_processes |
Agent execution state tracking |
| ai-agents | agent_metrics |
Depends on agent_tasks being populated first |
| ai-agents | agent_knowledge |
Agent-specific knowledge — no pipeline feeds it |
| ai-agents | platform_patterns |
Platform pattern extraction not running |
| ai-agents | builder_profiles |
No UI creates builder profiles |
| ai-agents | tenant_user_interactions |
T2/T3 frontend tracking not implemented |
| ai-agents | deployment_snapshots |
Module deployment versioning |
| ai-agents | configuration_sessions |
Configuration workflow sessions |
| ai-agents | workspace_configs |
Workspace registry (v12.0) |
| ai-mcp-dev | curiosity_triggers |
Active learning system needs episodes first |
| ai-mcp-dev | learning_requests |
Agent-initiated learning requests |
| ai-mcp-dev | knowledge_gaps |
Gap detection system |
| ai-mcp-dev | mcp_usage |
API usage tracking for billing |
| vitto-mind | agent-sessions |
Session 132 feature, code not wired into execution |
| vitto-mind | sub-agent-definitions |
Manual setup via API needed |
| vitto-mind | active-tasks |
In-flight task persistence |
| vitto-mind | Channel/webhook collections | Webhook & connector system not activated |
Correctly Empty (feature not built or manual activation)
| Database | Collection | Why |
|---|---|---|
| ai-agents | mcp_projects |
External project registry — manual setup |
| ai-mcp-dev | mcp_config |
Per-session MCP config — rarely used |
| vitto-mind | customer-sessions |
End-user chat not yet implemented |
| vitto-mind | encrypted-secrets |
Requires VITTO_MASTER_KEY env var + manual creation |
| vitto-mind | approval-requests |
Tool security gates not wired into execution flow |
| vitto-mind | skill-versions |
No skills exist yet to version |
Dead Code (should be deleted)
| Database | Collection | Why |
|---|---|---|
| ai-agents | test-modules |
0 docs, migration leftover |
| ai-agents | agent_embeddings |
0 docs, embeddings actually in ai-memory.agent_embeddings |
| vitto-mind | user-notification-prefs |
Schema file exists but NOT registered in MindModule |
4. Root Cause: The Outcome Detection Lynchpin
The single biggest systemic issue is that decision outcome detection is not wired up. This blocks 5+ downstream features.
The Problem
decision.service.ts (line 97):
this.eventEmitter.emit('decision.created', { ... });
↓
NO @OnEvent('decision.created') handler exists
↓
Outcomes never populated
↓
┌───────────────┼───────────────────┐
↓ ↓ ↓
agent_patterns agent_calibrations episodes
queries: queries: needs:
outcome.was outcome.was outcome data
Successful=true Successful=true in schema
→ 0 results → 0 results → empty
Current State
- 11,924 decisions in ai-agents.decisions
- Only 441 (3.7%) have any outcome data — these came from the MCP's
report_outcometool, which manually reports outcomes - The backend's
OutcomeDetectorServicewas designed to auto-detect outcomes from git commits, build results, and test passes — but its event handler was never connected
Impact
Without outcomes, these features are dead:
- Pattern Mining (cron every 6h) — queries
outcome.wasSuccessful=true, gets 0 results → 0 patterns - Confidence Calibration — queries outcomes to build calibration curves → 0 calibration data
- Episodic Memory — episodes require outcome data → method signature mismatch compounds the issue
- Training Pipeline — training jobs need
qualityRating >= 7from outcomes → all 6 jobs fail - Agent Outcome Correlations — no outcomes to correlate
Fix
Create an OutcomeDetectionListener that subscribes to decision.created events and auto-populates outcomes based on:
- Confidence-based heuristic (confidence >= 0.8 → likely successful)
- MCP outcome-tracker data sync (113 validated outcomes exist in local files)
- Later: git commit analysis, build results integration
File: apis/backend-ai-api/src/app/infrastructure/services/decision.service.ts (line 97)
New file: apis/backend-ai-api/src/app/learning/listeners/outcome-detection.listener.ts
5. Dead Code Inventory
5.1 Duplicate Schemas in backend-api
The following schemas exist in BOTH apis/backend-api/src/app/ai-agents/schemas/ and apis/backend-ai-api/src/app/agents/schemas/:
| Schema | backend-api (legacy) | backend-ai-api (active) |
|---|---|---|
| agent-calibration.schema.ts | Duplicate | Source of truth |
| agent-pattern.schema.ts | Duplicate | Source of truth |
| agent-embedding.schema.ts | Duplicate | Source of truth |
| agent-task.schema.ts | Duplicate | Source of truth |
| tenant-user-profile.schema.ts | Duplicate | Source of truth |
| tenant-user-interaction.schema.ts | Duplicate | Source of truth |
The backend-ai-api agents.module.ts explicitly documents: "Migrated from: apis/backend-api/src/app/ai-agents/" (line 4).
The entire apis/backend-api/src/app/ai-agents/ module is still registered in apis/backend-api/src/app/app.module.ts (line 134) but should be removed.
Action: Delete the 6 duplicate schema files and remove the module registration.
5.2 Misattributed Schema (NOT Dead)
apis/backend-vitto-api/src/app/mind/schemas/user-notification-prefs.schema.ts is NOT registered in mind.module.ts but IS registered in proactive.module.ts (line 30) and actively used by proactive-monitor.service.ts for user notification preferences.
Action: None needed. Schema is active, just registered in a different module.
5.3 Empty Collections to Drop
ai-agents.test-modules— 0 docs, migration artifactai-agents.agent_embeddings— 0 docs, embeddings live in ai-memory.agent_embeddings
Action: Drop collections from remote MongoDB.
5.4 Stale Data
| Location | Data | Age | Action |
|---|---|---|---|
ai-backups.*_pre_v11 |
11,922 docs (5.8 MB) | 2+ months | Define retention policy or delete |
vitto-mind.proactive-alerts |
2,031 docs (1,725 critical) | Accumulating | Investigate, add noise reduction |
.cursor/ai-memory/development-memory.json.backup |
22 MB | Months | Delete or archive |
.cursor/ai-memory/pending-events.json |
206 KB | Corrupted | Reset to empty JSON |
6. User-Type Segregation Analysis
6.1 Current State
Vitto memories support 4 user types via the layer field, but almost all data is developer-scoped:
| Layer | Count | Percentage | Description |
|---|---|---|---|
developer |
209 | 99.5% | Coding agent learning about code |
platform_builder |
1 | 0.5% | Platform builders building spaces |
customer |
0 | 0% | End-users of built spaces |
system (available) |
0 | 0% | Platform learning about itself |
6.2 Schema Support
The schemas have excellent multi-tenant fields, but no pipeline populates them:
vitto-memories schema:
layer: developer / platform_builder / customer / systemuserId: Per-user isolationspaceId: Per-space isolationshareLevel: private / team / organizationteamId: Team-level sharing (Phase 5.3 planned)
ai-agents schemas:
tenantId: Multi-tenant isolation (on agent_patterns, learned_patterns, agent_tasks)spaceId: Space-scoped data (on handoffs, space_agent_tasks)userId: User-scoped data (on chat_sessions, tenant_user_profiles)
SpaceAIDatabaseService (backend-ai-api) can dynamically create per-space databases (space-agents_{spaceSlug}) and has successfully created 2 space databases.
6.3 What's Missing
Builder Intelligence Pipeline: When a platform builder configures a space, no pipeline captures their decisions as builder-layer memories. The
space_builder_preferencescollection has 1 doc, but no continuous learning.Customer Intelligence Pipeline: When end-users interact with built spaces (via Vitto customer-facing agent), no pipeline captures their patterns. The
customer-sessionscollection exists but the customer chat feature is not yet implemented.System Intelligence Pipeline: The SuperIntelligence module (episodes, causal graphs, reflections) is designed for system self-learning but has no data pipeline feeding it.
Data Routing Policy: There's no middleware or service that decides which
layera new Vitto memory should be assigned to. Currently, theOutcomeFeedbackServicedefaults all memories tolayer: 'developer'.
6.4 Recommendations
Add a
MemoryLayerRouterservice that determines thelayerbased on context:- MCP decision source →
developer - Space configuration context →
platform_builder - Customer chat context →
customer - System health/monitoring →
system
- MCP decision source →
Wire the SpaceAIDatabaseService to create
platform_buildermemories when builders make space changesPlan customer intelligence for Phase 2 when customer-facing Vitto chat is implemented
7. Data Flow Diagrams
7.1 Decision Lifecycle
Developer in Cursor/Claude Code
│
▼
MCP: log_decision()
│
┌────┴────┐
▼ ▼
LOCAL REMOTE (REST API)
Files POST /ai-api/infrastructure/decisions
│ │
▼ ▼
hot-memory ai-agents.decisions (11,924)
.json (21) │
├──→ EventEmitter: 'decision.created'
│ │
│ ▼
│ OutcomeDetectionListener (MISSING)
│ │
│ ┌────┴────────────────┐
│ ▼ ▼
│ agent_patterns agent_calibrations
│ (0 docs) (0 docs)
│
├──→ EmbeddingService
│ │
│ ▼
│ ai-memory.agent_embeddings (8,151)
│
└──→ PatternMiningJob (cron 6h)
│
▼
ai-mcp-dev.learned_patterns (563)
│
▼ (promoted)
ai-mcp-dev.core_rules (10)
7.2 Vitto Memory Creation
Interaction Source
├── MCP Decision Sync (112 memories)
│ OutcomeFeedbackService → createMemoryFromDecision()
│
├── Chat Conversation (68 memories)
│ VittoEngineService → after response → createMemoryFromConversation()
│
├── Task Execution (26 memories)
│ PhaseExecutor → VERIFY phase → mind.recordExecution()
│
└── System Events (3 memories)
ProactiveMonitor → system alerts → createMemory()
│
▼
VittoMemoryService
├── Generate embedding (OpenAI text-embedding-3-small, 1536 dims)
├── Compute importance (outcome 0.3 + type 0.3 + recency 0.2 + access 0.2)
└── Store in vitto-mind.vitto-memories (210 docs)
│
▼
Hot Cache (in-memory Map, 30-min TTL)
├── Tier 1: In-memory recall (fastest)
├── Tier 2: MongoDB Vector Search ($vectorSearch, cosine similarity)
└── Tier 3: Platform API fallback (backend-ai-api queries)
7.3 Cross-Backend Intelligence Bridge
┌──────────────────────────┐ ┌──────────────────────────┐
│ backend-ai-api (3001) │ │ backend-vitto-api (3003)│
│ │ │ │
│ ai-agents.decisions ────┼──→───┼→ vitto-memories │
│ (11,924 docs) │ via │ (112 with sourceDecision│
│ │ Out-│ Id linking back) │
│ ai-mcp-dev.learned_ │ come│ │
│ patterns (563) ←────┼──←───┼← execution-traces (26) │
│ │ Feed│ → sends outcomes to │
│ ai-memory.agent_ │ back│ learning pyramid │
│ embeddings (8,151) │ │ │
│ │ │ strategy-memories (1) │
│ platform_agents (4) │ │ routing-decisions (157) │
└──────────┬───────────────┘ └──────────┬───────────────┘
│ │
└──────────┬───────────────────────┘
│
▼
VittoApiService (frontend)
injects BOTH:
- AI_API_URL (port 3001)
- VITTO_API_URL (port 3003)
8. Frontend Route -> Data Source Mapping
| Route | App | Port | Backend | API Endpoint | Data Source | Doc Count |
|---|---|---|---|---|---|---|
/agents/training-center |
gograb-dev | 5300/6300 | backend-ai-api (3001) | GET /ai-api/agents |
ai-agents.platform_agents | 4 |
/mcp/status |
gograb-dev | 5300/6300 | backend-ai-api (3001) | GET /ai-api/mcp-status |
ai-agents + live MCP | Computed |
/intelligence/cursor-agents |
gograb-dev | 5300/6300 | backend-ai-api (3001) | GET /ai-api/infrastructure/decisions?limit=100 |
ai-agents.decisions | 11,924 |
/intelligence/pyramid |
gograb-dev | 5300/6300 | backend-ai-api (3001) | GET /ai-api/learning/pyramid |
ai-mcp-dev.core_rules + learned_patterns | 10 + 563 |
/intelligence/memory |
gograb-dev | 5300/6300 | backend-ai-api (3001) | GET /ai-api/infrastructure/decisions |
ai-agents.decisions | 11,924 |
/vitto/memory |
dev/ai/admin | all | backend-vitto-api (3003) | GET /vitto-api/memories/list |
vitto-mind.vitto-memories | 210 |
/vitto/personas |
dev/ai/admin | all | backend-vitto-api (3003) | GET /vitto-api/personas/list |
vitto-mind.vitto-personas | 5 |
9. Performance & Architecture Assessment
9.1 Multi-Database Justification
| Database | Size | Access Pattern | Keep Separate? | Reasoning |
|---|---|---|---|---|
ai-agents |
31 MB | Write-heavy (decisions), frequent queries | YES | Core workload, hot path |
ai-memory |
189 MB | Vector search, computationally expensive | YES | 6x larger, vector ops compete with CRUD |
ai-mcp-dev |
5 MB | Session management, handoffs | OPTIONAL | Could merge into ai-agents |
ai-archive |
0.08 MB | Cold storage, rarely accessed | MERGE connection | Keep collection prefixes, share ai-agents connection |
vitto-mind |
8.6 MB | Mixed (memories + alerts) | YES | Separate cluster entirely |
9.2 Connection Pool Analysis
backend-ai-api currently opens 5 connections to the gograbspace cluster:
| Connection | Database | Pool Size | Justification |
|---|---|---|---|
| Default | gograb-api | maxPool: 50 | Main platform data access |
| AGENTS | ai-agents | maxPool: 20 | Decision CRUD, pattern queries |
| MEMORY | ai-memory | maxPool: 20 | Vector search (separate for performance) |
| MCP_DEV | ai-mcp-dev | maxPool: 20 | Session management |
| ARCHIVE | ai-archive | maxPool: 5 | Cold storage (unused) |
Recommendation: Merge ai-archive into the ai-agents connection (keep as collection prefix like archived_*). This reduces to 4 connections. Do NOT merge ai-memory — its 189 MB of vector data justifies isolation.
9.3 Index Coverage
Well-indexed collections:
decisions: sessionNumber+timestamp, agentId+type+confidence, globalSessionIdagent_embeddings: Vector search index (manual Atlas creation required)handoffs: workspace+status, toAgentType+statusvitto-memories: userId+createdAt, spaceId+createdAt, type+importance, vector search index
Missing indexes to add:
decisions: Add index onoutcome.wasSuccessful+createdAt(for pattern mining queries)proactive-alerts: Add index onresolved+createdAt(for cleanup queries)
10. Prioritized Recommendations
P0: Critical (Blocking Core Features)
| # | Action | Impact | Files |
|---|---|---|---|
| 1 | Create OutcomeDetectionListener for decision.created event |
Unblocks pattern mining, calibration, episodes, training | apis/backend-ai-api/src/app/learning/listeners/ (new) |
| 2 | Fix pending-events.json corruption | Restore local MCP-to-MongoDB sync | .cursor/ai-memory/pending-events.json |
| 3 | Investigate 2,031 proactive alerts (1,725 critical) | Data hygiene, reduce noise | apis/backend-vitto-api/src/app/proactive/proactive-monitor.service.ts |
P1: High (Dead Code & Data Quality)
| # | Action | Impact | Files |
|---|---|---|---|
| 4 | Delete 6 duplicate schemas from backend-api | Remove confusion, dead code | apis/backend-api/src/app/ai-agents/schemas/*.ts |
| 5 | Delete unregistered user-notification-prefs.schema | Dead code cleanup | apis/backend-vitto-api/src/app/mind/schemas/ |
| 6 | Fix agentType null on 2,844 agents | Data quality | Schema: add agentType field |
| 7 | Fix episode storage method signature mismatch | Enable episodic memory | apis/backend-ai-api/src/app/super-intelligence/services/episodic-memory.service.ts |
P2: Medium (Pipeline Activation)
| # | Action | Impact | Files |
|---|---|---|---|
| 8 | Wire recordAgentOutcome() in delegation-manager |
Enable agent performance tracking | apis/backend-vitto-api/src/app/engine/delegation-manager.service.ts |
| 9 | Add recordUserPattern() write logic |
Enable user preference learning | apis/backend-vitto-api/src/app/mind/services/mind.service.ts |
| 10 | Merge ai-archive connection into ai-agents | Reduce connections 5→4 | apis/backend-ai-api/src/app/app.module.ts |
| 11 | Define data ownership policy (layer routing) | Multi-tenant intelligence | Documentation + MemoryLayerRouter service |
| 12 | Add retention policy for ai-backups | Storage cleanup (5.8 MB) | Cron job or archive policy |
P3: Low (Future Improvements)
| # | Action | Impact | Files |
|---|---|---|---|
| 13 | Drop orphaned collections (test-modules, ai-agents.agent_embeddings) | Cleanup | Direct DB operation |
| 14 | Add missing indexes (outcome + createdAt on decisions) | Query performance | Schema migration |
| 15 | Activate builder/customer layers | Multi-tenant intelligence | Multiple services |
11. Additional Findings & Recommendations (Session 133.4 Deep Dive)
11.1 Index Bloat on ai-agents.decisions
The decisions collection has a critical index-to-data ratio problem:
- Data size: 4.93 MB (11,924 documents, avg 2,095 bytes each)
- Index size: 23.22 MB (30 indexes!)
- Ratio: 4.7:1 — indexes are nearly 5x the data itself
Worst offenders:
| Index | Size | Notes |
|---|---|---|
question_text_chosen_text_reasoning_text |
13.6 MB | Full-text index — 2.7x the entire data. Consider dropping if vector search is primary |
tags_1_confidence_-1 |
996 KB | Compound on array field |
tags_1 |
924 KB | Duplicate coverage with above |
workspace_1 |
828 KB | Only 2 unique values (editor2, gspace1) — low cardinality |
subSessionNumber_1 |
600 KB | Rarely queried directly |
Impact: Every decision insert updates 30 indexes. At scale (100K+ decisions), this will severely impact write performance.
Recommendation: Audit and drop unused indexes. Target: reduce from 30 to ~12 core indexes:
- Keep:
_id,sessionNumber+timestamp,agentId+type+confidence,outcome.wasSuccessful+confidence,globalSessionId+timestamp,createdAt - Evaluate: text index (13.6 MB) — if vector search (ai-memory.agent_embeddings) handles semantic search, the text index is redundant
- Drop: low-cardinality indexes (
workspace_1,platform_1), duplicate compound indexes
11.2 Agent Registration Spam
The ai-mcp-dev.agents collection has 2,844 unique agent registrations, but many are duplicate reconnections:
| Agent ID Prefix | Registrations | Cause |
|---|---|---|
control-center-17698* |
276 | Same process, many reconnects |
control-center-17697* |
143 | Same |
control-center-17699* |
137 | Same |
cowork-Anthropic-177* |
76 | Cowork session reconnects |
Distribution by platform:
- cowork: 2,398 (84%) — heavily over-represented
- vitto: 333 (12%)
- vscode: 64, claude-code: 22, external: 15, test: 9, cursor: 2
Recommendation:
- Use
upserton agent registration instead ofcreate— key onagentId - Add a TTL index: auto-delete agents not seen in 30 days
- Add a periodic cleanup cron to merge duplicate registrations
- Expected collection size after dedup: ~50-100 unique agents (vs 2,844)
11.3 Session Lifecycle — 434 "Active" Sessions Never Closed
| Age Bucket | Active Sessions |
|---|---|
| Last 24h | 23 |
| Last 7 days | 90 |
| Last 30 days | 258 |
| Older than 30 days | 63 |
63 sessions have been "active" for over 30 days. The session lifecycle (active → completed) is not being triggered.
Root cause: The MCP's setActiveSession() creates sessions but completeSession() is rarely called. Sessions stay "active" indefinitely.
Recommendation:
- Add a session cleanup cron that marks sessions as
completedafter 7 days of inactivity (no new decisions) - Or: auto-complete when a new session starts for the same workspace (only 1 active per workspace)
11.4 Handoff Timing Concerns
| Metric | Value |
|---|---|
| Average completion | 5.8 hours |
| Fastest | 0.6 seconds |
| Slowest | 75.4 hours |
| Completed | 80/130 (61.5%) |
| Expired | 36/130 (27.7%) |
| Rejected | 14/130 (10.8%) |
27.7% of handoffs expire — they're never picked up. The 75-hour max suggests some handoffs sit unclaimed for days.
Recommendation:
- Set default
expiresAtto 4 hours instead of unlimited - Add escalation: if not acknowledged in 30 minutes, re-route to a different agent type
- Add a dashboard metric for handoff SLA (target: 80% acknowledged within 15 minutes)
11.5 ai-backups Retention
ai-backups contains 5.8 MB of pre-v11 migration data:
decisions_pre_v11: 11,585 docssessions_pre_v11: 137 docsgolden_decisions_pre_v11: 200 docs
This data is 2+ months old and was created as a safety net during the v11 schema migration.
Recommendation: Either drop the database (migration is well past) or set a reminder to review in 30 days. This data is not referenced by any service.
11.6 ai_gateway Orphaned Database (Local Only)
The local MongoDB has an ai_gateway database (0.64 MB) with 5 collections containing workflow experiment data (conversations, messages, usage records). No backend currently references this database.
Recommendation: Drop the database from local MongoDB. If the data has historical value, export it first.
11.7 Local vs Remote MongoDB Divergence
Local and remote MongoDB are completely divergent:
- Local: 7 databases, mostly empty (only
ai_gatewayandvitto-mind.codebase-indexhave data) - Remote: 15+ databases with rich data
This means local development never queries real intelligence data. The MCP tools fall back to JSON files, and frontend dashboards show empty states locally.
Recommendation:
- Document the expected local dev experience (file-based only, no MongoDB intelligence)
- Or: add a
MONGODB_CONNECTION_STRINGoverride for dev that points to a read-only replica of remote - Or: create a seed script that populates local MongoDB with sample data for development
11.8 Security: Shared Credentials Across Clusters
All 3 Atlas clusters use the same username/password (paco:31grabThis!@). While acceptable for development, this should be addressed before production:
Recommendation:
- Create separate MongoDB users per backend (e.g.,
backend-ai-user,vitto-user) - Use least-privilege: each user only accesses its own databases
- Rotate credentials and use environment-specific secrets
- Consider MongoDB Atlas RBAC roles for fine-grained access control
11.9 Proactive Alert Investigation
The 2,031 alerts (1,725 critical) deserve deeper investigation:
# Run this to see which checks are generating the most alerts:
mongosh "mongodb+srv://..." --eval "
db['proactive-alerts'].aggregate([
{ \$group: { _id: { check: '\$checkName', severity: '\$severity' }, count: { \$sum: 1 } } },
{ \$sort: { count: -1 } }
])
"
The auto-resolution fix added in this session will help going forward, but the existing 2,031 unresolved alerts should be bulk-resolved or investigated.
11.10 MongoDB Atlas Vector Search Indexes
Both ai-memory.agent_embeddings and vitto-mind.vitto-memories use vector embeddings but require manually created Atlas Vector Search indexes. If these indexes don't exist, semantic search silently falls back to text search or returns no results.
Verification needed:
- Check Atlas UI for
agent_embeddings_vectorindex on ai-memory cluster - Check Atlas UI for
vitto_memories_vectorindex on vitto cluster - If missing, create them per the schema comments in
agent-embedding.schema.tsandvitto-memory.schema.ts
Appendix: Key File References
| Purpose | File |
|---|---|
| AI DB connections (5) | apis/backend-ai-api/src/app/app.module.ts |
| DB name constants | libs/libs-api/backend-core/src/lib/config/database-names.config.ts |
| Connection factory | libs/libs-api/backend-core/src/lib/config/mongodb.factory.ts |
| Vitto DB connection | apis/backend-vitto-api/src/app/app.module.ts |
| Decision service (event emit) | apis/backend-ai-api/src/app/infrastructure/services/decision.service.ts |
| Pattern mining cron | apis/backend-ai-api/src/app/learning/jobs/pattern-mining.job.ts |
| Calibration service | apis/backend-ai-api/src/app/learning/services/calibration.service.ts |
| Episodic memory | apis/backend-ai-api/src/app/super-intelligence/services/episodic-memory.service.ts |
| Vitto memory schema | apis/backend-vitto-api/src/app/mind/schemas/vitto-memory.schema.ts |
| MindService | apis/backend-vitto-api/src/app/mind/services/mind.service.ts |
| Phase executor | apis/backend-vitto-api/src/app/engine/phase-executor.service.ts |
| Delegation manager | apis/backend-vitto-api/src/app/engine/delegation-manager.service.ts |
| Proactive monitor | apis/backend-vitto-api/src/app/proactive/proactive-monitor.service.ts |
| MCP backend client | MCP/mcp-gograb-ai/src/services/backend-client.ts |
| MCP log decision | MCP/mcp-gograb-ai/src/tools/log-decision.ts |
| MCP file storage | MCP/mcp-gograb-ai/src/storage/file-storage.ts |
| Duplicate schemas (delete) | apis/backend-api/src/app/ai-agents/schemas/ |
| Dead schema (delete) | apis/backend-vitto-api/src/app/mind/schemas/user-notification-prefs.schema.ts |
| Env vars | .env.local (lines 47-62) |