agentic-api 1.0.5 → 2.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +118 -22
  2. package/dist/src/agents/agents.example.d.ts +3 -0
  3. package/dist/src/agents/agents.example.js +38 -0
  4. package/dist/src/agents/authentication.js +2 -0
  5. package/dist/src/agents/digestor.js +25 -16
  6. package/dist/src/agents/prompts.d.ts +2 -2
  7. package/dist/src/agents/prompts.js +112 -49
  8. package/dist/src/agents/reducer.core.d.ts +12 -0
  9. package/dist/src/agents/reducer.core.js +207 -0
  10. package/dist/src/agents/reducer.d.ts +3 -0
  11. package/dist/src/agents/reducer.example.d.ts +28 -0
  12. package/dist/src/agents/reducer.example.js +118 -0
  13. package/dist/src/agents/reducer.js +19 -0
  14. package/dist/src/agents/reducer.loaders.d.ts +34 -0
  15. package/dist/src/agents/reducer.loaders.js +122 -0
  16. package/dist/src/agents/reducer.process.d.ts +16 -0
  17. package/dist/src/agents/reducer.process.js +143 -0
  18. package/dist/src/agents/reducer.tools.d.ts +29 -0
  19. package/dist/src/agents/reducer.tools.js +157 -0
  20. package/dist/src/agents/reducer.types.d.ts +50 -0
  21. package/dist/src/agents/reducer.types.js +5 -0
  22. package/dist/src/agents/simulator.d.ts +47 -0
  23. package/dist/src/agents/simulator.executor.d.ts +26 -0
  24. package/dist/src/agents/simulator.executor.js +132 -0
  25. package/dist/src/agents/simulator.js +205 -0
  26. package/dist/src/agents/simulator.prompts.d.ts +16 -0
  27. package/dist/src/agents/simulator.prompts.js +108 -0
  28. package/dist/src/agents/simulator.types.d.ts +42 -0
  29. package/dist/src/agents/simulator.types.js +2 -0
  30. package/dist/src/agents/simulator.utils.d.ts +20 -0
  31. package/dist/src/agents/simulator.utils.js +87 -0
  32. package/dist/src/execute.d.ts +14 -7
  33. package/dist/src/execute.js +359 -84
  34. package/dist/src/index.d.ts +9 -0
  35. package/dist/src/index.js +14 -0
  36. package/dist/src/princing.openai.d.ts +9 -2
  37. package/dist/src/princing.openai.js +16 -11
  38. package/dist/src/prompts.d.ts +3 -2
  39. package/dist/src/prompts.js +207 -72
  40. package/dist/src/rag/embeddings.d.ts +103 -0
  41. package/dist/src/rag/embeddings.js +466 -0
  42. package/dist/src/rag/index.d.ts +12 -0
  43. package/dist/src/rag/index.js +40 -0
  44. package/dist/src/rag/lucene.d.ts +45 -0
  45. package/dist/src/rag/lucene.js +227 -0
  46. package/dist/src/rag/parser.d.ts +68 -0
  47. package/dist/src/rag/parser.js +192 -0
  48. package/dist/src/rag/tools.d.ts +76 -0
  49. package/dist/src/rag/tools.js +196 -0
  50. package/dist/src/rag/types.d.ts +178 -0
  51. package/dist/src/rag/types.js +21 -0
  52. package/dist/src/rag/usecase.d.ts +16 -0
  53. package/dist/src/rag/usecase.js +79 -0
  54. package/dist/src/rules/errors.d.ts +60 -0
  55. package/dist/src/rules/errors.js +97 -0
  56. package/dist/src/rules/git/git.e2e.helper.d.ts +104 -0
  57. package/dist/src/rules/git/git.e2e.helper.js +488 -0
  58. package/dist/src/rules/git/git.health.d.ts +66 -0
  59. package/dist/src/rules/git/git.health.js +354 -0
  60. package/dist/src/rules/git/git.helper.d.ts +129 -0
  61. package/dist/src/rules/git/git.helper.js +53 -0
  62. package/dist/src/rules/git/index.d.ts +6 -0
  63. package/dist/src/rules/git/index.js +76 -0
  64. package/dist/src/rules/git/repo.d.ts +128 -0
  65. package/dist/src/rules/git/repo.js +900 -0
  66. package/dist/src/rules/git/repo.pr.d.ts +137 -0
  67. package/dist/src/rules/git/repo.pr.js +589 -0
  68. package/dist/src/rules/git/repo.tools.d.ts +134 -0
  69. package/dist/src/rules/git/repo.tools.js +730 -0
  70. package/dist/src/rules/index.d.ts +8 -0
  71. package/dist/src/rules/index.js +25 -0
  72. package/dist/src/rules/messages.d.ts +17 -0
  73. package/dist/src/rules/messages.js +21 -0
  74. package/dist/src/rules/types.ctrl.d.ts +28 -0
  75. package/dist/src/rules/types.ctrl.js +2 -0
  76. package/dist/src/rules/types.d.ts +510 -0
  77. package/dist/src/rules/types.helpers.d.ts +132 -0
  78. package/dist/src/rules/types.helpers.js +2 -0
  79. package/dist/src/rules/types.js +33 -0
  80. package/dist/src/rules/user.mapper.d.ts +61 -0
  81. package/dist/src/rules/user.mapper.js +160 -0
  82. package/dist/src/rules/utils/slug.d.ts +22 -0
  83. package/dist/src/rules/utils/slug.js +35 -0
  84. package/dist/src/rules/utils.matter.d.ts +66 -0
  85. package/dist/src/rules/utils.matter.js +208 -0
  86. package/dist/src/rules/utils.slug.d.ts +22 -0
  87. package/dist/src/rules/utils.slug.js +35 -0
  88. package/dist/src/scrapper.d.ts +3 -2
  89. package/dist/src/scrapper.js +33 -37
  90. package/dist/src/stategraph/index.d.ts +8 -0
  91. package/dist/src/stategraph/index.js +21 -0
  92. package/dist/src/stategraph/stategraph.d.ts +91 -0
  93. package/dist/src/stategraph/stategraph.js +241 -0
  94. package/dist/src/stategraph/stategraph.storage.d.ts +41 -0
  95. package/dist/src/stategraph/stategraph.storage.js +166 -0
  96. package/dist/src/stategraph/types.d.ts +139 -0
  97. package/dist/src/stategraph/types.js +19 -0
  98. package/dist/src/types.d.ts +68 -39
  99. package/dist/src/types.js +53 -89
  100. package/dist/src/usecase.d.ts +4 -0
  101. package/dist/src/usecase.js +44 -0
  102. package/dist/src/utils.d.ts +12 -5
  103. package/dist/src/utils.js +30 -13
  104. package/package.json +9 -3
