<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Elie NEHME]]></title><description><![CDATA[Découvrez les réflexions d’Élie sur la stratégie technologique, l’architecture logicielle et la transformation par l’IA. Des retours d’expérience et des approches concrètes pour transformer la complexité technique en valeur durable pour l’entreprise.]]></description><link>https://elie29.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/625675fa6386ed96b050e2ec/54407cc0-fa69-4382-9964-6d9c8916822e.png</url><title>Elie NEHME</title><link>https://elie29.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 11 Nov 2026 16:46:10 GMT</lastBuildDate><atom:link href="https://elie29.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[SharedCore: un cœur produit partagé, des modèles de base adaptés, une évolution commune]]></title><description><![CDATA[De 70 à 6 jours pour migrer un client: SharedCore fait converger les clients vers un produit commun, adapté par configuration, jamais par le code]]></description><link>https://elie29.hashnode.dev/sharedcore-un-c-ur-produit-partag-des-mod-les-de-base-adapt-s-une-volution-commune</link><guid isPermaLink="true">https://elie29.hashnode.dev/sharedcore-un-c-ur-produit-partag-des-mod-les-de-base-adapt-s-une-volution-commune</guid><category><![CDATA[software architecture]]></category><category><![CDATA[legacy-systems]]></category><category><![CDATA[migration]]></category><category><![CDATA[SaaS]]></category><category><![CDATA[Product Management]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Mon, 02 Nov 2026 11:31:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/67ae48ba-c8f8-4044-8c51-7098ade59234.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Un éditeur qui sert des centaines de clients avec un logiciel adapté à chacun ne maintient pas un produit, il en maintient des centaines. Pour en sortir, il garde ce qui fonctionne, remplace le reste par un nouveau produit commun et y fait migrer ses clients: ce qui les distingue relève de leur configuration et de leur contrat, jamais du code.</em></p>
<p>Dans un <a href="https://elie29.hashnode.dev/reecrire-un-projet-avec-l-ia-plus-d-une-cinquantaine-de-r-gressions-malgr-une-documentation-compl-te">précédent article</a>, je présentais six stratégies pour sortir d’un système existant avec l’aide de l’IA. La dernière ne ressemblait pas aux autres: elle renonçait à migrer l’ancien système pour faire converger les clients vers un produit unique. Cet article la détaille, pour ceux qui la décident comme pour ceux qui la construisent, et pour les clients à qui elle s’adresse.</p>
<p>Je l’appelle <strong>SharedCore</strong>: elle désigne une stratégie dans laquelle l’éditeur construit et fait évoluer un produit commun avec ses clients, transforme les spécificités légitimes en configurations et refuse la multiplication des versions spécifiques.</p>
<h2>Un produit, des centaines de versions</h2>
<p>Prenons un ERP, un SIRH ou un logiciel de paie. Ces logiciels ont trois points communs. Ils servent plusieurs centaines, parfois plus d’un millier de clients. Ils appliquent une réglementation qui change sans cesse. Et leurs modules sont enchevêtrés: la paie dépend des contrats, qui dépendent des conventions, qui dépendent de la loi.</p>
<p>Au fil des années, chaque client a obtenu des adaptations. Certaines passent par la configuration prévue à cet effet, d’autres par du code écrit pour lui seul, d’autres encore par un mécanisme externe greffé autour du système, et souvent par plusieurs de ces voies à la fois. Chaque adaptation répondait à un besoin réel au moment où elle a été faite. Ensemble, elles ont transformé un produit en une collection de variantes.</p>
<p>Le prix de cette collection se paie à chaque évolution. Une nouvelle obligation légale doit être vérifiée sur chaque variante. Une correction de sécurité doit être appliquée, testée et livrée client par client. Une montée de version devient un projet propre à chaque client, avec sa recette, son calendrier et ses surprises. Et la connaissance de ce que fait réellement le logiciel pour un client donné finit par ne plus exister que dans la mémoire de quelques personnes.</p>
<h2>Pourquoi le statu quo ne tient plus</h2>
<p>Trois pressions rendent ce modèle intenable aujourd’hui.</p>
<p><strong>La première est économique</strong>. Les entités qui éditent ces logiciels doivent améliorer leur rentabilité avec un parc de clients presque stable, donc un chiffre d’affaires presque constant. La marge supplémentaire ne viendra pas des ventes: elle viendra du coût de production, et ce coût est fait des variantes, du code propre à chaque client et des montées de version faites à la main.</p>
<p><strong>La deuxième est réglementaire</strong>. Le Cyber Resilience Act, DORA pour le secteur financier, NIS2 et les autres réglementations imposent de surveiller, de corriger et de mettre en conformité chaque version maintenue. Quand chaque client a sa version, ce travail se multiplie par le nombre de clients, et une version dédiée cesse d’être rentable.</p>
<p><strong>La troisième tient à l’IA</strong>. Elle accélère tout ce qui repose sur un modèle commun et bien décrit, et bute sur ce qui est propre à chaque client et que personne ne documente. Faire évoluer l’écosystème n’est plus une option: l’objectif n’est plus de bricoler ni d’ajouter des couches en périphérie, mais de remettre le produit en état d’évoluer.</p>
<h2>La fausse bonne idée: construire à côté</h2>
<p>Face à un système existant qu’on n’ose plus toucher, la tentation est de construire à côté. Une équipe bâtit une nouvelle plateforme, moderne, bien architecturée, qui se branche sur l’existant et lui ajoute de nouveaux services. L’ancien système, lui, reste en place: on ne le modifie pas, on l’entoure.</p>
<p>Le scénario est courant, et son issue l’est aussi. Après un long effort, la nouvelle plateforme fonctionne, mais peu de clients y ont adhéré. Les autres n’ont aucune raison de bouger: leur logiciel fonctionne, et la migration leur coûte du temps sans rien leur retirer de pénible. Pour l’éditeur, le bilan est pire qu’avant: il maintient désormais l’ancien système, avec toutes ses variantes, et une plateforme de plus.</p>
<p>Ce n’est pas la technique qui a échoué. Une stratégie de remplacement progressif ne rapporte que si le nouveau remplace effectivement l’ancien, morceau par morceau, jusqu’à pouvoir l’éteindre. Une plateforme périphérique qui laisse l’existant intact ne retire rien: elle ajoute un coût, et l’ancien système reste le frein qu’il était.</p>
<p>La convergence, elle aussi, coûte d’abord: pendant la transition, le nouveau produit s’ajoute à l’ancien système. Elle s’en distingue par la suite, car chaque client qui migre retire une part de l’ancien système, jusqu’à pouvoir l’éteindre.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/79b2667f-c65d-4170-bb7a-7d8efe7660c6.svg" alt="Deux panneaux à la même échelle. À gauche, construire à côté: le coût de l’ancien système reste entier et celui de la nouvelle plateforme s’y ajoute, si bien que le coût total finit au-dessus du coût de départ. À droite, converger: le nouveau produit demande d’abord un effort de transition qui s’ajoute à l’ancien système, puis le coût de l’ancien système descend jusqu’à zéro à mesure que les clients migrent, et le coût total finit sous le coût de départ." style="display:block;margin:0 auto" />

<h2>Avant de décider: les questions à trancher</h2>
<p>La réunion qui lance l’évolution d’un système doit poser plusieurs questions, et y répondre, avant de décider quoi que ce soit.</p>
<ol>
<li><strong>Quel est l’objectif? Pourquoi veut-on changer le système?</strong> Adopter une nouvelle technologie, intégrer de l'IA, réécrire un module ou changer d'architecture ne constitue pas un objectif en soi, mais un moyen de l'atteindre. Un objectif définit un résultat concret, mesurable et inscrit dans un délai donné, comme réduire les coûts d'exploitation de 15 % en six mois.</li>
<li><strong>Les clients veulent-ils ce que nous allons leur proposer?</strong> L’a-t-on vérifié auprès d’eux, et à quel niveau de résistance faut-il s'attendre? Un changement que les clients ne veulent pas finit en échec, aussi réussi soit-il sur le plan technique.</li>
<li><strong>Que veut-on faire, précisément?</strong> Quelle fonctionnalité veut-on ajouter, réécrire ou faire évoluer?</li>
<li><strong>Qui l’a demandé, et pour combien de clients?</strong> Une demande portée par un seul client relève de sa configuration, ou de ses propres développements en dehors du produit; une demande partagée par une typologie de clients relève du produit.</li>
<li><strong>Que retire-t-on, et que reste-t-il?</strong> Quelle partie de l’ancien système, quelle version, quel coût disparaît, et que garde-t-on? Retirer ne suffit pas: si, au final, on ne fait que réécrire, même en retirant des choses, les clients n’y gagnent rien.</li>
</ol>
<p>Tant que ces réponses manquent, aucun chantier ne devrait démarrer: ni plateforme, ni réécriture, ni SharedCore.</p>
<h2>L’idée: un seul produit, trois règles</h2>
<p>SharedCore garde intact ce qui fonctionne, le moteur de calcul par exemple, et remplace le reste par un nouveau produit: les clients y migrent, leurs variantes non. Ce produit obéit à trois règles.</p>
<p><strong>Un cœur partagé.</strong> Rien ne se personnalise dans le code: le cœur ne change jamais pour un seul client, et ce qui varie d’un client à l’autre relève de la configuration. Un besoin que la configuration ne couvre pas a trois issues: il devient une fonctionnalité paramétrable, offerte à tous; le client le construit en dehors du produit, sur ses API; ou il n’est pas fait.</p>
<p><strong>Des modèles de base adaptés.</strong> Chaque client part du modèle de base de sa typologie, et le produit a une frontière, que trace une heuristique. Utiliser le produit tel quel, ou le régler avec ses options et ses paramètres, ne compte jamais; modifier ou développer un composant compte. Au-delà d’environ 20% des composants que le produit offre, le client ne relève plus du produit: le modifier à ce point serait de la tierce maintenance applicative (TMA) déguisée, c’est-à-dire du développement sur mesure, qui n’est pas le métier d’un éditeur. Il ne peut la proposer, sous son vrai nom, qu’à titre d’exception fortement justifiée, dans un contrat à part dont elle ne déborde jamais le périmètre. Pour les architectes, elle forme alors un bounded context à part entière, relié au produit par un context mapping explicite et par ses API versionnées: le produit ne change jamais pour elle (voir <a href="https://elie29.hashnode.dev/plus-le-projet-grossit-plus-l-ia-se-trompe">le bounded context comme investissement</a>).</p>
<p><strong>Une évolution commune.</strong> Il n’existe qu’une version, la version tête, et c’est l’éditeur, et non le client, qui décide de son évolution et la met à jour. Que le client l’exploite chez lui (on-premise) ou dans le cloud, il exécute la même version; on-premise, les mises à jour tombent dans des fenêtres convenues à l’avance avec les clients.</p>
<p>Ces trois règles fixent ce que l’éditeur vend: un produit, et non une prestation déguisée en produit. Pour les architectes, elles fixent ce qu’ils construisent: un cœur commun, des modèles de base, un mécanisme de configuration et des API, et non des branches de code par client.</p>
<h2>Le modèle de base, la pièce qui manquait</h2>
<p>La deuxième règle est la pièce qui manque derrière tant de migrations interminables: sans modèle de base unifié, chaque client est reconstruit à partir de zéro, et sa migration reste un projet sur mesure, même quand il a dit oui.</p>
<p>Nous l’avons appris, il y a quelques années, en remplaçant un ancien progiciel de gestion: un client-serveur utilisé à distance par quelque 1 500 clients, qui ne pouvait pas passer au web. L’objectif était économique: supprimer le coût des licences de cet accès à distance. L’obstacle était la migration, estimée à 70 jours de travail par client en moyenne. Le moteur de calcul, qui fonctionnait, est resté tel quel.</p>
<p>Le levier a été le modèle de base: les métiers, les architectes, le support et les clients en ont conçu ensemble plusieurs, chacun adapté à une typologie de client (petites, moyennes, grandes et très grandes entreprises). Nous avons réuni pour cela un panel de 10 à 12 responsables métier issus de clients de tous types, grands clients compris, qui avaient pour la plupart les mêmes problèmes. Ces modèles couvraient 80% des besoins, et 90% des clients ont accepté d’emblée celui de leur typologie, parce qu’il avait été construit avec eux et que les contrats ne se renouvelaient plus que sur le nouveau produit.</p>
<p>Le résultat a changé l’économie de la migration: la reprise d’un client existant, comme l’arrivée d’un nouveau, passait de 70 à 6 jours de personnalisation. Ces 6 jours ne disparaîtront jamais, et ce n’est pas un défaut: ils correspondent à ce qu’aucun modèle ne peut contenir, l’identité du client, ses coordonnées bancaires, ses effectifs et les autres données qui n’appartiennent qu’à lui. Cet objectif économique répondait à la première des trois pressions : la réglementation. Aujourd’hui, l’IA s’ajoute à l’équation, rendant la convergence à la fois plus nécessaire et plus accessible.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/42b4d07a-8e6c-4572-bc73-90c0f7a6741b.svg" alt="Deux barres horizontales sur une échelle de 0 à 70 jours. La reprise d’un client sur un ancien progiciel de gestion demandait 70 jours de travail en moyenne sans modèle de base, 6 jours de personnalisation avec. Ces 6 jours couvrent ce qu’aucun modèle ne peut contenir: l’identité du client, ses coordonnées bancaires, ses effectifs." style="display:block;margin:0 auto" />

<p>Le nouveau produit tient en quatre pièces: le moteur de calcul, sans état, qui n’a jamais été modifié pour un client; le modèle de base, versionné et déployé partout, et la configuration, qui lui disent quoi calculer; les données, que renseignent les 6 jours de personnalisation; et des API versionnées, prévues dès la conception, sur lesquelles le client construit ce que le produit n’offre pas sans que ses développements cassent à chaque mise à jour. Rien de propre à un client n’entre donc dans le code du produit, ce qui rend la première règle tenable.</p>
<p>Les 80% mesurent ce que le modèle couvre tel quel, et non le complément du seuil: l’essentiel du reste se règle avec les options du produit, et le seuil ne compte que ce qui va au-delà.</p>
<p>Deux précautions évitent de recréer le problème sous une autre forme. D’abord, tout ne doit pas devenir paramétrable: un mécanisme de configuration trop puissant devient un second langage de programmation, aussi difficile à tester et à maintenir que le code qu’il remplace. Ensuite, les paramètres doivent venir des variations réellement observées chez les clients, et non de tout ce qui pourrait un jour varier.</p>
<h2>Ce que le client reçoit, et ce qu’il ne reçoit pas</h2>
<p>La version unique ne veut pas dire que tous les clients reçoivent les mêmes fonctionnalités. Elle veut dire que tous reçoivent le même code, et que ce qui est actif pour chacun dépend de son contrat.</p>
<p>Le client n’active rien lui-même: à la négociation du contrat, il commande des modules et, à l’intérieur d’un module, les fonctionnalités dont il a besoin, et c’est le support qui les active. Ce qui n’a pas été commandé n’est pas livré; commandé plus tard, il arrive dans sa dernière version, jamais dans une version ancienne qu’il faudrait d’abord mettre à niveau.</p>
<p>En contrepartie, l’éditeur prend un engagement de mise à jour: chaque module et chaque fonctionnalité livrés sont mis à jour au moins deux fois par an, et chaque fois qu’un incident de sécurité ou une évolution réglementaire l’exige, on-premise comme dans le cloud.</p>
<p>Pour les architectes, chaque module et chaque fonctionnalité s’active ou non par client; Ainsi, l’offre devient lisible: le client paie ce qu’il a commandé, et une nouvelle fonctionnalité qu’il ne veut pas ou ne paie pas n’est pas activée.</p>
<h2>Ce que l’on promet au client</h2>
<p>Un produit, si bien conçu soit-il, ne sert à rien si les clients ne sont pas convaincus qu’il est fait pour leur bien. Le client cesse de financer ses propres montées de version: c’est l’éditeur qui les fait, sur un produit qu’il maîtrise.</p>
<p>Le reste de la promesse tient en cinq mots: résilience, souveraineté, qualité, performance et sécurité. Chacun de ces mots, pourtant, est promis par tous les éditeurs, et un client ne migre pas pour des mots. Il migre pour ce qu’il cesse de payer ou de subir.</p>
<p><strong>La résilience</strong>, c’est un incident corrigé une fois pour tous les clients, au lieu d’un correctif à reproduire sur chaque variante, et une version que l’éditeur connaît parce qu’il n’en exploite qu’une.</p>
<p><strong>La souveraineté</strong>, c’est le choix de l’endroit où vivent les données, chez le client ou dans le cloud, sans rien perdre des engagements de l’éditeur. Ce choix compte: dès qu’il s’agit de données sensibles comme la paie, beaucoup de clients hésitent encore à les confier au cloud, et le on-premise doit rester une option de plein droit.</p>
<p><strong>La qualité</strong>, c’est un client qui exécute la version que l’éditeur a testée, avec une configuration que l’éditeur sait tester, et non un code écrit pour lui seul que plus personne ne connaît.</p>
<p><strong>La performance</strong>, c’est chaque optimisation du produit qui profite d’un coup à tous les clients, sans attendre qu’un projet de montée de version la leur apporte.</p>
<p><strong>La sécurité</strong>, c’est un correctif appliqué par l’éditeur, sur une seule version, dans le délai que la réglementation impose, au lieu d’une faille qui reste ouverte chez le client en attendant sa prochaine recette.</p>
<p>Rares sont les entreprises qui développent encore leur propre CRM: la plupart adoptent un produit et s’y adaptent, et c’est ce que SharedCore demande au client.</p>
<h2>Ce que l’éditeur y gagne</h2>
<p>Pour un éditeur, le retour sur investissement tient à un renversement: l’effort dépend désormais de la taille du produit, et non du nombre de clients.</p>
<p>Chaque correction, chaque évolution réglementaire, chaque mise en conformité se fait une fois et profite à tous.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/11b4fad6-21f0-4543-959a-77f00972bbd2.svg" alt="Deux droites partent du même point: l’effort de maintenance et d’évolution selon le nombre de clients. Avec une version par client, l’effort monte fortement, car chaque client ajoute une variante à corriger, tester et livrer. Avec une seule version, il reste presque plat, car chaque client n’ajoute que ses jours de personnalisation." style="display:block;margin:0 auto" />

<p>Le gain le plus durable est ailleurs. Sans code spécifique ni versions multiples, la dette de connaissance ne se reforme pas, et le produit devient exploitable par l’IA: un modèle commun et une configuration explicite se décrivent, se testent et s’outillent; des centaines de variantes, non.</p>
<h2>Par où commencer: l’inventaire</h2>
<p>Sans IA, la phase la plus longue d’une telle convergence est l’inventaire: savoir ce qui a été modifié chez chaque client, et par quel moyen. L’IA l’accélère: elle recense les écarts au modèle de base, dans la configuration comme dans le code, et s’appuie sur les traces d’exécution pour signaler ce qui ne s’exécute plus, tandis que l’équipe vérifie et décide. On obtient une carte des changements et des clients qui les partagent, d’où se déduit la part de personnalisation de chacun.</p>
<p>Chaque adaptation faite dans le code appelle ensuite une décision. Si plusieurs clients en ont besoin, elle rejoint le produit sous forme de fonctionnalité paramétrable. Si elle ne s’exécute plus, ou si elle ne fait que redire la loi que le produit applique déjà, elle disparaît. Sinon, elle compte dans le seuil de 20%; sous ce seuil, c’est au client de la construire, ou de la faire construire, en dehors du produit, sur ses API et sous sa responsabilité. L’éditeur ne la maintient pas dans le produit, sans quoi il recréerait une version par client.</p>
<p>Inutile d’attendre un inventaire exhaustif: les premiers modèles de base et les premières migrations commencent avec les clients les mieux connus, pendant que l’inventaire se poursuit, pour éviter à la fois la réécriture à l’aveugle et une analyse sans fin.</p>
<h2>Migrer par cohortes, et non client par client</h2>
<p>Avec des centaines de clients, ouvrir un projet de migration par client reproduirait le problème que la stratégie veut résoudre. L’inventaire permet au contraire de regrouper les clients en trois cohortes, selon la manière dont ils ont été personnalisés.</p>
<p><strong>Les clients standards</strong> utilisent le produit tel qu’il est, avec sa configuration. Ils migrent les premiers: leur parcours est le plus court, et c’est sur eux que l’on valide le chemin de migration, l’outillage de reprise des données et les modèles de base.</p>
<p><strong>Les clients personnalisés par le mécanisme interne</strong> ont adapté le produit avec la configuration qu’il prévoit. Leur migration consiste à retrouver leur typologie dans un modèle de base, puis à traduire leurs paramètres dans la nouvelle configuration.</p>
<p><strong>Les clients personnalisés par un mécanisme externe, ou par une modification du système lui-même</strong>, concentrent la complexité. Pour chacun, l’inventaire tranche adaptation par adaptation; ceux qui restent sous le seuil migrent comme les autres, ceux qui le dépassent ne relèvent plus du produit.</p>
<p>La typologie dit vers quel modèle de base un client migre; sa cohorte et l’échéance de son contrat disent quand. L’ordre des cohortes n’est pas seulement technique: chaque client standard qui migre sans difficulté devient une preuve pour les suivants, et chaque cohorte livre au produit ce qui manquait pour la suivante.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/369bcdb1-eceb-4daa-b192-ed120ea74a28.svg" alt="Un axe mesure les composants qu’un client a modifiés ou développés, avec un seuil à 20%. À gauche, le produit, utilisé tel quel ou réglé avec ses options; à droite, le client n’en relève plus, et c’est du sur-mesure, sous son vrai nom s’il est proposé. Les clients standards et ceux du mécanisme interne se placent au début de l’axe, puisque régler le produit ne compte pas; ceux d’un mécanisme externe ou d’un système modifié s’étendent de part et d’autre du seuil: pour eux, l’inventaire décide." style="display:block;margin:0 auto" />

<h2>La fermeté, condition du succès</h2>
<p>Reste la question que tout le monde se pose: que faire des clients qui ne veulent pas suivre?</p>
<p>Puisque plus aucun contrat ne se signait sur l’ancien système, il ne vivrait plus que le temps du dernier contrat, cinq ans au plus: aucun système ne bascule du jour au lendemain. Ses serveurs se sont arrêtés à mesure que les clients les quittaient, quelques-uns tournant en parallèle pendant une période de grâce pour s’assurer de la qualité de la migration, jusqu’à l’arrêt de l’ancien produit: c’est le surcoût de la transition, qui précède la baisse du coût.</p>
<p>Laisser partir quelques clients coûte parfois moins cher que de les conserver dans le produit, où chacun devient une version spécifique supplémentaire à corriger, tester et livrer à chaque évolution. Ce qui compte, ce n’est pas le chiffre d’affaires généré par un client, mais sa rentabilité et le retour sur investissement qu’il permet. Un client qui coûte plus qu’il ne rapporte n’est pas nécessairement un client à conserver. Ces départs sont le prix à payer pour définir une frontière claire au produit, pas un échec.</p>
<p>Cette fermeté n’est tenable qu’à une condition: une offre crédible, et des clients accompagnés. Un modèle de base construit avec les clients, qui couvre l’essentiel de leurs besoins et qui leur évite 64 jours de travail sur 70, se défend. Un produit imposé sans eux ne se défend pas.</p>
<h2>La limite: un changement de modèle économique</h2>
<p>La limite de cette stratégie n’est pas technique. Passer d’un logiciel adapté à chaque client à un produit unique, c’est changer de modèle économique: l’éditeur cesse de vendre de l’adaptation pour vendre un produit et ses mises à jour, sous forme d’abonnement clés en main.</p>
<p>La migration dépend donc d’abord d’un choix stratégique et commercial, que seul le patron de l’entité peut faire. Les architectes peuvent construire le produit; ils ne peuvent pas prendre cette décision à la place de l’entité.</p>
<h2>Quand l’envisager</h2>
<p>SharedCore convient à un produit partagé par de nombreux clients, dont les modules sont trop enchevêtrés pour être remplacés l’un après l’autre, et dont les clients ont été adaptés un à un au fil des années. Elle convient moins à un logiciel construit pour un seul client, ou à un produit déjà standard, qui n’a pas besoin de converger. Faute de pouvoir remplacer les modules un à un, elle suppose un cœur qui peut rester inchangé, alimenté par un modèle: là où les spécificités des clients vivent dans le cœur, il faut d’abord les en sortir pour les faire passer dans le modèle.</p>
<p>Sous cette condition, ce qui a valu pour notre progiciel vaut pour un ERP ou un SIRH, qui servent eux aussi des typologies de clients récurrentes; c’est aux métiers de chaque domaine, avec un panel de clients, de définir les critères qui les distinguent.</p>
<table>
<thead>
<tr>
<th>Règle</th>
<th>Ce qu’elle change</th>
</tr>
</thead>
<tbody><tr>
<td>Un cœur partagé</td>
<td>Ce qui distingue un client reste lisible dans sa configuration, et la dette de connaissance ne se reforme pas</td>
</tr>
<tr>
<td>Des modèles de base adaptés</td>
<td>La reprise d’un client est désormais nettement plus rapide et moins coûteuse en personnalisation</td>
</tr>
<tr>
<td>Une évolution commune</td>
<td>Une correction et une mise en conformité profitent à tous les clients, on-premise ou cloud</td>
</tr>
<tr>
<td>Des modules et fonctionnalités activés au contrat</td>
<td>Le client reçoit ce qu’il a commandé, toujours dans sa dernière version</td>
</tr>
<tr>
<td>Un seuil heuristique de 20%</td>
<td>Au-delà, le client ne relève plus du produit</td>
</tr>
<tr>
<td>Un inventaire assisté par l’IA, puis des cohortes</td>
<td>La migration se pilote par groupes de clients, et non client par client</td>
</tr>
</tbody></table>
<h2>Conclusion</h2>
<p>Un éditeur qui maintient une version par client ne fait plus vraiment son métier d’éditeur. Il finance, sur sa marge, des adaptations que personne ne facture, et il porte seul le coût de réglementations qui exigent de surveiller chaque version maintenue.</p>
<p>La sortie ne passe pas par une plateforme de plus. Elle passe par SharedCore: un cœur partagé, qui ne change jamais pour un seul client; des modèles de base adaptés à chaque typologie et construits avec les clients; une évolution commune, gérée par l’éditeur; et la fermeté de ne plus faire de sur-mesure sous le nom de produit.</p>
<p><strong>Le modèle de base n’est pas un compromis imposé aux clients: c’est ce qui leur permet de recevoir, enfin, ce que l’éditeur sait faire de mieux.</strong></p>
<hr />
<h2>Articles similaires</h2>
<ul>
<li><a href="https://elie29.hashnode.dev/reecrire-un-projet-avec-l-ia-plus-d-une-cinquantaine-de-r-gressions-malgr-une-documentation-compl-te">Réécrire un projet avec l’IA: plus d’une cinquantaine de régressions malgré une documentation complète</a></li>
<li><a href="https://elie29.hashnode.dev/plus-le-projet-grossit-plus-l-ia-se-trompe">Plus le projet grossit, plus l’IA se trompe: le bounded context comme investissement</a></li>
</ul>
<h2>Restons en contact</h2>
<p>Pour suivre mes prochains articles ou en discuter:</p>
<ul>
<li>X: <a href="https://x.com/elie_nehme">@elie_nehme</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/elie-nehme/">Elie Nehmé</a></li>
<li>GitHub: <a href="https://github.com/elie29">elie29</a></li>
<li>Site web: <a href="https://elienehme.fr">elienehme.fr</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Réécrire un projet avec l’IA: plus d’une cinquantaine de régressions malgré une documentation complète]]></title><description><![CDATA[Une réécriture assistée par l’IA, livrée avec plus de 50 régressions malgré code, documentation et tests: ce que cela dit de la dette de connaissance]]></description><link>https://elie29.hashnode.dev/reecrire-un-projet-avec-l-ia-plus-d-une-cinquantaine-de-r-gressions-malgr-une-documentation-compl-te</link><guid isPermaLink="true">https://elie29.hashnode.dev/reecrire-un-projet-avec-l-ia-plus-d-une-cinquantaine-de-r-gressions-malgr-une-documentation-compl-te</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[legacy-systems]]></category><category><![CDATA[Testing]]></category><category><![CDATA[revamping]]></category><category><![CDATA[migration]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Mon, 26 Oct 2026 09:16:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/adc33549-9f46-43ec-b074-3ccc56f0b205.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Un projet qui fonctionnait, une organisation à faire évoluer</h2>
<p>Dans la vie d’un projet logiciel, il arrive un moment où une question organisationnelle devient incontournable: comment assurer durablement la maintenance d’une application lorsqu’une seule personne maîtrise réellement sa mise en œuvre?</p>
<p>C’est précisément le contexte de l’expérience que je souhaite partager.</p>
<p>Le projet initial, écrit il y a quelques années, fonctionnait très bien. Il disposait d’une documentation technique et fonctionnelle complète, de spécifications à jour, d’un historique des évolutions de la base de données, d’une bonne couverture de tests, ainsi que de README détaillés.</p>
<p>Autrement dit, les éléments nécessaires à la compréhension du système étaient disponibles. Il ne s’agissait pas d’une application abandonnée, sans documentation, dont le fonctionnement aurait été entièrement enfoui dans le code source.</p>
<p>Le projet avait connu un véritable succès. Mais son maintien en conditions opérationnelles ne pouvait pas reposer indéfiniment sur une seule personne, incapable d’assurer une disponibilité permanente, 24 heures sur 24 et 7 jours sur 7.</p>
<p>Le besoin de transfert était donc parfaitement légitime.</p>
<p>La difficulté venait de l’organisation: la reprise devait se faire dans une autre stack technique.</p>
<p>Le choix s’est alors porté sur une réécriture assistée par l’intelligence artificielle.</p>
<h2>Tout était disponible pour réussir la réécriture</h2>
<p>La réécriture partait donc de bien davantage qu’un simple dépôt de code: de quoi comprendre les objectifs fonctionnels du logiciel, son organisation technique, ses évolutions et une partie importante des comportements à préserver.</p>
<p>Pourtant, le résultat livré en qualification présentait un design médiocre et plus d’une cinquantaine de régressions, de différents niveaux de gravité.</p>
<p>Ce constat mérite que l’on s’y arrête.</p>
<p>Il ne démontre pas que l’intelligence artificielle est incapable de réécrire un logiciel. Il ne permet pas non plus d’attribuer automatiquement chaque régression à l’IA elle-même: la méthode de travail, les choix d’architecture, les consignes, les contrôles et les décisions humaines interviennent également dans le résultat.</p>
<p>En revanche, il met en évidence un point essentiel: <strong>disposer de toutes les informations nécessaires ne garantit pas qu’elles seront correctement exploitées.</strong></p>
<p>Le code peut être généré. Les fichiers peuvent être produits. Les fonctionnalités peuvent sembler présentes. Et pourtant, le logiciel livré peut s’éloigner sensiblement de celui qu’il était censé remplacer.</p>
<p>La question n’est donc pas seulement de savoir si l’IA sait produire du code. Il faut aussi savoir comment le résultat a été conçu, vérifié et qualifié.</p>
<h2>Réécrire un logiciel n’est pas traduire du code</h2>
<p>L’un des pièges d’une migration technologique consiste à considérer l’application existante comme un modèle qu’il suffirait de reproduire dans un autre langage.</p>
<p>Cette approche peut sembler séduisante. Le système fonctionne déjà, ses fonctionnalités sont connues et la documentation est disponible. Pourquoi ne pas demander à une IA de reconstruire l’ensemble dans la nouvelle stack?</p>
<p>Parce qu’une migration ne se résume pas à reproduire des fichiers ou à transposer des structures de code.</p>
<p>Un logiciel est un ensemble de règles métier, de contrats, de choix d’architecture, de dépendances et de comportements parfois difficiles à percevoir à la seule lecture du code.</p>
<p>Une architecture adaptée à un langage, à son écosystème et à ses mécanismes d’exécution ne constitue pas nécessairement une bonne architecture dans un autre environnement.</p>
<p>Les abstractions, la gestion des erreurs, la concurrence, les mécanismes de validation, les transactions, les bibliothèques et les conventions de développement peuvent différer profondément.</p>
<p>Une réécriture réussie doit donc distinguer deux objectifs:</p>
<ul>
<li>préserver les comportements fonctionnels attendus;</li>
<li>concevoir une implémentation cohérente avec les caractéristiques de la stack cible.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/fe966638-0e43-46d1-8868-75e92ac6cfe3.png" alt="Deux colonnes. À gauche, à préserver: les comportements fonctionnels attendus, les règles métier, les contrats d’API; non formalisés, ils deviennent des régressions. À droite, à concevoir pour la stack cible: l’architecture et les abstractions, la gestion des erreurs et la validation, la concurrence et les transactions, les bibliothèques et les conventions; copiés tels quels, ils deviennent des choix inadaptés." style="display:block;margin:0 auto" />

<p>Reproduire l’architecture existante sans l’évaluer dans le nouvel environnement risque de conserver des choix inadaptés. À l’inverse, réinventer l’architecture sans formaliser les comportements à préserver peut introduire des régressions.</p>
<p>La difficulté est de savoir ce qui doit rester identique et ce qui doit évoluer.</p>
<p>C’est un travail de conception logicielle. L’IA peut y contribuer, mais elle ne dispense pas l’équipe de prendre ces décisions.</p>
<h2>Plus d’une cinquantaine de régressions: que nous apprend la qualification?</h2>
<p>La qualification constitue un moment déterminant dans le cycle de vie d’un logiciel. Elle permet de confronter le résultat livré aux exigences et aux comportements attendus.</p>
<p>À lui seul, ce nombre ne dit pas combien de défauts relevaient de l’architecture, de la logique métier, des interfaces ou des choix d’implémentation. Il faudrait examiner les anomalies une par une pour établir cette répartition.</p>
<p>Mais il montre qu’une réécriture assistée par l’IA peut produire un écart significatif entre le logiciel initial et le résultat livré, même lorsque la documentation et les moyens de vérification sont disponibles.</p>
<p>La question devient alors: à quel moment les écarts auraient-ils dû être détectés?</p>
<p>Une partie aurait-elle pu être identifiée pendant la conception de la nouvelle architecture? D’autres auraient-elles été détectées par des tests de caractérisation, des tests de non-régression ou des revues de code? Certaines traduisaient-elles des exigences mal interprétées malgré leur documentation?</p>
<p>Ce sont ces questions qui permettent de tirer des enseignements opérationnels de l’expérience.</p>
<p>La qualification ne doit pas être considérée comme une formalité venant valider, à la fin, un travail déjà terminé. Elle doit être pensée dès le début de la migration, avec des critères de réussite explicites et des contrôles indépendants.</p>
<p><strong>Le fait qu’un code soit généré par une IA ne constitue ni une preuve de conformité fonctionnelle, ni une garantie de qualité architecturale.</strong></p>
<h2>Et si la documentation n’existait pas?</h2>
<p>C’est ici que cette expérience devient particulièrement intéressante.</p>
<p>Dans notre cas, tout était disponible, et la qualification a pourtant relevé ces régressions.</p>
<p>Que se passerait-il si les conditions étaient beaucoup moins favorables?</p>
<p>Imaginons maintenant un système dont le code est disponible, mais dont les règles métier n’ont jamais été formalisées. Les développeurs historiques connaissent les exceptions, les particularités de certains clients et les raisons de décisions prises plusieurs années auparavant. Une partie de ces connaissances n’existe que dans leur mémoire.</p>
<p>La documentation est incomplète ou obsolète. Les tests couvrent les parcours principaux, mais pas les cas limites. Certains comportements sont connus uniquement parce que l’application fonctionne ainsi depuis des années.</p>
<p>Dans ce contexte, l’IA peut analyser le code, repérer des dépendances, proposer des hypothèses et reproduire des comportements observés.</p>
<p>Mais comment peut-elle préserver une règle métier qui n’est ni documentée, ni testée, ni identifiable dans les traces disponibles?</p>
<p>Comment distinguer un comportement historique volontaire d’un défaut ancien?</p>
<p>Comment savoir qu’une exception apparemment inutile protège en réalité un processus métier critique?</p>
<p>Comment garantir que la nouvelle implémentation répond aux attentes des utilisateurs si ces attentes n’ont jamais été clairement exprimées?</p>
<p>L’IA peut contribuer à reconstituer la connaissance manquante. Elle peut aider à analyser les historiques, à générer des tests exploratoires et à préparer les questions à poser aux experts métier.</p>
<p>Mais elle ne peut pas garantir l’exactitude d’une règle qu’aucune information disponible ne permet d’établir.</p>
<p>Le danger est alors de produire un logiciel techniquement cohérent, propre en apparence et parfaitement compilable, mais fonctionnellement différent de celui que l’entreprise croit avoir remplacé.</p>
<p><strong>Lorsque la connaissance du système est incomplète, le problème n’est plus seulement de produire du code: il faut d’abord découvrir ce que le logiciel doit réellement faire.</strong></p>
<h2>La dette de connaissance: un risque que l’IA ne fait pas disparaître</h2>
<p>On parle beaucoup de dette technique: code difficile à maintenir, architecture vieillissante, dépendances obsolètes ou tests insuffisants.</p>
<p>Mais il existe un autre risque, souvent moins visible: la dette de connaissance.</p>
<p>Elle apparaît lorsqu’une organisation ne maîtrise plus suffisamment les règles métier, les choix historiques et les comportements de son propre système.</p>
<p>Un logiciel peut continuer à fonctionner pendant des années alors que seule une poignée de personnes comprend réellement pourquoi il fonctionne ainsi.</p>
<p>Lorsqu’une de ces personnes quitte l’équipe, la documentation ne suffit pas toujours à compenser la perte. Et lorsqu’une nouvelle équipe doit reprendre le projet dans une stack différente, le risque augmente encore.</p>
<p>L’intelligence artificielle ne supprime pas automatiquement cette dette.</p>
<p>Elle peut accélérer l’analyse du code et faciliter la formalisation des connaissances. Mais elle peut également accélérer la production d’une nouvelle implémentation avant que les incertitudes aient été levées.</p>
<p>On risque alors de transformer une dette de connaissance en dette technique: des choix mal compris sont reproduits, des hypothèses deviennent du code et des comportements erronés sont intégrés dans une architecture que l’équipe devra ensuite maintenir.</p>
<p>Le problème n’est pas que l’IA soit inutile. C’est qu’une capacité de génération rapide peut donner l’impression que le problème de compréhension a déjà été résolu.</p>
<p>Or, produire une nouvelle version n’est pas la même chose que comprendre et maîtriser le système.</p>
<h2>Comment utiliser l’IA sans sacrifier la qualité?</h2>
<p>Ce que j’observe aujourd’hui sur le marché oscille entre deux positions. D’un côté, des équipes qui refusent tout assistant de code, par prudence ou par principe, et se privent d’un gain réel sur l’analyse, les tests et les tâches répétitives. De l’autre, des organisations qui confient à l’IA l’essentiel de la production, les yeux fermés, convaincues que la vitesse de génération mesure la productivité. La réécriture décrite ici relève de cette seconde position.</p>
<p><strong>Entre refuser l’IA et lui confier le logiciel les yeux fermés, il existe une troisième voie: l’intégrer dans une démarche d’ingénierie adaptée aux risques du projet, où l’équipe garde la conception, la vérification et la responsabilité du résultat.</strong></p>
<p>Une migration sérieuse devrait commencer par une phase d’analyse de l’existant, avec l’identification des fonctionnalités, des dépendances, des contrats d’API, des règles métier et des comportements critiques.</p>
<p>Il faut ensuite concevoir l’architecture cible en tenant compte des spécificités du nouveau langage et de son écosystème. Cette étape ne devrait pas être réduite à la reproduction mécanique de l’architecture initiale.</p>
<p>Les tests existants doivent être évalués et complétés. Les tests de caractérisation permettent notamment de figer certains comportements observés avant la migration, y compris lorsque la documentation ne décrit pas tous les détails. Ils ne remplacent toutefois pas la validation métier: un comportement existant peut lui-même être erroné.</p>
<p>La réécriture peut ensuite progresser par lots fonctionnels, avec des revues techniques, des tests automatisés et des comparaisons entre l’ancienne et la nouvelle implémentation lorsque cela est possible.</p>
<p>Enfin, la qualification doit vérifier non seulement que le code fonctionne, mais aussi que le résultat respecte les exigences, les contraintes de sécurité, les performances attendues et les conditions réelles d’exploitation.</p>
<p>Il faut également préparer le transfert à l’équipe de maintenance: documentation actualisée, décisions d’architecture explicites, procédures d’exploitation, compétences et responsabilités clairement définies.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/e57bc7dd-cc65-4bdb-8a0c-f102f5ed523f.png" alt="Six étapes numérotées. 1, analyser l’existant: fonctionnalités, règles métier, contrats d’API. 2, concevoir la cible, pensée pour la nouvelle stack. 3, compléter les tests de caractérisation et de non-régression. 4, réécrire par lots, avec revues, tests et comparaison de l’ancien et du nouveau. 5, qualifier: exigences, sécurité, performances, exploitation. 6, transmettre à l’équipe: documentation, procédures, responsabilités. Dessous, un bandeau: l’IA accélère chaque étape, l’équipe décide, vérifie et porte le résultat." style="display:block;margin:0 auto" />

<p>L’IA devient alors un accélérateur de travail au sein d’un processus contrôlé, plutôt qu’un substitut à la conception et à la validation.</p>
<h2>La leçon à retenir</h2>
<p>Le code, la documentation et les tests ne réécrivent pas un logiciel à notre place. Ils rendent possible une démarche maîtrisée; ils ne la remplacent pas.</p>
<p>Une réécriture assistée par l’IA réussit lorsque l’équipe assume ses choix de conception, puis démontre par la qualification que le résultat est bien celui attendu.</p>
<p>Le choix de la stratégie dépend moins de l’outil que de ce que l’on sait réellement du système à remplacer.</p>
<h2>Quelle stratégie selon le legacy et la connaissance disponible?</h2>
<p>Il n’existe pas une seule façon de réécrire un logiciel avec l’IA. Le bon choix dépend de deux questions: que sait-on réellement du système existant, et quelle est la distance entre la stack initiale et la stack cible?</p>
<h3>Stratégie A — Répliquer l’architecture existante</h3>
<p>L’IA reproduit autant que possible l’organisation du code initial dans le nouveau langage.</p>
<p>Quand l’envisager: une application de taille modeste, bien connue, et deux stacks proches.</p>
<p>Risque: conserver des choix inadaptés au nouvel environnement.</p>
<h3>Stratégie B — Reconcevoir pour la stack cible</h3>
<p>L’équipe conserve les règles métier et les contrats fonctionnels, mais définit une architecture adaptée au langage, à ses bibliothèques et à ses pratiques.</p>
<p>Quand l’envisager: une connaissance documentée et testée, et deux stacks éloignées.</p>
<p>Avantage: obtenir un système cohérent avec son nouvel environnement technique.</p>
<p>Condition: formaliser d’abord les comportements à préserver.</p>
<h3>Stratégie C — Reconception, puis qualification systématique</h3>
<p>L’équipe combine une architecture cible adaptée, des tests de caractérisation de l’existant, des tests de non-régression, des contrôles de sécurité et une qualification indépendante.</p>
<p>C’est l’approche que je privilégierais pour une migration critique.</p>
<h3>Stratégie D — Reconstituer la connaissance avant de réécrire</h3>
<p>Lorsque la documentation est incomplète ou obsolète et que les règles métier reposent sur la mémoire de quelques personnes, la réécriture ne commence pas par le code.</p>
<p>L’équipe établit d’abord les règles métier et les comportements à préserver. L’IA y contribue, de l’analyse des historiques aux questions à poser aux experts métier; les tests de caractérisation figent ce qui est observé, et les experts tranchent entre un comportement volontaire et un défaut ancien.</p>
<p>Une fois cette connaissance formalisée, la réécriture peut suivre la stratégie C.</p>
<p>Risque: allonger le calendrier. C’est pourtant le prix de la dette de connaissance.</p>
<h3>Stratégie E — Remplacer progressivement, lot par lot</h3>
<p>C’est le principe du <em>strangler pattern</em>, ou <a href="https://martinfowler.com/bliki/StranglerFigApplication.html"><em>strangler fig</em></a> décrit par Martin Fowler: plutôt qu’une bascule unique, la nouvelle implémentation remplace l’ancienne par lots fonctionnels, jusqu’à la rendre inutile. Chaque lot est comparé à l’existant avant de passer au suivant.</p>
<p>Quand l’envisager: un système trop large ou trop critique pour être remplacé en une fois. Elle se combine avec les stratégies B, C ou D.</p>
<p>Avantage: détecter les écarts lot par lot, plutôt que de les découvrir tous ensemble en qualification.</p>
<p>Limite: elle suppose de pouvoir faire fonctionner l’ancienne et la nouvelle implémentation côte à côte pendant la transition.</p>
<h3>Stratégie F — Converger vers un produit unique plutôt que migrer l’existant</h3>
<p>Plutôt que de migrer l’ancien système, les clients passent sur un nouveau produit: une seule version, dont le fournisseur maîtrise l’évolution, où ce qui varie d’un client à l’autre relève de la configuration et non du code. L’IA recense les écarts de chaque client au modèle de base, dans la configuration comme dans le code.</p>
<p>Quand l’envisager: un produit partagé par de nombreux clients, comme un ERP ou un logiciel de paie, trop enchevêtré pour être découpé.</p>
<p>Avantage: l’effort dépend de la taille du socle et non du nombre de clients, et la dette de connaissance ne se reforme pas.</p>
<p>Limite: elle change le modèle économique; c’est d’abord un choix stratégique et commercial.</p>
<p>Le détail de cette stratégie, ses trois règles et le cas qui la fonde: <a href="https://elie29.hashnode.dev/sharedcore-un-c-ur-produit-partag-des-mod-les-de-base-adapt-s-une-volution-commune">SharedCore: un cœur produit partagé, des modèles de base adaptés, une évolution commune</a></p>
<h3>Choisir selon la situation</h3>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Stratégie</th>
</tr>
</thead>
<tbody><tr>
<td>Connaissance complète, stacks proches, application peu critique</td>
<td>A</td>
</tr>
<tr>
<td>Connaissance complète, stacks éloignées</td>
<td>B</td>
</tr>
<tr>
<td>Connaissance complète, migration critique</td>
<td>C</td>
</tr>
<tr>
<td>Connaissance incomplète, obsolète ou dans la mémoire de quelques personnes</td>
<td>D, puis C</td>
</tr>
<tr>
<td>Système trop large pour une bascule unique</td>
<td>E (strangler pattern), avec B, C ou D</td>
</tr>
<tr>
<td>Système impossible à découper, personnalisations propres à chaque client</td>
<td>F, avec C pour la qualification</td>
</tr>
</tbody></table>
<h2>Le véritable enjeu: qui porte la responsabilité du résultat?</h2>
<p>La réécriture répondait à un besoin légitime: ne plus dépendre d’une seule personne.</p>
<p>Mais il existe une différence fondamentale entre transférer la responsabilité d’un logiciel et transférer simplement son code.</p>
<p>Une équipe est réellement capable de prendre en charge un système lorsqu’elle comprend son fonctionnement, sait le diagnostiquer, peut le faire évoluer et dispose des moyens nécessaires pour garantir sa stabilité.</p>
<p>Si elle ne maîtrise pas la stack initiale, la migration vers une nouvelle technologie peut être une bonne décision. Encore faut-il que la nouvelle implémentation soit conçue pour cette technologie et que sa qualité soit démontrée.</p>
<p>L’IA peut faciliter ce transfert. Elle peut aider à documenter, expliquer, tester et reconstruire. Elle ne supprime cependant pas la responsabilité de ceux qui définissent l’architecture, valident les exigences et autorisent la mise en production.</p>
<p>Le management doit donc éviter de confondre réduction du temps de génération du code et réduction du coût global de possession du logiciel.</p>
<p>Un code produit plus rapidement peut nécessiter davantage de corrections, de qualification et de maintenance si le processus de développement n’est pas maîtrisé.</p>
<p>Le véritable indicateur de réussite n’est pas le volume de code généré ni la vitesse de réécriture. C’est la capacité de l’équipe à livrer un système fiable et à le maintenir dans la durée.</p>
<h2>Conclusion: l’avenir du développement ne consiste pas à remplacer aveuglément les développeurs</h2>
<p>Cette expérience soulève une question qui dépasse largement un projet particulier.</p>
<p>Si une réécriture présente plus d’une cinquantaine de régressions malgré un contexte complet, il faut examiner sérieusement la méthode employée. Et sur un logiciel dont la connaissance repose sur quelques individus, les risques deviennent plus difficiles encore à maîtriser.</p>
<p>Cela ne signifie pas que l’IA est incapable de réussir une migration. Cela signifie que la génération de code ne doit jamais être confondue avec la maîtrise d’un système logiciel.</p>
<p>L’avenir du développement repose probablement sur une collaboration de plus en plus étroite entre les développeurs, les architectes, les experts métier et les outils d’intelligence artificielle.</p>
<p>L’IA peut accélérer la compréhension du code, automatiser des tâches répétitives et aider à construire des tests.</p>
<p>Mais elle ne dispense pas l’organisation de formaliser ses exigences, de concevoir une architecture adaptée, de vérifier les comportements et d’assumer la responsabilité du résultat.</p>
<p><strong>On peut confier à l’IA la production d’une grande partie du code. On ne peut pas lui confier aveuglément la responsabilité de préserver une connaissance que l’entreprise elle-même ne maîtrise plus.</strong></p>
<p>La question fondamentale n’est donc pas: «L’IA peut-elle réécrire notre logiciel?»</p>
<p>C’est plutôt: <strong>«Sommes-nous capables de démontrer que le logiciel qu’elle a réécrit est réellement celui dont notre organisation a besoin?»</strong></p>
<p>Et vous, dans vos projets, considérez-vous l’IA comme un outil de développement, un accélérateur de migration ou un substitut à l’expertise technique? Où placez-vous la limite entre automatisation et responsabilité humaine?</p>
<hr />
<h2>Articles similaires</h2>
<ul>
<li><a href="https://elie29.hashnode.dev/sharedcore-un-c-ur-produit-partag-des-mod-les-de-base-adapt-s-une-volution-commune">SharedCore: un cœur produit partagé, des modèles de base adaptés, une évolution commune</a></li>
</ul>
<ul>
<li><a href="https://elie29.hashnode.dev/plus-le-projet-grossit-plus-l-ia-se-trompe">Plus le projet grossit, plus l’IA se trompe: le bounded context comme investissement</a></li>
<li><a href="https://elie29.medium.com/from-legacy-artifacts-to-served-context-my-six-stage-method-09f668052904">From Legacy Artifacts to Served Context: My Six-Stage Method</a> (en anglais)</li>
<li><a href="https://elie29.medium.com/the-living-specification-how-i-keep-ai-written-code-correct-907be05c9eed">The Living Specification: How I Keep AI-Written Code Correct</a> (en anglais)</li>
<li><a href="https://elie29.medium.com/ai-writes-the-code-so-what-is-the-engineers-job-now-79fa3fdf1b88">AI Writes the Code. So What Is the Engineer’s Job Now?</a> (en anglais)</li>
</ul>
<h2>Restons en contact</h2>
<p>Pour suivre mes prochains articles ou en discuter:</p>
<ul>
<li>X: <a href="https://x.com/elie_nehme">@elie_nehme</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/elie-nehme/">Elie Nehmé</a></li>
<li>GitHub: <a href="https://github.com/elie29">elie29</a></li>
<li>Site web: <a href="https://elienehme.fr">elienehme.fr</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[PHP2Shell: une faille repérée en 2024, démontrée en 2026]]></title><description><![CDATA[PHP2Shell: une faiblesse signalée en 2024, une exécution de code à distance démontrée en 2026 avec l’IA, et les versions de PHP à installer]]></description><link>https://elie29.hashnode.dev/php2shell-une-faille-rep-r-e-en-2024-d-montr-e-en-2026</link><guid isPermaLink="true">https://elie29.hashnode.dev/php2shell-une-faille-rep-r-e-en-2024-d-montr-e-en-2026</guid><category><![CDATA[PHP]]></category><category><![CDATA[cybersecurity]]></category><category><![CDATA[Security]]></category><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[DevSecOps]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Thu, 22 Oct 2026 13:14:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/458fab5a-5b14-4e48-9588-510dce46fdb5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Le 21 octobre 2026, PHP a publié en urgence les versions <em>8.5.12</em>, <em>8.4.27</em>, <em>8.3.36</em> et <em>8.2.35</em>. Elles corrigent deux failles critiques, <em>CVE-2026-109618</em> et <em>CVE-2026-109619</em>, notées 9,2 sur 10 (CVSS 4.0), qui permettent d’exécuter du code à distance sans authentification. Leurs découvreurs les ont baptisées PHP2Shell.</p>
<p>L’affaire met en lumière une distinction essentielle en cybersécurité: détecter un défaut, comprendre comment l’exploiter et démontrer une attaque concrète sont trois étapes différentes. Sa chronologie montre comment elles se sont enchaînées, et pourquoi il a fallu deux ans.</p>
<h2>Une chronologie qui soulève des questions</h2>
<h3>1. 2024: un premier signal, sans attaque démontrée</h3>
<p>Selon SentinelOne, un audit de 2024 avait déjà repéré une faiblesse de PHP dans la gestion des situations de manque de mémoire, sans parvenir à prouver qu’elle était exploitable.</p>
<p>Cette étape illustre une difficulté classique: observer un comportement dangereux dans le code ne signifie pas que l’on sait le transformer en compromission effective.</p>
<h3>2. Août 2026: l’IA relie les éléments</h3>
<p>En août 2026, le laboratoire de recherche en sécurité Calif reprend l’analyse du code de PHP avec GPT-5.6 Sol, un modèle d’OpenAI, lors d’un audit financé par OpenAI dans le cadre de son initiative «Patch the Planet». Calif y trouve un chemin d’exploitation qui mène à l’exécution de code à distance.</p>
<p>Quelques semaines plus tard, l’équipe Wiz Research trouve les mêmes failles de son côté, avec son outil Wiz Atlas et les modèles Gemini 4 Argon et GPT-5.6 Sol, qu’elle utilise de la découverte jusqu’à la validation du correctif. Wiz, Calif et OpenAI travaillent ensuite avec l’équipe de sécurité de PHP sur la coordination et la vérification du correctif.</p>
<p>L’intérêt de cette étape réside dans le passage d’une hypothèse technique à un scénario d’exploitation démontré. Calif précise n’avoir utilisé que des modèles accessibles à tous, sans outillage particulier, et rappelle qu’aucun modèle ne trouve «tous les bugs» avec de simples prompts. L’IA accélère l’exploration du code et la formulation d’hypothèses; les résultats doivent toujours être validés par des tests et une analyse technique rigoureuse.</p>
<h3>3. Deux failles qui, combinées, ouvrent l’accès</h3>
<p>La première, CVE-2026-109618, naît d’un manque de mémoire. Quand une requête dépasse <code>memory_limit</code>, PHP l’interrompt brutalement, parfois au milieu de l’analyse d’un envoi de fichier. Le nettoyage qui suit peut alors libérer une zone mémoire jamais initialisée, qui contient encore des données de l’attaquant.</p>
<p>La seconde, CVE-2026-109619, tient à un état global devenu obsolète. Un état propre à une requête survit à la libération de sa mémoire, après une erreur fatale par exemple, et une requête suivante sur le même processus peut le réutiliser avant qu’il ne soit remis à zéro: c’est une erreur de type use-after-free, où un programme continue d’utiliser une zone mémoire déjà libérée.</p>
<p>Combinées, ces faiblesses transforment une corruption mémoire en exécution de code. Wiz l’a démontré contre WordPress, Drupal et Joomla, mais l’attaque ne dépend d’aucune de ces applications. Selon PHP, mod_php est la configuration la plus exposée; PHP-FPM, php-cgi, FrankenPHP et LiteSpeed le sont aussi.</p>
<p>Ce point est particulièrement important: le risque ne dépend pas toujours d’un défaut isolé. Il peut résulter de l’interaction entre plusieurs problèmes dont les conséquences deviennent beaucoup plus graves lorsqu’ils sont combinés.</p>
<h3>4. 20 et 21 octobre 2026: une fuite avance le correctif</h3>
<p>Le 20 octobre, l’équipe de sécurité de PHP annonce une publication pour le lendemain à 14h UTC, en se réservant le droit de l’avancer si les détails venaient à fuiter. Ils fuitent: un message publié sur Hacker News, supprimé depuis, décrit les deux failles, et watchTowr confirme qu’elles sont réelles avant tout correctif. PHP publie les versions corrigées le 21 octobre, à 13h30 UTC selon le CERT-EU.</p>
<p>Le jour même, une preuve de concept circule et Cloudflare observe des attaques contre ses clients. Le CERT-EU juge l’exploitation probable.</p>
<p>Cette dernière étape rappelle que la découverte d’une vulnérabilité ne représente qu’une partie du travail. Il faut également coordonner la divulgation, préparer les correctifs, informer les utilisateurs et limiter les possibilités d’exploitation pendant la période de transition, même quand une fuite impose le calendrier.</p>
<h2>Pourquoi cette chronologie est-elle importante?</h2>
<p>Le fait que le problème ait été repéré dès 2024, puis exploité de manière démontrée en 2026, soulève plusieurs questions.</p>
<p>La première concerne l’ancienneté réelle du code vulnérable. Calif, Wiz et Cloudflare situent la portée des failles à partir de PHP 5.4, soit plus de dix ans de versions. Seule une analyse de l’historique du code source permettrait de dater précisément l’introduction du défaut.</p>
<p>La deuxième concerne le rôle de l’intelligence artificielle. Les outils d’IA aident à identifier des interactions complexes et à explorer des pistes qui auraient demandé beaucoup plus de temps avec des méthodes exclusivement manuelles. Il reste néanmoins nécessaire de distinguer leur contribution documentée du travail des chercheurs qui ont construit, testé et adapté l’exploitation.</p>
<p>Enfin, cette affaire souligne que l’absence d’un exploit connu ne constitue pas une garantie de sécurité durable. De nouvelles méthodes peuvent modifier rapidement l’évaluation du risque associé à une vulnérabilité ancienne.</p>
<h2>Ce qu’il faut faire</h2>
<ul>
<li><strong>Inventorier</strong> tous les serveurs et conteneurs qui exécutent PHP, y compris ceux que l’on a oubliés.</li>
<li><strong>Mettre à jour</strong> vers PHP 8.5.12, 8.4.27, 8.3.36 ou 8.2.35, puis redémarrer Apache, PHP-FPM et tous les processus de longue durée. Pour PHP, la mise à jour est le seul choix sûr.</li>
<li><strong>Traiter les versions non maintenues:</strong> PHP 8.1 et les versions antérieures ne reçoivent plus de mises à jour du projet. Il reste les rétroportages des distributions et des éditeurs de support long terme, les correctifs source que PHP a publiés pour 7.4, 8.0 et 8.1, ou la montée de version. PHP 8.2 arrive lui-même en fin de vie le 31 décembre 2026.</li>
<li><strong>En attendant le correctif</strong>, l’avis de PHP liste des mesures temporaires: <code>session.upload_progress.enabled=0</code>, <code>memory_limit=-1</code> imposé par <code>php_admin_value</code> avec une limite mémoire au niveau du conteneur, <code>post_max_size</code> à 8M (32M si l’application reçoit des fichiers), et <code>fatal_error_backtraces=0</code> en PHP 8.5. Elles réduisent l’exposition sans rendre l’installation sûre. Si la mise à jour est impossible, le CERT-EU recommande d’isoler du réseau public les serveurs exposés à Internet.</li>
</ul>
<h2>Conclusion</h2>
<p>Cette chronologie illustre un phénomène majeur en cybersécurité: une faille peut être identifiée longtemps avant que son potentiel d’exploitation soit pleinement démontré.</p>
<p>L’analyse assistée par IA a réduit le délai entre ces deux étapes, mais elle ne remplace ni l’expérimentation, ni la validation technique, ni la coordination nécessaire pour protéger les systèmes concernés.</p>
<p>Pour les organisations qui utilisent PHP, la priorité reste de vérifier les versions réellement déployées, d’appliquer les correctifs officiels et d’évaluer l’exposition des applications en production.</p>
<p>Une vulnérabilité n’est pas nécessairement nouvelle lorsqu’elle devient critique. Parfois, c’est notre capacité à comprendre ses conséquences qui vient de changer.</p>
<h2>Sources</h2>
<ul>
<li><a href="https://www.php.net/archive/2026.php">Security advisory: Critical remote code execution vulnerabilities, update now, PHP, 21 octobre 2026</a></li>
<li><a href="https://cert.europa.eu/publications/security-advisories/2026-018">Critical Vulnerabilities in PHP, avis de sécurité 2026-018, CERT-EU</a></li>
<li><a href="https://www.php2shell.com/">PHP2Shell, Wiz Research avec Calif et OpenAI</a></li>
<li><a href="https://thenextweb.com/news/php2shell-php-rce-ai-openai-wiz">PHP rushes out emergency patches for two critical bugs AI found first, The Next Web</a></li>
<li><a href="https://www.sentinelone.com/blog/stopping-php2shell-how-sentinelone-protects-customers-from-this-attack-technique/">Stopping PHP2SHELL, SentinelOne</a></li>
</ul>
<hr />
<ul>
<li>X: <a href="https://x.com/elie_nehme">@elie_nehme</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/elie-nehme/">Elie Nehmé</a></li>
<li>Site web: <a href="https://elienehme.fr">elienehme.fr</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Plus le projet grossit, plus l’IA se trompe ]]></title><description><![CDATA[Plus le projet grossit, plus l’IA générative se trompe: avec des bounded contexts, le coût du contexte se paie une fois, plutôt qu’à chaque requête]]></description><link>https://elie29.hashnode.dev/plus-le-projet-grossit-plus-l-ia-se-trompe</link><guid isPermaLink="true">https://elie29.hashnode.dev/plus-le-projet-grossit-plus-l-ia-se-trompe</guid><category><![CDATA[context-window]]></category><category><![CDATA[#Domain-Driven-Design]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[refactoring]]></category><category><![CDATA[SOLID principles]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Fri, 02 Oct 2026 07:04:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/4edfdeef-7e45-4121-ad23-cd4d37844eba.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sur un projet <em>green field</em>, les équipes qui adoptent un assistant de code IA (Kiro, Claude Code, GitHub Copilot ou un autre) vivent souvent la même lune de miel. Une fonctionnalité demandée le matin tourne l’après-midi en production, tests compris. La démo impressionne et l’équipe est conquise.</p>
<p>Puis, sprint après sprint, l’effet waouh s’estompe. Les réponses restent assurées, mais elles deviennent moins justes: une modification ici casse quelque chose là-bas, l’IA réinvente une règle qui existe déjà trois dossiers plus loin, et chaque requête oblige à réexpliquer le projet. De plus, les tokens s’envolent très vite 💸</p>
<blockquote>
<p>Le modèle n’a pas changé. Le projet, si. Ce que l’IA doit tenir en tête a grossi, et chaque requête en paie le prix. Découper le projet en bounded contexts ne se paie qu’une fois</p>
</blockquote>
<p>Sur plusieurs projets, j’ai mis en place une méthode pour réussir ce découpage. Je l’appelle <code>Context Budget</code>. Elle tient en cinq gestes, mais elle part d’un constat.</p>
<p><strong>N.B.</strong>: le budget dont il est question ici n’est pas celui du projet, ni en jours ni en euros. C’est celui des tokens que l’IA consomme à chaque requête.</p>
<h2>De 1 cm à 1 000 km</h2>
<p>Au premier jour, le projet fait 1 cm de diamètre. Tout tient dans la fenêtre de contexte de l’IA: le modèle de données, les règles, les conventions, les quelques fichiers qui existent. Elle voit tout, elle répond juste.</p>
<p>À 10 cm, les premières fonctionnalités sont là. Le projet tient encore, à peu près, dans ce que l’IA embrasse d’un regard.</p>
<p>À 100 m, c’est un produit. L’IA n’en voit plus qu’une partie et devine le reste, souvent bien, parfois avec assurance et à tort.</p>
<p>À 1 000 km, quelques mois plus tard, l’IA n’en voit plus qu’une fraction. Changer une ligne suppose désormais de connaître des règles, des exceptions et des dépendances dispersées dans tout le dépôt.</p>
<p><strong>Pour la même tâche, l’IA lit toujours plus, comprend toujours moins et se trompe davantage</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/0a3f65ba-2d0a-401b-b930-2e1509fc07cc.png" alt="Quatre cercles de plus en plus grands, de 1 cm à 1 000 km, représentent le projet dans le temps. Un cercle pointillé, ce dont une tâche a besoin, couvre tout le projet au début, puis une part de plus en plus petite: l’IA absorbe le reste en trop." style="display:block;margin:0 auto" />

<h2>Ce n’est pas le modèle qui faiblit, c’est le contexte qui grossit</h2>
<p>L’intuition se vérifie dans la recherche publique. Les études ci-dessous mesurent surtout la capacité à retrouver une information dans un long texte, pas l’écriture de code, mais elles disent toutes la même chose: à modèle constant, la précision baisse quand le contexte s’allonge.</p>
<ul>
<li><p>En 2023, <em>Lost in the Middle</em> montre que les modèles exploitent bien une information placée au début ou à la fin du contexte, et nettement moins bien au milieu, y compris les modèles conçus pour les contextes longs.</p>
</li>
<li><p>En 2025, <em>Chroma</em> teste 18 modèles et conclut qu’aucun ne garde des performances constantes quand la longueur du contexte augmente, même sur des tâches simples. Le phénomène a désormais un nom: le <strong>context rot</strong>.</p>
</li>
<li><p>La même année, <em>NoLiMa</em> évalue 13 modèles dont la fenêtre annoncée atteint au moins 128K tokens: dès 32K, 11 d’entre eux tombent sous la moitié du score qu’ils obtiennent sur un contexte court.</p>
</li>
<li><p><em>LongCodeBench</em>, enfin, est le plus proche de notre cas: du code, un modèle fixe, et un contexte qu’on gonfle en ajoutant d’autres fichiers du dépôt. <em>Claude 3.5 Sonnet</em> y tombe de 29% à 3% de réussite quand le contexte passe de 32K à 256K tokens.</p>
</li>
</ul>
<p>Anthropic en tire une règle de conduite: le contexte est une ressource finie, aux rendements décroissants, et chaque token entame un «budget d’attention». Le bon contexte est le plus petit ensemble d’informations qui suffit à la tâche.</p>
<p>Pour le décideur, la conséquence est directe: attendre le prochain modèle à un million de tokens ne règle pas le problème. Une fenêtre plus large laisse entrer plus de contexte, elle ne garantit pas qu’il soit mieux exploité. Dans <em>Lost in the Middle</em> déjà, les modèles à contexte étendu ne faisaient pas mieux que leurs versions standard.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/a7f5cb41-9985-4947-a54d-f1197f5747fd.png" alt="Deux courbes dans le temps. Le contexte à tenir monte, la pertinence des réponses de l’IA générative descend. Elles se croisent au point de bascule, au-delà duquel chaque requête coûte plus et rapporte moins." style="display:block;margin:0 auto" />

<h2>Le coût se paie à chaque requête</h2>
<p>Sur un projet qui a grossi sans frontières, chaque requête relit le monde. L’IA a besoin de plus de fichiers pour comprendre, et ce contexte se paie de quatre façons.</p>
<ol>
<li><p><strong>En tokens:</strong> les API facturent l’entrée au token. Chez Anthropic, depuis <em>Claude 4.6</em>, il n’y a plus de surcoût au-delà de 200k tokens, mais une requête de 900k tokens coûte toujours cent fois une requête de 9k. Le cache baisse le prix de ce qui se répète, mais il ne corrige pas la dilution de l’attention.</p>
</li>
<li><p><strong>En temps de revue:</strong> une réponse moins juste demande une relecture plus attentive, et souvent des corrections.</p>
</li>
<li><p><strong>En régressions hors du périmètre demandé:</strong> l’IA modifie ce qu’elle ne voit qu’à moitié.</p>
</li>
<li><p><strong>En explications répétées:</strong> chaque session réapprend ce que la précédente savait.</p>
</li>
</ol>
<p>Ce coût n’apparaît sur aucune ligne budgétaire. Il se dilue dans chaque requête de chaque développeur, chaque jour, et il croît avec le projet.</p>
<h2>Context Budget: payer une fois</h2>
<p>Le Domain-Driven Design (DDD) a déjà la réponse. Martin Fowler résume le principe du bounded context en expliquant que le DDD découpe un grand système en bounded contexts, chacun doté de son propre modèle unifié. Il cite Eric Evans, pour qui unifier entièrement le modèle d’un grand système n’est ni faisable ni rentable.</p>
<p>Un bounded context est aussi un contexte que l’IA peut tenir en entier: c’est le sens du nom <code>Context Budget</code>. Le premier schéma, plus haut, le montre. Le cercle pointillé, c’est ce dont une tâche a besoin; tout ce qui l’entoure, l’IA l’absorbe en trop. Le budget est dépassé dès que, pour une tâche donnée, l’IA doit absorber plus de contexte, de données ou de règles métier que la tâche n’en demande. Chaque bounded context doit tenir dans ce budget, et ce qui est hors du cercle ne se voit que par son contrat.</p>
<h2>La méthode tient en cinq gestes</h2>
<h3>1. Une spécification durable par bounded context</h3>
<p>Tout part de la spécification durable, celle que je décris dans <a href="https://elienehme.fr/writing/the-living-specification-how-i-keep-ai-written-code-correct/">The Living Specification</a>: la source de vérité que le code implémente. Il y en a une par bounded context. Un bounded context se compose lui-même d’un ou de plusieurs hexagones (au sens de l’architecture hexagonale) ou applications, selon son découpage interne. C’est la spécification qui permet d’évaluer la trajectoire du projet et sa volumétrie, et de tracer les frontières entre domaines à partir du langage ubiquitaire. Un même mot qui change de sens d’un domaine à l’autre signale presque toujours une frontière.</p>
<h3>2. Une évaluation à intervalle régulier</h3>
<p>La trajectoire s’évalue à date fixe, pas quand les symptômes apparaissent: tous les six sprints ou tous les trois mois selon le rythme du projet, par exemple en ouverture d’un sprint planning. L’évaluation réunit l’architecte, le PO ou le BA et l’équipe de développement autour des prochaines fonctionnalités à livrer. La question est celle du budget: pour livrer ces fonctionnalités, l’IA devra-t-elle absorber plus de contexte, de données ou de règles métier qu’elles n’en demandent? Si oui, un domaine est en train de sortir de son cercle.</p>
<p>Entre deux évaluations, certains signaux peuvent justifier une nouvelle évaluation plus tôt que prévu:</p>
<ul>
<li><p>Un changement ordinaire touche de plus en plus de fichiers</p>
</li>
<li><p>Il faut réexpliquer le même contexte à chaque requête</p>
</li>
<li><p>L’IA introduit des régressions hors du périmètre demandé</p>
</li>
<li><p>L’IA réinvente une règle qui existe déjà ailleurs</p>
</li>
</ul>
<p>La liste n’est pas exhaustive, mais il s’agit bien de déclencheurs, pas d’indicateurs à piloter. Ils signalent qu’il est temps de regarder, pas ce qu’il faut faire.</p>
<h3>3. Des frontières préparées dès le départ</h3>
<p>Pour ne payer le découpage qu’une fois, il faut l’avoir préparé. Dès le premier jour, chaque dépendance passe par une interface et un adapter, les principes SOLID sont respectés de bout en bout, et l’architecture est décrite selon le modèle C4, en systèmes, conteneurs et composants. Un composant peut alors devenir un conteneur, puis un conteneur un système, sans réécrire ceux qui l’appellent. Le moment de cette promotion se décide en Event Storming, avec l’architecte.</p>
<p>Le découpage devient un déplacement, pas une réécriture. C’est ce qui rend son coût ponctuel et prévisible.</p>
<h3>4. Un contexte par domaine</h3>
<p>Chaque bounded context est géré comme une unité indépendante, avec son langage ubiquitaire, sa spécification durable, ses hexagones et ses pipelines de CI/CD. À l’intérieur, chaque concept n’a qu’un sens et aucun synonyme. L’IA travaille dans un seul contexte à la fois: elle y trouve un modèle cohérent et des voisins qu’elle ne connaît que par leur contrat. C’est la même idée que le contrat d’API gelé de <a href="https://elienehme.fr/writing/i-tried-bmad-on-a-real-feature/">mon essai de BMAD</a>: de part et d’autre d’un contrat, chacun avance sans que l’intégration repose sur la confiance.</p>
<h3>5. Un refactoring porté par l’équipe</h3>
<p>C’est l’équipe qui découpe. Les frontières se tracent en Event Storming, avec l’architecte. L’atelier Big Picture regroupe les événements du domaine et délimite les bounded contexts. Selon le cas, l’atelier Process Modelling conçoit ensuite les processus métier de chaque bounded context, ou l’atelier Software Design fait émerger les agrégats, valide le découpage et choisit le type d’intégration entre bounded contexts. L’équipe matérialise ensuite ces frontières par le refactoring, assistée par l’architecte ou le tech lead. Décider où passe une frontière reste un jugement d’ingénieur, celui dont je défendais la place dans <a href="https://elienehme.fr/writing/ai-writes-the-code-so-what-is-the-engineers-job-now/">AI Writes the Code</a>.</p>
<h3>Un exemple, pour fixer les idées</h3>
<p>Cet exemple est fictif: il montre ce que la méthode produit.</p>
<p>Une plateforme de vente démarre avec un seul bounded context, Commandes, organisé en un hexagone. Sa spécification durable décrit le panier, les remises, le paiement, la facturation et l’expédition. À 10 cm, tout tient dans le budget: l’IA livre une fonctionnalité dans la journée.</p>
<p>À l’évaluation du trimestre, le PO présente ce qui arrive: la facturation en plusieurs devises, puis les avoirs. L’architecte, le PO et l’équipe posent la question du budget. Pour livrer la facturation en devises, l’IA devrait absorber tout Commandes, panier, remises et expédition compris, alors que la tâche n’a besoin que des règles de facturation. Le budget est dépassé.</p>
<p>L’Event Storming avec l’architecte fait apparaître la frontière. Les événements «Commande validée» et «Facture émise» n’appartiennent pas au même flux, et le mot «client» change de sens de l’un à l’autre: l’acheteur côté Commandes, le payeur côté Facturation. L’atelier Software Design valide ce découpage et fixe l’intégration: Facturation réagit à «Commande validée» et ne connaît rien d’autre de Commandes.</p>
<p>Comme la facturation passait déjà par une interface et un adapter, elle sort de Commandes sans réécrire ses appelants: d’abord comme composant, puis comme conteneur. Elle reçoit sa propre spécification durable et son propre langage ubiquitaire. Désormais, une requête à l’IA sur les devises ne charge que Facturation et le contrat qui la relie à Commandes.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/67f51216-bbf2-491e-acf6-e3112206c664.png" alt="À gauche, le projet découpé en six bounded contexts, Commandes, Catalogue, Facturation, Expédition, Clients et Stocks, reliés par des contrats, chacun tenant dans le contexte de l’IA. À droite, deux courbes de coût cumulé: avec découpage, un coût initial puis une pente faible; sans découpage, une pente qui s’accélère et finit par dépasser la première." style="display:block;margin:0 auto" />

<h2>Ce que j’ai observé</h2>
<p>J’ai vu le développement d’une API, tests de bout en bout compris, passer de 3,5 jours à 3 heures. Ce chiffre compare un projet sans découpage ni spécification durable à la méthode complète: il mesure donc l’effet de toute la méthode, pas du seul découpage.</p>
<h2>Ce que cela demande au décideur</h2>
<ul>
<li><p>Budgéter le découpage comme un investissement, pas comme une dette qu’on remboursera un jour: un coût ponctuel et prévisible, contre un coût récurrent qui croît avec le projet.</p>
</li>
<li><p>Mettre l’évaluation de la trajectoire au calendrier, au même titre que le sprint planning.</p>
</li>
<li><p>Exiger les interfaces, les adapters et le C4 dès le <em>green field</em>: ils fixent le prix du futur découpage.</p>
</li>
<li><p>Ne pas attendre le prochain modèle: une fenêtre plus large ne rend pas l’attention plus juste.</p>
</li>
</ul>
<p>Le <em>green field</em> est le meilleur moment pour l’IA, et le meilleur moment pour préparer la suite: c’est là que se décide combien coûtera chaque requête dans trois ans.</p>
<hr />
<h2>Restons en contact</h2>
<p>Pour suivre mes prochains articles ou en discuter:</p>
<ul>
<li><p>X: <a href="https://x.com/elie_nehme">@elie_nehme</a></p>
</li>
<li><p>LinkedIn: <a href="https://www.linkedin.com/in/elie-nehme/">Elie Nehmé</a></p>
</li>
<li><p>Site web: <a href="https://elienehme.fr">elienehme.fr</a></p>
</li>
</ul>
<hr />
<h2>Sources</h2>
<ul>
<li><p>Nelson F. Liu et al., <a href="https://arxiv.org/abs/2307.03172">Lost in the Middle: How Language Models Use Long Contexts</a>, Transactions of the ACL, vol. 12, 2024.</p>
</li>
<li><p>Kelly Hong, Anton Troynikov, Jeff Huber, <a href="https://www.trychroma.com/research/context-rot">Context Rot: How Increasing Input Tokens Impacts LLM Performance</a>, Chroma, 14 juillet 2025.</p>
</li>
<li><p>Ali Modarressi et al., <a href="https://arxiv.org/abs/2502.05167">NoLiMa: Long-Context Evaluation Beyond Literal Matching</a>, ICML 2025.</p>
</li>
<li><p>Stefano Rando et al., <a href="https://arxiv.org/abs/2505.07897">LongCodeBench: Evaluating Coding LLMs at 1M Context Windows</a>, 2025.</p>
</li>
<li><p>Anthropic, <a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Effective context engineering for AI agents</a>, 29 septembre 2025.</p>
</li>
<li><p>Anthropic, <a href="https://platform.claude.com/docs/en/about-claude/pricing">Pricing</a>, consulté le 1er octobre 2026.</p>
</li>
<li><p>Martin Fowler, <a href="https://martinfowler.com/bliki/BoundedContext.html">Bounded Context</a>, 15 janvier 2014.</p>
</li>
<li><p>Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software, Addison-Wesley, 2003.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Corriger ou atténuer: le CRA ne prévoit que deux réponses]]></title><description><![CDATA[CRA: depuis le 11 septembre 2026, déclarer une faille exploitée sous 24h se prépare avant l’incident: inventaire, SBOM, atténuation sans développeur]]></description><link>https://elie29.hashnode.dev/corriger-ou-attenuer-le-cra-ne-laisse-que-deux-reponses</link><guid isPermaLink="true">https://elie29.hashnode.dev/corriger-ou-attenuer-le-cra-ne-laisse-que-deux-reponses</guid><category><![CDATA[Cyber Resilience Act]]></category><category><![CDATA[legacy]]></category><category><![CDATA[DevSecOps]]></category><category><![CDATA[cybersecurity]]></category><category><![CDATA[sbom]]></category><category><![CDATA[SAST]]></category><category><![CDATA[DAST]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Fri, 25 Sep 2026 13:19:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/33b29c8f-01f6-4a0a-b313-913682791046.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Imaginons le scénario suivant:</strong> <code>vendredi soir, une vulnérabilité activement exploitée est signalée dans une bibliothèque que tout le monde embarque. Le compteur de 24h démarre dès que l’éditeur sait que cette faille touche son produit.</code></p>
<p><strong>Deux questions se posent alors:</strong></p>
<ol>
<li><p>Dans quels produits, dans quelles versions, chez quels clients?</p>
</li>
<li><p>Peut-on couper la fonctionnalité exposée ce soir, sans développeur, sur une version livrée il y a trois ans?</p>
</li>
</ol>
<p>Si la réponse à la première question demande deux jours d’enquête, le délai est déjà compromis. Si la réponse à la seconde question est non, il faudra informer les clients qu’ils vont rester exposés pendant un certain temps.</p>
<blockquote>
<p>Je le dis d’emblée: le délai de 24h ne se tient pas au moment de l’incident. Il se prépare dans la chaîne de livraison, dans le nombre de versions qu’on accepte de maintenir, dans la capacité des produits à être atténués sans développeur, et dans la décision de mettre ou non un produit sur le marché européen.</p>
</blockquote>
<h2>Ce qu’exige le 11 septembre, en bref</h2>
<p>Depuis le 11 septembre 2026, les fabricants de produits comportant des éléments numériques déclarent les vulnérabilités activement exploitées et les incidents graves ayant des répercussions sur la sécurité du produit.</p>
<p>Un éditeur est fabricant dès qu’il met un logiciel, payant ou gratuit, sur le marché sous son nom ou sa marque, dans le cadre d’une activité commerciale. Les produits déjà mis sur le marché sont aussi couverts, parc existant compris.</p>
<p>Une exploitation connue <strong>avant</strong> le 11 septembre n’a pas à être déclarée après coup; celle qui est découverte depuis cette date se déclare, même sur une faille ancienne. Une faille dans une bibliothèque intégrée au produit est une faille du produit, et c’est à l’éditeur de la déclarer.</p>
<p>Pour la Commission, cette déclaration ne s’impose que si la faille est exploitée dans le produit de l’éditeur: présente mais inatteignable, ou exploitée seulement ailleurs, elle ne déclenche pas son délai.</p>
<p>Une vulnérabilité est activement exploitée lorsqu’il existe des preuves fiables qu’un acteur malveillant l’a exploitée sur un système sans l’autorisation de son propriétaire. En revanche, découverte avant toute exploitation, elle n’a pas à être déclarée, corrigée ou non.</p>
<p>Un incident est grave dès qu’il remplit l’un des deux critères, qualitatifs et sans seuil chiffré: qu’il entache ou soit susceptible d’entacher la capacité du produit à protéger la disponibilité, l’authenticité, l’intégrité ou la confidentialité de données ou fonctions sensibles ou importantes; ou qu’il ait conduit ou soit susceptible de conduire à l’introduction ou à l’exécution d’un code malveillant dans le produit, ou dans le réseau et les systèmes d’information d’un utilisateur.</p>
<p>La déclaration <strong>part simultanément</strong> vers le CSIRT coordinateur du fabricant, l’équipe nationale de réponse aux incidents de sécurité, et vers l’ENISA, par la plateforme unique de signalement, et non vers le public: alerte précoce sans retard injustifié et au plus tard à 24h, notification au plus tard à 72h, puis un rapport final.</p>
<p>Pour une vulnérabilité, ce rapport est dû au plus tard 14 jours après la mise à disposition d’une mesure corrective ou d’atténuation; pour un incident grave, au plus tard un mois après la notification des 72h.</p>
<p>Atténuer, c’est fermer le chemin d’exploitation ou limiter ce que l’attaquant en tire, sans supprimer la faille. Informer les utilisateurs concernés est une obligation distincte.</p>
<p>Les obligations du 11 septembre ne fixent aucun délai pour corriger. Elles imposent de le dire, et une mesure d’atténuation suffit à faire partir le rapport final.</p>
<h2>Premier tri: le code de l’éditeur, ou celui d’un autre?</h2>
<p>Tout commence par ce tri. Il décide de ce que l’éditeur pourra écrire à 72h.</p>
<p>Quand la faille exploitée est dans son propre code, qu’elle ait été localisée par l’analyse statique du code (SAST), par les tests dynamiques (DAST) ou signalée par quelqu'un, l’éditeur a la main. La question devient arithmétique: combien de versions maintenues faut-il corriger, et chacune peut-elle passer en production vite?</p>
<p>Quand la faille vient d’une dépendance tierce, à condition que celle-ci soit toujours maintenue, l’éditeur dépend du calendrier du mainteneur alors que ses délais courent déjà. Rien ne les suspend: ni le week-end, ni l’attente d’un correctif amont. Et la déclaration lui revient.</p>
<p>J’ai mesuré une fois ce que vaut la disponibilité d’un mainteneur bénévole. Un bug grave découvert dans une bibliothèque open source, une <em>pull request</em> complète portant l’intégralité de la solution, acceptée deux mois plus tard avec ce message: je travaille gratuitement, c’est un projet open source, tu me paies, je corrige plus vite. Il avait raison. Mais deux mois, ce sont deux mois de clients exposés, et une notification des 72h sans mesure à annoncer.</p>
<p>Le pire des cas reste celui où la dépendance n’est pas maintenue. La déclaration revient quand même à l’éditeur, et personne en amont ne produira le correctif. La question se pose frontalement: faut-il modifier soi-même la bibliothèque? Les options sont connues, et toutes coûteuses:</p>
<ul>
<li><p>La corriger soi-même, par un fork ou un patch interne</p>
</li>
<li><p>Remplacer la dépendance</p>
</li>
<li><p>Retirer ou désactiver la fonctionnalité qui l’utilise</p>
</li>
</ul>
<p>Le fork a un coût caché. L’éditeur devient mainteneur de ce composant, sur toutes les versions du parc qui l’embarquent, pour toute leur durée de vie, y compris pour les failles suivantes. Et il faudra peut-être un jour le resynchroniser avec le dépôt distant, ce qui devient plus difficile à chaque divergence.</p>
<p>L’éditeur n’est pas seul dans ce cas. Tous ceux qui embarquent cette bibliothèque abandonnée ont la même faille. Le délai court pour chacun dès qu’elle est exploitée dans son produit, et chacun produit son correctif dans son coin, sans coordination: plusieurs forks divergents d’un même composant, autant de corrections à revalider, et aucune version de référence. Une dépendance abandonnée transforme une faille unique en N corrections parallèles, chez chacun d’eux. Les attitudes possibles, dont aucune n’est une obligation du 11 septembre:</p>
<ul>
<li><p>Reverser le correctif en amont, quand le dépôt existe encore, même sans mainteneur actif</p>
</li>
<li><p>Le partager ouvertement, pour que les autres utilisateurs n’aient pas à le refaire</p>
</li>
<li><p>Porter seul un fork qui diverge de ceux des autres</p>
</li>
</ul>
<p>Je recommande de reverser le correctif quand le dépôt vit encore, et sinon de le partager ouvertement: ces deux attitudes sont les moins coûteuses collectivement, et les seules qui réduisent le travail total. La troisième, on la subit.</p>
<p>Par ailleurs, si le produit permet une atténuation, l’éditeur la met à disposition et la déploie lui-même là où il exploite le produit. Sur un produit conçu avant le CRA, souvent, rien ne le permet: la fonctionnalité exposée ne peut être ni désactivée, ni isolée, ni contournée sans casser le produit. Une parade existe parfois hors du produit: une règle de pare-feu applicatif, un filtrage au reverse proxy, un isolement réseau, etc. Elle dépend alors de l’infrastructure, mais l’éditeur doit savoir comment la mettre en œuvre dans l’environnement de déploiement. À défaut, il reste le correctif amont ou le correctif interne, sans filet. Et à 72 h, il faut écrire ce que les utilisateurs peuvent faire ou non.</p>
<p>En ce qui concerne le correctif, son effet est multiplicateur à l’échelle d’un parc de produits. Une vulnérabilité exploitée dans une dépendance n’est presque jamais à un seul endroit du parc. Elle est dans plusieurs produits, et dans plusieurs versions de la même dépendance. Une seule faille, ce sont N correctifs à produire, à tester et à livrer, et un rapport final qui ne peut partir qu’une fois la mesure disponible. C’est là que l’inventaire cesse d’être de la documentation et devient la condition nécessaire pour tenir le délai.</p>
<p>Puisque la déclaration revient tout de même à l’éditeur, c’est à lui d’engager dès maintenant le travail d’inventaire, de sa propre initiative (Ce n’est pas une obligation du 11 septembre, mais cela relève du bon sens):</p>
<ol>
<li><p>Lister d’abord toutes les dépendances du parc, par produit et par version maintenue</p>
</li>
<li><p>Repérer ensuite celles qui sont à risque:</p>
<ul>
<li><p>Les obsolètes (versions en fin de vie ou en retard important sur la dernière version)</p>
</li>
<li><p>Les non maintenues (projet archivé, aucune version depuis longtemps, failles passées jamais corrigées)</p>
</li>
<li><p>Les peu actives (un seul mainteneur, peu de contributions, questions et signalements sans réponse)</p>
</li>
<li><p>Pour un tiers commercial, négocier aussi ses engagements de correction et de notification</p>
</li>
</ul>
</li>
<li><p>Préparer le plan B de chacune, avant l’incident: la dépendance de remplacement identifiée, ou le fork assumé avec son responsable nommé, ou le contrat qui engage un tiers à corriger, ou la fonctionnalité qu’on sait couper.</p>
</li>
</ol>
<blockquote>
<p>Un plan B choisi à froid se déclenche le vendredi soir. Un plan B improvisé le vendredi soir n’existe pas.</p>
</blockquote>
<h2>Ce qui doit exister avant l’incident</h2>
<p>Rien de ce qui précède ne tient sans une chaîne de livraison en état. Aucune des pratiques d’ingénierie qui suivent n’est une obligation du 11 septembre, mais elles rendent l’obligation tenable:</p>
<ul>
<li><p>Un pipeline capable à tout moment de reconstruire, corriger, tester et livrer chaque version maintenue, que la faille vienne du code de l’éditeur ou d’une dépendance</p>
</li>
<li><p>Des versions reconstructibles: toolchain, images de base et dépendances conservées et figées, dans un environnement isolé du reste du système d’information. Une version qu’on ne sait plus reconstruire est une version qu’on ne sait plus corriger</p>
</li>
<li><p>Un SBOM, la nomenclature des composants logiciels, produit à chaque build, versionné, relié à l’artefact livré et aux clients</p>
</li>
<li><p>La capacité d’interroger le parc en minutes, pas en jours: quel produit, quelle version, contient ce composant?</p>
</li>
<li><p>Pour chaque version, un avis d’exploitabilité (VEX) qui dit si le code vulnérable est réellement atteignable. Un composant présent n’est pas toujours exploitable, et cet avis est l’un des éléments qui étayent, le jour venu, la décision de déclarer ou non</p>
</li>
<li><p>Une mise à jour des dépendances vulnérables proposée automatiquement dans les pipelines, tirée d’un dépôt interne qui en vérifie la provenance, et validée par les tests de chaque version</p>
</li>
<li><p>La chaîne de <em>build</em> et le canal de mise à jour protégés comme le produit lui-même: une intrusion qui peut y injecter du code malveillant est un candidat sérieux à l’incident grave</p>
</li>
<li><p>La trace de chaque signalement reçu et de son évaluation initiale, menée sans attendre: pour la Commission, le compteur part dès que cette évaluation établit, avec une certitude raisonnable, que la faille est exploitée dans le produit</p>
</li>
</ul>
<h2>Réduire le nombre de versions maintenues, et décider avant de vendre</h2>
<p>Chaque version maintenue est un pipeline à tenir en état, un SBOM à suivre, un correctif de plus et un dossier de déclaration plus lourd à chaque faille.</p>
<p>Pour moi, réduire ce nombre devient indispensable, et cela demande un nouveau modèle de support: deux versions maintenues au plus, la dernière et la précédente, une fin de support écrite au contrat, et une montée de version offerte au client. Elle coûte moins cher qu’une version de plus à maintenir, tant qu’elle n’impose au client ni nouveau matériel ni nouvelle infrastructure. La fin de support arrête les correctifs; l’obligation de déclarer, elle, continue. Une version hors support mais exploitée chez un client reste à déclarer, et la mesure à lui proposer est le plus souvent la montée de version.</p>
<p>Le raisonnement va jusqu’au bout. Chaque produit mis sur le marché européen et couvert par le règlement entre dans ce dispositif de déclaration, avec tout ce qu’il suppose: pipeline, inventaire, astreinte, capacité d’atténuation. À mes yeux, un composant ou un produit dont le coût dépasserait ce qu’il rapporte ne doit tout simplement pas être mis sur le marché européen. La décision se prend en amont, avant sa première mise à disposition en Europe, payante ou gratuite, dans un cadre commercial: après, le produit est déjà couvert. Le responsable produit doit pouvoir l’instruire, chiffres à l’appui, avec le RSSI, puis la direction arbitre.</p>
<h2>La capacité d’atténuation se conçoit, elle ne s’improvise pas</h2>
<p>Les produits <em>legacy</em> montrent ce qu’il faut désormais concevoir. L’enjeu reste dans le périmètre du 11 septembre: être capable de mettre à disposition une mesure d’atténuation à déclarer à 72h, et faire démarrer le rapport final sans attendre le mainteneur d’un tiers.</p>
<p>Aucune obligation du 11 septembre n’impose ce qui suit. Je le fais porter aux nouveaux produits comme critères d’acceptation de conception, au même titre qu’une exigence fonctionnelle:</p>
<ul>
<li><p>Chaque fonctionnalité exposée à une entrée non maîtrisée, repérée par l’analyse de menace, peut être désactivée, isolée ou restreinte par configuration, sans nouvelle livraison, avec un mode dégradé défini</p>
</li>
<li><p>L’interrupteur est testé dans le pipeline à chaque version: un interrupteur jamais actionné ne marchera pas le vendredi soir</p>
</li>
<li><p>L’interrupteur est traité comme la surface d’attaque qu’il est: accès restreint, authentifié, tracé, configuration signée; il retire une fonctionnalité, il n’affaiblit jamais un contrôle de sécurité</p>
</li>
<li><p>Les dépendances critiques sont isolées derrière une interface qui permet de les remplacer ou de les couper</p>
</li>
<li><p>Chaque fonctionnalité a sa fiche d’atténuation, rédigée à froid: comment la couper, qui décide de la couper, qui la coupe, quel impact pour l’utilisateur, quel message lui envoyer et qui l’envoie.</p>
</li>
</ul>
<blockquote>
<p>Cela suit précisément la même logique qu’un PCA/PRA ou du chaos engineering: rédigé à froid et testé régulièrement.</p>
</blockquote>
<p>Couper la fonctionnalité exposée est souvent la seule mesure disponible. C’est un mal nécessaire, et c’est exactement ce qu’il faut écrire aux clients. Encore faut-il que ce soit possible. Sur un produit qui n’a pas été conçu pour, il n’y a rien à couper sans le casser: l’atténuation reste théoriquement possible et pratiquement indisponible, faute d’avoir été prévue dans les versions déjà déployées chez les clients. C’est ce travail de conception qui transforme le «rien à faire qu’attendre» du <em>legacy</em> en une atténuation déployable en quelques heures.</p>
<h2>Le vendredi soir, sans maintenance 7 jours sur 7</h2>
<p>Les délais courent à partir de la prise de connaissance, week-end compris. Beaucoup d’organisations n’ont pourtant aucune équipe de développement disponible le samedi. Trois capacités se distinguent, et les confondre coûte cher.</p>
<p>L’alerte à 24h demande une personne habilitée à déclarer, avec une délégation écrite et un modèle prêt. Elle ne demande pas une équipe de développement.</p>
<p>L’atténuation demande de pouvoir déclencher l’interrupteur sans développeur et sans livraison. Sur la partie du produit que l’éditeur héberge lui-même, son équipe d’exploitation l’actionne. Sur un produit installé chez le client, c’est le client qui l’actionne: l’atténuation devient une procédure documentée qu’il applique, et que portent la notification des 72h et l’information des utilisateurs.</p>
<p>Le contrat le prévoit avant l’incident: le droit de couper une fonctionnalité pour des raisons de sécurité, et un contact sécurité chez le client, qui remonte les exploitations qu’il constate.</p>
<p>Le correctif, lui, revient en heures ouvrées, sans mettre les développeurs en astreinte, à une condition: que l’atténuation ait été déployée le vendredi, ou mise à la disposition des clients qui exploitent eux-mêmes le produit. Les obligations du 11 septembre ne lui fixent aucun délai. Le mode dégradé imposé aux clients en fixe un.</p>
<p>Sans atténuation possible, il reste deux issues: mobiliser des développeurs le week-end, ce qui suppose une astreinte organisée et payée, ou écrire dans la notification des 72h que les clients restent exposés. Le choix entre les deux se fait à froid, produit par produit, et la direction le signe. Ce coût-là entre dans le calcul de rentabilité évoqué plus haut.</p>
<h2>Qui lit ce que vous déclarez</h2>
<p>Les alertes et les notifications ne sont pas publiques. Elles circulent entre le CSIRT coordinateur qui les reçoit, les CSIRT des États membres où le produit est disponible, l’ENISA et les autorités de surveillance du marché.</p>
<p>Dans des circonstances exceptionnelles, le fabricant peut indiquer le degré de sensibilité qu’il attribue à l’information et demander que sa diffusion aux autres CSIRT soit retardée. C’est le CSIRT qui décide de ce report; il reste limité à ce qui est strictement nécessaire et ne suspend aucun délai.</p>
<p>Il faut rester lucide sur ce qui finit par sortir: un document fuit, une information circule. Mais une vulnérabilité activement exploitée est déjà entre les mains d’au moins un attaquant. La déclaration ne lui apprend rien; le report de diffusion sert aussi à ne pas l’apprendre aux autres. Le silence, lui, laisse le client sans défense.</p>
<p>Ce qui sort vraiment du cercle des autorités, c’est l’information des utilisateurs. Elle est obligatoire: le fabricant informe les utilisateurs touchés, ou tous s’il y a lieu, de la vulnérabilité ou de l’incident et des mesures qu’ils peuvent prendre. Elle lui échappe s’il tarde: les CSIRT peuvent la délivrer à sa place quand ils l’estiment nécessaire.</p>
<p>Un éditeur qui peut annoncer une atténuation efficace sous 72h, par un interrupteur ou une consigne aux utilisateurs, peut aussi plaider pour que la diffusion entre CSIRT attende. La décision reste au CSIRT, et la diffusion suit si l’atténuation n’arrive pas à temps. Le <em>kill switch</em> protège deux fois: il protège les clients, et il change ce que la notification et l’information des utilisateurs ont à dire.</p>
<h2>Gouvernance: ce qui se décide à froid</h2>
<p>Trois décisions et un exercice se préparent à froid. Le RSSI, ou le PSIRT, l’équipe de réponse aux incidents de sécurité des produits, là où elle existe, instruit ces décisions; la direction les tranche et signe la délégation.</p>
<p>Qui décide de déclarer, auprès de quel CSIRT, sur quels critères, avec quelle délégation.</p>
<p>L’arbitrage entre sous-déclaration et sur-déclaration: déclarer trop produit du bruit et abîme la crédibilité, déclarer trop peu laisse les clients sans défense. Chaque décision de ne pas déclarer laisse une trace écrite et motivée.</p>
<p>La politique des dépendances: qui tient l’inventaire des dépendances à risque, à quelle fréquence il est revu, qui décide de déclencher un plan B, fork, remplacement ou coupure.</p>
<p>Un exercice à blanc, chronométré, sur un vrai produit <em>legacy</em> embarquant une dépendance tierce, avec le déclarant, le support, celui qui écrit aux clients et un client qui exploite lui-même le produit. C’est le seul moyen de savoir si l’alerte, l’atténuation et le correctif tiennent avant d’en avoir besoin.</p>
<h2>Mes règles d’or</h2>
<p>Ces règles n’engagent que moi. Je les pose, je les applique, et je les publie pour qu’elles soient reprises. Aucune n’est une obligation du 11 septembre, et chacune s’appuie sur des pratiques connues du métier. Ce qui m’appartient, c’est d’en faire des règles: elles sont la réponse logique à ce que le 11 septembre 2026 rend inévitable.</p>
<p><strong>L’inventaire est intégral:</strong> Toute version livrée et encore en service chez un client y figure, maintenue ou non, avec ses composants et ses dépendances, par produit et par client.</p>
<p><strong>La R&amp;D produit et valide la composition de chaque version:</strong> Le support, ou l’exploitation, tient à jour la version installée chez chaque client. Le RSSI reçoit cet inventaire. Reconstituer le parc pendant le compteur de 24 h ne relève pas du RSSI. L’inventaire est fourni, daté, validé par ceux qui construisent ou maintiennent les produits.</p>
<p><strong>Le SBOM est la source:</strong> Il est produit à chaque <em>build</em> et relié à l’artefact livré, pour chaque version maintenue.</p>
<p><strong>L’analyse de sécurité est obligatoire:</strong> SAST, DAST et analyse de composition couvrent tous les composants, images de conteneur et couches de base comprises. Une faille dans l’image de base livrée est une faille du produit livré: activement exploitée, elle se déclare au même titre.</p>
<p><strong>La réactivité est continue:</strong> Une analyse de composition et de dépendances tourne en permanence sur chaque version maintenue, pas seulement sur la dernière, et se croise avec les signaux d’exploitation publiés. L’alerte arrive avant le signalement extérieur.</p>
<p><strong>La branche principale est la plus propre possible:</strong> C’est la seule façon de ne pas ajouter sa dette au traitement de l’incident, et c’est depuis elle que se produisent les correctifs à rétroporter.</p>
<p><strong>Le pipeline CI/CD est la chaîne de preuve:</strong> Aucun artefact livré ne contourne le pipeline de construction, de contrôle et de traçabilité défini par le produit. Le code source, les dépendances, les contrôles de sécurité et l’artefact produit sont reliés entre eux. Ce qui est construit ou modifié hors chaîne ne peut pas devenir une version livrée.</p>
<p><strong>Une dernière règle les tient toutes:</strong> Aucune version maintenue, aucun composant n’échappe aux précédentes. Toute exception est écrite, datée, limitée dans le temps et signée par la direction.</p>
<h2>Ce que l’horloge révèle</h2>
<p>Le problème est antérieur au CRA. La chaîne de livraison, la conception des produits et la gestion du portefeuille auraient dû le résoudre depuis longtemps. Le règlement y pose une horloge, et une horloge ne se négocie pas. Le 11 décembre 2027, l’essentiel du texte s’appliquera à ce qui sera mis sur le marché à partir de cette date, et une partie de ces règles d’or deviendra une exigence. L’horloge tournera alors depuis plus d’un an, et elle aura déjà désigné les meilleurs: ceux qui savent construire des produits.</p>
<h2>Sources</h2>
<ul>
<li><p><a href="https://digital-strategy.ec.europa.eu/en/policies/cra-reporting">Cyber Resilience Act — Reporting obligations, Commission européenne</a></p>
</li>
<li><p><a href="https://www.enisa.europa.eu/topics/product-security-and-certification/single-reporting-platform-srp">Single Reporting Platform, ENISA</a></p>
</li>
<li><p><a href="https://eur-lex.europa.eu/eli/reg/2024/2847/oj">Règlement (UE) 2024/2847, texte intégral</a></p>
</li>
<li><p><a href="https://cyber.gouv.fr/reglementation/cybersecurite-des-produits/cyber-resilience-act/cadre-r%C3%A8glementaire-du-cra/">Cadre règlementaire du CRA</a></p>
</li>
<li><p><a href="https://digital-strategy.ec.europa.eu/en/library/commission-publishes-new-guidance-support-timely-cyber-resilience-act-implementation">Lignes directrices sur l’application du CRA, C(2026) 5252, Commission européenne</a>, non contraignantes</p>
</li>
<li><p><a href="https://www.enisa.europa.eu/topics/product-security/vulnerability-services/eu-incident-response-and-cyber-crisis-management/single-reporting-platform-srp/frequently-asked-questions">Questions fréquentes sur la plateforme unique de signalement, ENISA</a>, documentation opérationnelle</p>
</li>
</ul>
<hr />
<p><em>N.B.: Cet article présente mon analyse des implications du règlement, appuyée sur son texte et sur les lignes directrices publiées par la Commission. Il ne constitue pas un avis juridique et ne remplace pas celui d’un juriste ou d’un avocat sur la situation de votre organisation. Mon objectif est de proposer une feuille de route et mes règles d’or, là où la stratégie rejoint l’architecture.</em></p>
]]></content:encoded></item><item><title><![CDATA[From Legacy Artifacts to Served Context: My Six-Stage Method]]></title><description><![CDATA[Six stages to build and serve a release-versioned knowledge graph from C, PL/SQL, PHP and twenty years of documents, with the LLM kept behind a gate.]]></description><link>https://elie29.hashnode.dev/from-legacy-artifacts-to-served-context-my-six-stage-method</link><guid isPermaLink="true">https://elie29.hashnode.dev/from-legacy-artifacts-to-served-context-my-six-stage-method</guid><category><![CDATA[llm]]></category><category><![CDATA[context engineering]]></category><category><![CDATA[ontology]]></category><category><![CDATA[agentic AI]]></category><category><![CDATA[knowledge graph]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Fri, 18 Sep 2026 15:48:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/b077f877-b8e9-440a-9f2b-dcab14101e6f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Note: Originally published on <a href="https://elie29.medium.com/from-legacy-artifacts-to-served-context-my-six-stage-method-09f668052904">Medium</a></p>
</blockquote>
<p><em>In my</em> <a href="https://elienehme.fr/en/writing/ontology-based-context-engineering-when-rag-is-not-enough/"><em>previous article</em></a><em>, I explained why RAG alone was not enough for my legacy system, which standards exist (RDF, SKOS, SHACL, R2RML...), how to govern them, and I closed with the six stages of my method as a one-page overview. This part is the method itself: each stage in the detail that overview could not give, from raw legacy artifacts to context served to the LLM. And it covers both runs of the pipeline: the</em> <em><strong>initialization</strong></em>*, the first full pass that builds the baseline from an empty store, and the* <em><strong>update</strong></em>*, the delta that keeps the graph true at every release after it.*</p>
<p>An ontology with no data is a diagram on a wall. The value comes from the pipeline that extracts facts from real sources (code, database, documents), keeps them versioned release after release, and serves them to the model at question time. My method has six stages as follows:</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/45ec59b6-684f-4f45-b456-71bde0fdfbba.svg" alt="The six-stage pipeline as a loop, with the ontology, SKOS vocabulary and SHACL shapes as the contract every stage reads. Four build the graph: Analyzing picks a standard per artifact family, Collecting runs one collector per source family, Transforming merges with SKOS and puts LLM proposals behind a SHACL gate, Versioning appends a delta per release. Two use it: Retrieving does entity linking then release-filtered SPARQL, Serving returns context or MCP tools with the answer and its path." style="display:block;margin:0 auto" />

<p>The first four build and maintain the graph. The last two use it. The split is also a split of <em>when</em> things run:</p>
<ul>
<li><p>Stage 1 is a decision, taken once and revisited at every release</p>
</li>
<li><p>Stages 2 to 4 are the CI job (collect, validate, rebuild the store, one graph per release), with one human checkpoint inside Stage 3 for the facts an LLM proposed</p>
</li>
<li><p>Stages 5 and 6 run at question time, against the store that job produced</p>
</li>
</ul>
<p>The CI job has three triggers, the same three as the governance loop that takes an ontology change from proposal to deployed graph:</p>
<ul>
<li><p><strong>A pull request on the ontology repository.</strong> Validation only: the shapes, the reasoner and the regression queries run on sample data, and no collector runs until the change is merged.</p>
</li>
<li><p><strong>The merge of a change proposal.</strong> The job repopulates the store with the new terms.</p>
</li>
<li><p><strong>Every release of the sources</strong> (a commit, a tag or the nightly run). No proposal and no review, because the ontology already covers what changed.</p>
</li>
</ul>
<p>One run stands apart from those three: the <strong>initialization</strong>, a full pass over every source from an empty store. Every run after it is a delta. And one principle runs through all six stages, because everything else follows from it:</p>
<blockquote>
<p><strong>Facts extracted by deterministic tools are trusted. Facts proposed by an LLM are suspected until validated</strong></p>
</blockquote>
<p>Static analysis does not hallucinate. An LLM does. Both are useful, but they do not enter the graph through the same door.</p>
<p><strong>A note on confidentiality: which LLMs?</strong></p>
<p>One question always comes first when the sources are the code and the specifications of a legacy system: <em>is any of it sent to a public cloud?</em> No. Every LLM task in this method (document classification, version detection, link proposals, the sorting of quarantine reports, and the final answer generation) ran on <strong>local models served by Ollama</strong>, on my own machines, with nothing leaving the network. Which models is a detail I leave out on purpose: they changed during the project.</p>
<p>Note that the method does not depend on any specific model, which is one more benefit of keeping the LLM at the border: you can swap the model tomorrow without touching the graph, the collectors or the queries.</p>
<hr />
<h2>Stage 1 — Analyzing: match each artifact to its standard</h2>
<p>Before writing any collector, walk through your artifact families and decide, for each one, <strong>which standard will represent it</strong>. This stage is cheap (a few workshops with the ontology draft on the table) and it prevents the classic failure: modeling everything with the wrong tool.</p>
<p>This is how the analysis looked on my project:</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/ba8c01ce-112e-41dd-a0b8-0fda1958d0e3.svg" alt="Stage 1 decision table, one row per artifact family with what it contains and the standard that represents it. C, C++, PHP source code: structural facts as RDF triples typed by the ontology. Oracle schema and PL/SQL: dependencies from the data dictionary as triples, the data itself through R2RML / OBDA, virtual, no copy. Business vocabulary: SKOS labels. Documents: RDFS classes plus provenance. Quality rules: SHACL shapes. History: one named graph per release." style="display:block;margin:0 auto" />

<p>A question I get every time I show this table: <em>my system is Java and PostgreSQL, not C and Oracle. Does any of this still apply?</em> It does, and the table is its own proof: not one of its rows is really about a technology. The left column is a <strong>family of artifacts</strong>; the technologies I name are simply the ones that happened to be in my system.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/18da2808-7be3-4d2a-8c02-e9280bb3d99a.svg" alt="The same rows read as families, not technologies: what the row means, what it was in my system, what it becomes elsewhere. Source code with a call graph: C, C++, PHP, or Java, C#, Python, Go, the collector changes and the calls edge does not. A relational truth that knows its dependencies: Oracle, or PostgreSQL, SQL Server, DB2. A user-facing layer, versioned prose, a vocabulary with several names per concept, a notion of for which version this is true." style="display:block;margin:0 auto" />

<p>Only the <strong>collectors</strong> are technology-specific, and they are the cheapest and most replaceable part of the whole thing. The ontology, the SHACL shapes, the queries and the six stages do not change when you swap PHP for Java. That is the real reason to model the domain instead of the code: a call graph is about your language, <code>:calls</code> is about your system.</p>
<p>Two outputs close this stage. The first is the <strong>core ontology</strong>, which in my case stayed around a dozen classes (<code>CModule</code>, <code>CppModule</code>, <code>SmartyTemplate</code>, <code>PlsqlPackage</code>, <code>DbTable</code>, <code>SpecificationDocument</code>, <code>Release</code>, <code>BusinessRule</code>...). The second is the <strong>decision table above</strong>, which becomes the contract for every collector you write next.</p>
<p>There is a second decision in this stage, and it is the one I got wrong first: <strong>granularity</strong>. My instinct was to push the model down: every function a node, every SQL statement an edge, and why not every line an assertion. It is a trap. The graph becomes a bad copy of source files that are already the best representation of themselves; the number of facts to re-collect at every release explodes; and nobody has ever asked me a relationship question about a line. The rule I settled on: <strong>model a thing when it is either the endpoint of a relation someone will traverse, or an anchor an answer needs to cite.</strong> That puts the floor at the procedure, the table, the template, the document <em>section</em>: the level at which a senior developer can point and say "yes, that is the thing". Below that floor the node carries a pointer (file, line, section) and the content stays where it is. <strong>The graph stops where the text begins.</strong> That sentence is what keeps an ontology from becoming a slow re-implementation of the file system.</p>
<p>One warning from experience: resist the temptation to design the perfect ontology. Analyze one subsystem, model what it needs, and let the ontology grow release after release, through the change proposals that unanswered questions generate. A small ontology that is populated beats a complete ontology that is empty.</p>
<h2>Stage 2 — Collecting: one collector per source family</h2>
<p>Each source family gets its own collector. The good news: for code and database, extraction is deterministic and reliable. The bad news comes with the documents.</p>
<h3>C and C++: the call graph is already there</h3>
<p>You do not need an LLM to know that function A calls function B. Decades-old tooling does it better:</p>
<ul>
<li><p><strong>Doxygen</strong> (XML output) or <strong>libclang</strong> can provide functions, references/call relationships, and file structure. Even <strong>cscope</strong>/<strong>ctags</strong> databases can be exploited for a quick start.</p>
</li>
<li><p><strong>tree-sitter</strong> is my favorite middle ground: fast, tolerant of code that no longer compiles (yes, legacy repos contain files that no current toolchain accepts), and scriptable.</p>
</li>
<li><p><strong>Embedded SQL (Pro*C)</strong> deserves a dedicated pass: a simple parser over <code>EXEC SQL</code> blocks can extract valuable <code>readsTable</code> / <code>writesTable</code> relationships that connect the C world to the Oracle world.</p>
</li>
</ul>
<p>Traps to expect: macros that hide calls, function pointers, generated code. My rule: extract what is certain, mark the rest as <em>unresolved</em> instead of guessing. An incomplete graph that is true beats a complete graph that lies.</p>
<h3>PL/SQL: the database already knows everything</h3>
<p>As you know, Oracle already maintains, for free, most of the graph you need:</p>
<ul>
<li><p><code>ALL_DEPENDENCIES</code>: which package depends on which package, view, table. This single view is half of your PL/SQL subgraph.</p>
</li>
<li><p><strong>PL/Scope</strong> (<code>ALL_IDENTIFIERS</code>, <code>ALL_STATEMENTS</code>): once enabled at compilation, it tells you <em>which procedure</em> references <em>which column</em>, at line level. Gold.</p>
</li>
<li><p><code>ALL_SOURCE</code>, <code>ALL_TAB_COLUMNS</code>, constraints, triggers: the code text and the structural skeleton.</p>
</li>
</ul>
<p>The collector is mostly SQL queries against these views, and it emits Turtle like the other collectors: the dependency edges are collected facts, loaded into the graph of their release. Only the table contents stay in Oracle, served virtually through the R2RML mappings decided in Stage 1. The blind spot is <strong>dynamic SQL</strong> (<code>EXECUTE IMMEDIATE</code>, DBMS_SQL): the dictionary cannot see through it. I handle it with a text pass that flags dynamic statements and, when the table name is a literal, extracts it with a low-tech regex, marked with lower confidence, never silently mixed with dictionary facts.</p>
<h3>PHP: follow the routes</h3>
<p>For the PHP MVC layer, <strong>nikic/php-parser</strong> extracts includes, calls and database access points; the Smarty templates connect the user-facing screens to the controllers behind them. The chain template → controller → SQL → table is what links user behavior to the rest of the graph. Legacy PHP loves string-concatenated SQL, so the same rule applies: literal table names are extracted, dynamic ones are flagged.</p>
<h3>Documents: the real battlefield</h3>
<p>Code extraction is a solved problem. Twenty years of documents is not. Specifications in <code>.doc</code> and <code>.docx</code>, PDFs, exports of old wikis, two languages in the same corpus, and the same specification existing in five versions for five releases, none of them labeled clearly.</p>
<p>My document pipeline, in order: <strong>convert everything to text</strong> (keep the section structure, headings are the anchors the graph will point to); <strong>detect identity and version</strong>, which means asking "<em>which</em> document is this, and for <em>which</em> release?" before asking "what does this document?"; and this is where the <strong>LLM earns its place</strong>: classifying a document, guessing its release range, detecting that document A is probably a newer version of document B, proposing that section 4.2 describes <code>PKG_INVOICE</code>. Every proposal carries a confidence score and goes to the review queue of the next stage.</p>
<h2>Stage 3 — Transforming: from raw facts to validated graph</h2>
<p>Nothing enters the graph directly. The transformation stage has three jobs.</p>
<p><strong>Entity resolution.</strong> Legacy systems are champions of synonyms: the same concept is <code>CONTRACT</code> in the database, <code>ctr</code> in the C code, "souscription" in the French documents and "subscription" in the English ones. Deterministic keys solve it where possible (database objects have exact names; code entities have file + symbol; stable business keys prevent duplicates by construction). <strong>SKOS</strong> solves everything human: one node per business concept, one <code>skos:prefLabel</code>, as many <code>skos:altLabel</code> as history has produced, in both languages. Every synonym discovered in review becomes one more <code>altLabel</code>, and the glossary grows as a side effect of the pipeline.</p>
<p><strong>Human validation of LLM proposals.</strong> Every identity, version or link proposed by the LLM goes into a <strong>review queue</strong>. A domain expert confirms or corrects in seconds. That is much cheaper than discovering, three months later, that the graph mixed spec v2 and v3, which is exactly the failure vector RAG gave me before the ontology.</p>
<p><strong>The SHACL gate.</strong> Collectors write candidate facts into a <strong>staging graph</strong>: a dedicated repository for the current run, holding candidates that nothing has validated yet. SHACL shapes decide what passes on structure: every document has at least one <code>appliesToRelease</code>, every <code>calls</code> connects two known entities, no orphan nodes. The gate adds one quality rule on top of the shapes: a fact below the confidence threshold is not refused, it is held for a human decision. What fails goes into a <strong>quarantine graph</strong>, another dedicated repository, with the violation report attached. The quarantine is your to-do list: every entry is a collector bug, a modeling gap, or a real data problem in the sources. All three are worth knowing.</p>
<p>The gate runs the same way on both runs of the pipeline, and it is what shapes the <strong>initialization</strong>. The first pass walks every source from an empty store, and nothing that comes out of it is trusted on arrival: it crosses the gate like every later delta, the quarantine fills, and each entry is fixed at its origin (the collector, the shape or the ontology) or stays out when the fact is simply not in the sources. The collectors run again, and the baseline is what survives once the quarantine stops growing, which takes more than one pass. The <strong>update</strong> then walks only what changed since the last run, through the same collectors and the same gate, and Stage 4 says where its facts land.</p>
<p>Every fact that passes keeps its <strong>provenance</strong>. With RDF-star this is pleasantly compact:</p>
<pre><code class="language-yaml">&lt;&lt; :BillingEngine :calls :PKG_INVOICE &gt;&gt;
    :extractedBy   :CollectorC_v2 ;
    :extractedFrom "src/billing/engine.c" ;
    :extractedOn   "2026-05-12"^^xsd:date ;
    :confidence    0.98 .
</code></pre>
<p>The provenance travels with the fact into the fact store and comes back out as these RDF-star triples when the triple store is rebuilt. When a senior developer challenges an answer, you can show not only the path in the graph, but <em>where each edge of the path comes from</em>.</p>
<p><strong>Where the validated facts land.</strong> What passes the gate is merged into the <strong>fact store</strong>, and the <strong>triple store</strong> is built from it plus the repository. That makes four places a fact can sit, and they are easy to confuse: the staging graph while the run is on and nothing is decided, the quarantine graph if the gate refused it, the fact store once it was accepted or judged, and the triple store, rebuilt from the fact store, where the queries of Stage 5 read it.</p>
<p>It is worth being precise about what that triple store contains, because it is less than people assume. Four things: the ontology and the SKOS vocabulary, loaded straight from the repository; the facts the collectors extracted and the gate accepted; the provenance triples above; and the triples the reasoner derives from <code>reasoning/rl/</code>, computed once per release graph and loaded back into it. Three things it does not contain: the Oracle data, which stays in the database behind the R2RML mappings and is never copied; the text of the documents, which stays in the files while the graph keeps only pointers to the sections; and the history, which stays in the fact store. The triple store is rebuilt by CI from the repository plus the fact store, never edited in place, which is the rule of the whole approach seen from the pipeline side: <strong>the repository is the source of truth, the store is a build artifact.</strong></p>
<p>The <strong>fact store</strong> is the other half of that rule, and the half a rebuild cannot regenerate. It holds every fact the gate accepted, with its provenance, and every decision a human made along the way: the verdicts of the review queue and the analysis of the quarantine entries. The facts could be collected again from the tagged sources. The decisions could not, which is why the fact store is the one component to back up, while the triple store is disposable: it holds only the resolved facts, after validation, and it comes back identical from the repository and the fact store at any release. On the first run the two look alike, and it is tempting to ask why there are two. The difference is the history of the decisions: the fact store keeps every verdict, every closure and every candidate that was ever judged, while the triple store holds only what those decisions let through. A fact the expert refused is nowhere in the triple store, so nothing there can stop a stateless collector from proposing it again; only the fact store remembers that it was refused, and Stage 4 shows what happens when the merge forgets to ask.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/65dc66bd-5762-4da1-8b0a-bdfa0cd678e2.svg" alt="Population pipeline from four source families to the fact store. C and C++ (tree-sitter, Doxygen, Pro*C), PL/SQL and Oracle (ALL_DEPENDENCIES, PL/Scope) and PHP (nikic/php-parser, routes) go through deterministic collectors: trusted facts. Documents (Tika, OCR; many versions, two languages) go through LLM extraction, suspected, then a human review queue. Both reach a staging graph with provenance, then the SHACL gate: pass to the fact store, fail to quarantine with a report." style="display:block;margin:0 auto" />

<h2>Stage 4 — Versioning: updating without lying</h2>
<p>A graph that was true at release N and never updated is worse than no graph: people trust it, and it lies. Versioning is not an afterthought. It is a stage of the method, triggered every time the sources change.</p>
<p>One honest line before the rules. My graph covered several releases that already existed, side by side, so the named graphs and the two time axes below were built and tested on real multi-release data. The ongoing update, a new release arriving after the baseline and the delta run that follows it, is the part of the method I designed for that day and have not yet run in production. I describe it anyway, because a versioning stage that stops at the baseline answers nothing.</p>
<ul>
<li><p><strong>Delta runs per release.</strong> The collectors run in CI at every release (nightly for the cheap ones). The document pipeline runs only on new or changed files.</p>
</li>
<li><p><strong>Append-only, close-don't-delete.</strong> New facts land in the named graph of the new release; disappeared facts are not deleted: they stay in the graphs of the releases where they were true, and the fact store <em>closes</em> them with <code>:validUntil</code> the new release. Combined with the release graphs and <code>appliesToRelease</code>, you get two time axes almost for free: the release a fact talks about, and the moment you learned it. Warehouse people will know this as a bitemporal model, obtained here without the ceremony.</p>
</li>
<li><p><strong>A closed edge is not a deprecation.</strong> <code>:deprecatedInRelease</code> is a lifecycle fact, and it comes from two sources: a release note that announces it, or the comparison of two collector runs, and the fact store records which one. The distinction matters because a package that disappears from the code is not always deprecated; sometimes it was just renamed.</p>
</li>
<li><p><strong>The store is rebuilt, never patched.</strong> A delta run does not edit the store in place: it produces a new set of facts, those facts are merged into the fact store one artifact at a time (new ones inserted, survivors kept with their provenance and their review verdicts, vanished ones closed), and CI reloads the store from the repository plus the fact store. A rejection is a decision too, and I learned it the hard way: two facts I had refused because they did not match the code came back in the review queue at the next pass of the baseline, since the collector that produced them is stateless and the merge only asked whether a fact was already accepted, not whether it had already been judged. The rule that follows: a candidate that matches a rejected fact from the same source is dropped and counted, and only a candidate whose source changed since the verdict comes back to the queue, marked as previously rejected. The append-only rule above is about the <em>facts</em> (a closed edge stays in the graphs of the releases where it was true, and the fact store keeps its <code>:validUntil</code>), not about the store file, which remains what Stage 3 called it: a build artifact, reproducible from an empty database at any release.</p>
</li>
<li><p><strong>The ontology itself is versioned too</strong>, but that is a <em>schema</em> change, and it follows the git + CI + review process of the ontology repository (<code>owl:versionInfo</code>, deprecate never delete). Stage 4 is about the <em>data</em>; the governance loop is about the <em>model</em>. Keep the two changes separate and both stay safe.</p>
</li>
<li><p><strong>Drift metrics on a dashboard.</strong> Percentage of unresolved calls, quarantine size, documents with no confirmed release, coverage per subsystem: all four fall out of the gate and the fact store, so put them on a dashboard from the first run. The alert rule I would set is simple: quarantine growing two releases in a row means stop and fix.</p>
</li>
</ul>
<p><strong>The two axes, concretely.</strong> The distinction is worth one paragraph, because collapsing the two is the classic mistake. The release graph and <code>:appliesToRelease</code> say which release a fact talks <em>about</em>: <code>:BillingEngine :calls :PKG_INVOICE</code> sits in the graph of 2022.2, <code>SPEC_INV_V3</code> applies to 2021.1 and 2022.2, and that is exactly what the release filter in Stage 5 reads. <code>:validUntil</code>, in the fact store, says how long we <em>believed</em> a fact: the collectors saw a <code>:calls</code> edge up to release N, stopped seeing it at N+1, and the edge was closed instead of removed. The first axis answers "what is true for the version this developer works on", the second answers "what did we know, and when did we stop knowing it". Both are needed. Without the second one you cannot separate a fact that was never true from a fact you no longer believe, and <em>"when did this behavior change?"</em>, the question senior developers ask most, becomes unanswerable the moment you delete instead of close.</p>
<h2>Stage 5 — Retrieving: the graph selects, before the LLM reads</h2>
<p>At question time the direction reverses: we stop writing the graph and start asking it.</p>
<p>One thing to settle before the steps, because it is the whole design in one sentence: <strong>the retrieval channels are not peers.</strong> The tempting architecture is to put graph traversal, lexical search and vector search side by side, run the three of them on every question and merge the results with a ranking formula. What comes out is a ranked pile: better than a random pile, still a pile, and still not something a developer can verify. Here the ontology and the graph decide <strong>what is on the table</strong>: which artifacts, which documents, which release. The text channels never widen that selection; they only find the right lines inside it. A gate, then a funnel, then the model.</p>
<p>Concretely, three steps:</p>
<ol>
<li><p><strong>Entity linking.</strong> The question, "what happens to an invoice when the client changes his contract in the middle of the month?", is mapped to graph nodes through the SKOS labels, French and English synonyms included. That glossary lookup is what ran on my graph, and it carried the load on its own. Around it, the order I would recommend depends on the case, and it is boring on purpose: <strong>exact match first</strong>, because a large share of what a developer types contains a symbol (<code>PKG_INVOICE</code>, <code>T_CONTRACT</code>, an <code>ORA-</code> code), and an exact lookup on the labels resolves those without any model at all; then the glossary built in Stage 3, which handles most of what is left; then, if the labels still miss phrasings, a small embedding fallback, with every catch becoming a new <code>altLabel</code> so that the fallback shrinks over time. The first and the last are options; the glossary in the middle is the part that must exist.</p>
</li>
<li><p><strong>SPARQL traversal, filtered by release.</strong> Starting from the linked entities, queries collect the relevant subgraph (callers, called packages, touched tables, implementing rules), <strong>restricted to the release the user works on</strong>, which means the named graph of that release plus the shared graph, whose documents are filtered on <code>appliesToRelease</code> while the rules and lifecycle facts come as they are. This filter is the single biggest accuracy win. Be honest about its weakness, though: for the documents in the shared graph, the filter is query discipline, not physics. One query that forgets the <code>appliesToRelease</code> clause and versions mix again. This is exactly why the queries live in the repo and are reviewed like code, and why the SPARQL regression tests include a "wrong release must return nothing" case.</p>
</li>
<li><p><strong>Context assembly.</strong> The subgraph is serialized compactly, and the exact document <em>sections</em> it points to are fetched. Vector search did not disappear from my stack. It simply moved below the gate: it still finds the right paragraphs <em>inside</em> a long document. And if you build this today, put a plain lexical index under the gate next to it: when the question carries a symbol, exact search inside those same sections beats the embedding every time, because <code>CALC_PRORATA</code> is a string, not a meaning. But the graph decides <strong>which documents and which code artifacts are on the table</strong>, and the text channels only rank and read within what it allowed.</p>
</li>
</ol>
<p>The result is a small, dense, versioned context, not a pile of look-alike chunks.</p>
<p><strong>A word on how the lexical channel and the glossary relate</strong>, because it is tempting to read the two as rivals: if exact match works, why keep SKOS? They operate at different levels. In step 1 the exact lookup runs against the <em>graph's labels</em>, and those labels already carry the synonyms: <code>CONTRACT</code>, <code>ctr</code> and "souscription" all hang off the same node, so the lookup succeeds whichever of the three the user typed. In step 3 the lexical search runs against <em>raw text</em>, where it gets no such help. A search for <code>CONTRACT</code> finds the database objects and misses every C file that says <code>ctr</code>, silently, which is the dangerous kind of miss. So the glossary does not compete with the lexical channel, it feeds it: SKOS expands the term into its <code>altLabel</code>s and the index searches all of them at once. Without it, a lexical index on a bilingual corpus retrieves one name in three, and tells you nothing about the two it missed.</p>
<h3>What the graph does not answer</h3>
<p>Being precise about this is what keeps the method honest, and it is the question that always comes right after a demo: <em>is everything supposed to become an ontology assertion?</em> No. The graph answers four kinds of question, and only four: <strong>identity</strong> (which thing is this; is <code>ctr</code> the same concept as "souscription"?), <strong>classification</strong> (is this a package, a spec, a release note?), <strong>relationship</strong> (what calls it, what does it write, which rule does it implement?), and <strong>validity</strong> (for which release is this true, and what superseded it?).</p>
<p>It does not answer <em>content</em> questions ("what does §4.2 actually say?", "what does this four-hundred-line C function do?"), and it does not answer <em>similarity</em> questions ("is there another place that computes this differently?"). Those are text questions, and text questions are answered by reading text; the graph's job was to decide <strong>which</strong> text. That is the whole reason the stack keeps three channels instead of one, and the reason the ontology stays small: <strong>it is a map, not a replica.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/46839ad2-845b-4c1d-8be2-e2da65d18583.svg" alt="The retrieval gate for a developer on release 2022.2 asking about the pro-rata rule. Entity linking, recommended order: exact match on symbols, SKOS labels in French and English, embedding fallback. Then release-filtered SPARQL decides what is on the table: contract_change.tpl, BillingEngine, PKG_INVOICE.CALC_PRORATA, T_INVOICE and SPEC_INV_V3 section 4.2. Lexical and vector search run only inside that selection. Refused: spec v2, spec v4 and the rest of the corpus, not in the context at all." style="display:block;margin:0 auto" />

<h2>Stage 6 — Serving: expose the graph as tools, not as a dump</h2>
<p>The last stage is the interface between the graph and the model. Two serving modes proved useful:</p>
<p><strong>Assembled context</strong>, for question answering. The context service runs the stage-5 funnel and hands the LLM the finished package: subgraph plus document sections plus the provenance. The model's job is only to write the answer, and every answer ships with its <strong>traceable path</strong>: this template → this module → this package → this table → this document, this release. Senior developers can verify a path but never a pile of similar chunks.</p>
<p><strong>Graph tools</strong>, for agents. Instead of one big context, the agent gets a small set of callable tools backed by SPARQL (exposed through MCP): <em>resolve this term to an entity</em>, <em>give me the subgraph around X</em>, <em>what is the impact of changing Y?</em>, <em>which documents apply to release R?</em>. This is what makes the <strong>coding and correction loop</strong> safe: before proposing a fix, the agent queries the impact (who calls this procedure, which business rules does it implement, which screens touch this table), and the generated change respects what the graph knows. After the merge, the cycle restarts at Stage 1: most of the time the decision table already covers what changed and that pass costs nothing; when the change brings in something the ontology does not describe yet, this is where it gets added, and the collectors run again.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/785903b1-9cde-47d1-90f6-151c197d4ed1.svg" alt="The context service exposes the graph as tools over MCP. A question from a user or an agent on release R goes through entity linking on SKOS labels, SPARQL traversal filtered by release, and context assembly with the exact document sections, then to the LLM or agent, which writes the answer or codes the fix. Tools: resolve-entity, subgraph, impact-of-change, docs-for-release. The answer carries the traceable path; a wrong answer becomes a change proposal." style="display:block;margin:0 auto" />

<p>And when the model still gives a wrong or incomplete answer? That is not a failure of the method. It is its input: the missing fact or wrong link becomes a change proposal, and the correction loop of the ontology repository takes over.</p>
<h2>Two walkthroughs, end to end</h2>
<p>Theory is nice; let me show the machine running. Two real-style scenarios, one technical and one business, both around the same rule, because that is the point: <strong>the same graph serves both audiences</strong>.</p>
<h3>Walkthrough 1 — a developer hunts a bug</h3>
<p><strong>The question.</strong> A developer on release <strong>2022.2</strong> types: <em>"The pro-rata amount is wrong when a contract changes in the middle of the month. Which code implements this rule, and which spec defines it?"</em></p>
<p><strong>Step 1: entity linking.</strong> "pro-rata" matches <code>skos:altLabel</code> "prorata" (and the French "au prorata") on the node <code>:ProRataRule</code>. "Contract changes" resolves to the business term <code>:ContractChange</code>, linked to <code>:T_CONTRACT</code>. The release comes from the user's session: <code>:R2022_2</code>.</p>
<p><strong>Step 2: SPARQL traversal, release-filtered.</strong> One reusable query from <code>queries/</code> does the walk, over the named graph of the developer's release plus the shared one:</p>
<pre><code class="language-sql">SELECT ?artifact ?proc ?doc ?section
FROM g:R2022_2
FROM g:shared
WHERE {
  ?artifact :implementsRule :ProRataRule ;
            :hasProcedure   ?proc ;
            :describedBy    ?doc .
  ?doc :appliesToRelease :R2022_2 ;
       :hasSection       ?section .
  FILTER NOT EXISTS { ?artifact :deprecatedBefore :R2022_2 }
}
</code></pre>
<p>It returns <code>PKG_INVOICE</code> / <code>CALC_PRORATA</code>, described by <strong>Spec v3 §4.2</strong>, and <em>only</em> v3: Spec v2 is excluded because it does not apply to 2022.2, and Spec v4 does not exist yet for this release. The traversal also collects the callers (<code>BillingEngine</code>, <code>contract_change.tpl</code>) and the touched tables.</p>
<p><strong>Step 3: context assembly.</strong> The subgraph, the text of §4.2 (found by vector search <em>inside</em> the sections the graph selected), and, thanks to provenance, the exact source file of <code>CALC_PRORATA</code>.</p>
<p><strong>Step 4: what the developer sees.</strong></p>
<blockquote>
<p><strong>Rule:</strong> pro-rata invoicing (Spec v3 §4.2), valid for releases 2021.1 → 2022.2. The spec says the pro-rata is computed <strong>per day</strong>. The code in <code>PKG_INVOICE.CALC_PRORATA</code> (src line shown) still rounds <strong>per month</strong>, which is the v2 behavior. The divergence is your bug, and since v3 applies from 2021.1, the bug is two releases older than you think. <strong>Path:</strong> <code>contract_change.tpl</code> → <code>BillingEngine</code> → <code>PKG_INVOICE.CALC_PRORATA</code> → <code>T_INVOICE</code> (spec v3 §4.2, release 2022.2). <strong>Before you fix:</strong> <code>impact-of-change(CALC_PRORATA)</code> → 2 C modules, 1 batch job, 1 screen. Note: this package is deprecated in 2024.1 and replaced by <code>PKG_INVOICE_V2</code>. If the bug exists there too, two fixes are needed.</p>
</blockquote>
<p>Every claim carries a link the developer can open. Without the release filter, the assistant would have blended v2, v3 and v4 into one confident, wrong explanation: the exact failure that pushed me toward the ontology in the first place.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/92bcfe3e-1000-4d34-aa7b-4313b6c06a0d.svg" alt="A developer bug hunt on release 2022.2 in four steps. 1, entity linking: pro-rata matches the SKOS glossary and resolves to ProRataRule. 2, SPARQL traversal filtered by 2022.2 returns PKG_INVOICE.CALC_PRORATA described by spec v3 section 4.2, plus its callers; spec v2 and spec v4 are excluded. 3, context assembly: the subgraph, the text of section 4.2, the source of CALC_PRORATA. 4, the answer: the spec says per day, the code rounds per month, with the traceable path and the impact of a change." style="display:block;margin:0 auto" />

<h3>Walkthrough 2 — a business question across releases</h3>
<p><strong>The question.</strong> A product owner asks, in French: <em>"Comment est facturé un client qui change de contrat en milieu de mois ? Nos clients sont sur la 2021.1 et la 2023.1. Est-ce que la réponse est différente ?"</em></p>
<p><strong>Step 1: entity linking.</strong> "facturé... changement de contrat en milieu de mois" resolves through the French <code>altLabel</code>s to the same <code>:ProRataRule</code>. No translation step, no embedding gymnastics: the bilingual glossary from Stage 3 pays for itself here. Two releases are named, so the traversal will run <strong>once per release</strong>.</p>
<p><strong>Step 2: traversal, twice.</strong> The same query as above, once with <code>:R2021_1</code>, once with <code>:R2023_1</code>. For 2021.1 it returns Spec v3 §4.2; for 2023.1, Spec v4 §5.1, because v4 applies to 2023.1 and <code>:supersedes</code> v3.</p>
<p><strong>Step 3: assembly.</strong> Both sections, each tagged with its release range, plus the rule node they share.</p>
<p><strong>Step 4: what the product owner sees.</strong></p>
<blockquote>
<p><strong>Same rule, two behaviors:Releases 2021.1 → 2022.2</strong> (Spec v3 §4.2): the invoice is split per day; the old price applies until the change date, the new price after. <strong>Releases 2023.1 →</strong> (Spec v4 §5.1): same daily split, but the new price applies immediately and a one-time adjustment line is added on the next invoice. A client on 2021.1 and a client on 2023.1 asking the same question get <strong>different, both correct</strong> answers. Each statement above links to its spec section and release range.</p>
</blockquote>
<p>The LLM's only job was to turn two versioned facts into client-friendly French. It could not mix the versions, because it never saw the wrong one.</p>
<p>One honest detail connects the two walkthroughs: this business answer describes what the <em>spec</em> says, and it is trustworthy because the rounding bug from the first walkthrough had been fixed in the meantime. If it had not been, the answer could still have carried a warning: code and spec meet on the same <code>implementsRule</code> edge, so the context handed to the model holds both the section and the procedure, and the divergence is there to be read, as it was for the developer in the first walkthrough. An assistant that answers from documents alone never sees the code.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/1ef09572-b4b0-4343-ae75-5dbb08bcadd8.svg" alt="A product owner question asked in French about mid-month contract changes on releases 2021.1 and 2023.1. The bilingual SKOS glossary resolves it to ProRataRule with no translation step. The same query runs twice: release 2021.1 returns spec v3 section 4.2, old price until the change date; release 2023.1 returns spec v4 section 5.1, new price immediately plus an adjustment line. The answer gives one rule with two behaviors, both correct, each linked to its spec section and release range." style="display:block;margin:0 auto" />

<p>Two audiences, one graph, zero mixed versions. That is the demonstration I use to convince a room in fifteen minutes. One caveat belongs in that room too: the answer ships its path, and the path is what makes it checkable, but a checkable path is not a correct rule. The graph reports the system as it is, bugs included; its purpose is not to correct what exists. If <code>CALC_PRORATA</code> is wrong, the answer will faithfully describe a wrong computation, with the pointer that lets anyone see it and report it.</p>
<h2>Objections I expect, and how I answer them</h2>
<p>A method is only credible if it survives its own critics. Here are the four strongest objections I know against this method, and my honest answers.</p>
<h3>Your release filter is discipline, not a guarantee</h3>
<p>Partly true. For the structural facts I chose <strong>named graphs</strong>, one per release, so the isolation is physical: a query that runs over <code>g:R2022_2</code> cannot see a <code>:calls</code> edge collected in 2024.1, whatever its author forgot. What stays discipline is the shared graph, where the documents carry <code>appliesToRelease</code> and one forgotten clause silently mixes v2 and v3 again. The alternative is validity predicates on every fact (<code>appliesToRelease</code> and <code>validUntil</code> on the edges themselves): one graph, no duplication, and nothing but discipline between a query and a mixed answer. Named graphs have their price too: storage duplication, and painful cross-release questions, since "when did this behavior change?", exactly the question senior developers ask the most, now needs two graphs or the fact store's <code>validUntil</code> instead of one triple pattern. The guardrails are the same either way: shared queries in the repo, reviewed like code, and a regression test where the wrong release must return nothing. If your releases are many and your cross-release questions frequent, predicates are the lighter choice. Both are defensible; the important thing is to know which trade you are making.</p>
<h3>Your review queue will die under its own weight</h3>
<p>This is the classic death of metadata projects, and the objection I take most seriously. Twenty years of documents generate tens of thousands of LLM proposals; "a domain expert confirms in seconds" is true per item and false in total. The answer I designed for it is calibrated auto-acceptance: validate a random sample per proposal type, measure the precision, auto-accept the types that score above a threshold, and queue only the uncertain middle. And track the queue size as a drift metric: it must shrink release after release. If it grows, the pipeline is broken, not the reviewers.</p>
<h3>Deterministic does not mean correct</h3>
<p>Also true. Static analysis does not hallucinate, but it lies in its own way: function pointers, same-named symbols in different modules, dead code that still produces edges, files that no longer compile. Deterministic means <em>reproducible</em>: a false <code>calls</code> edge born from a name collision enters the graph with confidence 1.0 and full trust. Two defenses: keep the "unresolved" marking aggressive (extract only what is certain), and let the correction loop do its job. When a senior developer sees a wrong path in an answer, the provenance tells you exactly which collector produced the bad edge. Trust is earned by being correctable, not by being perfect.</p>
<h3>Stage 1 is waterfall thinking</h3>
<p>It would be, if the decision table were signed once and framed on a wall. You cannot know upfront that you will never need OWL inference, or that documents will not need richer modeling: some needs only appear when queries fail in Stage 5. So the decision table is a <em>living contract</em>: revisited at every release, with stage-5 failures as its main input. Stage 1 does not mean "design everything first"; it means "never write a collector without deciding, consciously, which standard it feeds". Those are two different disciplines.</p>
<h2>What I would tell you before you start</h2>
<ul>
<li><p><strong>Do the analysis stage for real.</strong> A few workshops mapping artifacts to standards save months of remodeling. The decision table is your contract.</p>
</li>
<li><p><strong>Start with the database collector.</strong> For a PL/SQL-heavy system it is the highest value for the lowest effort: the dictionary gives you thousands of reliable edges in a day.</p>
</li>
<li><p><strong>Do code before documents.</strong> The code graph gives the skeleton; documents then attach to entities that already exist. Doing documents first means linking prose to nothing.</p>
</li>
<li><p><strong>Keep the LLM at the border, not in the core.</strong> Classification, version detection, link proposals: yes. Direct writes to the graph: never. The review queue is not bureaucracy; it is what makes the graph a source of truth.</p>
</li>
<li><p><strong>Measure coverage honestly.</strong> A statement like "the graph knows 60% of the C modules" is useful and honest, and it is a roadmap. Silent gaps are how trust dies.</p>
</li>
<li><p><strong>One subsystem first.</strong> A complete six-stage pipeline on one subsystem teaches you more than six half-collectors on everything.</p>
</li>
</ul>
<h2>Conclusion</h2>
<p>Six stages, one method: <strong>analyze</strong> each artifact family and give it the right standard; <strong>collect</strong> with deterministic tools wherever possible; <strong>transform</strong> with entity resolution, human validation and a SHACL gate; <strong>version</strong> with append-only facts so the graph never lies about a release; <strong>retrieve</strong> by letting the graph select a small, dense, release-filtered context; <strong>serve</strong> it as assembled context for answers and as callable tools for agents.</p>
<p>None of it is glamorous: parsers, SQL against the data dictionary, review queues, dashboards. But this is the part that decides everything: the ontology gives the graph its shape, the pipeline gives it its truth, and the serving layer is what finally turns twenty years of scattered meaning into answers a senior developer can verify.</p>
<h2>Let's keep in touch</h2>
<p>As always, I would love to hear from you. Which stage looks the hardest in your context: the collecting, the versioning, or the serving? Have you found better tools for the extraction? Share your experience in the comments. I answer all of them.</p>
<p>If you enjoyed this article, follow me on <a href="https://x.com/elie_nehme">X</a> and connect with me on <a href="https://www.linkedin.com/in/elie-nehme/">LinkedIn</a> so you do not miss the next part, and feel free to share it with a colleague who is fighting with a legacy monster of their own. Everything I write also lands on my site, <a href="https://elienehme.fr">elienehme.fr</a>, in English and in French: each article gets a short summary and the reason I wrote it, next to shorter notes and ideas.</p>
<hr />
<p><em>Sources and further reading:</em></p>
<ul>
<li><p><a href="https://elienehme.fr/en/writing/ontology-based-context-engineering-when-rag-is-not-enough/">Ontology-Based Context Engineering: When RAG Is Not Enough</a></p>
</li>
<li><p><a href="https://www.doxygen.nl/">Doxygen</a>, <a href="https://clang.llvm.org/docs/LibClang.html">libclang</a>, <a href="https://cscope.sourceforge.net/">cscope</a>, <a href="https://ctags.io/">Universal Ctags</a>, <a href="https://tree-sitter.github.io/">tree-sitter</a>, <a href="https://github.com/nikic/PHP-Parser">nikic/php-parser</a></p>
</li>
<li><p>Oracle documentation: <a href="https://docs.oracle.com/en/database/oracle/oracle-database/19/adfns/plscope.html">PL/Scope</a>, <code>ALL_DEPENDENCIES</code></p>
</li>
<li><p>W3C: <a href="https://www.w3.org/TR/shacl/">SHACL</a>, <a href="https://www.w3.org/2021/12/rdf-star.html">RDF-star</a>, <a href="https://www.w3.org/TR/prov-o/">PROV-O</a>, <a href="https://www.w3.org/TR/skos-primer/">SKOS</a>, <a href="https://www.w3.org/TR/r2rml/">R2RML</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Ontology-Based Context Engineering: When RAG Is Not Enough]]></title><description><![CDATA[RAG alone failed on a 2M-line legacy system. How an ontology with RDF, SHACL and SPARQL, gives an LLM release-filtered context and a traceable path]]></description><link>https://elie29.hashnode.dev/ontology-based-context-engineering-when-rag-is-not-enough</link><guid isPermaLink="true">https://elie29.hashnode.dev/ontology-based-context-engineering-when-rag-is-not-enough</guid><category><![CDATA[ai agents]]></category><category><![CDATA[context engineering]]></category><category><![CDATA[ontology]]></category><category><![CDATA[llm]]></category><category><![CDATA[RAG ]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Fri, 11 Sep 2026 08:01:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/9eef286d-768c-4a78-b099-d612715031cb.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Note: Originally published on <a href="https://medium.com/@elie29/ontology-based-context-engineering-when-rag-is-not-enough-124e6b1de6bb">Medium</a></p>
</blockquote>
<p>In my previous articles, I discussed <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Context Engineering</a> and the <a href="https://elie29.hashnode.dev/i-tried-bmad-on-a-real-feature">BMAD method</a>. Today, I want to take it one step further and introduce <strong>Ontology-based Context Engineering</strong>.</p>
<p>I will explain what it is, how it compares to RAG and other techniques, which standards exist (RDF, OWL, SKOS, SHACL and friends), how to choose between them, and finally how I applied all of this to a real legacy system:</p>
<ul>
<li><p>More than 2 million lines of C and C++ code</p>
</li>
<li><p>Extensive PHP MVC code and PL/SQL</p>
</li>
<li><p>Hundreds of unstructured documents across multiple versions and releases</p>
</li>
</ul>
<h2>1. The problem: The meaning is never in one place</h2>
<p>If you work with a modern, well-documented application, maybe you do not have this problem. I did not have this luck.</p>
<p>In a large legacy system, the <em>meaning</em> of any concept is spread across many locations, split and scattered:</p>
<ul>
<li><p>The <strong>C/C++ code</strong> knows <em>how</em> things are computed, but not <em>why</em></p>
</li>
<li><p>The <strong>PL/SQL packages</strong> contain critical business rules, hidden inside thousands of procedures</p>
</li>
<li><p>The <strong>PHP <em>Smarty</em> templates</strong> know how users interact with the data</p>
</li>
<li><p>The <strong>documents</strong> (specifications, release notes, migration guides) explain the <em>why</em>, but they exist in many versions, for many releases, and they often contradict each other</p>
</li>
<li><p>And a big part of the knowledge is only in the heads of people who are now enjoying a peaceful retirement 😀</p>
</li>
</ul>
<p>When you ask an AI assistant a question like <em>"What happens to an invoice when the client changes his contract in the middle of the month?"</em>, the answer is not in one file. It is distributed across a C module, two PL/SQL packages, a database table, a specification from 2017 and a correction note from 2021. No single chunk of text contains the answer.</p>
<p>However, that answer exists, but only as a <em>path</em> between all those artifacts. And for this reason, it has to be modeled properly first.</p>
<h2>2. What is ontology-based context engineering?</h2>
<p><strong>Context engineering</strong> is the discipline of preparing and selecting the right information to put into the context of an LLM. The model depends on the context you give it.</p>
<p>An <strong>ontology</strong> is a formal, explicit model of a domain: the types of things that exist (module, package, table, document, release, business rule), the relationships between them (<em>calls</em>, <em>writes to</em>, <em>is described by</em>, <em>applies to release</em>, <em>supersedes</em>), and the constraints and logic that connect them.</p>
<p><strong>Ontology-based context engineering</strong> means: instead of throwing raw text at the model, you first build a machine-readable map of your domain (a knowledge graph structured by an ontology), and you use this map to select, connect, and validate the context before passing it to the LLM.</p>
<h3>What about embeddings?</h3>
<p>The key idea is simple: <strong>embeddings capture similarity, ontologies capture meaning.</strong></p>
<p>A vector database can tell you that two paragraphs "look alike". An ontology can tell you that <code>PKG_INVOICE</code> writes to table <code>T_INVOICE</code>, is called by the billing engine, is described by specification v3, and is deprecated since release <code>2024.1</code>. These are facts, not similarities.</p>
<blockquote>
<p><strong>The two techniques can be used together, but they play different roles.</strong></p>
</blockquote>
<p>Facts decide <em>what the model is allowed to look at</em>: which artifacts, which documents, which release. Similarity then decides which paragraph inside that selection actually answers.</p>
<p>Both techniques are used; only the order is fixed. <strong>And that order is the whole design.</strong></p>
<h2>3. The landscape: RAG, GraphRAG and ontologies</h2>
<p>Before choosing the ontology road, I tried almost everything else. Here is the comparison, based on my experience. And, of course, why classic RAG starts to fail in the situation I described earlier.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/67c836f5-358d-4599-81b2-84ca8b7feaaf.svg" alt="Six retrieval techniques compared on mechanism, strengths, weaknesses and best use. Long context: zero setup, noisy, lost at 2M+ lines. Fine-tuning: speaks your domain, costly, stale each release. Vector RAG: quick, but isolated chunks, mixed versions. GraphRAG: better multi-hop, but graph extracted not designed. Code graph: precise on code, blind to documents. Highlighted last row, ontology plus knowledge graph: precise, explainable, version-aware and traceable, at real upfront cost." style="display:block;margin:0 auto" />

<p><em><strong>But be careful:</strong></em> Vector RAG still works very well for simple, single-hop questions, and it is much cheaper to build. The point is not that <strong>RAG is bad</strong>. The point is that <strong>vector-only RAG does not explicitly represent relationships and versions</strong>. In a legacy system, relationships and versions are exactly where the meaning lives.</p>
<h2>4. The standards: RDF, OWL and friends</h2>
<p>When you decide to build an ontology, you enter the world of <strong>W3C Semantic Web standards</strong>. The names can be scary, but the ideas are simple. I experimented with some of these technologies and studied the others to understand where they fit. Here is my map.</p>
<ul>
<li><p><strong>RDF (Resource Description Framework):</strong> The foundation. Everything is expressed as triples: <em>subject → predicate → object</em> (<code>:BillingEngine :calls :PKG_INVOICE</code>). It is the fundamental data model.</p>
</li>
<li><p><strong>RDFS (RDF Schema):</strong> A lightweight schema layer on top of RDF: classes, subclasses, domains and ranges of properties. Often enough for lightweight schemas and simple ontologies.</p>
</li>
<li><p><strong>OWL (Web Ontology Language):</strong> The more expressive option. Based on description logics, it lets a reasoner infer new facts: disjoint classes, cardinalities, transitive properties, equivalences, and much more.</p>
</li>
<li><p><strong>OWL 2 DL</strong>: It is the decidable description-logic fragment of OWL 2 and the main target of description-logic reasoners. It is more expressive than the OWL 2 profiles, but more restrictive than OWL 2 Full. <strong>HermiT</strong> is a common reasoner for OWL 2 DL. Powerful, but the learning curve is real.</p>
</li>
<li><p><strong>OWL 2 EL:</strong> An OWL 2 profile designed for large ontologies and scalable reasoning. It gives up some expressiveness in exchange for more scalable reasoning. <strong>ELK</strong> is a reasoner designed for this profile.</p>
</li>
<li><p><strong>OWL 2 QL:</strong> An OWL 2 profile designed for efficient <strong>query</strong> answering over large amounts of relational data. Particularly interesting when the underlying data lives in existing databases.</p>
</li>
<li><p><strong>OWL 2 RL:</strong> An OWL 2 profile designed for <strong>rule-based</strong> reasoning. Useful when reasoning can be expressed efficiently through rules and database technologies.</p>
</li>
<li><p><strong>SKOS (Simple Knowledge Organization System):</strong> For vocabularies, thesauri and taxonomies: broader/narrower terms, preferred and alternative labels. Perfect for business glossaries.</p>
</li>
<li><p><strong>SHACL (Shapes Constraint Language):</strong> Validation. It checks that your graph respects the rules you define ("every PL/SQL package must be linked to at least one specification"). Think of it as schema validation for your knowledge graph.</p>
</li>
<li><p><strong>SPARQL:</strong> The query language, the SQL of graphs.</p>
</li>
<li><p><strong>R2RML:</strong> A W3C standard for mapping relational databases to RDF. It lets you define how tables and columns map to your RDF vocabulary.</p>
</li>
<li><p><strong>OBDA (Ontology-Based Data Access) / Ontop:</strong> An approach and tooling for querying existing data through an ontology. With a virtual knowledge graph, the data can stay in the relational database while SPARQL queries are translated into SQL. For a PL/SQL-heavy system, this one is gold.</p>
</li>
<li><p><strong>Labeled Property Graphs (Neo4j):</strong> Not part of the W3C RDF/OWL stack, but a pragmatic alternative: great developer experience and fast to start, with a different graph model and without the RDF/OWL semantic layer.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/79d6e7d1-1908-401f-b531-fa7427f28d46.svg" alt="Eight semantic standards compared on role, power, reasoning, validation and learning curve. RDF: the triple model, the foundation. RDFS: light schema, basic inference. OWL: formal semantics and inference, steep curve. SKOS: business terms and taxonomies. SHACL: constraints and validation, not inference. SPARQL: the query language. R2RML and OBDA: map a relational database, no duplication. LPG: speed over RDF/OWL semantics. Caption: layers, not competitors." style="display:block;margin:0 auto" />

<h3>So, which is better?</h3>
<p>Wrong question, and this is one of the most important lessons I learned. <strong>Although they solve different problems, these standards can be combined as layers.</strong> The realistic stack for a legacy project is:</p>
<blockquote>
<p><em>RDF</em> for the facts and relationships, <em>RDFS</em> where basic schema and hierarchy are useful, <strong>SKOS</strong> for the business vocabulary, <strong>SHACL</strong> for validation, <strong>SPARQL</strong> for querying, <strong>R2RML</strong> to plug in the relational database, and <strong>OWL</strong> only where inference is really worthwhile (impact analysis, derived relationships, deprecation rules).</p>
</blockquote>
<p>Using OWL everywhere can make ontology projects difficult to maintain. A pragmatic layered stack is how they survive.</p>
<h3>How to choose: My Decision Criteria</h3>
<ol>
<li><p><strong>Do you need automatic inference?</strong> In a legacy system, the answer may be different depending on the domain. Some parts may only need <strong>RDF</strong> to represent facts and relationships; others may need <strong>RDFS</strong> for basic schema and hierarchy; and only the parts where inference really pays off need <strong>OWL</strong>.</p>
</li>
<li><p><strong>Do you need to guarantee quality?</strong> In a legacy project with many contributors, yes → <strong>SHACL from day one.</strong> Define the constraints that your graph must respect and validate it continuously. SHACL is specifically designed for describing and validating RDF graphs against defined conditions.</p>
</li>
<li><p><strong>Where does the data live?</strong> Usually in more than one place, and each answer leads somewhere different:</p>
<ul>
<li><p><strong>Truth in a relational database</strong> (my case: Oracle + PL/SQL) → <strong>R2RML / OBDA</strong> exposes it through the ontology as a <em>Virtual Knowledge Graph.</em></p>
</li>
<li><p><strong>Truth in documents</strong> (specifications, release notes) → nothing to virtualize; everything is loaded into a graph: <strong>RDF</strong> (optionally with an <strong>OWL 2 ontology</strong>) or a <strong>property graph</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Do you need a business glossary?</strong> Legacy systems often have three names for the same concept → <strong>SKOS</strong> is a good fit for business terms, synonyms and taxonomies.</p>
</li>
<li><p><strong>One stack or both?</strong> If the graph must live for years and be shared across teams and tools → the <strong>W3C stack</strong> is a strong choice. If it is an internal tool where developer productivity and graph traversal matter more than semantic-web interoperability → a <strong>property graph</strong> can be a fair choice. And it is not always either/or: a valid pattern is to keep the <strong>W3C stack as the source of truth</strong> and add a <strong>property-graph projection</strong> for the parts of the domain that need graph algorithms (Neo4j Graph Data Science, GDS), at the cost of a sync pipeline, since LPG does not provide OWL’s standard semantics.</p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/f5f01c6b-4dd4-4adf-8463-db6c0bb2837e.svg" alt="Decision tree, five numbered questions for choosing a semantic stack. 1: which layers, RDF for facts, plus RDFS for schema and hierarchy, plus OWL 2 only if inference is needed. 2: need quality guarantees, then SHACL. 3: where the data lives, a relational database leads to R2RML/OBDA with Ontop as a virtual graph, documents to loading into a graph. 4: business glossary leads to SKOS. 5: one stack or both, W3C for long-lived, Neo4j for internal tools, both with W3C as source of truth." style="display:block;margin:0 auto" />

<h3>Where the standards live</h3>
<p>The question everybody asks right after the decision, and the one almost no article answers: where do these files sit, and what keeps them accurate?</p>
<p>Here is the good news: <strong>the artifacts are text-based.</strong> An OWL ontology, a SKOS glossary, a SHACL shapes graph and an R2RML mapping can all be represented using <strong>Turtle</strong> files. So, the answer is very simple: <strong>put them in a Git repository, review changes, test them in CI, and treat the ontology artifacts as code.</strong></p>
<p>In my case, I did not need a GDS, so I skipped the property-graph stack. My repository looks like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/51d6ed43-2847-40d2-a965-68f6b0fb59b8.png" alt="Legacy ontology repository structure and reasoning workflow" style="display:block;margin:0 auto" />

<p>Files in <code>ontology/</code> declare what <em>exists</em>: the classes, the relations, the hierarchy, and some metadata. The OWL layer is limited to declarations and a few <code>rdfs:range</code>.</p>
<p>Be careful with <code>rdfs:range</code>, I got caught the first time: <strong>a range is not a constraint</strong>. If a collector emits <code>:writesTable</code> towards something that is not a table, the engine does not complain, unless you declared that class disjoint from <code>:DbTable</code>, which I had not. It infers that the target is a <code>:DbTable</code>. Checking that the target really is a table is the job of SHACL, not of the ontology.</p>
<p>Moreover, the axioms that make a reasoner derive new facts live next door, because <strong>a profile belongs to the engine that consumes the ontology, not to the ontology itself.</strong></p>
<h2>5. My Experience: A Massive Legacy Codebase</h2>
<p>Now the real story. The project is a system with <strong>more than 2 million lines of C and C++</strong>, a large PHP layer, an enormous quantity of <strong>PL/SQL</strong> (a very big part of the business logic lives in the database), and hundreds of unstructured documents (specifications, release notes, migration guides) in <strong>many different versions, for many different releases</strong>. Some documents describe behavior that no longer exists. Some describe behavior that exists only from release X to release Y. Nothing tells you which one is true today.</p>
<h3>What I tried first (and why it was not enough)</h3>
<p>I did not start with ontologies. Instead, I started with the simple techniques, and I spent a lot of time on them:</p>
<p><strong>Vector RAG:</strong> I chunked the code and the documents, embedded everything, and retrieved by similarity. For simple questions ("what does this function do?") it was fine. For real questions, it failed in a predictable way: it returned five chunks that <em>looked</em> similar to the question, taken from <strong>different releases of the same specification</strong>, and the model mixed them into one answer that looked right and was not. The retrieval had no notion of version or "this document supersedes that one".</p>
<p><strong>Better chunking, metadata filters, rerankers:</strong> This brought some improvements, but the fundamental problem remained. People always suggest filtering by release, and they are right that it would fix the version mixing. The trouble is that I had nothing to filter on: the documents did not carry a reliable release tag, and producing that tag turned out to be most of the work I describe later. Similarity search does not explicitly model or reliably follow the path between those artifacts.</p>
<p><strong>GraphRAG:</strong> I let an LLM extract entities and relations from the corpus. On clean English text this works reasonably well. On a mix of C code, PL/SQL, French/English documents and twenty years of naming conventions, the extracted graph was noisy: duplicated entities, invented relations, and no predefined schema to control any of it. Interesting for exploration but unusable as a source of truth in my case.</p>
<p>One nuance I only understood later: I did not throw that step away. Letting an LLM read documents and propose entities and links is exactly what my document pipeline still does. The difference is not the extractor, it is where its output lands. In the GraphRAG pipeline I tested, the extracted information becomes part of the graph. In mine, it lands in a staging area, behind a schema decided in advance, a validation gate and a human review queue.</p>
<p>I still use it to explore a subsystem I do not know: the entities it proposes are a decent first draft of the classes. But not as my source of truth. The pipeline I tested did not keep the release semantics, so it blended v2 and v3 like vector RAG did.</p>
<blockquote>
<p><em>Each attempt was time consuming, and in terms of accuracy, none of them fit well enough. That is when I accepted that the problem was</em> <em><strong>not only retrieval</strong></em>. The deeper problem was <em><strong>representation</strong></em>.</p>
</blockquote>
<h3>The ontology approach</h3>
<p>So I inverted the logic. Instead of asking "how do I retrieve better chunks?", I asked "what are the <em>things</em> in this system, and how are they connected?". The core ontology was surprisingly small, about a dozen classes:</p>
<p><code>CModule</code>, <code>CppModule</code>, <code>SmartyTemplate</code>, <code>PhpController</code>, <code>PlsqlPackage</code>, <code>PlsqlProcedure</code>, <code>DbTable</code>, <code>SpecificationDocument</code>, <code>ReleaseNote</code>, <code>Release</code>, <code>BusinessRule</code>, <code>BusinessTerm</code>.</p>
<p>And the relations that carry the meaning: <code>calls</code>, <code>readsTable</code>, <code>writesTable</code>, <code>hasProcedure</code>, <code>implementsRule</code>, <code>describedBy</code>, <code>appliesToRelease</code>, <code>supersedes</code>, <code>deprecatedInRelease</code>, <code>replacedBy</code>.</p>
<p>Those classnames describe <em>my</em> system, not the method. A Java and PostgreSQL shop would write <code>SpringService</code> and <code>PgFunction</code> where I wrote <code>CModule</code> and <code>PlsqlPackage</code>. The collectors and parsers would change, of course, but the ontology engineering approach would remain the same. Many of the relations remain useful across implementations, although their exact semantics and extraction rules depend on the system: <code>calls</code>, <code>writesTable</code>, <code>describedBy</code>, <code>appliesToRelease</code> are about how a system is assembled and how its truth changes over time, not about what it is written in.</p>
<h3>The twelve classes: what they are, and how I found them</h3>
<p>Because this article involves both RDF and C++/PHP, you need to pay attention to class definitions. A <strong>class here is an RDF class, not an object-oriented one</strong>. <code>CModule</code> is not a class declared somewhere in the code, it is the <em>category</em> a node belongs to, and the triple <code>:BillingEngine a :CModule</code> says nothing more than "this node is a C module". There is no constructor and no method. RDFS does let one class be the subclass of another, and I used that, but a subclass here is not code reuse.</p>
<p>That distinction has a consequence people miss on the first read: the model never describes what an artifact <strong>does internally</strong>. There is no <code>save</code>, no <code>edit</code>, no <code>validate</code> anywhere in the ontology, and no relation says how a value is computed. I deliberately keep detailed behavior in the code, where it is already represented, rather than trying to reproduce it exhaustively in the ontology. What the graph carries is what each artifact <strong>is</strong> and what it <strong>touches</strong>: <code>calls</code>, <code>writesTable</code>, <code>describedBy</code>, <code>appliesToRelease</code>. That is a deliberate restriction, and it is the one that makes the model small, because the behavior of two million lines is unbounded while the ways those lines connect to each other are not. It also happens to be exactly what a path-shaped question needs: to follow a screen to a package to a table to a specification, I need the links, not the semantics of each function.</p>
<p>So the twelve classes are the vocabulary of a <strong>description of the system</strong>, and the nodes typed with them are generated from the code and the documents rather than written by hand.</p>
<p>That split decides what the repository actually contains, and it is worth stating plainly. Every name in this article that reads like a real thing (<code>:BillingEngine</code>, <code>:PKG_INVOICE</code>, <code>:T_INVOICE</code>, <code>:ProRataRule</code>) lives in no Turtle file of the repository. The files hold the <strong>language</strong>: twelve class names, ten relation names, the few axioms that say what a relation entails when it chains, and the SHACL shapes that say what a valid graph must look like.</p>
<p>The store holds the description of my system written in that language, and that description is where the meaning of two million lines actually sits. The repository is deliberately silent even about which kinds connect to which: <code>:calls</code> is declared with no domain and no range, because a call here crosses PHP, C and PL/SQL. The Java and PostgreSQL shop from earlier could take that repository and most of it would survive the trip. The store would be worth nothing to them, because it describes my system and only mine.</p>
<p>None of this is in tension with the repository being the source of truth, and a section further down returns to it: the facts in the store are derived, so the code is the source of the facts and the repository is the source of how to read them.</p>
<p>Below is an extract from the <code>ontology/</code> folder:</p>
<pre><code class="language-yaml">@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .
@prefix owl:  &lt;http://www.w3.org/2002/07/owl#&gt; .
@prefix :     &lt;https://example.com/legacy#&gt; .

&lt;https://example.com/legacy&gt; a owl:Ontology ;
    owl:versionInfo "1.4.0" .

:CModule        a owl:Class ; rdfs:label "C module" .
:PlsqlPackage   a owl:Class ; rdfs:label "PL/SQL package" .
:BusinessRule   a owl:Class ; rdfs:label "Business rule" .
:DbTable        a owl:Class ; rdfs:label "Database table" .

:calls          a owl:ObjectProperty .   # no range on purpose: a call crosses PHP, C and PL/SQL
:writesTable    a owl:ObjectProperty ; rdfs:range :DbTable .
:implementsRule a owl:ObjectProperty ; rdfs:range :BusinessRule .
</code></pre>
<p>That file names the terms and says what a relation points at, and every engine reads it the same way.</p>
<p>The axioms that depend on which engine reads them live apart, and the extract below comes from the <code>reasoning/rl/</code> folder:</p>
<pre><code class="language-yaml">@prefix owl:  &lt;http://www.w3.org/2002/07/owl#&gt; .
@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .
@prefix :     &lt;https://example.com/legacy#&gt; .

# a module that calls a package implementing a rule reaches that rule
:reachesRule    a owl:ObjectProperty ;
                owl:propertyChainAxiom ( :calls :implementsRule ) .
:implementsRule rdfs:subPropertyOf     :reachesRule .

# a specification that supersedes a superseded one supersedes it as well
:supersedes     a owl:ObjectProperty , owl:TransitiveProperty .
</code></pre>
<p>Finally, we can find a small extract from the graph itself, written entirely in those terms. Nobody typed those triples, and unlike the two snippets above they live in no folder of the repository: the repository holds the terms and the axioms, while the facts expressed in them are produced by the collectors and loaded into the graph at build time.</p>
<pre><code class="language-yaml">@prefix :    &lt;https://example.com/legacy#&gt; .
@prefix g:   &lt;https://example.com/legacy/graph/&gt; .
@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .

# structural facts, as collected from the sources of release 2022.2
g:R2022_2 {
    :BillingEngine a :CModule ;
        rdfs:label "Billing engine (C)" ;
        :calls :PKG_INVOICE ;
        :readsTable :T_CONTRACT .

    :PKG_INVOICE a :PlsqlPackage ;
        rdfs:label "PKG_INVOICE" ;
        :hasProcedure :CALC_PRORATA ;
        :writesTable :T_INVOICE ;
        :implementsRule :ProRataRule ;
        :describedBy :SPEC_INV_V3 .

    :CALC_PRORATA a :PlsqlProcedure ;
        rdfs:label "CALC_PRORATA" ;
        :implementsRule :ProRataRule .
}

# facts that span releases: documents, business rules, lifecycle
g:shared {
    :PKG_INVOICE
        :deprecatedInRelease :R2024_1 ;
        :replacedBy :PKG_INVOICE_V2 .

    :SPEC_INV_V3 a :SpecificationDocument ;
        :appliesToRelease :R2021_1, :R2022_2 ;
        :supersedes :SPEC_INV_V2 .

    :ProRataRule a :BusinessRule ;
        rdfs:label "Mid-month contract change is invoiced pro rata" .
}
</code></pre>
<p><code>:implementsRule</code> appears twice on purpose, once on the package and once on the procedure inside it. The <strong>package-level</strong> edge is the one a question about the system reaches first. The <strong>procedure-level</strong> edge is what lets an answer say <em>which</em> of forty procedures carries the rule.</p>
<p>This extract is in <em>TriG</em> and not in <em>Turtle</em>, because I need to show <strong>where</strong> the triples are stored. This is the mechanism behind the version handling I promised earlier.</p>
<p>A triple has no place for a release: <code>:BillingEngine :calls :PKG_INVOICE</code> is true in <code>2021.1</code> and maybe false in <code>2024.1</code>, and its three positions leave no room to say it. An RDF dataset adds a fourth one, the name of the graph a triple belongs to, and TriG is the syntax that writes it. So I opted for <strong>one named graph per release</strong> (<code>g:R2022_2</code>, <code>g:R2024_1</code>, etc.).</p>
<p>The collectors load the structural facts of a release into its graph, and a question runs against the graph of the release the user works on. What spans several releases goes into a shared graph: a specification covers several releases, so it carries <code>:appliesToRelease</code>; a business rule does not depend on a release; and <code>:deprecatedInRelease</code> or <code>:replacedBy</code> describe the life of a package across releases, not its state in one of them. RDF-star is the other option to attach a validity to a triple, but named graphs were enough for me.</p>
<p>So far the graph can answer things that no <strong>similarity search alone</strong> can answer reliably:</p>
<ul>
<li><p><em>Which specification applies to release</em> <code>2022.2</code><em>?</em></p>
</li>
<li><p><em>What depends on</em> <code>PKG_INVOICE</code><em>?</em></p>
</li>
<li><p><em>Which C modules implement the pro-rata rule, directly or indirectly?</em></p>
</li>
</ul>
<p>The first two are plain SPARQL over the facts above. The third one taught me something about the reasoner. The property chain gives <code>:BillingEngine :reachesRule :ProRataRule</code> for the modules that call the package directly. But a SPARQL 1.1 property path (<code>?m :calls+/:implementsRule ?rule</code>) answers the direct and the indirect case, at any depth, with no reasoner at all. So the chain is comfortable, not necessary. Where the reasoner really pays is on the facts that do not depend on a release. <code>:supersedes</code> lives in the shared graph, so declaring it transitive costs one closure, computed once and never leaking across releases, and every query that asks which specification is authoritative, and every shape that checks the version chain, reads plain edges instead of walking it by hand. And, where an explicit rule or query is defined, the deprecation of a package can be propagated to its procedures.</p>
<p>A reasoner does not know which graph a triple belongs to. If it is run over the entire store, it can combine facts from different releases and derive conclusions that were never true in any single release. For example, it might combine a <code>:calls</code> triple collected in <code>2022.2</code> with an <code>:implementsRule</code> triple collected in <code>2024.1</code> and derive a <code>:reachesRule</code> triple that belongs to neither release.</p>
<p>There is also a storage problem. A reasoner typically writes its inferred triples to the default graph. As a result, even valid inferences may not be visible to a query scoped to a particular release graph, such as <code>g:R2022_2</code>.</p>
<p>To avoid both problems, the build runs the reasoner separately for each release. For each run, it uses the release graph together with the shared graph, then loads the inferred triples back into that release graph. This prevents facts from different releases from being mixed and ensures that release-scoped queries can see the inferred triples.</p>
<p>The shared graph is reasoned over separately because its facts are independent of any release. For example, a transitive closure such as <code>:supersedes</code> can be computed once and reused across releases, making it much cheaper than repeating the same reasoning for every release.</p>
<p>The diagram below is a <em><strong>wider extract</strong></em>: it adds the screen and the PHP controller that lead into <code>BillingEngine</code>, and leaves the successor package out, because what matters here is the overall shape.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/c9b321a2-d8c2-4a71-9601-8be24d11d8bd.svg" alt="Graph extract around one PL/SQL package, in three zones. Code: contract_change.tpl calls ContractChangeCtrl.php, which calls the BillingEngine C module, which calls PKG_INVOICE. Knowledge: PKG_INVOICE implements the pro-rata rule, is described by SPEC_INV_V3 (superseding V2), is valid from 2021.1 until 2022.2 and deprecated in 2024.1. Database: BillingEngine reads T_CONTRACT, PKG_INVOICE writes T_INVOICE. Caption: the meaning is in the edges, each relation a fact, not a similarity score." style="display:block;margin:0 auto" />

<h3>What the repository builds</h3>
<p>Three pieces are built from the repository layout I showed earlier:</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/68d34313-0a36-4a23-8502-43eb1163765f.svg" alt="The legacy-ontology git repo and the three runtime artifacts built from it: ontology (RDFS and OWL classes), reasoning axioms, one folder per OWL 2 profile (rl for transitivity and chains, ql for what Ontop rewrites), vocab (SKOS), shapes (SHACL), mappings (R2RML) and queries (SPARQL). CI loads the triple store from rl; the mappings configure an Ontop endpoint over Oracle from ql; a context service assembles the context. Caption: the profile belongs to the engine, not the ontology." style="display:block;margin:0 auto" />

<p>A <strong>triple store</strong> is the database of the graph: where a relational database stores rows, it stores <strong>triples</strong>, subject then predicate then object (<code>:BillingEngine :calls :PKG_INVOICE</code>), and it answers SPARQL instead of SQL. CI fills it from the Turtle files plus everything the collectors extracted from the code and the documents, and it is the engine that loads <code>reasoning/rl/</code>.</p>
<p>Next to it, the <strong>Ontop endpoint</strong> serves the half of the graph that is never copied: <code>mappings/*.r2rml.ttl</code> says how Oracle tables become triples, <code>reasoning/ql/</code> is the only reasoning folder it loads on top of the declarations in <code>ontology/</code>, and SPARQL is translated into SQL against the live database, but the mappings and the ontology still need maintenance. That's why the mappings arrow in the diagram leaves the <code>mappings/</code> folder and not the repository as a whole. That half has a release too, and it gets it from the database itself: each Oracle schema is a release apart, so the mappings cover every release still maintained, one set per schema, and each set writes its triples into the named graph of its release (<code>rr:graph</code>), the same graph name the collected facts of that release carry in the triple store, so the context service merges the two halves by release without any bookkeeping of its own. A release that is no longer maintained has no schema left, so no virtual half, only its collected facts.</p>
<p>In front of both sits the <strong>context service</strong>, the only component the LLM ever talks to: it resolves the question to entities, runs the queries from <code>queries/</code> filtered by the release the user works on, and returns one small package instead of a dump. The same service exposes those queries as <strong>MCP</strong> tools.</p>
<p>The important mental switch: <strong>the triple store is a build artifact.</strong> The source systems remain authoritative for facts; the ontology repository is authoritative for their representation, validation and querying. If the store burns, you rebuild it from the repo and the <strong>fact store</strong>, the database where everything the collectors accepted accumulates, release after release.</p>
<p>That <strong>fact store</strong> is the one component a rebuild cannot regenerate. It contains all the decisions a domain expert made on a quarantine entry and all the facts from different sources. The facts could be collected again from the tagged sources. The decisions could not, and they are the reason it is the one thing to back up. The triple store is what comes out when the repository and the fact store are loaded together and the reasoner has run.</p>
<h3>How the graph gets initialized</h3>
<p>The repository layout says what the artifacts are, not where their content came from. That first load deserves a paragraph of its own, because readers may mistakenly think that someone would have to write Turtle for two million lines of code, entity by entity. Nobody can do that.</p>
<p>Only the top layer is designed rather than collected, and it is deliberately tiny. A few hundred lines of Turtle, and the only part of the repository where I read every line before it lands. Getting that first version right took me almost 4 days.</p>
<p>Everything else is generated by a <strong>first full collector run</strong>, and that run is <em><strong>deterministic</strong></em> from end to end. It walks the sources file by file: the call graph and the table accesses come out of static analysis of the C and C++, the PL/SQL half comes out of the Oracle data dictionary (<code>ALL_DEPENDENCIES</code> for the package-to-object dependencies, PL/Scope with <code>ALL_STATEMENTS</code> and <code>ALL_IDENTIFIERS</code> to know if it is a read or a write, because <code>ALL_DEPENDENCIES</code> only tells you that a package touches a table), the screen-to-controller chain out of PHP route analysis. Each collector emits Turtle expressed in the classes and relations <code>ontology/</code> already declares. <strong>No LLM produces a single fact in that baseline.</strong> A parser knows that <em>function A</em> calls <em>function B</em>, and asking an LLM to guess it would be slower, more expensive and less certain.</p>
<p>I should be precise about what <em><strong>deterministic</strong></em> means here, because I used the word for the method and not for the result. A parser gives the same output every time it reads the same file, and no model is involved. That does not make every fact certain: an <code>EXEC SQL</code> block tells me which table it touches, a statement built at runtime does not, and I never resolved calls made through function pointers. So the collectors attach a confidence to what they emit, and facts from ambiguous constructs are considered less reliable and remain marked as such.</p>
<p>What the collectors produce does not enter the graph on arrival. It lands in a staging area, the SHACL shapes run over it, and whatever violates a shape is quarantined with its violation report attached instead of being loaded. The gate itself is deterministic: a shape holds or it does not, and the report names the node, the shape and the constraint that failed.</p>
<p>The early runs generated a lot of quarantine entries, and that is the useful part, because every entry is one of three things and each one has a different fix:</p>
<ol>
<li><p>A fact that is real but mangled by the extraction is a <strong>collector bug</strong>.</p>
</li>
<li><p>A fact that is real and legitimate but rejected by a rule that was too strict is a <strong>correction to the shape or to the ontology</strong>, and since shapes live in the repository, that correction travels through exactly the review process described in the next section.</p>
</li>
<li><p>A fact that is simply not true in the sources <strong>stays out</strong> and requires human analysis.</p>
</li>
</ol>
<p>The loop did not succeed on the first attempt. It took ten passes. Collect, read the quarantine, fix the collector or the shape, collect again, ten times over before what came out was worth trusting, with the first three runs carrying most of the volume. This is also the one place where I used an LLM in the baseline, and only as a sorter: grouping the violations into families and suggesting which families looked like a rule to adjust rather than a collector to fix. It decided nothing. Every verdict was mine, and that loop took 20 to 25 days, collectors not counted: they were already written.</p>
<p>The documents are the exception, and the one place where an LLM proposes content instead of sorting reports: classifying a specification, detecting which releases it applies to, proposing that a section describes a given package. Those proposals do not enter the graph directly either, they go to a human review queue.</p>
<p>So the shape of the baseline is simple: the code side is parsed, the document side is proposed then reviewed, and both cross the same validation gate. Once the baseline is reproducible from an empty store, everything after it is a delta, as described in the next section.</p>
<h3>How the graph gets updated</h3>
<p>The delta goes through a governance loop that takes a change from proposal to deployed graph without breaking the consumers.</p>
<p>Updating follows the same logic as any code change:</p>
<ul>
<li><p><strong>Change proposal.</strong> A developer or a domain expert needs a new class, relation or rule (e.g. "we need to model batch jobs"). It becomes an issue, then a pull request on the Turtle files.</p>
</li>
<li><p><strong>Ontology validation.</strong> Automatically, on the pull request: SHACL validation on sample data, a reasoner consistency check (no logical contradictions), a profile check that <code>ontology/</code> together with <code>reasoning/ql/</code> is still valid OWL 2 QL (the check that catches a class declared with <code>rdfs:Class</code> where OWL 2 expects <code>owl:Class</code>), and SPARQL regression tests, which check that existing queries still return the expected results. A broken ontology never reaches the main branch.</p>
</li>
<li><p><strong>Human review.</strong> The domain person is not optional: the ontology is a contract about meaning, not just syntax.</p>
</li>
<li><p><strong>Merge and version.</strong> Tag the release and record the version in the ontology itself (<code>owl:versionInfo</code>, <code>owl:versionIRI</code>). One rule saves you from breaking every consumer: <strong>deprecate, never delete.</strong> Mark old terms with <code>owl:deprecated true</code>, just as you would deprecate an API.</p>
</li>
<li><p><strong>Deploy and repopulate.</strong> Re-run the collectors over what changed, merge the result into the fact store, then <strong>rebuild</strong> the store; if the mappings have changed, update the R2RML/OBDA mappings. The new graph is served. The same step also runs on its own at every release of the sources (a commit, a tag or the nightly run), with no proposal and no review, because the ontology already covers what changed.</p>
</li>
<li><p><strong>Feedback.</strong> When the LLM gives a wrong or incomplete answer, or a release brings an artifact the ontology does not describe yet, that becomes the next change proposal. The loop closes.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/304b3ae2-a844-4524-aaef-fc1b490c6c49.svg" alt="Governance loop for an ontology change. A proposal from a developer or domain expert becomes a pull request on the Turtle files. Ontology validation: SHACL, consistency check, OWL 2 profile check and SPARQL regression tests; a failure returns to the proposal. Review by a developer and a domain expert. Merge and version tag, deprecating not deleting. Deploy and repopulate, on the merge and at every release of the sources (commit, tag or nightly), then serve release-filtered context." style="display:block;margin:0 auto" />

<p>If this looks exactly like the lifecycle of a shared library (semantic versioning, CI, code review, deprecation policy), that is the point. Your team already knows how to do this. The only new skill is managing Turtle files.</p>
<h3>How the LLM uses it</h3>
<p>At question time, the pipeline became: <strong>entity linking → graph traversal → context assembly</strong>. The question is mapped to entities in the graph (using SKOS labels and synonyms), SPARQL queries collect the relevant subgraph <em>filtered by the release the user works on</em> (the named graph of that release, plus the shared graph, whose documents are filtered on <code>:appliesToRelease</code> while its rules and lifecycle facts come as they are), and only then are the connected facts, plus the exact document sections they point to, given to the LLM as context. Vector search did not disappear: it still finds the right paragraphs <em>inside</em> a document. But the <strong>graph decides which documents and which code artifacts are on the table</strong>, and the versions no longer get mixed.</p>
<p>The difference was not subtle. Here is the kind of question that changed: which specification governs the pro-rata computation for a client on release <code>2022.2</code>. The vector setup returned passages from <code>SPEC_INV_V2</code> and <code>SPEC_INV_V3</code> side by side, without any indication of which one was valid, and the model picked one. The graph selects <code>SPEC_INV_V3</code>, because it applies to <code>2022.2</code> and supersedes v2 under the project’s policy for choosing the latest applicable specification, and it names <code>PKG_INVOICE</code> as the package implementing the rule. And, very important for adoption, every answer came with a <strong>traceable path</strong>: <em>this module → this package → this table → this document, this release</em>.</p>
<blockquote>
<p>Developers can verify the path but not a pile of similar chunks!</p>
</blockquote>
<h3>The full pipeline, step by step</h3>
<p>Let me put the complete flow in one place, as an overview:</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/dca8e94b-3946-480e-a4b3-84370d4051e5.svg" alt="The six-stage pipeline as a loop, with the ontology, SKOS vocabulary and SHACL shapes as the contract every stage reads. Four build the graph: Analyzing picks a standard per artifact family, Collecting runs one collector per source family, Transforming merges with SKOS and puts LLM proposals behind a SHACL gate, Versioning appends a delta per release. Two use it: Retrieving does entity linking then release-filtered SPARQL, Serving returns context or MCP tools with the answer and its path." style="display:block;margin:0 auto" />

<ul>
<li><p><strong>Analyzing.</strong> Before writing a single collector, walk through your artifact families and decide which standard represents each one: RDF triples for the structural facts in the code, R2RML/OBDA for relational data that stays in Oracle, SKOS for the bilingual vocabulary, SHACL for the quality rules. The output is a small core ontology plus a decision table that becomes the contract for every collector you write next.</p>
</li>
<li><p><strong>Collecting.</strong> Scan all the sources: static analysis of the C/C++ (call graphs, table access), the Oracle data dictionary (<code>ALL_DEPENDENCIES</code> and PL/Scope) for PL/SQL, PHP routing, and every document repository. Each fact is collected with its origin, its date and, when detectable, its release.</p>
</li>
<li><p><strong>Transforming.</strong> Map the raw facts to the ontology terms, merge duplicated entities (legacy systems always have three names for the same concept, using SKOS for synonyms and labels), and let the LLM propose classifications and links that a human validates. Then, SHACL shapes act as a quality gate: any fact that fails the defined constraints is quarantined instead of entering the graph. What passes is loaded into the triple store, or, when the truth already lives in the relational database, exposed virtually through an OBDA/VKG layer.</p>
</li>
<li><p><strong>Versioning.</strong> The collectors run again at every release. New facts land in the named graph of that release, and the facts that disappeared are not deleted: they stay in the named graphs of the releases where they were true, and the fact store records the release in which each one was last seen (<code>validUntil</code>). <code>:deprecatedInRelease</code> is a special case: it comes either from a release note or from the comparison of two collector runs, and the fact store keeps track of which one. A package that disappears from the code is not always deprecated, sometimes it was just renamed.</p>
</li>
<li><p><strong>Retrieving.</strong> At question time: entity linking maps the question to graph nodes, SPARQL queries the relevant subgraph <em>filtered by the user's release</em> (its named graph, plus the shared one), and the connected facts plus the exact document sections are assembled into the context.</p>
</li>
<li><p><strong>Serving.</strong> The assembled context goes to the LLM, which writes the answer with its traceable path attached. The same graph is also exposed as tools an agent can call, and this is where it becomes really interesting: before proposing a fix, the assistant asks the graph for the impact (<em>who calls this procedure? which business rules does it implement? which screens touch this table?</em>), so the generated change respects what the graph knows. Once that change is merged, the cycle restarts at analyzing: most of the time the contract already covers what changed and that pass costs nothing, but when the change brings in an artifact family or a concept the ontology does not describe yet, this is where it gets added, and the collectors run again.</p>
</li>
</ul>
<p>Notice that the list splits in two. Stages 1 to 4 build and maintain the graph, which is classic data engineering: stage 1 is a decision, <strong>stages 2 to 4 are the CI job that reruns at every release</strong>. Stages 5 and 6 use it at question time, which is the context-engineering part. The ontology is the contract between them.</p>
<h3>What it cost me</h3>
<ul>
<li><p>The upfront modeling took real time, but far less than the accumulated time I lost tuning RAG pipelines that could not work.</p>
</li>
<li><p>The value is in the <strong>pipelines that keep the graph up to date</strong>, not in the ontology file. An ontology that is not maintained and a graph that is not updated with each release are just more outdated documentation.</p>
</li>
<li><p>Start small. My first working ontology covered only one subsystem. It proved the value in weeks, and it can grow from there.</p>
</li>
</ul>
<h2>6. Conclusion</h2>
<ul>
<li><p><strong>RAG is not dead.</strong> It is simply not sufficient when the meaning of your system is split across code, database, documents and releases.</p>
</li>
<li><p><strong>Ontologies are not academic.</strong> RDF + RDFS + SKOS + SHACL is a pragmatic and effective stack. Keep OWL for the places where inference pays.</p>
</li>
<li><p><strong>The graph is the semantic layer for context engineering.</strong> The LLM stays the language expert; the ontology decides what the LLM is allowed to see, for which release, with a traceable path.</p>
</li>
<li><p><strong>On a 2M-line legacy system, this was the first approach that fit the constraints.</strong></p>
</li>
</ul>
<p>This article stops at the map. The territory—how to extract a reliable graph from C/C++, PL/SQL and twenty years of documents, and how to serve it to the model without losing your sanity—is where most of the real work sits. I cover that in the next article: <a href="https://elie29.hashnode.dev/from-legacy-artifacts-to-served-context-my-six-stage-method">From Legacy Artifacts to Served Context: My Six-Stage Method</a>.</p>
<hr />
<h2>Let's keep in touch</h2>
<p>Before I wrap up, I’d love to hear from you.</p>
<p>Have you tried RAG on a large legacy system? Did you run into the same challenges with scattered meaning and mixed versions? Are you using ontologies, property graphs, or something else?</p>
<p>Share your experience in the comments. I read and respond to every one.</p>
<p>If you enjoyed this article, follow me on <a href="https://x.com/elie_nehme">X</a> and connect with me on <a href="https://www.linkedin.com/in/elie-nehme/">LinkedIn</a>. Your feedback also helps me choose what to explore next.</p>
]]></content:encoded></item><item><title><![CDATA[I Tried BMAD on a Real Feature]]></title><description><![CDATA[What a formal method adds to a living specification, and where the two collide]]></description><link>https://elie29.hashnode.dev/i-tried-bmad-on-a-real-feature</link><guid isPermaLink="true">https://elie29.hashnode.dev/i-tried-bmad-on-a-real-feature</guid><category><![CDATA[AI]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[software development]]></category><category><![CDATA[claude-code]]></category><category><![CDATA[BMAD]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Mon, 24 Aug 2026 11:02:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/e43a5f95-a933-4d9d-b25a-5b22c443e314.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Note: Originally published on <a href="https://elie29.medium.com/i-tried-bmad-on-a-real-feature-69afd0ba53b3">Medium</a></p>
</blockquote>
<p>At the end of <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">The Living Specification</a>, I wrote that structured methods for AI-driven development deserved their own article, and that BMAD was one of the notable approaches I had come across.</p>
<p>This is that article.</p>
<p>And before diving into the topic, the question we should ask is not "Is BMAD good?" It is simpler than that: "What does BMAD add when you already have a specification that is the source of truth?"</p>
<p>I ran BMAD with the Superpowers plugin for <em>Claude Code</em> on a real feature, across two repositories: a Java backend and an Angular frontend. What follows is what I learned, including where I got wrong. The purpose of this article is to share my reasoning about where it is useful to use BMAD and where we should absolutely avoid it.</p>
<p>Over two months of AI-assisted work, the single most expensive habit I had to break was letting the specification live in several places at once: a bit in the ticket, a bit in the architecture document, a bit in a chat I could no longer find, and a bit in the code itself. A human team survives that, people ask each other. An AI does not ask. It reads whatever you point it at, treats it as the truth, and writes hundreds of consistent lines on top of a fragment.</p>
<blockquote>
<p>A specification scattered across five places is not a specification. It is five opinions, and the AI will pick one: not necessarily the right one, just the one it happened to read.</p>
</blockquote>
<p>So the rule that runs through this entire article is the same: <strong>one shared place holds the intent; everything else refers to it</strong>. That sounds obvious until you add a formal method on top of an existing one, because a method arrives with its own artifacts, and every one of them wants to be the source of truth too.</p>
<hr />
<blockquote>
<p><strong>If you have not read the series</strong></p>
<p>The method I am comparing against is simple to state: the specification is the source of truth, the invariants are the contract, and the code is an implementation of that contract. Work state lives in plan files, not in conversations. "Done" means a verification command and its real output, not "it should work". The human owns the commit.</p>
<p>The story behind it is in <a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now">Part 1</a>, and the method itself in <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>.</p>
</blockquote>
<hr />
<h2>What BMAD actually is</h2>
<p>BMAD is, simply, files. It is a collection of agent personas and workflows written in Markdown, plus a CLI installer that drops them into your AI coding tool. It is not a product, an IDE, or a service you log into.</p>
<p>That matters more than it sounds. Because BMAD lives as text in your repository, it is portable across <em>Claude Code</em>, <em>Cursor</em>, <em>Kiro</em>, or others.</p>
<p>The <a href="https://docs.bmad-method.org/reference/workflow-map/">BMad Method module</a> organises work into four phases: <em>Analysis</em> (optional), <em>Planning</em>, <em>Solutioning</em>, and <em>Implementation</em>. Each phase produces documents that become the context for the next one. The official framing is explicit about the reason for this: without that structure, agents make inconsistent decisions.</p>
<p>Each phase offers several workflows rather than a single mandatory path. Planning has <code>bmad-prd</code> and <code>bmad-spec</code>. Solutioning has <code>bmad-architecture</code>, <code>bmad-create-epics-and-stories</code> and <code>bmad-sprint-planning</code>. Implementation converges on <code>bmad-build</code>, with <code>bmad-code-review</code>, <code>bmad-correct-course</code> and <code>bmad-retrospective</code> around it.</p>
<p><strong>Do not memorise those names.</strong> BMAD moves quickly so take the list as an illustration of the shape.</p>
<p>Whatever the names are in your version, you are meant to choose among them rather than run them all. That is the part most people miss, and it is the reason BMAD gets a reputation for heaviness that it doesn't always deserve.</p>
<h3>So why BMAD, and not a template of my own?</h3>
<p>If BMAD is just files, why I did not write my own? I already had rules, skills, and reusable prompts. So, just adding an epic template and an architecture template would have taken an afternoon.</p>
<p>The first answer is that a template and a method are not the same thing. A template gives you a shape to fill in. BMAD gives you a process that questions you while you fill it in: guided discovery instead of an empty heading. My own templates ask the questions I already know to ask. They do not challenge the blind spots I don't know I have. It is the same reason the adversarial review in <a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now">Part 1</a> beat my own review: not more knowledge, but a different angle of attack.</p>
<p>The second part is the ordering and the handoffs: which artifact must exist before which one, and what each step is allowed to assume. That is the part I would have got wrong alone, and the part that took the longest to learn.</p>
<p>And the third part is the one I didn't expect to matter so much. I adopted BMAD, I did not copy it into my project. It stays what it is, upstream, and it improves without me. If I had written my own version, every improvement would have been mine to invent and mine to maintain.</p>
<p>Adopting it costs less than people assume because BMAD does not ask you to change tools. That is what makes it feel more like an <strong>engine</strong> you can share than a framework you install: the method is common, the tooling stays yours. That argument has a longer version, and I come back to it at the end of this article.</p>
<h2>How I used it</h2>
<p>This came after two months of delivering features for the same product. I was then asked to build a few dashboards. However, this article focuses on the first one, because it took most of the time.</p>
<p>The feature was an income &amp; expenses dashboard, with trends, period comparisons, and other details that aren’t relevant here. As I analysed it, I found myself duplicating invariants and rules across both repositories again, not for the first time in this project, and not without knowing better. But this feature was large enough that the duplication would not stay small. I needed a method that would stop it at the source.</p>
<p>And as I was using the <em>Superpowers plugin</em> and didn't want to lose it, I created a whole loop combining it with BMAD to benefit from both.</p>
<p>My loop, shown in the figure below, has three stages. Only the first and last are BMAD, and they sit a layer above its four phases rather than renaming them: Stage 1 alone runs through more than one.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/22753985-f92e-4afc-acb4-f9740b12c3fc.svg" alt="Diagram of the three-stage loop. Stage 1, BMAD: product brief and PRD, then architecture, which freezes the API contract; from it, two parallel tracks, a Java backend story and an Angular frontend story, written on disk. Then a session boundary: new session, the story is the input, the plan is the state. Stage 2, Superpowers: write-plan, a TDD loop in a worktree per track, code review, merge. Stage 3, BMAD: a conformance audit; a mismatch goes back to the contract or the story, not to the code." style="display:block;margin:0 auto" />

<p><strong>Stage 1 — BMAD scopes the product and the architecture.</strong> A light PRD, then the architecture workflow. It ends when the stories exist on disk, one set per repository.</p>
<p><strong>Stage 2 — Superpowers implements.</strong> The stories are read from disk. <code>write-plan</code>, then <code>execute-plan</code> inside a git worktree, TDD, then automated code review and the branch is finished.</p>
<p><strong>Stage 3 — BMAD audits conformance.</strong> Does the merged code still match the contract and the architecture that Stage 1 froze?</p>
<p>On this feature the whole thing took three working weeks, and I was not alone: a BA and a PO worked with me. It splits into roughly four days for Stage 1, nine for Stage 2, and two for Stage 3.</p>
<h3>The box that makes the rest legal</h3>
<p>The most important part of that diagram is not a stage, it is the <strong>API contract</strong>. What matters is not that it never changes, but that it can only change on purpose, through an explicit, visible act.</p>
<p>"Frozen" is the shorthand I use, and it is a slightly dangerous word. It does not mean the contract is correct, and it does not mean it is permanent. It means no story gets to quietly reinterpret it. Changing it is allowed, but loudly, in one place, with both tracks notified.</p>
<p>Once the architecture workflow has frozen the contract, the backend track exposes it and the frontend track mocks it. Neither waits for the other. The two coloured columns are not a drawing convenience: they are two parallel work streams that are only safe because a contract sits above both of them.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/15732dea-ca9c-4dc1-81ff-19efd1a4d8ea.svg" alt="Diagram of the frozen contract above two parallel tracks. A purple band at the top, the API contract, states it changes on purpose, in one place, and both tracks are notified. Two arrows drop to a blue Java backend track and an orange Angular frontend track, each mocking or exposing the contract and running plan, TDD and review, neither waiting for the other. Both feed a dashed conformance audit: a divergence is a matter of contract, not of code. A red loop runs back up to the contract." style="display:block;margin:0 auto" />

<p>This is the same argument I made in <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> about OpenAPI as the source of truth for the API. Here, it does structural work: it is what allows two agents in two repositories to move at the same time without integrating on trust. Freeze the contract and parallelism becomes possible. Leave it soft and every story becomes a negotiation.</p>
<p>And now the honest part, because this is the claim in the article most likely to be wrong in your project. A contract frozen before implementation can be frozen in the wrong shape, and a wrong contract held firmly is worse than no contract at all: both tracks implement faithfully against it, both suites go green, and you get two well-tested halves of a mistake. Green tests on both sides is exactly what a mismatch looks like when the mismatch is upstream of the tests.</p>
<p>That is why the correction loop later in this article is not an optional refinement: it is what makes freezing the contract early survivable.</p>
<h3>Epic, story, plan — three different objects</h3>
<p>Below the contract sits the work itself, divided into three objects that are easy to confuse. A shorthand I hear often is that epics are the features and stories are the design. That is half right, and the wrong half causes trouble.</p>
<p><strong>The epic is the feature.</strong> A coherent slice of product value, with acceptance criteria that outlive any single commit.</p>
<p><strong>The story is a unit of implementable work</strong>, not the design. The design lives in the architecture. What a BMAD story carries is enough context to implement it <em>without</em> re-reading the architecture: the constraints that apply here, the patterns to follow, and the part of the contract it touches. That is why a good story reads like a design document, but it is not one: it is a projection of the design onto one unit of work.</p>
<p><strong>The plan is the state of execution.</strong> Status, current task, decisions, blockers, verification commands, expected build state — all kept aligned with the code.</p>
<p>In my example, the feature was one epic and three stories: one for the backend, two for the frontend.</p>
<p>And that is where an agile reader should raise an eyebrow, because splitting a feature into a backend story and a frontend story is normally an anti-pattern. It is horizontal slicing: neither story delivers value on its own, and the integration risk is deferred to the merge.</p>
<p>The frozen contract is what makes it legitimate here. The integration decision has already been made and written down before either story starts. The stories are not postponing a negotiation, they are consuming an agreement.</p>
<p>Split by layer without a contract and you get two components that meet for the first time in a merge request. Most of the time, problems emerge during integration, and the production delivery gets postponed with no clear date.</p>
<p>Three objects, three lifetimes: the epic outlives the sprint, the story is consumed once, the plan changes at every task. The epic becomes historical too, but later than the others and under a condition: when the feature is delivered <em>and</em> its invariants have been migrated into the durable specification.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/c82508b7-0815-413f-ae82-3eb45aa4b8b0.svg" alt="Timeline of three objects across Stage 1, the session boundary and delivery. The epic, the feature, carries acceptance criteria and invariants and outlives the sprint. The story, one unit of work, is written in Stage 1 and read once at the start of Stage 2, then never edited and never consulted for the state. The plan, the state, does not exist yet in Stage 1, changes at every task with status, decisions, blockers and evidence, and is done with the branch." style="display:block;margin:0 auto" />

<h3>Where does the epic live?</h3>
<p>This is a legitimate question anyone asks when the feature crosses more than one repository, and it has a clean answer.</p>
<p><strong>The epic belongs to the feature. The stories belong to the repositories.</strong></p>
<p>An epic is not backend work or frontend work, it is the feature, and the feature is what the business asked for. So it cannot live inside either repository without one of them silently becoming the owner of product intent. The same is true of the PRD, the architecture, and the contract.</p>
<p>That gives a shared planning space: a small repository of its own, or a folder inside one repository. Either works. What doesn't work is copying the same content in many places.</p>
<p><strong>One epic produces one or many stories per repository</strong>, split by what is implementable in one go, not by a wish for symmetry between the two sides.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/d606b406-a9b0-4d27-b493-daec05ce4731.svg" alt="File tree of the layout. A shared planning space owned by the feature, platform-docs/, holds the product brief, the PRD, ARCHITECTURE.md, openapi.yaml (the frozen contract) and the epic. From that epic, one story goes to the Java backend repository and two to the Angular frontend one. Each repository has .claude/ with its rules, docs/ with its stories and plans (the state), src/ generated from the contract, and tests/." style="display:block;margin:0 auto" />

<p>The stories are different. A story is implementable work, and implementable work happens in exactly one repository, next to the rules and the code it touches. That is where the Superpowers session will run, and it needs the story on disk locally.</p>
<h3>But my epics live in Jira</h3>
<p>They probably do, and that is not a conflict, because "epic" names two different objects.</p>
<p><strong>The epic as a work item</strong> lives in the tracker. Status, assignee, dates, dependencies, reporting. It exists so people can run the project. A large feature can hold several of them, and the hierarchy above it depends on your framework rather than on any method.</p>
<p><strong>The epic as a context artifact</strong> lives in the repository. It exists so an agent can implement correctly without asking. It is not a status object at all.</p>
<p>They share a name and almost nothing else.</p>
<p>This distinction determines who maintains each artifact, what they put in it, and whether it belongs in the tracker or the repository. The Product Owner or the BA details the epic <strong>in the repository artifact</strong> (scope, acceptance criteria, constraints, vocabulary, the edge cases someone argued about in a meeting) and leaves the tracker item with what a tracker is for: key, title, status, links, dates.</p>
<p>The tracker holds the status, the repository holds the context, and they are linked by a key, never by a copy. If you paste the epic description into both, you have rebuilt the two-realities problem at the organisational level. So <code>epics/</code> holds one file per epic, named for its tracker key, and Jira keeps doing what Jira is good at.</p>
<p>The repository file is versioned alongside the code it governs, reviewed in the same pull request, and easy to find when the scope changes; a ticket description is mutable and not tied to any particular code state.</p>
<h3>The rule at the session boundary</h3>
<p>Between Stage 1 and Stage 2 there is a session change, and that is where I had to make a decision.</p>
<p>At that moment, I had two files claiming to be the state of the work: BMAD's story, and the plan. The Superpowers plan and my plan file from the living-spec method are not two candidates, they are the same file. Superpowers writes the plan; the living-spec method decides what goes in it, which is the state of the current work instead of leaving it in the chat.</p>
<p>I resolved it with one rule:</p>
<blockquote>
<p><strong>The story is input. The plan is the state.</strong></p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/d5bd93a4-77a6-4185-9bbb-7f4ba3b5d92a.svg" alt="Diagram of the session boundary. At the end of Stage 1 the stories are on disk, next to the code they touch. A new session starts with an empty context, where two files claim the state. The BMAD story is the input: what to build and why, read once, then never edited and never consulted for the state. The plan file is the state: one file, changing at every task with status, current task, decisions, blockers and verification commands." style="display:block;margin:0 auto" />

<p>The BMAD story describes what to build and why, similar to what Superpowers proposes with its specs/design files. It is read once, at the start of Stage 2, and then it becomes a historical document. From that point, the plan file carries the current task, decisions, blockers, and verification commands, exactly as in the living-spec method. Superpowers itself makes the same distinction: the <code>specs</code> folder holds the design, while the <code>plans</code> folder holds the execution plans. So in my loop, the BMAD story plays the role of the design input, while the plan remains the living state of execution.</p>
<p>This is not a detail. Only one file can hold the state. Let two of them claim it and they do not average into one truth: they drift apart quietly, and the agent believes whichever one it opened last.</p>
<p>I did not have to test this on purpose, it happened by itself. The plan was written one day and the execution started the day after, or later. More than once I stopped in the middle, at task 3 or task 4, and came back the next day, in a new session, to continue at the same task. Nothing was lost, because the plan file said where I was.</p>
<h2>Who holds which role</h2>
<p>While building the loop, I also wanted to make one thing explicit: who actually owns each decision.</p>
<p>The artifacts are settled, and so is the boundary between them. What is not settled is the sign-off. <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> walked through ten roles across the SDLC.</p>
<p>What follows is not that, but an overview of the few roles that own a step in this particular loop: Product Owner, Architect, Tech Lead, and Developer. The others do not disappear.</p>
<p>UX/UI, QA, Security, Data, Platform, and SRE simply have no tile of their own here, and two of them are worth naming. QA moved inside the TDD cycle and the conformance audit rather than into a step of its own, and the question from <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>, do these tests prove the right thing, is now part of what the Developer approves in the plan.</p>
<p>The UX/UI Designer works one level below this diagram: the design rules live in the frontend rule files, and the running Angular application is still the maquette.</p>
<p>For the roles that are shown, the claim from <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> holds and becomes concrete: the value of each one moves from producing an artifact to judging whether it should exist, whether it expresses the intended solution, and whether there is enough evidence to trust it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/be0ab05b-92e2-4cf0-805b-8915b27bec02.svg" alt="Diagram of the three stages, each tile split between the AI and the human who decides. Stage 1: the AI drafts the PRD, the Product Owner decides the scope; the AI proposes options, the Architect freezes the contract; the AI writes the stories, the Tech Lead accepts the split. Stage 2: the AI plans, the Developer approves; the AI writes the test then the code, the Developer reads the real output; the Developer owns the commit. Stage 3: the AI audits, the Tech Lead accepts or sends it back." style="display:block;margin:0 auto" />

<p>Read the diagram against the role descriptions in <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>, and the mapping is direct. The Product Owner no longer writes requirements; they decide the scope and make the ambiguity explicit before it becomes code. The Architect no longer draws the architecture; they compare the proposed options and freeze the contract. The Developer no longer types the implementation; they approve the plan and read the real output. The Tech Lead is left with the part that is never automated: <strong>judgment</strong>.</p>
<p>One mapping is not a straight copy. In <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> the Architect verifies conformance continuously, and here the Stage 3 audit is accepted by the Tech Lead. The audit runs across two repositories, so the question is not only whether one service respects the contract, but whether the two generated solutions still fit together. That is the Tech Lead question from <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>, and it is the same one behind accepting the story split.</p>
<p>A note on the labels: BMAD ships named agent personas, and that line-up moves between versions: v6 folded the separate Scrum Master and QA agents into the Developer agent. So my diagram names <strong>roles rather than personas</strong>. A role survives an upgrade; a persona name does not, and an article built on persona names would be wrong by the next release.</p>
<p>The AI can hold every role in that diagram. That is the part people find unsettling, and it is not the interesting part.</p>
<p>The interesting part is that every step ends with a human decision, and this is not an option at all.</p>
<p><a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> argued that AI made quality cheaper because the mechanical cost of doing the right thing collapsed. If I now demand an approval at seven steps per story, I have simply moved the bottleneck from typing to attention, and attention is a scarce resource. A method that needs a thoughtful human at every step will get a distracted one instead, which is worse than not asking.</p>
<p>So the decisions are not equal, and pretending otherwise is how approval becomes a rubber stamp. The distinction I actually used is reversibility. Approving a plan is cheap to undo: a bad plan costs one rewrite. <strong>Freezing the contract, owning the commit, and accepting the conformance verdict are different: they are the points where a mistake propagates into other people's work, and none of the three is delegable</strong>, not because the AI would do them badly, but because they are where somebody takes responsibility. An agent can produce the architecture; it cannot be accountable for having chosen it.</p>
<p>Note how consistent that is across my loop: decide the scope, accept the split, approve the plan, read the real output. Not one of those is typing.</p>
<h2>Why three stages, and not one</h2>
<p>Superpowers alone is already a serious workflow: brainstorming before code, plan writing, red-green-refactor where the test must fail first, systematic debugging, review by a separate agent. If it is that good, why wrap it in BMAD at all?</p>
<p>Because of scope.</p>
<p><strong>Planning scope is not execution scope.</strong> Superpowers reasons brilliantly about the task in front of it. It cannot tell you that story 7 will quietly break an authorization rule established in story 2, because story 2 is not in the room. Stage 1 exists to hold the level above the story: the contract, the architecture, the order of the work, the parts of the system a single story cannot see.</p>
<p><strong>A gate is not a persona.</strong> BMAD's implementation workflow is a role with instructions. Superpowers' TDD is a gate: the test must fail before the code is written. A persona can be talked out of its discipline by an eager model; a red-green cycle cannot. Stage 2 exists because that is where I want mechanical enforcement rather than good intentions.</p>
<p>In <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>, one of the rules that survived the whole project was to separate audit from fix. Stage 3 is that rule in tool form. The agent that just wrote the code is not a reviewer of the code.</p>
<p>Those three reasons are also the answer to the question I opened with. What BMAD adds to a living specification is not more specification, but the level above the story: the contract, the order of the work, and a reader of the result who did not write it.</p>
<p>And there is a fourth element, one that never appears on the diagram: <strong>the seam between the stages</strong>. I gave it a rule earlier (the story is input, the plan is the state) but that rule only settles who holds the state across the seam, not why the seam is worth having.</p>
<p>Planning artifacts are expensive to carry. Dropping them at the handoff is a feature, not a compromise, provided the stories on disk are complete enough to survive the drop. That is what <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> demanded of a session, applied to a tool chain: kill the session, clear the context, and see whether a fresh agent can continue from artifacts alone. I never ran that as an experiment. My own working days ran it for me, and the plan file is what made it pass.</p>
<h2>Where the two methods collided</h2>
<p>The two methods never contradicted each other on paper. They collided in the middle of a session, and the collision looked exactly like good practice.</p>
<p>Stage 2 opened on the backend story. Superpowers did what it is supposed to do: brainstorm before writing anything. And it asked a good question:</p>
<ul>
<li>should the server compute the period comparison and return one payload, or return two series and let the client compare them?</li>
</ul>
<blockquote>
<p>That's a fair question, well posed, the kind you want an engineer to ask.</p>
</blockquote>
<p>It is also a question Stage 1 had already answered and written into the contract.</p>
<p>Nothing failed. No tool complained. The agent weighed both options, chose the one it judged better, and wrote a coherent plan against it, ready to start with a failing test. Every Superpowers gate was respected. Meanwhile, in the other repository, the frontend track was mocking the parameter that plan had just decided to drop.</p>
<p>Two methods, both behaving correctly, pointing in opposite directions:</p>
<ul>
<li><p>Superpowers says <em>explore the design before you build</em>.</p>
</li>
<li><p>BMAD says <em>the contract is frozen — you are consuming an agreement, not negotiating one</em>.</p>
</li>
</ul>
<p>The dangerous part is that you don't notice at plan time. The plan reads well. If I had let it run, both suites would have gone green: two well-tested halves of a mistake I described earlier. I caught it while reading the plan, and only because the contract was a document I could compare against and not an assumption in my head.</p>
<p>So the contract did not stop the drift, it only made the drift visible. That is a smaller promise than it sounds, and it is the one I can defend: freezing the contract does not remove the need to read what the agent decided, it gives you something to compare it against. Both cases in this article were caught that way, by reading. The two tracks are safe because of the contract and the reading together.</p>
<p>So the collision is not tool against tool, it is a scope mismatch. Superpowers reasons about the story in front of it, and it is right to; it simply cannot know that the design question it just raised was decided one level up, in a room it was never in.</p>
<p>The rule that came out of it sits at the same seam as the previous one:</p>
<blockquote>
<p>In Stage 2, the agent may brainstorm about <strong>how</strong>, never about <strong>what the contract says</strong>. A good idea that contradicts the contract is not an implementation decision, it is a change request.</p>
</blockquote>
<p>And it stayed a good idea. It was not discarded: it went back up to Stage 1 through <code>bmad-correct-course</code>, the contract changed on purpose and in one place, and both tracks were told.</p>
<h3>Two specifications</h3>
<p>BMAD produces a PRD, an architecture document, and stories. My method already has a specification and invariants. Nothing in either tool tells you which one wins. That is the scattered-specification problem from the opening, arriving this time through the front door, wearing the uniform of a respected method.</p>
<p>Both tools offer a design artifact: Superpowers has its <code>specs</code> folder, BMAD has its stories. They describe the same thing, so only one was allowed to exist, and I kept the story. What I dropped is <code>specs/</code> alone: <code>plans/</code> stays exactly where it was, and it is still the state of execution. The content of the specification did not disappear; it moved. The invariants and acceptance criteria are stated in the epic, and the invariants are then projected into the stories that touch them.</p>
<p>The reason for keeping the story is where the context already sits: at the end of Stage 1, BMAD is holding the PRD, the architecture, and the epic in one session, so the story is simply recording what was decided minutes earlier. Producing the same document again in Stage 2 would mean rebuilding that context in a fresh session and paying for it with another round of tokens, only to end up with the artifact I already had.</p>
<p>My conclusion: BMAD's artifacts are <strong>derived working artifacts</strong>; the living specification is <strong>durable</strong>.</p>
<p>That does not mean the working artifacts are disposable in the careless sense. The valuable decisions in them still have to survive the workflow. The most valuable content in a PRD is not the requirement, it is the alternatives that were rejected and the reason they lost. <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a> says a decision that lives outside the plan did not happen; the same applies here. If you discard the PRD without preserving the reasoning behind the decision, you keep the conclusion but lose the rationale, and the team will debate the same choice again six months later.</p>
<p>So the rule is: <strong>the PRD is no longer authoritative once its decisions have been migrated</strong>, and the migration is a step somebody performs, not an intention somebody has.</p>
<h3>Acceptance criteria are not invariants</h3>
<p>This is the sharpest difference, and it is not a criticism of BMAD, it is a difference of object.</p>
<p>An acceptance criterion says: <em>this feature must do X</em>. It is scoped to the work it describes and expires when that work is delivered.</p>
<p>An invariant says: <em>this must never stop being true, in any story, forever</em>. Every API entry point uses the same authorization rule. An asset belongs to the correct organisational scope. A migration preserves the required relationships.</p>
<p>So the two objects went to two different places, and they follow the same route as the design. Both are stated in the epic, because the epic is the feature. From there the acceptance criteria stay at feature level, while the invariants are projected into the stories that touch them: a story carries the invariants that apply to its own unit of work, exactly as it carries the part of the contract it touches.</p>
<p>That solves the short term, not the long one. An epic outlives a sprint; an invariant outlives the epic. <em>Every API entry point uses the same authorization rule</em> is not a statement about this feature, and the next epic must not have to rediscover it. So an invariant ends where the PRD's rejected alternatives end: migrated into the durable specification, by somebody, as a step. A story-shaped method can carry an invariant down to the code. It cannot be the place the invariant lives.</p>
<blockquote>
<p>Acceptance criteria are checked once, invariants are checked forever.</p>
</blockquote>
<p>The same gap shows up a second time, at the end of the work rather than the start. BMAD's <code>bmad-retrospective</code> reviews a completed epic against its acceptance criteria and produces a verdict. Superpowers finishes a branch once the review agent is satisfied. My method says: show me the verification command and its real output, plus the expected result, written before the command was run. Three declarations of done, and only the third one is evidence. The other two are opinions about evidence. Writing the expectation first is what makes it evidence: a result read afterwards can always be made to look like a success.</p>
<h2>The correction loop</h2>
<p>Stage 3 asks whether the code still matches the contract and the architecture. The interesting question is what happens when the answer is <strong>no</strong>.</p>
<p>Most BMAD diagrams, including the ones in tutorials, draw the flow going one way. But the method itself ships <code>bmad-correct-course</code> for significant mid-sprint changes, and <code>bmad-retrospective</code> for evidence-based review against acceptance criteria.</p>
<p>The return path exists. It is simply the part everyone skips, because a linear diagram makes the pipeline look finished at the last box.</p>
<p>I draw it explicitly, with a direction. A mismatch is first a question about the specification (the story, architecture, or contract) before it is a question about the code.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/e7490286-d92b-43d6-8799-e3562ce7c4bb.svg" alt="Diagram of the correction loop. The Stage 3 conformance audit asks whether the code still matches the contract. When the answer is no, the question becomes which artifact was wrong: the story, back at the PRD, or the contract, back at the architecture. The contract is changed on purpose, in one place, and both tracks are told before either one resumes Stage 2, where a new session runs plan, TDD and review. The code is never fixed first." style="display:block;margin:0 auto" />

<p>If Stage 3 finds a divergence, the first move is not to patch the implementation, but to ask which upstream artifact is wrong (the story, the architecture, or the contract) and correct that artifact first. The code should then follow the corrected specification. This is the same discipline as <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>, one level up: do not change the code until you know what in the specification needs to change.</p>
<p>The filters are my clearest example. I wanted the dashboard filters to be the same as the ones on the homepage list of assets, because a user should not have to learn two filter bars in the same product. But the two screens do not show the same data, so the same filter does not always return the same thing. Same filters, different data. That is a decision about the product and the specification, and not the kind of decision a single story should take on its own. So we called <code>bmad-correct-course</code>. The contract itself did not really move, only its description changed. What changed is the specification: the invariants were reinforced and new decisions were added, and both tracks then worked from that. The code came last, which is the whole point of the direction above.</p>
<h2>When to use it and when to avoid it</h2>
<p>BMAD is powerful and can handle a lot of work, but that doesn’t mean every piece of work benefits from it. It shines when the uncertainty or coordination risk is high enough to justify the overhead.</p>
<h3>Greenfield or brownfield</h3>
<p>Everything above describes a feature added to a system I already knew. That is the ordinary case, but the first thing to separate is <strong>greenfield</strong> from <strong>brownfield</strong> work.</p>
<p><strong>Greenfield is where the method is easiest to justify.</strong> There is no existing code to reconcile, so the artifacts BMAD produces are decisions rather than descriptions. Planning pays for itself because it is doing real work: choosing, not documenting.</p>
<p><strong>Brownfield is where the method gets more expensive, because context already exists in the code.</strong> BMAD supports established projects, including context discovery that examines the codebase, verifies what it finds, and confirms it with you before recording it.</p>
<p><em><strong>The trap is thinking you need to describe the whole system first.</strong></em></p>
<p><strong>You don't have to do that at all</strong>. Reverse-engineering an entire codebase into a PRD and architecture document is slow, expensive, and often produces documents that <strong>describe rather than decide</strong>. Worse, an AI-generated description can be fluent and plausible while still being wrong.</p>
<p>So my rule for existing projects is:</p>
<blockquote>
<p><strong>Adopt the method at the boundary of new work. Describe the existing system only as deeply as that work requires.</strong></p>
</blockquote>
<p>New features get the full treatment: epic, contract, stories. Existing features get documented only when something touches them. Context discovery should cover the modules the new work actually reaches, not the entire repository.</p>
<p>The old code remains the source of truth about itself, and the specification grows one feature at a time instead of arriving as one 200-page document written up front.</p>
<p>The cost follows from that split. On greenfield, planning cost is proportional to the feature. On brownfield, it is proportional to <strong>how much of the existing system you choose to explain first</strong>, and that number is under your control.</p>
<p>Beyond that split, the decision comes down to a short list.</p>
<h3>Use it when</h3>
<ul>
<li><p><strong>the work crosses repositories, stacks, teams, or ownership boundaries;</strong></p>
</li>
<li><p><strong>the API contract is the risky part, and freezing it early unlocks parallel work;</strong></p>
</li>
<li><p><strong>the domain is new to you and the expensive mistakes are conceptual, not technical;</strong></p>
</li>
<li><p><strong>the decisions need to remain understandable to people who are not in the room today.</strong></p>
</li>
</ul>
<h3>Skip it when</h3>
<ul>
<li><p><strong>the change is clear and local</strong>: BMAD's own guidance is that clear work can enter implementation directly, without the planning artifacts;</p>
</li>
<li><p><strong>you are exploring rather than committing</strong>: a spike, prototype, or proof of concept that you expect to throw away does not need the full specification workflow;</p>
</li>
<li><p><strong>the ceremony is larger than the feature</strong>: a one-file fix does not need a PRD, and pretending otherwise is how teams learn to hate a method;</p>
</li>
<li><p><strong>the work is repetitive and well understood</strong>: a CRUD back-office over a known schema, a simple admin screen, an internal tool, or a batch job where the data model already determines most of the design leaves little for the planning layer to decide;</p>
</li>
<li><p><strong>the change does not alter the feature's shape</strong>: bug fixes, copy changes, renames, dependency updates, and missing null checks generally do not require reopening the feature definition or contract.</p>
</li>
</ul>
<p>The distinction is not project size, it is <strong>how much of the risk is in deciding what to build</strong>. When that risk is near zero, the planning layer has nothing to protect you from.</p>
<p>And the important one, because it is the case that comes up every week: <strong>BMAD being installed on the project does not mean every change goes through it.</strong> It should not be used for every task. Use it when the work is substantial enough to justify an epic.</p>
<p>The planning layer exists to protect the shape of the system, so it earns its place only when the change can alter that shape. When the answer is clearly no, running it anyway costs time and teaches the team that the method is bureaucracy. The method covers the feature, it does not have to cover every commit.</p>
<p>The real cost is not tokens, it is that <strong>you have to learn the workflow set and the handoffs between them</strong> before the method starts paying.</p>
<h2>If you are not on Claude Code</h2>
<p>Stages 1 and 3 are portable. Stage 2 is the replaceable slot.</p>
<p>BMAD is Markdown and YAML, so it works wherever your agent reads files. Superpowers is a <em>Claude Code</em> plugin, so if you work elsewhere, that is the piece you swap: for another plugin, another IDE that enforces the same discipline, or your own commands.</p>
<p>Two things matter when you choose the replacement. It must enforce the test-first cycle rather than suggest it, and it must let a reviewer who did not write the code look at the result. Without those, Stage 3 has to carry weight it was not designed to carry.</p>
<p>One warning, and it is the same one as everywhere else in this article: some tools bring their own planning documents. If yours does, decide which layer owns the story before you start. Running two planners is how you end up with two specifications, scattered again.</p>
<h2>We have done this before, and it did not end well</h2>
<p>This is the longer version of the argument I promised earlier.</p>
<p>For years, companies built their own frameworks even though good public ones already existed. The reasoning was always the same: <em>our needs are special; we know our business better.</em> For a while, it felt like an advantage. The homemade framework did not fail by breaking, it failed by blocking everything above it.</p>
<p>Now the same reflex is appearing one level higher. Open methods like BMAD exist, yet teams are building their own prompt libraries, rule formats and internal workflows by copying pieces from elsewhere. Same reasons, same trap.</p>
<p>The difference is that this time it moves faster. Models and tools change every day, so maintaining your own method means keeping up with all of those changes yourself. And when a copied rule stops working, its upstream may already have fixed it, but you never get the fix.</p>
<p>The line I would draw is between <strong>the engine and the edges</strong> as follows:</p>
<p><strong>The engine</strong> is the workflows, phases, agent roles and handoff rules. Take that from outside. Let someone else maintain it, find the bugs and keep it current.</p>
<p><strong>The edges</strong> are yours: your invariants, business rules, architecture constraints, naming, verification commands and skills. That is where your real specificity belongs.</p>
<p>Before building anything internal, ask:</p>
<ul>
<li><p><strong>Who fixes this when it breaks?</strong> If the answer is only us, it is a liability.</p>
</li>
<li><p><strong>What does it cost to leave?</strong> BMAD is Markdown and YAML, so leaving costs a delete. A custom orchestrator with its own state and habits costs a migration.</p>
</li>
</ul>
<p>The same applies to forking. Customise BMAD until nobody recognises it and you have simply rebuilt the homemade framework, including the same upgrade problem.</p>
<p>That distinction also explains what I publish myself. The living specification is not an engine, it is a way to organise a project: where intent lives, what counts as an invariant, what "done" means, plus practices that survived real work. That is an edge, and every team needs to define its own.</p>
<p>The engine comes from outside. BMAD publishes the workflows, roles, rules and skills, and a community keeps them alive. I am not asking anyone to adopt my framework because I don't have one. I am suggesting a way to organise your project, whichever engine you choose.</p>
<h2>What I would tell a team on Monday</h2>
<p><strong>Adopt</strong> the frozen contract and the session boundary. They cost almost nothing and they are what make parallel tracks safe. I also recommend adopting the loop that lets you revise the contract when it turns out to be wrong.</p>
<p><strong>Adapt</strong> the artifacts. Use BMAD's planning workflows to <strong>reach decisions</strong>, then record those decisions in your specification and let the PRD go. One durable source of truth, several disposable scaffolds.</p>
<p><strong>Skip</strong> the full track for small work. Enter implementation directly. A method you apply to everything is a method your team will eventually bypass.</p>
<p>And above all, keep the intent in one shared place. Every lesson in this article is a variation on that one.</p>
<blockquote>
<p>AI writes the code. A method decides what gets built. Neither one decides whether it is right.</p>
</blockquote>
<p><strong>That still requires an engineer.</strong></p>
<hr />
<h2>Links</h2>
<p><strong>The series</strong></p>
<ul>
<li><p><a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now">Part 1 — AI Writes the Code. So What Is the Engineer's Job Now?</a></p>
</li>
<li><p><a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2 — The Living Specification: How I Keep AI-Written Code Correct</a></p>
</li>
<li><p><a href="https://github.com/elie29/ai-sample">The template repository</a> — <code>CLAUDE.md</code>, rule files, skills, specifications, plans and reusable prompts</p>
</li>
</ul>
<p><strong>Official documentation</strong></p>
<ul>
<li><p><a href="https://docs.bmad-method.org/">BMAD Method</a></p>
</li>
<li><p><a href="https://github.com/obra/superpowers">Superpowers</a></p>
</li>
</ul>
<p><strong>Further reading</strong></p>
<ul>
<li><p><a href="https://claude-codex.fr/en/advanced/methodologies-ecosystem/">Claude Code methodologies: Superpowers, BMAD, Spec Kit, OpenSpec</a> — how the four compare</p>
</li>
<li><p><a href="https://github.github.com/spec-kit/concepts/spec-persistence.html">Spec Kit — spec persistence models</a> — the durable specification and its disposable derivations, named</p>
</li>
<li><p><a href="https://github.com/bmad-code-org/BMAD-METHOD/discussions/1425">BMAD discussion — backend, frontend and hardware in one method</a></p>
</li>
<li><p><a href="https://github.com/orgs/community/discussions/72720">GitHub discussion — stories when you have more than one repository</a></p>
</li>
<li><p><a href="https://arxiv.org/html/2602.00180v1">Spec-Driven Development: From Code to Contract in the Age of AI Coding Assistants</a> — invariants, pre and postconditions, integration contracts</p>
</li>
</ul>
<hr />
<h2>Let's stay in touch</h2>
<p>I share what I learn about AI-assisted engineering, software architecture and databases. If this article made you rethink how you work with a method, follow me on <a href="https://x.com/elie_nehme"><strong>X</strong></a> and connect with me on <a href="https://www.linkedin.com/in/elie-nehme/"><strong>LinkedIn</strong></a>. I would like to hear how BMAD, or any other method, behaved on your own projects.</p>
]]></content:encoded></item><item><title><![CDATA[The Living Specification: How I Keep AI-Written Code Correct]]></title><description><![CDATA[The spec is the source of truth, invariants are the contract, code is a verified implementation. A practical method for AI-assisted engineering]]></description><link>https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct</link><guid isPermaLink="true">https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct</guid><category><![CDATA[aitools]]></category><category><![CDATA[SDLC]]></category><category><![CDATA[context engineering]]></category><category><![CDATA[System Design]]></category><category><![CDATA[System Thinking]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Wed, 19 Aug 2026 15:05:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/3af63d3e-5d41-47de-a342-9218c4d35d1b.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<blockquote>
<p><em><strong>Note: Originally published on</strong></em> <a href="https://elie29.medium.com/the-living-specification-how-i-keep-ai-written-code-correct-907be05c9eed"><em><strong>Medium</strong></em></a></p>
</blockquote>
<p><em>Second and final part of "AI Writes the Code. So What Is the Engineer's Job Now?", a series in 2 articles.</em></p>
<p><a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now"><em>Previously</em></a><em>: the story</em> — <em>one developer, two months, and the three bugs an adversarial AI review found before a single line of code.</em></p>
<p><em>Today: the method.</em></p>
<p>In <a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now">Part 1</a>, an adversarial design review found three real problems before implementation. The obvious question is: what kind of workflow makes this repeatable?</p>
<blockquote>
<p>The answer is a change in the source of truth!</p>
</blockquote>
<h2>The code is not the source of truth anymore</h2>
<p>This is the most important change in my workflow, and it is easy to misunderstand.</p>
<p>I do not start from code and then try to keep the specification close to it.</p>
<blockquote>
<p>The specification is the source of truth. The invariants are the contract. The code is an implementation of that contract.</p>
</blockquote>
<p>An invariant is a rule that must remain true in the system. For example:</p>
<ul>
<li><p>a user must not access a period they cannot see;</p>
</li>
<li><p>an asset must belong to the correct organisational scope;</p>
</li>
<li><p>every API entry point must use the same authorization rule;</p>
</li>
<li><p>a migration must preserve the required organisational relationships.</p>
</li>
</ul>
<p>These are not implementation details. They are properties of the system.</p>
<p>In a <strong>traditional project</strong>, specifications are written before development and then slowly become outdated. The code changes every day. The documentation changes when somebody remembers to update it 🫩</p>
<img src="https://cdn-images-1.medium.com/max/1500/1*euSqpzu4Ge2TiTZ7WPd2yA.png" alt="Diagram of specification drift. A specification, written once then frozen, is linked to the code by a dashed line crossed out and labelled &quot;updated when somebody remembers&quot;. The code changes every week and exchanges arrows with reality: bugs, new needs and hotfixes. Eventually the code becomes the real source of truth and the documentation becomes historical." style="display:block;margin:0 auto" />

<p>With an AI-assisted workflow, I cannot afford this. If the specification is outdated, the AI will read outdated information and produce new code based on it.</p>
<p>So the rule becomes strict: <em><strong>The specification is the source of truth. Code reflects the specification. Not the opposite.</strong></em></p>
<img src="https://cdn-images-1.medium.com/max/1500/1*3-QoxtAtb0ZU3qEiYYUFSQ.png" alt="Diagram of the living specification cycle. Specification and invariants are the source of truth: the rules that must remain true in the system. The AI implementation takes one small task, applied against the rules. It produces code, an implementation of the contract and never where decisions are made. Verification asks whether the code satisfies the invariants, with a real command. If it fails, an arrow returns to the specification, which is fixed first, then the AI realigns the code." style="display:block;margin:0 auto" />

<p>When something is wrong, I do not touch or modify the code at all. First, I ask:</p>
<ul>
<li><p>Is the specification wrong?</p>
</li>
<li><p>Is an invariant missing or ambiguous?</p>
</li>
<li><p>Did we misunderstand the business rule?</p>
</li>
</ul>
<p>If the specification was wrong, I correct it. If an invariant was missing, I add it. Then I ask the AI to align the code with the specification.</p>
<p><strong>N.B.: This discipline is not optional.</strong> If you change the code directly and forget the specification, the next AI session reads the old rule and can reintroduce the old behavior. The project splits into two realities: what the documentation says and what the code does.</p>
<p>The whole approach exists to prevent exactly that.</p>
<h2>Three development models</h2>
<p>I see three different models in the industry right now:</p>
<img src="https://cdn-images-1.medium.com/max/1500/1*VM8qXoI4LbswuLYvWFcosg.png" alt="Diagram comparing three development models. Model 1, classic: business need, specification, architecture, development, review and QA, security review, deployment; feedback arrives late. Model 2, AI coding assistant: the human designs, the AI writes, the human reviews; it assumes the design is correct. Model 3, highlighted: human and AI explore the problem, specification and invariants, the AI attacks the design, implements a small task, verification, human review and commit." style="display:block;margin:0 auto" />

<p><strong>Model 1</strong> —<strong>the classic approach:</strong> The problem is not that every part is wrong. The problem is the feedback loop. You discover a misunderstanding during QA. You discover an architecture problem after several features are built. You discover a security problem near the end of the process, whether you're using a waterfall approach or Agile. The process is mostly sequential.</p>
<p><strong>Model 2</strong> —<strong>the AI coding assistant:</strong> It is already much faster. But it uses AI for the cheapest part of software development: <em><strong>typing</strong></em>. It also assumes the human's design is correct. And because this model is widely used, people <strong>incorrectly think</strong> that developers are no longer needed.</p>
<p>My project showed me that my own designs were not always correct. It contained the wrong validation boundary, an incomplete migration and the wrong sorting. If the AI had started only after the design was approved, it would simply have implemented those mistakes faster.</p>
<p>There is also another problem: how do you review <em><strong>hundreds of generated lines</strong></em> if there is no written specification? Without expected behavior and verification commands, code review becomes very difficult, if not impossible.</p>
<p><strong>Model 3</strong> —<strong>AI-assisted engineering:</strong> The important difference is that AI participates before implementation. It is not only a code generator. It becomes a questioning system. It challenges the product idea, challenges the architecture, writes and reviews tests, reviews security, checks accessibility. But the human remains responsible for the decisions.</p>
<h2>The real operating system: rules, skills and plans</h2>
<p>One of the most useful things I built was the AI configuration structure of the project. It contains <strong>rules</strong> and <strong>skills</strong>. The rules describe the project. The skills perform actions.</p>
<p>In <a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now">Part 1</a>, I explained that <code>CLAUDE.md</code> should stay concise and delegate to focused rule files. The frontend rules alone eventually became 18 smaller files: architecture, API, RBAC, security, testing, design and UX, performance, naming...</p>
<p>However, <strong>a skill that is specific to the project lives in the repository; a skill that is repeatable across projects lives at the account level</strong> (<code>~/.claude/skills/</code>). An adversarial design review works the same everywhere - install it once and every project benefits. A skill that knows your routes, your roles or your migration conventions belongs to the project.</p>
<p>The second important structure: every non-trivial feature gets a <strong>specification</strong> and an <strong>execution plan</strong>. The plan contains status, current task, decisions, blockers, verification commands and expected build state.</p>
<p>Two sentences became the rules of the project— and, eventually, of all projects:</p>
<ul>
<li><p><em><strong>The plan file is the source of truth</strong></em></p>
</li>
<li><p><em><strong>A decision that lives outside the plan did not happen</strong></em></p>
</li>
</ul>
<blockquote>
<p>A two-month project contains many conversations. Conversations disappear. The repository remains.</p>
</blockquote>
<p>This has a very practical consequence: <strong>the state of the work lives ONLY in the plans</strong>. I can stop a session, clear the context, or restart the conversation at any moment without losing anything. The next session reads the plan—current task, decisions, blockers, expected build state —and continues exactly where the previous one stopped.</p>
<h2>Prompts are project assets</h2>
<p>There is a third element next to rules and skills: <strong>reusable prompts</strong>.</p>
<p>During the project, the same requests kept coming back: explore a business need and create the specification, implement one task from a plan, review a migration before writing it, apply an API contract change, run an accessibility review. I stopped typing them from scratch. Each one became a file in the repository, versioned with the code and improved after every use.</p>
<p>A good reusable prompt encodes the discipline so I do not have to remember it: which rule files apply, the exact scope, the verification command, and where the AI must stop and ask. For example: <em>"Implement ONLY task N from the plan. Run its verification command and show me the real output. Do not start the next task. Do not commit."</em></p>
<p>The prompt library grows like a toolbox. A prompt that produced a good result is worth keeping. A prompt that produced a bad one is worth fixing— exactly like code. See my <a href="https://github.com/elie29/ai-sample">GitHub project</a> for an example.</p>
<h2>Small tasks, real verification</h2>
<p>AI can produce a lot of code very quickly. That creates a new danger: it can also produce a lot of <strong><em>WRONG</em> code very quickly</strong>.</p>
<p>So I added strict scope rules. One task. One file when possible. One verification. Then review.</p>
<p>When I asked AI to generate tests for everything, I got many poor tests that I did not properly review. When I asked for one file at a time, quality increased because the review became manageable. The same principle applies to security: <strong>audit can be broad, fixing should be narrow.</strong></p>
<p>I also changed the meaning of "done". Previously: <em>the code looks good</em>. Now: <strong>show me the evidence</strong>.</p>
<p>Every task has a verification command, and the expected result is written before the command is executed. The AI is not allowed to say "it should work".</p>
<p>This matters because AI has a particular failure mode: <strong>confident, well-structured answers that are wrong</strong>. The answer is not to trust the AI less. The answer is to verify more.</p>
<p>And the human's work must be verified too. During the redesign, I predicted the test suite would stay green through the first tasks. The measured result: 807 tests run, 138 failures, 38 errors. The plan was wrong. The measurement corrected it.</p>
<h2>Quality became cheaper</h2>
<p>One of the biggest changes was economic.</p>
<p>Before AI, doing the proper thing had a cost. Detailed tests, double migrations, documented decisions, edge-case reviews— often the answer was "<em>we don't have time</em>".</p>
<p>AI changes that equation. The project has <strong>16,092 lines of test code versus 14,226 lines of production code</strong>. I had never reached that ratio on a project of this size. Not because I became more disciplined— because the mechanical cost of the right way became small.</p>
<p><em><strong>When the mechanical cost becomes small, the right way becomes cheaper.</strong></em></p>
<p>The industry may not become less disciplined. It may become possible to be <em>more</em> disciplined without paying the old cost. That is a much more interesting effect than writing code faster.</p>
<h2>How Every Role Changes</h2>
<p>AI does not simply make each role faster. It changes where the value of each role lies.</p>
<p>The shift across the main SDLC roles covered here is as follows:</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/a1f5a57c-921c-4621-8010-3560afc5d388.png" alt="Table of how ten roles move from an old to a new centre of gravity. Product owner or BA, from requirements to intent and decisions. UX/UI designer, from screens to design systems. Architect, to architecture as executable constraints. Developer, from code to solution definition and verification. QA, to quality strategy and evidence. Security, to continuous verification. Data, to data contracts. Platform, to paved roads. SRE, to reliability boundaries. Tech lead, to judgement and coherence." style="display:block;margin:0 auto" />

<h3>Product Owner / BA</h3>
<p>From writing requirements to <strong>exploring them with AI, challenging assumptions and making decisions explicit</strong>.</p>
<p>Ambiguous business language becomes expensive when an AI can apply it across thousands of lines of code.</p>
<p>The PO/BA therefore becomes less of a requirements writer and more of an interpreter of intent: identifying ambiguity, resolving contradictions, exploring edge cases and making decisions explicit enough for both humans and machines to act on.</p>
<h3>UX/UI Designer</h3>
<p>From producing screens to <strong>producing design systems, interaction rules and accessibility constraints</strong>.</p>
<p>In my project there was no Figma: the running Angular application, generated inside a set of design rules, became the maquette, and the browser became the feedback loop.</p>
<p>This changes the designer's role from producing individual screens to defining the system that generates consistent experiences: components, interaction patterns, responsive behaviour, accessibility rules and visual constraints.</p>
<h3>Architect</h3>
<p>From designing the architecture to <strong>comparing AI-generated alternatives and verifying conformance continuously</strong>.</p>
<p>My architecture verification skill checks the actual code against the constraints.</p>
<p>The architecture is no longer only a diagram. It becomes a testable contract.</p>
<p>The clearest example in my project is the OpenAPI contract: it is the source of truth for the API. The backend generates its interfaces from it, the frontend consumes it, and generated code is never manually edited.</p>
<p>An architectural change is no longer:</p>
<blockquote>
<p>“Let's change the code”</p>
</blockquote>
<p>It becomes:</p>
<blockquote>
<p>“Let's change the contract and see what breaks”</p>
</blockquote>
<p>The compiler and the generated code become part of the impact analysis.</p>
<h3>Developer</h3>
<p>From implementing features to <strong>defining, reviewing, validating and evolving solutions</strong>.</p>
<p>When implementation itself becomes increasingly cheap, the developer's value moves toward understanding the problem, selecting between alternatives, defining the right constraints and reviewing the output.</p>
<p>The developer is no longer simply the person who translates a specification into code.</p>
<p>They increasingly define what a good implementation looks like and provide the evidence that the generated implementation actually satisfies that definition.</p>
<h3>QA Engineer</h3>
<p>AI can generate 100 tests.</p>
<p>The QA engineer must ask:</p>
<blockquote>
<p>“Do these 100 tests prove the right thing?”</p>
</blockquote>
<p>That is a more valuable question.</p>
<p>The role moves from producing and executing test cases toward <strong>quality strategy, coverage reasoning and evidence</strong>.</p>
<p>AI can generate tests at enormous scale, but it does not automatically know whether the tests capture the important business risks, missing scenarios or incorrect assumptions.</p>
<h3>Security Engineer</h3>
<p>From a review phase at the end to <strong>security reasoning during design and continuous verification</strong>.</p>
<p>My most interesting security finding did not come from a scanner.</p>
<p>It came from a domain question:</p>
<blockquote>
<p>“If category routes enforce period visibility, do asset routes enforce it too?”</p>
</blockquote>
<p>A scanner cannot easily ask that.</p>
<p>AI can make security checks more continuous and can find classes of technical vulnerabilities at scale.</p>
<p>But security expertise increasingly lies in understanding the domain, identifying the security invariants that must hold, and asking the questions that automated tools would not know to ask.</p>
<h3>Data Engineer</h3>
<p>From implementing pipelines and SQL to <strong>defining data contracts and ensuring semantic correctness</strong>.</p>
<p>AI can generate transformations, queries and pipelines very quickly.</p>
<p>The difficult question becomes whether the resulting data actually means what the business thinks it means.</p>
<p>The data engineer therefore increasingly owns contracts, quality rules, semantic definitions and validation—not simply the mechanics of moving and transforming data.</p>
<h3>Platform Engineer</h3>
<p>From building and maintaining infrastructure to <strong>defining platform constraints and paved roads</strong>.</p>
<p>AI can generate Terraform, CI/CD pipelines, Kubernetes manifests and configuration.</p>
<p>The platform engineer increasingly defines the environment in which those generated solutions are allowed to operate.</p>
<p>The goal becomes less:</p>
<blockquote>
<p>“How do I configure this service?”</p>
</blockquote>
<p>and more:</p>
<blockquote>
<p>“How do I make the correct path the easiest path, while making incorrect configurations impossible?”</p>
</blockquote>
<h3>SRE</h3>
<p>From operating systems and responding to incidents to <strong>defining reliability boundaries and enabling automated verification and remediation</strong>.</p>
<p>AI can analyse telemetry, correlate signals, generate runbooks and propose or execute remediation.</p>
<p>But someone still needs to define what reliable means, which failures are acceptable, what actions are safe to automate and where human intervention is required.</p>
<p>The SRE therefore moves toward defining SLOs, failure boundaries, observability requirements and the limits of autonomous remediation.</p>
<h3>Tech Lead</h3>
<p>Enforcing standards can increasingly be automated: architecture checks, naming conventions, test-quality rules, repeated security audits and other forms of static verification.</p>
<p>The remaining part becomes the whole job:</p>
<blockquote>
<p><strong>Judgement</strong></p>
</blockquote>
<p>The Tech Lead increasingly operates at the level where individual outputs have to form a coherent system.</p>
<p>The question is no longer simply whether the code follows the rules, but whether the rules themselves are appropriate, whether the trade-offs make sense and whether the different AI-generated solutions still fit together.</p>
<h3>The common shift</h3>
<p>Across all these roles, the pattern is similar.</p>
<p><strong>AI lowers the cost of producing software.</strong></p>
<p>The SDLC therefore shifts toward <strong>making intent explicit, defining constraints, evaluating alternatives, and demonstrating that the produced system is correct</strong>.</p>
<p>The intended skill is no longer the ability to produce an artifact.</p>
<p>It is the ability to <strong>judge whether the artifact should exist, whether it expresses the intended solution, and whether there is enough evidence to trust it.</strong></p>
<h2>Am I losing my skills?</h2>
<p>Some skills became less important for me: typing speed, API memorisation, boilerplate, manual test scaffolding.</p>
<p>And I have noticed something uncomfortable: <strong>my recall has become worse</strong>. I cannot write a <em>Spring Security filter chain</em> from memory as fluently as I could two years ago. I do not want to hide that. 😁😁😁</p>
<p>But I can still read one. I can identify when it is wrong. I can explain why. For me, that is a good trade— but it is a trade, and we should not pretend otherwise.</p>
<p>At the same time, my technical reach expanded. The learning loop changed <strong>from</strong> "<em>read a tutorial → memorise → use it later</em>" <strong>to</strong> "<em>need something → ask why → compare options → implement → break it → understand it</em>". AI makes that loop very fast.</p>
<blockquote>
<p>AI increases the value of technical understanding, because it increases the amount of technical output one engineer can control.</p>
</blockquote>
<p><strong>This creates a hard problem for junior developers</strong>. A junior can now generate a migration without understanding data consistency, or authentication without understanding the threat model.</p>
<p>The answer cannot be "<em>don't use AI until you are senior</em>" — AI is too useful. The answer is: <strong>use AI as a teacher, but require understanding and verification</strong>. Not "<em>write this</em>", but "<em>explain three ways to implement this, the risks, why you would choose one, and how to test it</em>".</p>
<p>The goal is not to protect typing skills. The goal is to build engineering judgement.</p>
<h2>A new skill: context engineering</h2>
<p>One skill did not have this importance before. It is <strong>context engineering:</strong> knowing how to give AI the context required to produce your system instead of generic code.</p>
<p>Writing good rules and specifications. Defining architecture constraints and scope. Recording decisions. Defining verification. Structuring skills and specialised agents. Maintaining project memory.</p>
<p>This is not prompt engineering in the old sense. It is engineering the environment in which the AI operates. And it requires technical understanding: you cannot write good architecture rules if you do not understand architecture, and you cannot define a good verification command if you do not know what correctness means.</p>
<blockquote>
<p>AI amplifies the quality of the context. It does not magically create that quality.</p>
</blockquote>
<h2>What I Recommend for a Team</h2>
<ol>
<li><p><strong>Write the rules.</strong> A project-level document with architecture, coding standards, security rules, testing rules, naming, commands and forbidden patterns. Make it part of the repository.</p>
</li>
<li><p><strong>Separate rules from actions.</strong> Rules explain how the project works; skills explain how to perform a task. Do not put everything into one huge instruction file.</p>
</li>
<li><p><strong>Make AI challenge the design.</strong> Before implementation, ask: what did we forget? What assumption is dangerous? What happens to existing data? What happens when two rules interact?</p>
</li>
<li><p><strong>Make decisions persistent.</strong> Decision, date, reason, rejected alternatives. A decision that lives only in the chat did not happen.</p>
</li>
<li><p><strong>Keep tasks small.</strong> One task, one verification, one review. Then continue.</p>
</li>
<li><p><strong>Separate audit and fix.</strong> One process finds problems, another applies the fix, then audit again.</p>
</li>
<li><p><strong>Keep the human responsible for commits.</strong> In my workflow, <em>Claude Code</em> never commits. The commit is the moment where I say: <em>I accept responsibility for this change</em>.</p>
</li>
<li><p><strong>Measure reality.</strong> Do not write "the tests should pass". Run them. Do not write "the security issue is fixed". Re-audit it.</p>
</li>
</ol>
<h2>From the keyboard to the review seat</h2>
<p>For twenty-five years, a large part of my professional value came from producing code. AI changed that. The production part almost disappeared.</p>
<p>But the engineering part did not. It became more visible.</p>
<p>I now spend more time deciding what to build, why to build it, what "correct" means, what can go wrong, how to verify it, and whether I trust the result.</p>
<p>That is not less engineering. It is a different kind of engineering.</p>
<p>The new paradigm is not "<em>human thinks → AI types</em>". It is:</p>
<p><em><strong>Human and AI explore → specify → challenge → implement → verify → learn</strong></em></p>
<p>The human brings responsibility. The AI brings speed and breadth. The repository keeps the memory. The tests provide evidence. The adversarial review provides a machine that is willing to attack my assumptions before my users do.</p>
<p>AI writes the code now. It does not decide whether the code is right. That still requires an engineer. And perhaps more engineering skills than before.</p>
<p>Structured methods for AI-driven development are emerging —<a href="https://docs.bmad-method.org/"><strong>BMAD</strong></a> is a notable one. Comparing them with the approach described here deserves its own article.</p>
<blockquote>
<p>So do not ask whether AI can write your code. Ask whether you would know if it was wrong.</p>
</blockquote>
<hr />
<p>Missed the story behind this method? Read <a href="https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now">Part 1 ←</a></p>
<hr />
<h2><strong>Grab the template</strong></h2>
<p>Everything described in this article - a concise <a href="http://CLAUDE.md"><code>CLAUDE.md</code></a>, focused rule files, skills, specifications, plans and reusable prompts - is available as a public template: <a href="http://github.com/elie29/ai-sample"><strong>github.com/elie29/ai-sample</strong></a>. Copy the structure, rewrite the rules for your project, and make it yours.</p>
<hr />
<h2><strong>Let's stay in touch</strong></h2>
<p>I share what I learn about AI-assisted engineering, software architecture and databases. If this article made you rethink your own workflow, follow me on <a href="https://x.com/elie_nehme"><strong>X</strong></a> and connect with me on <a href="https://www.linkedin.com/in/elie-nehme/"><strong>LinkedIn</strong></a> .  I would like to hear how you work with AI on real projects.</p>
]]></content:encoded></item><item><title><![CDATA[AI Writes the Code. So What Is the Engineer's Job Now?]]></title><description><![CDATA[How I used Claude and an adversarial design review to build an enterprise software assets platform]]></description><link>https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now</link><guid isPermaLink="true">https://elie29.hashnode.dev/ai-writes-the-code-so-what-is-the-engineer-s-job-now</guid><category><![CDATA[ai agents]]></category><category><![CDATA[claude-code]]></category><category><![CDATA[skills development]]></category><category><![CDATA[superpowers]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Sat, 15 Aug 2026 07:38:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/68e03345-8688-4ccc-8b7d-6a9ff851050d.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Note: Originally published on <a href="https://medium.com/@elie29/ai-writes-the-code-so-what-is-the-engineers-job-now-79fa3fdf1b88">Medium</a></p>
</blockquote>
<p><em>First part of “AI Writes the Code. So What Is the Engineer’s Job Now?”, a series in 2 articles.</em></p>
<p><em>Today: the story — one developer, two months, and the three bugs an adversarial AI review found before a single line of code.</em></p>
<p><a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct"><em>Part 2</em></a><em>: the method — the living specification, the invariants, and how every role in the SDLC changes.</em></p>
<p>A few weeks ago, I asked <em>Claude Code</em> to attack a design I had already prepared.</p>
<p>I did not ask it to write code. I asked it to find what was wrong with my thinking.</p>
<p>The feature was a redesign of how my application handles periods and years. I thought the design was ready. Unfortunately, it was not 😞</p>
<p>The review found a validation rule that would have hidden an entire period from users. It found a database migration that would have copied only part of the organisational hierarchy. It found a sort order that would have silently changed the period selector for every user.</p>
<p>And then it found something more uncomfortable.</p>
<p>There was already a security gap in production. The asset routes did not apply the same period visibility rule as the category routes. A user could still see an asset for a period they were not supposed to see.</p>
<p>None of these problems were syntax errors. The compiler could not detect them. The test suite could not detect them either.</p>
<p>They were not coding but <strong>engineering mistakes</strong>.</p>
<p>That is the main lesson I took from several months of building with <em>Claude Code</em>:</p>
<blockquote>
<p><em>AI does not remove the need for engineering skills. It changes where we apply them.</em></p>
</blockquote>
<p>AI can now produce code extremely quickly. The important question is no longer “Can AI write this code?”. It clearly can.</p>
<p>The better question is: <em><strong>“Would I know if the code was wrong?”.</strong></em> And answering that question requires more engineering skill, not less.</p>
<h3>The project: one developer, two repositories</h3>
<p>The project is an enterprise <strong>software assets platform</strong>: an application that answers a simple business need — <em>we need to know what assets we have and what they are worth.</em></p>
<p>I built it in two repositories: a Spring Boot / Java backend and an Angular frontend.</p>
<p>The project started from almost nothing. No Figma. No architecture document. No ticket backlog. No existing application.</p>
<p>Two months later, the result was:</p>
<ul>
<li><p>14,226 lines of backend production code</p>
</li>
<li><p>16,092 lines of backend test code</p>
</li>
<li><p>25 database migrations, each written for PostgreSQL and H2</p>
</li>
<li><p>118 design records and 13 cross-repository handoff documents</p>
</li>
<li><p>14 custom AI skills and agents</p>
</li>
</ul>
<p>➡️ <em>These numbers come from the repositories, not from memory.</em></p>
<p>I did not run a controlled productivity experiment, so I will not pretend I can prove a precise percentage improvement. My estimate is that the same scope at the same quality would normally require a team of two or three developers for six to nine months. That is an order-of-magnitude difference — but I prefer the more useful statement:</p>
<p><em><strong>One developer could reach a scope that I would previously have considered a small team project.</strong></em></p>
<p>And there is another important point. The project did not become simpler because AI was involved. It became <strong>more ambitious</strong>: a year-scoped organisational hierarchy, seven periodised content categories, period lifecycle management, annual rollover, RBAC with seven roles, PDF and CSV exports, several dashboards, an MCP server for AI agents, and audit logging.</p>
<p>This is not a CRUD demo. It is a production application where a wrong visibility rule can expose financial information.</p>
<p>That is what makes AI-assisted development so <strong>transformative</strong> and <strong>amazing</strong>.</p>
<h3>First lesson: I did not start with code</h3>
<p>This is probably the biggest difference from how I used to work.</p>
<p>My old instinct was simple: <em>I have the requirement. Let me create the first controller.</em></p>
<p>This time, I wrote the rules first.</p>
<p>Each repository has a <a href="http://CLAUDE.md"><code>CLAUDE.md</code></a> file at its root. It is the first thing the AI reads in every session, so it became the project's operating system.</p>
<p>The discipline that makes it work: keep <a href="http://CLAUDE.md"><code>CLAUDE.md</code></a> <strong>concise.</strong> It does not try to contain everything. It describes what the project is, states the non-negotiable rules, and points to dedicated rule files — architecture, naming conventions, security, testing, design, commands and forbidden patterns. The AI loads a detailed rule file only when it works on that topic.</p>
<p>I learned this the hard way. My first version was one large file with everything in it. It did not work well: every session paid the cost of reading it, and the important rules drowned in the details. A concise <a href="http://CLAUDE.md"><code>CLAUDE.md</code></a> that delegates to focused rule files keeps the context sharp.</p>
<p>I published a public example of this structure on GitHub: <a href="https://github.com/elie29/ai-sample">github.com/elie29/ai-sample</a>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/f13ac6c6-3bfc-4ee3-864a-d8e68deeb7a9.png" alt="Diagram of the CLAUDE.md structure. A concise CLAUDE.md, holding what the project is, the non-negotiable rules and pointers to the details, fans out to five directories: .claude/rules/, loaded on demand; .claude/skills/, actions rather than descriptions; docs/superpowers/, the source of truth per feature, with specs/ and plans/; docs/prompts/, reusable and versioned; and docs/decisions/, the persistent memory, because a decision that lives only in the chat did not happen." style="display:block;margin:0 auto" />

<hr />
<p>This created an interesting change. Previously, documentation was something I wrote for humans. Now, documentation became something the development system uses.</p>
<p>That makes incorrect documentation much more dangerous - if the AI reads a wrong rule, it produces wrong code. But it also makes documentation much more valuable. A rule that is consumed every day is much more likely to stay useful.</p>
<p>One sentence became important for the whole project: Documentation only stays correct when something consumes it.</p>
<h2>My "AI team" is not one AI</h2>
<p>Another mistake would be to think that I simply opened Claude Code and asked: "<em>Build my application</em>".</p>
<p>That is not what happened. I created a set of specialised roles: a security agent, a test agent, an accessibility agent, a SQL data generation agent for generating realistic production-like test data, an architecture verification skill, and audit-and-fix skills for security, tests and accessibility.</p>
<p>The important idea is <strong>specialisation</strong>. Treating AI as one general-purpose developer produced weaker results. Treating it as a team of specialists - one agent, one responsibility; one skill, one purpose; one task, one scope - produced much better ones.</p>
<p>For example, the security agent does not try to develop the application. It performs a loop:</p>
<blockquote>
<p><code>audit → prioritise → ask me → fix one file → re-audit</code></p>
</blockquote>
<p>The re-audit is important. A fix that has not been verified is not a fix. It is a claim.</p>
<p>This changed my mental model and shifted me toward a new development paradigm. Claude Code is not a junior developer. It is closer to <strong>a team of specialised technical roles that I direct, but that never carries responsibility for the final result.</strong></p>
<p>The AI can propose, implement, review and challenge. But the human always decides.</p>
<h2>The adversarial review: move the bugs before the code</h2>
<p>The most valuable tool in my workflow is <code>grill-me</code>, a skill created by <code>Matt Pocock</code>. It is not a code-review tool. It operates <strong>before implementation</strong>.</p>
<p>The idea is simple: <em>Do not ask AI to help you build your design. Ask AI to attack your design</em>.</p>
<p>Instead of "<em>How should I implement this?</em>", the questions become:</p>
<ul>
<li><p>"What did I forget?"</p>
</li>
<li><p>"What happens if this assumption is false?"</p>
</li>
<li><p>"What happens when these two rules interact?"</p>
</li>
<li><p>"What happens to existing data?"</p>
</li>
<li><p>"What happens to a user who already has a value selected?"</p>
</li>
</ul>
<p>The result is that bugs move from production into the design phase. In one sentence:</p>
<blockquote>
<p>It moved some of my bugs from production to the design document.</p>
</blockquote>
<p>And I have concrete examples:</p>
<h3>Bug 1: one number could hide an entire period</h3>
<p>Some context first. The application organises its data into periods, and each period reads its data from a specific year.</p>
<p>The redesign introduced an intentional business decision: the inventory period must read its data from the previous year. So the Inventory 2025 period maps to the year 2024.</p>
<p>At the same time, seven asset routes still carried an older validation rule: <code>minimum: 2025</code>. That rule was correct before the redesign. Nobody thought about it, because nothing about it changed.</p>
<p>Each rule is reasonable on its own. Now follow one user request through both of them:</p>
<ol>
<li><p>The user opens the Inventory period.</p>
</li>
<li><p>The backend translates that period into the year 2024 - as designed.</p>
</li>
<li><p>The request becomes <code>GET /assets/list/2024</code>.</p>
</li>
<li><p>The validation layer rejects it: 2024 is below the minimum of 2025.</p>
</li>
<li><p>The frontend receives <code>400 Bad Request</code>  and shows the period with no assets.</p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/107b55a4-09cd-4176-8eb8-75ac74adfe0d.png" alt="Diagram of the bug in four steps. The frontend: the user opens the Inventory period. The backend mapping: rule A, intentional, makes Inventory 2025 read year 2024. The validation layer: rule B, older, requires 2025 or above on seven asset routes. The API response: GET /assets/list/2024 rejected with 400 Bad Request. The two middle steps are correct alone, the result wrong together, above them the interaction nobody reviewed. One entire period silently missing, with no crash." style="display:block;margin:0 auto" />

<p>The result: one entire period silently missing from the application. Not a crash. Not an exception. Nothing in a log to chase. The screen simply stays empty.</p>
<p>And here is the uncomfortable part: <strong>both rules were correct</strong>. The mapping was an approved business decision. The validation was a sensible guard. The bug existed only in their combination - and nobody reviews "the combination".</p>
<p>The review found the interaction. And the fix was better than changing one number: we moved the year rule into one shared schema used by all 28 routes, so the two rules can never diverge again.</p>
<blockquote>
<p>The problem lived between two correct-looking rules. That is architecture.</p>
</blockquote>
<h3>Bug 2: the half-fix that looks finished</h3>
<p>Another question was about copying organisational data from one year to another.</p>
<p>The migration copied one table. That looked correct. But the actual search query joined two year-scoped tables. If only the first one was copied, the application would start, the tests could pass, the screen would render - and two organisational levels would simply be empty.</p>
<p>This is one of the most dangerous types of bug. Nothing crashes. The application looks healthy. The data is simply wrong.</p>
<p>I call it <strong>the half-fix that looks done</strong>. It was not a syntax problem. It was a system understanding problem.</p>
<h3>Bug 3: the security gap I did not know existed</h3>
<p>The most uncomfortable finding was a security one.</p>
<p>The application can hide some periods from some users. The category routes correctly enforced that visibility rule. The asset routes did not. A hidden period could still return its asset list.</p>
<p>This was not introduced by the redesign. It was already in production. And the review found it while examining a different feature.</p>
<p>The product owner confirmed the routes should not bypass the rule, so we fixed it. But we did something else I consider important: we did not silently absorb the change into the feature. We recorded it as <strong>deliberate scope growth.</strong></p>
<p>AI can find problems. AI cannot decide whether a newly discovered problem should be fixed now, later, or accepted as a risk. <strong>That remains a human decision.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/625675fa6386ed96b050e2ec/6fe61c2b-1c74-4ddf-acd2-ba228875c94a.png" alt="Diagram of the decision after a finding. The AI finds a problem, a bug, a gap or a risk, even one already in production. The human decides, on business impact, risk and priority, knowledge that is not in the code. Three outcomes: fix now, a small scoped task, verified then re-audited; fix later, recorded as deliberate scope growth; or accept as risk, documented with the reason. In every case the decision is recorded, with the date, the reason and the rejected alternatives." style="display:block;margin:0 auto" />

<h2>When the AI was wrong</h2>
<p>This is an important part of the story, because it happened frequently.</p>
<p>LLMs were born from a paper called Attention Is All You Need. Ironically, that is also the best advice for engineers who use them: <strong>attention is all you need</strong>.</p>
<p>Here are four examples I remember well:</p>
<ol>
<li><p><strong>The migration strategy that did not fit:</strong> The AI proposed the classic expand/contract migration strategy for the redesign. A reasonable recommendation, and wrong for this project. The application is deployed as a single artefact; we did not need to support multiple versions during a rolling deployment. The strategy would have added unnecessary complexity. I rejected it.</p>
</li>
<li><p><strong>The internal rule it wanted to make public:</strong> The AI proposed making an internal rule public because it needed access to it. Convenient for the code, but it weakened encapsulation. I rejected that too.</p>
</li>
<li><p><strong>The sort order that looked right:</strong> The AI proposed a DESC sort order. It looked perfectly reasonable. But the existing business behaviour required the opposite order after the new period mapping. Rejected again.</p>
</li>
<li><p><strong>The one-character bug in the audit context:</strong> Before changing data, the application tells PostgreSQL who is acting, so the audit triggers can record it: <code>SELECT set_config('app.changed_by', ?, true)</code></p>
</li>
</ol>
<p>The third parameter decides the scope: <code>true</code> means the value lives only for the current transaction, <code>false</code> means it lives for the whole database session.</p>
<p>The AI proposed <code>false</code>. No explanation. No questions.</p>
<p>An experienced PostgreSQL engineer would see the bug immediately: the application uses a connection pool. A session-scoped value remains attached to the pooled connection after the request ends ,  so the next request, possibly from <strong>another user</strong>, could write audit records under the previous user's name.</p>
<p>Every test would still pass. The audit trail would silently attribute changes to the wrong people. One character, false instead of true, and the audit log becomes a liability.</p>
<hr />
<blockquote>
<p>A good default is not automatically a good decision for your system</p>
</blockquote>
<p>This is why I do not describe AI as an autonomous architect. I describe it as an <strong>architectural proposer</strong>. It can give me several technically valid options, explain the trade-offs, and produce a lot of implementation.</p>
<p>But the missing information is often not in the code. It is in the business, the deployment model, the history of the application, and why an audit log exists.</p>
<blockquote>
<p>That knowledge is the engineer's responsibility.</p>
</blockquote>
<h2>What comes next</h2>
<p>Many real problems, found before implementation, by a machine that was told to attack my assumptions instead of confirming them.</p>
<p>The obvious question is: <em>what kind of workflow makes this repeatable?</em></p>
<p>That is <a href="https://elie29.hashnode.dev/the-living-specification-how-i-keep-ai-written-code-correct">Part 2</a>: the living specification,  why the code is no longer the source of truth, how invariants become the contract, how the three development models compare, and what this changes for every role in the SDLC, from product owner to tech lead.</p>
<p><em>So do not ask whether AI can write your code. Ask whether you would know if it was wrong.</em></p>
<hr />
<h2>Grab the template</h2>
<p>Everything described in this article - a concise <code>CLAUDE.md</code>, focused rule files, skills, specifications, plans and reusable prompts - is available as a public template: <a href="http://github.com/elie29/ai-sample">github.com/elie29/ai-sample</a>. Copy the structure, rewrite the rules for your project, and make it yours.</p>
<hr />
<h2>Let's stay in touch</h2>
<p>I share what I learn about AI-assisted engineering, software architecture and databases. If this article made you rethink your own workflow, follow me on <a href="https://x.com/elie_nehme">X</a> and connect with me on <a href="https://www.linkedin.com/in/elie-nehme/">LinkedIn</a> .  I would like to hear how you work with AI on real projects.</p>
]]></content:encoded></item><item><title><![CDATA[Quand false ne veut rien dire]]></title><description><![CDATA[Découvrez pourquoi retourner un `bool` dans vos méthodes est un anti-pattern et comment améliorer la gestion des erreurs]]></description><link>https://elie29.hashnode.dev/quand-false-ne-veut-rien-dire</link><guid isPermaLink="true">https://elie29.hashnode.dev/quand-false-ne-veut-rien-dire</guid><category><![CDATA[Boolean]]></category><category><![CDATA[anti pattern]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Thu, 18 Dec 2025 09:31:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/K3flzwdifUg/upload/9c1545d9e96d3afaabc0104ccb4df343.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-le-bool-qui-fache">Le <code>bool</code> qui fâche</h1>
<h2 id="heading-les-methodes-ne-doivent-jamais-ou-presque-retourner-bool">Les méthodes ne doivent jamais (ou presque) retourner <code>bool</code></h2>
<p>Quand une fonction peut échouer pour <strong>une ou plusieurs causes</strong>, retourner <code>bool</code> (<code>true/false</code>) fait perdre l'information la plus utile : <strong>le “pourquoi”</strong>.</p>
<ul>
<li><p>L'appelant reçoit <code>false</code> et ne sait pas quoi faire (retry ? message utilisateur ? mapping HTTP ? compensation ?).</p>
</li>
<li><p>"Mais on log l'erreur" disait <em>Peppa Pig</em>! Et bah ça ne règle pas le problème : <strong>les logs ne sont pas une API</strong> (ils peuvent être absents, filtrés, non corrélés, non accessibles, etc.).</p>
</li>
</ul>
<p>L'objectif : <strong>remonter une cause exploitable</strong> (code d'erreur, type d'erreur, contexte), pas juste “KO”.</p>
<hr />
<h2 id="heading-focus-c-historique-patterns">Focus C : historique + patterns</h2>
<h3 id="heading-historique-le-c-navait-pas-de-bool-avant-c99">Historique : le C n'avait pas de <code>bool</code> (avant C99)</h3>
<p>Historiquement, le C (C89/C90) n'avait <strong>pas</strong> de type booléen natif : on utilisait des <code>int</code> avec la convention :</p>
<ul>
<li><p><code>0</code> = faux</p>
</li>
<li><p>non-zéro = vrai</p>
</li>
</ul>
<p>Depuis <strong>C99</strong>, on a <code>&lt;stdbool.h&gt;</code> et <code>bool</code>, mais la culture des API C est restée :<br /><strong>0 = succès, non-zéro = erreur</strong> (souvent négatif), ou <strong>\&gt;= 0 = succès, -1 = erreur</strong> + <code>errno</code>. Sans oublier les pièges que le nouveau type bool a apportés.</p>
<hr />
<h2 id="heading-lanti-pattern-bool">L’anti-pattern : <code>bool</code></h2>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdbool.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">save_user</span><span class="hljs-params">(struct User u)</span> </span>{
    <span class="hljs-keyword">if</span> (!validate(u)) { log_error(<span class="hljs-string">"invalid user"</span>); <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }
    <span class="hljs-keyword">if</span> (!db_connect()) { log_error(<span class="hljs-string">"db down"</span>); <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }
    <span class="hljs-keyword">if</span> (!write_row(u)) { log_error(<span class="hljs-string">"io error"</span>); <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}

<span class="hljs-keyword">if</span> (!save_user(u)) {
    <span class="hljs-comment">// 🤷 L'appelant ne sait pas quoi faire.</span>
    <span class="hljs-comment">// Impossible de distinguer invalid vs conflit vs IO vs timeout...</span>
}
</code></pre>
<h3 id="heading-pourquoi-cest-mauvais">Pourquoi c'est mauvais</h3>
<ul>
<li><p>L'appelant ne peut pas adapter son comportement.</p>
</li>
<li><p>Les tests ne peuvent pas affirmer précisément la cause.</p>
</li>
<li><p>On finit par parser des logs / messages → fragile et non contractuel.</p>
</li>
<li><p>En plus, c'est un anti-pattern avéré (cf. Martin Fowler, Eric Evans, etc.)</p>
</li>
</ul>
<hr />
<h2 id="heading-bon-pattern-en-c-pour-depoussierer-la-memoire-des-plus-vieux">Bon pattern en C (pour dépoussiérer la mémoire des plus vieux)</h2>
<h3 id="heading-convention-simple">Convention simple</h3>
<ul>
<li><p><code>0</code> : succès (<code>OK</code>)</p>
</li>
<li><p><code>&lt; 0</code> : erreurs (codées)</p>
</li>
</ul>
<pre><code class="lang-c"><span class="hljs-comment">// errors.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> OK               0</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> ERR_INVALID     -1</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> ERR_IO          -2</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> ERR_CONFLICT    -3</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> ERR_TIMEOUT     -4</span>
</code></pre>
<pre><code class="lang-c"><span class="hljs-comment">// user_service.c</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"errors.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">save_user</span><span class="hljs-params">(<span class="hljs-keyword">const</span> struct User* u)</span> </span>{
    <span class="hljs-keyword">if</span> (!validate_user(u))   <span class="hljs-keyword">return</span> ERR_INVALID;
    <span class="hljs-keyword">if</span> (email_exists(u-&gt;email)) <span class="hljs-keyword">return</span> ERR_CONFLICT;
    <span class="hljs-keyword">if</span> (!db_connect())       <span class="hljs-keyword">return</span> ERR_IO;
    <span class="hljs-keyword">if</span> (!write_row(u))       <span class="hljs-keyword">return</span> ERR_IO;

    <span class="hljs-keyword">return</span> OK;
}
</code></pre>
<p>Usage simpliste :</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> rc = save_user(&amp;u);
<span class="hljs-keyword">if</span> (rc != OK) {
    <span class="hljs-keyword">switch</span> (rc) {
        <span class="hljs-keyword">case</span> ERR_INVALID:  <span class="hljs-comment">/* message / 400 */</span> <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> ERR_CONFLICT: <span class="hljs-comment">/* 409 */</span> <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> ERR_TIMEOUT:  <span class="hljs-comment">/* retry */</span> <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:           <span class="hljs-comment">/* 500 */</span> <span class="hljs-keyword">break</span>;
    }
}
</code></pre>
<p>✅ L'appelant sait <strong>pourquoi</strong> et peut décider <strong>quoi faire</strong>.</p>
<hr />
<h2 id="heading-variante-c-bitmask-octets-00000001-00000010">Variante C : “bitmask” (octets 00000001, 00000010, …)</h2>
<p>Quand il peut y avoir <strong>plusieurs erreurs en même temps</strong> (ou des statuts cumulables), on peut utiliser des flags. Toujours d'actualité même dans GO.</p>
<p>Exemple en <strong>octet</strong> (<code>uint8_t</code>) :</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdint.h&gt;</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> E_NONE      0x00  <span class="hljs-comment">// 00000000</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> E_INVALID   0x01  <span class="hljs-comment">// 00000001</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> E_IO        0x02  <span class="hljs-comment">// 00000010</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> E_CONFLICT  0x04  <span class="hljs-comment">// 00000100</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> E_TIMEOUT   0x08  <span class="hljs-comment">// 00001000</span></span>

<span class="hljs-function"><span class="hljs-keyword">uint8_t</span> <span class="hljs-title">validate_and_save</span><span class="hljs-params">(<span class="hljs-keyword">const</span> struct User* u)</span> </span>{
    <span class="hljs-keyword">uint8_t</span> err = E_NONE;

    <span class="hljs-keyword">if</span> (!validate_user(u)) err |= E_INVALID;
    <span class="hljs-keyword">if</span> (email_exists(u-&gt;email)) err |= E_CONFLICT;

    <span class="hljs-comment">// On peut choisir d'arrêter tôt, ou continuer pour collecter plusieurs erreurs</span>
    <span class="hljs-keyword">if</span> (err != E_NONE) <span class="hljs-keyword">return</span> err;

    <span class="hljs-keyword">if</span> (!db_connect()) err |= E_IO;
    <span class="hljs-keyword">if</span> (!write_row(u)) err |= E_IO;

    <span class="hljs-keyword">return</span> err;
}
</code></pre>
<p>Usage :</p>
<pre><code class="lang-c"><span class="hljs-keyword">uint8_t</span> err = validate_and_save(&amp;u);
<span class="hljs-keyword">if</span> (err &amp; E_INVALID)  { <span class="hljs-comment">/* ... */</span> }
<span class="hljs-keyword">if</span> (err &amp; E_CONFLICT) { <span class="hljs-comment">/* ... */</span> }
<span class="hljs-keyword">if</span> (err &amp; E_IO)       { <span class="hljs-comment">/* ... */</span> }
</code></pre>
<p>✅ Intéressant si :</p>
<ul>
<li><p>plusieurs états peuvent coexister,</p>
</li>
<li><p>on veut agréger des validations (ex : formulaire).</p>
</li>
</ul>
<p>⚠️ Moins adapté si :</p>
<ul>
<li><p>on a besoin d'un <strong>seul</strong> code précis + contexte riche,</p>
</li>
<li><p>on veut une hiérarchie d'erreurs.</p>
</li>
</ul>
<hr />
<h2 id="heading-autres-styles-au-choix-tant-quon-evite-lanti-pattern">Autres styles (au choix)… tant qu'on évite l'anti-pattern</h2>
<p>Il n'y a pas “un” style universel : l'essentiel est <strong>d'éviter</strong> <code>bool</code> ambigu.</p>
<h3 id="heading-result"><code>Result&lt;T&gt;</code></h3>
<p>On peut se servir du pattern <strong>Result</strong> :</p>
<ul>
<li><p>Success / Failure</p>
</li>
<li><ul>
<li>un <strong>code</strong> d'erreur (enum)</li>
</ul>
</li>
<li><ul>
<li>message + détails</li>
</ul>
</li>
</ul>
<blockquote>
<p>Il existe une bibliothèque populaire, <strong>Ardalis.Result</strong>, qui fournit un <code>Result</code> prêt à l'emploi.</p>
</blockquote>
<p>Exemple minimal :</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> SaveUserError { InvalidInput, Conflict, IoFailure, Timeout }

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> record <span class="hljs-title">Result</span>&lt;<span class="hljs-title">TError</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">bool</span> IsSuccess, TError? Error, <span class="hljs-keyword">string</span>? Message</span>)</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;TError&gt; <span class="hljs-title">Ok</span>(<span class="hljs-params"></span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-literal">true</span>, <span class="hljs-keyword">default</span>, <span class="hljs-literal">null</span>);
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;TError&gt; <span class="hljs-title">Fail</span>(<span class="hljs-params">TError error, <span class="hljs-keyword">string</span>? message = <span class="hljs-literal">null</span></span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-literal">false</span>, error, message);
}
</code></pre>
<p>✅ L'appelant peut faire un mapping propre (HTTP 400/409/500…), afficher un message UX, décider de retry, etc.</p>
<hr />
<h3 id="heading-exception-metier-technique-approche-ddd">Exception métier / technique (Approche DDD)</h3>
<ul>
<li><p>throw new InvalidEmailException(...)</p>
</li>
<li><p>throw new InvalidArgumentException(...)</p>
</li>
</ul>
<p>✅ L'appelant peut distinguer “expected business error” vs “technical error”.</p>
<hr />
<h3 id="heading-enum-ou-constante">Enum ou constante</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> SaveUserError
{
    None = <span class="hljs-number">0</span>,        <span class="hljs-comment">// Succès (équivalent de OK)</span>
    InvalidInput = <span class="hljs-number">1</span>,
    Conflict = <span class="hljs-number">2</span>,
    IoFailure = <span class="hljs-number">3</span>,
    Timeout = <span class="hljs-number">4</span>
}

<span class="hljs-comment">// OU </span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ErrorCodes</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> USER_INVALID  = <span class="hljs-string">"USER_INVALID"</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> USER_CONFLICT = <span class="hljs-string">"USER_CONFLICT"</span>;
}
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<h3 id="heading-regles-simples">Règles simples</h3>
<ul>
<li><p>✅ <code>bool</code> à éviter voire à bannir</p>
</li>
<li><p>✅ <strong>code d'erreur</strong> / <strong>Result</strong> / <strong>error</strong> / <strong>enum</strong> / <strong>bitmask</strong> / ...</p>
</li>
<li><p>✅ Les logs aident le diagnostic, mais <strong>ne remplacent pas</strong> un contrat de retour</p>
</li>
</ul>
<p>Choisissez le style qui vous convient <strong>mais ne choisissez pas l'anti-pattern</strong> !</p>
]]></content:encoded></item><item><title><![CDATA[La CI/CD n’est pas une priorité !]]></title><description><![CDATA[Découvrez comment éviter les pièges courants de la CI/CD et implémenter un processus fiable, sécurisé et optimisé pour vos projets DevOps.]]></description><link>https://elie29.hashnode.dev/la-cicd-nest-pas-une-priorite</link><guid isPermaLink="true">https://elie29.hashnode.dev/la-cicd-nest-pas-une-priorite</guid><category><![CDATA[cicd]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[Devops]]></category><category><![CDATA[automation testing ]]></category><category><![CDATA[Security]]></category><category><![CDATA[deployment]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Wed, 07 May 2025 08:01:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/L4gN0aeaPY4/upload/094bd2a577cbad3902803fe7dff687b0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Dans beaucoup d’équipes et projets que j’ai accompagnés dans leur transformation DevOps, le réflexe et l’initiative de départ étaient de « <strong>mettre en place une CI/CD</strong> ». Apparement, c’est un gage de sérieux, d’industrialisation et de modernité. Mais trop souvent, cette mise en place était prématurée, mal comprise, ou <strong>incomplète</strong>.</p>
<blockquote>
<p>Avant de déployer une CI/CD, il faut <strong>savoir ce que c’est réellement</strong>, et surtout <strong>ce que cela implique</strong>. Car une CI/CD mal conçue peut donner une fausse impression de qualité… tout en laissant passer des bugs, des failles ou des régressions.</p>
</blockquote>
<h2 id="heading-la-cicd-ce-nest-pas-juste-un-script-qui-tourne">La CI/CD, ce n’est pas juste un script qui tourne</h2>
<p>Très souvent, les équipes ont des pipelines avec un lancement manuel ou périodique non orchestrés ni pilotés — Combien de pipelines aujourd’hui voient les tests désactivés ou la qualimétrie suspendue ?</p>
<p>Or, un <strong>vrai pipeline CI/CD</strong> n’est <strong>pas un ensemble d’étapes automatisées qu’on lance manuellement</strong>. Ce n’est pas non plus un job périodique qui tourne la nuit ou toutes les heures.</p>
<p>C’est un processus <strong>qui se déclenche automatiquement</strong> à chaque modification de code, <strong>sensible à la qualité du livrable</strong>, et <strong>capable de stopper la chaîne en cas d’anomalie.</strong></p>
<blockquote>
<p>On ne peut parler de CI/CD que si :</p>
<ul>
<li><p>Le déclenchement et les étapes sont <strong>entièrement automatisés</strong> (push, tag, PR, merge…) ;</p>
</li>
<li><p><strong>Les erreurs bloquent la chaîne</strong> (tests, qualité, sécurité, conformité…) ;</p>
</li>
<li><p>Le déploiement est défini selon une stratégie appropriée (Blue/Green, Canary, Rolling Update, …)</p>
</li>
</ul>
</blockquote>
<p>Un pipeline qui continue malgré des tests qui échouent ou des vulnérabilités connues n’est pas une chaîne CI/CD. <strong>L’automatisation n’est pas qu’un gain de temps : c’est un garde-fou.</strong></p>
<p>💡Il n'est pas nécessaire d'avoir à la fois la CI et la CD pour considérer le travail comme sérieux. Il vaut mieux maîtriser l'une des deux avec un processus fiable et contrôlé, puis construire le reste progressivement.</p>
<h2 id="heading-pourquoi-ne-pas-commencer-par-la-cicd">Pourquoi ne pas commencer par la CI/CD ?</h2>
<p>Si vous lancez une CI/CD sans avoir sécurisé :</p>
<ul>
<li><p>L’<strong>architecture logicielle</strong>,</p>
</li>
<li><p>Le <strong>système de persistance</strong>,</p>
</li>
<li><p>La <strong>qualité</strong> et la <strong>sécurité des livrables</strong>,</p>
</li>
<li><p>Les <strong>stratégies appropriées de livraison et de rollback</strong>,</p>
</li>
</ul>
<p>… vous risquez <strong>d’accélérer</strong> la mise en production des <strong>erreurs</strong> au lieu de la <strong>valeur</strong>.</p>
<p>La mise en place d’une CI/CD suppose que les questions suivantes ont déjà été résolues :</p>
<ul>
<li><p>Comment tester ? (unitaires, intégration, end-to-end, …)</p>
</li>
<li><p>Comment contrôler la qualité ? (lint, coverage, complexité, …)</p>
</li>
<li><p>Comment analyser la sécurité ? (SAST, dépendances, droits d’accès, …)</p>
</li>
<li><p>Quelle stratégie de déploiement adopter ? (blue/green, rolling, feature flag)</p>
</li>
</ul>
<p>Sans avoir des réponses claires à ces questions et les outils appropriés sur place, c’est déployer tout simplement un processus flou sans aucune valeur ajoutée. Surtout que toute mesure de temps de livraison ou de déploiement sera erronée, car le déploiement n’est pas un processus fiable.</p>
<p>⚠️ Une CI/CD qui casse la prod ou qui n’est pas en mesure d’effectuer un retour-arrière est une CI/CD incomplète.</p>
<h2 id="heading-ce-quon-oublie-souvent-le-systeme-de-persistance">Ce qu’on oublie souvent : Le système de persistance</h2>
<p>Le vrai danger de l’automatisation sans contrôle préalable est lié directement au <strong>système de persistance</strong>, souvent irréversible une fois modifié.</p>
<p>👉 Ci-après quelques composants auxquels il faut <strong>penser AVANT</strong> de mettre en œuvre la CI/CD (liste non exhaustive) :</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong><em>Composant</em></strong></td><td><strong><em>Risque en cas de déploiement anarchique</em></strong></td><td><strong><em>Bonne pratique</em></strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Base de données</strong></td><td>Suppression/modification de colonnes, de tables ou de données critiques</td><td>Suppression logique, migrations versionnées, backward compatibility</td></tr>
<tr>
<td><strong>Bus de messages</strong></td><td>Changement de format de message (breaking change)</td><td>Versionner les schémas (ex: Avro), maintenir plusieurs consumers, planifier la cohabitation</td></tr>
<tr>
<td><strong>Fichiers de configuration</strong></td><td>Ajout/suppression de clés sans fallback</td><td>Mettre des valeurs par défaut, gérer les versions de config</td></tr>
<tr>
<td><strong>Stockage fichier (Blob, S3, etc.)</strong></td><td>Écrasement de fichiers, structure non compatible</td><td>Nommer avec hash/version, ne jamais écraser, taguer</td></tr>
<tr>
<td><strong>Index de recherche (Elastic, etc.)</strong></td><td>Perte ou corruption de données d’index</td><td>Rebuild automatique, index en double lors des migrations</td></tr>
<tr>
<td><strong>Modèle de sécurité (RBAC, IAM)</strong></td><td>Révocation ou attribution non désirée de droits</td><td>Tests en environnement sécurisé, audit des droits, rollback possible</td></tr>
</tbody>
</table>
</div><h2 id="heading-ce-quon-rencontre-regulierement-un-seul-pipeline-pour-tout-gerer">Ce qu’on rencontre régulièrement : Un seul pipeline pour tout gérer !</h2>
<p>Un seul pipeline pour déployer les composants applicatifs et d’infrastructure est une très mauvaise pratique. Il est crucial de distinguer deux types de pipelines aux objectifs et temporalités différentes :</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong><em>Type</em></strong></td><td><strong><em>Objectif</em></strong></td><td><strong><em>Déclencheur</em></strong></td><td><strong><em>Contenu principal</em></strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Pipeline applicatif</strong></td><td>Déployer une version de l’application</td><td>Commit, tag, PR</td><td>Tests, build, packaging, déploiement</td></tr>
<tr>
<td><strong>Pipeline d’infrastructure</strong></td><td>Provisionner ou mettre à jour l’infrastructure cible</td><td>Changement d’IaC ou de configuration</td><td>Terraform, Ansible, Helm, séquençage des composants</td></tr>
</tbody>
</table>
</div><p>Les changements applicatifs sont généralement plus fréquents que les changements d'infrastructure. Il est donc recommandé de maintenir des pipelines séparés pour éviter des redéploiements inutiles de l'infrastructure lors de modifications applicatives.</p>
<p>Il est également important de noter que certaines stratégies de déploiement <strong>ne s'appliquent pas</strong> à l'infrastructure ou <strong>ne sont pas</strong> appropriées (Recreate, Feature Toggle, A/B Testing, etc.).</p>
<h2 id="heading-pipeline-dinfrastructure-ordre-code-et-precaution">Pipeline d’infrastructure : ordre, code et précaution</h2>
<p>Le pipeline d'infrastructure repose sur trois principes fondamentaux :</p>
<ol>
<li><p><strong>Infrastructure as Code (IaC)</strong><br /> Utilisez des outils comme Terraform ou Pulumi pour décrire, versionner et auditer l'infrastructure.</p>
</li>
<li><p><strong>Configuration as Code (CaC)</strong><br /> Employez des outils tels qu'Ansible, Helm ou Kustomize pour gérer les paramètres d'environnement, les secrets, les chemins, les limites de mémoire, etc.</p>
</li>
<li><p><strong>Déploiement séquencé et autonome des composants</strong><br /> Déployez les composants dans un ordre logique pour assurer la stabilité et la cohérence du système. Ce déploiement doit être modulaire, où chaque composant est autonome et possède sa propre stratégie (par exemple, un tfState par composant et non par déploiement complet).</p>
</li>
</ol>
<h2 id="heading-le-pipeline-dinfrastructure-un-processus-orchestre-pas-forcement-continu">Le pipeline d’infrastructure : un processus orchestré, pas forcément continu</h2>
<p>Contrairement au pipeline applicatif, qui s’exécute automatiquement à chaque modification de code, <strong>le pipeline d’infrastructure peut (et doit souvent) être soumis à une validation manuelle.</strong></p>
<p>Pourquoi ?</p>
<ul>
<li><p>Les changements d’infrastructure peuvent avoir un <strong>impact large</strong> (pannes, indisponibilité, …).</p>
</li>
<li><p>Ils doivent respecter des <strong>fenêtres de maintenance</strong>, des <strong>procédures de contrôle</strong>, ou une <strong>stratégie de montée en charge</strong>.</p>
</li>
<li><p>Certaines opérations (provisionnement de base de données, modification réseau, montée de version d’un broker Kafka) nécessitent une <strong>validation humaine</strong>.</p>
</li>
</ul>
<p>Enfin, <strong>le rythme de déclenchement dépend de l’environnement</strong> :</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong><em>Environnement</em></strong></td><td><strong><em>Déclenchement</em></strong></td><td><strong><em>Automatique ?</em></strong></td><td><strong><em>Exemple de cadence</em></strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Dev / Sandbox</strong></td><td>À chaque PR</td><td>✅ Oui</td><td>Plusieurs fois par jour</td></tr>
<tr>
<td><strong>Pré-prod</strong></td><td>Après validation</td><td>⚠️ Contrôlé</td><td>1–2 fois par semaine</td></tr>
<tr>
<td><strong>Production</strong></td><td>Fenêtré, validé</td><td>❌ Jamais sans revue</td><td>1–2 fois par mois</td></tr>
</tbody>
</table>
</div><p><strong>Automatiser ne signifie pas abandonner le discernement.</strong> En matière d’infrastructure, <strong>l’automatisation encadre, documente, trace… mais ne remplace pas la responsabilité.</strong> Le pipeline d’infrastructure est donc une <strong>brique stratégique</strong> du SI qui doit rester sous contrôle.</p>
<h2 id="heading-deploiement-pilote-par-strategie">Déploiement piloté par stratégie</h2>
<p>Chaque fonctionnalité ou composant peut nécessiter une stratégie de déploiement spécifique. Un fichier JSON ou YAML permet de définir cela dynamiquement :</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"feature"</span>: <span class="hljs-string">"recommendationV3"</span>,
  <span class="hljs-attr">"strategy"</span>: <span class="hljs-string">"blue-green"</span>,
  <span class="hljs-attr">"rollbackOnError"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"preDeployTests"</span>: [<span class="hljs-string">"load"</span>, <span class="hljs-string">"regression"</span>],
  <span class="hljs-attr">"persistenceSafetyChecks"</span>: {
    <span class="hljs-attr">"dbMigrationIdempotent"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"messageSchemaBackwardCompatible"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"configFallback"</span>: <span class="hljs-literal">true</span>
  }
}
</code></pre>
<p>Ce type de configuration permet d'adapter le déploiement aux spécificités de chaque projet au niveau de chaque commit, tout en assurant des garde-fous pour préserver la stabilité du système.</p>
<p>La CI/CD doit être en mesure de choisir une stratégie de déploiement adaptée à la fonctionnalité ou au contexte en s’appuyant sur un répertoire dédié à la configuration.</p>
<h3 id="heading-un-apercu-des-differentes-strategies-de-deploiement">Un aperçu des différentes stratégies de déploiement :</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong><em>Stratégie</em></strong></td><td><strong><em>Objectif principal</em></strong></td><td><strong><em>Reprise facile</em></strong></td></tr>
</thead>
<tbody>
<tr>
<td><em>💥</em> Recreate</td><td>Remplacement complet d’une version existante. Adapté à des services simples ou internes.</td><td>🔥🔥🔥🔥</td></tr>
<tr>
<td><em>🔄</em> Rolling Update</td><td>Mise à jour progressive sans interruption. Courant dans les systèmes conteneurisés.</td><td>🔥🔥</td></tr>
<tr>
<td><em>🟦🟩</em> Blue/Green</td><td>Maintien de deux environnements complets avec bascule rapide. Retour arrière instantané.</td><td>🔥</td></tr>
<tr>
<td><em>🎚️</em> Feature Toggle</td><td>Activation conditionnelle d’une fonctionnalité. Permet le test en production sécurisé.</td><td>🔥</td></tr>
<tr>
<td><em>🐤</em> Canary</td><td>Déploiement progressif sur un sous-ensemble d’utilisateurs. Observation du comportement.</td><td>🔥🔥</td></tr>
<tr>
<td><em>🧪</em> A/B Testing</td><td>Comparaison de deux variantes auprès d’utilisateurs pour évaluer un KPI métier.</td><td>🔥🔥</td></tr>
<tr>
<td><em>👥</em> Shadow Release</td><td>Déploiement invisible à l’utilisateur pour tester la charge, la compatibilité, etc.</td><td>🔥</td></tr>
</tbody>
</table>
</div><p>Chaque stratégie de déploiement présente des avantages et des limites. Le choix de l’approche la plus pertinente dépend des besoins spécifiques du projet, de la complexité des évolutions à livrer, ainsi que du niveau de tolérance aux interruptions de service.</p>
<p>Il revient à l’équipe d’évaluer <strong>l’ensemble des critères</strong> (impact utilisateur, coût, complexité, …) afin d’adopter la méthode de déploiement la mieux adaptée à leur contexte technique, métier et organisationnel.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Mettre en place une CI/CD, ce n’est pas simplement cocher une case. C’est établir un cadre d’exécution <strong>fiable</strong>, <strong>traçable</strong> et <strong>sécurisé</strong>, garantissant la qualité des livraisons et assurant la continuité du service.</p>
<p>La CI/CD doit être une <strong>démarche progressive</strong>, adaptée à chaque projet. Cependant, pour maximiser son efficacité, elle doit s’appuyer sur des outils communs, des bonnes pratiques et des standards organisationnels bien définis. En respectant ces standards, on assure non seulement la cohérence et la stabilité du processus, mais aussi la sécurité et la conformité de l’ensemble des livrables à long terme.</p>
<hr />
<p><strong>Merci pour votre lecture !</strong><br />Si vous avez apprécié cet article, n’hésitez pas à me suivre sur <a target="_blank" href="https://www.linkedin.com/in/elie-nehme/">LinkedIn</a> pour découvrir mes prochaines publications.<br />Une remarque ou une suggestion ? Laissez un commentaire ci-dessous — j’y répondrai avec plaisir 👌</p>
]]></content:encoded></item><item><title><![CDATA[Justifier le Craftsmanship auprès des DSI : ROI, contexte et impact réel]]></title><description><![CDATA[Découvrez comment démontrer le ROI des bonnes pratiques de développement logiciel auprès des DSI avec une approche stratégique et contextualisée.]]></description><link>https://elie29.hashnode.dev/justifier-le-craftsmanship-aupres-des-dsi-roi-contexte-et-impact-reel</link><guid isPermaLink="true">https://elie29.hashnode.dev/justifier-le-craftsmanship-aupres-des-dsi-roi-contexte-et-impact-reel</guid><category><![CDATA[craftsmanship]]></category><category><![CDATA[ROI (Return on Investment)]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[leadership]]></category><category><![CDATA[technical-debt]]></category><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Thu, 01 May 2025 22:37:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746138191044/cfd42899-c963-4fc5-8c0c-78c1db962277.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Mettre en place des bonnes pratiques ne suffit pas. Encore faut-il qu’elles répondent à un besoin métier clair et qu’on sache démontrer leur valeur. Voici comment articuler ROI, excellence technique et pilotage stratégique.</p>
<p>Un CTO m’a expliqué qu’il avait déployé à l’échelle des outils comme Sonar et GitLab, avec un coût non négligeable. Pourtant, il se retrouve dans l’incapacité de démontrer à la direction ni l’utilité de son travail, ni le retour sur investissement. Un autre directeur technique m’a détaillé la mise en place du <em>pair programming</em> et des revues de code, et rencontrait exactement la même difficulté pour prouver l'efficacité de sa "bonne volonté". J’ai même été confronté à un DSI qui ne connaissait ni les objectifs ni les enjeux de son chantier DevOps.</p>
<p><strong>Bref.</strong></p>
<p>J’ai l’habitude de déployer à l’échelle le Craftsmanship et le DevOps en m’appuyant sur la méthode 4S que j’ai élaborée — je la détaillerai dans un autre billet. Dans cet article, je souhaite me concentrer sur les <strong>bénéfices des bonnes pratiques de développement</strong>, et plus précisément de <strong>l’excellence technique</strong>.</p>
<h2 id="heading-toute-bonne-pratique-hors-contexte-devient-une-mauvaise-pratique">Toute bonne pratique hors contexte devient une mauvaise pratique</h2>
<p>Avant de se demander <strong>comment</strong> déployer une pratique ou <strong>comment</strong> justifier son ROI, il faut revenir à l’essentiel : LE <strong>Pourquoi ?</strong><br />Quel est le problème que l’on cherche à résoudre ?</p>
<p>Expliquer à la direction ce qu’est la complexité cyclomatique, ou que nous avons amélioré une méthode en O(n²) à O(n), n’a que peu d’impact. Ce type d’argument, bien qu’il soit pertinent techniquement, n’apporte aucune valeur métier aux yeux d’un décideur ou à la direction.</p>
<p>Il faut donc deux niveaux de mesure :</p>
<ul>
<li><p><strong>Une approche tactique</strong>, orientée équipe, qui se base sur des indicateurs opérationnels.</p>
</li>
<li><p><strong>Une approche stratégique</strong>, orientée “<em>management</em>”, qui expose des indicateurs de performance et de création de valeur.</p>
</li>
</ul>
<hr />
<h3 id="heading-connaitre-son-perimetre-ses-forces-et-ses-faiblesses">Connaître son périmètre, ses forces et ses faiblesses</h3>
<p>Toutes les pratiques ne sont pas appropriées partout et pour tous les contextes. Une équipe qui maintient des projets en TMA (<em>Tierce Maintenance Applicative</em>) n’a pas forcément besoin de TDD. Du <em>clean code</em>, bien appliqué, peut suffire largement. L’effort doit être ciblé selon les contraintes réelles du projet.</p>
<p>Parfois, la question n’est pas uniquement de mettre en place des bonnes pratiques de développement, mais de <strong>refondre tout ou partie du système</strong>.<br />Quand les équipes souffrent, que la dette technique est massive, il peut être plus judicieux de <strong>décommissionner progressivement les fonctionnalités critiques</strong> pour repartir sur des bases saines — données comprises.</p>
<h2 id="heading-lingenierie-logicielle-est-au-service-du-metier-pas-linverse">L’ingénierie logicielle est au service du métier, pas l’inverse</h2>
<p>Les technologies et les pratiques doivent répondre aux besoins métier. Chaque cas d’usage mérite sa propre architecture, sa propre solution, sa propre conception.</p>
<p>Standardiser ne signifie pas <strong>uniformiser à outrance</strong>.</p>
<p>Trop souvent, des dirigeants pensent qu’industrialiser ou standardiser des pratiques au sein d’une usine logicielle revient à imposer <strong>une seule technique</strong>, <strong>un seul outillage</strong>, <strong>une seule organisation</strong> pour l’ensemble des projets. C’est une erreur fatale !!!</p>
<p>Pourtant une simple matrice des cas d’usage (par complexité, niveau de compétence requis, courbe d’apprentissage, criticité métier, etc.) constitue <strong>un bon levier d’évaluation et de choix</strong> pour chaque contexte.</p>
<h2 id="heading-en-conclusion">En conclusion</h2>
<p>Le Craftsmanship ou l’excellence technique ne se vend pas avec des outils ou des dogmes. Il se <strong>justifie par les problèmes qu’il résout</strong> et <strong>la valeur qu’il permet de produire durablement</strong>.</p>
<p>Le ROI n’est pas dans les bonnes pratiques (le TDD, Sonar ou GitLab), mais dans ce que ces pratiques rendent possible : un logiciel plus fiable, une équipe plus autonome, une vélocité plus prévisible, et in fine, <strong>un métier mieux servi</strong>.</p>
<hr />
<p><strong>Merci pour votre lecture !</strong><br />Si vous avez apprécié cet article, n’hésitez pas à me suivre sur <a target="_blank" href="https://www.linkedin.com/in/elie-nehme/">LinkedIn</a> pour découvrir mes prochaines publications.<br />Une remarque ou une suggestion ? Laissez un commentaire ci-dessous — j’y répondrai avec plaisir 👌</p>
]]></content:encoded></item><item><title><![CDATA[Building a Resilient Site-Aware Synchronization]]></title><description><![CDATA[Building a Resilient Multi-Site Synchronization Architecture with RabbitMQ and the Outbox Pattern to ensure idempotency, scalability, and replayability.]]></description><link>https://elie29.hashnode.dev/building-a-resilient-site-aware-synchronization</link><guid isPermaLink="true">https://elie29.hashnode.dev/building-a-resilient-site-aware-synchronization</guid><category><![CDATA[rabbitmq]]></category><category><![CDATA[Resilience]]></category><category><![CDATA[outbox pattern]]></category><category><![CDATA[idempotence]]></category><category><![CDATA[event-driven-architecture]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Mon, 14 Apr 2025 21:29:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/VviFtDJakYk/upload/fbc5c58194ad3ee3b72fc3e37bc74041.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-the-challenge-of-multi-site-data-autonomy">The Challenge of Multi-Site Data Autonomy</h2>
<p>In distributed environments, especially in industrial or regulated contexts, applications are often deployed across multiple geographically separated sites. These sites must remain fully operational even in the event of a network outage lasting several days.</p>
<h3 id="heading-what-the-heck-is-the-challenge"><em>What the heck is the challenge?</em></h3>
<p>Ensuring local application <strong>autonomy</strong>, while maintaining <strong>data consistency</strong> and <strong>eventual synchronization</strong> across all different sites.</p>
<h2 id="heading-a-hybrid-on-prem-multi-db-ecosystem">A Hybrid, On-Prem, Multi-DB Ecosystem</h2>
<p>In our case, we manage <strong>several on-premise sites</strong>, each with its own local database. Some use <strong>PostgreSQL</strong>, others <strong>Oracle</strong>. A cloud-native solution wasn't viable due to strict network constraints, and we needed every site to operate independently without relying on real-time connectivity.</p>
<h2 id="heading-classic-replication-vs-resilient-architecture">Classic Replication vs Resilient Architecture</h2>
<p>I explored traditional database replication methods, including cross-database replication tools like GoldenGate or SymmetricDS. These tools inevitably introduce operational complexity. Moreover, synchronization conflicts must be addressed regardless.</p>
<p>Instead, I chose to design a resilient, event-driven architecture based on asynchronous communication and eventual consistency, with near real-time propagation when neither conflicts nor network failures are present.</p>
<h2 id="heading-event-driven-site-aware-synchronization">Event-Driven, Site-Aware Synchronization</h2>
<p>I designed an architecture that combines the <strong>Outbox Pattern</strong>, a <strong>RabbitMQ cluster</strong> with 3 nodes, and an <strong>event fanout strategy</strong> to broadcast the event to all sites. Each site manages its own data and produces events locally.</p>
<h3 id="heading-key-concepts">Key Concepts:</h3>
<ul>
<li><p><strong>Outbox Pattern:</strong> Events are stored in a dedicated table in the local DB in the same local transaction.</p>
</li>
<li><p><strong>RabbitMQ Cluster:</strong> Three brokers deployed in a logical grouping with <strong>quorum queues</strong> to ensure reliability across nodes.</p>
</li>
<li><p><strong>Fanout Mode:</strong> Events are broadcast to all consumers, including the originating site.</p>
</li>
<li><p><strong>Deduplication:</strong> Each event has a globally unique identifier <code>id</code> to support idempotent processing.</p>
</li>
<li><p><strong>Historization:</strong> A dedicated queue that receives all events to be stored in the reference site's database for auditing and replay purposes.</p>
</li>
</ul>
<h2 id="heading-architecture-overview">Architecture Overview</h2>
<h3 id="heading-event-propagation-flow-london-as-propagator-paris-as-golden-source">Event Propagation Flow – London as Propagator, Paris as Golden Source</h3>
<p>Below is a simple Event Propagation Flow Design involving three sites. In this setup, <strong>London acts as the Propagator,</strong> while <strong>Paris,</strong> which also <em>processes events</em>, serves as the <em>Golden Source</em> responsible for archiving all events. This architecture deploys an <strong>eventual consistency model</strong> and <strong>does not include automatic conflict resolution</strong>.<br />In case of a conflict, <strong>events are routed to a Dead Letter Queue (DLQ)</strong> for manual inspection and processing.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744704092045/9dc639a2-7de3-4202-b14c-44dde09735b7.png" alt="Diagram illustrating an event-driven architecture for user data propagation. An admin adds a user via the London API, which saves the data to the London DB. London Producer reads events periodically and sends them to a fanout exchange. The events are then distributed to multiple sites: London, Madrid, Paris, and Paris historical. Consumer apps for each site process and update their respective databases. Some events are ignored if not relevant to the destination site. The process includes steps for data confirmation and event deletion." class="image--center mx-auto" /></p>
<h2 id="heading-principal-actors">Principal Actors</h2>
<ol>
<li><p><strong>Local Write:</strong> The application (API) writes to the local database and inserts a new event with a unique ID into the outbox table within the same transaction.</p>
</li>
<li><p><strong>Outbox Dispatcher:</strong> A background service reads events from the outbox table and publishes them to a RabbitMQ fanout exchange.</p>
</li>
<li><p><strong>Fanout Exchange:</strong> Broadcasts the event to all sites.</p>
</li>
<li><p><strong>Event Handling Consumer:</strong> Each site checks whether it has already processed the event (using the unique ID). If not, it applies the corresponding change to its local database.</p>
</li>
<li><p><strong>Self-Cleanup:</strong> The originating site deletes the event from its outbox table once it has been successfully consumed from its queue, confirming that the event was propagated correctly.</p>
</li>
<li><p><strong>Historization:</strong> The event is also sent to the <code>SITE_PARIS_HISTO</code> queue and stored in the Paris database for auditing and replay.</p>
</li>
<li><p><strong>Retention:</strong> A scheduled task deletes historical events older than 90 days (configurable via application settings).</p>
</li>
</ol>
<h2 id="heading-event-payload-structure">Event Payload Structure</h2>
<p>Each event includes a fixed first-level structure:</p>
<ul>
<li><p><strong>id:</strong> A unique identifier for the event, composed of the site name followed by a UUID (e.g., <em>London_9f8a4c2e-3b1d-4a6b-91d9-df4b2e6e8a7f</em>)</p>
</li>
<li><p><strong>timestamp:</strong> The date and time when the event was created.</p>
</li>
<li><p><strong>origin:</strong> The <strong>originating</strong> site name (i.e., the propagating site).</p>
</li>
<li><p><strong>type:</strong> A unique event name, such as <code>User_Added</code>, <code>Dinner_Reserved</code>, etc.</p>
</li>
<li><p><strong>data:</strong> The payload containing the event-specific information.</p>
</li>
</ul>
<h2 id="heading-key-design-choices">Key Design Choices</h2>
<ul>
<li><p><strong>Decentralized event production</strong>: Any site can produce events.</p>
</li>
<li><p><strong>Resilience first:</strong> The system tolerates network outages thanks to the outbox pattern.</p>
</li>
<li><p><strong>Replayability:</strong> Events stored in the Paris archive can be replayed to recover a site.</p>
</li>
<li><p><strong>Scalability:</strong> New sites can be added with minimal configuration.</p>
</li>
<li><p><strong>Idempotency:</strong> Guaranteed through the use of globally unique event IDs.</p>
</li>
</ul>
<h2 id="heading-advanced-option-confirmed-event-processing">Advanced Option – Confirmed Event Processing</h2>
<p>To further secure event handling, I introduced a <strong>confirmation event</strong> handler. Each site sends a confirmation after successfully processing its event. These confirmation events follow the same structure as the original business events:</p>
<ul>
<li><p><strong>id:</strong> A unique identifier for the confirmation event.</p>
</li>
<li><p><strong>timestamp:</strong> The date and time when the event was created.</p>
</li>
<li><p><strong>origin:</strong> The name of the <strong>consuming</strong> site (<em>not the propagator</em>).</p>
</li>
<li><p><strong>type:</strong> A prefix like <code>Confirmation_</code> followed by the original event type (e.g., <code>Confirmation_User_Added</code>).</p>
</li>
<li><p><strong>data:</strong> Specific details of the confirmation event.</p>
</li>
</ul>
<p>The confirmation event is propagated through a <strong>topic exchange</strong> to ensure it is delivered both to the <strong>original propagator</strong> and to the <strong>historization site</strong> (<code>SITE_PARIS_HISTO</code>).</p>
<p>This enables:</p>
<ul>
<li><p><strong>Reliable</strong> <strong>replay detection</strong> (without reprocessing).</p>
</li>
<li><p><strong>Auditing</strong> of which site processed which event and when.</p>
</li>
<li><p>Easier <strong>debugging</strong> in multi-step processing chains.</p>
</li>
</ul>
<p>This confirmation layer complements idempotency and ensures clarity in multi-site data flow.</p>
<h2 id="heading-clustering-federation-or-shovel">Clustering, Federation, or Shovel?</h2>
<p>When building a resilient, site-aware RabbitMQ architecture, one common trap is to pick the wrong mechanism for interconnecting brokers — often without fully considering business needs and constraints. <strong>Clustering</strong>, <strong>Federation</strong>, and <strong>Shovel</strong> each solve very different problems—understanding when to use which can make or break your system’s reliability.</p>
<p>Here’s a quick overview to guide your choice:</p>
<ul>
<li><h3 id="heading-clustering-for-local-resilience">Clustering – For Local Resilience</h3>
<p>  RabbitMQ clustering links multiple nodes into a single logical broker. Nodes share queues and state (with quorum queues), making it a good fit for <strong>high availability within a single site or region</strong>. It ensures a failover mechanism between nodes with minimal delay.</p>
</li>
<li><h3 id="heading-federation-for-loose-selective-links">Federation – For Loose, Selective Links</h3>
<p>  Federation connects <strong>independent brokers</strong>, pulling messages from upstream exchanges into downstream exchanges. It’s useful when you want <strong>loose coupling</strong> across sites, and only care about replicating certain queues. However, <strong>federation doesn’t preserve</strong> ordering or offer guaranteed delivery in all failure scenarios.</p>
</li>
<li><h3 id="heading-shovel-for-reliable-directed-transfer">Shovel – For Reliable, Directed Transfer</h3>
<p>  Shovel is a purpose-built plugin that <strong>relays messages from a queue in one broker to an exchange or queue in another one</strong>. However, Shovel is heavier operationally and doesn’t mirror broker behavior—it moves messages as-is.</p>
</li>
</ul>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>In distributed multi-site environments, ensuring data autonomy and consistency — especially during network disruptions — is essential. A resilient, event-driven architecture based on the <strong>Outbox Pattern</strong>, <strong>RabbitMQ Cluster</strong>, and <strong>eventual consistency</strong> offers a robust foundation for synchronizing data without sacrificing local control.</p>
<p>With features like <strong>decentralized event production</strong>, <strong>idempotency</strong>, <strong>scalability</strong>, and <strong>replayability</strong>, this approach enables reliable and maintainable cross-site communication, even in the face of failure.</p>
<h2 id="heading-try-it-yourself">Try It Yourself</h2>
<p>I have created a <a target="_blank" href="https://github.com/elie29/rabbitmq-cluster-multi-site">GitHub repository</a> that includes:</p>
<ul>
<li><p>A simple flow diagram that illustrates the architecture</p>
</li>
<li><p>A Docker Compose setup to launch a RabbitMQ Cluster with 3 nodes behind an HAProxy</p>
</li>
<li><p>A README file with detailed instructions about the whole setup</p>
</li>
</ul>
<p>Feel free to fork the repository, run the setup locally, and customize it to fit your needs.</p>
<hr />
<p><strong>Thanks for reading!</strong><br />If you enjoyed this post, follow me on <a target="_blank" href="https://x.com/elie_nehme">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/elie-nehme/">LinkedIn</a> for more. Got feedback or suggestions? Drop a comment below—I’d love to hear from you 👌</p>
]]></content:encoded></item><item><title><![CDATA[Stratégie de déploiement Blue/Green]]></title><description><![CDATA[Dans la littérature beaucoup d’articles qui mettent en avant la définition du Blue/Green ou expliquent d’une manière très succincte le déploiement]]></description><link>https://elie29.hashnode.dev/strategie-de-deploiement-bluegreen</link><guid isPermaLink="true">https://elie29.hashnode.dev/strategie-de-deploiement-bluegreen</guid><category><![CDATA[Blue/Green deployment]]></category><category><![CDATA[continuous deployment]]></category><category><![CDATA[bonnes pratiques]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Sun, 27 Aug 2023 15:57:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693144357199/5723d327-16f3-4537-9b07-42d03c55882f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Nous trouvons dans la littérature beaucoup d'articles qui mettent en avant la définition du Blue/Green ou qui expliquent d'une manière très succincte l'implémentation d'un service « hello world » déconnectée de la réalité du terrain. L'objectif de cet article est de mettre en évidence les éléments à identifier pour réussir efficacement cette stratégie.</p>
<p>Mais avant de rentrer dans le vif du sujet, reprenons une définition type du mode Blue/Green :</p>
<blockquote>
<p>Le déploiement blue/green stipule que la version B (green) est déployée à côté de la version A (blue) avec le même nombre d'instances. Après avoir <strong>testé</strong> que la version B <strong>répond à toutes les exigences</strong>, le trafic est basculé de la version A vers la version B.</p>
</blockquote>
<p><em>N.B. : Que veut dire « répondre à toutes les exigences » ? Je reviendrai sur cette hypothèse plus bas.</em></p>
<p>Il est certain que l'objectif du B/G est d'assurer une continuité de service, cependant, toutes les stratégies de déploiement, hormis le « recreate », garantissent cette continuité. Dans cet article, je ne vais pas donner le détail de toutes les stratégies ni leurs cas d'utilisation que j'aborderai ultérieurement dans un autre billet.</p>
<p>La clé de réussite réside dans la collaboration et l'implication de toute l'équipe : métier, dev et ops. Cette équipe doit d'abord se pencher sur la conception d'un tel déploiement afin de définir un processus complet répondant à leurs attentes.</p>
<hr />
<p>Ci-après quelques points majeurs à aborder par l'équipe pour établir une démarche viable autour du B/G :</p>
<h2 id="heading-perimetre-du-bg">Périmètre du B/G</h2>
<p>Prenons l'exemple d'une application regroupant plusieurs composants : Répartiteurs de charge, base de données, cache, stockage de fichier, frontend et backend. L'équipe ne doit pas traiter ces composants dans un même et unique pipeline sous aucun prétexte.</p>
<p>Il est vrai que la définition évoque « <em>le même nombre d'instances</em> » et peut porter à confusion. Cependant, ce nombre d'instances est lié à la version d'un composant et non pas à la totalité des composants ni à l'environnement dans sa globalité.</p>
<blockquote>
<p><strong>N.B. :</strong> <em>Ne pas confondre composant et instances de composant. Si un composant est déployé en plusieurs instances, le pipeline doit impacter toutes les instances de ce même composant.</em></p>
</blockquote>
<p>Le fait de dupliquer la totalité de l'environnement mène à une complexité ingérable voire à une désynchronisation des données et forcément à une interruption de service. En conséquence, c'est un <strong>anti-pattern</strong> de mélanger les concepts dans un même pipeline et il est fortement recommandé de fuire cette mauvaise pratique.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Faut-il dupliquer le cluster <em>Kubernetes</em> pour mettre en place cette stratégie de déploiement ? A cette question, la réponse est de toute évidence NON ; <strong>c'est une approche totalement rédhibitoire.</strong></div>
</div>

<p>Par ailleurs, certains composants n'exigent pas du tout ce type de stratégie. Par exemple, la mise à jour du frontend ne requiert pas du B/G et n'implique pas une migration de base de données non plus. Idem pour le backend, qui nécessite une mise à jour potentielle du schéma mais en aucun cas, une migration de base de données (<em>passage de PostgreSQL v12 à v14</em>). Donc il est inutile de mélanger les topologies dans un même pipeline. Cela s'applique également à toutes les stratégies et non uniquement au B/G.</p>
<p>Opter pour un pipeline par topologie facilite grandement la mise en place et le déploiement. Ainsi, l'équipe peut adopter la bonne stratégie de déploiement pour chaque composant. <em>Exemple, un pipeline pour la migration de base de données en mode B/G ou RollingUpdate et un autre pour le backend en mode Canary</em>.</p>
<h2 id="heading-phase-initiale-vs-phase-de-mise-a-jour">Phase initiale vs Phase de mise à jour</h2>
<p>Est-ce qu'il faut un seul pipeline pour les deux phases ? L'équipe doit prendre une décision qui dépend fortement des outils mis à disposition et de la technologie utilisée.</p>
<p>Il est indispensable de pouvoir distinguer facilement entre les environnements ou les namespaces. Tout dépend si le déploiement est en mode VM ou Conteneurisé par exemple.</p>
<p>De plus, Il faut pouvoir détecter l'existence ou non d'un déploiement préalable et de trouver le moyen facile de mettre à jour le statut final à la fin de l'exécution du pipeline.</p>
<p><em>Sur un projet, je me basais sur les adresses de mes machines dans la configuration de mon HAProxy - haproxy.cfg - afin de détecter les serveurs applicatifs; sur un autre projet, un simple fichier YAML regroupait les informations utiles au déploiement.</em></p>
<h2 id="heading-retrocompatibilite-du-systeme-de-persistance">Rétrocompatibilité du système de persistance</h2>
<p>Un élément très important, sans lequel aucune stratégie ne peut réussir, concerne le système de persistance : schéma de base de données, structure de fichiers, gestion des propriétés ou structure des bus événementiels (topics)...</p>
<p>Tout changement modifiant la structure des données mettra en péril le retour arrière en cas d'erreur; l'ancienne version n'étant plus compatible avec la nouvelle version. D'où la nécessité de définir un processus de rétrocompatibilité détaillant la gestion de suppression et/ou de modification de la structure en question.</p>
<p><em>En cas de suppression, par exemple, l'équipe optera pour une suppression logique impliquant uniquement le code de la nouvelle version, puis une suppression physique quelques versions plus tard.</em></p>
<p>Le métier et les devs doivent respecter minutieusement ce processus, et c'est pour cette raison, j'insiste toujours sur l'utilité de la collaboration entre le métier, les devs et les ops.</p>
<h2 id="heading-gestion-des-sessions">Gestion des sessions</h2>
<p>L'objectif d'une stratégie de déploiement est la continuité de service, par conséquent, la bascule d'une version vers une autre ne doit pas entraîner la déconnexion des utilisateurs.</p>
<p>D'où la nécessité de sauvegarder la session ou les informations de connexion de manière transparente et indépendante qui n'impactera pas les utilisateurs en cas de bascule.</p>
<p><em>Par exemple, les données de session peuvent être stockées dans un cache type redis ou dans une base de données.</em></p>
<h2 id="heading-decommissionner-lenvironnement-blue">Décommissionner l'environnement Blue</h2>
<p>L'équipe doit décider à quel moment l'ancienne version (blue) est à supprimer et surtout comment y procéder. Le fait que la définition évoque la validation des exigences, il est convenable de les définir et de décider quel moyen et/ou quel outil utiliser pour les valider.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Le décommissionnement peut être fait <strong>automatiquement</strong> à la fin de la recette métier, <strong>manuellement</strong> en cliquant sur un bouton, <strong>par événement</strong> à la clôture d'un ticket ou <strong>après un temps</strong> défini qui mettra un terme au pipeline, etc...</div>
</div>

<p>Une fois le décommissionnement est terminé, la version Green deviendra alors la version Blue et le retour arrière vers l'ancienne version ne sera plus possible que par le lancement d'un nouveau déploiement.</p>
<blockquote>
<p>A noter que la plupart des projets ne possèdent pas une couverture de tests fonctionnels suffisante et dans la plupart du temps, les recettes métiers sont manuelles. Par conséquent, les Ops ne peuvent pas prendre cette décision de manière unilatérale.</p>
</blockquote>
<h2 id="heading-retour-arriere-en-cas-derreur">Retour arrière en cas d'erreur</h2>
<p>Le retour arrière en cas d'erreur, en rebasculant le trafic vers la version A, n'est possible que si les deux environnements sont toujours actifs.</p>
<p>L'équipe doit préciser la manière de décommissionner le Green pour rebasculer vers le Blue, le temps d'apporter une correction ou une amélioration de la nouvelle version.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Le retour arrière peut être fait <strong>automatiquement</strong> à la détection d'une erreur, <strong>manuellement</strong> en cliquant sur un bouton, <strong>par événement</strong> à l'échec de la recette métier ou <strong>après un temps</strong> de non confirmation de la fin du pipeline, etc...</div>
</div>

<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>Cette liste non exhaustive des points à élucider avant d'entamer l'écriture d'un pipeline est primordiale voire obligatoire. Sans oublier l'étroite collaboration entre le métier, les devs et les ops pour définir les exigences attendues et évaluer la nécessité d'un Blue/Green et ce, composant par composant selon leur contexte et leur topologie.</p>
]]></content:encoded></item><item><title><![CDATA[Java functional programming to leverage polymorphism]]></title><description><![CDATA[How to replace a switch and reduce complexity?]]></description><link>https://elie29.hashnode.dev/java-functional-programming-to-leverage-polymorphism</link><guid isPermaLink="true">https://elie29.hashnode.dev/java-functional-programming-to-leverage-polymorphism</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[lambda]]></category><category><![CDATA[refactoring]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Elie Nehmé]]></dc:creator><pubDate>Wed, 13 Apr 2022 10:03:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/TYnHpsuAkBg/upload/v1649833691060/MK3u151t2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introducing-the-factory">Introducing the factory</h1>
<p>Let's consider a factory method that creates a profile based on some user input as follows:</p>
<pre><code class="lang-JAVA"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Profile <span class="hljs-title">create</span><span class="hljs-params">(String profile)</span> </span>{
  <span class="hljs-keyword">switch</span> (profile) {
  <span class="hljs-keyword">case</span> ADMIN:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Admin();
  <span class="hljs-keyword">case</span> HR:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Hr();
  <span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Anonymous();
  }
}
</code></pre>
<blockquote>
<p>In the default statement, we could throw an exception, however, in this example I decided to return a value.</p>
</blockquote>
<p>Although the <em>create method</em> is very simple, each time we introduce a new profile we should add a new statement and a new complexity to the class:</p>
<pre><code class="lang-JAVA"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Profile <span class="hljs-title">create</span><span class="hljs-params">(String profile)</span> </span>{
  <span class="hljs-keyword">switch</span> (profile) {
  <span class="hljs-keyword">case</span> ADMIN:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Admin();
  <span class="hljs-keyword">case</span> HR:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Hr();
  <span class="hljs-keyword">case</span> HRD:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Hrd();
  <span class="hljs-keyword">case</span> VALIDATOR:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Validator();
  <span class="hljs-keyword">case</span> READER:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Reader();
  <span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Anonymous();
  }
}
</code></pre>
<h2 id="heading-lambda-and-hashmap-to-the-rescue">Lambda and HashMap to the rescue</h2>
<p>Instead of using a switch case to find out which class we need to instantiate, we can take full advantage of HashMap and Functional Interfaces; in our previous case, the <strong>Supplier Interface</strong>:</p>
<p><em>Since Java 9, we can use Map.of</em></p>
<pre><code class="lang-JAVA"><span class="hljs-keyword">static</span> Map&lt;String, Supplier&lt;Profile&gt;&gt; profiles = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

<span class="hljs-keyword">static</span> {
  profiles.put(ADMIN, Admin::<span class="hljs-keyword">new</span>);
  profiles.put(HR, Hr::<span class="hljs-keyword">new</span>);
  profiles.put(HRD, Hrd::<span class="hljs-keyword">new</span>);
  profiles.put(VALIDATOR, Validator::<span class="hljs-keyword">new</span>);
  profiles.put(READER, Reader::<span class="hljs-keyword">new</span>);
}
</code></pre>
<p>Therefore, our factory method is reduced to verifying the key or creating the anonymous profile:</p>
<pre><code class="lang-JAVA"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Profile <span class="hljs-title">create</span><span class="hljs-params">(String profile)</span> </span>{
  <span class="hljs-keyword">if</span> (profiles.containsKey(profile)) {
    <span class="hljs-keyword">return</span> profiles.get(profile).get();
  }
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Anonymous();
}
</code></pre>
<p>The complexity now is steady stable and won't be affected by adding or removing profiles.</p>
<p>Moreover, we can use <em>Function Interface</em> or apply a specific <em>Functional Interface</em> whenever a constructor is required with one or more arguments.</p>
<h3 id="heading-using-function-when-one-argument-is-required">Using Function when one argument is required</h3>
<pre><code class="lang-JAVA"><span class="hljs-keyword">static</span> Map&lt;String, Function&lt;Integer, Profile&gt;&gt; profiles = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

<span class="hljs-comment">// Filling the hashMap does not change</span>
<span class="hljs-keyword">static</span> {
  profiles.put(ADMIN, Admin::<span class="hljs-keyword">new</span>);
  profiles.put(HR, Hr::<span class="hljs-keyword">new</span>);
  profiles.put(HRD, Hrd::<span class="hljs-keyword">new</span>);
  profiles.put(VALIDATOR, Validator::<span class="hljs-keyword">new</span>);
  profiles.put(READER, Reader::<span class="hljs-keyword">new</span>);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Profile <span class="hljs-title">create</span><span class="hljs-params">(String profile, <span class="hljs-keyword">int</span> arg)</span> </span>{
  <span class="hljs-keyword">if</span> (profiles.containsKey(profile)) {
    <span class="hljs-keyword">return</span> profiles.get(profile).apply(arg);
  }
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Anonymous(arg);
}
</code></pre>
<h3 id="heading-using-specific-functional-interface-with-one-or-more-arguments">Using Specific Functional Interface with one or more arguments</h3>
<p>First, we create the <em>Functional Interface</em> with the required arguments:</p>
<pre><code class="lang-JAVA"><span class="hljs-meta">@FunctionalInterface</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ProfileFunction</span> </span>{

   <span class="hljs-function">Profile <span class="hljs-title">apply</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arg1, String arg2)</span></span>;
}
</code></pre>
<p>Then, we change the HashMap to accept the <em>ProfileFunction</em> as follows:</p>
<pre><code class="lang-JAVA"><span class="hljs-keyword">static</span> Map&lt;String, ProfileFunction&gt; profiles = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

<span class="hljs-comment">// Filling the hashMap does not change</span>
<span class="hljs-keyword">static</span> {
  profiles.put(ADMIN, Admin::<span class="hljs-keyword">new</span>);
  profiles.put(HR, Hr::<span class="hljs-keyword">new</span>);
  profiles.put(HRD, Hrd::<span class="hljs-keyword">new</span>);
  profiles.put(VALIDATOR, Validator::<span class="hljs-keyword">new</span>);
  profiles.put(READER, Reader::<span class="hljs-keyword">new</span>);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Profile <span class="hljs-title">create</span><span class="hljs-params">(String profile, <span class="hljs-keyword">int</span> arg1, String arg2)</span> </span>{
  <span class="hljs-keyword">if</span> (profiles.containsKey(profile)) {
    <span class="hljs-keyword">return</span> profiles.get(profile).apply(arg1, arg2);
  }
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Anonymous(arg1, arg2);
}
</code></pre>
<h2 id="heading-a-great-advantage-with-enum">A great advantage with Enum</h2>
<p>In such a use case, we can replace the HashMap and delegate the profile creation to an <em>Enum</em>, which brings a more elegant and efficient design💖:</p>
<pre><code class="lang-JAVA"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">ProfileEnum</span> </span>{

  ADMIN(Admin::<span class="hljs-keyword">new</span>),
  HR(Hr::<span class="hljs-keyword">new</span>),
  HRD(Hrd::<span class="hljs-keyword">new</span>),
  VALIDATOR(Validator::<span class="hljs-keyword">new</span>);

  <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ProfileFunction profileFunction;

  ProfileEnum(ProfileFunction profileFunction) {
     <span class="hljs-keyword">this</span>.profileFunction = profileFunction;
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> Profile <span class="hljs-title">get</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arg1, String arg2)</span> </span>{
     <span class="hljs-keyword">return</span> profileFunction.apply(arg1, arg2);
  }

}
</code></pre>
<p>And the factory method would become:</p>
<pre><code class="lang-JAVA"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProfileFactory</span> </span>{

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Profile <span class="hljs-title">create</span><span class="hljs-params">(String profile, <span class="hljs-keyword">int</span> arg1, String arg2)</span> </span>{
     <span class="hljs-keyword">try</span> {
        ProfileEnum constant = ProfileEnum.valueOf(profile.toUpperCase());
        <span class="hljs-keyword">return</span> constant.get(arg1, arg2);
     } <span class="hljs-keyword">catch</span> (IllegalArgumentException iae) {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Anonymous(arg1, arg2);
     }
  }

}
</code></pre>
<blockquote>
<p>valueOf would throw an IllegalArgumentException if the enum type cannot find a constant with the specified profile name.</p>
</blockquote>
<h2 id="heading-source-code">Source Code</h2>
<p>The complete source code is available at: https://github.com/elie29/factory-pattern, where each step has its own specific branch.</p>
<blockquote>
<p>Thanks for reading!
If you enjoyed this post, follow me on <a target="_blank" href="https://www.twitter.com/elie_nehme">Twitter</a> for more content. If you have any feedback or suggestions, leave it in the comments below and I’ll do my best to get back to you 👌</p>
</blockquote>
]]></content:encoded></item></channel></rss>