# Cross-Module Validation Rules

> **Purpose:** Define FK validation, circular dependency detection, and dependency graph checks
> that must be executed before consolidation approval.

## Module Index Files & Granular Data Loading

For each completed module, read `index.json` and discover granular files:

```javascript
const moduleFiles = {
  entities: "entities.json",
  rules: "rules.json",
  usecases: "usecases.json",
  permissions: "permissions.json",
  screens: "screens.json"
};

for (const module of completedModules) {
  const index = ba-reader.readSection(module.code, "index");
  module.files = index.files;
  // Load only files needed for consolidation
  module.entities = ba-reader.readSection(module.code, "entities");
  module.permissions = ba-reader.readSection(module.code, "permissions");
}
```

## Foreign Key References & Shared Entities Validation

Build entity registry and validate cross-module references:

```javascript
const entityRegistry = {};
for (const module of completedModules) {
  entityRegistry[module.code] = {
    entities: module.entities.map(e => ({
      name: e.name,
      attributes: e.attributes.map(a => a.name),
      pk: e.attributes.find(a => a.name === "Id" || a.unique)?.name || "Id"
    }))
  };
}

// Detect shared entities
const sharedEntities = [];
for (const module of completedModules) {
  for (const entity of module.entities) {
    for (const rel of entity.relationships || []) {
      if (rel.target.includes(".")) {
        const [targetModule, targetEntity] = rel.target.split(".");
        if (!entityRegistry[targetModule]) {
          BLOCKING_ERROR(`Module ${module.code}: references non-existent module "${targetModule}"`);
        }
        sharedEntities.push({
          entity: targetEntity,
          definedIn: targetModule,
          referencedBy: module.code,
          referenceType: rel.type
        });
      }
    }
  }
}
```

## Circular Dependency Detection

```javascript
const cycles = detectCycles(dependencyGraph);
if (cycles.length > 0) {
  BLOCKING_ERROR("Circular dependencies detected:");
  for (const cycle of cycles) {
    ERROR(`  ${cycle.join(" → ")}`);
  }
  ACTIONS: Review dependencies, move shared entities to Core module, or use event-driven communication
  STOP - DO NOT PROCEED
}
```

## Cross-Module Interactions Display

```
═══════════════════════════════════════════════════════════════
  CROSS-MODULE INTERACTIONS VALIDATED
═══════════════════════════════════════════════════════════════

| Source Module | Target | Type | Status |
|---------------|--------|------|--------|
| Orders        | Customers.Customer | FK (N:1) | ✓ RESOLVED |
| Invoices      | Customers.Customer | FK (N:1) | ✓ RESOLVED |

Total: {count} cross-module references
Shared entities: {count}
═══════════════════════════════════════════════════════════════
```
