siada-cli 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.
Files changed (215) hide show
  1. agent_config.yaml +34 -0
  2. siada/__init__.py +13 -0
  3. siada/agent_hub/__init__.py +10 -0
  4. siada/agent_hub/coder/bug_fix_agent.py +398 -0
  5. siada/agent_hub/coder/code_gen_agent.py +235 -0
  6. siada/agent_hub/coder/fe_gen_agent.py +37 -0
  7. siada/agent_hub/coder/issue_review_agent.py +68 -0
  8. siada/agent_hub/coder/prompt/__init__.py +0 -0
  9. siada/agent_hub/coder/prompt/base/__init__.py +0 -0
  10. siada/agent_hub/coder/prompt/base/capabilities.py +18 -0
  11. siada/agent_hub/coder/prompt/base/non_interactive.py +14 -0
  12. siada/agent_hub/coder/prompt/base/prompt_builder.py +33 -0
  13. siada/agent_hub/coder/prompt/base/rules.py +40 -0
  14. siada/agent_hub/coder/prompt/base/tool_use.py +14 -0
  15. siada/agent_hub/coder/prompt/bug_prompt/bug_fix_prompt.py +51 -0
  16. siada/agent_hub/coder/prompt/bug_prompt/rules.py +53 -0
  17. siada/agent_hub/coder/prompt/code_gen_prompt.py +45 -0
  18. siada/agent_hub/coder/prompt/fe_gen_prompt.py +45 -0
  19. siada/agent_hub/coder/prompt/issue_review_prompt.py +121 -0
  20. siada/agent_hub/coder/tracing/__init__.py +22 -0
  21. siada/agent_hub/coder/tracing/logger_tracing_processor.py +458 -0
  22. siada/agent_hub/hooks/__init__.py +0 -0
  23. siada/agent_hub/hooks/io_hooks.py +30 -0
  24. siada/agent_hub/siada_agent.py +214 -0
  25. siada/config/__init__.py +0 -0
  26. siada/config/config_loader.py +67 -0
  27. siada/entrypoint/__init__.py +3 -0
  28. siada/entrypoint/args_parser/__init__.py +0 -0
  29. siada/entrypoint/args_parser/args.py +195 -0
  30. siada/entrypoint/interaction/__init__.py +0 -0
  31. siada/entrypoint/interaction/base_turn.py +107 -0
  32. siada/entrypoint/interaction/config.py +30 -0
  33. siada/entrypoint/interaction/controller.py +122 -0
  34. siada/entrypoint/interaction/nointeractive_controller.py +27 -0
  35. siada/entrypoint/interaction/turn/interface.py +116 -0
  36. siada/entrypoint/interaction/turn/models.py +34 -0
  37. siada/entrypoint/interaction/turn/run_turn.py +641 -0
  38. siada/entrypoint/interaction/turn_factory.py +35 -0
  39. siada/entrypoint/interaction/turn_models.py +28 -0
  40. siada/entrypoint/siadahub.py +413 -0
  41. siada/foundation/__init__.py +0 -0
  42. siada/foundation/code_agent_context.py +48 -0
  43. siada/foundation/config.py +59 -0
  44. siada/foundation/constants.py +2 -0
  45. siada/foundation/context.py +76 -0
  46. siada/foundation/logging.py +341 -0
  47. siada/foundation/tools/__init__.py +0 -0
  48. siada/foundation/tools/get_git_diff.py +105 -0
  49. siada/io/__init__.py +0 -0
  50. siada/io/banner.py +148 -0
  51. siada/io/color_settings.py +207 -0
  52. siada/io/color_utils.py +16 -0
  53. siada/io/components/__init__.py +0 -0
  54. siada/io/components/mdstream.py +204 -0
  55. siada/io/console_printer.py +68 -0
  56. siada/io/io.py +661 -0
  57. siada/io/key_bindings.py +129 -0
  58. siada/io/notification_command.py +40 -0
  59. siada/io/test_banner.py +64 -0
  60. siada/models/__init__.py +0 -0
  61. siada/models/agent.py +47 -0
  62. siada/models/coder/__init__.py +0 -0
  63. siada/models/converter.py +27 -0
  64. siada/models/model_base_config.py +121 -0
  65. siada/models/model_run_config.py +153 -0
  66. siada/provider/__init__.py +0 -0
  67. siada/provider/client_factory.py +112 -0
  68. siada/provider/llm_client.py +11 -0
  69. siada/provider/openrouter/__init__.py +0 -0
  70. siada/provider/openrouter/coverter.py +17 -0
  71. siada/provider/openrouter/openroute_provider.py +33 -0
  72. siada/provider/provider_factory.py +53 -0
  73. siada/queries/tree-sitter-language-pack/README.md +7 -0
  74. siada/queries/tree-sitter-language-pack/arduino-tags.scm +5 -0
  75. siada/queries/tree-sitter-language-pack/c-tags.scm +9 -0
  76. siada/queries/tree-sitter-language-pack/chatito-tags.scm +16 -0
  77. siada/queries/tree-sitter-language-pack/commonlisp-tags.scm +122 -0
  78. siada/queries/tree-sitter-language-pack/cpp-tags.scm +15 -0
  79. siada/queries/tree-sitter-language-pack/csharp-tags.scm +26 -0
  80. siada/queries/tree-sitter-language-pack/d-tags.scm +26 -0
  81. siada/queries/tree-sitter-language-pack/dart-tags.scm +92 -0
  82. siada/queries/tree-sitter-language-pack/elisp-tags.scm +5 -0
  83. siada/queries/tree-sitter-language-pack/elixir-tags.scm +54 -0
  84. siada/queries/tree-sitter-language-pack/elm-tags.scm +19 -0
  85. siada/queries/tree-sitter-language-pack/gleam-tags.scm +41 -0
  86. siada/queries/tree-sitter-language-pack/go-tags.scm +42 -0
  87. siada/queries/tree-sitter-language-pack/java-tags.scm +20 -0
  88. siada/queries/tree-sitter-language-pack/javascript-tags.scm +88 -0
  89. siada/queries/tree-sitter-language-pack/lua-tags.scm +34 -0
  90. siada/queries/tree-sitter-language-pack/ocaml-tags.scm +115 -0
  91. siada/queries/tree-sitter-language-pack/ocaml_interface-tags.scm +98 -0
  92. siada/queries/tree-sitter-language-pack/pony-tags.scm +39 -0
  93. siada/queries/tree-sitter-language-pack/properties-tags.scm +5 -0
  94. siada/queries/tree-sitter-language-pack/python-tags.scm +14 -0
  95. siada/queries/tree-sitter-language-pack/r-tags.scm +21 -0
  96. siada/queries/tree-sitter-language-pack/racket-tags.scm +12 -0
  97. siada/queries/tree-sitter-language-pack/ruby-tags.scm +64 -0
  98. siada/queries/tree-sitter-language-pack/rust-tags.scm +60 -0
  99. siada/queries/tree-sitter-language-pack/solidity-tags.scm +43 -0
  100. siada/queries/tree-sitter-language-pack/swift-tags.scm +51 -0
  101. siada/queries/tree-sitter-language-pack/udev-tags.scm +20 -0
  102. siada/queries/tree-sitter-languages/README.md +23 -0
  103. siada/queries/tree-sitter-languages/c-tags.scm +9 -0
  104. siada/queries/tree-sitter-languages/c_sharp-tags.scm +46 -0
  105. siada/queries/tree-sitter-languages/cpp-tags.scm +15 -0
  106. siada/queries/tree-sitter-languages/dart-tags.scm +91 -0
  107. siada/queries/tree-sitter-languages/elisp-tags.scm +8 -0
  108. siada/queries/tree-sitter-languages/elixir-tags.scm +54 -0
  109. siada/queries/tree-sitter-languages/elm-tags.scm +19 -0
  110. siada/queries/tree-sitter-languages/go-tags.scm +30 -0
  111. siada/queries/tree-sitter-languages/hcl-tags.scm +77 -0
  112. siada/queries/tree-sitter-languages/java-tags.scm +20 -0
  113. siada/queries/tree-sitter-languages/javascript-tags.scm +88 -0
  114. siada/queries/tree-sitter-languages/kotlin-tags.scm +27 -0
  115. siada/queries/tree-sitter-languages/ocaml-tags.scm +115 -0
  116. siada/queries/tree-sitter-languages/ocaml_interface-tags.scm +98 -0
  117. siada/queries/tree-sitter-languages/php-tags.scm +26 -0
  118. siada/queries/tree-sitter-languages/python-tags.scm +12 -0
  119. siada/queries/tree-sitter-languages/ql-tags.scm +26 -0
  120. siada/queries/tree-sitter-languages/ruby-tags.scm +64 -0
  121. siada/queries/tree-sitter-languages/rust-tags.scm +60 -0
  122. siada/queries/tree-sitter-languages/scala-tags.scm +65 -0
  123. siada/queries/tree-sitter-languages/typescript-tags.scm +41 -0
  124. siada/services/__init__.py +30 -0
  125. siada/services/at_file_recommendation_design_document.md +1213 -0
  126. siada/services/code_context_manager.py +136 -0
  127. siada/services/enhanced_fix_result_check.py +546 -0
  128. siada/services/execution_trace_collector.py +207 -0
  129. siada/services/file_recommendation/__init__.py +136 -0
  130. siada/services/file_recommendation/core/__init__.py +17 -0
  131. siada/services/file_recommendation/core/completion_engine.py +351 -0
  132. siada/services/file_recommendation/core/config.py +62 -0
  133. siada/services/file_recommendation/core/file_discovery.py +353 -0
  134. siada/services/file_recommendation/core/suggestion.py +110 -0
  135. siada/services/file_recommendation/utils/__init__.py +22 -0
  136. siada/services/file_recommendation/utils/path_utils.py +138 -0
  137. siada/services/file_recommendation/utils/text_utils.py +253 -0
  138. siada/services/fix_result_check.py +377 -0
  139. siada/services/handle_at_command/README.md +247 -0
  140. siada/services/handle_at_command/__init__.py +115 -0
  141. siada/services/handle_at_command/exceptions.py +46 -0
  142. siada/services/handle_at_command/models.py +92 -0
  143. siada/services/handle_at_command/parser.py +189 -0
  144. siada/services/handle_at_command/processor.py +321 -0
  145. siada/services/handle_at_command/resolver.py +318 -0
  146. siada/services/handle_at_command/utils.py +345 -0
  147. siada/services/model_info_service.py +103 -0
  148. siada/services/siada_runner.py +170 -0
  149. siada/session/__init__.py +29 -0
  150. siada/session/session_manager.py +66 -0
  151. siada/session/session_models.py +43 -0
  152. siada/support/__init__.py +0 -0
  153. siada/support/completer.py +204 -0
  154. siada/support/editor.py +146 -0
  155. siada/support/envprocessor.py +54 -0
  156. siada/support/repo.py +51 -0
  157. siada/support/slash_commands.py +410 -0
  158. siada/support/spinner.py +320 -0
  159. siada/tools/__init__.py +0 -0
  160. siada/tools/ast/README.md +345 -0
  161. siada/tools/ast/ast_tool.py +341 -0
  162. siada/tools/ast/models.py +11 -0
  163. siada/tools/coder/__init__.py +0 -0
  164. siada/tools/coder/ask_followup_question.py +70 -0
  165. siada/tools/coder/cmd_runner.py +132 -0
  166. siada/tools/coder/file_operator.py +284 -0
  167. siada/tools/coder/file_search/README.md +223 -0
  168. siada/tools/coder/file_search/__init__.py +10 -0
  169. siada/tools/coder/file_search/bin/rg-linux-arm64 +0 -0
  170. siada/tools/coder/file_search/bin/rg-linux-x64 +0 -0
  171. siada/tools/coder/file_search/bin/rg-macos-arm64 +0 -0
  172. siada/tools/coder/file_search/bin/rg-macos-x64 +0 -0
  173. siada/tools/coder/file_search/bin/rg.exe +0 -0
  174. siada/tools/coder/file_search/search.py +437 -0
  175. siada/tools/coder/file_search/setup_package.py +150 -0
  176. siada/tools/coder/file_search/test_search.py +142 -0
  177. siada/tools/coder/files.py +147 -0
  178. siada/tools/coder/fix_attempt_completion.py +58 -0
  179. siada/tools/coder/issue_review_completion.py +29 -0
  180. siada/tools/coder/observation/__init__.py +0 -0
  181. siada/tools/coder/observation/error.py +22 -0
  182. siada/tools/coder/observation/file_observation.py +216 -0
  183. siada/tools/coder/observation/observation.py +71 -0
  184. siada/tools/coder/repo_map/__init__.py +157 -0
  185. siada/tools/coder/repo_map/dump.py +29 -0
  186. siada/tools/coder/repo_map/io.py +226 -0
  187. siada/tools/coder/repo_map/repo_map.py +881 -0
  188. siada/tools/coder/repo_map/special.py +203 -0
  189. siada/tools/coder/repo_map/token_counter.py +154 -0
  190. siada/tools/coder/repo_map/waiting.py +221 -0
  191. siada/tools/coder/reproduce_completion.py +39 -0
  192. siada/tools/coder/run_cmd.py +60 -0
  193. siada/tools/coder/test_completion.py +25 -0
  194. siada/tools/coder/tool_docs.py +44 -0
  195. siada/tools/compression_tool.py +200 -0
  196. siada/tools/read_many_files/README.md +220 -0
  197. siada/tools/read_many_files/__init__.py +25 -0
  198. siada/tools/read_many_files/file_processor.py +486 -0
  199. siada/tools/read_many_files/filters.py +326 -0
  200. siada/tools/read_many_files/formatters.py +204 -0
  201. siada/tools/read_many_files/models.py +189 -0
  202. siada/tools/read_many_files_tool.py +233 -0
  203. siada/tools/tool_call_format/__init__.py +55 -0
  204. siada/tools/tool_call_format/file_to_language.py +231 -0
  205. siada/tools/tool_call_format/formatter_factory.py +80 -0
  206. siada/tools/tool_call_format/formatters.py +282 -0
  207. siada/tools/tool_call_format/tool_call_formatter.py +54 -0
  208. siada/tools/web/__init__.py +0 -0
  209. siada/tools/web/web_crawl.py +208 -0
  210. siada/utils.py +194 -0
  211. siada_cli-0.0.1.dist-info/LICENSE +201 -0
  212. siada_cli-0.0.1.dist-info/METADATA +457 -0
  213. siada_cli-0.0.1.dist-info/RECORD +215 -0
  214. siada_cli-0.0.1.dist-info/WHEEL +4 -0
  215. siada_cli-0.0.1.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,881 @@
