Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions AiCodeGraph.Cli/Commands/AgentIntegrationContent.cs
Original file line number Diff line number Diff line change
@@ -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`
";
}
1 change: 1 addition & 0 deletions AiCodeGraph.Cli/Commands/CommandRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public static RootCommand Build()
new McpCommand(),
new SetupClaudeCommand(),
new SetupCursorCommand(),
new SetupCodexCommand(),
new StatusCommand(),
new LayersCommand(),
new QueryCommand(),
Expand Down
265 changes: 265 additions & 0 deletions AiCodeGraph.Cli/Commands/SetupCodexCommand.cs
Original file line number Diff line number Diff line change
@@ -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<string>("--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<string>();
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<string> 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<string> 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<string> 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<string>(out var value) &&
string.Equals(value, expected, StringComparison.Ordinal);
}
}
Loading
Loading