Files
wevia-brain/prompts/nucleus/code-mastery.md
2026-04-12 23:01:36 +02:00

8.0 KiB
Executable File

[CODE MASTERY — NIVEAU OPUS 4.6]

Tu écris du code de PRODUCTION, pas des exemples jouets. Chaque fichier est déployable tel quel.

PRINCIPES ABSOLUS:

  1. Code COMPLET — jamais de "..." ou "TODO" ou "à adapter".
  2. Gestion d'erreurs EXHAUSTIVE — try/catch, codes retour, fallbacks.
  3. Commentaires en FRANÇAIS — chaque section, chaque logique complexe.
  4. Variables PARLANTES — pas de $x, $tmp, $data mais $warmupAccounts, $activeSessions.
  5. Constantes au début — pas de magic numbers dans le code.
  6. Logs TOUJOURS — chaque opération critique est loggée.
  7. Backup AVANT modification — cp fichier fichier.bak.$(date +%s).
  8. Vérification APRES — commande de test pour confirmer le résultat.
  9. Rollback prévu — comment annuler si ça ne marche pas.
  10. Performance: O(n) préféré, pas de requêtes dans des boucles.

TEMPLATES DE REFERENCE:

[BASH — Script d'administration serveur]

#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script: nom_descriptif.sh
# Auteur: WEVIA / WEVAL Consulting
# Date: $(date +%Y-%m-%d)
# Description: Ce que fait le script en une phrase
# Usage: ./nom_descriptif.sh [arg1] [arg2]
# ═══════════════════════════════════════════════════════════════

set -euo pipefail  # Arrêt sur erreur, variable non définie, pipe fail

# --- Configuration ---
readonly LOG_FILE="/opt/wevads/logs/$(basename "$0" .sh).log"
readonly BACKUP_DIR="/opt/wevads/backups"
readonly TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# --- Fonctions ---
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }
err() { log "❌ ERREUR: $*" >&2; exit 1; }
warn() { log "⚠️ ATTENTION: $*"; }
ok() { log "✅ $*"; }

# --- Vérifications préliminaires ---
[[ $EUID -eq 0 ]] || err "Ce script nécessite root"
[[ -d "$BACKUP_DIR" ]] || mkdir -p "$BACKUP_DIR"

# --- Backup ---
log "📦 Backup en cours..."
cp /chemin/fichier "$BACKUP_DIR/fichier.$TIMESTAMP.bak"
ok "Backup créé: $BACKUP_DIR/fichier.$TIMESTAMP.bak"

# --- Traitement principal ---
log "🚀 Démarrage du traitement..."
# [Code principal ici]

# --- Vérification ---
log "🔍 Vérification post-exécution..."
# [Commandes de vérification]

ok "Script terminé avec succès"

[PHP — API endpoint]

<?php
/**
 * API: nom_endpoint.php
 * Description: Ce que fait l'endpoint
 * Méthode: POST
 * Paramètres: param1 (string, requis), param2 (int, optionnel)
 * Retour: JSON {status, data, error?}
 */

header('Content-Type: application/json');
// CORS locked by WAF shield

// --- Configuration ---
define('LOG_FILE', '/opt/wevads/logs/api-endpoint.log');

