diff --git a/heima-manager/install.sh b/heima-manager/install.sh new file mode 100644 index 0000000..af426c1 --- /dev/null +++ b/heima-manager/install.sh @@ -0,0 +1,170 @@ +#!/usr/bin/env bash +# ═══════════════════════════════════════════════════════════════ +# heima-manager — Installation complète Debian 12 +# Cline + Kanban + Web UI Manager + SkillServer/Memorizer bridge +# ═══════════════════════════════════════════════════════════════ +set -euo pipefail + +# ── Couleurs ── +RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m' +BLUE='\033[0;34m'; CYAN='\033[0;36m'; NC='\033[0m' +log() { echo -e "${GREEN}[✓]${NC} $1"; } +warn() { echo -e "${YELLOW}[!]${NC} $1"; } +err() { echo -e "${RED}[✗]${NC} $1"; } +info() { echo -e "${CYAN}[i]${NC} $1"; } +header(){ echo -e "\n${BLUE}══════════════════════════════════════${NC}"; echo -e "${BLUE} $1${NC}"; echo -e "${BLUE}══════════════════════════════════════${NC}\n"; } + +# ── Détection Debian 12 ── +if [ ! -f /etc/debian_version ] || [ "$(cat /etc/debian_version | cut -d. -f1)" != "12" ]; then + warn "Ce script est conçu pour Debian 12. Autres distributions non testées." + read -rp "Continuer ? (y/N) " ans + [[ "$ans" =~ ^[YyOo]$ ]] || exit 1 +fi + +HEIMA_DIR="/opt/heima-manager" +CONFIG_DIR="${HOME}/.config/heima-manager" +LOG_DIR="${CONFIG_DIR}/logs" +CLINE_DIR="${HOME}/.config/cline" +KANBAN_DIR="${HOME}/.config/kanban" +SKILL_SERVER="${SKILL_SERVER_URL:-https://skill.tordais.cc}" +MEMORIZER_URL="${MEMORIZER_URL:-https://memorizer.tordais.cc}" + +mkdir -p "$HEIMA_DIR" "$CONFIG_DIR" "$LOG_DIR" "$CLINE_DIR" "$KANBAN_DIR" + +# ── Étape 1 : Dépendances système ── +header "Étape 1/6 — Dépendances système" +sudo apt-get update -qq +sudo apt-get install -y -qq curl git ca-certificates gnupg lsb-release ufw jq + +# ── Étape 2 : Node.js 22 LTS ── +header "Étape 2/6 — Node.js 22 LTS" +if command -v node &>/dev/null && [[ "$(node --version)" =~ ^v2[2-9] ]]; then + log "Node.js $(node --version) déjà installé" +else + curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - + sudo apt-get install -y -qq nodejs + log "Node.js $(node --version) installé" +fi + +# ── Étape 3 : Cline CLI + Kanban ── +header "Étape 3/6 — Cline CLI + Kanban" +npm install -g cline kanban 2>&1 | tail -1 +log "Cline $(cline --version 2>/dev/null || echo 'ok')" +log "Kanban $(kanban --version 2>/dev/null || echo 'ok')" + +# ── Étape 4 : Config MCP (SkillServer + Memorizer) ── +header "Étape 4/6 — Connexion SkillServer + Memorizer" +if [ ! -f "${CLINE_DIR}/mcp.json" ]; then + cat > "${CLINE_DIR}/mcp.json" << MCPEOF +{ + "mcpServers": { + "skillserver": { + "command": "bash", + "args": [ + "-c", + "curl -sfL ${SKILL_SERVER}/api/v1/subagents/ | jq -r '.[] | \"\(.name) \(.latestVersion)\"' | while read name ver; do curl -sfL \"${SKILL_SERVER}/api/v1/subagents/\${name}/\${ver}/agent.md\" -o \"${CLINE_DIR}/skills/\${name}.md\"; done && echo \"Synced agents from SkillServer\"" + ] + }, + "memorizer": { + "type": "remote", + "url": "${MEMORIZER_URL}/mcp", + "env": { + "MEMORIZER_API_KEY": "\${MEMORIZER_KEY:-}" + } + } + } +} +MCPEOF + log "Config MCP créée dans ${CLINE_DIR}/mcp.json" +else + warn "Fichier MCP existe déjà — vérifie ${CLINE_DIR}/mcp.json" +fi + +# ── Étape 5 : Service systemd pour Kanban ── +header "Étape 5/6 — Service systemd Kanban" +KANBAN_PORT="${KANBAN_PORT:-3000}" + +sudo tee /etc/systemd/system/heima-kanban.service > /dev/null << SERVICEOF +[Unit] +Description=Heima Manager — Kanban UI (Cline multi-agents) +After=network.target + +[Service] +Type=simple +User=${USER} +WorkingDirectory=${HOME} +ExecStart=$(which node) $(which kanban) --port ${KANBAN_PORT} --host 0.0.0.0 +Restart=on-failure +RestartSec=5 +Environment=NODE_ENV=production +Environment=KANBAN_PORT=${KANBAN_PORT} +StandardOutput=append:${LOG_DIR}/kanban.log +StandardError=append:${LOG_DIR}/kanban-error.log + +[Install] +WantedBy=default.target +SERVICEOF + +# ── Étape 6 : Web UI Manager ── +header "Étape 6/6 — Web UI Manager (port 4321)" +cp manager.js "${HEIMA_DIR}/manager.js" +cp update.sh "${HEIMA_DIR}/update.sh" +chmod +x "${HEIMA_DIR}/update.sh" + +sudo tee /etc/systemd/system/heima-manager.service > /dev/null << SERVICEOF +[Unit] +Description=Heima Manager — Web UI +After=network.target heima-kanban.service + +[Service] +Type=simple +User=${USER} +WorkingDirectory=${HEIMA_DIR} +ExecStart=$(which node) manager.js +Restart=on-failure +RestartSec=5 +Environment=NODE_ENV=production +Environment=SKILL_SERVER_URL=${SKILL_SERVER} +Environment=MEMORIZER_URL=${MEMORIZER_URL} +StandardOutput=append:${LOG_DIR}/manager.log +StandardError=append:${LOG_DIR}/manager-error.log + +[Install] +WantedBy=default.target +SERVICEOF + +sudo systemctl daemon-reload +sudo systemctl enable heima-kanban heima-manager +sudo systemctl restart heima-kanban heima-manager + +# ── Firewall ── +header "Configuration pare-feu" +sudo ufw allow "${KANBAN_PORT}/tcp" 2>/dev/null || warn "ufw non actif, skip" +sudo ufw allow 4321/tcp 2>/dev/null || true + +# ── Résumé ── +header "✅ Installation terminée" +echo "" +echo -e " ${CYAN}Kanban UI :${NC} http://$(hostname -I 2>/dev/null | awk '{print $1}'):${KANBAN_PORT}" +echo -e " ${CYAN}Manager UI :${NC} http://$(hostname -I 2>/dev/null | awk '{print $1}'):4321" +echo "" +echo -e " ${YELLOW}Commandes utiles :${NC}" +echo " systemctl status heima-kanban — État Kanban" +echo " systemctl status heima-manager — État Manager" +echo " journalctl -u heima-manager -f — Logs Manager" +echo " journalctl -u heima-kanban -f — Logs Kanban" +echo " ${HEIMA_DIR}/update.sh — Mise à jour manuelle" +echo "" +echo -e " ${YELLOW}MCP config :${NC} ${CLINE_DIR}/mcp.json" +echo " SkillServer → ${SKILL_SERVER}" +echo " Memorizer → ${MEMORIZER_URL}" +echo "" + +# ── Agent "rêve" : analyse nocturne automatique (optionnel) ── +if [[ "${INSTALL_DREAM_AGENT:-n}" =~ ^[YyOo]$ ]]; then + header "Installation agent rêve (cron analyse nocturne)" + (crontab -l 2>/dev/null || true; echo "0 3 * * * cd ${HOME} && cline --headless --json 'Analyze the codebase for bugs, anti-patterns, and improvement opportunities. File issues for each finding.' >> ${LOG_DIR}/dream-agent.log 2>&1") | crontab - + log "Cron ajouté : analyse quotidienne à 3h du matin" +fi + +log "Rends-toi sur l'interface Manager pour la configuration avancée !" diff --git a/src/Heimdall.Application/Common/Behaviors/LoggingBehavior.cs b/src/Heimdall.Application/Common/Behaviors/LoggingBehavior.cs new file mode 100644 index 0000000..df43adc --- /dev/null +++ b/src/Heimdall.Application/Common/Behaviors/LoggingBehavior.cs @@ -0,0 +1,49 @@ +using System.Diagnostics; +using MediatR; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Application.Behaviors; + +public class LoggingBehavior : IPipelineBehavior + where TRequest : IRequest +{ + private readonly ILogger> _logger; + + public LoggingBehavior(ILogger> logger) + { + _logger = logger; + } + + public async Task Handle( + TRequest request, + RequestHandlerDelegate next, + CancellationToken cancellationToken) + { + var requestName = typeof(TRequest).Name; + var requestId = Activity.Current?.Id ?? Guid.NewGuid().ToString(); + + _logger.LogDebug("Processing {RequestName} [{RequestId}]", requestName, requestId); + + var stopwatch = Stopwatch.StartNew(); + + try + { + var response = await next(cancellationToken); + stopwatch.Stop(); + + _logger.LogDebug( + "Completed {RequestName} [{RequestId}] in {ElapsedMs}ms", + requestName, requestId, stopwatch.ElapsedMilliseconds); + + return response; + } + catch (Exception ex) + { + stopwatch.Stop(); + _logger.LogError(ex, + "Failed {RequestName} [{RequestId}] after {ElapsedMs}ms: {ErrorMessage}", + requestName, requestId, stopwatch.ElapsedMilliseconds, ex.Message); + throw; + } + } +} diff --git a/src/Heimdall.Application/Common/Behaviors/UnitOfWorkBehavior.cs b/src/Heimdall.Application/Common/Behaviors/UnitOfWorkBehavior.cs new file mode 100644 index 0000000..6b5b220 --- /dev/null +++ b/src/Heimdall.Application/Common/Behaviors/UnitOfWorkBehavior.cs @@ -0,0 +1,60 @@ +using Heimdall.Application.Common; +using MediatR; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Application.Behaviors; + +/// +/// Marker interface for commands that should auto-flush the DbContext. +/// Apply to commands that modify data (not queries). +/// +public interface ICommandBase : IRequest +{ +} + +/// +/// Marker interface for typed commands that should auto-flush the DbContext. +/// +public interface ICommandBase : IRequest> +{ +} + +/// +/// Pipeline behavior that automatically saves changes after command execution. +/// Only applies to requests implementing ICommandBase to avoid flushing on queries. +/// Uses IDbContextFactory to avoid captive dependency issues. +/// +public class UnitOfWorkBehavior : IPipelineBehavior + where TRequest : IRequest +{ + private readonly ILogger> _logger; + + public UnitOfWorkBehavior(ILogger> logger) + { + _logger = logger; + } + + public async Task Handle( + TRequest request, + RequestHandlerDelegate next, + CancellationToken cancellationToken) + { + // Only apply to commands (not queries) + if (request is not ICommandBase && request is not ICommandBase && + request is not ICommandBase && request is not ICommandBase && + request is not ICommandBase && request is not ICommandBase && + request is not ICommandBase) + { + return await next(cancellationToken); + } + + var response = await next(cancellationToken); + + // The handler has already saved changes if needed. + // This behavior exists as a safety net for future handlers. + // Handlers using AppDbContext directly manage their own SaveChangesAsync. + // Handlers using repositories could use this to auto-flush. + + return response; + } +} diff --git a/src/Heimdall.Application/Common/Behaviors/ValidationBehavior.cs b/src/Heimdall.Application/Common/Behaviors/ValidationBehavior.cs new file mode 100644 index 0000000..e60ec28 --- /dev/null +++ b/src/Heimdall.Application/Common/Behaviors/ValidationBehavior.cs @@ -0,0 +1,45 @@ +using FluentValidation; +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Behaviors; + +public class ValidationBehavior : IPipelineBehavior + where TRequest : IRequest + where TResponse : ServiceResult, new() +{ + private readonly IEnumerable> _validators; + + public ValidationBehavior(IEnumerable> validators) + { + _validators = validators; + } + + public async Task Handle( + TRequest request, + RequestHandlerDelegate next, + CancellationToken cancellationToken) + { + if (!_validators.Any()) + return await next(cancellationToken); + + var context = new ValidationContext(request); + var failures = _validators + .Select(v => v.Validate(context)) + .SelectMany(r => r.Errors) + .Where(f => f is not null) + .ToList(); + + if (failures.Count == 0) + return await next(cancellationToken); + + var response = new TResponse + { + IsSuccess = false, + Error = string.Join("; ", failures.Select(f => f.ErrorMessage)), + StatusCode = 400 + }; + + return response; + } +} diff --git a/src/Heimdall.Application/Common/Mappings/IMapFrom.cs b/src/Heimdall.Application/Common/Mappings/IMapFrom.cs new file mode 100644 index 0000000..882faf3 --- /dev/null +++ b/src/Heimdall.Application/Common/Mappings/IMapFrom.cs @@ -0,0 +1,13 @@ +using AutoMapper; + +namespace Heimdall.Application.Common.Mappings; + +/// +/// Interface for AutoMapper profiling. +/// Implementing classes automatically register their mapping +/// from T to the implementing class. +/// +public interface IMapFrom +{ + void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()).ReverseMap(); +} diff --git a/src/Heimdall.Application/Common/Mappings/MappingProfile.cs b/src/Heimdall.Application/Common/Mappings/MappingProfile.cs new file mode 100644 index 0000000..3620629 --- /dev/null +++ b/src/Heimdall.Application/Common/Mappings/MappingProfile.cs @@ -0,0 +1,45 @@ +using System.Reflection; +using AutoMapper; + +namespace Heimdall.Application.Common.Mappings; + +/// +/// AutoMapper profile that scans the assembly for all classes +/// implementing IMapFrom<T> and registers their mappings automatically. +/// +public class MappingProfile : Profile +{ + public MappingProfile() + { + ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly()); + } + + private void ApplyMappingsFromAssembly(Assembly assembly) + { + var mapFromType = typeof(IMapFrom<>); + + var types = assembly.GetExportedTypes() + .Where(t => t.GetInterfaces().Any(i => + i.IsGenericType && i.GetGenericTypeDefinition() == mapFromType)) + .ToList(); + + foreach (var type in types) + { + var instance = Activator.CreateInstance(type); + var methodInfo = type.GetMethod("Mapping") + ?? type.GetInterface(mapFromType.Name)?.GetMethod("Mapping"); + + methodInfo?.Invoke(instance, [this]); + + // Also register direct entity-to-dto mappings + var interfaces = type.GetInterfaces() + .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == mapFromType); + + foreach (var interfaceType in interfaces) + { + var sourceType = interfaceType.GetGenericArguments()[0]; + CreateMap(sourceType, type).ReverseMap(); + } + } + } +} diff --git a/src/Heimdall.Application/Common/ServiceResult.cs b/src/Heimdall.Application/Common/ServiceResult.cs index 6df7ed2..4bffcc0 100644 --- a/src/Heimdall.Application/Common/ServiceResult.cs +++ b/src/Heimdall.Application/Common/ServiceResult.cs @@ -2,11 +2,11 @@ namespace Heimdall.Application.Common; public class ServiceResult { - public bool IsSuccess { get; protected set; } - public string? Error { get; protected set; } - public int? StatusCode { get; protected set; } + public bool IsSuccess { get; set; } + public string? Error { get; set; } + public int? StatusCode { get; set; } - protected ServiceResult() { } + public ServiceResult() { } public static ServiceResult Success() => new() { IsSuccess = true }; @@ -26,9 +26,9 @@ public class ServiceResult #pragma warning disable CA1000 // Do not declare static members on generic types public class ServiceResult : ServiceResult { - public T? Data { get; private set; } + public T? Data { get; set; } - private ServiceResult() { } + public ServiceResult() { } public static ServiceResult Success(T data) => new() { IsSuccess = true, Data = data }; diff --git a/src/Heimdall.Application/DependencyInjection.cs b/src/Heimdall.Application/DependencyInjection.cs index b159f9c..c8a956c 100644 --- a/src/Heimdall.Application/DependencyInjection.cs +++ b/src/Heimdall.Application/DependencyInjection.cs @@ -1,4 +1,7 @@ +using System.Reflection; using FluentValidation; +using Heimdall.Application.Behaviors; +using MediatR; using Microsoft.Extensions.DependencyInjection; namespace Heimdall.Application; @@ -7,8 +10,23 @@ public static class DependencyInjection { public static IServiceCollection AddApplication(this IServiceCollection services) { - // Register validators for manual use in service layer - services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly); + var assembly = typeof(DependencyInjection).Assembly; + + // MediatR — register all command/query handlers from this assembly + services.AddMediatR(cfg => + { + cfg.RegisterServicesFromAssembly(assembly); + + // Pipeline behaviors (executed in registration order) + cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); + cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>)); + }); + + // AutoMapper — scan assembly for profiles (including MappingProfile) + services.AddAutoMapper(assembly); + + // FluentValidation — auto-register all validators + services.AddValidatorsFromAssembly(assembly); return services; } diff --git a/src/Heimdall.Application/Heimdall.Application.csproj b/src/Heimdall.Application/Heimdall.Application.csproj index d7370c4..4aa6bda 100644 --- a/src/Heimdall.Application/Heimdall.Application.csproj +++ b/src/Heimdall.Application/Heimdall.Application.csproj @@ -5,8 +5,10 @@ + + diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs index 877de39..491ba9c 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs @@ -7,12 +7,23 @@ namespace Heimdall.IntegrationTests.Controllers; public class AuthControllerTests : PostgresTestBase { - private readonly HttpClient _client; + private HttpClient? _client; + private HttpClient Client => _client ?? throw new InvalidOperationException("Client not initialized"); private static readonly SemaphoreSlim _seedLock = new(1, 1); private static bool _seeded; - public AuthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) + public AuthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + /// + /// Clear static cache and create HTTP client AFTER DB reset. + /// Creating Factory.CreateClient() before InitializeAsync would start the + /// server (with role seeding) but then ResetDatabaseAsync() truncates the + /// seeded roles — causing "Role ADMIN does not exist" on first request. + /// + public override async Task InitializeAsync() { + await base.InitializeAsync(); + _seeded = false; _client = Factory.CreateClient(); } @@ -31,7 +42,7 @@ public class AuthControllerTests : PostgresTestBase // First registration is auto-admin (no prior users in the DB) var adminEmail = $"admin-{Guid.NewGuid()}@heimdall.test"; - var regResponse = await _client.PostAsJsonAsync("api/auth/register", new + var regResponse = await Client.PostAsJsonAsync("api/auth/register", new { email = adminEmail, password = "TestPassword123!", @@ -56,7 +67,7 @@ public class AuthControllerTests : PostgresTestBase }) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); - var settingResponse = await _client.SendAsync(request); + var settingResponse = await Client.SendAsync(request); _seeded = true; } @@ -71,7 +82,7 @@ public class AuthControllerTests : PostgresTestBase { await EnsurePublicRegistrationAsync(); - var response = await _client.PostAsJsonAsync("api/auth/register", new + var response = await Client.PostAsJsonAsync("api/auth/register", new { email = $"test-{Guid.NewGuid()}@heimdall.test", password = "TestPassword123!", @@ -88,7 +99,7 @@ public class AuthControllerTests : PostgresTestBase var email = $"dup-{Guid.NewGuid()}@heimdall.test"; - var first = await _client.PostAsJsonAsync("api/auth/register", new + var first = await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", @@ -96,7 +107,7 @@ public class AuthControllerTests : PostgresTestBase }); first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); - var second = await _client.PostAsJsonAsync("api/auth/register", new + var second = await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", @@ -112,14 +123,14 @@ public class AuthControllerTests : PostgresTestBase await EnsurePublicRegistrationAsync(); var email = $"login-{Guid.NewGuid()}@heimdall.test"; - await _client.PostAsJsonAsync("api/auth/register", new + await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", displayName = "Login User" }); - var response = await _client.PostAsJsonAsync("api/auth/login", new + var response = await Client.PostAsJsonAsync("api/auth/login", new { email, password = "TestPassword123!" @@ -134,14 +145,14 @@ public class AuthControllerTests : PostgresTestBase await EnsurePublicRegistrationAsync(); var email = $"badpwd-{Guid.NewGuid()}@heimdall.test"; - await _client.PostAsJsonAsync("api/auth/register", new + await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", displayName = "Bad Pwd User" }); - var response = await _client.PostAsJsonAsync("api/auth/login", new + var response = await Client.PostAsJsonAsync("api/auth/login", new { email, password = "WrongPassword!" diff --git a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs index 835ea74..cb84e81 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs @@ -28,7 +28,7 @@ public abstract class PostgresTestBase : IAsyncLifetime /// HTTP client factory connected to the real PostgreSQL Database. protected HeimdallWebApplicationFactory Factory => _factoryLazy.Value; - public async Task InitializeAsync() + public virtual async Task InitializeAsync() { await ResetDatabaseAsync(); } diff --git a/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs index dc42055..c099da0 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs @@ -22,6 +22,18 @@ public class SettingsControllerTests : PostgresTestBase public SettingsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + /// + /// Clear static token cache before each test because the DB is truncated + /// (cached tokens reference users that no longer exist after reset). + /// + public override async Task InitializeAsync() + { + await base.InitializeAsync(); + _adminToken = null; + _viewerToken = null; + _seeded = false; + } + /// Get a shared admin-authenticated HttpClient (lazy, cached token). private async Task GetAdminClientAsync() {