-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathProgram.cs
More file actions
1511 lines (1305 loc) · 73.6 KB
/
Program.cs
File metadata and controls
1511 lines (1305 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using CobolToQuarkusMigration.Helpers;
using CobolToQuarkusMigration.Models;
using CobolToQuarkusMigration.Persistence;
using CobolToQuarkusMigration.Processes;
using CobolToQuarkusMigration.Agents;
using CobolToQuarkusMigration.Agents.Infrastructure;
using CobolToQuarkusMigration.Mcp;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using System.CommandLine;
using Microsoft.Extensions.Logging.Console;
namespace CobolToQuarkusMigration;
/// <summary>
/// Main entry point for the COBOL to Java/C# migration tool.
/// Uses dual-API architecture:
/// - ResponsesApiClient for code agents (gpt-5.1-codex-mini via Responses API)
/// - IChatClient for chat/reports (gpt-5.1-chat via Chat Completions API)
/// </summary>
internal static class Program
{
public static async Task<int> Main(string[] args)
{
// Start live log capture for portal's Live Run Log panel
var logsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Logs");
Directory.CreateDirectory(logsDirectory);
// Only enable live logging for migration runs (not MCP server or conversation modes)
var isMigrationRun = !args.Contains("mcp") && !args.Contains("conversation");
LiveLogWriter? liveLogWriter = null;
if (isMigrationRun)
{
liveLogWriter = LiveLogWriter.Start(logsDirectory);
}
try
{
// Configure logger to write to Stderr to avoid breaking MCP JSON-RPC on Stdout
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Trace;
});
});
var logger = loggerFactory.CreateLogger(nameof(Program));
var fileHelper = new FileHelper(loggerFactory.CreateLogger<FileHelper>());
var settingsHelper = new SettingsHelper(loggerFactory.CreateLogger<SettingsHelper>());
if (!ValidateAndLoadConfiguration())
{
return 1;
}
var rootCommand = BuildRootCommand(loggerFactory, logger, fileHelper, settingsHelper);
return await rootCommand.InvokeAsync(args);
}
finally
{
// Stop live logging and restore console
if (liveLogWriter != null)
{
LiveLogWriter.Stop();
}
}
}
private static RootCommand BuildRootCommand(ILoggerFactory loggerFactory, ILogger logger, FileHelper fileHelper, SettingsHelper settingsHelper)
{
var rootCommand = new RootCommand("COBOL to Java Quarkus Migration Tool (Agent Framework)");
var cobolSourceOption = new Option<string>("--source", "Path to the folder containing COBOL source files and copybooks")
{
Arity = ArgumentArity.ZeroOrOne
};
cobolSourceOption.AddAlias("-s");
rootCommand.AddOption(cobolSourceOption);
var javaOutputOption = new Option<string>("--java-output", () => "output", "Path to the folder for Java output files")
{
Arity = ArgumentArity.ZeroOrOne
};
javaOutputOption.AddAlias("-j");
rootCommand.AddOption(javaOutputOption);
var reverseEngineerOutputOption = new Option<string>("--reverse-engineer-output", () => "output", "Path to the folder for reverse engineering output")
{
Arity = ArgumentArity.ZeroOrOne
};
reverseEngineerOutputOption.AddAlias("-reo");
rootCommand.AddOption(reverseEngineerOutputOption);
var reverseEngineerOnlyOption = new Option<bool>("--reverse-engineer-only", () => false, "Run only reverse engineering (skip Java conversion)")
{
Arity = ArgumentArity.ZeroOrOne
};
reverseEngineerOnlyOption.AddAlias("-reo-only");
rootCommand.AddOption(reverseEngineerOnlyOption);
var skipReverseEngineeringOption = new Option<bool>("--skip-reverse-engineering", () => false, "Skip reverse engineering and run only Java conversion")
{
Arity = ArgumentArity.ZeroOrOne
};
skipReverseEngineeringOption.AddAlias("-skip-re");
rootCommand.AddOption(skipReverseEngineeringOption);
var reuseReOption = new Option<bool>("--reuse-re", () => false, "When combined with --skip-reverse-engineering, loads business logic persisted from the latest previous RE run and injects it into the conversion prompts")
{
Arity = ArgumentArity.ZeroOrOne
};
reuseReOption.AddAlias("-reuse-re");
rootCommand.AddOption(reuseReOption);
var configOption = new Option<string>("--config", () => "Config/appsettings.json", "Path to the configuration file")
{
Arity = ArgumentArity.ZeroOrOne
};
configOption.AddAlias("-c");
rootCommand.AddOption(configOption);
var resumeOption = new Option<bool>("--resume", () => false, "Resume from the last migration run if possible")
{
Arity = ArgumentArity.ZeroOrOne
};
resumeOption.AddAlias("-r");
rootCommand.AddOption(resumeOption);
var conversationCommand = BuildConversationCommand(loggerFactory);
rootCommand.AddCommand(conversationCommand);
var mcpCommand = BuildMcpCommand(loggerFactory, settingsHelper);
rootCommand.AddCommand(mcpCommand);
var reverseEngineerCommand = BuildReverseEngineerCommand(loggerFactory, fileHelper, settingsHelper);
rootCommand.AddCommand(reverseEngineerCommand);
rootCommand.SetHandler(async (string cobolSource, string javaOutput, string reverseEngineerOutput, bool reverseEngineerOnly, bool skipReverseEngineering, bool reuseRe, string configPath, bool resume) =>
{
await RunMigrationAsync(loggerFactory, logger, fileHelper, settingsHelper, cobolSource, javaOutput, reverseEngineerOutput, reverseEngineerOnly, skipReverseEngineering, reuseRe, configPath, resume);
}, cobolSourceOption, javaOutputOption, reverseEngineerOutputOption, reverseEngineerOnlyOption, skipReverseEngineeringOption, reuseReOption, configOption, resumeOption);
return rootCommand;
}
private static Command BuildConversationCommand(ILoggerFactory loggerFactory)
{
var conversationCommand = new Command("conversation", "Generate a readable conversation log from migration logs");
var sessionIdOption = new Option<string>("--session-id", "Specific session ID to generate conversation for (optional)")
{
Arity = ArgumentArity.ZeroOrOne
};
sessionIdOption.AddAlias("-sid");
conversationCommand.AddOption(sessionIdOption);
var logDirOption = new Option<string>("--log-dir", () => "Logs", "Path to the logs directory")
{
Arity = ArgumentArity.ZeroOrOne
};
logDirOption.AddAlias("-ld");
conversationCommand.AddOption(logDirOption);
var liveOption = new Option<bool>("--live", () => false, "Enable live conversation feed that updates in real-time");
liveOption.AddAlias("-l");
conversationCommand.AddOption(liveOption);
conversationCommand.SetHandler(async (string sessionId, string logDir, bool live) =>
{
await GenerateConversationAsync(loggerFactory, sessionId, logDir, live);
}, sessionIdOption, logDirOption, liveOption);
return conversationCommand;
}
private static Command BuildMcpCommand(ILoggerFactory loggerFactory, SettingsHelper settingsHelper)
{
var mcpCommand = new Command("mcp", "Expose migration insights over the Model Context Protocol");
var runIdOption = new Option<int?>("--run-id", () => null, "Specific run ID to expose via MCP (defaults to latest)")
{
Arity = ArgumentArity.ZeroOrOne
};
runIdOption.AddAlias("-r");
mcpCommand.AddOption(runIdOption);
var configOption = new Option<string>("--config", () => "Config/appsettings.json", "Path to the configuration file")
{
Arity = ArgumentArity.ZeroOrOne
};
configOption.AddAlias("-c");
mcpCommand.AddOption(configOption);
mcpCommand.SetHandler(async (int? runId, string configPath) =>
{
await RunMcpServerAsync(loggerFactory, settingsHelper, runId, configPath);
}, runIdOption, configOption);
return mcpCommand;
}
private static Command BuildReverseEngineerCommand(ILoggerFactory loggerFactory, FileHelper fileHelper, SettingsHelper settingsHelper)
{
var reverseEngineerCommand = new Command("reverse-engineer", "Extract business logic from COBOL applications");
var cobolSourceOption = new Option<string>("--source", "Path to the folder containing COBOL source files")
{
Arity = ArgumentArity.ExactlyOne
};
cobolSourceOption.AddAlias("-s");
reverseEngineerCommand.AddOption(cobolSourceOption);
var outputOption = new Option<string>("--output", () => "output", "Path to the output folder")
{
Arity = ArgumentArity.ZeroOrOne
};
outputOption.AddAlias("-o");
reverseEngineerCommand.AddOption(outputOption);
var configOption = new Option<string>("--config", () => "Config/appsettings.json", "Path to the configuration file")
{
Arity = ArgumentArity.ZeroOrOne
};
configOption.AddAlias("-c");
reverseEngineerCommand.AddOption(configOption);
reverseEngineerCommand.SetHandler(async (string cobolSource, string output, string configPath) =>
{
await RunReverseEngineeringAsync(loggerFactory, fileHelper, settingsHelper, cobolSource, output, configPath);
}, cobolSourceOption, outputOption, configOption);
return reverseEngineerCommand;
}
private static async Task GenerateConversationAsync(ILoggerFactory loggerFactory, string sessionId, string logDir, bool live)
{
try
{
var enhancedLogger = new EnhancedLogger(loggerFactory.CreateLogger<EnhancedLogger>());
var logCombiner = new LogCombiner(logDir, enhancedLogger);
Console.WriteLine("🤖 Generating conversation log from migration data...");
string outputPath;
if (live)
{
Console.WriteLine("📡 Starting live conversation feed...");
outputPath = await logCombiner.CreateLiveConversationFeedAsync();
Console.WriteLine($"✅ Live conversation feed created: {outputPath}");
Console.WriteLine("📝 The conversation will update automatically as new logs are generated.");
Console.WriteLine("Press Ctrl+C to stop monitoring.");
await Task.Delay(-1);
}
else
{
outputPath = await logCombiner.CreateConversationNarrativeAsync(sessionId);
Console.WriteLine($"✅ Conversation narrative created: {outputPath}");
if (File.Exists(outputPath))
{
var preview = await File.ReadAllTextAsync(outputPath);
var lines = preview.Split('\n').Take(20).ToArray();
Console.WriteLine("\n📖 Preview of conversation:");
Console.WriteLine("═══════════════════════════════════════");
foreach (var line in lines)
{
Console.WriteLine(line);
}
if (preview.Split('\n').Length > 20)
{
Console.WriteLine("... (and more)");
}
Console.WriteLine("═══════════════════════════════════════");
}
}
}
catch (Exception ex)
{
loggerFactory.CreateLogger(nameof(Program)).LogError(ex, "Error generating conversation log");
Environment.Exit(1);
}
}
private static async Task RunMcpServerAsync(ILoggerFactory loggerFactory, SettingsHelper settingsHelper, int? runId, string configPath)
{
try
{
AppSettings? loadedSettings = await settingsHelper.LoadSettingsAsync<AppSettings>(configPath);
var settings = loadedSettings ?? new AppSettings();
LoadEnvironmentVariables();
OverrideSettingsFromEnvironment(settings);
var databasePath = settings.ApplicationSettings.MigrationDatabasePath;
if (!Path.IsPathRooted(databasePath))
{
databasePath = Path.GetFullPath(databasePath);
}
var repositoryLogger = loggerFactory.CreateLogger<SqliteMigrationRepository>();
var sqliteRepository = new SqliteMigrationRepository(databasePath, repositoryLogger);
await sqliteRepository.InitializeAsync();
// Initialize Neo4j if enabled
Neo4jMigrationRepository? neo4jRepository = null;
var mcpLogger = loggerFactory.CreateLogger(nameof(Program));
if (settings.ApplicationSettings.Neo4j?.Enabled == true)
{
try
{
var neo4jDriver = Neo4j.Driver.GraphDatabase.Driver(
settings.ApplicationSettings.Neo4j.Uri,
Neo4j.Driver.AuthTokens.Basic(
settings.ApplicationSettings.Neo4j.Username,
settings.ApplicationSettings.Neo4j.Password
)
);
var neo4jLogger = loggerFactory.CreateLogger<Neo4jMigrationRepository>();
neo4jRepository = new Neo4jMigrationRepository(neo4jDriver, neo4jLogger);
mcpLogger.LogInformation("Neo4j graph database enabled at {Uri}", settings.ApplicationSettings.Neo4j.Uri);
}
catch (Exception ex)
{
mcpLogger.LogWarning(ex, "Failed to connect to Neo4j, continuing with SQLite only");
}
}
var hybridLogger = loggerFactory.CreateLogger<HybridMigrationRepository>();
var repository = new HybridMigrationRepository(sqliteRepository, neo4jRepository, hybridLogger);
await repository.InitializeAsync();
var targetRunId = runId;
if (!targetRunId.HasValue)
{
var latest = await repository.GetLatestRunAsync();
if (latest is null)
{
Console.Error.WriteLine("No migration runs available in the database. Run the migration process first.");
return;
}
targetRunId = latest.RunId;
}
// Create EnhancedLogger early so it can track ALL API calls
var enhancedLogger = new EnhancedLogger(loggerFactory.CreateLogger<EnhancedLogger>());
// Get API version from environment or default
var apiVersion = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_VERSION") ?? "2025-04-01-preview";
// Create ResponsesApiClient for code agents - Use same logic as RunMigrationAsync
ResponsesApiClient? responsesApiClient = null;
if (!string.IsNullOrEmpty(settings.AISettings.Endpoint) && !string.IsNullOrEmpty(settings.AISettings.DeploymentName))
{
// Force Entra ID (DefaultAzureCredential) by passing empty API Key as requested
responsesApiClient = new ResponsesApiClient(
settings.AISettings.Endpoint,
string.Empty, // Forces DefaultAzureCredential
settings.AISettings.DeploymentName,
loggerFactory.CreateLogger<ResponsesApiClient>(),
enhancedLogger,
profile: settings.CodexProfile,
apiVersion: apiVersion,
rateLimitSafetyFactor: settings.ChunkingSettings.RateLimitSafetyFactor);
mcpLogger.LogInformation("ResponsesApiClient initialized for codex model: {DeploymentName} (Entra ID)", settings.AISettings.DeploymentName);
}
// Create IChatClient for MCP server
IChatClient? chatClient = null;
var chatEndpoint = settings.AISettings?.ChatEndpoint ?? settings.AISettings?.Endpoint;
var chatApiKey = settings.AISettings?.ChatApiKey ?? settings.AISettings?.ApiKey;
var chatDeployment = settings.AISettings?.ChatDeploymentName ?? settings.AISettings?.ChatModelId ?? settings.AISettings?.DeploymentName;
if (!string.IsNullOrEmpty(chatEndpoint) && !string.IsNullOrEmpty(chatDeployment))
{
bool useEntraId = string.IsNullOrEmpty(chatApiKey) || chatApiKey.Contains("your-api-key");
if (useEntraId)
{
chatClient = ChatClientFactory.CreateAzureOpenAIChatClientWithDefaultCredential(chatEndpoint, chatDeployment);
mcpLogger.LogInformation("IChatClient initialized for MCP server with deployment: {Deployment} (Entra ID)", chatDeployment);
}
else if (!string.IsNullOrEmpty(chatApiKey))
{
chatClient = ChatClientFactory.CreateAzureOpenAIChatClient(chatEndpoint, chatApiKey, chatDeployment);
mcpLogger.LogInformation("IChatClient initialized for MCP server with deployment: {Deployment} (API Key)", chatDeployment);
}
}
var serverLogger = loggerFactory.CreateLogger<McpServer>();
var server = new McpServer(repository, targetRunId.Value, serverLogger, settings.AISettings, chatClient, responsesApiClient);
var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, args) =>
{
args.Cancel = true;
cts.Cancel();
};
await server.RunAsync(cts.Token);
}
catch (Exception ex)
{
loggerFactory.CreateLogger(nameof(Program)).LogError(ex, "Error running MCP server");
Environment.Exit(1);
}
}
private static void ConfigureSmartChunking(AppSettings settings, string chatDeployment, ILogger logger)
{
// 1. TRUST THE CONFIGURATION FIRST:
// If the user has explicitly set ContextWindowSize in appsettings.json, use that numeric value
// to determine if we can enable Whole-Program Analysis.
// This decouples the logic from "magic strings" and allows future models to work automatically.
if (settings.AISettings.ContextWindowSize.HasValue)
{
var size = settings.AISettings.ContextWindowSize.Value;
if (size >= 100_000) // 100k+ tokens (covers 128k, 200k, 1M models)
{
// Apply high-context optimization
settings.ChunkingSettings.AutoChunkLineThreshold = 25_000;
settings.ChunkingSettings.AutoChunkCharThreshold = 400_000;
settings.ChunkingSettings.MaxTokensPerChunk = 90_000;
logger.LogInformation("🚀 Optimized Strategy: 'Whole-Program Analysis' enabled based on configured ContextWindowSize ({Size} tokens).", size);
return;
}
}
// 2. FALLBACK TO DETECTION (Legacy/Convenience):
// If no explicit context size is provided, we try to detect known high-context models.
var targetModel = chatDeployment ?? settings.AISettings.ChatModelId ?? settings.AISettings.DeploymentName;
if (!string.IsNullOrEmpty(targetModel))
{
// Detect High-Context Models dynamically from config strings
if (targetModel.Contains("gpt-5", StringComparison.OrdinalIgnoreCase) ||
targetModel.Contains("codex", StringComparison.OrdinalIgnoreCase) ||
targetModel.Contains("gpt-4o", StringComparison.OrdinalIgnoreCase) ||
targetModel.Contains("o1-", StringComparison.OrdinalIgnoreCase) ||
targetModel.Contains("128k", StringComparison.OrdinalIgnoreCase))
{
// Increase transparency for next-gen models:
settings.ChunkingSettings.AutoChunkLineThreshold = 25_000;
settings.ChunkingSettings.AutoChunkCharThreshold = 400_000;
settings.ChunkingSettings.MaxTokensPerChunk = 90_000;
logger.LogInformation("🚀 Next-Gen Model Detected ({Model}). Optimized strategy: 'Whole-Program Analysis' enabled for files up to {NewLines} lines.",
targetModel, settings.ChunkingSettings.AutoChunkLineThreshold);
}
}
}
private static async Task RunMigrationAsync(ILoggerFactory loggerFactory, ILogger logger, FileHelper fileHelper, SettingsHelper settingsHelper, string cobolSource, string javaOutput, string reverseEngineerOutput, bool reverseEngineerOnly, bool skipReverseEngineering, bool reuseRe, string configPath, bool resume)
{
try
{
logger.LogInformation("Loading settings from {ConfigPath}", configPath);
AppSettings? loadedSettings = await settingsHelper.LoadSettingsAsync<AppSettings>(configPath);
var settings = loadedSettings ?? new AppSettings();
LoadEnvironmentVariables();
OverrideSettingsFromEnvironment(settings);
if (string.IsNullOrEmpty(settings.ApplicationSettings.CobolSourceFolder))
{
logger.LogError("COBOL source folder not specified. Use --source option or set in config file.");
Environment.Exit(1);
}
// Output folder validation - check both Java and C# based on target
var targetLanguage = settings.ApplicationSettings.TargetLanguage;
if (targetLanguage == TargetLanguage.CSharp)
{
// For C#, use CSharpOutputFolder if set, otherwise fall back to JavaOutputFolder or default
if (string.IsNullOrEmpty(settings.ApplicationSettings.CSharpOutputFolder) &&
string.IsNullOrEmpty(settings.ApplicationSettings.JavaOutputFolder))
{
settings.ApplicationSettings.CSharpOutputFolder = "output/csharp";
logger.LogInformation("Using default C# output folder: output/csharp");
}
}
else
{
// For Java, require JavaOutputFolder
if (string.IsNullOrEmpty(settings.ApplicationSettings.JavaOutputFolder))
{
logger.LogError("Java output folder not specified. Use --java-output option or set in config file.");
Environment.Exit(1);
}
}
if (string.IsNullOrEmpty(settings.AISettings.Endpoint) ||
string.IsNullOrEmpty(settings.AISettings.DeploymentName))
{
logger.LogError("Azure OpenAI configuration incomplete. Please ensure endpoint and deployment name are configured.");
logger.LogError("You can set them in Config/ai-config.local.env or as environment variables.");
Environment.Exit(1);
}
if (string.IsNullOrEmpty(settings.AISettings.ModelId))
{
logger.LogError("ModelId is not configured. Set AISettings:ModelId in appsettings.json or AZURE_OPENAI_MODEL_ID environment variable.");
Environment.Exit(1);
}
// Create EnhancedLogger early so it can track ALL API calls
var enhancedLogger = new EnhancedLogger(loggerFactory.CreateLogger<EnhancedLogger>());
var chatLogger = new ChatLogger(loggerFactory.CreateLogger<ChatLogger>());
// Get API version from environment or default
var apiVersion = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_VERSION") ?? "2025-04-01-preview";
// Create ResponsesApiClient for code agents (codex model via Responses API)
// gpt-5.1-codex-mini uses Responses API at /openai/responses, NOT Chat Completions
var responsesApiClient = new ResponsesApiClient(
settings.AISettings.Endpoint,
string.Empty, // Forces DefaultAzureCredential
settings.AISettings.DeploymentName,
loggerFactory.CreateLogger<ResponsesApiClient>(),
enhancedLogger,
profile: settings.CodexProfile,
apiVersion: apiVersion,
rateLimitSafetyFactor: settings.ChunkingSettings.RateLimitSafetyFactor); // Pass EnhancedLogger for API call tracking
logger.LogInformation("ResponsesApiClient initialized for codex model: {DeploymentName} (API: {ApiVersion}, Entra ID)",
settings.AISettings.DeploymentName, apiVersion);
// Create IChatClient for chat agents (RE reports, chat via Chat Completions API)
var chatEndpoint = settings.AISettings.ChatEndpoint ?? settings.AISettings.Endpoint;
var chatApiKey = settings.AISettings.ChatApiKey ?? settings.AISettings.ApiKey;
var chatDeployment = settings.AISettings.ChatDeploymentName ?? settings.AISettings.DeploymentName;
IChatClient chatClient;
bool useEntraId = string.IsNullOrEmpty(chatApiKey) || chatApiKey.Contains("your-api-key");
if (useEntraId)
{
chatClient = ChatClientFactory.CreateAzureOpenAIChatClientWithDefaultCredential(chatEndpoint, chatDeployment);
logger.LogInformation("IChatClient initialized for chat model: {ChatDeployment} (Entra ID)", chatDeployment);
}
else
{
chatClient = ChatClientFactory.CreateAzureOpenAIChatClient(chatEndpoint, chatApiKey, chatDeployment);
logger.LogInformation("IChatClient initialized for chat model: {ChatDeployment} (API Key)", chatDeployment);
}
var databasePath = settings.ApplicationSettings.MigrationDatabasePath;
if (!Path.IsPathRooted(databasePath))
{
databasePath = Path.GetFullPath(databasePath);
}
var migrationRepositoryLogger = loggerFactory.CreateLogger<SqliteMigrationRepository>();
var sqliteMigrationRepository = new SqliteMigrationRepository(databasePath, migrationRepositoryLogger);
await sqliteMigrationRepository.InitializeAsync();
// Initialize Neo4j if enabled
Neo4jMigrationRepository? neo4jMigrationRepository = null;
if (settings.ApplicationSettings.Neo4j?.Enabled == true)
{
try
{
var neo4jDriver = Neo4j.Driver.GraphDatabase.Driver(
settings.ApplicationSettings.Neo4j.Uri,
Neo4j.Driver.AuthTokens.Basic(
settings.ApplicationSettings.Neo4j.Username,
settings.ApplicationSettings.Neo4j.Password
)
);
var neo4jLogger = loggerFactory.CreateLogger<Neo4jMigrationRepository>();
neo4jMigrationRepository = new Neo4jMigrationRepository(neo4jDriver, neo4jLogger);
logger.LogInformation("✅ Neo4j graph database connected at {Uri}", settings.ApplicationSettings.Neo4j.Uri);
}
catch (Exception ex)
{
logger.LogWarning(ex, "⚠️ Neo4j connection failed, using SQLite only");
}
}
var hybridLogger = loggerFactory.CreateLogger<HybridMigrationRepository>();
var migrationRepository = new HybridMigrationRepository(sqliteMigrationRepository, neo4jMigrationRepository, hybridLogger);
await migrationRepository.InitializeAsync();
// Cleanup stale runs on startup
if (!resume)
{
await migrationRepository.CleanupStaleRunsAsync();
}
// Holds business logic extracted during reverse engineering to be passed into migration
ReverseEngineeringResult? reverseEngResultForMigration = null;
// Step 1: Run reverse engineering if requested (and not skipped)
if (!skipReverseEngineering || reverseEngineerOnly)
{
// EnhancedLogger and ChatLogger already created above for API tracking
ConfigureSmartChunking(settings, chatDeployment, logger);
// Create orchestrator early so agents can use it
var targetLang = settings.ApplicationSettings.TargetLanguage;
var chunkingOrchestrator = new CobolToQuarkusMigration.Chunking.ChunkingOrchestrator(
settings.ChunkingSettings,
settings.ConversionSettings,
databasePath,
loggerFactory.CreateLogger<CobolToQuarkusMigration.Chunking.ChunkingOrchestrator>(),
targetLang);
// CobolAnalyzerAgent uses Responses API client (codex for code analysis)
var cobolAnalyzerAgent = new CobolAnalyzerAgent(
responsesApiClient,
loggerFactory.CreateLogger<CobolAnalyzerAgent>(),
settings.AISettings.CobolAnalyzerModelId,
enhancedLogger,
chatLogger,
settings: settings);
// BusinessLogicExtractorAgent uses ResponsesApiClient (codex for RE reports)
// This ensures compatibility with gpt-5.2-chat which requires Responses API
var businessLogicExtractorAgent = new BusinessLogicExtractorAgent(
responsesApiClient,
loggerFactory.CreateLogger<BusinessLogicExtractorAgent>(),
chatDeployment,
enhancedLogger,
chatLogger,
chunkingOrchestrator: chunkingOrchestrator,
settings: settings);
// DependencyMapperAgent uses ResponsesApiClient (codex for dependency analysis)
var dependencyMapperAgent = new DependencyMapperAgent(
responsesApiClient,
loggerFactory.CreateLogger<DependencyMapperAgent>(),
settings.AISettings.DependencyMapperModelId ?? settings.AISettings.CobolAnalyzerModelId,
enhancedLogger,
chatLogger,
settings: settings);
// Smart routing: check for large files to decide between chunked vs direct RE
var cobolFiles = await fileHelper.ScanDirectoryForCobolFilesAsync(settings.ApplicationSettings.CobolSourceFolder);
var hasLargeFiles = cobolFiles.Any(f =>
settings.ChunkingSettings.RequiresChunking(f.Content.Length, f.Content.Split('\n').Length));
ReverseEngineeringResult reverseEngResult;
if (hasLargeFiles)
{
// Use ChunkedReverseEngineeringProcess for large files
Console.WriteLine("📦 Large files detected - using smart chunked reverse engineering");
logger.LogInformation("Large files detected, using ChunkedReverseEngineeringProcess");
// chunkingOrchestrator and targetLang initialized in outer scope
var chunkedREProcess = new ChunkedReverseEngineeringProcess(
cobolAnalyzerAgent,
businessLogicExtractorAgent,
dependencyMapperAgent,
fileHelper,
settings.ChunkingSettings,
chunkingOrchestrator,
loggerFactory.CreateLogger<ChunkedReverseEngineeringProcess>(),
enhancedLogger,
databasePath,
migrationRepository);
reverseEngResult = await chunkedREProcess.RunAsync(
settings.ApplicationSettings.CobolSourceFolder,
reverseEngineerOutput,
(status, current, total) =>
{
Console.WriteLine($"{status} - {current}/{total}");
});
}
else
{
// Use standard ReverseEngineeringProcess for small files
Console.WriteLine("⚡ All files below chunking threshold - using direct reverse engineering");
var reverseEngineeringProcess = new ReverseEngineeringProcess(
cobolAnalyzerAgent,
businessLogicExtractorAgent,
dependencyMapperAgent,
fileHelper,
loggerFactory.CreateLogger<ReverseEngineeringProcess>(),
enhancedLogger,
migrationRepository);
reverseEngResult = await reverseEngineeringProcess.RunAsync(
settings.ApplicationSettings.CobolSourceFolder,
reverseEngineerOutput,
(status, current, total) =>
{
Console.WriteLine($"{status} - {current}/{total}");
});
}
if (!reverseEngResult.Success)
{
logger.LogError("Reverse engineering failed: {Error}", reverseEngResult.ErrorMessage);
Environment.Exit(1);
}
// Store reverse engineering result so migration can use the extracted business logic
reverseEngResultForMigration = reverseEngResult;
// If reverse-engineer-only mode, exit here
if (reverseEngineerOnly)
{
Console.WriteLine("Reverse engineering completed successfully. Skipping Java conversion as requested.");
return;
}
}
else
{
// --skip-reverse-engineering: only load persisted business logic when --reuse-re is also set
if (reuseRe)
{
var latestRun = await migrationRepository.GetLatestRunAsync();
if (latestRun != null && latestRun.RunId > 0)
{
var savedLogic = await migrationRepository.GetBusinessLogicAsync(latestRun.RunId);
if (savedLogic.Count > 0)
{
Console.WriteLine($"♻️ Loaded {savedLogic.Count} business logic entries from Run #{latestRun.RunId} (use --reuse-re with a specific run by passing --resume).");
reverseEngResultForMigration = new ReverseEngineeringResult
{
Success = true,
RunId = latestRun.RunId,
BusinessLogicExtracts = savedLogic.ToList()
};
}
else
{
Console.WriteLine($"⚠️ --reuse-re: no persisted business logic found for Run #{latestRun.RunId}. Migration will proceed without business logic context.");
}
}
else
{
Console.WriteLine("⚠️ --reuse-re: no previous run found. Migration will proceed without business logic context.");
}
}
else
{
Console.WriteLine("ℹ️ Skipping reverse engineering. Pass --reuse-re to inject business logic from a previous RE run.");
}
}
// Step 2: Run code conversion (unless reverse-engineer-only mode)
if (!reverseEngineerOnly)
{
// Determine output folder based on target language
var targetLang = settings.ApplicationSettings.TargetLanguage;
var outputFolder = targetLang == TargetLanguage.CSharp
? settings.ApplicationSettings.CSharpOutputFolder
: settings.ApplicationSettings.JavaOutputFolder;
// Ensure output folder has a default value
if (string.IsNullOrEmpty(outputFolder))
{
outputFolder = targetLang == TargetLanguage.CSharp ? "output/csharp" : "output/java";
}
var langName = targetLang == TargetLanguage.CSharp ? "C# .NET" : "Java Quarkus";
// ═══════════════════════════════════════════════════════════════════
// QUALITY GATE: Final verification before migration starts
// ═══════════════════════════════════════════════════════════════════
Console.WriteLine("");
Console.WriteLine("═══════════════════════════════════════════════════════════════════");
Console.WriteLine(" 🔒 QUALITY GATE: PRE-MIGRATION CHECK");
Console.WriteLine("═══════════════════════════════════════════════════════════════════");
Console.WriteLine($" Target Language: {langName}");
Console.WriteLine($" Output Folder: {outputFolder}");
Console.WriteLine($" ENV Variable: TARGET_LANGUAGE={Environment.GetEnvironmentVariable("TARGET_LANGUAGE") ?? "(not set)"}");
Console.WriteLine($" Smart Chunking: ENABLED (auto-routes large files)");
Console.WriteLine($" Chunk Threshold: {settings.ChunkingSettings.AutoChunkCharThreshold:N0} chars / {settings.ChunkingSettings.AutoChunkLineThreshold:N0} lines");
// Verify env var matches what we're about to do
var envLang = Environment.GetEnvironmentVariable("TARGET_LANGUAGE");
if (!string.IsNullOrEmpty(envLang))
{
var expectedCSharp = envLang.Equals("CSharp", StringComparison.OrdinalIgnoreCase) ||
envLang.Equals("C#", StringComparison.OrdinalIgnoreCase);
var actualCSharp = targetLang == TargetLanguage.CSharp;
if (expectedCSharp != actualCSharp)
{
Console.WriteLine($" ❌ MISMATCH DETECTED!");
Console.WriteLine($" ENV says: {(expectedCSharp ? "CSharp" : "Java")}");
Console.WriteLine($" Settings say: {targetLang}");
Console.WriteLine("═══════════════════════════════════════════════════════════════════");
Console.WriteLine("❌ QUALITY GATE FAILED: Language mismatch between env var and settings!");
Console.WriteLine(" This indicates a bug in configuration loading. Aborting.");
Environment.Exit(1);
}
}
Console.WriteLine($" ✅ Quality Gate PASSED");
Console.WriteLine("═══════════════════════════════════════════════════════════════════");
Console.WriteLine("");
Console.WriteLine($"Starting COBOL to {langName} migration with Smart Orchestration...");
Console.WriteLine($"Target language: {langName}");
Console.WriteLine($"Output folder: {outputFolder}");
int? resumeRunId = null;
if (resume)
{
logger.LogInformation("Resume requested. Fetching latest run...");
var latestRun = await migrationRepository.GetLatestRunAsync();
if (latestRun != null && latestRun.Status != "Completed")
{
resumeRunId = latestRun.RunId;
logger.LogInformation("Resuming run ID: {RunId} (Status: {Status})", latestRun.RunId, latestRun.Status);
Console.WriteLine($"🔄 Resuming from Run ID: {latestRun.RunId}");
}
else
{
logger.LogWarning("Resume requested but no active run found. Starting new run.");
Console.WriteLine("⚠️ No resumable run found. Starting new run.");
}
}
// Use SmartMigrationOrchestrator for intelligent file routing
// - Small files → direct MigrationProcess (fast, no chunking overhead)
// - Large files → ChunkedMigrationProcess (preserves ALL code, no truncation)
var smartOrchestrator = new SmartMigrationOrchestrator(
responsesApiClient,
chatClient,
loggerFactory,
fileHelper,
settings,
migrationRepository);
var migrationStats = await smartOrchestrator.RunAsync(
settings.ApplicationSettings.CobolSourceFolder,
outputFolder,
(status, current, total) =>
{
Console.WriteLine($"{status} - {current}/{total}");
},
existingRunId: resumeRunId,
businessLogicExtracts: reverseEngResultForMigration?.BusinessLogicExtracts,
existingDependencyMap: reverseEngResultForMigration?.DependencyMap,
runType: skipReverseEngineering ? "Conversion Only" : "Full Migration");
Console.WriteLine("Migration process completed successfully.");
Console.WriteLine($" 📊 Stats: {migrationStats.TotalFiles} files ({migrationStats.DirectFiles} direct, {migrationStats.ChunkedFiles} chunked)");
if (migrationStats.TotalChunks > 0)
{
Console.WriteLine($" 📦 Total chunks processed: {migrationStats.TotalChunks}");
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error in migration process");
Environment.Exit(1);
}
}
private static void LoadEnvironmentVariables()
{
try
{
string currentDir = Directory.GetCurrentDirectory();
string configDir = Path.Combine(currentDir, "Config");
string localConfigFile = Path.Combine(configDir, "ai-config.local.env");
string templateConfigFile = Path.Combine(configDir, "ai-config.env");
if (File.Exists(localConfigFile))
{
LoadEnvFile(localConfigFile);
}
else
{
Console.WriteLine("💡 Consider creating Config/ai-config.local.env for your personal settings");
Console.WriteLine(" You can copy from Config/ai-config.local.env.example");
}
if (File.Exists(templateConfigFile))
{
LoadEnvFile(templateConfigFile);
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Error loading environment configuration: {ex.Message}");
}
}
private static void LoadEnvFile(string filePath)
{
var rawVars = new Dictionary<string, string>();
foreach (string line in File.ReadAllLines(filePath))
{
string trimmedLine = line.Trim();
if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith('#'))
continue;
var parts = trimmedLine.Split('=', 2);
if (parts.Length == 2)
{
string key = parts[0].Trim();
string value = parts[1].Trim().Trim('"', '\'');
// Store raw value first
rawVars[key] = value;
// Variable Expansion (Basic)
// If value contains $VAR or ${VAR}, try to replace from ALREADY loaded Env vars or current file dictionary
if (value.Contains('$'))
{
value = ExpandVariables(value, rawVars);
}
// CRITICAL: Do NOT overwrite environment variables that are already set
var existingValue = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrEmpty(existingValue))
{
Environment.SetEnvironmentVariable(key, value);
}
else if (key == "TARGET_LANGUAGE")
{
Console.WriteLine($"🔒 Preserving TARGET_LANGUAGE from shell: '{existingValue}' (ignoring config file value: '{value}')");
}
}
}
}
private static string ExpandVariables(string value, Dictionary<string, string> fileVars)
{
// Simple expansion: find $VAR or ${VAR}
// This is not a full bash emulator but handles common cases
// We iterate specifically looking for keys we might know
// 1. Check fileVars (local scope first)
foreach (var kvp in fileVars)
{
value = value.Replace($"${{{kvp.Key}}}", kvp.Value)
.Replace($"${kvp.Key}", kvp.Value);
}
// 2. Check Environment (global scope)
// We don't iterate all env vars (too many), but we could use regex to find substitutions
// For now, let's just handle simple known variable patterns if needed,
// but typically users only reference vars defined earlier in the SAME file or standard ones.
return value;
}
private static void OverrideSettingsFromEnvironment(AppSettings settings)
{
var aiSettings = settings.AISettings ??= new AISettings();
var applicationSettings = settings.ApplicationSettings ??= new ApplicationSettings();
// Primary deployment (for codex models via Responses API)
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
if (!string.IsNullOrEmpty(endpoint))
{
aiSettings.Endpoint = endpoint;
}
var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
if (!string.IsNullOrEmpty(apiKey))
{
aiSettings.ApiKey = apiKey;
}
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME");
if (!string.IsNullOrEmpty(deploymentName))
{
aiSettings.DeploymentName = deploymentName;
}
var modelId = Environment.GetEnvironmentVariable("AZURE_OPENAI_MODEL_ID");
if (!string.IsNullOrEmpty(modelId))
{
aiSettings.ModelId = modelId;
}
// Chat deployment (for gpt-5.1-chat models via Chat Completions API)
var chatEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_CHAT_ENDPOINT");
if (!string.IsNullOrEmpty(chatEndpoint))
{
aiSettings.ChatEndpoint = chatEndpoint;
}
var chatApiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_CHAT_API_KEY");
if (!string.IsNullOrEmpty(chatApiKey))
{
aiSettings.ChatApiKey = chatApiKey;
}
var chatDeploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME");
if (!string.IsNullOrEmpty(chatDeploymentName))
{
aiSettings.ChatDeploymentName = chatDeploymentName;