AGENTS MAX

Documentation for Developers

AGENTS-MAX - Full Documentation

DEPRECATED (Session 135): All essential rules have been consolidated into AGENTS.md. This file is archived for historical reference. DO NOT read this file for current rules. Use AGENTS.md + MCP get_conventions() instead.


START HERE - Read this files before starting any task:

NX Library Build System - Critical Rules:

🔧 TypeScript Library Configuration (MANDATORY)

Rule 1: NEVER use rootDir in library tsconfig.lib.json

Problem: TypeScript libraries with rootDir: "./src" emit declarations to dist/lib/src/index.d.ts, but ng-packagr and other consumers expect them at dist/lib/index.d.ts, causing module resolution failures.

// ❌ WRONG - DO NOT DO THIS:
{
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "../../../dist/libs/my-lib"
  }
}

// ✅ CORRECT - Always use this:
{
  "compilerOptions": {
    "outDir": "../../../dist/libs/my-lib"
    // NO rootDir - TypeScript infers it correctly
  }
}

Rule 2: Use Custom Builder for Consistency

All libraries should use the custom build-angular-library.js builder for consistent output structure:

// In project.json
{
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "outputs": ["{workspaceRoot}/dist/libs/<path-to-lib>"],
      "options": {
        "command": "node tools/scripts/build/build-angular-library.js <lib-path>"
      },
      "configurations": {
        "production": {
          "command": "node tools/scripts/build/build-angular-library.js <lib-path>"
        }
      },
      "defaultConfiguration": "production",
      "dependsOn": ["^build"],
      "cache": true,
      "parallelism": true
    }
  }
}

Why? The custom builder ensures:

Rule 3: Always Export Through Public API

Problem: Components/services/manifests existing in library but not exported through src/index.ts cause "no exported member" errors.

Solution: Always export everything through the library's public API:

// libs/my-library/src/index.ts
export * from './lib/my-component';
export * from './lib/my-service';
export * from './lib/my-manifest';  // ✅ Don't forget manifests if we are building a module!
export * from './lib/types';

Rule 4: SCSS Import Paths - Use Correct Structure

Problem: Incorrect SCSS import paths cause "Can't find stylesheet to import" errors.

// ❌ WRONG - Old incorrect path:
@use 'libs/libs-foundational/theme-system/theme-styles/src/lib/styles/global.scss';

// ✅ CORRECT - Use this path:
@use 'libs/theme-system/theme-styles/src/lib/styles/global.scss';

Always verify SCSS imports use the correct library path structure.

🚨 Build Troubleshooting Workflow

When encountering build errors:

  1. Check for rootDir in tsconfig.lib.json

    # Find all libraries with rootDir
    find libs -name "tsconfig.lib.json" -exec grep -l '"rootDir"' {} \;
    
  2. Remove rootDir from affected libraries

    • Edit tsconfig.lib.json and remove the rootDir line
    • Clear caches: nx reset && rm -rf dist/ tmp/
    • Rebuild: nx build <library-name> --skip-nx-cache
  3. Verify output structure

    # Check that index.d.ts is at root level (NOT under /src/)
    ls -la dist/libs/<path-to-lib>/index.*
    

    Expected output:

    dist/libs/<path-to-lib>/
      ├── index.d.ts      ✅ At ROOT level
      ├── index.js
      └── lib/            ✅ Implementation nested
    
  4. Check SCSS import paths

    # Find incorrect SCSS imports
    grep -r "@use 'libs/libs-foundational/theme-system" --include="*.scss"
    
  5. Verify public API exports

    • Check src/index.ts exports all necessary components/services/manifests
    • Rebuild library after adding exports

📊 Quick Reference - Common Errors & Fixes

Error Root Cause Fix
TS2307: Cannot find module '@libs-foundational/core-models' rootDir: "./src" in dependency's tsconfig Remove rootDir, clear cache, rebuild
Module has no exported member 'ComponentName' Missing export in src/index.ts Add export * from './lib/component'
Can't find stylesheet to import Incorrect SCSS path Update to libs/theme-system/...
index.d.ts nested under /src/ in dist Using @nx/js:tsc with rootDir Switch to custom builder OR remove rootDir

