mulle-roam-code 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mulle_roam_code-0.0.1.dist-info/METADATA +1590 -0
- mulle_roam_code-0.0.1.dist-info/RECORD +257 -0
- mulle_roam_code-0.0.1.dist-info/WHEEL +5 -0
- mulle_roam_code-0.0.1.dist-info/entry_points.txt +3 -0
- mulle_roam_code-0.0.1.dist-info/licenses/LICENSE +21 -0
- mulle_roam_code-0.0.1.dist-info/top_level.txt +1 -0
- roam/__init__.py +8 -0
- roam/__main__.py +5 -0
- roam/analysis/__init__.py +1 -0
- roam/analysis/effects.py +639 -0
- roam/analysis/taint.py +689 -0
- roam/api.py +238 -0
- roam/bridges/__init__.py +3 -0
- roam/bridges/base.py +49 -0
- roam/bridges/bridge_config.py +218 -0
- roam/bridges/bridge_protobuf.py +352 -0
- roam/bridges/bridge_rest_api.py +242 -0
- roam/bridges/bridge_salesforce.py +198 -0
- roam/bridges/bridge_template.py +247 -0
- roam/bridges/registry.py +51 -0
- roam/catalog/__init__.py +0 -0
- roam/catalog/detectors.py +2242 -0
- roam/catalog/fixes.py +86 -0
- roam/catalog/smells.py +599 -0
- roam/catalog/tasks.py +1260 -0
- roam/cli.py +548 -0
- roam/commands/__init__.py +0 -0
- roam/commands/changed_files.py +139 -0
- roam/commands/cmd_adversarial.py +699 -0
- roam/commands/cmd_affected.py +432 -0
- roam/commands/cmd_affected_tests.py +375 -0
- roam/commands/cmd_agent_context.py +168 -0
- roam/commands/cmd_agent_export.py +890 -0
- roam/commands/cmd_agent_plan.py +315 -0
- roam/commands/cmd_ai_ratio.py +765 -0
- roam/commands/cmd_ai_readiness.py +775 -0
- roam/commands/cmd_alerts.py +409 -0
- roam/commands/cmd_annotate.py +210 -0
- roam/commands/cmd_api_changes.py +796 -0
- roam/commands/cmd_api_drift.py +781 -0
- roam/commands/cmd_attest.py +913 -0
- roam/commands/cmd_auth_gaps.py +799 -0
- roam/commands/cmd_bisect.py +216 -0
- roam/commands/cmd_breaking.py +464 -0
- roam/commands/cmd_budget.py +413 -0
- roam/commands/cmd_bus_factor.py +403 -0
- roam/commands/cmd_capsule.py +275 -0
- roam/commands/cmd_check_rules.py +574 -0
- roam/commands/cmd_clean.py +147 -0
- roam/commands/cmd_closure.py +294 -0
- roam/commands/cmd_clusters.py +457 -0
- roam/commands/cmd_codeowners.py +600 -0
- roam/commands/cmd_complexity.py +364 -0
- roam/commands/cmd_config.py +310 -0
- roam/commands/cmd_context.py +1151 -0
- roam/commands/cmd_conventions.py +697 -0
- roam/commands/cmd_coupling.py +462 -0
- roam/commands/cmd_coverage_gaps.py +638 -0
- roam/commands/cmd_cut.py +235 -0
- roam/commands/cmd_dark_matter.py +127 -0
- roam/commands/cmd_dashboard.py +365 -0
- roam/commands/cmd_dead.py +1585 -0
- roam/commands/cmd_debt.py +731 -0
- roam/commands/cmd_deps.py +121 -0
- roam/commands/cmd_describe.py +959 -0
- roam/commands/cmd_dev_profile.py +580 -0
- roam/commands/cmd_diagnose.py +377 -0
- roam/commands/cmd_diff.py +633 -0
- roam/commands/cmd_digest.py +214 -0
- roam/commands/cmd_doc_staleness.py +334 -0
- roam/commands/cmd_docs_coverage.py +193 -0
- roam/commands/cmd_doctor.py +319 -0
- roam/commands/cmd_drift.py +377 -0
- roam/commands/cmd_duplicates.py +559 -0
- roam/commands/cmd_effects.py +362 -0
- roam/commands/cmd_endpoints.py +768 -0
- roam/commands/cmd_entry_points.py +358 -0
- roam/commands/cmd_fan.py +311 -0
- roam/commands/cmd_file.py +334 -0
- roam/commands/cmd_fingerprint.py +172 -0
- roam/commands/cmd_fitness.py +723 -0
- roam/commands/cmd_fn_coupling.py +295 -0
- roam/commands/cmd_forecast.py +366 -0
- roam/commands/cmd_grep.py +282 -0
- roam/commands/cmd_guard.py +434 -0
- roam/commands/cmd_health.py +922 -0
- roam/commands/cmd_hooks.py +458 -0
- roam/commands/cmd_hotspots.py +606 -0
- roam/commands/cmd_impact.py +228 -0
- roam/commands/cmd_index.py +102 -0
- roam/commands/cmd_ingest_trace.py +143 -0
- roam/commands/cmd_init.py +166 -0
- roam/commands/cmd_intent.py +459 -0
- roam/commands/cmd_invariants.py +301 -0
- roam/commands/cmd_layers.py +387 -0
- roam/commands/cmd_map.py +275 -0
- roam/commands/cmd_math.py +213 -0
- roam/commands/cmd_mcp_setup.py +135 -0
- roam/commands/cmd_metrics.py +663 -0
- roam/commands/cmd_migration_safety.py +712 -0
- roam/commands/cmd_minimap.py +519 -0
- roam/commands/cmd_missing_index.py +885 -0
- roam/commands/cmd_module.py +204 -0
- roam/commands/cmd_mutate.py +400 -0
- roam/commands/cmd_n1.py +967 -0
- roam/commands/cmd_onboard.py +740 -0
- roam/commands/cmd_orchestrate.py +180 -0
- roam/commands/cmd_orphan_routes.py +754 -0
- roam/commands/cmd_over_fetch.py +633 -0
- roam/commands/cmd_owner.py +299 -0
- roam/commands/cmd_partition.py +714 -0
- roam/commands/cmd_path_coverage.py +564 -0
- roam/commands/cmd_patterns.py +689 -0
- roam/commands/cmd_plan.py +616 -0
- roam/commands/cmd_plan_refactor.py +432 -0
- roam/commands/cmd_pr_diff.py +292 -0
- roam/commands/cmd_pr_risk.py +677 -0
- roam/commands/cmd_preflight.py +706 -0
- roam/commands/cmd_relate.py +405 -0
- roam/commands/cmd_report.py +304 -0
- roam/commands/cmd_reset.py +117 -0
- roam/commands/cmd_risk.py +533 -0
- roam/commands/cmd_rules.py +319 -0
- roam/commands/cmd_safe_delete.py +224 -0
- roam/commands/cmd_safe_zones.py +295 -0
- roam/commands/cmd_schema.py +166 -0
- roam/commands/cmd_search.py +295 -0
- roam/commands/cmd_search_semantic.py +101 -0
- roam/commands/cmd_secrets.py +636 -0
- roam/commands/cmd_semantic_diff.py +538 -0
- roam/commands/cmd_simulate.py +296 -0
- roam/commands/cmd_simulate_departure.py +632 -0
- roam/commands/cmd_sketch.py +160 -0
- roam/commands/cmd_smells.py +179 -0
- roam/commands/cmd_snapshot.py +50 -0
- roam/commands/cmd_spectral.py +183 -0
- roam/commands/cmd_split.py +432 -0
- roam/commands/cmd_suggest_refactoring.py +486 -0
- roam/commands/cmd_suggest_reviewers.py +491 -0
- roam/commands/cmd_supply_chain.py +831 -0
- roam/commands/cmd_symbol.py +135 -0
- roam/commands/cmd_syntax_check.py +301 -0
- roam/commands/cmd_test_gaps.py +574 -0
- roam/commands/cmd_testmap.py +308 -0
- roam/commands/cmd_tour.py +377 -0
- roam/commands/cmd_trace.py +304 -0
- roam/commands/cmd_trend.py +461 -0
- roam/commands/cmd_trends.py +929 -0
- roam/commands/cmd_understand.py +763 -0
- roam/commands/cmd_uses.py +170 -0
- roam/commands/cmd_verify.py +812 -0
- roam/commands/cmd_verify_imports.py +435 -0
- roam/commands/cmd_vibe_check.py +932 -0
- roam/commands/cmd_visualize.py +361 -0
- roam/commands/cmd_vuln_map.py +139 -0
- roam/commands/cmd_vuln_reach.py +289 -0
- roam/commands/cmd_vulns.py +414 -0
- roam/commands/cmd_watch.py +759 -0
- roam/commands/cmd_weather.py +118 -0
- roam/commands/cmd_why.py +325 -0
- roam/commands/cmd_ws.py +755 -0
- roam/commands/cmd_xlang.py +170 -0
- roam/commands/context_helpers.py +1137 -0
- roam/commands/gate_presets.py +222 -0
- roam/commands/graph_helpers.py +93 -0
- roam/commands/metrics_history.py +298 -0
- roam/commands/next_steps.py +107 -0
- roam/commands/resolve.py +302 -0
- roam/competitor_site_data.py +2229 -0
- roam/coverage_reports.py +462 -0
- roam/db/__init__.py +0 -0
- roam/db/connection.py +359 -0
- roam/db/queries.py +151 -0
- roam/db/schema.py +335 -0
- roam/exit_codes.py +100 -0
- roam/graph/__init__.py +43 -0
- roam/graph/anomaly.py +493 -0
- roam/graph/builder.py +61 -0
- roam/graph/clusters.py +286 -0
- roam/graph/cycles.py +210 -0
- roam/graph/dark_matter.py +207 -0
- roam/graph/diff.py +467 -0
- roam/graph/fingerprint.py +297 -0
- roam/graph/layers.py +134 -0
- roam/graph/pagerank.py +171 -0
- roam/graph/partition.py +437 -0
- roam/graph/pathfinding.py +119 -0
- roam/graph/propagation.py +208 -0
- roam/graph/simulate.py +286 -0
- roam/graph/spectral.py +260 -0
- roam/index/__init__.py +5 -0
- roam/index/complexity.py +1108 -0
- roam/index/discovery.py +338 -0
- roam/index/file_roles.py +586 -0
- roam/index/git_stats.py +577 -0
- roam/index/incremental.py +75 -0
- roam/index/indexer.py +1191 -0
- roam/index/parser.py +461 -0
- roam/index/relations.py +537 -0
- roam/index/symbols.py +71 -0
- roam/index/test_conventions.py +508 -0
- roam/languages/__init__.py +21 -0
- roam/languages/apex_lang.py +241 -0
- roam/languages/aura_lang.py +228 -0
- roam/languages/base.py +111 -0
- roam/languages/c_lang.py +458 -0
- roam/languages/csharp_lang.py +1215 -0
- roam/languages/foxpro_lang.py +1554 -0
- roam/languages/generic_lang.py +702 -0
- roam/languages/go_lang.py +392 -0
- roam/languages/hcl_lang.py +398 -0
- roam/languages/java_lang.py +418 -0
- roam/languages/javascript_lang.py +799 -0
- roam/languages/kotlin_lang.py +147 -0
- roam/languages/objc_lang.py +401 -0
- roam/languages/php_lang.py +696 -0
- roam/languages/python_lang.py +850 -0
- roam/languages/registry.py +283 -0
- roam/languages/ruby_lang.py +429 -0
- roam/languages/rust_lang.py +545 -0
- roam/languages/sfxml_lang.py +276 -0
- roam/languages/swift_lang.py +173 -0
- roam/languages/typescript_lang.py +323 -0
- roam/languages/visualforce_lang.py +151 -0
- roam/languages/yaml_lang.py +566 -0
- roam/mcp_server.py +4794 -0
- roam/output/__init__.py +0 -0
- roam/output/formatter.py +557 -0
- roam/output/mermaid.py +62 -0
- roam/output/sarif.py +897 -0
- roam/output/schema_registry.py +57 -0
- roam/plugins.py +208 -0
- roam/refactor/__init__.py +0 -0
- roam/refactor/codegen.py +106 -0
- roam/refactor/transforms.py +711 -0
- roam/rules/__init__.py +0 -0
- roam/rules/ast_match.py +238 -0
- roam/rules/builtin.py +617 -0
- roam/rules/dataflow.py +515 -0
- roam/rules/engine.py +943 -0
- roam/runtime/__init__.py +3 -0
- roam/runtime/hotspots.py +138 -0
- roam/runtime/trace_ingest.py +535 -0
- roam/search/__init__.py +1 -0
- roam/search/framework_packs.py +673 -0
- roam/search/index_embeddings.py +732 -0
- roam/search/onnx_embeddings.py +233 -0
- roam/search/tfidf.py +355 -0
- roam/security/__init__.py +1 -0
- roam/security/vuln_reach.py +246 -0
- roam/security/vuln_store.py +334 -0
- roam/surface_counts.py +158 -0
- roam/workspace/__init__.py +3 -0
- roam/workspace/aggregator.py +426 -0
- roam/workspace/api_scanner.py +538 -0
- roam/workspace/config.py +95 -0
- roam/workspace/db.py +136 -0
|
@@ -0,0 +1,959 @@
|
|
|
1
|
+
"""Auto-generate a project description for AI coding agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
|
|
11
|
+
from roam.commands.resolve import ensure_index
|
|
12
|
+
from roam.db.connection import find_project_root, open_db
|
|
13
|
+
from roam.output.formatter import json_envelope, to_json
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _section_overview(conn):
|
|
17
|
+
"""Project overview: languages, file/symbol/edge counts."""
|
|
18
|
+
lines = ["## Project Overview", ""]
|
|
19
|
+
total_files = conn.execute("SELECT COUNT(*) FROM files").fetchone()[0]
|
|
20
|
+
total_symbols = conn.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
|
|
21
|
+
total_edges = conn.execute("SELECT COUNT(*) FROM edges").fetchone()[0]
|
|
22
|
+
|
|
23
|
+
files = conn.execute("SELECT language FROM files").fetchall()
|
|
24
|
+
lang_counts = Counter(f["language"] for f in files if f["language"])
|
|
25
|
+
lang_str = ", ".join(f"{lang} ({n})" for lang, n in lang_counts.most_common(8))
|
|
26
|
+
|
|
27
|
+
lines.append(f"- **Files:** {total_files}")
|
|
28
|
+
lines.append(f"- **Symbols:** {total_symbols}")
|
|
29
|
+
lines.append(f"- **Edges:** {total_edges}")
|
|
30
|
+
lines.append(f"- **Languages:** {lang_str}")
|
|
31
|
+
return lines
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _section_directories(conn):
|
|
35
|
+
"""Directory structure with file counts and primary language."""
|
|
36
|
+
lines = ["", "## Directory Structure", ""]
|
|
37
|
+
rows = conn.execute("""
|
|
38
|
+
SELECT CASE WHEN INSTR(REPLACE(path, '\\', '/'), '/') > 0
|
|
39
|
+
THEN SUBSTR(REPLACE(path, '\\', '/'), 1, INSTR(REPLACE(path, '\\', '/'), '/') - 1)
|
|
40
|
+
ELSE '.' END as dir,
|
|
41
|
+
COUNT(*) as cnt
|
|
42
|
+
FROM files GROUP BY dir ORDER BY cnt DESC
|
|
43
|
+
""").fetchall()
|
|
44
|
+
|
|
45
|
+
# Get primary language per directory
|
|
46
|
+
dir_langs = conn.execute("""
|
|
47
|
+
SELECT CASE WHEN INSTR(REPLACE(path, '\\', '/'), '/') > 0
|
|
48
|
+
THEN SUBSTR(REPLACE(path, '\\', '/'), 1, INSTR(REPLACE(path, '\\', '/'), '/') - 1)
|
|
49
|
+
ELSE '.' END as dir,
|
|
50
|
+
language, COUNT(*) as cnt
|
|
51
|
+
FROM files WHERE language IS NOT NULL
|
|
52
|
+
GROUP BY dir, language ORDER BY dir, cnt DESC
|
|
53
|
+
""").fetchall()
|
|
54
|
+
primary_lang = {}
|
|
55
|
+
for r in dir_langs:
|
|
56
|
+
d = r["dir"]
|
|
57
|
+
if d not in primary_lang:
|
|
58
|
+
primary_lang[d] = r["language"]
|
|
59
|
+
|
|
60
|
+
lines.append("| Directory | Files | Primary Language |")
|
|
61
|
+
lines.append("|-----------|-------|------------------|")
|
|
62
|
+
for r in rows[:20]:
|
|
63
|
+
lang = primary_lang.get(r["dir"], "")
|
|
64
|
+
lines.append(f"| `{r['dir']}/` | {r['cnt']} | {lang} |")
|
|
65
|
+
return lines
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _section_entry_points(conn):
|
|
69
|
+
"""Entry points: conventional names + main() functions."""
|
|
70
|
+
lines = ["", "## Entry Points", ""]
|
|
71
|
+
entry_names = {
|
|
72
|
+
"main.py",
|
|
73
|
+
"__main__.py",
|
|
74
|
+
"__init__.py",
|
|
75
|
+
"index.js",
|
|
76
|
+
"index.ts",
|
|
77
|
+
"main.go",
|
|
78
|
+
"main.rs",
|
|
79
|
+
"app.py",
|
|
80
|
+
"app.js",
|
|
81
|
+
"app.ts",
|
|
82
|
+
"mod.rs",
|
|
83
|
+
"lib.rs",
|
|
84
|
+
"setup.py",
|
|
85
|
+
"manage.py",
|
|
86
|
+
}
|
|
87
|
+
files = conn.execute("SELECT path FROM files").fetchall()
|
|
88
|
+
entries = [f["path"] for f in files if os.path.basename(f["path"]) in entry_names]
|
|
89
|
+
|
|
90
|
+
main_files = conn.execute(
|
|
91
|
+
"SELECT DISTINCT f.path FROM symbols s JOIN files f ON s.file_id = f.id "
|
|
92
|
+
"WHERE s.name = 'main' AND s.kind = 'function'",
|
|
93
|
+
).fetchall()
|
|
94
|
+
for r in main_files:
|
|
95
|
+
if r["path"] not in entries:
|
|
96
|
+
entries.append(r["path"])
|
|
97
|
+
|
|
98
|
+
if entries:
|
|
99
|
+
for e in entries[:25]:
|
|
100
|
+
lines.append(f"- `{e}`")
|
|
101
|
+
else:
|
|
102
|
+
lines.append("No conventional entry points detected.")
|
|
103
|
+
return lines
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _section_key_abstractions(conn):
|
|
107
|
+
"""Top 15 symbols by PageRank."""
|
|
108
|
+
lines = ["", "## Key Abstractions", ""]
|
|
109
|
+
try:
|
|
110
|
+
top = conn.execute("""
|
|
111
|
+
SELECT s.name, s.kind, s.signature, f.path as file_path,
|
|
112
|
+
s.line_start, gm.pagerank
|
|
113
|
+
FROM symbols s
|
|
114
|
+
JOIN files f ON s.file_id = f.id
|
|
115
|
+
JOIN graph_metrics gm ON s.id = gm.symbol_id
|
|
116
|
+
WHERE s.kind IN ('function', 'class', 'method', 'interface', 'struct', 'trait')
|
|
117
|
+
ORDER BY gm.pagerank DESC LIMIT 15
|
|
118
|
+
""").fetchall()
|
|
119
|
+
except Exception:
|
|
120
|
+
lines.append("Graph metrics not available. Run `roam index` first.")
|
|
121
|
+
return lines
|
|
122
|
+
|
|
123
|
+
if not top:
|
|
124
|
+
lines.append("No graph metrics available.")
|
|
125
|
+
return lines
|
|
126
|
+
|
|
127
|
+
lines.append("Top symbols by importance (PageRank):")
|
|
128
|
+
lines.append("")
|
|
129
|
+
lines.append("| Symbol | Kind | Location |")
|
|
130
|
+
lines.append("|--------|------|----------|")
|
|
131
|
+
for s in top:
|
|
132
|
+
sig = s["signature"] or ""
|
|
133
|
+
if len(sig) > 50:
|
|
134
|
+
sig = sig[:47] + "..."
|
|
135
|
+
kind = s["kind"]
|
|
136
|
+
name = s["name"]
|
|
137
|
+
if sig:
|
|
138
|
+
name = f"{name} {sig}"
|
|
139
|
+
lines.append(f"| `{name}` | {kind} | `{s['file_path']}:{s['line_start']}` |")
|
|
140
|
+
return lines
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _section_architecture(conn):
|
|
144
|
+
"""Layer count, shape, and cycle count."""
|
|
145
|
+
lines = ["", "## Architecture", ""]
|
|
146
|
+
try:
|
|
147
|
+
from roam.graph.builder import build_symbol_graph
|
|
148
|
+
from roam.graph.cycles import find_cycles
|
|
149
|
+
from roam.graph.layers import detect_layers
|
|
150
|
+
|
|
151
|
+
G = build_symbol_graph(conn)
|
|
152
|
+
if len(G) == 0:
|
|
153
|
+
lines.append("No graph data available.")
|
|
154
|
+
return lines
|
|
155
|
+
|
|
156
|
+
layers = detect_layers(G)
|
|
157
|
+
cycles = find_cycles(G)
|
|
158
|
+
|
|
159
|
+
max_layer = max(layers.values()) if layers else 0
|
|
160
|
+
lines.append(f"- **Dependency layers:** {max_layer + 1}")
|
|
161
|
+
lines.append(f"- **Cycles (SCCs):** {len(cycles)}")
|
|
162
|
+
|
|
163
|
+
if layers:
|
|
164
|
+
layer_counts = Counter(layers.values())
|
|
165
|
+
lines.append(
|
|
166
|
+
"- **Layer distribution:** "
|
|
167
|
+
+ ", ".join(f"L{k}: {v} symbols" for k, v in sorted(layer_counts.items())[:5])
|
|
168
|
+
)
|
|
169
|
+
except Exception:
|
|
170
|
+
lines.append("Architecture analysis not available (graph module not loaded).")
|
|
171
|
+
return lines
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _section_testing(conn):
|
|
175
|
+
"""Test directories, test file count, test-to-source ratio."""
|
|
176
|
+
lines = ["", "## Testing", ""]
|
|
177
|
+
files = conn.execute("SELECT path FROM files").fetchall()
|
|
178
|
+
all_paths = [f["path"].replace("\\", "/") for f in files]
|
|
179
|
+
|
|
180
|
+
test_files = []
|
|
181
|
+
source_files = []
|
|
182
|
+
for p in all_paths:
|
|
183
|
+
basename = os.path.basename(p)
|
|
184
|
+
is_test = any(pat in basename for pat in ["test_", "_test.", ".test.", ".spec."]) or any(
|
|
185
|
+
d in p for d in ["tests/", "test/", "__tests__/", "spec/"]
|
|
186
|
+
)
|
|
187
|
+
if is_test:
|
|
188
|
+
test_files.append(p)
|
|
189
|
+
else:
|
|
190
|
+
source_files.append(p)
|
|
191
|
+
|
|
192
|
+
# Detect test directories
|
|
193
|
+
test_dirs = set()
|
|
194
|
+
for tf in test_files:
|
|
195
|
+
parts = tf.split("/")
|
|
196
|
+
for i, part in enumerate(parts):
|
|
197
|
+
if part in ("tests", "test", "__tests__", "spec"):
|
|
198
|
+
test_dirs.add("/".join(parts[: i + 1]))
|
|
199
|
+
|
|
200
|
+
if test_dirs:
|
|
201
|
+
lines.append("**Test directories:** " + ", ".join(f"`{d}/`" for d in sorted(test_dirs)))
|
|
202
|
+
lines.append(f"- **Test files:** {len(test_files)}")
|
|
203
|
+
lines.append(f"- **Source files:** {len(source_files)}")
|
|
204
|
+
if source_files:
|
|
205
|
+
ratio = len(test_files) / len(source_files)
|
|
206
|
+
lines.append(f"- **Test-to-source ratio:** {ratio:.2f}")
|
|
207
|
+
return lines
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _read_manifest_info(project_root):
|
|
211
|
+
"""Read package name/description from manifest files."""
|
|
212
|
+
if not project_root:
|
|
213
|
+
return []
|
|
214
|
+
import json
|
|
215
|
+
|
|
216
|
+
lines = []
|
|
217
|
+
for manifest in ("package.json", "composer.json"):
|
|
218
|
+
mpath = project_root / manifest
|
|
219
|
+
if not mpath.exists():
|
|
220
|
+
continue
|
|
221
|
+
try:
|
|
222
|
+
data = json.loads(mpath.read_text(encoding="utf-8"))
|
|
223
|
+
desc = data.get("description", "")
|
|
224
|
+
name = data.get("name", "")
|
|
225
|
+
if desc:
|
|
226
|
+
lines.append(f"- **Package:** {name}")
|
|
227
|
+
lines.append(f"- **Description:** {desc}")
|
|
228
|
+
except Exception:
|
|
229
|
+
pass
|
|
230
|
+
break
|
|
231
|
+
|
|
232
|
+
for manifest in ("pyproject.toml",):
|
|
233
|
+
mpath = project_root / manifest
|
|
234
|
+
if not mpath.exists():
|
|
235
|
+
continue
|
|
236
|
+
try:
|
|
237
|
+
text = mpath.read_text(encoding="utf-8")
|
|
238
|
+
for line in text.splitlines():
|
|
239
|
+
if line.strip().startswith("description"):
|
|
240
|
+
desc = line.split("=", 1)[1].strip().strip('"').strip("'")
|
|
241
|
+
if desc:
|
|
242
|
+
lines.append(f"- **Description:** {desc}")
|
|
243
|
+
break
|
|
244
|
+
except Exception:
|
|
245
|
+
pass
|
|
246
|
+
break
|
|
247
|
+
return lines
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
_DOMAIN_STOP_WORDS = frozenset(
|
|
251
|
+
{
|
|
252
|
+
# Generic programming
|
|
253
|
+
"get",
|
|
254
|
+
"set",
|
|
255
|
+
"new",
|
|
256
|
+
"init",
|
|
257
|
+
"create",
|
|
258
|
+
"make",
|
|
259
|
+
"build",
|
|
260
|
+
"run",
|
|
261
|
+
"test",
|
|
262
|
+
"handle",
|
|
263
|
+
"process",
|
|
264
|
+
"parse",
|
|
265
|
+
"format",
|
|
266
|
+
"check",
|
|
267
|
+
"has",
|
|
268
|
+
"the",
|
|
269
|
+
"from",
|
|
270
|
+
"with",
|
|
271
|
+
"for",
|
|
272
|
+
"add",
|
|
273
|
+
"remove",
|
|
274
|
+
"delete",
|
|
275
|
+
"update",
|
|
276
|
+
"find",
|
|
277
|
+
"load",
|
|
278
|
+
"save",
|
|
279
|
+
"read",
|
|
280
|
+
"write",
|
|
281
|
+
"send",
|
|
282
|
+
"resolve",
|
|
283
|
+
"validate",
|
|
284
|
+
"setup",
|
|
285
|
+
"use",
|
|
286
|
+
"can",
|
|
287
|
+
"should",
|
|
288
|
+
"will",
|
|
289
|
+
"not",
|
|
290
|
+
"all",
|
|
291
|
+
"any",
|
|
292
|
+
"map",
|
|
293
|
+
"list",
|
|
294
|
+
"item",
|
|
295
|
+
"data",
|
|
296
|
+
"type",
|
|
297
|
+
"name",
|
|
298
|
+
"value",
|
|
299
|
+
"key",
|
|
300
|
+
"index",
|
|
301
|
+
"count",
|
|
302
|
+
"result",
|
|
303
|
+
"response",
|
|
304
|
+
"request",
|
|
305
|
+
"error",
|
|
306
|
+
"node",
|
|
307
|
+
"path",
|
|
308
|
+
"base",
|
|
309
|
+
"util",
|
|
310
|
+
"utils",
|
|
311
|
+
"helper",
|
|
312
|
+
"helpers",
|
|
313
|
+
"model",
|
|
314
|
+
"models",
|
|
315
|
+
# UI / framework
|
|
316
|
+
"props",
|
|
317
|
+
"emit",
|
|
318
|
+
"emits",
|
|
319
|
+
"ref",
|
|
320
|
+
"computed",
|
|
321
|
+
"watch",
|
|
322
|
+
"reactive",
|
|
323
|
+
"component",
|
|
324
|
+
"view",
|
|
325
|
+
"render",
|
|
326
|
+
"mount",
|
|
327
|
+
"unmount",
|
|
328
|
+
"click",
|
|
329
|
+
"submit",
|
|
330
|
+
"change",
|
|
331
|
+
"input",
|
|
332
|
+
"select",
|
|
333
|
+
"close",
|
|
334
|
+
"open",
|
|
335
|
+
"show",
|
|
336
|
+
"hide",
|
|
337
|
+
"toggle",
|
|
338
|
+
"modal",
|
|
339
|
+
"form",
|
|
340
|
+
"field",
|
|
341
|
+
"row",
|
|
342
|
+
"col",
|
|
343
|
+
"icon",
|
|
344
|
+
"btn",
|
|
345
|
+
"wrapper",
|
|
346
|
+
"slot",
|
|
347
|
+
"class",
|
|
348
|
+
"style",
|
|
349
|
+
"define",
|
|
350
|
+
"expose",
|
|
351
|
+
"provide",
|
|
352
|
+
"inject",
|
|
353
|
+
# Vue/React/Angular
|
|
354
|
+
"state",
|
|
355
|
+
"store",
|
|
356
|
+
"action",
|
|
357
|
+
"dispatch",
|
|
358
|
+
"reducer",
|
|
359
|
+
"effect",
|
|
360
|
+
"callback",
|
|
361
|
+
"memo",
|
|
362
|
+
"context",
|
|
363
|
+
"hook",
|
|
364
|
+
# DOM events / UI interactions
|
|
365
|
+
"click",
|
|
366
|
+
"focus",
|
|
367
|
+
"blur",
|
|
368
|
+
"hover",
|
|
369
|
+
"scroll",
|
|
370
|
+
"resize",
|
|
371
|
+
"keydown",
|
|
372
|
+
"keyup",
|
|
373
|
+
"keypress",
|
|
374
|
+
"mousedown",
|
|
375
|
+
"mouseup",
|
|
376
|
+
"mouseover",
|
|
377
|
+
"mouseenter",
|
|
378
|
+
"mouseleave",
|
|
379
|
+
"touchstart",
|
|
380
|
+
"touchend",
|
|
381
|
+
"touchmove",
|
|
382
|
+
"drag",
|
|
383
|
+
"drop",
|
|
384
|
+
"dropdown",
|
|
385
|
+
"popover",
|
|
386
|
+
"tooltip",
|
|
387
|
+
"overlay",
|
|
388
|
+
"collapse",
|
|
389
|
+
"expand",
|
|
390
|
+
"visible",
|
|
391
|
+
"disabled",
|
|
392
|
+
"active",
|
|
393
|
+
"selected",
|
|
394
|
+
"loading",
|
|
395
|
+
"loaded",
|
|
396
|
+
"pending",
|
|
397
|
+
"ready",
|
|
398
|
+
"mounted",
|
|
399
|
+
"updated",
|
|
400
|
+
"before",
|
|
401
|
+
"after",
|
|
402
|
+
"enter",
|
|
403
|
+
"leave",
|
|
404
|
+
"transition",
|
|
405
|
+
"animate",
|
|
406
|
+
"width",
|
|
407
|
+
"height",
|
|
408
|
+
"size",
|
|
409
|
+
"offset",
|
|
410
|
+
"position",
|
|
411
|
+
"layout",
|
|
412
|
+
"container",
|
|
413
|
+
"content",
|
|
414
|
+
"header",
|
|
415
|
+
"footer",
|
|
416
|
+
"sidebar",
|
|
417
|
+
"panel",
|
|
418
|
+
"tab",
|
|
419
|
+
"tabs",
|
|
420
|
+
"menu",
|
|
421
|
+
"nav",
|
|
422
|
+
"link",
|
|
423
|
+
"button",
|
|
424
|
+
"label",
|
|
425
|
+
"text",
|
|
426
|
+
"image",
|
|
427
|
+
"avatar",
|
|
428
|
+
"badge",
|
|
429
|
+
"card",
|
|
430
|
+
"dialog",
|
|
431
|
+
"drawer",
|
|
432
|
+
"divider",
|
|
433
|
+
# Generic code patterns
|
|
434
|
+
"fetch",
|
|
435
|
+
"query",
|
|
436
|
+
"execute",
|
|
437
|
+
"apply",
|
|
438
|
+
"call",
|
|
439
|
+
"bind",
|
|
440
|
+
"start",
|
|
441
|
+
"stop",
|
|
442
|
+
"reset",
|
|
443
|
+
"clear",
|
|
444
|
+
"filter",
|
|
445
|
+
"sort",
|
|
446
|
+
"default",
|
|
447
|
+
"config",
|
|
448
|
+
"options",
|
|
449
|
+
"params",
|
|
450
|
+
"args",
|
|
451
|
+
}
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _section_domain(conn):
|
|
456
|
+
"""Infer project domain from symbol names and manifest files."""
|
|
457
|
+
import re
|
|
458
|
+
|
|
459
|
+
lines = ["", "## Domain Keywords", ""]
|
|
460
|
+
|
|
461
|
+
project_root = None
|
|
462
|
+
try:
|
|
463
|
+
from roam.db.connection import find_project_root
|
|
464
|
+
|
|
465
|
+
project_root = find_project_root()
|
|
466
|
+
except Exception:
|
|
467
|
+
pass
|
|
468
|
+
|
|
469
|
+
lines.extend(_read_manifest_info(project_root))
|
|
470
|
+
|
|
471
|
+
symbols = conn.execute(
|
|
472
|
+
"SELECT name FROM symbols WHERE kind IN ('function', 'class', 'method', 'interface', 'struct') LIMIT 2000"
|
|
473
|
+
).fetchall()
|
|
474
|
+
|
|
475
|
+
word_counts: dict[str, int] = {}
|
|
476
|
+
_split_re = re.compile(r"[A-Z][a-z]+|[a-z]+|[A-Z]+(?=[A-Z][a-z]|\b)")
|
|
477
|
+
for s in symbols:
|
|
478
|
+
for p in _split_re.findall(s["name"]):
|
|
479
|
+
w = p.lower()
|
|
480
|
+
if len(w) >= 3 and w not in _DOMAIN_STOP_WORDS:
|
|
481
|
+
word_counts[w] = word_counts.get(w, 0) + 1
|
|
482
|
+
|
|
483
|
+
top_words = sorted(
|
|
484
|
+
word_counts.items(),
|
|
485
|
+
key=lambda x: -(x[1] * (1 + max(0, len(x[0]) - 4) * 0.15)),
|
|
486
|
+
)[:20]
|
|
487
|
+
if top_words:
|
|
488
|
+
lines.append(f"- **Top domain terms:** {', '.join(w for w, _ in top_words)}")
|
|
489
|
+
|
|
490
|
+
return lines
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _section_conventions(conn):
|
|
494
|
+
"""Document detected coding conventions for agents to follow."""
|
|
495
|
+
import re
|
|
496
|
+
|
|
497
|
+
lines = ["", "## Coding Conventions", ""]
|
|
498
|
+
lines.append("Follow these conventions when writing code in this project:")
|
|
499
|
+
lines.append("")
|
|
500
|
+
|
|
501
|
+
_SNAKE = re.compile(r"^[a-z_][a-z0-9_]*$")
|
|
502
|
+
_CAMEL = re.compile(r"^[a-z][a-zA-Z0-9]*$")
|
|
503
|
+
_PASCAL = re.compile(r"^[A-Z][a-zA-Z0-9]*$")
|
|
504
|
+
|
|
505
|
+
for kind, label in [("function", "Functions"), ("class", "Classes"), ("method", "Methods")]:
|
|
506
|
+
rows = conn.execute("SELECT name FROM symbols WHERE kind = ?", (kind,)).fetchall()
|
|
507
|
+
if not rows:
|
|
508
|
+
continue
|
|
509
|
+
names = [r["name"] for r in rows]
|
|
510
|
+
counts = {"snake_case": 0, "camelCase": 0, "PascalCase": 0}
|
|
511
|
+
for n in names:
|
|
512
|
+
if _PASCAL.match(n):
|
|
513
|
+
counts["PascalCase"] += 1
|
|
514
|
+
elif _SNAKE.match(n):
|
|
515
|
+
counts["snake_case"] += 1
|
|
516
|
+
elif _CAMEL.match(n):
|
|
517
|
+
counts["camelCase"] += 1
|
|
518
|
+
dominant = max(counts, key=counts.get)
|
|
519
|
+
total = len(names)
|
|
520
|
+
pct = round(counts[dominant] * 100 / total) if total else 0
|
|
521
|
+
if pct >= 80:
|
|
522
|
+
kind_plural = "classes" if kind == "class" else f"{kind}s"
|
|
523
|
+
lines.append(f"- **{label}:** Use `{dominant}` ({pct}% of {total} {kind_plural})")
|
|
524
|
+
|
|
525
|
+
# Import style
|
|
526
|
+
try:
|
|
527
|
+
total_edges = conn.execute("SELECT COUNT(*) FROM file_edges").fetchone()[0]
|
|
528
|
+
cross_dir = conn.execute(
|
|
529
|
+
"SELECT COUNT(*) FROM file_edges fe "
|
|
530
|
+
"JOIN files sf ON fe.source_file_id = sf.id "
|
|
531
|
+
"JOIN files tf ON fe.target_file_id = tf.id "
|
|
532
|
+
"WHERE sf.path NOT LIKE tf.path || '%'"
|
|
533
|
+
).fetchone()[0]
|
|
534
|
+
if total_edges > 0:
|
|
535
|
+
pct = round(cross_dir * 100 / total_edges)
|
|
536
|
+
if pct > 60:
|
|
537
|
+
lines.append(f"- **Imports:** Prefer absolute imports ({pct}% are cross-directory)")
|
|
538
|
+
else:
|
|
539
|
+
lines.append(f"- **Imports:** Relative imports common ({100 - pct}% same-directory)")
|
|
540
|
+
except Exception:
|
|
541
|
+
pass
|
|
542
|
+
|
|
543
|
+
# Test patterns
|
|
544
|
+
test_files = conn.execute("SELECT path FROM files WHERE path LIKE '%test%'").fetchall()
|
|
545
|
+
if test_files:
|
|
546
|
+
patterns = set()
|
|
547
|
+
for r in test_files:
|
|
548
|
+
name = r["path"].replace("\\", "/").split("/")[-1]
|
|
549
|
+
if name.startswith("test_"):
|
|
550
|
+
patterns.add("test_*.py")
|
|
551
|
+
elif name.endswith("_test.py"):
|
|
552
|
+
patterns.add("*_test.py")
|
|
553
|
+
elif ".test." in name:
|
|
554
|
+
patterns.add("*.test.*")
|
|
555
|
+
elif ".spec." in name:
|
|
556
|
+
patterns.add("*.spec.*")
|
|
557
|
+
if patterns:
|
|
558
|
+
lines.append(f"- **Test files:** {', '.join(sorted(patterns))}")
|
|
559
|
+
|
|
560
|
+
return lines
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _section_complexity_guide(conn):
|
|
564
|
+
"""Document complexity hotspots to guide refactoring."""
|
|
565
|
+
lines = ["", "## Complexity Hotspots", ""]
|
|
566
|
+
|
|
567
|
+
try:
|
|
568
|
+
row = conn.execute(
|
|
569
|
+
"SELECT COUNT(*) as total, AVG(cognitive_complexity) as avg_cc FROM symbol_metrics"
|
|
570
|
+
).fetchone()
|
|
571
|
+
if not row or row["total"] == 0:
|
|
572
|
+
return lines
|
|
573
|
+
|
|
574
|
+
lines.append(f"Average function complexity: {row['avg_cc']:.1f} ({row['total']} functions analyzed)")
|
|
575
|
+
lines.append("")
|
|
576
|
+
|
|
577
|
+
critical = conn.execute(
|
|
578
|
+
"SELECT s.name, sm.cognitive_complexity, f.path, s.line_start "
|
|
579
|
+
"FROM symbol_metrics sm "
|
|
580
|
+
"JOIN symbols s ON sm.symbol_id = s.id "
|
|
581
|
+
"JOIN files f ON s.file_id = f.id "
|
|
582
|
+
"WHERE sm.cognitive_complexity >= 25 "
|
|
583
|
+
"ORDER BY sm.cognitive_complexity DESC LIMIT 10"
|
|
584
|
+
).fetchall()
|
|
585
|
+
|
|
586
|
+
if critical:
|
|
587
|
+
lines.append("Functions with highest complexity (consider refactoring):")
|
|
588
|
+
lines.append("")
|
|
589
|
+
lines.append("| Function | Complexity | Location |")
|
|
590
|
+
lines.append("|----------|-----------|----------|")
|
|
591
|
+
for r in critical:
|
|
592
|
+
lines.append(f"| `{r['name']}` | {r['cognitive_complexity']:.0f} | `{r['path']}:{r['line_start']}` |")
|
|
593
|
+
except Exception:
|
|
594
|
+
pass
|
|
595
|
+
|
|
596
|
+
return lines
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _section_dependencies(conn):
|
|
600
|
+
"""Top imported files (most incoming file_edges)."""
|
|
601
|
+
lines = ["", "## Core Modules", ""]
|
|
602
|
+
try:
|
|
603
|
+
top_deps = conn.execute("""
|
|
604
|
+
SELECT f.path, COUNT(*) as import_count, SUM(fe.symbol_count) as total_symbols
|
|
605
|
+
FROM file_edges fe
|
|
606
|
+
JOIN files f ON fe.target_file_id = f.id
|
|
607
|
+
GROUP BY fe.target_file_id
|
|
608
|
+
ORDER BY import_count DESC
|
|
609
|
+
LIMIT 10
|
|
610
|
+
""").fetchall()
|
|
611
|
+
except Exception:
|
|
612
|
+
lines.append("File edge data not available.")
|
|
613
|
+
return lines
|
|
614
|
+
|
|
615
|
+
if not top_deps:
|
|
616
|
+
lines.append("No dependency data available.")
|
|
617
|
+
return lines
|
|
618
|
+
|
|
619
|
+
lines.append("Most-imported modules (everything depends on these):")
|
|
620
|
+
lines.append("")
|
|
621
|
+
lines.append("| Module | Imported By | Symbols Used |")
|
|
622
|
+
lines.append("|--------|-------------|--------------|")
|
|
623
|
+
for r in top_deps:
|
|
624
|
+
lines.append(f"| `{r['path']}` | {r['import_count']} files | {r['total_symbols']} |")
|
|
625
|
+
return lines
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _agent_prompt_data(conn):
|
|
629
|
+
"""Gather compact data for --agent-prompt output."""
|
|
630
|
+
import re
|
|
631
|
+
|
|
632
|
+
data = {}
|
|
633
|
+
|
|
634
|
+
# ── Project overview ─────────────────────────────────────────────
|
|
635
|
+
total_files = conn.execute("SELECT COUNT(*) FROM files").fetchone()[0]
|
|
636
|
+
total_symbols = conn.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
|
|
637
|
+
|
|
638
|
+
files = conn.execute("SELECT language FROM files").fetchall()
|
|
639
|
+
lang_counts = Counter(f["language"] for f in files if f["language"])
|
|
640
|
+
languages = ", ".join(lang for lang, _ in lang_counts.most_common(5))
|
|
641
|
+
|
|
642
|
+
# Infer project name from project root directory
|
|
643
|
+
try:
|
|
644
|
+
root = find_project_root()
|
|
645
|
+
project_name = root.name
|
|
646
|
+
except Exception:
|
|
647
|
+
project_name = "unknown"
|
|
648
|
+
|
|
649
|
+
data["project"] = project_name
|
|
650
|
+
data["files"] = total_files
|
|
651
|
+
data["symbols"] = total_symbols
|
|
652
|
+
data["languages"] = languages
|
|
653
|
+
|
|
654
|
+
# ── Stack / key dependencies (from most-imported files) ──────────
|
|
655
|
+
try:
|
|
656
|
+
top_imports = conn.execute("""
|
|
657
|
+
SELECT f.path, COUNT(*) as import_count
|
|
658
|
+
FROM file_edges fe
|
|
659
|
+
JOIN files f ON fe.target_file_id = f.id
|
|
660
|
+
GROUP BY fe.target_file_id
|
|
661
|
+
ORDER BY import_count DESC
|
|
662
|
+
LIMIT 10
|
|
663
|
+
""").fetchall()
|
|
664
|
+
stack_items = []
|
|
665
|
+
for r in top_imports:
|
|
666
|
+
p = r["path"].replace("\\", "/")
|
|
667
|
+
# Use top-level directory or filename as dependency hint
|
|
668
|
+
parts = p.split("/")
|
|
669
|
+
stack_items.append(parts[0] if len(parts) > 1 else p)
|
|
670
|
+
# Deduplicate preserving order
|
|
671
|
+
seen = set()
|
|
672
|
+
stack_deduped = []
|
|
673
|
+
for s in stack_items:
|
|
674
|
+
if s not in seen:
|
|
675
|
+
seen.add(s)
|
|
676
|
+
stack_deduped.append(s)
|
|
677
|
+
data["stack"] = ", ".join(stack_deduped[:8])
|
|
678
|
+
except Exception:
|
|
679
|
+
data["stack"] = ""
|
|
680
|
+
|
|
681
|
+
# ── Conventions ──────────────────────────────────────────────────
|
|
682
|
+
_SNAKE = re.compile(r"^[a-z_][a-z0-9_]*$")
|
|
683
|
+
_CAMEL = re.compile(r"^[a-z][a-zA-Z0-9]*$")
|
|
684
|
+
_PASCAL = re.compile(r"^[A-Z][a-zA-Z0-9]*$")
|
|
685
|
+
|
|
686
|
+
conventions = []
|
|
687
|
+
for kind, label in [("function", "functions"), ("class", "classes"), ("method", "methods")]:
|
|
688
|
+
rows = conn.execute("SELECT name FROM symbols WHERE kind = ?", (kind,)).fetchall()
|
|
689
|
+
if not rows:
|
|
690
|
+
continue
|
|
691
|
+
counts = {"snake_case": 0, "camelCase": 0, "PascalCase": 0}
|
|
692
|
+
for r in rows:
|
|
693
|
+
n = r["name"]
|
|
694
|
+
if _PASCAL.match(n):
|
|
695
|
+
counts["PascalCase"] += 1
|
|
696
|
+
elif _SNAKE.match(n):
|
|
697
|
+
counts["snake_case"] += 1
|
|
698
|
+
elif _CAMEL.match(n):
|
|
699
|
+
counts["camelCase"] += 1
|
|
700
|
+
dominant = max(counts, key=counts.get)
|
|
701
|
+
total = len(rows)
|
|
702
|
+
pct = round(counts[dominant] * 100 / total) if total else 0
|
|
703
|
+
if pct >= 70:
|
|
704
|
+
conventions.append(f"{label}={dominant}")
|
|
705
|
+
data["conventions"] = ", ".join(conventions) if conventions else "mixed"
|
|
706
|
+
|
|
707
|
+
# ── Directory structure ──────────────────────────────────────────
|
|
708
|
+
dir_rows = conn.execute("""
|
|
709
|
+
SELECT CASE WHEN INSTR(REPLACE(path, '\\', '/'), '/') > 0
|
|
710
|
+
THEN SUBSTR(REPLACE(path, '\\', '/'), 1, INSTR(REPLACE(path, '\\', '/'), '/') - 1)
|
|
711
|
+
ELSE '.' END as dir,
|
|
712
|
+
COUNT(*) as cnt
|
|
713
|
+
FROM files GROUP BY dir ORDER BY cnt DESC
|
|
714
|
+
""").fetchall()
|
|
715
|
+
dir_parts = [f"{r['dir']}/ ({r['cnt']})" for r in dir_rows[:8]]
|
|
716
|
+
data["structure"] = ", ".join(dir_parts)
|
|
717
|
+
|
|
718
|
+
# ── Key abstractions (top 5 by PageRank) ─────────────────────────
|
|
719
|
+
abstractions = []
|
|
720
|
+
try:
|
|
721
|
+
top = conn.execute("""
|
|
722
|
+
SELECT s.name, s.kind, f.path as file_path, gm.pagerank
|
|
723
|
+
FROM symbols s
|
|
724
|
+
JOIN files f ON s.file_id = f.id
|
|
725
|
+
JOIN graph_metrics gm ON s.id = gm.symbol_id
|
|
726
|
+
WHERE s.kind IN ('function', 'class', 'method', 'interface', 'struct', 'trait')
|
|
727
|
+
ORDER BY gm.pagerank DESC LIMIT 5
|
|
728
|
+
""").fetchall()
|
|
729
|
+
for s in top:
|
|
730
|
+
abstractions.append(f"{s['name']} ({s['kind']}, {s['file_path']})")
|
|
731
|
+
except Exception:
|
|
732
|
+
pass
|
|
733
|
+
data["key_abstractions"] = abstractions
|
|
734
|
+
|
|
735
|
+
# ── Hotspots (top 3 by churn * complexity) ───────────────────────
|
|
736
|
+
hotspots = []
|
|
737
|
+
try:
|
|
738
|
+
rows = conn.execute("""
|
|
739
|
+
SELECT s.name, f.path, sm.cognitive_complexity,
|
|
740
|
+
COALESCE(gs.commit_count, 0) as churn
|
|
741
|
+
FROM symbol_metrics sm
|
|
742
|
+
JOIN symbols s ON sm.symbol_id = s.id
|
|
743
|
+
JOIN files f ON s.file_id = f.id
|
|
744
|
+
LEFT JOIN git_stats gs ON f.id = gs.file_id
|
|
745
|
+
WHERE sm.cognitive_complexity > 0
|
|
746
|
+
ORDER BY (sm.cognitive_complexity * COALESCE(gs.commit_count, 1)) DESC
|
|
747
|
+
LIMIT 3
|
|
748
|
+
""").fetchall()
|
|
749
|
+
for r in rows:
|
|
750
|
+
hotspots.append(
|
|
751
|
+
f"{r['name']} (complexity={r['cognitive_complexity']:.0f}, churn={r['churn']}, {r['path']})"
|
|
752
|
+
)
|
|
753
|
+
except Exception:
|
|
754
|
+
pass
|
|
755
|
+
data["hotspots"] = hotspots
|
|
756
|
+
|
|
757
|
+
# ── Health score + cycles ────────────────────────────────────────
|
|
758
|
+
data["health_score"] = "N/A"
|
|
759
|
+
data["cycles"] = "N/A"
|
|
760
|
+
try:
|
|
761
|
+
from roam.graph.builder import build_symbol_graph
|
|
762
|
+
from roam.graph.cycles import find_cycles
|
|
763
|
+
|
|
764
|
+
G = build_symbol_graph(conn)
|
|
765
|
+
total_syms = len(G)
|
|
766
|
+
if total_syms > 0:
|
|
767
|
+
cycles = find_cycles(G)
|
|
768
|
+
cycle_syms = sum(len(c) for c in cycles)
|
|
769
|
+
cycle_pct = (cycle_syms / total_syms * 100) if total_syms else 0
|
|
770
|
+
score = max(0, 100 - int(cycle_pct * 2))
|
|
771
|
+
data["health_score"] = score
|
|
772
|
+
data["cycles"] = len(cycles)
|
|
773
|
+
except Exception:
|
|
774
|
+
pass
|
|
775
|
+
|
|
776
|
+
# ── Test command guess ───────────────────────────────────────────
|
|
777
|
+
test_files = conn.execute("SELECT path FROM files WHERE path LIKE '%test%' LIMIT 1").fetchall()
|
|
778
|
+
if test_files:
|
|
779
|
+
p = test_files[0]["path"].replace("\\", "/")
|
|
780
|
+
if "tests/" in p:
|
|
781
|
+
data["test_cmd"] = "pytest tests/"
|
|
782
|
+
elif "test/" in p:
|
|
783
|
+
data["test_cmd"] = "pytest test/"
|
|
784
|
+
elif ".spec." in p or ".test." in p:
|
|
785
|
+
data["test_cmd"] = "npm test"
|
|
786
|
+
else:
|
|
787
|
+
data["test_cmd"] = "pytest"
|
|
788
|
+
else:
|
|
789
|
+
data["test_cmd"] = ""
|
|
790
|
+
|
|
791
|
+
return data
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _format_agent_prompt(data: dict) -> str:
|
|
795
|
+
"""Format agent-prompt data as compact plain text."""
|
|
796
|
+
lines = []
|
|
797
|
+
lines.append(f"Project: {data['project']} ({data['files']} files, {data['symbols']} symbols, {data['languages']})")
|
|
798
|
+
if data.get("stack"):
|
|
799
|
+
lines.append(f"Stack: {data['stack']}")
|
|
800
|
+
lines.append(f"Conventions: {data['conventions']}")
|
|
801
|
+
lines.append(f"Structure: {data['structure']}")
|
|
802
|
+
|
|
803
|
+
if data.get("key_abstractions"):
|
|
804
|
+
lines.append("Key abstractions:")
|
|
805
|
+
for a in data["key_abstractions"]:
|
|
806
|
+
lines.append(f" - {a}")
|
|
807
|
+
|
|
808
|
+
if data.get("hotspots"):
|
|
809
|
+
lines.append("Hotspots:")
|
|
810
|
+
for h in data["hotspots"]:
|
|
811
|
+
lines.append(f" - {h}")
|
|
812
|
+
|
|
813
|
+
health = data.get("health_score", "N/A")
|
|
814
|
+
cycles = data.get("cycles", "N/A")
|
|
815
|
+
lines.append(f"Health: {health}/100, {cycles} cycles")
|
|
816
|
+
|
|
817
|
+
if data.get("test_cmd"):
|
|
818
|
+
lines.append(f"Test cmd: {data['test_cmd']}")
|
|
819
|
+
|
|
820
|
+
return "\n".join(lines)
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
# Roam usage instructions prepended to written agent config files.
|
|
824
|
+
# Mirrors the "Copy-paste agent instructions" block in the README.
|
|
825
|
+
_ROAM_USAGE_INSTRUCTIONS = """\
|
|
826
|
+
## Codebase navigation with roam
|
|
827
|
+
|
|
828
|
+
This project uses `roam` for codebase comprehension. Always prefer roam \
|
|
829
|
+
over Glob/Grep/Read exploration.
|
|
830
|
+
|
|
831
|
+
Before modifying any code:
|
|
832
|
+
1. First time in the repo: `roam understand` then `roam tour`
|
|
833
|
+
2. Find a symbol: `roam search <pattern>`
|
|
834
|
+
3. Before changing a symbol: `roam preflight <name>` (blast radius + tests + fitness)
|
|
835
|
+
4. Need files to read: `roam context <name>` (files + line ranges, prioritized)
|
|
836
|
+
5. Debugging a failure: `roam diagnose <name>` (root cause ranking)
|
|
837
|
+
6. After making changes: `roam diff` (blast radius of uncommitted changes)
|
|
838
|
+
|
|
839
|
+
Additional commands: `roam health` (0-100 score), `roam impact <name>` (what breaks),
|
|
840
|
+
`roam pr-risk` (PR risk score), `roam file <path>` (file skeleton).
|
|
841
|
+
|
|
842
|
+
Run `roam --help` for all commands. Use `roam --json <cmd>` for structured output.
|
|
843
|
+
"""
|
|
844
|
+
|
|
845
|
+
# Agent config file detection order — first existing file wins.
|
|
846
|
+
# If none exist, fall back to CLAUDE.md (most common).
|
|
847
|
+
_AGENT_CONFIG_FILES = [
|
|
848
|
+
"CLAUDE.md", # Claude Code
|
|
849
|
+
"AGENTS.md", # OpenAI Codex CLI
|
|
850
|
+
"GEMINI.md", # Gemini CLI
|
|
851
|
+
".cursor/rules/roam.mdc", # Cursor
|
|
852
|
+
".windsurf/rules/roam.md", # Windsurf
|
|
853
|
+
".github/copilot-instructions.md", # GitHub Copilot
|
|
854
|
+
"CONVENTIONS.md", # Aider / generic
|
|
855
|
+
".clinerules/roam.md", # Cline
|
|
856
|
+
]
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def _detect_agent_config(root: "Path") -> "Path":
|
|
860
|
+
"""Auto-detect the right agent config file in the project.
|
|
861
|
+
|
|
862
|
+
Checks for existing AI tool config files in priority order.
|
|
863
|
+
If one already exists, returns it (so ``--write`` updates the right file).
|
|
864
|
+
Otherwise defaults to ``CLAUDE.md``.
|
|
865
|
+
"""
|
|
866
|
+
for rel in _AGENT_CONFIG_FILES:
|
|
867
|
+
candidate = root / rel
|
|
868
|
+
if candidate.exists():
|
|
869
|
+
return candidate
|
|
870
|
+
return root / "CLAUDE.md"
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
@click.command()
|
|
874
|
+
@click.option("--write", is_flag=True, help="Write output to the detected agent config file")
|
|
875
|
+
@click.option("--force", is_flag=True, help="Overwrite existing file without confirmation")
|
|
876
|
+
@click.option("--agent-prompt", is_flag=True, help="Compact agent-oriented prompt (under 500 tokens)")
|
|
877
|
+
@click.option(
|
|
878
|
+
"-o",
|
|
879
|
+
"--output",
|
|
880
|
+
"out_file",
|
|
881
|
+
default=None,
|
|
882
|
+
help="Explicit output path (overrides auto-detection)",
|
|
883
|
+
)
|
|
884
|
+
@click.pass_context
|
|
885
|
+
def describe(ctx, write, force, agent_prompt, out_file):
|
|
886
|
+
"""Auto-generate a project description for AI coding agents.
|
|
887
|
+
|
|
888
|
+
By default prints to stdout. Use ``--write`` to save to your agent's
|
|
889
|
+
config file (auto-detected: CLAUDE.md, AGENTS.md, .cursor/rules, etc.)
|
|
890
|
+
or ``-o PATH`` to specify an explicit output path.
|
|
891
|
+
"""
|
|
892
|
+
json_mode = ctx.obj.get("json") if ctx.obj else False
|
|
893
|
+
ensure_index()
|
|
894
|
+
|
|
895
|
+
if agent_prompt:
|
|
896
|
+
with open_db(readonly=True) as conn:
|
|
897
|
+
data = _agent_prompt_data(conn)
|
|
898
|
+
|
|
899
|
+
if json_mode:
|
|
900
|
+
click.echo(
|
|
901
|
+
to_json(
|
|
902
|
+
json_envelope(
|
|
903
|
+
"describe",
|
|
904
|
+
summary={"mode": "agent-prompt"},
|
|
905
|
+
**data,
|
|
906
|
+
)
|
|
907
|
+
)
|
|
908
|
+
)
|
|
909
|
+
else:
|
|
910
|
+
click.echo(_format_agent_prompt(data))
|
|
911
|
+
return
|
|
912
|
+
|
|
913
|
+
with open_db(readonly=True) as conn:
|
|
914
|
+
sections = []
|
|
915
|
+
sections.append(["# Project Architecture", ""])
|
|
916
|
+
sections.append(_section_overview(conn))
|
|
917
|
+
sections.append(_section_directories(conn))
|
|
918
|
+
sections.append(_section_entry_points(conn))
|
|
919
|
+
sections.append(_section_key_abstractions(conn))
|
|
920
|
+
sections.append(_section_architecture(conn))
|
|
921
|
+
sections.append(_section_testing(conn))
|
|
922
|
+
sections.append(_section_conventions(conn))
|
|
923
|
+
sections.append(_section_complexity_guide(conn))
|
|
924
|
+
sections.append(_section_domain(conn))
|
|
925
|
+
sections.append(_section_dependencies(conn))
|
|
926
|
+
|
|
927
|
+
output = "\n".join(line for sec in sections for line in sec)
|
|
928
|
+
|
|
929
|
+
if json_mode:
|
|
930
|
+
click.echo(
|
|
931
|
+
to_json(
|
|
932
|
+
json_envelope(
|
|
933
|
+
"describe",
|
|
934
|
+
summary={"length": len(output)},
|
|
935
|
+
markdown=output,
|
|
936
|
+
)
|
|
937
|
+
)
|
|
938
|
+
)
|
|
939
|
+
return
|
|
940
|
+
|
|
941
|
+
if write or out_file:
|
|
942
|
+
from pathlib import Path
|
|
943
|
+
|
|
944
|
+
root = find_project_root()
|
|
945
|
+
if out_file:
|
|
946
|
+
out_path = Path(out_file)
|
|
947
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
948
|
+
else:
|
|
949
|
+
out_path = _detect_agent_config(root)
|
|
950
|
+
if out_path.exists() and not force:
|
|
951
|
+
click.echo(f"{out_path.name} already exists at {out_path}")
|
|
952
|
+
click.echo("Use --force to overwrite, or omit --write to print to stdout.")
|
|
953
|
+
return
|
|
954
|
+
# Prepend roam usage instructions so AI agents know how to use roam
|
|
955
|
+
write_output = _ROAM_USAGE_INSTRUCTIONS + "\n" + output
|
|
956
|
+
out_path.write_text(write_output, encoding="utf-8")
|
|
957
|
+
click.echo(f"Wrote {out_path}")
|
|
958
|
+
else:
|
|
959
|
+
click.echo(output)
|