@@ -0,0 +1,354 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GitHealthManager = void 0;
4
+ const git_1 = require("../git");
5
+ /**
6
+ * Git Repository Health Manager
7
+ *
8
+ * Manages repository health diagnostics, repairs, and maintenance operations.
9
+ * Provides safe operations that protect user work by only allowing destructive
10
+ * operations on temporary validation branches.
11
+ */
12
+ class GitHealthManager {
13
+ constructor(config) {
14
+ this.config = (0, git_1.gitLoad)(config);
15
+ this.git = this.config.instance;
16
+ }
17
+ /**
18
+ * Detects and resolves any ongoing merge states in the repository
19
+ * This should be called before any migration operations
20
+ *
21
+ * Uses the robust gitGetBranchHealth function to diagnose issues:
22
+ * - git merge --abort → abandonne tout merge en cours
23
+ * - git reset --hard HEAD → nettoie index + working directory
24
+ */
25
+ async repairRepository(branch) {
26
+ // CRITICAL FIX: Checkout sur la branche cible avant forceRepair()
27
+ // Sinon ensureSafeBranch() vérifie la branche courante (qui peut être 'main')
28
+ try {
29
+ await this.git.checkout(branch);
30
+ }
31
+ catch (checkoutError) {
32
+ // Si checkout normal échoue, forcer le checkout
33
+ console.log(`🔧 Checkout forcé vers ${branch}...`, checkoutError);
34
+ }
35
+ try {
36
+ // Use the robust health diagnostic function
37
+ const health = await (0, git_1.gitGetBranchHealth)(this.git, branch);
38
+ // If branch is healthy, show only one line
39
+ if (health.healthy) {
40
+ console.log(`✅ ${health.branch} est en bonne santé`);
41
+ }
42
+ // Display issues found
43
+ if (health.issues.length > 0) {
44
+ console.log(`❌ Problèmes détectés:`);
45
+ health.issues.forEach(issue => console.log(` - ${issue}`));
46
+ }
47
+ // Display recommendations
48
+ if (health.recommendations.length > 0) {
49
+ console.log(`🔧 Réparations recommandées:`);
50
+ health.recommendations.forEach(rec => console.log(` - ${rec}`));
51
+ }
52
+ // Perform repair using the two essential commands
53
+ const { mainBranch, draftBranch, validationPrefix } = this.config;
54
+ // PROTECTION: Permettre la réparation seulement sur les branches de validation
55
+ // Refuser sur les branches protégées (main, rule-editor) et sur toute branche non-validation
56
+ if ([mainBranch, draftBranch].includes(health.branch) || !health.branch.startsWith(validationPrefix)) {
57
+ console.log(`🚨 PROTECTION: Réparation refusée sur la branche '${health.branch}' - uniquement autorisée sur les branches '${validationPrefix}*'`);
58
+ return;
59
+ }
60
+ if (!health.healthy) {
61
+ console.log(`✅ Branche de validation détectée: '${health.branch}' - réparation automatique`);
62
+ this.forceRepair();
63
+ }
64
+ // Verify repair was successful
65
+ const healthAfterRepair = await (0, git_1.gitGetBranchHealth)(this.git, branch);
66
+ if (!healthAfterRepair.healthy) {
67
+ console.warn(`⚠️ Réparation partielle. Problèmes restants:`);
68
+ healthAfterRepair.issues.forEach(issue => console.log(` - ${issue}`));
69
+ }
70
+ // Only show details if there are problems
71
+ // console.log(`🔧 Diagnostic de l'état du dépôt sur ${health.branch}...`);
72
+ // console.log(`📊 Branche: ${health.branch}`);
73
+ // console.log(` Existe: ${health.exists ? '✅' : '❌'}`);
74
+ // console.log(` Accessible: ${health.accessible ? '✅' : '❌'}`);
75
+ // console.log(` Propre: ${health.clean ? '✅' : '❌'}`);
76
+ // console.log(` Index lisible: ${health.indexReadable ? '✅' : '❌'}`);
77
+ // console.log(` État global: ${health.healthy ? '✅ SAIN' : '⚠️ PROBLÉMATIQUE'}`);
78
+ }
79
+ catch (error) {
80
+ console.error(`❌ Échec du diagnostic/réparation${branch ? ` sur ${branch}` : ''}:`, error);
81
+ throw new Error(`Impossible de diagnostiquer ou réparer le dépôt: ${error.message}`);
82
+ }
83
+ }
84
+ /**
85
+ * Ensures we're on a safe branch before performing destructive operations
86
+ * Protects user work by refusing operations on main branches
87
+ */
88
+ async ensureSafeBranch() {
89
+ const currentBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']);
90
+ const { mainBranch, draftBranch, validationPrefix } = this.config;
91
+ // Check if we're on a protected branch
92
+ if (currentBranch === mainBranch) {
93
+ throw new Error(`🚨 PROTECTION: git reset --hard HEAD INTERDIT sur la branche '${mainBranch}' (branche de production)`);
94
+ }
95
+ if (currentBranch === draftBranch) {
96
+ throw new Error(`🚨 PROTECTION: git reset --hard HEAD INTERDIT sur la branche '${draftBranch}' (contient le travail utilisateur)`);
97
+ }
98
+ // Only allow on validation branches (temporary)
99
+ if (!currentBranch.startsWith(validationPrefix)) {
100
+ throw new Error(`🚨 PROTECTION: git reset --hard HEAD autorisé UNIQUEMENT sur les branches '${validationPrefix}*' (branches temporaires). Branche courante: '${currentBranch}'`);
101
+ }
102
+ console.log(`✅ Branche sécurisée détectée: '${currentBranch}' - opération autorisée`);
103
+ return currentBranch;
104
+ }
105
+ /**
106
+ * Force repair when git status fails
107
+ * PROTECTED: Only works on validation branches to protect user work
108
+ */
109
+ async forceRepair() {
110
+ // SECURITY: Verify we're on a safe branch before destructive operations
111
+ await this.ensureSafeBranch();
112
+ try {
113
+ await this.git.raw(['merge', '--abort']);
114
+ console.log(' ✅ Merge abandonné (forcé)');
115
+ }
116
+ catch (abortError) {
117
+ }
118
+ try {
119
+ await this.git.raw(['reset', '--hard', 'HEAD']);
120
+ console.log(' ✅ Index et working directory nettoyés');
121
+ }
122
+ catch (resetError) {
123
+ throw new Error(`Échec du reset --hard: ${resetError}`);
124
+ }
125
+ }
126
+ /**
127
+ * Comprehensive health check for all important branches in the system
128
+ * Provides a complete overview of repository health
129
+ */
130
+ async diagnosticRepository() {
131
+ console.log('🏥 Diagnostic complet du dépôt...');
132
+ const results = [];
133
+ const { mainBranch, draftBranch, validationPrefix } = this.config;
134
+ try {
135
+ // Check main branch
136
+ const mainHealth = await (0, git_1.gitGetBranchHealth)(this.git, mainBranch);
137
+ results.push(mainHealth);
138
+ this.displayHealthSummary(mainHealth);
139
+ // Check draft branch
140
+ const draftHealth = await (0, git_1.gitGetBranchHealth)(this.git, draftBranch);
141
+ results.push(draftHealth);
142
+ this.displayHealthSummary(draftHealth);
143
+ // Check all validation branches
144
+ const allBranches = await (0, git_1.gitGetAllBranches)(this.git);
145
+ const validationBranches = allBranches.filter(b => b.startsWith(validationPrefix));
146
+ if (validationBranches.length > 0) {
147
+ for (const branch of validationBranches) {
148
+ const health = await (0, git_1.gitGetBranchHealth)(this.git, branch);
149
+ results.push(health);
150
+ this.displayHealthSummary(health);
151
+ }
152
+ }
153
+ // Global summary
154
+ const healthyCount = results.filter(h => h.healthy).length;
155
+ const totalCount = results.length;
156
+ const problemCount = totalCount - healthyCount;
157
+ if (problemCount === 0) {
158
+ console.log(`✅ Toutes les branches (${totalCount}) sont en bonne santé`);
159
+ }
160
+ else {
161
+ console.log(`📊 Résumé: ${healthyCount}/${totalCount} branches saines, ${problemCount} nécessitent une attention`);
162
+ console.log('💡 Utilisez repairRepository(branchName) pour les réparer');
163
+ }
164
+ return results;
165
+ }
166
+ catch (error) {
167
+ console.error('❌ Erreur lors du diagnostic complet:', error);
168
+ throw new Error(`Diagnostic complet échoué: ${error.message}`);
169
+ }
170
+ }
171
+ /**
172
+ * Display a concise health summary for a branch
173
+ */
174
+ displayHealthSummary(health) {
175
+ if (health.healthy) {
176
+ console.log(`✅ ${health.branch}`);
177
+ }
178
+ else {
179
+ console.log(`⚠️ ${health.branch}: ${health.issues.slice(0, 2).join(', ')}${health.issues.length > 2 ? '...' : ''}`);
180
+ }
181
+ }
182
+ /**
183
+ * Synchronizes and repairs all validation branches with the editor branch
184
+ *
185
+ * This function updates existing validation branches to stay in sync with rule-editor,
186
+ * not merging rule-editor into validation branches.
187
+ *
188
+ * Handles:
189
+ * - Échecs de synchronisation → tentative de réparation par branche
190
+ * - Branches inaccessibles → git checkout -f + git reset --hard HEAD (protected)
191
+ * - Working directory sale → git reset --hard HEAD (protected)
192
+ * - Retry automatique après réparation
193
+ * - Branches irréparables → log d'intervention manuelle
194
+ */
195
+ async syncValidationBranches() {
196
+ const { validationPrefix } = this.config;
197
+ if (!validationPrefix) {
198
+ console.error("Erreur: Le préfixe de validation n'est pas configuré.");
199
+ return;
200
+ }
201
+ // FIXME: forceRepair should manage this issue.
202
+ // PROTECTION: Sauvegarder la branche courante pour y revenir à la fin
203
+ const originalBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']).catch(() => 'main');
204
+ try {
205
+ const allBranches = await (0, git_1.gitGetAllBranches)(this.git, { unmergedOnly: true });
206
+ const validationBranches = allBranches.filter(b => b.startsWith(validationPrefix));
207
+ const user = {
208
+ name: 'repair',
209
+ email: 'olivier@evaletolab.ch',
210
+ };
211
+ if (validationBranches.length === 0) {
212
+ return;
213
+ }
214
+ console.log(`🔄 Synchronisation de ${validationBranches.length} branche(s) de validation...`);
215
+ for (const branch of validationBranches) {
216
+ try {
217
+ await this.repairRepository(branch);
218
+ }
219
+ catch (error) {
220
+ console.warn(`⚠️ Échec de la synchronisation de ${branch}: ${error.message}`);
221
+ // Try to repair this specific branch
222
+ try {
223
+ console.log(`🔧 Tentative de réparation de la branche ${branch}...`);
224
+ // SECURITY: Verify this is a validation branch before destructive operations
225
+ if (!branch.startsWith(this.config.validationPrefix)) {
226
+ throw new Error(`🚨 PROTECTION: Réparation refusée sur '${branch}' - uniquement autorisée sur les branches '${this.config.validationPrefix}*'`);
227
+ }
228
+ // Check if the branch is in a problematic state
229
+ const currentBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']);
230
+ if (currentBranch !== branch) {
231
+ try {
232
+ await this.git.checkout(branch);
233
+ }
234
+ catch (checkoutError) {
235
+ // If checkout fails due to merge state, reset the branch
236
+ console.log(`🔧 Réinitialisation forcée de la branche ${branch}...`);
237
+ await this.git.raw(['checkout', '-f', branch]);
238
+ // Abort any ongoing merge
239
+ await this.git.raw(['merge', '--abort']).catch(() => { });
240
+ }
241
+ }
242
+ // SECURITY: Double-check we're on the correct validation branch before reset
243
+ const finalBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']);
244
+ if (!finalBranch.startsWith(this.config.validationPrefix)) {
245
+ throw new Error(`🚨 PROTECTION: Branche courante '${finalBranch}' n'est pas une branche de validation - reset --hard HEAD annulé`);
246
+ }
247
+ // Clean the working directory - reset --hard does it all (PROTECTED)
248
+ console.log(`✅ Branche de validation confirmée: '${finalBranch}' - nettoyage autorisé`);
249
+ await this.git.raw(['reset', '--hard', 'HEAD']);
250
+ // Retry the sync
251
+ await (0, git_1.gitSyncPR)(this.git, branch, user);
252
+ console.log(`✅ ${branch} réparée et synchronisée`);
253
+ }
254
+ catch (repairError) {
255
+ console.error(`❌ Impossible de réparer ${branch}: ${repairError.message}`);
256
+ console.error(`📝 Cette branche nécessite une intervention manuelle`);
257
+ throw repairError;
258
+ }
259
+ }
260
+ }
261
+ }
262
+ finally {
263
+ // FIXME the final state is unknown
264
+ // PROTECTION: Revenir à la branche originale seulement si elle est sécurisée
265
+ try {
266
+ const currentBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']).catch(() => '');
267
+ if (currentBranch !== originalBranch) {
268
+ const { mainBranch, draftBranch, validationPrefix } = this.config;
269
+ // Ne revenir à la branche originale que si elle est une branche de validation
270
+ // Pour les branches protégées, rester sur la branche courante pour éviter les erreurs
271
+ if (originalBranch.startsWith(validationPrefix)) {
272
+ await this.git.checkout(originalBranch).catch(() => {
273
+ console.warn(`⚠️ Impossible de revenir à la branche de validation '${originalBranch}'`);
274
+ });
275
+ }
276
+ else if ([mainBranch, draftBranch].includes(originalBranch)) {
277
+ console.log(`ℹ️ Branche originale '${originalBranch}' est protégée - reste sur '${currentBranch}' pour la sécurité`);
278
+ }
279
+ }
280
+ }
281
+ catch (error) {
282
+ console.warn(`⚠️ Erreur lors du retour à la branche originale: ${error}`);
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * Migrates Git notes from the first commit of validation branches to the last one.
288
+ *
289
+ * Handles:
290
+ * - Notes déjà présentes sur HEAD → skip migration
291
+ * - Merge-base introuvable → skip branche avec warning
292
+ * - Notes orphelines sur anciens commits → copie vers HEAD + suppression
293
+ * - Branches sans historique de notes → ignore silencieusement
294
+ * - Erreurs de traitement par branche → continue avec les autres
295
+ */
296
+ async migrateNotes() {
297
+ const { mainBranch, validationPrefix, gitNotes } = this.config;
298
+ if (!validationPrefix || !gitNotes.namespace) {
299
+ console.error("Erreur: Le préfixe de validation ou le namespace des notes n'est pas configuré.");
300
+ return;
301
+ }
302
+ const allBranches = await (0, git_1.gitGetAllBranches)(this.git);
303
+ const validationBranches = allBranches.filter(b => b.startsWith(validationPrefix));
304
+ if (validationBranches.length === 0) {
305
+ return;
306
+ }
307
+ let migratedCount = 0;
308
+ let alreadyOkCount = 0;
309
+ for (const branch of validationBranches) {
310
+ try {
311
+ const lastCommit = (await this.git.revparse(branch)).trim();
312
+ // 1. Check if note is already on the last commit
313
+ const noteOnHead = await (0, git_1.gitReadNote)(this.git, lastCommit, gitNotes.namespace, 1);
314
+ if (noteOnHead) {
315
+ alreadyOkCount++;
316
+ continue;
317
+ }
318
+ // 2. Scan the branch history for a note
319
+ const mergeBase = (await this.git.raw('merge-base', mainBranch, branch)).trim();
320
+ if (!mergeBase) {
321
+ console.log(`⚠️ ${branch}: Impossible de trouver un point de merge avec '${mainBranch}'. Ignoré.`);
322
+ continue;
323
+ }
324
+ const revListOutput = await this.git.raw('rev-list', `${mergeBase}..${branch}`);
325
+ const branchCommits = revListOutput.split('\n').filter(Boolean);
326
+ let oldNoteCommit = null;
327
+ for (const commitHash of branchCommits) {
328
+ const note = await (0, git_1.gitReadNote)(this.git, commitHash, gitNotes.namespace, 1);
329
+ if (note) {
330
+ oldNoteCommit = commitHash;
331
+ break; // Found the first note, stop searching
332
+ }
333
+ }
334
+ // 3. If a note was found on an old commit, migrate it
335
+ if (oldNoteCommit) {
336
+ console.log(`🔄 ${branch}: Migration de la note de ${oldNoteCommit.substring(0, 8)} vers ${lastCommit.substring(0, 8)}...`);
337
+ await this.git.raw('notes', '--ref', gitNotes.namespace, 'copy', '--force', oldNoteCommit, lastCommit);
338
+ await (0, git_1.gitDeleteNote)(this.git, oldNoteCommit, gitNotes.namespace);
339
+ console.log(`✅ ${branch}: Migration terminée`);
340
+ migratedCount++;
341
+ }
342
+ }
343
+ catch (error) {
344
+ console.error(`❌ ${branch}: Erreur lors de la migration:`, error);
345
+ throw error;
346
+ }
347
+ }
348
+ // Summary only if there was work to do
349
+ if (migratedCount > 0 || alreadyOkCount !== validationBranches.length) {
350
+ console.log(`✅ Migration des notes terminée: ${migratedCount} migrées, ${alreadyOkCount} déjà OK`);
351
+ }
352
+ }
353
+ }
354
+ exports.GitHealthManager = GitHealthManager;
@@ -0,0 +1,129 @@
1
+ import { RulesGitConfig, GitCommitHistory } from '../types';
2
+ import { IGitOperations, IGitRepository } from '../types.helpers';
3
+ /**
4
+ * Mock basique pour les opérations Git
5
+ * Peut être étendu dans les tests spécifiques
6
+ */
7
+ export declare class MockGitOperations implements IGitOperations {
8
+ private mockData;
9
+ constructor(mockData?: {
10
+ files?: Record<string, Record<string, string>>;
11
+ branches?: string[];
12
+ fileExists?: Record<string, Record<string, boolean>>;
13
+ mergedFiles?: Record<string, boolean>;
14
+ });
15
+ getFileContent(filePath: string, branch?: string): Promise<GitCommitHistory | null>;
16
+ listFilesInBranch(branch: string, pattern?: string): Promise<string[]>;
17
+ fileExistsInBranch(filePath: string, branch: string): Promise<boolean>;
18
+ isFileMerged(filePath: string, from: string, target?: string): Promise<boolean>;
19
+ getAllBranches(): Promise<string[]>;
20
+ validateConfiguration(): Promise<boolean>;
21
+ }
22
+ /**
23
+ * Configuration pour les tests E2E
24
+ */
25
+ export interface E2ETestConfig {
26
+ /**
27
+ * Répertoire temporaire pour les tests
28
+ */
29
+ tempDir: string;
30
+ /**
31
+ * Configuration Git pour les tests
32
+ */
33
+ gitConfig: RulesGitConfig;
34
+ /**
35
+ * Nettoyage automatique après les tests
36
+ */
37
+ autoCleanup: boolean;
38
+ }
39
+ /**
40
+ * Interface pour les opérations de test E2E
41
+ * Étend les interfaces existantes avec des méthodes spécifiques aux tests
42
+ */
43
+ export interface IE2ETestOperations extends IGitRepository {
44
+ /**
45
+ * Initialise un repository Git temporaire pour les tests
46
+ */
47
+ initTemporaryRepo(): Promise<void>;
48
+ /**
49
+ * Nettoie le repository temporaire
50
+ */
51
+ cleanup(): Promise<void>;
52
+ /**
53
+ * Crée un fichier dans le repository
54
+ * @param filePath Chemin du fichier
55
+ * @param content Contenu du fichier
56
+ * @param branch Branche optionnelle (par défaut: draft)
57
+ */
58
+ createOrEditFile(filePath: string, content: string, branch?: string): Promise<GitCommitHistory>;
59
+ /**
60
+ * Modifie un fichier existant
61
+ * @param filePath Chemin du fichier
62
+ * @param content Contenu du fichier
63
+ * @param branch Branche optionnelle (par défaut: draft)
64
+ */
65
+ editFile(filePath: string, content: string, branch?: string): Promise<GitCommitHistory>;
66
+ /**
67
+ * Vérifie l'état du repository (intégrité, branches, etc.)
68
+ */
69
+ validateRepositoryState(): Promise<{
70
+ isValid: boolean;
71
+ branches: string[];
72
+ files: Record<string, string[]>;
73
+ errors: string[];
74
+ }>;
75
+ /**
76
+ * Simule un workflow complet de création et validation de PR
77
+ */
78
+ runCompleteWorkflow(files: {
79
+ path: string;
80
+ content: string;
81
+ }[], description: string): Promise<{
82
+ prBranch: string;
83
+ commitHash: string;
84
+ mergeCommitHash?: string;
85
+ }>;
86
+ }
87
+ /**
88
+ * Résultat d'un test E2E
89
+ */
90
+ export interface E2ETestResult {
91
+ success: boolean;
92
+ duration: number;
93
+ details: {
94
+ repositoryValid: boolean;
95
+ filesCreated: string[];
96
+ prCreated?: string;
97
+ prClosed?: boolean;
98
+ merged?: boolean;
99
+ };
100
+ errors: string[];
101
+ }
102
+ /**
103
+ * Interface pour les assertions E2E spécifiques au domain rules
104
+ */
105
+ export interface IRulesE2EAssertions {
106
+ /**
107
+ * Vérifie qu'un fichier existe et a le contenu attendu
108
+ */
109
+ assertFileContent(filePath: string, expectedContent: string, branch?: string): Promise<void>;
110
+ /**
111
+ * Vérifie qu'un PR existe et est dans l'état attendu
112
+ */
113
+ assertPRState(branch: string, expectedState: 'open' | 'closed'): Promise<void>;
114
+ /**
115
+ * Vérifie qu'un fichier a été mergé dans la branche principale
116
+ */
117
+ assertFilemerged(filePath: string, fromBranch: string, toBranch?: string): Promise<void>;
118
+ /**
119
+ * Vérifie la cohérence de l'historique Git
120
+ */
121
+ assertGitHistory(expectedCommits: {
122
+ message: string;
123
+ author?: string;
124
+ }[]): Promise<void>;
125
+ /**
126
+ * Vérifie que les branches ont été créées correctement
127
+ */
128
+ assertBranchStructure(expectedBranches: string[]): Promise<void>;
129
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MockGitOperations = void 0;
4
+ // ===== INTERFACES MOCKABLES POUR LES TESTS =====
5
+ // ===== CLASSES MOCK POUR LES TESTS =====
6
+ /**
7
+ * Mock basique pour les opérations Git
8
+ * Peut être étendu dans les tests spécifiques
9
+ */
10
+ class MockGitOperations {
11
+ constructor(mockData = {}) {
12
+ this.mockData = mockData;
13
+ }
14
+ async getFileContent(filePath, branch) {
15
+ const branchKey = branch || 'HEAD';
16
+ if (!this.mockData.files?.[branchKey]?.[filePath]) {
17
+ return null;
18
+ }
19
+ const commit = {
20
+ hash: 'mock-commit-hash',
21
+ date: new Date(),
22
+ message: 'Mock commi',
23
+ author: {
24
+ name: 'Mock Auor',
25
+ email: '@uhorcom'
26
+ },
27
+ content: this.mockData.files[branchKey][filePath],
28
+ };
29
+ return commit;
30
+ }
31
+ async listFilesInBranch(branch, pattern = '.md') {
32
+ const branchFiles = this.mockData.files?.[branch] || {};
33
+ const files = Object.keys(branchFiles);
34
+ if (pattern === '.md') {
35
+ return files.filter(file => file.endsWith('.md'));
36
+ }
37
+ const regex = new RegExp(pattern.replace('*', '.*'));
38
+ return files.filter(file => regex.test(file));
39
+ }
40
+ async fileExistsInBranch(filePath, branch) {
41
+ return this.mockData.fileExists?.[branch]?.[filePath] ?? false;
42
+ }
43
+ async isFileMerged(filePath, from, target = 'main') {
44
+ return this.mockData.mergedFiles?.[filePath] ?? false;
45
+ }
46
+ async getAllBranches() {
47
+ return this.mockData.branches || [];
48
+ }
49
+ async validateConfiguration() {
50
+ return true;
51
+ }
52
+ }
53
+ exports.MockGitOperations = MockGitOperations;
@@ -0,0 +1,6 @@
1
+ export { lock, unlock, gitLoad, gitIsFileMerged, gitLastCommit, gitListFilesInBranch, gitListFilesOutsideRepo, gitFileExistsInBranch, gitGetFilesSummary, gitGetFileContent, gitGetFilePreview, gitGetFileHistory, gitReadFileOutsideRepo, gitGetUnmergedBranchesForFile, gitGetAllBranches, gitGetDiffFiles, gitReadNote, gitWriteNote, gitDeleteNote, } from './repo.tools';
2
+ export { gitInit, gitEnsureRepositoryConfiguration, gitEnsureRemoteConfiguration, gitSetupRepository, gitShowConfiguration, gitCheckConfiguration, gitGetBranchHealth, gitCreateOrEditFile, gitEditFile, gitRenameFile, gitDeleteFile, } from './repo';
3
+ export { gitSyncPR, gitIsPRClosed, gitIsPRClosedRobust, gitGetPRMetadata, gitGetAllPR, gitGetClosedPRs, gitLoadPR, gitPRUpdateComments, gitClosePR, gitClosePRRobust, gitGetNextPRNumber, gitNewValidationRequest, gitNewPR, } from './repo.pr';
4
+ export * from './git.e2e.helper';
5
+ export * from './git.health';
6
+ export * from './git.helper';
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.gitNewPR = exports.gitNewValidationRequest = exports.gitGetNextPRNumber = exports.gitClosePRRobust = exports.gitClosePR = exports.gitPRUpdateComments = exports.gitLoadPR = exports.gitGetClosedPRs = exports.gitGetAllPR = exports.gitGetPRMetadata = exports.gitIsPRClosedRobust = exports.gitIsPRClosed = exports.gitSyncPR = exports.gitDeleteFile = exports.gitRenameFile = exports.gitEditFile = exports.gitCreateOrEditFile = exports.gitGetBranchHealth = exports.gitCheckConfiguration = exports.gitShowConfiguration = exports.gitSetupRepository = exports.gitEnsureRemoteConfiguration = exports.gitEnsureRepositoryConfiguration = exports.gitInit = exports.gitDeleteNote = exports.gitWriteNote = exports.gitReadNote = exports.gitGetDiffFiles = exports.gitGetAllBranches = exports.gitGetUnmergedBranchesForFile = exports.gitReadFileOutsideRepo = exports.gitGetFileHistory = exports.gitGetFilePreview = exports.gitGetFileContent = exports.gitGetFilesSummary = exports.gitFileExistsInBranch = exports.gitListFilesOutsideRepo = exports.gitListFilesInBranch = exports.gitLastCommit = exports.gitIsFileMerged = exports.gitLoad = exports.unlock = exports.lock = void 0;
18
+ // === OPÉRATIONS GIT BAS NIVEAU ===
19
+ // Fonctions atomiques pour manipuler Git directement
20
+ var repo_tools_1 = require("./repo.tools");
21
+ // Concurrence
22
+ Object.defineProperty(exports, "lock", { enumerable: true, get: function () { return repo_tools_1.lock; } });
23
+ Object.defineProperty(exports, "unlock", { enumerable: true, get: function () { return repo_tools_1.unlock; } });
24
+ // Configuration
25
+ Object.defineProperty(exports, "gitLoad", { enumerable: true, get: function () { return repo_tools_1.gitLoad; } });
26
+ // Lecture de fichiers
27
+ Object.defineProperty(exports, "gitIsFileMerged", { enumerable: true, get: function () { return repo_tools_1.gitIsFileMerged; } });
28
+ Object.defineProperty(exports, "gitLastCommit", { enumerable: true, get: function () { return repo_tools_1.gitLastCommit; } });
29
+ Object.defineProperty(exports, "gitListFilesInBranch", { enumerable: true, get: function () { return repo_tools_1.gitListFilesInBranch; } });
30
+ Object.defineProperty(exports, "gitListFilesOutsideRepo", { enumerable: true, get: function () { return repo_tools_1.gitListFilesOutsideRepo; } });
31
+ Object.defineProperty(exports, "gitFileExistsInBranch", { enumerable: true, get: function () { return repo_tools_1.gitFileExistsInBranch; } });
32
+ Object.defineProperty(exports, "gitGetFilesSummary", { enumerable: true, get: function () { return repo_tools_1.gitGetFilesSummary; } });
33
+ Object.defineProperty(exports, "gitGetFileContent", { enumerable: true, get: function () { return repo_tools_1.gitGetFileContent; } });
34
+ Object.defineProperty(exports, "gitGetFilePreview", { enumerable: true, get: function () { return repo_tools_1.gitGetFilePreview; } });
35
+ Object.defineProperty(exports, "gitGetFileHistory", { enumerable: true, get: function () { return repo_tools_1.gitGetFileHistory; } });
36
+ Object.defineProperty(exports, "gitReadFileOutsideRepo", { enumerable: true, get: function () { return repo_tools_1.gitReadFileOutsideRepo; } });
37
+ // Gestion des branches
38
+ Object.defineProperty(exports, "gitGetUnmergedBranchesForFile", { enumerable: true, get: function () { return repo_tools_1.gitGetUnmergedBranchesForFile; } });
39
+ Object.defineProperty(exports, "gitGetAllBranches", { enumerable: true, get: function () { return repo_tools_1.gitGetAllBranches; } });
40
+ Object.defineProperty(exports, "gitGetDiffFiles", { enumerable: true, get: function () { return repo_tools_1.gitGetDiffFiles; } });
41
+ // Git Notes
42
+ Object.defineProperty(exports, "gitReadNote", { enumerable: true, get: function () { return repo_tools_1.gitReadNote; } });
43
+ Object.defineProperty(exports, "gitWriteNote", { enumerable: true, get: function () { return repo_tools_1.gitWriteNote; } });
44
+ Object.defineProperty(exports, "gitDeleteNote", { enumerable: true, get: function () { return repo_tools_1.gitDeleteNote; } });
45
+ var repo_1 = require("./repo");
46
+ Object.defineProperty(exports, "gitInit", { enumerable: true, get: function () { return repo_1.gitInit; } });
47
+ Object.defineProperty(exports, "gitEnsureRepositoryConfiguration", { enumerable: true, get: function () { return repo_1.gitEnsureRepositoryConfiguration; } });
48
+ Object.defineProperty(exports, "gitEnsureRemoteConfiguration", { enumerable: true, get: function () { return repo_1.gitEnsureRemoteConfiguration; } });
49
+ Object.defineProperty(exports, "gitSetupRepository", { enumerable: true, get: function () { return repo_1.gitSetupRepository; } });
50
+ Object.defineProperty(exports, "gitShowConfiguration", { enumerable: true, get: function () { return repo_1.gitShowConfiguration; } });
51
+ Object.defineProperty(exports, "gitCheckConfiguration", { enumerable: true, get: function () { return repo_1.gitCheckConfiguration; } });
52
+ Object.defineProperty(exports, "gitGetBranchHealth", { enumerable: true, get: function () { return repo_1.gitGetBranchHealth; } });
53
+ Object.defineProperty(exports, "gitCreateOrEditFile", { enumerable: true, get: function () { return repo_1.gitCreateOrEditFile; } });
54
+ Object.defineProperty(exports, "gitEditFile", { enumerable: true, get: function () { return repo_1.gitEditFile; } });
55
+ Object.defineProperty(exports, "gitRenameFile", { enumerable: true, get: function () { return repo_1.gitRenameFile; } });
56
+ Object.defineProperty(exports, "gitDeleteFile", { enumerable: true, get: function () { return repo_1.gitDeleteFile; } });
57
+ // === GESTION DES PULL REQUESTS (repo.pr.ts) ===
58
+ var repo_pr_1 = require("./repo.pr");
59
+ // Synchronisation et statut
60
+ Object.defineProperty(exports, "gitSyncPR", { enumerable: true, get: function () { return repo_pr_1.gitSyncPR; } });
61
+ Object.defineProperty(exports, "gitIsPRClosed", { enumerable: true, get: function () { return repo_pr_1.gitIsPRClosed; } });
62
+ Object.defineProperty(exports, "gitIsPRClosedRobust", { enumerable: true, get: function () { return repo_pr_1.gitIsPRClosedRobust; } });
63
+ Object.defineProperty(exports, "gitGetPRMetadata", { enumerable: true, get: function () { return repo_pr_1.gitGetPRMetadata; } });
64
+ Object.defineProperty(exports, "gitGetAllPR", { enumerable: true, get: function () { return repo_pr_1.gitGetAllPR; } });
65
+ Object.defineProperty(exports, "gitGetClosedPRs", { enumerable: true, get: function () { return repo_pr_1.gitGetClosedPRs; } });
66
+ Object.defineProperty(exports, "gitLoadPR", { enumerable: true, get: function () { return repo_pr_1.gitLoadPR; } });
67
+ // Opérations sur les PRs
68
+ Object.defineProperty(exports, "gitPRUpdateComments", { enumerable: true, get: function () { return repo_pr_1.gitPRUpdateComments; } });
69
+ Object.defineProperty(exports, "gitClosePR", { enumerable: true, get: function () { return repo_pr_1.gitClosePR; } });
70
+ Object.defineProperty(exports, "gitClosePRRobust", { enumerable: true, get: function () { return repo_pr_1.gitClosePRRobust; } });
71
+ Object.defineProperty(exports, "gitGetNextPRNumber", { enumerable: true, get: function () { return repo_pr_1.gitGetNextPRNumber; } });
72
+ Object.defineProperty(exports, "gitNewValidationRequest", { enumerable: true, get: function () { return repo_pr_1.gitNewValidationRequest; } });
73
+ Object.defineProperty(exports, "gitNewPR", { enumerable: true, get: function () { return repo_pr_1.gitNewPR; } });
74
+ __exportStar(require("./git.e2e.helper"), exports);
75
+ __exportStar(require("./git.health"), exports);
76
+ __exportStar(require("./git.helper"), exports);