💡 Prevention Guidelines

When creating new libraries:

  1. ✅ USE THE LIBRARY GENERATOR SCRIPT (Recommended!)

    yarn create:lib:proper
    # or
    node tools/scripts/create-library.js
    

    This automatically creates libraries with correct configuration.

  2. ✅ DO NOT add rootDir to tsconfig.lib.json

  3. ✅ USE the custom builder in project.json

  4. ✅ EXPORT all public APIs through src/index.ts

  5. ✅ VERIFY output structure after first build

  6. ✅ USE correct SCSS import paths (libs/theme-system/...)

  7. ✅ CLEAR caches after config changes (nx reset)

Build System Documentation:


Editor Monorepo Rules:

🎯 What is GoGrab Space?

GoGrab Space (gograb-space NX App) is the most innovative, powerful, modern, and robust platform for building, organizing, and managing complete platforms (aka "universes") through the use of modules, reusable blocks, and AI-powered vibe coding.

Vision: Become the Ferrari/Lamborghini of visual platform builders and vibe coding tools.


🏗️ Monorepo Architecture

Repository Structure

editor/                              # Current monorepo (production-ready)
├── apps/
│   ├── gograb-space/               # Main platform app (port 5200)
│   ├── gograb-admin/               # Admin dashboard (port 4300)
│   ├── space-admin/                # Space management (port 5300)
│   ├── docs-angular/               # Documentation system (port 5010)
│   └── backend-api/                # Backend API service (port 3000)
├── libs/
│   ├── core/                       # Core TypeScript libraries
│   ├── libs-foundational/          # Foundation libs (core-models, storage-system, etc.)
│   ├── libs-ui/                    # UI component libraries
│   ├── libs-ux/                    # UX enhancement libraries
│   ├── libs-structural/            # Structural components (editor, modularity, etc.)
│   ├── libs-ai/                    # AI integration libraries (gograb-ai, prompt-system)
│   ├── libs-widgets/               # Widget management
│   ├── libs-space/                 # Space management features
│   ├── libs-api/                   # API integration libraries
│   └── theme-system/               # Theme system and styling
├── modules/                         # Modular features directory
│   ├── new-user-management/
│   ├── space-management/
│   └── structural/
└── tools/                          # Build scripts and utilities
    └── scripts/
        ├── build/                  # Custom build system
        └── create-library.js       # Library generator

Important Path Mappings

All libraries use path aliases defined in tsconfig.base.json:

⚠️ Critical: Always use these path aliases, never relative paths across library boundaries.


🧩 Module System Architecture

Core Philosophy

GoGrab Space uses a modular architecture where every feature is a self-contained, reusable module that:

Module Contract System

Current Standard: BrowserModuleContract from @libs-core/module-base

// Module implementation example
export class MyModule implements BrowserModuleContract {
  readonly moduleId = 'my-module';
  readonly manifest: ModuleManifest = { /* ... */ };
  
  async configure(config: ModuleConfiguration): Promise<void> { /* ... */ }
  async initialize(): Promise<void> { /* ... */ }
  async start(): Promise<void> { /* ... */ }
  async stop(): Promise<void> { /* ... */ }
  async destroy(): Promise<void> { /* ... */ }
}

Key Module Libraries

  1. @libs-core/module-base - Core module contracts and interfaces
  2. @libs-core/action-registry - Inter-module communication
  3. @libs-core/event-system - Event-driven architecture
  4. @storage-system - Persistent storage
  5. @libs-foundational/core-models - Shared type definitions

Module Communication Patterns

// Action Registry (inter-module communication)
actionRegistry.registerAction('my-module', 'doSomething', async (params) => {
  // Handle action
});

// Event Bus (reactive events)
eventBus.emit('module:loaded', { moduleId: 'my-module' });

// Storage System (persistent state)
storage.set('module:my-module:config', config);

For more information regarding the module system, for example how to create a new module, how to register a module, how to communicate between modules, how to store data in the module, etc., follow this documentation:


🎨 Angular Architecture Rules

Component Structure

Workflow Rules:

Follow this documentation when we start a new workflow: WORKFLOW RULES (all docs inside)

Ai Agent Instructions: Follow this documentation when we start a new ai agent: AI AGENT INSTRUCTIONS (all docs inside)

Github Rules:

Do not commit, nor push to github, unless the user asks you to do so.

MANDATORY: Use Angular 20+ Standalone API - NO NgModules

// ✅ CORRECT: Standalone component
@Component({
  selector: 'app-my-component',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './my-component.component.html',
  styleUrl: './my-component.component.scss'
})
export class MyComponent { }

// ❌ WRONG: Using NgModule
@NgModule({ declarations: [MyComponent] })
export class MyModule { }

File Separation

ALWAYS keep files separate - NO inline templates or styles:

my-component/
├── my-component.component.ts      # Logic only
├── my-component.component.html    # Template only
├── my-component.component.scss    # Styles only
└── my-component.component.spec.ts # Tests only

Type Definition Rules

CRITICAL: Never define types locally in components or services!

// ❌ WRONG: Defining types in component
@Component({...})
export class MyComponent {
  interface MyData { id: string; }  // DON'T DO THIS
}

// ✅ CORRECT: Types in models directory
// libs/my-lib/src/lib/models/my-data.model.ts
export interface MyData { id: string; }

// Then import
import { MyData } from '../models';

Why? Prevents build errors like "Cannot destructure property" and promotes reusability.


💾 Storage System Architecture

Flash Persistence System

GoGrab Space uses an advanced flash-persistence system for instant state synchronization:

// Services automatically persist state
@Injectable()
export class MyService {
  private storage = inject(GgStorage);
  
  async saveState(state: MyState) {
    // Flash persistence: instant sync across tabs/sessions
    await this.storage.set('my-state', state);
  }
}

Storage Layers

  1. In-Memory Cache - Instant access (< 1ms)
  2. IndexedDB - Browser persistence (< 10ms)
  3. Backend Sync - Cloud synchronization (async)
  4. Flash Updates - Real-time cross-tab sync

🔄 Reactive Programming Rules (MANDATORY)

State Management Hierarchy

Use this priority order for all state management:

  1. Angular Signals (preferred for synchronous state)
  2. RxJS Observables (for async operations)
  3. autoFlashState (for persisted reactive state)

❌ NEVER Use Promises

Promises are FORBIDDEN in this codebase. Always use RxJS Observables instead.

// ❌ WRONG - Using Promises
async loadTheme(themeId: string): Promise<Theme> {
  const theme = await this.storage.get(themeId);
  return theme;
}

// ✅ CORRECT - Using RxJS
loadTheme(themeId: string): Observable<Theme> {
  return from(this.storage.get(themeId)).pipe(
    catchError(error => {
      this.logger.error('Failed to load theme:', error);
      return of(null);
    })
  );
}

❌ NEVER Use setTimeout

Use RxJS timer() or delay() instead of setTimeout:

// ❌ WRONG
setTimeout(() => this.doSomething(), 1000);

// ✅ CORRECT
timer(1000).pipe(
  takeUntilDestroyed(this.destroyRef)
).subscribe(() => this.doSomething());

✅ Use autoFlashState for Persisted State

// ✅ CORRECT - Flash-persisted reactive state
readonly activeThemeId = autoFlashState<string | null>('active-theme-id', null, {
  database: 'theme-system',
  collection: 'preferences',
  priority: 'critical',
  ttl: 90 * 24 * 60 * 60 * 1000,
  debounceMs: 50
});

// Update state (instant + auto-persisted)
this.activeThemeId.set(newThemeId);

✅ Converting Legacy Promises to RxJS

When working with APIs that return Promises, wrap them with from():

// Converting Promise-based storage to Observable
loadFromStorage(key: string): Observable<Data> {
  return from(this.storage.get(key)).pipe(
    map(data => data ?? defaultValue),
    catchError(() => of(defaultValue))
  );
}

Why RxJS Over Promises?

  1. Cancellation - Observables can be cancelled with takeUntil/takeUntilDestroyed
  2. Operators - Rich transformation pipeline (map, filter, switchMap, etc.)
  3. Consistency - Angular's HttpClient, Router, Forms all use Observables
  4. Memory Management - Automatic cleanup with takeUntilDestroyed
  5. Composability - Easy to combine multiple async streams