1
+ import colorsys
2
+ import math
3
+ import os
4
+ import random
5
+ import shutil
6
+ import sqlite3
7
+ import sys
8
+ import time
9
+ import warnings
10
+ from collections import Counter, defaultdict, namedtuple
11
+ from importlib import resources
12
+ from pathlib import Path
13
+
14
+ from diskcache import Cache
15
+ from grep_ast import TreeContext, filename_to_lang
16
+ from pygments.lexers import guess_lexer_for_filename
17
+ from pygments.token import Token
18
+ from tqdm import tqdm
19
+
20
+ from .dump import dump
21
+ from .special import filter_important_files
22
+ from .waiting import Spinner
23
+
24
+ # tree_sitter is throwing a FutureWarning
25
+ warnings.simplefilter("ignore", category=FutureWarning)
26
+ from grep_ast.tsl import USING_TSL_PACK, get_language, get_parser # noqa: E402
27
+
28
+ Tag = namedtuple("Tag", "rel_fname fname line name kind".split())
29
+
30
+
31
+ SQLITE_ERRORS = (sqlite3.OperationalError, sqlite3.DatabaseError, OSError)
32
+
33
+
34
+ CACHE_VERSION = 3
35
+ if USING_TSL_PACK:
36
+ CACHE_VERSION = 4
37
+
38
+ UPDATING_REPO_MAP_MESSAGE = "Updating repo map"
39
+
40
+
41
+ class RepoMap:
42
+ TAGS_CACHE_DIR = f".siada.tags.cache.v{CACHE_VERSION}"
43
+
44
+ warned_files = set()
45
+
46
+ def __init__(
47
+ self,
48
+ map_tokens=1024,
49
+ root=None,
50
+ main_model=None,
51
+ io=None,
52
+ repo_content_prefix=None,
53
+ verbose=False,
54
+ max_context_window=None,
55
+ map_mul_no_files=8,
56
+ refresh="auto",
57
+ ):
58
+ """
59
+ Initialize RepoMap instance
60
+
61
+ Args:
62
+ map_tokens (int): Maximum token count for repository map, default 1024
63
+ root (str): Repository root directory path, uses current working directory if None
64
+ main_model: Main language model instance for token calculation
65
+ io: Input/output processor for file reading and logging
66
+ repo_content_prefix (str): Prefix template for repository content
67
+ verbose (bool): Whether to enable verbose output mode
68
+ max_context_window (int): Maximum context window size
69
+ map_mul_no_files (int): Map token multiplier when no chat files, default 8
70
+ refresh (str): Cache refresh strategy, options: "auto", "always", "files", "manual"
71
+ """
72
+ self.io = io
73
+ self.verbose = verbose
74
+ self.refresh = refresh
75
+
76
+ if not root:
77
+ root = os.getcwd()
78
+ self.root = root
79
+
80
+ self.load_tags_cache()
81
+ self.cache_threshold = 0.95
82
+
83
+ self.max_map_tokens = map_tokens
84
+ self.map_mul_no_files = map_mul_no_files
85
+ self.max_context_window = max_context_window
86
+
87
+ self.repo_content_prefix = repo_content_prefix
88
+
89
+ self.main_model = main_model
90
+
91
+ self.tree_cache = {}
92
+ self.tree_context_cache = {}
93
+ self.map_cache = {}
94
+ self.map_processing_time = 0
95
+ self.last_map = None
96
+
97
+ if self.verbose:
98
+ self.io.tool_output(
99
+ f"RepoMap initialized with map_mul_no_files: {self.map_mul_no_files}"
100
+ )
101
+
102
+ def token_count(self, text):
103
+ len_text = len(text)
104
+ if len_text < 200:
105
+ return self.main_model.token_count(text)
106
+
107
+ lines = text.splitlines(keepends=True)
108
+ num_lines = len(lines)
109
+ step = num_lines // 100 or 1
110
+ lines = lines[::step]
111
+ sample_text = "".join(lines)
112
+ sample_tokens = self.main_model.token_count(sample_text)
113
+ est_tokens = sample_tokens / len(sample_text) * len_text
114
+ return est_tokens
115
+
116
+ def get_repo_map(
117
+ self,
118
+ chat_files,
119
+ other_files,
120
+ mentioned_fnames=None,
121
+ mentioned_idents=None,
122
+ force_refresh=False,
123
+ ):
124
+ """
125
+ Generate repository map containing file structure and important code definitions
126
+
127
+ This method analyzes definitions and references in code files to generate a repository map
128
+ containing important code structures. The map uses PageRank algorithm to rank files and
129
+ identifiers, prioritizing the most relevant content.
130
+
131
+ This method should be called before each coding task to ensure the latest repository map.
132
+ Args:
133
+ chat_files (list): List of files involved in current chat, these files get higher weight
134
+ other_files (list): List of other files to analyze
135
+ mentioned_fnames (set, optional): Set of filenames mentioned in conversation
136
+ mentioned_idents (set, optional): Set of identifiers mentioned in conversation
137
+ force_refresh (bool): Whether to force refresh cache, default False
138
+
139
+ Returns:
140
+ str: Formatted repository map string containing file paths and important code definitions,
141
+ returns None if map cannot be generated
142
+
143
+ Note:
144
+ - When no chat files exist, expands map token limit to provide comprehensive repo view
145
+ - Uses caching mechanism to improve performance and avoid redundant computation
146
+ - Automatically disables repo map functionality if repo is too large causing recursion errors
147
+ """
148
+ if self.max_map_tokens <= 0:
149
+ return
150
+ if not other_files:
151
+ return
152
+ if not mentioned_fnames:
153
+ mentioned_fnames = set()
154
+ if not mentioned_idents:
155
+ mentioned_idents = set()
156
+
157
+ max_map_tokens = self.max_map_tokens
158
+
159
+ # With no files in the chat, give a bigger view of the entire repo
160
+ padding = 4096
161
+ if max_map_tokens and self.max_context_window:
162
+ target = min(
163
+ int(max_map_tokens * self.map_mul_no_files),
164
+ self.max_context_window - padding,
165
+ )
166
+ else:
167
+ target = 0
168
+ if not chat_files and self.max_context_window and target > 0:
169
+ max_map_tokens = target
170
+
171
+ try:
172
+ files_listing = self.get_ranked_tags_map(
173
+ chat_files,
174
+ other_files,
175
+ max_map_tokens,
176
+ mentioned_fnames,
177
+ mentioned_idents,
178
+ force_refresh,
179
+ )
180
+ except RecursionError:
181
+ self.io.tool_error("Disabling repo map, git repo too large?")
182
+ self.max_map_tokens = 0
183
+ return
184
+
185
+ if not files_listing:
186
+ return
187
+
188
+ if self.verbose:
189
+ num_tokens = self.token_count(files_listing)
190
+ self.io.tool_output(f"Repo-map: {num_tokens / 1024:.1f} k-tokens")
191
+
192
+ if chat_files:
193
+ other = "other "
194
+ else:
195
+ other = ""
196
+
197
+ if self.repo_content_prefix:
198
+ repo_content = self.repo_content_prefix.format(other=other)
199
+ else:
200
+ repo_content = ""
201
+
202
+ repo_content += files_listing
203
+
204
+ return repo_content
205
+
206
+ def get_rel_fname(self, fname):
207
+ try:
208
+ return os.path.relpath(fname, self.root)
209
+ except ValueError:
210
+ # Issue #1288: ValueError: path is on mount 'C:', start on mount 'D:'
211
+ # Just return the full fname.
212
+ return fname
213
+
214
+ def tags_cache_error(self, original_error=None):
215
+ """Handle SQLite errors by trying to recreate cache, falling back to dict if needed"""
216
+
217
+ if self.verbose and original_error:
218
+ self.io.tool_warning(f"Tags cache error: {str(original_error)}")
219
+
220
+ if isinstance(getattr(self, "TAGS_CACHE", None), dict):
221
+ return
222
+
223
+ path = Path(self.root) / self.TAGS_CACHE_DIR
224
+
225
+ # Try to recreate the cache
226
+ try:
227
+ # Delete existing cache dir
228
+ if path.exists():
229
+ shutil.rmtree(path)
230
+
231
+ # Try to create new cache
232
+ new_cache = Cache(path)
233
+
234
+ # Test that it works
235
+ test_key = "test"
236
+ new_cache[test_key] = "test"
237
+ _ = new_cache[test_key]
238
+ del new_cache[test_key]
239
+
240
+ # If we got here, the new cache works
241
+ self.TAGS_CACHE = new_cache
242
+ return
243
+
244
+ except SQLITE_ERRORS as e:
245
+ # If anything goes wrong, warn and fall back to dict
246
+ self.io.tool_warning(
247
+ f"Unable to use tags cache at {path}, falling back to memory cache"
248
+ )
249
+ if self.verbose:
250
+ self.io.tool_warning(f"Cache recreation error: {str(e)}")
251
+
252
+ self.TAGS_CACHE = dict()
253
+
254
+ def load_tags_cache(self):
255
+ path = Path(self.root) / self.TAGS_CACHE_DIR
256
+ try:
257
+ self.TAGS_CACHE = Cache(path)
258
+ except SQLITE_ERRORS as e:
259
+ self.tags_cache_error(e)
260
+
261
+ def save_tags_cache(self):
262
+ pass
263
+
264
+ def get_mtime(self, fname):
265
+ try:
266
+ return os.path.getmtime(fname)
267
+ except FileNotFoundError:
268
+ self.io.tool_warning(f"File not found error: {fname}")
269
+
270
+ def get_tags(self, fname, rel_fname):
271
+ # Check if the file is in the cache and if the modification time has not changed
272
+ file_mtime = self.get_mtime(fname)
273
+ if file_mtime is None:
274
+ return []
275
+
276
+ cache_key = fname
277
+ try:
278
+ val = self.TAGS_CACHE.get(cache_key) # Issue #1308
279
+ except SQLITE_ERRORS as e:
280
+ self.tags_cache_error(e)
281
+ val = self.TAGS_CACHE.get(cache_key)
282
+
283
+ if val is not None and val.get("mtime") == file_mtime:
284
+ try:
285
+ return self.TAGS_CACHE[cache_key]["data"]
286
+ except SQLITE_ERRORS as e:
287
+ self.tags_cache_error(e)
288
+ return self.TAGS_CACHE[cache_key]["data"]
289
+
290
+ # miss!
291
+ data = list(self.get_tags_raw(fname, rel_fname))
292
+
293
+ # Update the cache
294
+ try:
295
+ self.TAGS_CACHE[cache_key] = {"mtime": file_mtime, "data": data}
296
+ self.save_tags_cache()
297
+ except SQLITE_ERRORS as e:
298
+ self.tags_cache_error(e)
299
+ self.TAGS_CACHE[cache_key] = {"mtime": file_mtime, "data": data}
300
+
301
+ return data
302
+
303
+ def get_tags_raw(self, fname, rel_fname):
304
+ lang = filename_to_lang(fname)
305
+ if not lang:
306
+ return
307
+
308
+ try:
309
+ language = get_language(lang)
310
+ parser = get_parser(lang)
311
+ except Exception as err:
312
+ print(f"Skipping file {fname}: {err}")
313
+ return
314
+
315
+ query_scm = get_scm_fname(lang)
316
+ if not query_scm.exists():
317
+ return
318
+ query_scm = query_scm.read_text()
319
+
320
+ code = self.io.read_text(fname)
321
+ if not code:
322
+ return
323
+ tree = parser.parse(bytes(code, "utf-8"))
324
+
325
+ # Run the tags queries
326
+ query = language.query(query_scm)
327
+ captures = query.captures(tree.root_node)
328
+
329
+ saw = set()
330
+ if USING_TSL_PACK:
331
+ all_nodes = []
332
+ for tag, nodes in captures.items():
333
+ all_nodes += [(node, tag) for node in nodes]
334
+ else:
335
+ all_nodes = list(captures)
336
+
337
+ for node, tag in all_nodes:
338
+ if tag.startswith("name.definition."):
339
+ kind = "def"
340
+ elif tag.startswith("name.reference."):
341
+ kind = "ref"
342
+ else:
343
+ continue
344
+
345
+ saw.add(kind)
346
+
347
+ result = Tag(
348
+ rel_fname=rel_fname,
349
+ fname=fname,
350
+ name=node.text.decode("utf-8"),
351
+ kind=kind,
352
+ line=node.start_point[0],
353
+ )
354
+
355
+ yield result
356
+
357
+ if "ref" in saw:
358
+ return
359
+ if "def" not in saw:
360
+ return
361
+
362
+ # We saw defs, without any refs
363
+ # Some tags files only provide defs (cpp, for example)
364
+ # Use pygments to backfill refs
365
+
366
+ try:
367
+ lexer = guess_lexer_for_filename(fname, code)
368
+ except Exception: # On Windows, bad ref to time.clock which is deprecated?
369
+ # self.io.tool_error(f"Error lexing {fname}")
370
+ return
371
+
372
+ tokens = list(lexer.get_tokens(code))
373
+ tokens = [token[1] for token in tokens if token[0] in Token.Name]
374
+
375
+ for token in tokens:
376
+ yield Tag(
377
+ rel_fname=rel_fname,
378
+ fname=fname,
379
+ name=token,
380
+ kind="ref",
381
+ line=-1,
382
+ )
383
+
384
+ def get_ranked_tags(
385
+ self, chat_fnames, other_fnames, mentioned_fnames, mentioned_idents, progress=None
386
+ ):
387
+ import networkx as nx
388
+
389
+ defines = defaultdict(set)
390
+ references = defaultdict(list)
391
+ definitions = defaultdict(set)
392
+
393
+ personalization = dict()
394
+
395
+ fnames = set(chat_fnames).union(set(other_fnames))
396
+ chat_rel_fnames = set()
397
+
398
+ fnames = sorted(fnames)
399
+
400
+ # Default personalization for unspecified files is 1/num_nodes
401
+ # https://networkx.org/documentation/stable/_modules/networkx/algorithms/link_analysis/pagerank_alg.html#pagerank
402
+ personalize = 100 / len(fnames)
403
+
404
+ try:
405
+ cache_size = len(self.TAGS_CACHE)
406
+ except SQLITE_ERRORS as e:
407
+ self.tags_cache_error(e)
408
+ cache_size = len(self.TAGS_CACHE)
409
+
410
+ if len(fnames) - cache_size > 100:
411
+ self.io.tool_output(
412
+ "Initial repo scan can be slow in larger repos, but only happens once."
413
+ )
414
+ fnames = tqdm(fnames, desc="Scanning repo")
415
+ showing_bar = True
416
+ else:
417
+ showing_bar = False
418
+
419
+ for fname in fnames:
420
+ if self.verbose:
421
+ self.io.tool_output(f"Processing {fname}")
422
+ if progress and not showing_bar:
423
+ progress(f"{UPDATING_REPO_MAP_MESSAGE}: {fname}")
424
+
425
+ try:
426
+ file_ok = Path(fname).is_file()
427
+ except OSError:
428
+ file_ok = False
429
+
430
+ if not file_ok:
431
+ if fname not in self.warned_files:
432
+ self.io.tool_warning(f"Repo-map can't include {fname}")
433
+ self.io.tool_output(
434
+ "Has it been deleted from the file system but not from git?"
435
+ )
436
+ self.warned_files.add(fname)
437
+ continue
438
+
439
+ # dump(fname)
440
+ rel_fname = self.get_rel_fname(fname)
441
+ current_pers = 0.0 # Start with 0 personalization score
442
+
443
+ if fname in chat_fnames:
444
+ current_pers += personalize
445
+ chat_rel_fnames.add(rel_fname)
446
+
447
+ if rel_fname in mentioned_fnames:
448
+ # Use max to avoid double counting if in chat_fnames and mentioned_fnames
449
+ current_pers = max(current_pers, personalize)
450
+
451
+ # Check path components against mentioned_idents
452
+ path_obj = Path(rel_fname)
453
+ path_components = set(path_obj.parts)
454
+ basename_with_ext = path_obj.name
455
+ basename_without_ext, _ = os.path.splitext(basename_with_ext)
456
+ components_to_check = path_components.union({basename_with_ext, basename_without_ext})
457
+
458
+ matched_idents = components_to_check.intersection(mentioned_idents)
459
+ if matched_idents:
460
+ # Add personalization *once* if any path component matches a mentioned ident
461
+ current_pers += personalize
462
+
463
+ if current_pers > 0:
464
+ personalization[rel_fname] = current_pers # Assign the final calculated value
465
+
466
+ tags = list(self.get_tags(fname, rel_fname))
467
+ if tags is None:
468
+ continue
469
+
470
+ for tag in tags:
471
+ if tag.kind == "def":
472
+ defines[tag.name].add(rel_fname)
473
+ key = (rel_fname, tag.name)
474
+ definitions[key].add(tag)
475
+
476
+ elif tag.kind == "ref":
477
+ references[tag.name].append(rel_fname)
478
+
479
+ ##
480
+ # dump(defines)
481
+ # dump(references)
482
+ # dump(personalization)
483
+
484
+ if not references:
485
+ references = dict((k, list(v)) for k, v in defines.items())
486
+
487
+ idents = set(defines.keys()).intersection(set(references.keys()))
488
+
489
+ G = nx.MultiDiGraph()
490
+
491
+ # Add a small self-edge for every definition that has no references
492
+ # Helps with tree-sitter 0.23.2 with ruby, where "def greet(name)"
493
+ # isn't counted as a def AND a ref. tree-sitter 0.24.0 does.
494
+ for ident in defines.keys():
495
+ if ident in references:
496
+ continue
497
+ for definer in defines[ident]:
498
+ G.add_edge(definer, definer, weight=0.1, ident=ident)
499
+
500
+ for ident in idents:
501
+ if progress:
502
+ progress(f"{UPDATING_REPO_MAP_MESSAGE}: {ident}")
503
+
504
+ definers = defines[ident]
505
+
506
+ mul = 1.0
507
+
508
+ is_snake = ("_" in ident) and any(c.isalpha() for c in ident)
509
+ is_camel = any(c.isupper() for c in ident) and any(c.islower() for c in ident)
510
+ if ident in mentioned_idents:
511
+ mul *= 10
512
+ if (is_snake or is_camel) and len(ident) >= 8:
513
+ mul *= 10
514
+ if ident.startswith("_"):
515
+ mul *= 0.1
516
+ if len(defines[ident]) > 5:
517
+ mul *= 0.1
518
+
519
+ for referencer, num_refs in Counter(references[ident]).items():
520
+ for definer in definers:
521
+ # dump(referencer, definer, num_refs, mul)
522
+ # if referencer == definer:
523
+ # continue
524
+
525
+ use_mul = mul
526
+ if referencer in chat_rel_fnames:
527
+ use_mul *= 50
528
+
529
+ # scale down so high freq (low value) mentions don't dominate
530
+ num_refs = math.sqrt(num_refs)
531
+
532
+ G.add_edge(referencer, definer, weight=use_mul * num_refs, ident=ident)
533
+
534
+ if not references:
535
+ pass
536
+
537
+ if personalization:
538
+ pers_args = dict(personalization=personalization, dangling=personalization)
539
+ else:
540
+ pers_args = dict()
541
+
542
+ try:
543
+ ranked = nx.pagerank(G, weight="weight", **pers_args)
544
+ except ZeroDivisionError:
545
+ # Issue #1536
546
+ try:
547
+ ranked = nx.pagerank(G, weight="weight")
548
+ except ZeroDivisionError:
549
+ return []
550
+
551
+ # distribute the rank from each source node, across all of its out edges
552
+ ranked_definitions = defaultdict(float)
553
+ for src in G.nodes:
554
+ if progress:
555
+ progress(f"{UPDATING_REPO_MAP_MESSAGE}: {src}")
556
+
557
+ src_rank = ranked[src]
558
+ total_weight = sum(data["weight"] for _src, _dst, data in G.out_edges(src, data=True))
559
+ # dump(siada, src_rank, total_weight)
560
+ for _src, dst, data in G.out_edges(src, data=True):
561
+ data["rank"] = src_rank * data["weight"] / total_weight
562
+ ident = data["ident"]
563
+ ranked_definitions[(dst, ident)] += data["rank"]
564
+
565
+ ranked_tags = []
566
+ ranked_definitions = sorted(
567
+ ranked_definitions.items(), reverse=True, key=lambda x: (x[1], x[0])
568
+ )
569
+
570
+ # dump(ranked_definitions)
571
+
572
+ for (fname, ident), rank in ranked_definitions:
573
+ # print(f"{rank:.03f} {fname} {ident}")
574
+ if fname in chat_rel_fnames:
575
+ continue
576
+ ranked_tags += list(definitions.get((fname, ident), []))
577
+
578
+ rel_other_fnames_without_tags = set(self.get_rel_fname(fname) for fname in other_fnames)
579
+
580
+ fnames_already_included = set(rt[0] for rt in ranked_tags)
581
+
582
+ top_rank = sorted([(rank, node) for (node, rank) in ranked.items()], reverse=True)
583
+ for rank, fname in top_rank:
584
+ if fname in rel_other_fnames_without_tags:
585
+ rel_other_fnames_without_tags.remove(fname)
586
+ if fname not in fnames_already_included:
587
+ ranked_tags.append((fname,))
588
+
589
+ for fname in rel_other_fnames_without_tags:
590
+ ranked_tags.append((fname,))
591
+
592
+ return ranked_tags
593
+
594
+ def get_ranked_tags_map(
595
+ self,
596
+ chat_fnames,
597
+ other_fnames=None,
598
+ max_map_tokens=None,
599
+ mentioned_fnames=None,
600
+ mentioned_idents=None,
601
+ force_refresh=False,
602
+ ):
603
+ # Create a cache key
604
+ cache_key = [
605
+ tuple(sorted(chat_fnames)) if chat_fnames else None,
606
+ tuple(sorted(other_fnames)) if other_fnames else None,
607
+ max_map_tokens,
608
+ ]
609
+
610
+ if self.refresh == "auto":
611
+ cache_key += [
612
+ tuple(sorted(mentioned_fnames)) if mentioned_fnames else None,
613
+ tuple(sorted(mentioned_idents)) if mentioned_idents else None,
614
+ ]
615
+ cache_key = tuple(cache_key)
616
+
617
+ use_cache = False
618
+ if not force_refresh:
619
+ if self.refresh == "manual" and self.last_map:
620
+ return self.last_map
621
+
622
+ if self.refresh == "always":
623
+ use_cache = False
624
+ elif self.refresh == "files":
625
+ use_cache = True
626
+ elif self.refresh == "auto":
627
+ use_cache = self.map_processing_time > 1.0
628
+
629
+ # Check if the result is in the cache
630
+ if use_cache and cache_key in self.map_cache:
631
+ return self.map_cache[cache_key]
632
+
633
+ # If not in cache or force_refresh is True, generate the map
634
+ start_time = time.time()
635
+ result = self.get_ranked_tags_map_uncached(
636
+ chat_fnames, other_fnames, max_map_tokens, mentioned_fnames, mentioned_idents
637
+ )
638
+ end_time = time.time()
639
+ self.map_processing_time = end_time - start_time
640
+
641
+ # Store the result in the cache
642
+ self.map_cache[cache_key] = result
643
+ self.last_map = result
644
+
645
+ return result
646
+
647
+ def get_ranked_tags_map_uncached(
648
+ self,
649
+ chat_fnames,
650
+ other_fnames=None,
651
+ max_map_tokens=None,
652
+ mentioned_fnames=None,
653
+ mentioned_idents=None,
654
+ ):
655
+ if not other_fnames:
656
+ other_fnames = list()
657
+ if not max_map_tokens:
658
+ max_map_tokens = self.max_map_tokens
659
+ if not mentioned_fnames:
660
+ mentioned_fnames = set()
661
+ if not mentioned_idents:
662
+ mentioned_idents = set()
663
+
664
+ spin = Spinner(UPDATING_REPO_MAP_MESSAGE)
665
+
666
+ ranked_tags = self.get_ranked_tags(
667
+ chat_fnames,
668
+ other_fnames,
669
+ mentioned_fnames,
670
+ mentioned_idents,
671
+ progress=spin.step,
672
+ )
673
+
674
+ other_rel_fnames = sorted(set(self.get_rel_fname(fname) for fname in other_fnames))
675
+ special_fnames = filter_important_files(other_rel_fnames)
676
+ ranked_tags_fnames = set(tag[0] for tag in ranked_tags)
677
+ special_fnames = [fn for fn in special_fnames if fn not in ranked_tags_fnames]
678
+ special_fnames = [(fn,) for fn in special_fnames]
679
+
680
+ ranked_tags = special_fnames + ranked_tags
681
+
682
+ spin.step()
683
+
684
+ num_tags = len(ranked_tags)
685
+ lower_bound = 0
686
+ upper_bound = num_tags
687
+ best_tree = None
688
+ best_tree_tokens = 0
689
+
690
+ chat_rel_fnames = set(self.get_rel_fname(fname) for fname in chat_fnames)
691
+
692
+ self.tree_cache = dict()
693
+
694
+ middle = min(int(max_map_tokens // 25), num_tags)
695
+ while lower_bound <= upper_bound:
696
+ # dump(lower_bound, middle, upper_bound)
697
+
698
+ if middle > 1500:
699
+ show_tokens = f"{middle / 1000.0:.1f}K"
700
+ else:
701
+ show_tokens = str(middle)
702
+ spin.step(f"{UPDATING_REPO_MAP_MESSAGE}: {show_tokens} tokens")
703
+
704
+ tree = self.to_tree(ranked_tags[:middle], chat_rel_fnames)
705
+ num_tokens = self.token_count(tree)
706
+
707
+ pct_err = abs(num_tokens - max_map_tokens) / max_map_tokens
708
+ ok_err = 0.15
709
+ if (num_tokens <= max_map_tokens and num_tokens > best_tree_tokens) or pct_err < ok_err:
710
+ best_tree = tree
711
+ best_tree_tokens = num_tokens
712
+
713
+ if pct_err < ok_err:
714
+ break
715
+
716
+ if num_tokens < max_map_tokens:
717
+ lower_bound = middle + 1
718
+ else:
719
+ upper_bound = middle - 1
720
+
721
+ middle = int((lower_bound + upper_bound) // 2)
722
+
723
+ spin.end()
724
+ return best_tree
725
+
726
+ tree_cache = dict()
727
+
728
+ def render_tree(self, abs_fname, rel_fname, lois):
729
+ mtime = self.get_mtime(abs_fname)
730
+ key = (rel_fname, tuple(sorted(lois)), mtime)
731
+
732
+ if key in self.tree_cache:
733
+ return self.tree_cache[key]
734
+
735
+ if (
736
+ rel_fname not in self.tree_context_cache
737
+ or self.tree_context_cache[rel_fname]["mtime"] != mtime
738
+ ):
739
+ code = self.io.read_text(abs_fname) or ""
740
+ if not code.endswith("\n"):
741
+ code += "\n"
742
+
743
+ context = TreeContext(
744
+ rel_fname,
745
+ code,
746
+ color=False,
747
+ line_number=False,
748
+ child_context=False,
749
+ last_line=False,
750
+ margin=0,
751
+ mark_lois=False,
752
+ loi_pad=0,
753
+ # header_max=30,
754
+ show_top_of_file_parent_scope=False,
755
+ )
756
+ self.tree_context_cache[rel_fname] = {"context": context, "mtime": mtime}
757
+
758
+ context = self.tree_context_cache[rel_fname]["context"]
759
+ context.lines_of_interest = set()
760
+ context.add_lines_of_interest(lois)
761
+ context.add_context()
762
+ res = context.format()
763
+ self.tree_cache[key] = res
764
+ return res
765
+
766
+ def to_tree(self, tags, chat_rel_fnames):
767
+ if not tags:
768
+ return ""
769
+
770
+ cur_fname = None
771
+ cur_abs_fname = None
772
+ lois = None
773
+ output = ""
774
+
775
+ # add a bogus tag at the end so we trip the this_fname != cur_fname...
776
+ dummy_tag = (None,)
777
+ for tag in sorted(tags) + [dummy_tag]:
778
+ this_rel_fname = tag[0]
779
+ if this_rel_fname in chat_rel_fnames:
780
+ continue
781
+
782
+ # ... here ... to output the final real entry in the list
783
+ if this_rel_fname != cur_fname:
784
+ if lois is not None:
785
+ output += "\n"
786
+ output += cur_fname + ":\n"
787
+ output += self.render_tree(cur_abs_fname, cur_fname, lois)
788
+ lois = None
789
+ elif cur_fname:
790
+ output += "\n" + cur_fname + "\n"
791
+ if type(tag) is Tag:
792
+ lois = []
793
+ cur_abs_fname = tag.fname
794
+ cur_fname = this_rel_fname
795
+
796
+ if lois is not None:
797
+ lois.append(tag.line)
798
+
799
+ # truncate long lines, in case we get minified js or something else crazy
800
+ output = "\n".join([line[:100] for line in output.splitlines()]) + "\n"
801
+
802
+ return output
803
+
804
+
805
+ def find_src_files(directory):
806
+ if not os.path.isdir(directory):
807
+ return [directory]
808
+
809
+ src_files = []
810
+ for root, dirs, files in os.walk(directory):
811
+ for file in files:
812
+ src_files.append(os.path.join(root, file))
813
+ return src_files
814
+
815
+
816
+ def get_random_color():
817
+ hue = random.random()
818
+ r, g, b = [int(x * 255) for x in colorsys.hsv_to_rgb(hue, 1, 0.75)]
819
+ res = f"#{r:02x}{g:02x}{b:02x}"
820
+ return res
821
+
822
+
823
+ def get_scm_fname(lang):
824
+ # Load the tags queries from siada/queries directory
825
+ # First try to find the project root
826
+ current_file = Path(__file__)
827
+ project_root = current_file.parent.parent.parent.parent # Go up to siada/ level
828
+ queries_dir = project_root / "queries"
829
+
830
+ if USING_TSL_PACK:
831
+ subdir = "tree-sitter-language-pack"
832
+ path = queries_dir / subdir / f"{lang}-tags.scm"
833
+ if path.exists():
834
+ return path
835
+
836
+ # Fall back to tree-sitter-languages
837
+ subdir = "tree-sitter-languages"
838
+ path = queries_dir / subdir / f"{lang}-tags.scm"
839
+ if path.exists():
840
+ return path
841
+
842
+ # If not found, return None
843
+ return None
844
+
845
+
846
+ def get_supported_languages_md():
847
+ from grep_ast.parsers import PARSERS
848
+
849
+ res = """
850
+ | Language | File extension | Repo map | Linter |
851
+ |:--------:|:--------------:|:--------:|:------:|
852
+ """
853
+ data = sorted((lang, ex) for ex, lang in PARSERS.items())
854
+
855
+ for lang, ext in data:
856
+ fn = get_scm_fname(lang)
857
+ repo_map = "✓" if Path(fn).exists() else ""
858
+ linter_support = "✓"
859
+ res += f"| {lang:20} | {ext:20} | {repo_map:^8} | {linter_support:^6} |\n"
860
+
861
+ res += "\n"
862
+
863
+ return res
864
+
865
+
866
+ if __name__ == "__main__":
867
+ fnames = sys.argv[1:]
868
+
869
+ chat_fnames = []
870
+ other_fnames = []
871
+ for fname in sys.argv[1:]:
872
+ if Path(fname).is_dir():
873
+ chat_fnames += find_src_files(fname)
874
+ else:
875
+ chat_fnames.append(fname)
876
+
877
+ rm = RepoMap(root=".")
878
+ repo_map = rm.get_ranked_tags_map(chat_fnames, other_fnames)
879
+
880
+ dump(len(repo_map))
881
+ print(repo_map)