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..8a26e0c --- /dev/null +++ b/AiCodeGraph.Cli/Commands/SetupCodexCommand.cs @@ -0,0 +1,265 @@ +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 (MergeMcpServer(existingServerObject, dbPath)) + { + 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); + const string sectionHeader = "## Auto-Context: Code Graph Integration"; + + if (File.Exists(agentsPath)) + { + var existing = File.ReadAllText(agentsPath); + var sectionIndex = existing.IndexOf(sectionHeader, StringComparison.Ordinal); + if (sectionIndex < 0) + { + File.AppendAllText(agentsPath, snippet); + created.Add(agentsPath + " (appended)"); + } + else + { + var replacement = snippet.TrimStart('\r', '\n'); + var nextHeaderIndex = existing.IndexOf("\n## ", sectionIndex + sectionHeader.Length, StringComparison.Ordinal); + var sectionEnd = nextHeaderIndex >= 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; + } + + 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); + } + } + + 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 e41c47f..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; } @@ -145,88 +144,86 @@ 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 ---- - -# 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 + private static string GetRuleContent() => AgentIntegrationContent.GetCursorRuleContent(); -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. + private static string GetSkillContent() => AgentIntegrationContent.GetSharedSkillContent(); -## 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. + private static bool MergeMcpServer(JsonObject existingServerObject, string dbPath) + { + var changed = false; -Then run: -- `cg_get_impact` for transitive caller impact -- `cg_get_callgraph` for direct relationships + if (existingServerObject["type"] == null) + { + existingServerObject["type"] = "stdio"; + changed = true; + } -## Refactoring Workflows + if (existingServerObject["command"] == null) + { + existingServerObject["command"] = "ai-code-graph"; + changed = true; + } -- **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. + if (existingServerObject["args"] is not JsonArray args) + { + existingServerObject["args"] = new JsonArray("mcp", "--db", dbPath); + return true; + } -## Search Workflows + 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; + } + } -- 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. + if (commandIsAiCodeGraph && !hasMcp) + { + args.Insert(0, "mcp"); + changed = true; + } -## Architecture Review + var dbFlagIndex = -1; + for (var i = 0; i < args.Count; i++) + { + if (NodeEqualsString(args[i], "--db")) + { + dbFlagIndex = i; + break; + } + } -- 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` + 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; + } -## Task-to-Tool Decision Guide + return changed; + } -- **""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 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 1651a4b..1038eec 100644 --- a/AiCodeGraph.Tests/CliCommandTests.cs +++ b/AiCodeGraph.Tests/CliCommandTests.cs @@ -358,4 +358,292 @@ 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 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() + { + 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); + 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"); + 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, ".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, ".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 + + When modifying methods in this codebase, run the context command first if `./old/graph.db` exists: + + ```bash + ai-code-graph context "MethodName" --db ./old/graph.db + ``` + + ## 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("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] + 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