Backend API Integration

All backend communication goes through @libs-api/* libraries:

// Backend API structure
apis/backend-api/
├── src/
│   ├── modules/
│   │   ├── auth/
│   │   ├── storage/
│   │   ├── universes/
│   │   └── widgets/
│   └── main.ts

Port: 3000 (configurable via environment)


🎨 Theme System

Theme Architecture

Location: libs/theme-system/

SCSS Import Paths (Critical - See NX Library Build System section):

// ✅ CORRECT
@use 'libs/theme-system/theme-styles/src/lib/styles/global.scss';

// ❌ WRONG
@use 'libs/libs-foundational/theme-system/...';  // Old path, deprecated

Theme System Rules

  1. Never override theme colors directly

    • Use theme utilities and CSS variables
    • Extend capabilities, don't override
  2. Use CSS Variables for styling (NOT @Input())

    :host {
      --component-bg: var(--ux-surface);
      --component-text: var(--ux-text-primary);
    }
    
  3. Theme System Libraries:

    • @theme-system/theme-styles - Core styles and mixins
    • @theme-system/theme-runtime - Runtime theme switching
    • @theme-system/cosmic-backgrounds - Visual effects

🤖 AI Integration

⚠️ CRITICAL: Always Analyze gograb-ai Library First

BEFORE making ANY AI-related changes, you MUST:

  1. Read libs/libs-ai/gograb-ai/src/lib/models/ai-models.ts - Contains all verified AI model definitions
  2. Read docs/english/GoGrab-Space/libs/libs-ai/gograb-ai/gograb-ai.md - Comprehensive AI documentation
  3. Check existing services in @libs-ai/gograb-ai-lib for reusable functionality

Why? The gograb-ai library contains:

When working on backend AI (apis/backend-api/src/app/ai/):

AI-Powered Features

GoGrab Space includes extensive AI integration:

  1. @libs-ai/gograb-ai-lib - Core AI services (START HERE for AI work)
  2. @libs-ai/prompt-system - Intelligent prompting
  3. @libs-ai/ai-data-connector - Data analysis

Vibe Coding

Philosophy: Build through natural language and visual interfaces

// AI can understand module manifests to generate code
const manifest: ModuleManifest = {
  id: 'my-feature',
  name: 'My Feature',
  actions: [/* AI-discoverable actions */],
  widgets: [/* AI-composable widgets */]
};

AI Training Goals


🛠️ Development Workflow

Port Configuration

Default Ports (Multi-monorepo setup):

Node Configuration:

NODE_OPTIONS="--max-old-space-size=8192 --max-listeners=30"

Common Commands

# Development
yarn serve:gograb-space       # Start gograb-space (port 5200)
yarn serve:docs              # Start documentation (port 5010)
yarn serve:backend-api       # Start backend API (port 3000)

# Building
yarn build:all               # Build all projects
yarn build:libs:auto         # Build libraries only
yarn build:apps:auto         # Build apps only

# Library Management
yarn create:lib:proper       # Create new library (RECOMMENDED)
yarn fix:libs                # Fix library issues

# Documentation
yarn docs:scan               # Scan and update docs manifest

Build System Best Practices

  1. Always clear caches after config changes:

    nx reset && rm -rf dist/ tmp/
    
  2. Use --skip-nx-cache when debugging build issues:

    nx build my-lib --skip-nx-cache
    
  3. Verify build outputs:

    ls -la dist/libs/<category>/<lib-name>/index.*
    # Should see: index.d.ts, index.js at ROOT level
    

📚 Documentation System

Active Documentation Root

Location: docs/ (configured in apps/docs-angular/docs-config.ts)

For more information regarding the documentation system, for example how to write documentation, how to find documentation, how to organize documentation, etc., follow this documentation: DOCS INSTRUCTIONS


🔄 gograb-modules Monorepo Sync

Two-Team Structure

  1. Editor Monorepo (current) - Production platform
  2. gograb-modules Monorepo (external) - Module system R&D

