| 1 | #nullable enable |
| 2 | using AgentNotes.Core; |
| 3 | using CascadeIDE.Models; |
| 4 | |
| 5 | namespace CascadeIDE.Services; |
| 6 | |
| 7 | /// <summary> |
| 8 | /// In-proc init of <see cref="AgentNotesRuntime"/> from <see cref="AgentNotesSettings.ConfigPath"/> (SSOT with MCP <c>--config</c>). |
| 9 | /// </summary> |
| 10 | internal static class AgentNotesRuntimeLoader |
| 11 | { |
| 12 | private static readonly object Gate = new(); |
| 13 | private static string? s_lastConfigPath; |
| 14 | private static string? s_loadError; |
| 15 | |
| 16 | public static string? LastLoadError => Volatile.Read(ref s_loadError); |
| 17 | |
| 18 | public static bool EnsureInitialized(CascadeIdeSettings settings) |
| 19 | { |
| 20 | var configPath = ResolveConfigPath(settings); |
| 21 | if (configPath is null) |
| 22 | { |
| 23 | lock (Gate) |
| 24 | { |
| 25 | AgentNotesRuntime.ClearConfiguration(); |
| 26 | s_lastConfigPath = null; |
| 27 | s_loadError = null; |
| 28 | } |
| 29 | |
| 30 | return false; |
| 31 | } |
| 32 | |
| 33 | lock (Gate) |
| 34 | { |
| 35 | if (s_lastConfigPath == configPath && AgentNotesRuntime.IsConfigured) |
| 36 | return true; |
| 37 | |
| 38 | try |
| 39 | { |
| 40 | var local = LocalSettingsLoader.Load(configPath); |
| 41 | AgentNotesRuntime.Initialize(local, configPath); |
| 42 | s_lastConfigPath = configPath; |
| 43 | s_loadError = null; |
| 44 | return true; |
| 45 | } |
| 46 | catch (Exception ex) |
| 47 | { |
| 48 | s_loadError = ex.Message; |
| 49 | AgentNotesRuntime.ClearConfiguration(); |
| 50 | s_lastConfigPath = null; |
| 51 | return false; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// <summary>Absolute path to agent-notes TOML from settings (may be missing on disk).</summary> |
| 57 | public static string? ResolveConfigPath(CascadeIdeSettings settings) |
| 58 | { |
| 59 | var raw = settings.AgentNotes.ResolveConfigPath().Trim(); |
| 60 | if (raw.Length == 0) |
| 61 | return null; |
| 62 | |
| 63 | return Path.IsPathRooted(raw) |
| 64 | ? Path.GetFullPath(raw) |
| 65 | : Path.GetFullPath(Path.Combine(SettingsService.GetSettingsDirectory(), raw)); |
| 66 | } |
| 67 | |
| 68 | /// <summary>Clears loader cache and <see cref="AgentNotesRuntime"/> (tests and config unload).</summary> |
| 69 | public static void Reset() |
| 70 | { |
| 71 | lock (Gate) |
| 72 | { |
| 73 | AgentNotesRuntime.ClearConfiguration(); |
| 74 | s_lastConfigPath = null; |
| 75 | s_loadError = null; |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |