Skip to main content

cgx_engine/
skill.rs

1use std::path::Path;
2
3use crate::graph::{GraphDb, Node};
4
5pub struct SkillData {
6    pub indexed_at: String,
7    pub node_count: u64,
8    pub function_count: u64,
9    pub class_count: u64,
10    pub file_count: u64,
11    pub edge_count: u64,
12    pub language_breakdown: String,
13    pub community_count: u32,
14    pub top_communities: Vec<CommunityInfo>,
15    pub hotspots: Vec<Node>,
16    pub entry_points: Vec<Node>,
17    pub god_nodes: Vec<Node>,
18}
19
20pub struct CommunityInfo {
21    pub id: i64,
22    pub label: String,
23    pub node_count: i64,
24}
25
26const SKILL_TEMPLATE: &str = r#"# cgx — Codebase Knowledge Graph
27
28> Auto-generated by cgx on {{ indexed_at }}. Do not edit manually.
29> Re-run `cgx analyze` to refresh.
30
31## When to Use cgx
32
33Use cgx commands INSTEAD of reading source files when you need to:
34- Find where any function, class, or variable is defined
35- Understand what depends on a specific piece of code
36- Know what will break before making a change
37- Understand the architecture of an unfamiliar area
38- Find who owns a file or module
39- Find dead code or unused exports
40- Trace a full call chain from entry point to implementation
41
42**Rule: Never open a file speculatively. Query first. Open only if you need
43the implementation body — not to find where something lives.**
44
45## Trigger Patterns
46
47Run cgx automatically when the user says or implies any of:
48- "what calls X" / "who uses X" / "what depends on X"
49- "show me the architecture" / "how does this work"
50- "what breaks if I change X" / "blast radius of X"
51- "find X in the codebase" / "where is X defined"
52- "who owns X" / "who wrote X"
53- "is X used anywhere" / "is X dead code"
54- Starting a new task in an unfamiliar part of the codebase
55- Before making any edit to a function with many callers
56
57## Commands
58
59```bash
60# Always run first in a new session
61cgx summary
62
63# Find any symbol
64cgx query find <name>
65cgx query find <name> --kind=Function
66
67# Dependencies of a node
68cgx query deps <node-name>
69
70# Blast radius — run BEFORE every edit
71cgx query blast-radius <function-name>
72
73# Trace a call path
74cgx query chain "<A> -> <B>"
75
76# High-risk files
77cgx hotspots
78
79# Code ownership
80cgx query owners <path>
81
82# Search by concept
83cgx query search "<phrase>"
84
85# Community / cluster
86cgx query community <id-or-name>
87
88# Dead code
89cgx query dead-code
90```
91
92## Workflow: Starting a Task
93
941. `cgx summary`                        — orient yourself
952. `cgx query find <entry-point>`       — locate the relevant node
963. `cgx query blast-radius <node>`      — know the risk before touching it
974. Open only the specific files you need
98
99## Workflow: Before Every Edit
100
1011. `cgx query blast-radius <function>`  — what breaks?
1022. `cgx query deps <function>`          — what does it depend on?
1033. Make the change
1044. `cgx query blast-radius <function>`  — verify ripple is as expected
105
106## Token Budget
107
108| Action                    | Approx tokens |
109|---------------------------|---------------|
110| `cgx summary`             | ~400          |
111| `cgx query find X`        | ~200          |
112| `cgx query blast-radius X`| ~300-800      |
113| Opening one source file   | ~2,000-15,000 |
114
115Prefer 3 cgx queries over opening 1 file speculatively.
116
117## This Codebase
118
119- **Indexed:** {{ indexed_at }}
120- **Nodes:** {{ node_count }} ({{ function_count }} functions,
121  {{ class_count }} classes, {{ file_count }} files)
122- **Edges:** {{ edge_count }}
123- **Languages:** {{ language_breakdown }}
124- **Communities:** {{ community_count }}
125
126### Top Communities
127{{ top_communities_list }}
128
129### Hotspots (highest risk — review carefully before editing)
130{{ hotspots_list }}
131
132### Entry Points (nothing imports these — safe starting points)
133{{ entry_points_list }}
134
135### Most Depended-On Nodes (god nodes — change with extreme care)
136{{ god_nodes_list }}
137"#;
138
139const AGENTS_TEMPLATE: &str = r#"# Codebase Architecture
140> Auto-generated by cgx {{ indexed_at }}. Re-run `cgx analyze` to refresh.
141
142## Stats
143- **Nodes:** {{ node_count }} across {{ file_count }} files
144- **Languages:** {{ language_breakdown }}
145- **Communities:** {{ community_count }} architectural clusters
146
147## Architectural Communities
148The graph is partitioned into {{ community_count }} communities via Louvain clustering.
149Each community is a cohesive module — edits inside one community rarely ripple outside it.
150{{ community_descriptions }}
151
152## Hotspots (High Risk — Review Before Editing)
153Files ranked by churn × coupling score. Editing these is likely to break things.
154{{ hotspots_table }}
155
156## Entry Points
157Files/functions with no inbound dependencies — safe places to start tracing.
158{{ entry_points_list }}
159
160## God Nodes (Most Depended-On)
161These are used everywhere. Breaking them has maximum blast radius.
162{{ god_nodes_list }}
163
164## How to Use This Index
165
166### With MCP (structured queries — recommended)
167After `cgx setup` + editor restart, cgx tools are available directly in chat:
168- `get_repo_summary` — full architectural overview
169- `find_symbol <name>` — locate any function, class, or variable
170- `get_neighbors <node_id>` — direct dependencies of a node
171- `get_blast_radius <node_id>` — what breaks if this changes
172- `get_call_chain <from> <to>` — trace a call path
173- `get_hotspots` — riskiest files to edit
174- `get_file_owners <path>` — git blame ownership
175- `run_query <sql>` — raw SQL against the graph database
176
177### With CLI (fallback)
178```
179cgx summary                     # architectural overview
180cgx query find <name>           # locate a symbol
181cgx query blast-radius <name>   # change impact analysis
182cgx query deps <name>           # what does this depend on
183cgx query chain "<A> -> <B>"    # trace call path
184cgx query owners <path>         # file ownership
185cgx query dead-code             # unused exports
186```
187
188## AI Agent Guidance
1891. **Start every session** with `get_repo_summary` (MCP) or `cgx summary` (CLI) to orient yourself.
1902. **Before editing** any hotspot file, call `get_blast_radius` — the risk score tells you how careful to be.
1913. **To find a symbol**, use `find_symbol` instead of grepping source files — it's 10× faster.
1924. **Community IDs** in node metadata tell you which module a node belongs to; use `get_community` to explore the whole cluster.
1935. **God nodes** (above) are used by many callers — any change there needs tests across all callers.
194"#;
195
196pub fn build_skill_data(db: &GraphDb) -> anyhow::Result<SkillData> {
197    let node_count = db.node_count()?;
198    let edge_count = db.edge_count()?;
199    let lang_breakdown = db.get_language_breakdown()?;
200    let communities = db.get_communities()?;
201    let counts_by_kind = db.get_node_counts_by_kind()?;
202
203    let function_count = counts_by_kind.get("Function").copied().unwrap_or(0);
204    let class_count = counts_by_kind.get("Class").copied().unwrap_or(0);
205    let file_count = counts_by_kind.get("File").copied().unwrap_or(0);
206
207    let language_breakdown = if lang_breakdown.is_empty() {
208        "none".to_string()
209    } else {
210        let mut entries: Vec<_> = lang_breakdown.iter().collect();
211        entries.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(std::cmp::Ordering::Equal));
212        entries
213            .iter()
214            .map(|(lang, pct)| format!("{} {:.0}%", lang, *pct * 100.0))
215            .collect::<Vec<_>>()
216            .join(", ")
217    };
218
219    let top_communities: Vec<CommunityInfo> = communities
220        .iter()
221        .take(5)
222        .map(|(id, label, count, _top_nodes)| CommunityInfo {
223            id: *id,
224            label: label.clone(),
225            node_count: *count,
226        })
227        .collect();
228
229    let all_nodes = db.get_all_nodes()?;
230
231    let mut file_nodes: Vec<&Node> = all_nodes
232        .iter()
233        .filter(|n| n.kind == "File" && n.churn > 0.0)
234        .collect();
235    file_nodes.sort_by(|a, b| {
236        let sa = a.churn * a.coupling + a.in_degree as f64 * 0.01;
237        let sb = b.churn * b.coupling + b.in_degree as f64 * 0.01;
238        sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal)
239    });
240    let hotspots: Vec<Node> = file_nodes.iter().take(5).map(|&n| n.clone()).collect();
241
242    let mut entry_nodes: Vec<&Node> = all_nodes
243        .iter()
244        .filter(|n| n.in_degree == 0 && n.kind != "File" && n.kind != "Author")
245        .collect();
246    entry_nodes.sort_by_key(|node| std::cmp::Reverse(node.out_degree));
247    let entry_points: Vec<Node> = entry_nodes.iter().take(5).map(|&n| n.clone()).collect();
248
249    let mut god_nodes: Vec<&Node> = all_nodes
250        .iter()
251        .filter(|n| n.in_degree > 0 && n.kind != "File")
252        .collect();
253    god_nodes.sort_by_key(|node| std::cmp::Reverse(node.in_degree));
254    // Deduplicate by name (same function defined in multiple files shows same name)
255    let mut seen_names = std::collections::HashSet::new();
256    let top_god_nodes: Vec<Node> = god_nodes
257        .iter()
258        .filter(|n| seen_names.insert(n.name.clone()))
259        .take(5)
260        .map(|&n| n.clone())
261        .collect();
262
263    Ok(SkillData {
264        indexed_at: chrono::Utc::now().to_rfc3339(),
265        node_count,
266        function_count,
267        class_count,
268        file_count,
269        edge_count,
270        language_breakdown,
271        community_count: communities.len() as u32,
272        top_communities,
273        hotspots,
274        entry_points,
275        god_nodes: top_god_nodes,
276    })
277}
278
279pub fn generate_skill(data: &SkillData) -> String {
280    let mut c = SKILL_TEMPLATE.to_string();
281
282    c = c.replace("{{ indexed_at }}", &data.indexed_at);
283    c = c.replace("{{ node_count }}", &data.node_count.to_string());
284    c = c.replace("{{ function_count }}", &data.function_count.to_string());
285    c = c.replace("{{ class_count }}", &data.class_count.to_string());
286    c = c.replace("{{ file_count }}", &data.file_count.to_string());
287    c = c.replace("{{ edge_count }}", &data.edge_count.to_string());
288    c = c.replace("{{ language_breakdown }}", &data.language_breakdown);
289    c = c.replace("{{ community_count }}", &data.community_count.to_string());
290
291    let communities_list = if data.top_communities.is_empty() {
292        "_(none detected)_\n".to_string()
293    } else {
294        data.top_communities
295            .iter()
296            .map(|ci| format!("- **#{}** — {} ({} nodes)", ci.id, ci.label, ci.node_count))
297            .collect::<Vec<_>>()
298            .join("\n")
299    };
300    c = c.replace("{{ top_communities_list }}", &communities_list);
301
302    let hotspots_list = if data.hotspots.is_empty() {
303        "_(none — no git history or low churn)_\n".to_string()
304    } else {
305        data.hotspots
306            .iter()
307            .map(|n| {
308                format!(
309                    "- `{}` — churn {:.2}, {} callers",
310                    n.path, n.churn, n.in_degree
311                )
312            })
313            .collect::<Vec<_>>()
314            .join("\n")
315    };
316    c = c.replace("{{ hotspots_list }}", &hotspots_list);
317
318    let entry_list = if data.entry_points.is_empty() {
319        "_(none detected)_\n".to_string()
320    } else {
321        data.entry_points
322            .iter()
323            .map(|n| format!("- `{}` ({})", n.name, n.kind))
324            .collect::<Vec<_>>()
325            .join("\n")
326    };
327    c = c.replace("{{ entry_points_list }}", &entry_list);
328
329    let god_list = if data.god_nodes.is_empty() {
330        "_(none detected)_\n".to_string()
331    } else {
332        data.god_nodes
333            .iter()
334            .map(|n| format!("- `{}` — {} callers", n.name, n.in_degree))
335            .collect::<Vec<_>>()
336            .join("\n")
337    };
338    c = c.replace("{{ god_nodes_list }}", &god_list);
339
340    if c.contains("{{") {
341        eprintln!("  Warning: CGX_SKILL.md contains unreplaced placeholder tokens");
342    }
343    c
344}
345
346pub fn generate_agents_md(data: &SkillData) -> String {
347    let mut c = AGENTS_TEMPLATE.to_string();
348
349    c = c.replace("{{ indexed_at }}", &data.indexed_at);
350    c = c.replace("{{ node_count }}", &data.node_count.to_string());
351    c = c.replace("{{ file_count }}", &data.file_count.to_string());
352    c = c.replace("{{ language_breakdown }}", &data.language_breakdown);
353    c = c.replace("{{ community_count }}", &data.community_count.to_string());
354
355    let community_descriptions = if data.top_communities.is_empty() {
356        "No architectural communities detected.\n".to_string()
357    } else {
358        data.top_communities
359            .iter()
360            .map(|ci| format!("- **#{} — {}** ({} nodes)", ci.id, ci.label, ci.node_count))
361            .collect::<Vec<_>>()
362            .join("\n")
363    };
364    c = c.replace("{{ community_descriptions }}", &community_descriptions);
365
366    let hotspots_table = if data.hotspots.is_empty() {
367        "No hotspots detected (no git history or low churn).\n".to_string()
368    } else {
369        let mut t = String::from("| File | Churn | Callers |\n|------|-------|--------|\n");
370        for n in &data.hotspots {
371            t.push_str(&format!(
372                "| `{}` | {:.2} | {} |\n",
373                n.path, n.churn, n.in_degree
374            ));
375        }
376        t
377    };
378    c = c.replace("{{ hotspots_table }}", &hotspots_table);
379
380    let entry_list = if data.entry_points.is_empty() {
381        "_(none detected)_\n".to_string()
382    } else {
383        data.entry_points
384            .iter()
385            .map(|n| format!("- `{}` ({})", n.name, n.kind))
386            .collect::<Vec<_>>()
387            .join("\n")
388    };
389    c = c.replace("{{ entry_points_list }}", &entry_list);
390
391    let god_list = if data.god_nodes.is_empty() {
392        "_(none detected)_\n".to_string()
393    } else {
394        data.god_nodes
395            .iter()
396            .map(|n| {
397                format!(
398                    "- `{}` ({}) — {} callers, in `{}`",
399                    n.name, n.kind, n.in_degree, n.path
400                )
401            })
402            .collect::<Vec<_>>()
403            .join("\n")
404    };
405    c = c.replace("{{ god_nodes_list }}", &god_list);
406
407    if c.contains("{{") {
408        eprintln!("  Warning: AGENTS.md contains unreplaced placeholder tokens");
409    }
410
411    c
412}
413
414pub fn write_skill(repo_root: &Path, data: &SkillData) -> anyhow::Result<()> {
415    std::fs::write(repo_root.join("CGX_SKILL.md"), generate_skill(data))?;
416    Ok(())
417}
418
419pub fn write_agents_md(repo_root: &Path, data: &SkillData) -> anyhow::Result<()> {
420    std::fs::write(repo_root.join("AGENTS.md"), generate_agents_md(data))?;
421    Ok(())
422}
423
424pub fn install_git_hooks(repo_root: &Path) -> anyhow::Result<(bool, bool)> {
425    let hooks_dir = repo_root.join(".git").join("hooks");
426    if !hooks_dir.exists() {
427        return Ok((false, false));
428    }
429    Ok((
430        install_one_hook(&hooks_dir.join("post-commit")),
431        install_one_hook(&hooks_dir.join("post-checkout")),
432    ))
433}
434
435fn install_one_hook(path: &Path) -> bool {
436    if path.exists() {
437        if let Ok(existing) = std::fs::read_to_string(path) {
438            let lines: Vec<&str> = existing.lines().collect();
439            if lines.len() < 2 || !lines[1].contains("cgx-managed") {
440                eprintln!(
441                    "  Warning: {} exists but was not created by cgx. Skipping.",
442                    path.display()
443                );
444                return false;
445            }
446        } else {
447            return false;
448        }
449    }
450    // Use the running binary's path so the hook works even if cgx isn't on PATH
451    let bin = std::env::current_exe()
452        .ok()
453        .and_then(|p| p.to_str().map(|s| s.to_string()))
454        .unwrap_or_else(|| "cgx".to_string());
455    let content = format!(
456        "#!/bin/sh\n# cgx-managed\n{} analyze --incremental --quiet\n",
457        bin
458    );
459    if std::fs::write(path, content).is_err() {
460        return false;
461    }
462    #[cfg(unix)]
463    {
464        use std::os::unix::fs::PermissionsExt;
465        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
466    }
467    true
468}