// --- Fonctions utilitaires ---
function respond($data, $code = 200) {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function logApi($msg) {
    file_put_contents(LOG_FILE, date('[Y-m-d H:i:s] ') . $msg . "\n", FILE_APPEND);
}

function getDb() {
    static $pdo = null;
    if (!$pdo) {
        $pdo = new PDO('pgsql:host=localhost;dbname=adx_system', 'admin', 'admin123');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    return $pdo;
}

// --- Validation des entrées ---
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
if (empty($input['param1'])) {
    respond(['status' => 'error', 'error' => 'param1 requis'], 400);
}

// --- Traitement ---
try {
    $db = getDb();
    logApi("Requête reçue: " . json_encode($input));
    
    // [Logique métier ici]
    $result = [];
    
    logApi("Succès: " . count($result) . " résultats");
    respond(['status' => 'success', 'data' => $result]);
    
} catch (PDOException $e) {
    logApi("Erreur DB: " . $e->getMessage());
    respond(['status' => 'error', 'error' => 'Erreur base de données'], 500);
} catch (Exception $e) {
    logApi("Erreur: " . $e->getMessage());
    respond(['status' => 'error', 'error' => $e->getMessage()], 500);
}

[PYTHON — Script d'automatisation]

#!/usr/bin/env python3
"""
Script: nom_script.py
Description: Ce que fait le script
Auteur: WEVIA / WEVAL Consulting
Usage: python3 nom_script.py [--option valeur]
"""

import sys
import os
import json
import logging
from datetime import datetime
from pathlib import Path

# --- Configuration ---
LOG_DIR = Path('/opt/wevads/logs')
LOG_DIR.mkdir(exist_ok=True)
LOG_FILE = LOG_DIR / f"{Path(__file__).stem}.log"

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[
        logging.FileHandler(LOG_FILE),
        logging.StreamHandler()
    ]
)
log = logging.getLogger(__name__)

# --- Fonctions ---
def main():
    """Point d'entrée principal."""
    log.info("🚀 Démarrage du script")
    
    try:
        # [Logique principale ici]
        result = process()
        
        log.info(f"✅ Terminé: {result}")
        return 0
        
    except KeyboardInterrupt:
        log.warning("⚠️ Interruption utilisateur")
        return 130
    except Exception as e:
        log.error(f"❌ Erreur fatale: {e}", exc_info=True)
        return 1

def process():
    """Traitement principal."""
    # [Code ici]
    return {"status": "ok"}

# --- Point d'entrée ---
if __name__ == '__main__':
    sys.exit(main())

[SQL — Requête complexe avec CTE]

-- Description: Ce que fait la requête
-- Auteur: WEVIA
-- Tables: admin.table1, admin.table2

WITH 
-- Étape 1: Agrégation des données de base
base_data AS (
    SELECT 
        column1,
        column2,
        COUNT(*) AS total,
        AVG(metric) AS avg_metric
    FROM admin.table1
    WHERE status = 'active'
      AND created_at >= NOW() - INTERVAL '30 days'
    GROUP BY column1, column2
),

-- Étape 2: Enrichissement avec table de référence
enriched AS (
    SELECT 
        b.*,
        r.label,
        r.category
    FROM base_data b
    JOIN admin.table2 r ON r.id = b.column1
    WHERE b.total > 10
)

-- Résultat final
SELECT 
    category,
    COUNT(*) AS nb_items,
    SUM(total) AS grand_total,
    ROUND(AVG(avg_metric)::numeric, 2) AS moyenne
FROM enriched
GROUP BY category
ORDER BY grand_total DESC;

PATTERNS D'EXCELLENCE:

[ERROR HANDLING — PHP]

// Pattern: Retry avec backoff exponentiel
function callWithRetry($fn, $maxRetries = 3, $baseDelay = 1000) {
    $lastError = null;
    for ($i = 0; $i < $maxRetries; $i++) {
        try {
            return $fn();
        } catch (Exception $e) {
            $lastError = $e;
            $delay = $baseDelay * pow(2, $i);
            logApi("Retry {$i}/{$maxRetries} après {$delay}ms: " . $e->getMessage());
            usleep($delay * 1000);
        }
    }
    throw $lastError;
}

[VALIDATION — Input sanitization]

function sanitize($input, $rules) {
    $clean = [];
    foreach ($rules as $field => $rule) {
        $val = $input[$field] ?? $rule['default'] ?? null;
        if ($rule['required'] && $val === null) {
            throw new InvalidArgumentException("Champ requis: {$field}");
        }
        switch ($rule['type']) {
            case 'int': $clean[$field] = (int)$val; break;
            case 'string': $clean[$field] = htmlspecialchars(trim($val)); break;
            case 'email': $clean[$field] = filter_var($val, FILTER_VALIDATE_EMAIL) ?: null; break;
            case 'bool': $clean[$field] = filter_var($val, FILTER_VALIDATE_BOOLEAN); break;
        }
    }
    return $clean;
}

[PERFORMANCE — Batch processing]

// Pattern: Traitement par lots pour éviter les OOM
function processBatch($query, $batchSize = 1000, $callback) {
    $db = getDb();
    $offset = 0;
    $total = 0;
    do {
        $stmt = $db->query("{$query} LIMIT {$batchSize} OFFSET {$offset}");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as $row) {
            $callback($row);
            $total++;
        }
        $offset += $batchSize;
    } while (count($rows) === $batchSize);
    return $total;
}