ARCHITECTURAL REORGANIZATION PLAN

Documentation for Plans

Architectural Reorganization Plan - Multiverse Platform

Priority: CRITICAL - Foundation First, Design Later
Date: October 26, 2025
Status: IN PROGRESS


Vision Recap

Transform the platform into a true Multiverse Builder:

Multiverse (all spaces)
  └── Space (user's workspace)
      └── Universe (mega-module, deployable)
          └── Galaxy (collection of pages/modules)
              └── Planet/Page (built in Editor)
                  └── Widgets (micro-components)
                      └── Connected to Flows (from Singularity)

Key Principles:

  1. Recursive Modularity: Everything is a module that can contain modules
  2. AI-First: AI assistance at every creation point
  3. Flutter-Ready: Decoupled for cross-platform export
  4. Launch Station: Central hub for deploying universes

Phase 1: Conceptual Model Reorganization (PRIORITY 1)

1.1 Define the Multiverse Hierarchy

Files to Create:

libs/core-models/src/lib/types/multiverse.types.ts

/**
 * Multiverse Architecture Types
 * 
 * Hierarchy:
 * Multiverse → Space → Universe → Galaxy → Planet (Page)
 */

/**
 * Space = User's entire workspace
 * Contains multiple universes that can be deployed independently
 */
export interface Space {
  id: string;
  name: string;
  ownerId: string;
  
  // Metadata
  createdAt: Date;
  updatedAt: Date;
  
  // Settings
  settings: SpaceSettings;
  
  // Universes in this space
  universes: Universe[];
}

export interface SpaceSettings {
  defaultTheme: string;
  aiProvider: 'openai' | 'anthropic' | 'gemini';
  storageLocation: 'local' | 'cloud';
}

/**
 * Universe = Deployable mega-module
 * A complete application that can be launched
 * Can be deployed to its own domain
 */
export interface Universe {
  id: string;
  spaceId: string;
  name: string;
  slug: string;
  description?: string;
  
  // Deployment info
  deploymentStatus: 'draft' | 'building' | 'deployed' | 'failed';
  deployedUrl?: string;
  customDomain?: string;
  
  // Structure
  galaxies: Galaxy[];
  
  // Dashboard (auto-generated)
  dashboardId?: string;
  
  // Metadata
  icon?: string;
  color?: string;
  createdAt: Date;
  updatedAt: Date;
  lastDeployedAt?: Date;
}

/**
 * Galaxy = Collection of related pages/modules
 * Organizational unit within a universe
 */
export interface Galaxy {
  id: string;
  universeId: string;
  name: string;
  slug: string;
  description?: string;
  
  // Structure
  planets: Planet[]; // Pages
  modules: Module[]; // Packaged modules
  
  // Metadata
  icon?: string;
  color?: string;
  category?: string;
  createdAt: Date;
  updatedAt: Date;
}

/**
 * Planet = Page (built in Editor)
 * Individual page with widgets
 */
export interface Planet {
  id: string;
  galaxyId: string;
  name: string;
  slug: string;
  route: string;
  
  // Content
  widgets: Widget[];
  layout: PageLayout;
  
  // Connections
  flows: FlowReference[]; // Singularity flows used on this page
  
  // Metadata
  createdAt: Date;
  updatedAt: Date;
  publishedAt?: Date;
}

/**
 * Module = Packaged collection of planets + flows
 * Created in Modularity, deployed to galaxies
 */
export interface Module {
  id: string;
  name: string;
  description: string;
  version: string;
  
  // Contents (references, not duplicates)
  planets: PlanetReference[];
  flows: FlowReference[];
  
  // Deployment
  baseRoute: string;
  manifest: ModuleManifest;
  
  // Metadata
  createdAt: Date;
  updatedAt: Date;
}

export interface PlanetReference {
  planetId: string;
  planetName: string;
  routeInModule: string;
}

export interface FlowReference {
  flowId: string;
  flowName: string;
  flowType: 'database' | 'logic' | 'workflow' | 'orchestration';
  exposeAsAction: boolean;
  actionName?: string;
}

1.2 Update Existing Models

Files to Modify:

  1. Rename World to Planet (or keep as World but clarify it's a Planet)

    • libs/core-models/src/lib/types/page.types.ts
    • Update all references to World to use new Planet type
    • OR: Keep World but add type alias: export type Planet = World;
  2. Update UniverseGroup to align with new Universe type

    • libs/core-models/src/lib/types/space-map/space-map.types.ts
    • Add deploymentStatus, deployedUrl, customDomain
    • Add dashboardId reference
  3. Update GalaxyGroup to align with new Galaxy type

    • Add modules array
    • Add planets (pages) array

1.3 Create Space Service

Files to Create:

libs/core-angular/src/lib/services/space.service.ts

import { Injectable, inject, signal } from '@angular/core';
import { GgStorage } from '@storage-system';
import { LoggerService } from '@libs-core/log-system';
import { Space, Universe } from '@libs-foundational/core-models';

/**
 * SpaceService
 * Manages the user's entire space (workspace)
 * Contains all universes
 */
@Injectable({
  providedIn: 'root'
})
export class SpaceService {
  private readonly storage = inject(GgStorage);
  private readonly logger = inject(LoggerService);
  
  // Current space (user has one space per account)
  private readonly _currentSpace = signal<Space | null>(null);
  readonly currentSpace = this._currentSpace.asReadonly();
  
  // All universes in current space
  private readonly _universes = signal<Universe[]>([]);
  readonly universes = this._universes.asReadonly();
  
  /**
   * Initialize space for current user
   */
  async initializeSpace(userId: string): Promise<Space> {
    this.logger.info('[SpaceService] Initializing space for user:', userId);
    
    // Try to load existing space
    let space = await this.loadSpace(userId);
    
    // Create space if it doesn't exist
    if (!space) {
      space = await this.createSpace(userId);
    }
    
    this._currentSpace.set(space);
    
    // Load all universes in space
    await this.loadUniverses(space.id);
    
    return space;
  }
  
  /**
   * Create new space for user
   */
  private async createSpace(userId: string): Promise<Space> {
    const space: Space = {
      id: `space_${userId}`,
      name: 'My Space',
      ownerId: userId,
      createdAt: new Date(),
      updatedAt: new Date(),
      settings: {
        defaultTheme: 'dark',
        aiProvider: 'anthropic',
        storageLocation: 'local'
      },
      universes: []
    };
    
    await this.storage.put(`space_${userId}`, space);
    this.logger.info('[SpaceService] Created new space:', space.id);
    
    return space;
  }
  
  /**
   * Load space from storage
   */
  private async loadSpace(userId: string): Promise<Space | null> {
    try {
      const space = await this.storage.get<Space>(`space_${userId}`);
      return space || null;
    } catch (error) {
      this.logger.error('[SpaceService] Failed to load space:', error);
      return null;
    }
  }
  
  /**
   * Load all universes in space
   */
  private async loadUniverses(spaceId: string): Promise<void> {
    try {
      // TODO: Load from storage/backend
      // For now, use existing UniverseManagerService data
      this._universes.set([]);
    } catch (error) {
      this.logger.error('[SpaceService] Failed to load universes:', error);
    }
  }
  
  /**
   * Create new universe in space
   */
  async createUniverse(name: string, description?: string): Promise<Universe> {
    const space = this._currentSpace();
    if (!space) {
      throw new Error('No space initialized');
    }
    
    const universe: Universe = {
      id: `universe_${Date.now()}`,
      spaceId: space.id,
      name,
      slug: name.toLowerCase().replace(/\s+/g, '-'),
      description,
      deploymentStatus: 'draft',
      galaxies: [],
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    // Save universe
    await this.storage.put(`universe_${universe.id}`, universe);
    
    // Update space
    space.universes.push(universe);
    await this.storage.put(`space_${space.ownerId}`, space);
    
    // Update signal
    this._universes.set([...this._universes(), universe]);
    
    this.logger.info('[SpaceService] Created universe:', universe.id);
    
    return universe;
  }
}

Phase 2: Launch Station - Universe Deployment Hub (PRIORITY 2)

2.1 Create Launch Station Library

Command:

cd editor
nx g @nx/angular:library launch-station-lib --directory=libs/launch-station-lib --standalone --importPath=@launch-station-lib

2.2 Launch Station Core Components

Files to Create:

libs/launch-station-lib/src/lib/launch-station.routes.ts

import { Routes } from '@angular/router';

export const LaunchStationRoutes: Routes = [
  {
    path: '',
    loadComponent: () => import('./components/launch-dashboard/launch-dashboard.component')
      .then(m => m.LaunchDashboardComponent),
    title: 'Launch Station - Deploy Universes'
  },
  {
    path: 'deploy/:universeId',
    loadComponent: () => import('./components/deployment-wizard/deployment-wizard.component')
      .then(m => m.DeploymentWizardComponent),
    title: 'Deploy Universe'
  },
  {
    path: 'colonize',
    loadComponent: () => import('./components/colonization-hub/colonization-hub.component')
      .then(m => m.ColonizationHubComponent),
    title: 'Colonize New Universe'
  }
];

libs/launch-station-lib/src/lib/components/launch-dashboard/launch-dashboard.component.ts

/**
 * Launch Station Dashboard
 * Central hub for managing and deploying universes
 * 
 * Features:
 * - View all universes in space
 * - Deploy/undeploy universes
 * - Monitor deployment status
 * - Configure domains
 * - Access analytics
 */
@Component({
  selector: 'lib-launch-dashboard',
  standalone: true,
  imports: [CommonModule, RouterLink],
  template: `
    <div class="launch-station">
      <header class="station-header">
        <h1>🚀 Launch Station</h1>
        <p>Deploy and manage your universes</p>
        
        <button class="btn-colonize" routerLink="/launch-station/colonize">
          <i class="fas fa-plus-circle"></i>
          Colonize New Universe
        </button>
      </header>
      
      <div class="universes-grid">
        @for (universe of universes(); track universe.id) {
          <div class="universe-card" [attr.data-status]="universe.deploymentStatus">
            <div class="card-header">
              <h3>{{ universe.name }}</h3>
              <span class="status-badge" [class]="universe.deploymentStatus">
                {{ universe.deploymentStatus }}
              </span>
            </div>
            
            <div class="card-content">
              <p>{{ universe.description }}</p>
              
              <div class="stats">
                <div class="stat">
                  <span class="label">Galaxies</span>
                  <span class="value">{{ universe.galaxies.length }}</span>
                </div>
                <div class="stat">
                  <span class="label">Pages</span>
                  <span class="value">{{ getTotalPages(universe) }}</span>
                </div>
              </div>
              
              @if (universe.deployedUrl) {
                <a [href]="universe.deployedUrl" target="_blank" class="deployed-link">
                  {{ universe.deployedUrl }}
                  <i class="fas fa-external-link-alt"></i>
                </a>
              }
            </div>
            
            <div class="card-actions">
              @if (universe.deploymentStatus === 'draft') {
                <button class="btn-primary" (click)="deployUniverse(universe)">
                  <i class="fas fa-rocket"></i>
                  Deploy
                </button>
              } @else if (universe.deploymentStatus === 'deployed') {
                <button class="btn-secondary" (click)="manageUniverse(universe)">
                  <i class="fas fa-cog"></i>
                  Manage
                </button>
                <button class="btn-danger" (click)="undeployUniverse(universe)">
                  <i class="fas fa-power-off"></i>
                  Undeploy
                </button>
              }
              
              <button class="btn-ghost" [routerLink]="['/space-map', universe.slug]">
                <i class="fas fa-map"></i>
                View in Space Map
              </button>
            </div>
          </div>
        }
        
        @if (universes().length === 0) {
          <div class="empty-state">
            <i class="fas fa-rocket"></i>
            <h3>No Universes Yet</h3>
            <p>Create your first universe to get started</p>
            <button class="btn-primary" routerLink="/launch-station/colonize">
              Colonize New Universe
            </button>
          </div>
        }
      </div>
    </div>
  `,
  styleUrls: ['./launch-dashboard.component.scss']
})
export class LaunchDashboardComponent implements OnInit {
  private readonly spaceService = inject(SpaceService);
  
  universes = this.spaceService.universes;
  
  async ngOnInit(): Promise<void> {
    // Universes are already loaded by SpaceService
  }
  
  getTotalPages(universe: Universe): number {
    return universe.galaxies.reduce((total, galaxy) => 
      total + (galaxy.planets?.length || 0), 0
    );
  }
  
  deployUniverse(universe: Universe): void {
    // Navigate to deployment wizard
    this.router.navigate(['/launch-station/deploy', universe.id]);
  }
  
  manageUniverse(universe: Universe): void {
    // TODO: Open universe management panel
  }
  
  undeployUniverse(universe: Universe): void {
    // TODO: Undeploy universe
  }
}

2.3 Colonization Hub (New Universe Creator)

libs/launch-station-lib/src/lib/components/colonization-hub/colonization-hub.component.ts

/**
 * Colonization Hub
 * Create new universes with templates and AI assistance
 * 
 * Features:
 * - Start from blank universe
 * - Use pre-built templates
 * - AI-generated universe from description
 * - Bring pre-made tools (Editor, Singularity, Modularity)
 */
@Component({
  selector: 'lib-colonization-hub',
  standalone: true,
  template: `
    <div class="colonization-hub">
      <header>
        <h1>🌌 Colonize New Universe</h1>
        <p>Choose how to start your new universe</p>
      </header>
      
      <div class="creation-methods">
        <!-- Blank Universe -->
        <div class="method-card" (click)="createBlankUniverse()">
          <i class="fas fa-file-alt"></i>
          <h3>Blank Universe</h3>
          <p>Start from scratch with all tools available</p>
        </div>
        
        <!-- Template -->
        <div class="method-card" (click)="showTemplates()">
          <i class="fas fa-layer-group"></i>
          <h3>From Template</h3>
          <p>Use pre-built universe templates</p>
        </div>
        
        <!-- AI Generation -->
        <div class="method-card" (click)="showAIGenerator()">
          <i class="fas fa-magic"></i>
          <h3>AI-Generated</h3>
          <p>Describe your universe, AI builds it</p>
        </div>
      </div>
      
      @if (showAI()) {
        <div class="ai-generator">
          <textarea 
            [(ngModel)]="aiDescription" 
            placeholder="Describe your universe... (e.g., 'A blog platform with user authentication, post management, and commenting')"
            rows="5"
          ></textarea>
          <button class="btn-primary" (click)="generateWithAI()">
            <i class="fas fa-robot"></i>
            Generate Universe
          </button>
        </div>
      }
    </div>
  `
})
export class ColonizationHubComponent {
  private readonly spaceService = inject(SpaceService);
  private readonly router = inject(Router);
  
  showAI = signal(false);
  aiDescription = signal('');
  
  async createBlankUniverse(): Promise<void> {
    const universe = await this.spaceService.createUniverse('New Universe', 'Created from Launch Station');
    
    // Navigate to Space Map to continue building
    await this.router.navigate(['/space-map', universe.slug]);
  }
  
  showTemplates(): void {
    // TODO: Navigate to template gallery
  }
  
  showAIGenerator(): void {
    this.showAI.set(true);
  }
  
  async generateWithAI(): Promise<void> {
    // TODO: Use AI to generate universe structure
  }
}

Phase 3: Transform Modularity to Packager (PRIORITY 3)

3.1 Simplify Modularity Service

File: libs/modularity-lib/src/lib/services/modularity.service.ts

Changes:

/**
 * ModularityService - Module Packager
 * 
 * DOES:
 * - Select existing pages from Space Map
 * - Select existing flows from Singularity
 * - Package them into deployable modules
 * - Generate module manifests
 * 
 * DOES NOT:
 * - Build UI (use Editor instead)
 * - Create data models (use Singularity instead)
 * - Generate workflows (use Singularity instead)
 */

3.2 Update Module Builder to 3-Tab Interface

File: libs/modularity-lib/src/lib/components/module-builder/module-builder.component.ts

New Structure:

activeTab = signal<'content' | 'logic' | 'deploy'>('content');

tabs = [
  { id: 'content', label: 'Content', icon: 'fa-file-alt', description: 'Select pages' },
  { id: 'logic', label: 'Logic', icon: 'fa-project-diagram', description: 'Select flows' },
  { id: 'deploy', label: 'Deploy', icon: 'fa-rocket', description: 'Configure & deploy' }
];

3.3 Delete Unnecessary Components

Files to Delete:


Phase 4: Enhance Singularity with Dual Modes (PRIORITY 4)

4.1 Add Mode Switcher

File: libs/singularity-lib/src/lib/components/singularity-layout/singularity-layout.component.ts

// Add mode signal
mode = signal<'micro' | 'orchestration'>('micro');

// Mode descriptions
modes = {
  micro: {
    label: 'Micro Mode',
    description: 'Build functions, database schemas, and small flows',
    icon: 'fa-cube'
  },
  orchestration: {
    label: 'Orchestration Mode',
    description: 'Build cross-module workflows and universe-level automations',
    icon: 'fa-cubes'
  }
};

toggleMode(): void {
  this.mode.set(this.mode() === 'micro' ? 'orchestration' : 'micro');
}

4.2 Create Orchestration Canvas

File: libs/singularity-lib/src/lib/components/orchestration-canvas/orchestration-canvas.component.ts

/**
 * Orchestration Canvas
 * Large-scale workflow builder for connecting modules
 * 
 * Features:
 * - Shows modules as high-level blocks
 * - Connect module outputs to inputs
 * - Define universe-level workflows
 * - Event-driven architecture
 */

Phase 5: Update Main App Routes (PRIORITY 5)

File: apps/gograb-space/src/app/app.routes.ts

export const appRoutes: Route[] = [
  // Dashboard
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full'
  },
  
  // Dashboard - Overview of all universes
  {
    path: 'dashboard',
    loadComponent: () => import('./features/dashboard/dashboard.component')
      .then(m => m.DashboardComponent),
    title: 'Dashboard'
  },
  
  // Launch Station - Deploy universes
  {
    path: 'launch-station',
    loadChildren: () => import('@launch-station-lib')
      .then(m => m.LaunchStationRoutes),
    title: 'Launch Station'
  },
  
  // Space Map - Universe/Galaxy/Page structure
  {
    path: 'space-map',
    loadChildren: () => import('@space-map-lib')
      .then(m => m.SpaceMapRoutes),
    title: 'Space Map'
  },
  
  // Editor - Build pages and widgets (universe-scoped)
  {
    path: 'editor/:universeIdentifier',
    loadChildren: () => import('@editor-web-lib')
      .then(m => m.EditorRoutes),
    title: 'Editor'
  },
  
  // Singularity - Build flows and functions (universe-scoped)
  {
    path: 'singularity/:universeIdentifier',
    loadChildren: () => import('@singularity-lib')
      .then(m => m.SingularityRoutes),
    title: 'Singularity'
  },
  
  // Modularity - Package modules
  {
    path: 'modularity',
    loadChildren: () => import('@modularity-lib')
      .then(m => m.ModularityRoutes),
    title: 'Modularity'
  }
];

Implementation Order

Week 1: Conceptual Foundation

  1. ✅ Create multiverse types (multiverse.types.ts)
  2. ✅ Create SpaceService
  3. ✅ Update existing models to align
  4. ✅ Test space initialization

Week 2: Launch Station

  1. ✅ Generate Launch Station library
  2. ✅ Create Launch Dashboard component
  3. ✅ Create Colonization Hub component
  4. ✅ Integrate with app routes
  5. ✅ Test universe deployment flow

Week 3: Modularity Transformation

  1. ✅ Simplify ModularityService (remove builders)
  2. ✅ Update Module Builder to 3-tab interface
  3. ✅ Delete unnecessary components
  4. ✅ Create Page Selector component
  5. ✅ Create Flow Selector component
  6. ✅ Test module packaging

Week 4: Singularity Enhancement

  1. ✅ Add mode switcher to Singularity
  2. ✅ Create Orchestration Canvas component
  3. ✅ Test dual-mode functionality

Week 5: Integration & Testing

  1. ✅ Update all routes
  2. ✅ Test complete workflow (create → build → package → deploy)
  3. ✅ Fix any integration issues
  4. ✅ Update documentation

Week 6: UI Polish (LAST)

  1. ✅ Compact header design
  2. ✅ Galaxy editor enhancements
  3. ✅ Visual improvements across platform
  4. ✅ Responsive design

Success Criteria

Foundation (Weeks 1-5):

Polish (Week 6):


Current Status

Completed:

Next Steps (THIS ORDER):

  1. Create multiverse.types.ts - Define new architecture
  2. Create SpaceService - Manage user workspace
  3. Generate Launch Station library - Central deployment hub
  4. Transform Modularity - From builder to packager
  5. Enhance Singularity - Add dual modes
  6. THEN polish UI

Let's proceed with this order. Should I start with Step 1: Create multiverse.types.ts?