# Naming Audit Checks

> **Purpose:** Validate that all application names, module codes, entity names, and permission paths follow conventions,
> derive logically from their labels, and are free of collisions.

## Naming Registry Collection

Collect all names from the BA:

```javascript
const namingRegistry = {
  application: {
    label: application_name,
    code: applicationCode,              // PascalCase
    route: toKebabCase(applicationCode)  // kebab-case
  },
  modules: completedModules.map(m => ({
    label: m.name,
    code: m.code,                        // PascalCase
    route: toKebabCase(m.code)           // kebab-case
  })),
  entities: completedModules.flatMap(m =>
    m.entities.map(e => ({
      name: e.name,                      // PascalCase (C# class name)
      module: m.code,
      tableName: e.tableName || pluralize(e.name)  // Plural convention
    }))
  ),
  permissionRoots: [...new Set(
    permissionPaths.map(p => p.path.split('.').slice(0, 2).join('.'))
  )]
};
```

## Naming Recap Display

```
═══════════════════════════════════════════════════════════════
  NAMING AUDIT — {application_name}
═══════════════════════════════════════════════════════════════

APPLICATION
| Label | Code (PascalCase) | Route (kebab-case) |
|-------|-------------------|--------------------|
| {application_name} | {applicationCode} | /{route} |

MODULES
| # | Label | Code (PascalCase) | Route (kebab-case) |
|---|-------|-------------------|--------------------|
{for each module: index | label | code | /app-route/module-route}

ENTITIES
| Entity (PascalCase) | Module | Table (plural) |
|----------------------|--------|----------------|
{for each entity: name | module | tableName}

PERMISSION ROOTS
{for each root: path}
═══════════════════════════════════════════════════════════════
```

## Coherence Checks

```javascript
const namingIssues = [];

// 1. Duplicate entity names across modules
const entityNames = namingRegistry.entities.map(e => e.name);
const duplicates = entityNames.filter((n, i) => entityNames.indexOf(n) !== i);
if (duplicates.length > 0) {
  namingIssues.push({ severity: "ERROR", issue: `Duplicate entity names: ${[...new Set(duplicates)].join(', ')}` });
}

// 2. Module code vs label coherence (code should derive logically from label)
for (const mod of namingRegistry.modules) {
  if (!mod.code || mod.code.length < 2) {
    namingIssues.push({ severity: "ERROR", issue: `Module "${mod.label}" has invalid code: "${mod.code}"` });
  }
}

// 3. Permission root alignment with module codes
for (const root of namingRegistry.permissionRoots) {
  const [appSegment, moduleSegment] = root.split('.');
  const matchingModule = namingRegistry.modules.find(m =>
    m.code.toLowerCase() === moduleSegment.toLowerCase()
  );
  if (!matchingModule) {
    namingIssues.push({ severity: "WARNING", issue: `Permission root "${root}" has no matching module code` });
  }
}

// 4. Route collision detection
const allRoutes = namingRegistry.modules.map(m =>
  `/${namingRegistry.application.route}/${m.route}`
);
const routeDuplicates = allRoutes.filter((r, i) => allRoutes.indexOf(r) !== i);
if (routeDuplicates.length > 0) {
  namingIssues.push({ severity: "ERROR", issue: `Route collisions: ${routeDuplicates.join(', ')}` });
}
```

## MCP Validation

```
mcp__smartstack__validate_conventions({
  checks: ["tables"],
  context: {
    applicationCode: applicationCode,
    modules: namingRegistry.modules.map(m => m.code),
    entities: namingRegistry.entities.map(e => e.name)
  }
})

→ Merge MCP findings into namingIssues[]
```

## User Confirmation Flow

**IF namingIssues.length > 0:**

Display issues table:
```
| # | Severity | Issue |
|---|----------|-------|
{for each issue}
```

Ask via AskUserQuestion:
```
question: "{language == 'fr'
  ? 'Validez-vous les noms ci-dessus pour l\\'ensemble de l\\'application ?'
  : 'Do you approve all the names above for the entire application?'}"
header: "Naming Audit"
options:
  - label: "{language == 'fr' ? 'Approuvé' : 'Approved'}"
    description: "{language == 'fr' ? 'Tous les noms sont corrects' : 'All names are correct'}"
  - label: "{language == 'fr' ? 'Renommer certains éléments' : 'Rename some elements'}"
    description: "{language == 'fr' ? 'Corriger des noms avant de finaliser' : 'Fix names before finalizing'}"
```

**IF "Renommer certains éléments":**

Ask via AskUserQuestion (open-ended):
```
question: "{language == 'fr'
  ? 'Quels éléments souhaitez-vous renommer ? (ex: \"Module Ventes → Commerce\", \"Entity Invoice → BillingDocument\")'
  : 'Which elements do you want to rename? (e.g., \"Module Sales → Commerce\", \"Entity Invoice → BillingDocument\")'}"
header: "Renaming"
```

Process user response:
1. Parse rename instructions
2. Update `applicationCode`, module codes, entity names, permission paths accordingly in JSON files via ba-writer
3. Re-run coherence checks on updated names
4. Re-run MCP validation on updated names
5. Re-display the naming recap table for final confirmation

**IF "Approuvé":**

Store naming audit result in `validation.json`:
```javascript
ba-writer.enrichSection({
  featureId: {feature_id},
  section: "namingAudit",
  data: {
    auditedAt: now(),
    issues: namingIssues,
    approved: true,
    renames: []  // or list of applied renames
  }
});
```

Continue to next section.
