From ad8a34ac98005e40c0b89bb320151368bb83a18d Mon Sep 17 00:00:00 2001 From: Krystian Mikrut Date: Tue, 3 Mar 2026 23:12:57 +0100 Subject: [PATCH 1/2] setup codex integration --- .../Commands/AgentIntegrationContent.cs | 117 ++++++++++++ AiCodeGraph.Cli/Commands/CommandRegistry.cs | 1 + AiCodeGraph.Cli/Commands/SetupCodexCommand.cs | 170 ++++++++++++++++++ .../Commands/SetupCursorCommand.cs | 85 +-------- AiCodeGraph.Tests/CliCommandTests.cs | 163 +++++++++++++++++ README.md | 9 + 6 files changed, 462 insertions(+), 83 deletions(-) create mode 100644 AiCodeGraph.Cli/Commands/AgentIntegrationContent.cs create mode 100644 AiCodeGraph.Cli/Commands/SetupCodexCommand.cs diff --git a/AiCodeGraph.Cli/Commands/AgentIntegrationContent.cs b/AiCodeGraph.Cli/Commands/AgentIntegrationContent.cs new file mode 100644 index 0000000..c9782e2 --- /dev/null +++ b/AiCodeGraph.Cli/Commands/AgentIntegrationContent.cs @@ -0,0 +1,117 @@ +namespace AiCodeGraph.Cli.Commands; + +internal static class AgentIntegrationContent +{ + public static string GetCursorRuleContent() => @"--- +description: AI Code Graph MCP workflow for C# analysis and edits +alwaysApply: true +--- + +# AI Code Graph Integration + +If `cg_*` MCP tools are available, use them for code-understanding tasks. + +Before editing any method, call `cg_get_context` first (when graph data exists) to review complexity, callers, callees, duplicates, and cluster context. + +Primary tools: +- `cg_get_context` +- `cg_get_hotspots` +- `cg_get_callgraph` +- `cg_get_impact` +- `cg_query` +- `cg_dead_code` + +Secondary tools: +- `cg_token_search`, `cg_semantic_search`, `cg_get_similar` +- `cg_get_duplicates`, `cg_get_clusters`, `cg_export_graph` +- `cg_churn`, `cg_coupling`, `cg_diff`, `cg_get_drift`, `cg_get_tree`, `cg_analyze` + +If the database is missing, run `cg_analyze` first to build `./ai-code-graph/graph.db`. +"; + + public static string GetSharedSkillContent() => @"--- +name: ai-code-graph +description: Guides AI Code Graph workflows for .NET analysis, refactoring, architecture checks, impact analysis, and duplicate detection. Use when users ask about complexity hotspots, blast radius, dead code, coupling, drift, or semantic code lookup. +--- + +# AI Code Graph Skill + +## Quick Start + +1. If graph data is missing, run `cg_analyze` on the solution. +2. Before editing a method, run `cg_get_context`. +3. Use method IDs from results for stable follow-up calls. + +## Before Editing a Method + +Use `cg_get_context` and interpret: +- **Complexity**: If CC > 10, avoid increasing branching/nesting. +- **Callers/Callees**: Estimate blast radius before signature or behavior changes. +- **Duplicates**: Apply the same fix to clone partners when appropriate. +- **Cluster**: Keep changes aligned with the method's intent group. + +Then run: +- `cg_get_impact` for transitive caller impact +- `cg_get_callgraph` for direct relationships + +## Refactoring Workflows + +- **Complexity hotspot review**: `cg_get_hotspots` and prioritize highest CC methods. +- **Dead code cleanup**: `cg_dead_code`, remove or deprecate unreachable methods. +- **Coupling risk scan**: `cg_coupling`, focus on high-instability namespaces/types. +- **Churn risk scan**: `cg_churn`, prioritize high change-frequency x complexity areas. + +## Search Workflows + +- Use `cg_query` first for deterministic graph-based retrieval. +- Use `cg_token_search` for identifier/token overlap lookups. +- Use `cg_semantic_search` as fallback for natural-language intent matching. +- Use `cg_get_similar` to find candidates for consolidation. + +## Architecture Review + +- Use `cg_get_drift` to compare against baseline and detect regressions. +- Use `cg_get_clusters` and `cg_get_duplicates` to inspect intent fragmentation. +- Use `cg_export_graph` for structured downstream analysis. +- For layer and dependency policy checks, run CLI commands: + - `ai-code-graph layers --db ./ai-code-graph/graph.db` + - `ai-code-graph check-deps --db ./ai-code-graph/graph.db` + +## Task-to-Tool Decision Guide + +- **""I need context before changing code""** -> `cg_get_context` +- **""What breaks if I change this?""** -> `cg_get_impact` then `cg_get_callgraph` +- **""Where are risky areas?""** -> `cg_get_hotspots`, `cg_churn`, `cg_coupling` +- **""Can we delete this?""** -> `cg_dead_code` and caller checks +- **""Find code related to this idea""** -> `cg_query`, then `cg_token_search`/`cg_semantic_search` +- **""Are we drifting architecturally?""** -> `cg_get_drift`, `cg_get_clusters`, duplicates review +"; + + public static string GetCodexOpenAiYamlContent() => @"display_name: AI Code Graph +short_description: .NET graph-aware analysis and refactoring workflows. +default_prompt: Use AI Code Graph MCP tools for context before edits, impact analysis, and architecture checks. +"; + + public static string GetAgentsMdSnippet(string dbPath) => $@" +## Auto-Context: Code Graph Integration + +When modifying methods in this codebase, run the context command first if `{dbPath}` exists: + +```bash +ai-code-graph context ""MethodName"" --db {dbPath} +``` + +This returns complexity, callers, callees, cluster membership, and duplicates in one call. Use this information to: +- Avoid increasing complexity of already-complex methods (CC > 10) +- Update callers if you change a method's signature or behavior +- Apply the same fix to duplicates when fixing bugs +- Understand which intent cluster a method belongs to before refactoring + +For broader workflows, prefer MCP tools: +- `cg_get_context`, `cg_get_impact`, `cg_get_callgraph` +- `cg_get_hotspots`, `cg_dead_code`, `cg_coupling`, `cg_churn` +- `cg_query` first, then `cg_token_search` or `cg_semantic_search` as fallback + +To rebuild the graph after significant changes: `ai-code-graph analyze YourSolution.sln` +"; +} diff --git a/AiCodeGraph.Cli/Commands/CommandRegistry.cs b/AiCodeGraph.Cli/Commands/CommandRegistry.cs index 1496e4e..bc0a0b5 100644 --- a/AiCodeGraph.Cli/Commands/CommandRegistry.cs +++ b/AiCodeGraph.Cli/Commands/CommandRegistry.cs @@ -33,6 +33,7 @@ public static RootCommand Build() new McpCommand(), new SetupClaudeCommand(), new SetupCursorCommand(), + new SetupCodexCommand(), new StatusCommand(), new LayersCommand(), new QueryCommand(), diff --git a/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs b/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs new file mode 100644 index 0000000..f5d7aad --- /dev/null +++ b/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs @@ -0,0 +1,170 @@ +using System.CommandLine; +using System.CommandLine.Parsing; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace AiCodeGraph.Cli.Commands; + +public class SetupCodexCommand : ICommandHandler +{ + public Command BuildCommand() + { + var dbOption = new Option("--db") + { + Description = "Path to graph.db used by Codex MCP integration", + DefaultValueFactory = _ => "./ai-code-graph/graph.db" + }; + + var command = new Command("setup-codex", "Scaffold Codex MCP config, AGENTS.md guidance, and skill metadata for AI Code Graph") + { + dbOption + }; + + command.SetAction((parseResult, _) => + { + var dbPath = parseResult.GetValue(dbOption) ?? "./ai-code-graph/graph.db"; + var created = new List(); + var currentDir = Directory.GetCurrentDirectory(); + + var codexDir = Path.Combine(currentDir, ".codex"); + var skillDir = Path.Combine(codexDir, "skills", "ai-code-graph"); + var agentsDir = Path.Combine(skillDir, "agents"); + + Directory.CreateDirectory(codexDir); + Directory.CreateDirectory(skillDir); + Directory.CreateDirectory(agentsDir); + + CreateFileIfMissing(skillDir, "SKILL.md", AgentIntegrationContent.GetSharedSkillContent(), created); + CreateFileIfMissing(agentsDir, "openai.yaml", AgentIntegrationContent.GetCodexOpenAiYamlContent(), created); + + EnsureMcpConfig(currentDir, dbPath, created); + EnsureAgentsMd(currentDir, dbPath, created); + + if (created.Count > 0) + { + Console.WriteLine("Codex integration set up:"); + foreach (var path in created) + { + Console.WriteLine($" + {Path.GetRelativePath(currentDir, path)}"); + } + + Console.WriteLine(); + Console.WriteLine("Next steps:"); + Console.WriteLine(" 1. Run `ai-code-graph analyze YourSolution.sln` to build graph.db"); + Console.WriteLine(" 2. Ensure your Codex client loads `.mcp.json` for MCP server discovery"); + Console.WriteLine(" 3. Ask the agent to use AI Code Graph context before edits"); + } + else + { + Console.WriteLine("All Codex integration files already exist. Nothing to do."); + } + + return Task.CompletedTask; + }); + + return command; + } + + private static void EnsureMcpConfig(string currentDir, string dbPath, List created) + { + var mcpPath = Path.Combine(currentDir, ".mcp.json"); + var serverNode = new JsonObject + { + ["type"] = "stdio", + ["command"] = "ai-code-graph", + ["args"] = new JsonArray("mcp", "--db", dbPath) + }; + + if (!File.Exists(mcpPath)) + { + var root = new JsonObject + { + ["mcpServers"] = new JsonObject + { + ["ai-code-graph"] = serverNode + } + }; + + File.WriteAllText(mcpPath, root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + created.Add(mcpPath); + return; + } + + try + { + var root = JsonNode.Parse(File.ReadAllText(mcpPath)) as JsonObject; + if (root == null) + { + Console.WriteLine("Warning: .mcp.json is not a JSON object. Skipping MCP update."); + return; + } + + var servers = root["mcpServers"] as JsonObject; + if (servers == null) + { + servers = new JsonObject(); + root["mcpServers"] = servers; + } + + var hasServer = servers.ContainsKey("ai-code-graph"); + var existingServer = hasServer ? servers["ai-code-graph"] : null; + var shouldWrite = false; + + if (!hasServer) + { + servers["ai-code-graph"] = serverNode; + shouldWrite = true; + } + else if (existingServer is not JsonObject existingServerObject) + { + servers["ai-code-graph"] = serverNode; + shouldWrite = true; + } + else if (!JsonNode.DeepEquals(existingServerObject, serverNode)) + { + servers["ai-code-graph"] = serverNode; + shouldWrite = true; + } + + if (shouldWrite) + { + File.WriteAllText(mcpPath, root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + created.Add(mcpPath + " (updated)"); + } + } + catch (JsonException) + { + Console.WriteLine("Warning: failed to parse .mcp.json. Skipping MCP update."); + } + } + + private static void EnsureAgentsMd(string currentDir, string dbPath, List created) + { + var agentsPath = Path.Combine(currentDir, "AGENTS.md"); + var snippet = AgentIntegrationContent.GetAgentsMdSnippet(dbPath); + + if (File.Exists(agentsPath)) + { + var existing = File.ReadAllText(agentsPath); + if (!existing.Contains("Auto-Context: Code Graph Integration")) + { + File.AppendAllText(agentsPath, snippet); + created.Add(agentsPath + " (appended)"); + } + return; + } + + File.WriteAllText(agentsPath, $"# Agent Instructions\n{snippet}"); + created.Add(agentsPath); + } + + private static void CreateFileIfMissing(string dir, string filename, string content, List created) + { + var path = Path.Combine(dir, filename); + if (!File.Exists(path)) + { + File.WriteAllText(path, content); + created.Add(path); + } + } +} diff --git a/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs b/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs index e41c47f..8376955 100644 --- a/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs +++ b/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs @@ -145,88 +145,7 @@ private static void CreateFileIfMissing(string dir, string filename, string cont } } - private static string GetRuleContent() => @"--- -description: AI Code Graph MCP workflow for C# analysis and edits -alwaysApply: true ---- + private static string GetRuleContent() => AgentIntegrationContent.GetCursorRuleContent(); -# AI Code Graph Integration - -If `cg_*` MCP tools are available, use them for code-understanding tasks. - -Before editing any method, call `cg_get_context` first (when graph data exists) to review complexity, callers, callees, duplicates, and cluster context. - -Primary tools: -- `cg_get_context` -- `cg_get_hotspots` -- `cg_get_callgraph` -- `cg_get_impact` -- `cg_query` -- `cg_dead_code` - -Secondary tools: -- `cg_token_search`, `cg_semantic_search`, `cg_get_similar` -- `cg_get_duplicates`, `cg_get_clusters`, `cg_export_graph` -- `cg_churn`, `cg_coupling`, `cg_diff`, `cg_get_drift`, `cg_get_tree`, `cg_analyze` - -If the database is missing, run `cg_analyze` first to build `./ai-code-graph/graph.db`. -"; - - private static string GetSkillContent() => @"--- -name: ai-code-graph -description: Guides AI Code Graph workflows for .NET analysis, refactoring, architecture checks, impact analysis, and duplicate detection. Use when users ask about complexity hotspots, blast radius, dead code, coupling, drift, or semantic code lookup. ---- - -# AI Code Graph Skill - -## Quick Start - -1. If graph data is missing, run `cg_analyze` on the solution. -2. Before editing a method, run `cg_get_context`. -3. Use method IDs from results for stable follow-up calls. - -## Before Editing a Method - -Use `cg_get_context` and interpret: -- **Complexity**: If CC > 10, avoid increasing branching/nesting. -- **Callers/Callees**: Estimate blast radius before signature or behavior changes. -- **Duplicates**: Apply the same fix to clone partners when appropriate. -- **Cluster**: Keep changes aligned with the method's intent group. - -Then run: -- `cg_get_impact` for transitive caller impact -- `cg_get_callgraph` for direct relationships - -## Refactoring Workflows - -- **Complexity hotspot review**: `cg_get_hotspots` and prioritize highest CC methods. -- **Dead code cleanup**: `cg_dead_code`, remove or deprecate unreachable methods. -- **Coupling risk scan**: `cg_coupling`, focus on high-instability namespaces/types. -- **Churn risk scan**: `cg_churn`, prioritize high change-frequency x complexity areas. - -## Search Workflows - -- Use `cg_query` first for deterministic graph-based retrieval. -- Use `cg_token_search` for identifier/token overlap lookups. -- Use `cg_semantic_search` as fallback for natural-language intent matching. -- Use `cg_get_similar` to find candidates for consolidation. - -## Architecture Review - -- Use `cg_get_drift` to compare against baseline and detect regressions. -- Use `cg_get_clusters` and `cg_get_duplicates` to inspect intent fragmentation. -- Use `cg_export_graph` for structured downstream analysis. -- For layer and dependency policy checks, run CLI commands: - - `ai-code-graph layers --db ./ai-code-graph/graph.db` - - `ai-code-graph check-deps --db ./ai-code-graph/graph.db` - -## Task-to-Tool Decision Guide - -- **""I need context before changing code""** -> `cg_get_context` -- **""What breaks if I change this?""** -> `cg_get_impact` then `cg_get_callgraph` -- **""Where are risky areas?""** -> `cg_get_hotspots`, `cg_churn`, `cg_coupling` -- **""Can we delete this?""** -> `cg_dead_code` and caller checks -- **""Find code related to this idea""** -> `cg_query`, then `cg_token_search`/`cg_semantic_search` -- **""Are we drifting architecturally?""** -> `cg_get_drift`, `cg_get_clusters`, duplicates review -"; + private static string GetSkillContent() => AgentIntegrationContent.GetSharedSkillContent(); } diff --git a/AiCodeGraph.Tests/CliCommandTests.cs b/AiCodeGraph.Tests/CliCommandTests.cs index 1651a4b..911488b 100644 --- a/AiCodeGraph.Tests/CliCommandTests.cs +++ b/AiCodeGraph.Tests/CliCommandTests.cs @@ -358,4 +358,167 @@ await File.WriteAllTextAsync( Assert.NotNull(servers["ai-code-graph"]); Assert.Equal("./inserted/graph.db", servers["ai-code-graph"]!["args"]!.AsArray()[2]!.GetValue()); } + + [Fact] + public async Task SetupCodexCommand_CleanWorkspace_CreatesScaffoldFiles() + { + var workspace = Path.Combine(TempDir, "workspace-codex-create"); + Directory.CreateDirectory(workspace); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./codex/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains(Path.Combine(".codex", "skills", "ai-code-graph", "SKILL.md"), output); + Assert.Contains(Path.Combine(".codex", "skills", "ai-code-graph", "agents", "openai.yaml"), output); + Assert.Contains(".mcp.json", output); + Assert.Contains("AGENTS.md", output); + + var skillPath = Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "SKILL.md"); + var metadataPath = Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents", "openai.yaml"); + var mcpPath = Path.Combine(workspace, ".mcp.json"); + var agentsPath = Path.Combine(workspace, "AGENTS.md"); + + Assert.True(File.Exists(skillPath)); + Assert.True(File.Exists(metadataPath)); + Assert.True(File.Exists(mcpPath)); + Assert.True(File.Exists(agentsPath)); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var args = root["mcpServers"]!["ai-code-graph"]!["args"]!.AsArray(); + Assert.Equal("mcp", args[0]!.GetValue()); + Assert.Equal("--db", args[1]!.GetValue()); + Assert.Equal("./codex/graph.db", args[2]!.GetValue()); + + var agentsContent = await File.ReadAllTextAsync(agentsPath); + Assert.Contains("Auto-Context: Code Graph Integration", agentsContent); + Assert.Contains("./codex/graph.db", agentsContent); + } + + [Fact] + public async Task SetupCodexCommand_WithExistingServer_UpdatesDbPath() + { + var workspace = Path.Combine(TempDir, "workspace-codex-update"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents")); + + var mcpPath = Path.Combine(workspace, ".mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./old/graph.db"] + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "SKILL.md"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents", "openai.yaml"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, "AGENTS.md"), "# Agent Instructions\n"); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./new/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains(".mcp.json (updated)", output); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var args = root["mcpServers"]!["ai-code-graph"]!["args"]!.AsArray(); + Assert.Equal("mcp", args[0]!.GetValue()); + Assert.Equal("--db", args[1]!.GetValue()); + Assert.Equal("./new/graph.db", args[2]!.GetValue()); + } + + [Fact] + public async Task SetupCodexCommand_WithMatchingInputs_NoChanges() + { + var workspace = Path.Combine(TempDir, "workspace-codex-noop"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents")); + + var mcpPath = Path.Combine(workspace, ".mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./same/graph.db"] + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "SKILL.md"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents", "openai.yaml"), "existing"); + await File.WriteAllTextAsync( + Path.Combine(workspace, "AGENTS.md"), + """ + # Agent Instructions + + ## Auto-Context: Code Graph Integration + already present + """); + + var mcpBefore = await File.ReadAllTextAsync(mcpPath); + var agentsBefore = await File.ReadAllTextAsync(Path.Combine(workspace, "AGENTS.md")); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./same/graph.db", workingDirectory: workspace); + + var mcpAfter = await File.ReadAllTextAsync(mcpPath); + var agentsAfter = await File.ReadAllTextAsync(Path.Combine(workspace, "AGENTS.md")); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains("Nothing to do.", output); + Assert.Equal(mcpBefore, mcpAfter); + Assert.Equal(agentsBefore, agentsAfter); + } + + [Fact] + public async Task SetupCodexCommand_WithOtherServers_PreservesAndAddsAiCodeGraph() + { + var workspace = Path.Combine(TempDir, "workspace-codex-merge"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents")); + + var mcpPath = Path.Combine(workspace, ".mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "other-server": { + "type": "stdio", + "command": "other-tool", + "args": ["run"] + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "SKILL.md"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents", "openai.yaml"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, "AGENTS.md"), "# Agent Instructions\n"); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./merged/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains(".mcp.json (updated)", output); + Assert.Contains("AGENTS.md (appended)", output); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var servers = root["mcpServers"]!.AsObject(); + Assert.NotNull(servers["other-server"]); + Assert.NotNull(servers["ai-code-graph"]); + Assert.Equal("./merged/graph.db", servers["ai-code-graph"]!["args"]!.AsArray()[2]!.GetValue()); + } } diff --git a/README.md b/README.md index 28672a6..026a626 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,15 @@ ai-code-graph setup-cursor Creates `.cursor/mcp.json`, `.cursor/rules/ai-code-graph.mdc`, and `.cursor/skills/ai-code-graph/SKILL.md`. +### Codex + +```bash +# One-command setup +ai-code-graph setup-codex +``` + +Creates `.codex/skills/ai-code-graph/SKILL.md`, `.codex/skills/ai-code-graph/agents/openai.yaml`, `.mcp.json`, and `AGENTS.md` integration guidance. + ### MCP Server ```bash From bad464c8bda89c2db8d6253fdd6f8d9346992952 Mon Sep 17 00:00:00 2001 From: Krystian Mikrut Date: Wed, 4 Mar 2026 13:57:00 +0100 Subject: [PATCH 2/2] snags --- AiCodeGraph.Cli/Commands/SetupCodexCommand.cs | 101 +++++++++++- .../Commands/SetupCursorCommand.cs | 82 +++++++++- AiCodeGraph.Tests/CliCommandTests.cs | 149 ++++++++++++++++-- 3 files changed, 315 insertions(+), 17 deletions(-) diff --git a/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs b/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs index f5d7aad..8a26e0c 100644 --- a/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs +++ b/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs @@ -120,9 +120,8 @@ private static void EnsureMcpConfig(string currentDir, string dbPath, List= 0 ? nextHeaderIndex + 1 : existing.Length; + + var currentSection = existing[sectionIndex..sectionEnd]; + if (!string.Equals(currentSection.Trim(), replacement.Trim(), StringComparison.Ordinal)) + { + var updated = existing[..sectionIndex] + replacement + existing[sectionEnd..]; + File.WriteAllText(agentsPath, updated); + created.Add(agentsPath + " (updated)"); + } + } + return; } @@ -167,4 +183,83 @@ private static void CreateFileIfMissing(string dir, string filename, string cont created.Add(path); } } + + private static bool MergeMcpServer(JsonObject existingServerObject, string dbPath) + { + var changed = false; + + if (existingServerObject["type"] == null) + { + existingServerObject["type"] = "stdio"; + changed = true; + } + + if (existingServerObject["command"] == null) + { + existingServerObject["command"] = "ai-code-graph"; + changed = true; + } + + if (existingServerObject["args"] is not JsonArray args) + { + existingServerObject["args"] = new JsonArray("mcp", "--db", dbPath); + return true; + } + + var commandIsAiCodeGraph = NodeEqualsString(existingServerObject["command"], "ai-code-graph"); + var hasMcp = false; + for (var i = 0; i < args.Count; i++) + { + if (NodeEqualsString(args[i], "mcp")) + { + hasMcp = true; + break; + } + } + + if (commandIsAiCodeGraph && !hasMcp) + { + args.Insert(0, "mcp"); + changed = true; + } + + var dbFlagIndex = -1; + for (var i = 0; i < args.Count; i++) + { + if (NodeEqualsString(args[i], "--db")) + { + dbFlagIndex = i; + break; + } + } + + if (dbFlagIndex >= 0) + { + if (dbFlagIndex + 1 >= args.Count) + { + args.Add(dbPath); + changed = true; + } + else if (!NodeEqualsString(args[dbFlagIndex + 1], dbPath)) + { + args[dbFlagIndex + 1] = dbPath; + changed = true; + } + } + else + { + args.Add("--db"); + args.Add(dbPath); + changed = true; + } + + return changed; + } + + private static bool NodeEqualsString(JsonNode? node, string expected) + { + return node is JsonValue valueNode && + valueNode.TryGetValue(out var value) && + string.Equals(value, expected, StringComparison.Ordinal); + } } diff --git a/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs b/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs index 8376955..c662037 100644 --- a/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs +++ b/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs @@ -117,9 +117,8 @@ private static void EnsureCursorMcpConfig(string cursorDir, string dbPath, List< servers["ai-code-graph"] = serverNode; shouldWrite = true; } - else if (!JsonNode.DeepEquals(existingServerObject, serverNode)) + else if (MergeMcpServer(existingServerObject, dbPath)) { - servers["ai-code-graph"] = serverNode; shouldWrite = true; } @@ -148,4 +147,83 @@ private static void CreateFileIfMissing(string dir, string filename, string cont private static string GetRuleContent() => AgentIntegrationContent.GetCursorRuleContent(); private static string GetSkillContent() => AgentIntegrationContent.GetSharedSkillContent(); + + private static bool MergeMcpServer(JsonObject existingServerObject, string dbPath) + { + var changed = false; + + if (existingServerObject["type"] == null) + { + existingServerObject["type"] = "stdio"; + changed = true; + } + + if (existingServerObject["command"] == null) + { + existingServerObject["command"] = "ai-code-graph"; + changed = true; + } + + if (existingServerObject["args"] is not JsonArray args) + { + existingServerObject["args"] = new JsonArray("mcp", "--db", dbPath); + return true; + } + + var commandIsAiCodeGraph = NodeEqualsString(existingServerObject["command"], "ai-code-graph"); + var hasMcp = false; + for (var i = 0; i < args.Count; i++) + { + if (NodeEqualsString(args[i], "mcp")) + { + hasMcp = true; + break; + } + } + + if (commandIsAiCodeGraph && !hasMcp) + { + args.Insert(0, "mcp"); + changed = true; + } + + var dbFlagIndex = -1; + for (var i = 0; i < args.Count; i++) + { + if (NodeEqualsString(args[i], "--db")) + { + dbFlagIndex = i; + break; + } + } + + if (dbFlagIndex >= 0) + { + if (dbFlagIndex + 1 >= args.Count) + { + args.Add(dbPath); + changed = true; + } + else if (!NodeEqualsString(args[dbFlagIndex + 1], dbPath)) + { + args[dbFlagIndex + 1] = dbPath; + changed = true; + } + } + else + { + args.Add("--db"); + args.Add(dbPath); + changed = true; + } + + return changed; + } + + private static bool NodeEqualsString(JsonNode? node, string expected) + { + return node is JsonValue valueNode && + valueNode.TryGetValue(out var value) && + string.Equals(value, expected, StringComparison.Ordinal); + } } diff --git a/AiCodeGraph.Tests/CliCommandTests.cs b/AiCodeGraph.Tests/CliCommandTests.cs index 911488b..1038eec 100644 --- a/AiCodeGraph.Tests/CliCommandTests.cs +++ b/AiCodeGraph.Tests/CliCommandTests.cs @@ -359,6 +359,53 @@ await File.WriteAllTextAsync( Assert.Equal("./inserted/graph.db", servers["ai-code-graph"]!["args"]!.AsArray()[2]!.GetValue()); } + [Fact] + public async Task SetupCursorCommand_WithCustomServerFields_PreservesFieldsWhenUpdatingDbPath() + { + var workspace = Path.Combine(TempDir, "workspace-cursor-custom-fields"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "rules")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph")); + + var mcpPath = Path.Combine(workspace, ".cursor", "mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./old/graph.db", "--trace"], + "env": { "ASPNETCORE_ENVIRONMENT": "Development" }, + "cwd": "./tools", + "wrapperOptions": { "retry": 3 } + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "rules", "ai-code-graph.mdc"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph", "SKILL.md"), "existing"); + + var (exitCode, output, error) = await RunCliAsync("setup-cursor --db ./new/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains($"{Path.Combine(".cursor", "mcp.json")} (updated)", output); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var server = root["mcpServers"]!["ai-code-graph"]!.AsObject(); + var args = server["args"]!.AsArray(); + + Assert.Equal("./new/graph.db", args[2]!.GetValue()); + Assert.Equal("--trace", args[3]!.GetValue()); + Assert.Equal("Development", server["env"]!["ASPNETCORE_ENVIRONMENT"]!.GetValue()); + Assert.Equal("./tools", server["cwd"]!.GetValue()); + Assert.Equal(3, server["wrapperOptions"]!["retry"]!.GetValue()); + } + [Fact] public async Task SetupCodexCommand_CleanWorkspace_CreatesScaffoldFiles() { @@ -439,6 +486,31 @@ public async Task SetupCodexCommand_WithMatchingInputs_NoChanges() { var workspace = Path.Combine(TempDir, "workspace-codex-noop"); Directory.CreateDirectory(workspace); + var firstRun = await RunCliAsync("setup-codex --db ./same/graph.db", workingDirectory: workspace); + Assert.Equal(0, firstRun.ExitCode); + Assert.True(string.IsNullOrWhiteSpace(firstRun.Error)); + + var mcpPath = Path.Combine(workspace, ".mcp.json"); + var mcpBefore = await File.ReadAllTextAsync(mcpPath); + var agentsBefore = await File.ReadAllTextAsync(Path.Combine(workspace, "AGENTS.md")); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./same/graph.db", workingDirectory: workspace); + + var mcpAfter = await File.ReadAllTextAsync(mcpPath); + var agentsAfter = await File.ReadAllTextAsync(Path.Combine(workspace, "AGENTS.md")); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains("Nothing to do.", output); + Assert.Equal(mcpBefore, mcpAfter); + Assert.Equal(agentsBefore, agentsAfter); + } + + [Fact] + public async Task SetupCodexCommand_WithCustomServerFields_PreservesFieldsWhenUpdatingDbPath() + { + var workspace = Path.Combine(TempDir, "workspace-codex-custom-fields"); + Directory.CreateDirectory(workspace); Directory.CreateDirectory(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents")); var mcpPath = Path.Combine(workspace, ".mcp.json"); @@ -450,36 +522,89 @@ await File.WriteAllTextAsync( "ai-code-graph": { "type": "stdio", "command": "ai-code-graph", - "args": ["mcp", "--db", "./same/graph.db"] + "args": ["mcp", "--db", "./old/graph.db", "--trace"], + "env": { "ASPNETCORE_ENVIRONMENT": "Development" }, + "cwd": "./tools", + "wrapperOptions": { "retry": 3 } } } } """); + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "SKILL.md"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents", "openai.yaml"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, "AGENTS.md"), "# Agent Instructions\n"); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./new/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains(".mcp.json (updated)", output); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var server = root["mcpServers"]!["ai-code-graph"]!.AsObject(); + var args = server["args"]!.AsArray(); + + Assert.Equal("./new/graph.db", args[2]!.GetValue()); + Assert.Equal("--trace", args[3]!.GetValue()); + Assert.Equal("Development", server["env"]!["ASPNETCORE_ENVIRONMENT"]!.GetValue()); + Assert.Equal("./tools", server["cwd"]!.GetValue()); + Assert.Equal(3, server["wrapperOptions"]!["retry"]!.GetValue()); + } + + [Fact] + public async Task SetupCodexCommand_WithExistingAutoContextSection_UpdatesDbPath() + { + var workspace = Path.Combine(TempDir, "workspace-codex-agents-update"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents")); + await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "SKILL.md"), "existing"); await File.WriteAllTextAsync(Path.Combine(workspace, ".codex", "skills", "ai-code-graph", "agents", "openai.yaml"), "existing"); await File.WriteAllTextAsync( - Path.Combine(workspace, "AGENTS.md"), + Path.Combine(workspace, ".mcp.json"), + """ + { + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./new/graph.db"] + } + } + } + """); + + var agentsPath = Path.Combine(workspace, "AGENTS.md"); + await File.WriteAllTextAsync( + agentsPath, """ # Agent Instructions ## Auto-Context: Code Graph Integration - already present - """); - var mcpBefore = await File.ReadAllTextAsync(mcpPath); - var agentsBefore = await File.ReadAllTextAsync(Path.Combine(workspace, "AGENTS.md")); + When modifying methods in this codebase, run the context command first if `./old/graph.db` exists: - var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./same/graph.db", workingDirectory: workspace); + ```bash + ai-code-graph context "MethodName" --db ./old/graph.db + ``` - var mcpAfter = await File.ReadAllTextAsync(mcpPath); - var agentsAfter = await File.ReadAllTextAsync(Path.Combine(workspace, "AGENTS.md")); + ## OtherSection + keep this + """); + + var (exitCode, output, error) = await RunCliAsync("setup-codex --db ./new/graph.db", workingDirectory: workspace); Assert.Equal(0, exitCode); Assert.True(string.IsNullOrWhiteSpace(error)); - Assert.Contains("Nothing to do.", output); - Assert.Equal(mcpBefore, mcpAfter); - Assert.Equal(agentsBefore, agentsAfter); + Assert.Contains("AGENTS.md (updated)", output); + + var updated = await File.ReadAllTextAsync(agentsPath); + Assert.DoesNotContain("./old/graph.db", updated); + Assert.Contains("./new/graph.db", updated); + Assert.Contains("## OtherSection", updated); + var sectionCount = updated.Split("## Auto-Context: Code Graph Integration").Length - 1; + Assert.Equal(1, sectionCount); } [Fact]