-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrepomap.py
More file actions
922 lines (759 loc) · 30.8 KB
/
repomap.py
File metadata and controls
922 lines (759 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
#!/usr/bin/env python3
"""
Repomap - Generate AI-friendly code structure maps and steering guidance
Inspired by Aider's repomap.py
Extended with steering generation for AI agents
Purpose: Context window optimization + Agent steering guidance
"""
import argparse
import ast
import json
import os
import sys
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Set
try:
import tree_sitter_bash as tsbash
import tree_sitter_go as tsgo
import tree_sitter_javascript as tsjavascript
import tree_sitter_python as tspython
import tree_sitter_typescript as tstypescript
from tree_sitter import Language, Parser, Query, QueryCursor
except ImportError:
print(
"Error: Required tree-sitter packages not installed.", file=sys.stderr
)
print(
"Install with: pip install tree-sitter tree-sitter-python "
"tree-sitter-javascript tree-sitter-typescript tree-sitter-go "
"tree-sitter-bash",
file=sys.stderr,
)
sys.exit(1)
LANGUAGE_CONFIGS = {
".py": {
"language": Language(tspython.language()),
"queries": {
"function": "(function_definition name: (identifier) @name)",
"class": "(class_definition name: (identifier) @name)",
},
},
".js": {
"language": Language(tsjavascript.language()),
"queries": {
"function": "(function_declaration name: (identifier) @name)",
"class": "(class_declaration name: (identifier) @name)",
},
},
".ts": {
"language": Language(tstypescript.language_typescript()),
"queries": {
"function": "(function_declaration name: (identifier) @name)",
"class": "(class_declaration name: (identifier) @name)",
"interface": "(interface_declaration name: (type_identifier) @name)",
},
},
".tsx": {
"language": Language(tstypescript.language_tsx()),
"queries": {
"function": "(function_declaration name: (identifier) @name)",
"class": "(class_declaration name: (identifier) @name)",
"interface": "(interface_declaration name: (type_identifier) @name)",
},
},
".go": {
"language": Language(tsgo.language()),
"queries": {
"function": "(function_declaration name: (identifier) @name)",
"method": "(method_declaration name: (field_identifier) @name)",
"struct": "(type_declaration (type_spec name: (type_identifier) @name))",
},
},
".sh": {
"language": Language(tsbash.language()),
"queries": {
"function": "(function_definition name: (word) @name)",
},
},
".bash": {
"language": Language(tsbash.language()),
"queries": {
"function": "(function_definition name: (word) @name)",
},
},
}
@dataclass
class CodeSymbol:
"""Represents a code symbol (function, class, method, etc.)"""
name: str
type: str
line: int
parent: Optional[str] = None
@dataclass
class FileInfo:
"""Information about a parsed file"""
path: str
symbols: List[CodeSymbol]
error: Optional[str] = None
@dataclass
class FunctionSignature:
"""Detailed function signature for steering docs"""
name: str
params: List[str]
return_type: Optional[str]
decorators: List[str]
docstring: Optional[str]
line: int
file_path: str
is_async: bool = False
is_method: bool = False
class_name: Optional[str] = None
@dataclass
class ClassInfo:
"""Detailed class information for steering docs"""
name: str
bases: List[str]
methods: List[FunctionSignature]
docstring: Optional[str]
line: int
file_path: str
decorators: List[str]
class PythonAnalyzer:
"""Detailed Python code analysis for steering generation"""
def __init__(self, file_path: Path, code: str):
self.file_path = file_path
self.code = code
try:
self.tree = ast.parse(code)
except SyntaxError:
self.tree = None
def extract_docstring(self, node) -> Optional[str]:
"""Extract docstring from a node"""
if not isinstance(
node, (ast.FunctionDef, ast.ClassDef, ast.Module, ast.AsyncFunctionDef)
):
return None
if (
node.body
and isinstance(node.body[0], ast.Expr)
and isinstance(node.body[0].value, ast.Constant)
and isinstance(node.body[0].value.value, str)
):
return node.body[0].value.value.strip()
return None
def extract_type_annotation(self, annotation) -> Optional[str]:
"""Extract type annotation as string"""
if annotation is None:
return None
return ast.unparse(annotation)
def extract_decorators(self, node) -> List[str]:
"""Extract decorator names"""
decorators = []
for decorator in node.decorator_list:
if isinstance(decorator, ast.Name):
decorators.append(decorator.id)
elif isinstance(decorator, ast.Call) and isinstance(
decorator.func, ast.Name
):
decorators.append(decorator.func.id)
else:
decorators.append(ast.unparse(decorator))
return decorators
def extract_function_signature(
self, node, class_name: Optional[str] = None
) -> FunctionSignature:
"""Extract detailed function signature"""
params = []
for arg in node.args.args:
param_str = arg.arg
if arg.annotation:
param_str += f": {self.extract_type_annotation(arg.annotation)}"
params.append(param_str)
if node.args.vararg:
vararg = f"*{node.args.vararg.arg}"
if node.args.vararg.annotation:
vararg += f": {self.extract_type_annotation(node.args.vararg.annotation)}"
params.append(vararg)
if node.args.kwarg:
kwarg = f"**{node.args.kwarg.arg}"
if node.args.kwarg.annotation:
kwarg += f": {self.extract_type_annotation(node.args.kwarg.annotation)}"
params.append(kwarg)
return FunctionSignature(
name=node.name,
params=params,
return_type=self.extract_type_annotation(node.returns),
decorators=self.extract_decorators(node),
docstring=self.extract_docstring(node),
line=node.lineno,
file_path=str(self.file_path),
is_async=isinstance(node, ast.AsyncFunctionDef),
is_method=class_name is not None,
class_name=class_name,
)
def extract_classes(self) -> List[ClassInfo]:
"""Extract all class definitions"""
if not self.tree:
return []
classes = []
for node in ast.walk(self.tree):
if isinstance(node, ast.ClassDef):
bases = [ast.unparse(base) for base in node.bases]
methods = []
for item in node.body:
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
methods.append(
self.extract_function_signature(item, class_name=node.name)
)
classes.append(
ClassInfo(
name=node.name,
bases=bases,
methods=methods,
docstring=self.extract_docstring(node),
line=node.lineno,
file_path=str(self.file_path),
decorators=self.extract_decorators(node),
)
)
return classes
def extract_functions(self) -> List[FunctionSignature]:
"""Extract all top-level function definitions"""
if not self.tree:
return []
functions = []
for node in self.tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
functions.append(self.extract_function_signature(node))
return functions
class RepomapGenerator:
"""Generate repository structure maps using tree-sitter"""
def __init__(
self, root_dir: str, max_file_size: int = 1024 * 1024, verbose: bool = False
):
self.root_dir = Path(root_dir).resolve()
self.max_file_size = max_file_size
self.verbose = verbose
self.gitignore_patterns = self._load_gitignore()
def _load_gitignore(self) -> Set[str]:
"""Load .gitignore patterns"""
gitignore_path = self.root_dir / ".gitignore"
patterns = {
".git",
"__pycache__",
"node_modules",
".venv",
"venv",
"*.pyc",
".DS_Store",
".acp",
}
if gitignore_path.exists():
try:
with open(gitignore_path) as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
patterns.add(line)
except Exception as e:
if self.verbose:
print(
f"Warning: Could not read .gitignore: {e}", file=sys.stderr
)
return patterns
def _should_ignore(self, path: Path) -> bool:
"""Check if path should be ignored"""
relative_path = path.relative_to(self.root_dir)
path_str = str(relative_path)
for pattern in self.gitignore_patterns:
if pattern.startswith("*"):
if path_str.endswith(pattern[1:]):
return True
elif pattern in path.parts:
return True
elif path_str.startswith(pattern):
return True
return False
def _is_binary(self, file_path: Path) -> bool:
"""Check if file is binary"""
try:
with open(file_path, "rb") as f:
chunk = f.read(1024)
return b"\0" in chunk
except Exception:
return True
def _get_file_extension(self, file_path: Path) -> Optional[str]:
"""Get file extension if it's a supported language"""
ext = file_path.suffix.lower()
return ext if ext in LANGUAGE_CONFIGS else None
def _discover_files(self) -> List[Path]:
"""Discover all parseable files in the repository"""
files = []
for path in self.root_dir.rglob("*"):
if not path.is_file():
continue
if self._should_ignore(path):
continue
if not self._get_file_extension(path):
continue
if self._is_binary(path):
continue
try:
if path.stat().st_size > self.max_file_size:
if self.verbose:
print(f"Skipping large file: {path}", file=sys.stderr)
continue
except Exception:
continue
files.append(path)
return sorted(files)
def _parse_file(self, file_path: Path) -> FileInfo:
"""Parse a single file and extract symbols"""
relative_path = file_path.relative_to(self.root_dir)
ext = self._get_file_extension(file_path)
if not ext:
return FileInfo(str(relative_path), [], error="Unsupported file type")
config = LANGUAGE_CONFIGS[ext]
language = config["language"]
try:
with open(file_path, encoding="utf-8", errors="ignore") as f:
code = f.read()
parser = Parser(language)
tree = parser.parse(bytes(code, "utf8"))
symbols = []
for symbol_type, query_str in config["queries"].items():
try:
query = Query(language, query_str)
cursor = QueryCursor(query)
captures_dict = cursor.captures(tree.root_node)
if "name" in captures_dict:
for node in captures_dict["name"]:
symbol_name = code[node.start_byte : node.end_byte]
line = node.start_point[0] + 1
symbols.append(
CodeSymbol(name=symbol_name, type=symbol_type, line=line)
)
except Exception as e:
if self.verbose:
print(
f"Warning: Query failed for {symbol_type} in "
f"{relative_path}: {e}",
file=sys.stderr,
)
return FileInfo(str(relative_path), symbols)
except Exception as e:
return FileInfo(str(relative_path), [], error=str(e))
def _format_output(self, file_infos: List[FileInfo]) -> str:
"""Format file information as a tree structure"""
output = []
dir_files = defaultdict(list)
for file_info in file_infos:
path = Path(file_info.path)
dir_path = str(path.parent) if path.parent != Path(".") else ""
dir_files[dir_path].append(file_info)
for dir_path in sorted(dir_files.keys()):
if dir_path:
output.append(f"{dir_path}/")
for file_info in sorted(dir_files[dir_path], key=lambda f: f.path):
file_name = Path(file_info.path).name
indent = " " if dir_path else ""
output.append(f"{indent}{file_name}")
if file_info.error:
if self.verbose:
output.append(f"{indent} # Error: {file_info.error}")
else:
classes = sorted(
[
s
for s in file_info.symbols
if s.type in ("class", "struct", "interface")
],
key=lambda s: s.line,
)
functions = sorted(
[
s
for s in file_info.symbols
if s.type in ("function", "method")
],
key=lambda s: s.line,
)
shown_functions = set()
for i, symbol in enumerate(classes):
output.append(f"{indent} {symbol.type} {symbol.name}")
next_class_line = (
classes[i + 1].line if i + 1 < len(classes) else float("inf")
)
for func in functions:
if symbol.line < func.line < next_class_line:
output.append(f"{indent} def {func.name}()")
shown_functions.add(func.line)
for func in functions:
if func.line not in shown_functions:
output.append(f"{indent} def {func.name}()")
return "\n".join(output)
def generate(self, parallel: bool = True) -> str:
"""Generate the repository map"""
files = self._discover_files()
if not files:
return "# No parseable files found"
if self.verbose:
print(f"Processing {len(files)} files...", file=sys.stderr)
if parallel and len(files) > 1:
file_infos = []
with ProcessPoolExecutor() as executor:
futures = {executor.submit(self._parse_file, f): f for f in files}
for future in as_completed(futures):
try:
file_infos.append(future.result())
except Exception as e:
file_path = futures[future]
if self.verbose:
print(
f"Error processing {file_path}: {e}", file=sys.stderr
)
else:
file_infos = [self._parse_file(file_path) for file_path in files]
return self._format_output(file_infos)
class SteeringGenerator:
"""Generate steering guidance for AI agents"""
def __init__(
self,
root_dir: str,
repo_name: str,
output_dir: Optional[str] = None,
verbose: bool = False,
):
self.root_dir = Path(root_dir).resolve()
self.repo_name = repo_name
self.output_dir = (
Path(output_dir)
if output_dir
else Path.home() / ".acp" / "repos" / repo_name
)
self.verbose = verbose
self.functions: List[FunctionSignature] = []
self.classes: List[ClassInfo] = []
self.modules: Dict[str, Dict] = defaultdict(
lambda: {"functions": [], "classes": []}
)
def log(self, message: str):
"""Log verbose output"""
if self.verbose:
print(f"[STEERING] {message}", file=sys.stderr)
def analyze_codebase(self):
"""Analyze codebase and extract detailed information"""
self.log(f"Analyzing codebase in {self.root_dir}")
python_files = []
for path in self.root_dir.rglob("*.py"):
if not any(
p in path.parts for p in [".acp", "__pycache__", ".git", "venv", ".venv"]
):
python_files.append(path)
self.log(f"Found {len(python_files)} Python files")
for file_path in python_files:
try:
with open(file_path, encoding="utf-8", errors="ignore") as f:
code = f.read()
analyzer = PythonAnalyzer(
file_path.relative_to(self.root_dir), code
)
functions = analyzer.extract_functions()
classes = analyzer.extract_classes()
self.functions.extend(functions)
self.classes.extend(classes)
module_path = file_path.relative_to(self.root_dir).parent
module_key = str(module_path).replace("/", ".")
self.modules[module_key]["functions"].extend(functions)
self.modules[module_key]["classes"].extend(classes)
except Exception as e:
self.log(f"Error analyzing {file_path}: {e}")
self.log(f"Extracted {len(self.functions)} functions, {len(self.classes)} classes")
def generate_steering_files(self):
"""Generate steering guidance files"""
self.log("Generating steering files")
steering_dir = self.output_dir / "steering"
steering_dir.mkdir(parents=True, exist_ok=True)
for module_name, content in self.modules.items():
if not content["functions"] and not content["classes"]:
continue
steering_md = self._generate_module_steering(module_name, content)
module_file = module_name.replace(".", "_") or "root"
output_file = steering_dir / f"{module_file}.md"
with open(output_file, "w") as f:
f.write(steering_md)
self.log(f"Generated steering: {output_file}")
def _generate_module_steering(self, module_name: str, content: Dict) -> str:
"""Generate steering content for a module"""
md = f"# {module_name.title()}\n\n"
md += "## When to Use\n\n"
md += self._generate_when_to_use(content)
md += "\n## When NOT to Use\n\n"
md += self._generate_when_not_to_use()
md += "\n## Key Abstractions\n\n"
md += self._generate_key_abstractions(content)
md += "\n## Common Patterns\n\n"
md += self._generate_common_patterns(content)
return md
def _generate_when_to_use(self, content: Dict) -> str:
"""Generate when-to-use guidance"""
guidance = []
function_names = [f.name for f in content["functions"]]
class_names = [c.name for c in content["classes"]]
if any("create" in n.lower() for n in function_names + class_names):
guidance.append("When you need to create new instances or resources")
if any("delete" in n.lower() or "remove" in n.lower() for n in function_names):
guidance.append("When you need to remove or clean up resources")
if any("list" in n.lower() or "get" in n.lower() for n in function_names):
guidance.append("When you need to retrieve or query existing resources")
if any(
"update" in n.lower() or "edit" in n.lower() or "modify" in n.lower()
for n in function_names
):
guidance.append("When you need to modify existing resources")
if class_names:
guidance.append(
f"When working with {', '.join(class_names[:3])} abstractions"
)
if not guidance:
guidance.append("Refer to the API documentation for specific use cases")
return "\n".join(f"- {g}" for g in guidance) + "\n"
def _generate_when_not_to_use(self) -> str:
"""Generate when-not-to-use guidance"""
guidance = [
"For simple operations that don't require the full abstraction",
"When working with different resource types (check other modules)",
]
return "\n".join(f"- {g}" for g in guidance) + "\n"
def _generate_key_abstractions(self, content: Dict) -> str:
"""Generate key abstractions section"""
md = ""
for cls in content["classes"][:5]:
md += f"### {cls.name}\n\n"
if cls.docstring:
md += f"{cls.docstring.split(chr(10))[0]}\n\n"
if cls.methods:
md += "Key methods:\n"
for method in cls.methods[:5]:
params = ", ".join(method.params) if method.params else ""
md += f"- `{method.name}({params})`"
if method.docstring:
md += f": {method.docstring.split(chr(10))[0]}"
md += "\n"
md += "\n"
return md
def _generate_common_patterns(self, content: Dict) -> str:
"""Generate common patterns section"""
patterns = []
decorator_usage = defaultdict(list)
for func in content["functions"]:
for dec in func.decorators:
decorator_usage[dec].append(func.name)
for dec, usages in decorator_usage.items():
if len(usages) >= 2:
patterns.append(
f"- **{dec} decorator**: Used in {', '.join(usages[:3])}"
)
async_funcs = [f.name for f in content["functions"] if f.is_async]
if async_funcs:
patterns.append(
f"- **Async operations**: {', '.join(async_funcs[:3])} use async/await"
)
if not patterns:
patterns.append("- Follow standard Python conventions")
return "\n".join(patterns) + "\n"
def generate_docs_files(self):
"""Generate detailed API documentation files"""
self.log("Generating docs files")
docs_dir = self.output_dir / "docs"
docs_dir.mkdir(parents=True, exist_ok=True)
index_md = self._generate_index_doc()
with open(docs_dir / "index.md", "w") as f:
f.write(index_md)
for module_name, content in self.modules.items():
if not content["functions"] and not content["classes"]:
continue
docs_md = self._generate_module_docs(module_name, content)
module_file = module_name.replace(".", "_") or "root"
with open(docs_dir / f"{module_file}.md", "w") as f:
f.write(docs_md)
self.log(f"Generated docs: {module_file}.md")
def _generate_index_doc(self) -> str:
"""Generate index.md"""
md = f"# {self.repo_name.title()}\n\n"
md += f"API documentation for {self.repo_name}.\n\n"
md += "## Overview\n\n"
md += f"- **Modules**: {len(self.modules)}\n"
md += f"- **Functions**: {len(self.functions)}\n"
md += f"- **Classes**: {len(self.classes)}\n\n"
md += "## Modules\n\n"
for module_name in sorted(self.modules.keys()):
content = self.modules[module_name]
if content["functions"] or content["classes"]:
md += (
f"- **{module_name}**: {len(content['classes'])} classes, "
f"{len(content['functions'])} functions\n"
)
return md
def _generate_module_docs(self, module_name: str, content: Dict) -> str:
"""Generate API documentation for a module"""
md = f"# {module_name.title()}\n\n"
if content["classes"]:
md += "## Classes\n\n"
for cls in content["classes"]:
md += self._format_class_docs(cls)
if content["functions"]:
md += "## Functions\n\n"
for func in content["functions"]:
md += self._format_function_docs(func)
return md
def _format_class_docs(self, cls: ClassInfo) -> str:
"""Format class documentation"""
md = f"### {cls.name}\n\n"
if cls.docstring:
md += f"{cls.docstring}\n\n"
bases_str = f"({', '.join(cls.bases)})" if cls.bases else ""
md += "```python\n"
for dec in cls.decorators:
md += f"@{dec}\n"
md += f"class {cls.name}{bases_str}:\n"
if cls.methods:
for method in cls.methods[:3]:
async_prefix = "async " if method.is_async else ""
params = ", ".join(method.params) if method.params else ""
return_type = f" -> {method.return_type}" if method.return_type else ""
md += f" {async_prefix}def {method.name}({params}){return_type}\n"
else:
md += " ...\n"
md += "```\n\n"
if cls.methods:
md += "**Methods:**\n\n"
for method in cls.methods:
params = ", ".join(method.params) if method.params else ""
return_type = f" -> {method.return_type}" if method.return_type else ""
md += f"- `{method.name}({params}){return_type}`"
if method.docstring:
md += f": {method.docstring.split(chr(10))[0]}"
md += "\n"
md += "\n"
return md
def _format_function_docs(self, func: FunctionSignature) -> str:
"""Format function documentation"""
md = f"### {func.name}\n\n"
if func.docstring:
md += f"{func.docstring.split(chr(10) + chr(10))[0]}\n\n"
async_prefix = "async " if func.is_async else ""
params = ", ".join(func.params) if func.params else ""
return_type = f" -> {func.return_type}" if func.return_type else ""
md += "```python\n"
for dec in func.decorators:
md += f"@{dec}\n"
md += f"{async_prefix}def {func.name}({params}){return_type}\n"
md += "```\n\n"
if func.params:
md += "**Parameters:**\n\n"
for param in func.params:
md += f"- `{param}`\n"
md += "\n"
if func.return_type:
md += f"**Returns:** `{func.return_type}`\n\n"
return md
def generate_manifest(self):
"""Generate steering.json manifest"""
self.log("Generating manifest")
manifest = {
"name": self.repo_name,
"version": "1.0.0",
"generated_at": datetime.utcnow().isoformat(),
"statistics": {
"modules": len(self.modules),
"functions": len(self.functions),
"classes": len(self.classes),
},
}
with open(self.output_dir / "steering.json", "w") as f:
json.dump(manifest, f, indent=2)
self.log(f"Generated manifest: steering.json")
def generate(self):
"""Generate all steering content"""
self.log(f"Starting steering generation for {self.repo_name}")
self.output_dir.mkdir(parents=True, exist_ok=True)
self.analyze_codebase()
self.generate_steering_files()
self.generate_docs_files()
self.generate_manifest()
self.log(f"Steering generation complete! Output: {self.output_dir}")
return str(self.output_dir)
def main():
"""Main CLI entry point"""
parser = argparse.ArgumentParser(
description="Generate AI-friendly code structure maps and steering guidance",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
repomap . --repo-name platform
repomap /path/to/repo --repo-name workflows --output ~/.acp/repos/workflows
repomap . --repo-name platform --verbose
Generates:
1. Repository map (printed to stdout)
2. Steering content in .acp/repos/<repo-name>/
- steering/ (when/why guidance)
- docs/ (API documentation)
- steering.json (manifest)
""",
)
parser.add_argument(
"directory", nargs="?", default=".", help="Directory to analyze"
)
parser.add_argument("--repo-name", required=True, help="Repository name")
parser.add_argument(
"--output", help="Output directory (default: ~/.acp/repos/<repo-name>)"
)
parser.add_argument(
"--max-file-size",
type=int,
default=1024 * 1024,
help="Maximum file size in bytes",
)
parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
parser.add_argument(
"--no-parallel", action="store_true", help="Disable parallel processing"
)
args = parser.parse_args()
if not os.path.isdir(args.directory):
print(f"Error: '{args.directory}' is not a valid directory", file=sys.stderr)
sys.exit(1)
try:
# Generate repomap
repomap_generator = RepomapGenerator(
root_dir=args.directory,
max_file_size=args.max_file_size,
verbose=args.verbose,
)
repomap_output = repomap_generator.generate(parallel=not args.no_parallel)
print(repomap_output)
# Generate steering
steering_generator = SteeringGenerator(
root_dir=args.directory,
repo_name=args.repo_name,
output_dir=args.output,
verbose=args.verbose,
)
steering_path = steering_generator.generate()
if args.verbose:
print(f"\n✓ Steering content generated: {steering_path}", file=sys.stderr)
except KeyboardInterrupt:
print("\nInterrupted by user", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
if args.verbose:
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()