Key Sync Areas

The gograb-modules team leads innovation in:

Sync Strategy: Analyze docs/english/GoGrab-modules/ for latest patterns and architectural decisions.

Integration Status

Current State: This editor monorepo has:

Route Strategy Decision: Static routes with modular components provides better control than fully dynamic manifest-based routing.


⚠️ Common Pitfalls & Solutions

1. Module Resolution Errors

Problem: Cannot find module '@libs-foundational/core-models'
Solution: Remove rootDir from tsconfig.lib.json, clear cache, rebuild

2. Missing Exports

Problem: Module has no exported member 'MyComponent'
Solution: Add export to library's src/index.ts

3. SCSS Import Errors

Problem: Can't find stylesheet to import
Solution: Use correct path libs/theme-system/... (not libs/libs-foundational/...)

4. Build Cache Issues

Problem: Changes not reflecting in build
Solution: nx reset && rm -rf dist/ tmp/

5. Linter Errors After Edits

Problem: TypeScript errors after file changes
Solution: Check running serve process logs (DON'T use build command to check)


🎯 Goals & Vision

Platform Goals

GoGrab Space aims to become:

  1. Most powerful platform builder on the planet
  2. Most intelligent visual development environment
  3. Ultimate vibe coding experience (Ferrari/Lambo level)
  4. AI-first development platform

Technical Goals

Current Challenges

  1. Routing Strategy: Static vs. manifest-based (currently using static)
  2. Module Discovery: Balancing automation vs. control
  3. Cross-Monorepo Sync: Keeping patterns aligned with gograb-modules

🎨 Design System Guidelines

MANDATORY: Use Theme System for All Styling

All components must use the design system patterns from docs/english/GoGrab-Space/theme-system/design/:

  1. Read Design Docs First:

    • design-prompts.md - Core design patterns (glassmorphism, gradients, animations)
    • admin-panel-design-system.md - Panel, card, button, form patterns
  2. Required Design Patterns:

    • Glassmorphism: backdrop-filter: blur(16px), semi-transparent backgrounds
    • Gradient Accents: Use linear-gradient(135deg, var(--ux-primary), var(--ux-secondary)) for primary
    • Micro-interactions: Hover effects with translateY(-2px) and enhanced shadows
    • Border Radius: 20px for panels, 12px for buttons, 16px for cards
  3. **Follow our theme system design system for all styling: theme-system


🔲 Modal System Guidelines

MANDATORY: Use UX Portal for Modals

DO NOT use traditional modal services. Always use the UX Portal system.

Documentation: docs/english/GoGrab-Space/libs/libs-ui/ux-portal/modal-using-portal.md

Implementation Pattern:

import { UxPortalService } from '@libs-ux/ux-portal';
import { UxPortalConfig } from '@libs-ux/ux-portal';

// 1. Inject service
private readonly portalService = inject(UxPortalService);

// 2. Setup global handlers BEFORE opening portal
private setupModalHandlers(): void {
  (window as any).closeModal = () => {
    this.portalService.closePortal('modal-id');
  };
  (window as any).submitForm = (data: any) => {
    this.handleSubmit(data);
  };
}

// 3. Open portal with inline HTML
async openModal(): Promise<void> {
  this.setupModalHandlers();  // CRITICAL: Setup handlers FIRST!
  
  const config: UxPortalConfig = {
    id: 'modal-id',
    content: { type: 'string', data: this.getModalHTML() },
    backdrop: { type: 'modal', enabled: true, blur: 8 },
    container: { mode: 'modal', closeOnEscape: true },
    positioning: { strategy: 'center' }
  };
  
  this.portalService.openPortal(config);
}

Common Issues:


🧩 Existing Library Usage

ALWAYS check for existing libraries before creating new functionality:

  1. Modals/Dialogs: Use @libs-ux/ux-portal (NOT traditional modal services)
  2. Storage: Use @storage-system with GgStorage and autoFlashState
  3. Logging: Use @libs-core/log-system with LoggerService
  4. Events: Use @libs-core/event-system
  5. Actions: Use @libs-core/action-registry

General Guidelines for working with Nx

Connection Rules: