codis 1.1.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 (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
@@ -0,0 +1,921 @@
1
+ """Codis IA - Construtor de contexto automático para o assistente.
2
+
3
+ Responsabilidade única: reunir tudo que a IA precisa saber sobre o projeto
4
+ e o estado atual do editor, empacotando num bloco de contexto injetado
5
+ no system prompt antes de cada requisição.
6
+
7
+ Com esse módulo ativo, a IA não precisa perguntar onde está o workspace,
8
+ qual arquivo está aberto, qual linguagem é usada, ou como o projeto se
9
+ estrutura. Ela recebe tudo como contexto implícito, sem orientação extra.
10
+
11
+ Informações coletadas (todas opcionais/seguras para falhar)
12
+ -----------------------------------------------------------
13
+ Nível de projeto:
14
+ - Nome, caminho e tipo de projeto (detectado via arquivos de config)
15
+ - Linguagens detectadas com contagem de arquivos
16
+ - Árvore de arquivos relevante (limitada, filtrada, com tamanhos)
17
+ - Branch git atual, último commit e status de arquivos modificados
18
+ - Dependências declaradas (primeiras entradas do arquivo de deps)
19
+ - Resumo do README (primeiras linhas não-vazias)
20
+
21
+ Nível de arquivo ativo:
22
+ - Caminho relativo e linguagem
23
+ - Imports/includes do arquivo (para entender dependências internas)
24
+ - Conteúdo da região ao redor do cursor (janela de +/-N linhas)
25
+ - Diagnósticos ativos (erros/avisos do linter/LSP)
26
+ - Estilo de código (indentação, encoding)
27
+ - Seleção de texto ativa (quando há texto selecionado)
28
+
29
+ Uso típico (em iaspace.py)
30
+ --------------------------
31
+ from src.ia.context_builder import build_context_block
32
+
33
+ system_base = cfg.get("sistema", _DEFAULT_SYSTEM)
34
+ system_completo = system_base + build_context_block(
35
+ get_editor = self._get_editor,
36
+ get_workspace = self._get_workspace,
37
+ )
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import contextlib
43
+ import logging
44
+ import re
45
+ import subprocess
46
+ import tkinter as tk
47
+ from collections.abc import Callable
48
+ from pathlib import Path
49
+ from typing import Any
50
+
51
+ from src import proc_registry
52
+ from src.constants import SKIP_DIRS
53
+
54
+ logger = logging.getLogger("Codis.IA.ContextBuilder")
55
+
56
+ def _run(*args, **kwargs):
57
+ """``subprocess.run`` registrado como tarefa da IA, para o Gerenciador de Processos poder encerrá-lo."""
58
+ return proc_registry.run(*args, kind="ia", **kwargs)
59
+
60
+
61
+ _MAX_CONTEXT_CHARS: int = 10_000
62
+
63
+ _MAX_TREE_LINES: int = 80
64
+
65
+ _MAX_README_LINES: int = 25
66
+
67
+ _MAX_SYMBOLS: int = 60
68
+
69
+ _CURSOR_WINDOW_LINES: int = 30
70
+
71
+ _MAX_IMPORTS: int = 20
72
+
73
+ _MAX_TODOS: int = 8
74
+
75
+ _IGNORED_EXTENSIONS: frozenset[str] = frozenset(
76
+ {
77
+ ".pyc",
78
+ ".pyo",
79
+ ".pyd",
80
+ ".so",
81
+ ".dll",
82
+ ".dylib",
83
+ ".jpg",
84
+ ".jpeg",
85
+ ".png",
86
+ ".gif",
87
+ ".svg",
88
+ ".ico",
89
+ ".mp3",
90
+ ".mp4",
91
+ ".wav",
92
+ ".ogg",
93
+ ".flac",
94
+ ".zip",
95
+ ".tar",
96
+ ".gz",
97
+ ".bz2",
98
+ ".xz",
99
+ ".7z",
100
+ ".pdf",
101
+ ".docx",
102
+ ".xlsx",
103
+ ".pptx",
104
+ ".lock",
105
+ ".sum",
106
+ ".woff",
107
+ ".woff2",
108
+ ".ttf",
109
+ ".eot",
110
+ ".bin",
111
+ ".exe",
112
+ ".o",
113
+ ".a",
114
+ }
115
+ )
116
+
117
+ _EXT_TO_LANG: dict[str, str] = {
118
+ ".py": "Python",
119
+ ".pyx": "Cython",
120
+ ".js": "JavaScript",
121
+ ".mjs": "JavaScript (ESM)",
122
+ ".ts": "TypeScript",
123
+ ".jsx": "React/JSX",
124
+ ".tsx": "React/TSX",
125
+ ".java": "Java",
126
+ ".kt": "Kotlin",
127
+ ".rs": "Rust",
128
+ ".go": "Go",
129
+ ".rb": "Ruby",
130
+ ".php": "PHP",
131
+ ".cs": "C#",
132
+ ".cpp": "C++",
133
+ ".cc": "C++",
134
+ ".cxx": "C++",
135
+ ".c": "C",
136
+ ".h": "C/C++ header",
137
+ ".hpp": "C++ header",
138
+ ".swift": "Swift",
139
+ ".dart": "Dart",
140
+ ".lua": "Lua",
141
+ ".sh": "Shell",
142
+ ".bash": "Bash",
143
+ ".zsh": "Zsh",
144
+ ".fish": "Fish",
145
+ ".ps1": "PowerShell",
146
+ ".html": "HTML",
147
+ ".htm": "HTML",
148
+ ".css": "CSS",
149
+ ".scss": "SCSS/Sass",
150
+ ".less": "Less",
151
+ ".sql": "SQL",
152
+ ".json": "JSON",
153
+ ".yaml": "YAML",
154
+ ".yml": "YAML",
155
+ ".toml": "TOML",
156
+ ".xml": "XML",
157
+ ".md": "Markdown",
158
+ ".rst": "reStructuredText",
159
+ ".r": "R",
160
+ ".jl": "Julia",
161
+ ".ex": "Elixir",
162
+ ".exs": "Elixir Script",
163
+ ".erl": "Erlang",
164
+ ".hs": "Haskell",
165
+ ".elm": "Elm",
166
+ ".clj": "Clojure",
167
+ ".vue": "Vue",
168
+ ".svelte": "Svelte",
169
+ ".tf": "Terraform",
170
+ ".proto": "Protobuf",
171
+ ".graphql": "GraphQL",
172
+ ".gql": "GraphQL",
173
+ }
174
+
175
+ _DEPENDENCY_FILES: list[str] = [
176
+ "pyproject.toml",
177
+ "requirements.txt",
178
+ "requirements-dev.txt",
179
+ "setup.py",
180
+ "setup.cfg",
181
+ "Pipfile",
182
+ "package.json",
183
+ "Cargo.toml",
184
+ "go.mod",
185
+ "pom.xml",
186
+ "Gemfile",
187
+ "composer.json",
188
+ "pubspec.yaml",
189
+ "mix.exs",
190
+ ]
191
+
192
+ _PROJECT_TYPE_MARKERS: dict[str, str] = {
193
+ "pyproject.toml": "Python (pyproject)",
194
+ "setup.py": "Python (setuptools)",
195
+ "requirements.txt": "Python",
196
+ "Pipfile": "Python (Pipenv)",
197
+ "package.json": "Node.js / JavaScript",
198
+ "Cargo.toml": "Rust",
199
+ "go.mod": "Go",
200
+ "pom.xml": "Java (Maven)",
201
+ "build.gradle": "Java/Kotlin (Gradle)",
202
+ "Gemfile": "Ruby",
203
+ "composer.json": "PHP",
204
+ "pubspec.yaml": "Dart / Flutter",
205
+ "mix.exs": "Elixir",
206
+ "CMakeLists.txt": "C/C++ (CMake)",
207
+ "Makefile": "C/C++ (Make)",
208
+ }
209
+
210
+
211
+ def build_context_block(
212
+ get_editor: Callable[[], Any] | None = None,
213
+ get_workspace: Callable[[], Any] | None = None,
214
+ ) -> str:
215
+ """Constrói e retorna o bloco de contexto do projeto/editor.
216
+
217
+ Retorna string vazia se não houver nada relevante a informar.
218
+ Nunca levanta exceção - todas as coletas são envolvidas em try/except.
219
+
220
+ Parameters
221
+ ----------
222
+ get_editor:
223
+ Callable que retorna o EditorPane ativo, ou None.
224
+ get_workspace:
225
+ Callable que retorna o Path do workspace, ou None.
226
+ """
227
+ builder = _ContextBuilder(get_editor, get_workspace)
228
+ return builder.build()
229
+
230
+
231
+ class _ContextBuilder:
232
+ """Coleta e monta o bloco de contexto de forma controlada e segura."""
233
+
234
+ def __init__(
235
+ self,
236
+ get_editor: Callable[[], Any] | None,
237
+ get_workspace: Callable[[], Any] | None,
238
+ ) -> None:
239
+ self._get_editor = get_editor
240
+ self._get_workspace = get_workspace
241
+ self._parts: list[str] = []
242
+ self._chars_used: int = 0
243
+
244
+ def build(self) -> str:
245
+ """Constrói e retorna o bloco de contexto completo."""
246
+ workspace = self._safe_workspace()
247
+ editor = self._safe_editor()
248
+
249
+ self._collect_project_header(workspace)
250
+ self._collect_git_info(workspace)
251
+ self._collect_project_tree(workspace)
252
+ self._collect_readme(workspace)
253
+ self._collect_dependencies(workspace)
254
+ self._collect_active_file(editor, workspace)
255
+
256
+ if not self._parts:
257
+ return ""
258
+
259
+ body = "\n\n".join(self._parts)
260
+ return f"\n\n---\n## Context\n\n{body}\n---\n"
261
+
262
+ def _collect_project_header(self, workspace: Path | None) -> None:
263
+ """Registra nome, caminho, tipo e linguagens detectadas do workspace."""
264
+ if workspace is None:
265
+ self._add(
266
+ "*Nenhum workspace aberto. Respondendo sem contexto de projeto.*")
267
+ return
268
+
269
+ proj_type = "desconhecido"
270
+ for marker, label in _PROJECT_TYPE_MARKERS.items():
271
+ if (workspace / marker).exists():
272
+ proj_type = label
273
+ break
274
+
275
+ langs = self._detect_project_languages(workspace)
276
+ langs_label = (
277
+ ", ".join(
278
+ f"{lang} ({count} arquivo{'s' if count != 1 else ''})"
279
+ for lang, count in langs[:5]
280
+ )
281
+ if langs
282
+ else "indeterminado"
283
+ )
284
+
285
+ self._add(
286
+ f"**Projeto:** `{workspace.name}` (`{workspace}`) - {proj_type}\n"
287
+ f"**Linguagens:** {langs_label}"
288
+ )
289
+
290
+ def _collect_git_info(self, workspace: Path | None) -> None:
291
+ """Branch atual, último commit e lista de arquivos modificados."""
292
+ if workspace is None:
293
+ return
294
+ with contextlib.suppress(OSError, FileNotFoundError):
295
+ branch = self._run_git(
296
+ ["git", "branch", "--show-current"], workspace)
297
+ if not branch:
298
+ return
299
+
300
+ commit = self._run_git(
301
+ ["git", "log", "-1", "--pretty=format:%h - %s"],
302
+ workspace,
303
+ )
304
+
305
+ git_parts = [f"**Git:** branch `{branch}`"]
306
+ if commit:
307
+ git_parts.append(f"último commit: `{commit}`")
308
+
309
+ git_status_raw = self._run_git(
310
+ ["git", "status", "--short", "--porcelain"], workspace
311
+ )
312
+ if git_status_raw:
313
+ modified = [
314
+ line[3:].strip()
315
+ for line in git_status_raw.splitlines()
316
+ if line.strip()
317
+ ][:8]
318
+ if modified:
319
+ git_parts.append(
320
+ "arquivos modificados: " +
321
+ ", ".join(f"`{f}`" for f in modified)
322
+ )
323
+
324
+ self._add(" | ".join(git_parts))
325
+
326
+ def _collect_project_tree(self, workspace: Path | None) -> None:
327
+ """Lista hierárquica compacta dos arquivos relevantes do workspace."""
328
+ if workspace is None or self._over_budget():
329
+ return
330
+ lines: list[str] = []
331
+ self._walk_tree(workspace, workspace, 0, lines)
332
+ if not lines:
333
+ return
334
+ tree_text = "\n".join(lines[:_MAX_TREE_LINES])
335
+ self._add("### Estrutura do projeto\n```\n" + tree_text + "\n```")
336
+
337
+ def _walk_tree(
338
+ self,
339
+ root: Path,
340
+ target: Path,
341
+ depth: int,
342
+ out: list[str],
343
+ ) -> None:
344
+ """Percorre a árvore de diretórios de forma recursiva e limitada."""
345
+ if depth > 4 or len(out) >= _MAX_TREE_LINES:
346
+ return
347
+ indent = " " * depth
348
+ try:
349
+ entries = sorted(
350
+ target.iterdir(),
351
+ key=lambda p: (p.is_file(), p.name.lower()),
352
+ )
353
+ except OSError:
354
+ return
355
+
356
+ for entry in entries:
357
+ if len(out) >= _MAX_TREE_LINES:
358
+ break
359
+ if entry.name.startswith(".") and entry.name not in {".env.example"}:
360
+ continue
361
+ if entry.is_dir():
362
+ if entry.name in SKIP_DIRS:
363
+ continue
364
+ out.append(f"{indent}{entry.name}/")
365
+ self._walk_tree(root, entry, depth + 1, out)
366
+ elif entry.is_file():
367
+ if entry.suffix.lower() in _IGNORED_EXTENSIONS:
368
+ continue
369
+ size = entry.stat().st_size
370
+ size_label = f"{size // 1024} KB" if size >= 1024 else f"{size} B"
371
+ out.append(f"{indent}{entry.name} ({size_label})")
372
+
373
+ def _collect_readme(self, workspace: Path | None) -> None:
374
+ """Inclui as primeiras linhas não-triviais do README."""
375
+ if workspace is None or self._over_budget():
376
+ return
377
+ for name in ("README.md", "README.rst", "README.txt", "README"):
378
+ candidate = workspace / name
379
+ if candidate.is_file():
380
+ with contextlib.suppress(OSError):
381
+ lines = candidate.read_text(
382
+ "utf-8", errors="replace").splitlines()
383
+
384
+ meaningful = [
385
+ l_
386
+ for l_ in lines
387
+ if l_.strip() and not l_.strip().startswith("[![")
388
+ ][:_MAX_README_LINES]
389
+ if meaningful:
390
+ snippet = "\n".join(meaningful)
391
+ self._add(f"### README (resumo)\n```\n{snippet}\n```")
392
+ return
393
+
394
+ def _collect_dependencies(self, workspace: Path | None) -> None:
395
+ """Informa arquivo de dependências e lista os pacotes principais."""
396
+ if workspace is None or self._over_budget():
397
+ return
398
+ for dep_file in _DEPENDENCY_FILES:
399
+ path = workspace / dep_file
400
+ if not path.is_file():
401
+ continue
402
+ with contextlib.suppress(OSError):
403
+ content = path.read_text("utf-8", errors="replace")
404
+ lines = [
405
+ l_.strip()
406
+ for l_ in content.splitlines()
407
+ if l_.strip() and not l_.strip().startswith(("#", "//", ";", "["))
408
+ ]
409
+ preview = "\n".join(lines[:15])
410
+ self._add(
411
+ f"### Dependências (`{dep_file}`)\n```\n{preview}\n```")
412
+ return
413
+
414
+ def _collect_active_file(
415
+ self,
416
+ editor: Any,
417
+ workspace: Path | None,
418
+ ) -> None:
419
+ """Informações detalhadas sobre o arquivo aberto no editor."""
420
+ if editor is None:
421
+ self._add("*Nenhum arquivo aberto no editor.*")
422
+ return
423
+
424
+ file_path: Path | None = getattr(editor, "path", None)
425
+ lang: str = getattr(editor, "lang", "")
426
+ lang_label = _EXT_TO_LANG.get(f".{lang}", lang or "desconhecida")
427
+
428
+ if file_path:
429
+ if workspace and file_path.is_relative_to(workspace):
430
+ rel_path = str(file_path.relative_to(workspace))
431
+ else:
432
+ rel_path = str(file_path)
433
+ else:
434
+ rel_path = "(arquivo sem nome - ainda não salvo)"
435
+
436
+ self._add(f"### Arquivo ativo: `{rel_path}` - {lang_label}")
437
+
438
+ content: str | None = None
439
+ with contextlib.suppress(tk.TclError):
440
+ content = editor.text.get("1.0", "end-1c")
441
+ if content is None and file_path:
442
+ with contextlib.suppress(OSError):
443
+ content = file_path.read_text("utf-8", errors="replace")
444
+
445
+ cursor_line = self._collect_cursor_position(editor)
446
+
447
+ if content:
448
+ self._collect_imports(content, lang)
449
+
450
+ if content:
451
+ self._collect_symbols(content, lang)
452
+
453
+ if content and cursor_line > 0:
454
+ self._collect_cursor_region(content, cursor_line, lang)
455
+
456
+ self._collect_selection(editor, lang)
457
+
458
+ if content:
459
+ self._collect_todos(content)
460
+
461
+ self._collect_diagnostics(editor)
462
+
463
+ if content:
464
+ self._collect_style_hints(content)
465
+
466
+ def _collect_cursor_position(self, editor: Any) -> int:
467
+ """Linha e coluna atual do cursor. Retorna número da linha (1-based)."""
468
+ try:
469
+ index = editor.text.index("insert")
470
+ row, col = index.split(".")
471
+ row_int = int(row)
472
+ self._add(f"**Cursor:** linha {row_int}, coluna {int(col) + 1}")
473
+ return row_int
474
+ except (tk.TclError, ValueError):
475
+ return 0
476
+
477
+ def _collect_imports(self, content: str, lang: str) -> None:
478
+ """Lista os imports/includes do arquivo para orientar sobre dependências."""
479
+ if self._over_budget():
480
+ return
481
+ lines = content.splitlines()
482
+ imports: list[str] = []
483
+
484
+ if lang == "python":
485
+ for line in lines:
486
+ stripped = line.strip()
487
+ if stripped.startswith(("import ", "from ")):
488
+ imports.append(stripped)
489
+ elif stripped and not stripped.startswith("#") and imports:
490
+ if not stripped.startswith(('"""', "'''", "#")):
491
+ break
492
+
493
+ elif lang in ("javascript", "typescript", "jsx", "tsx"):
494
+ import_re = re.compile(r"^(?:import|require|export)\s+")
495
+ for line in lines[:50]:
496
+ if import_re.match(line.strip()):
497
+ imports.append(line.strip())
498
+
499
+ elif lang in ("java", "kotlin", "cs"):
500
+ import_re = re.compile(r"^(?:import|using)\s+")
501
+ for line in lines[:60]:
502
+ if import_re.match(line.strip()):
503
+ imports.append(line.strip())
504
+
505
+ elif lang == "go":
506
+ in_import = False
507
+ for line in lines[:40]:
508
+ stripped = line.strip()
509
+ if stripped.startswith("import ("):
510
+ in_import = True
511
+ elif in_import and stripped == ")":
512
+ break
513
+ elif in_import or stripped.startswith("import "):
514
+ imports.append(stripped)
515
+
516
+ if imports:
517
+ preview = "\n".join(imports[:_MAX_IMPORTS])
518
+ self._add(f"**Imports:**\n```\n{preview}\n```")
519
+
520
+ def _collect_symbols(self, content: str, lang: str) -> None:
521
+ """Extrai símbolos (funções, classes, variáveis) do conteúdo por linguagem."""
522
+ if self._over_budget():
523
+ return
524
+ symbols = _extract_symbols(content, lang)
525
+ if not symbols:
526
+ return
527
+ lines_out = [f" - {s}" for s in symbols[:_MAX_SYMBOLS]]
528
+ self._add("**Símbolos definidos:**\n" + "\n".join(lines_out))
529
+
530
+ def _collect_cursor_region(
531
+ self,
532
+ content: str,
533
+ cursor_line: int,
534
+ lang: str,
535
+ ) -> None:
536
+ """Exibe as linhas ao redor do cursor - região de maior relevância."""
537
+ if self._over_budget():
538
+ return
539
+ lines = content.splitlines()
540
+ total = len(lines)
541
+ if total == 0:
542
+ return
543
+
544
+ start = max(0, cursor_line - _CURSOR_WINDOW_LINES - 1)
545
+ end = min(total, cursor_line + _CURSOR_WINDOW_LINES)
546
+ region = lines[start:end]
547
+
548
+ numbered = "\n".join(
549
+ f"{start + i + 1:4d} {line}" for i, line in enumerate(region)
550
+ )
551
+ line_start = start + 1
552
+ line_end = start + len(region)
553
+ self._add(
554
+ f"**Região do cursor (linhas {line_start}–{line_end}):**\n```{lang}\n{numbered}\n```"
555
+ )
556
+
557
+ def _collect_selection(self, editor: Any, lang: str) -> None:
558
+ """Texto atualmente selecionado no editor (quando há seleção ativa)."""
559
+ if self._over_budget():
560
+ return
561
+ with contextlib.suppress(tk.TclError):
562
+ selected = editor.text.get(tk.SEL_FIRST, tk.SEL_LAST)
563
+ if selected and selected.strip():
564
+ preview = selected[:800]
565
+ if len(selected) > 800:
566
+ preview += "\n... (truncado)"
567
+ self._add(f"**Texto selecionado:**\n```{lang}\n{preview}\n```")
568
+
569
+ def _collect_todos(self, content: str) -> None:
570
+ """Coleta comentários TODO/FIXME/HACK do conteúdo para enriquecer o contexto."""
571
+ if self._over_budget():
572
+ return
573
+ todo_re = re.compile(
574
+ r"(?:TODO|FIXME|HACK|XXX|BUG)\s*[:\-]?\s*(.+)", re.IGNORECASE
575
+ )
576
+ found: list[str] = []
577
+ for i, line in enumerate(content.splitlines(), 1):
578
+ m = todo_re.search(line)
579
+ if m:
580
+ found.append(f" linha {i}: {line.strip()[:100]}")
581
+ if len(found) >= _MAX_TODOS:
582
+ break
583
+ if found:
584
+ self._add("**TODOs/FIXMEs:**\n" + "\n".join(found))
585
+
586
+ def _collect_diagnostics(self, editor: Any) -> None:
587
+ """Erros e avisos do linter/LSP do arquivo ativo."""
588
+ with contextlib.suppress(AttributeError):
589
+ diags = getattr(editor, "_diags", []) or []
590
+ if not diags:
591
+ self._add("**Diagnósticos:** ✅ Nenhum erro ou aviso")
592
+ return
593
+ lines = []
594
+ for d in diags[:10]:
595
+ level = getattr(d, "level", "?").upper()
596
+ lineno = getattr(d, "line", 0)
597
+ msg = getattr(d, "message", str(d))
598
+ source = getattr(d, "source", "")
599
+ entry = f" [{level}] linha {lineno}: {msg}"
600
+ if source:
601
+ entry += f" ({source})"
602
+ lines.append(entry)
603
+ self._add("**Diagnósticos:**\n" + "\n".join(lines))
604
+
605
+ def _collect_style_hints(self, content: str) -> None:
606
+ """Indentação detectada - para manter consistência ao gerar código."""
607
+ with contextlib.suppress(ValueError, AttributeError):
608
+ if not content:
609
+ return
610
+ uses_tabs = "\t" in content
611
+ indent_char = "tabs" if uses_tabs else "espaços"
612
+ indent_size: int | None = None
613
+ for line in content.splitlines():
614
+ if line.startswith(" "):
615
+ indent_size = 4
616
+ break
617
+ if line.startswith(" "):
618
+ indent_size = 2
619
+ break
620
+ size_label = f" ({indent_size} por nível)" if indent_size else ""
621
+ self._add(f"**Estilo:** indentação com {indent_char}{size_label}")
622
+
623
+ @staticmethod
624
+ def _detect_project_languages(workspace: Path) -> list[tuple[str, int]]:
625
+ """Retorna as linguagens mais presentes no workspace com contagem."""
626
+ counts: dict[str, int] = {}
627
+ with contextlib.suppress(OSError):
628
+ for p in workspace.rglob("*"):
629
+ if p.is_file() and p.suffix.lower() in _EXT_TO_LANG:
630
+ if any(part in SKIP_DIRS for part in p.parts):
631
+ continue
632
+ lang = _EXT_TO_LANG[p.suffix.lower()]
633
+ counts[lang] = counts.get(lang, 0) + 1
634
+ return sorted(counts.items(), key=lambda x: -x[1])[:6]
635
+
636
+ def _add(self, text: str) -> None:
637
+ """Adiciona um trecho ao bloco, respeitando o orçamento de caracteres."""
638
+ if self._chars_used + len(text) > _MAX_CONTEXT_CHARS:
639
+ return
640
+ self._parts.append(text)
641
+ self._chars_used += len(text)
642
+
643
+ def _over_budget(self) -> bool:
644
+ return self._chars_used >= _MAX_CONTEXT_CHARS
645
+
646
+ def _safe_editor(self) -> Any:
647
+ """Retorna o editor ativo sem levantar exceção."""
648
+ try:
649
+ return self._get_editor() if self._get_editor else None
650
+ except (AttributeError, RuntimeError):
651
+ return None
652
+
653
+ def _safe_workspace(self) -> Path | None:
654
+ """Retorna o workspace Path sem levantar exceção."""
655
+ try:
656
+ return self._get_workspace() if self._get_workspace else None
657
+ except (AttributeError, RuntimeError):
658
+ return None
659
+
660
+ @staticmethod
661
+ def _run_git(args: list[str], cwd: Path) -> str:
662
+ """Executa um comando git e retorna stdout limpo, ou string vazia."""
663
+ try:
664
+ result = _run(
665
+ args,
666
+ cwd=str(cwd),
667
+ capture_output=True,
668
+ text=True,
669
+ timeout=5,
670
+ check=False,
671
+ )
672
+ return result.stdout.strip()
673
+ except (OSError, subprocess.TimeoutExpired):
674
+ return ""
675
+
676
+
677
+ def _extract_symbols(content: str, lang: str) -> list[str]:
678
+ """Extrai símbolos (classes, funções, etc.) de um arquivo de código fonte.
679
+
680
+ Retorna lista de strings no formato ``"tipo NomeDoSímbolo (linha N)"``.
681
+ Suporta as linguagens mais comuns com regexes leves - sem AST real.
682
+
683
+ Args:
684
+ content: Conteúdo completo do arquivo como texto.
685
+ lang: Identificador de linguagem no formato do Codis (ex: ``"python"``).
686
+ """
687
+ symbols: list[str] = []
688
+ lines = content.splitlines()
689
+
690
+ extractor = _SYMBOL_EXTRACTORS.get(lang) or _SYMBOL_EXTRACTORS.get(
691
+ _LANG_ALIASES.get(lang, "")
692
+ )
693
+ if extractor is None:
694
+ extractor = _extract_symbols_generic
695
+ extractor(lines, symbols)
696
+ return symbols
697
+
698
+
699
+ _LANG_ALIASES: dict[str, str] = {
700
+ "jsx": "javascript",
701
+ "tsx": "typescript",
702
+ "c++": "cpp",
703
+ "kotlin": "java",
704
+ }
705
+
706
+
707
+ def _extract_symbols_python(lines: list[str], out: list[str]) -> None:
708
+ """Extrai classes, funções e funções assíncronas de Python."""
709
+ pattern = re.compile(r"^(\s*)(class|def|async def)\s+(\w+)")
710
+ for i, line in enumerate(lines, 1):
711
+ m = pattern.match(line)
712
+ if m:
713
+ indent = len(m.group(1))
714
+ prefix = " " if indent > 0 else ""
715
+ out.append(f"{prefix}{m.group(2)} {m.group(3)} (linha {i})")
716
+
717
+
718
+ def _extract_symbols_js(lines: list[str], out: list[str]) -> None:
719
+ """Extrai classes, funções e arrow functions de JavaScript/TypeScript."""
720
+ cls_pat = re.compile(r"^(?:export\s+)?(?:abstract\s+)?class\s+(\w+)")
721
+ fn_pat = re.compile(
722
+ r"^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)"
723
+ )
724
+ arrow_pat = re.compile(
725
+ r"^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?"
726
+ r"(?:function|\(|[a-zA-Z_$][\w$]*\s*=>)"
727
+ )
728
+ for i, line in enumerate(lines, 1):
729
+ stripped = line.strip()
730
+ if m := cls_pat.match(stripped):
731
+ out.append(f"class {m.group(1)} (linha {i})")
732
+ elif m := fn_pat.match(stripped):
733
+ out.append(f"function {m.group(1)} (linha {i})")
734
+ elif m := arrow_pat.match(stripped):
735
+ out.append(f"const {m.group(1)} (arrow/fn) (linha {i})")
736
+
737
+
738
+ def _extract_symbols_java(lines: list[str], out: list[str]) -> None:
739
+ """Extrai classes, interfaces e métodos de Java/Kotlin."""
740
+ cls_pat = re.compile(
741
+ r"(?:public|private|protected|internal|open|data|abstract|sealed)?\s*"
742
+ r"(?:class|interface|object|enum)\s+(\w+)"
743
+ )
744
+ fn_pat = re.compile(
745
+ r"(?:public|private|protected|internal|override|suspend|fun|void)\s+(\w+)\s*\("
746
+ )
747
+ for i, line in enumerate(lines, 1):
748
+ if line.strip().startswith("//"):
749
+ continue
750
+ if m := cls_pat.search(line):
751
+ out.append(f"class {m.group(1)} (linha {i})")
752
+ elif m := fn_pat.search(line):
753
+ out.append(f" fun {m.group(1)} (linha {i})")
754
+
755
+
756
+ def _extract_symbols_rust(lines: list[str], out: list[str]) -> None:
757
+ """Extrai fn, struct, enum, trait, impl, mod e type de Rust."""
758
+ _RUST_KINDS = {"fn", "struct", "enum", "trait", "impl", "mod", "type"}
759
+ pat = re.compile(
760
+ r"^(?:pub(?:\([^)]*\))?\s+)?(?:fn|struct|enum|trait|impl|mod|type)\s+(\w+)"
761
+ )
762
+ for i, line in enumerate(lines, 1):
763
+ m = pat.match(line)
764
+ if m:
765
+ kind = next((t for t in line.strip().split()
766
+ if t in _RUST_KINDS), "fn")
767
+ out.append(f"{kind} {m.group(1)} (linha {i})")
768
+
769
+
770
+ def _extract_symbols_go(lines: list[str], out: list[str]) -> None:
771
+ """Extrai func e type struct/interface de Go."""
772
+ fn_pat = re.compile(r"^func\s+(?:\(.*?\)\s+)?(\w+)")
773
+ typ_pat = re.compile(r"^type\s+(\w+)\s+(?:struct|interface)")
774
+ for i, line in enumerate(lines, 1):
775
+ if m := fn_pat.match(line):
776
+ out.append(f"func {m.group(1)} (linha {i})")
777
+ elif m := typ_pat.match(line):
778
+ out.append(f"type {m.group(1)} (linha {i})")
779
+
780
+
781
+ def _extract_symbols_ruby(lines: list[str], out: list[str]) -> None:
782
+ """Extrai def, class e module de Ruby."""
783
+ pat = re.compile(r"^\s*(?:def|class|module)\s+([\w.]+)")
784
+ for i, line in enumerate(lines, 1):
785
+ m = pat.match(line)
786
+ if m:
787
+ kind = line.strip().split()[0]
788
+ indent = " " if line.startswith(" ") else ""
789
+ out.append(f"{indent}{kind} {m.group(1)} (linha {i})")
790
+
791
+
792
+ def _extract_symbols_php(lines: list[str], out: list[str]) -> None:
793
+ """Extrai function, class, interface, trait e enum de PHP."""
794
+ pat = re.compile(
795
+ r"(?:function|class|interface|trait|enum)\s+(\w+)", re.IGNORECASE)
796
+ for i, line in enumerate(lines, 1):
797
+ stripped = line.strip()
798
+ if stripped.startswith("//") or stripped.startswith("*"):
799
+ continue
800
+ m = pat.search(line)
801
+ if m:
802
+ kind = m.group(0).strip().split()[0].lower()
803
+ out.append(f"{kind} {m.group(1)} (linha {i})")
804
+
805
+
806
+ def _extract_symbols_c(lines: list[str], out: list[str]) -> None:
807
+ """Extrai class, struct, namespace, enum e funções de C/C++."""
808
+ cls_pat = re.compile(r"^(?:class|struct|namespace|enum)\s+(\w+)")
809
+ fn_pat = re.compile(
810
+ r"^(?:[\w:*&<>\s]+?)\s+(\w+)\s*\([^;]*\)\s*(?:const\s*)?(?:\{|$)"
811
+ )
812
+ for i, line in enumerate(lines, 1):
813
+ stripped = line.strip()
814
+ if stripped.startswith("//") or stripped.startswith("#"):
815
+ continue
816
+ if m := cls_pat.match(stripped):
817
+ kind = stripped.split()[0]
818
+ out.append(f"{kind} {m.group(1)} (linha {i})")
819
+ elif m := fn_pat.match(line):
820
+ out.append(f"fn {m.group(1)} (linha {i})")
821
+
822
+
823
+ def _extract_symbols_generic(lines: list[str], out: list[str]) -> None:
824
+ """Extrai símbolos de linguagens não mapeadas usando padrão genérico."""
825
+ pat = re.compile(
826
+ r"^\s*(?:function|func|fn|def|proc|procedure|sub)\s+(\w+)",
827
+ re.IGNORECASE,
828
+ )
829
+ for i, line in enumerate(lines, 1):
830
+ m = pat.match(line)
831
+ if m:
832
+ out.append(f"function {m.group(1)} (linha {i})")
833
+
834
+
835
+ _SymExtractor = Callable[[list[str], list[str]], None]
836
+ _SYMBOL_EXTRACTORS: dict[str, _SymExtractor] = {
837
+ "python": _extract_symbols_python,
838
+ "javascript": _extract_symbols_js,
839
+ "typescript": _extract_symbols_js,
840
+ "java": _extract_symbols_java,
841
+ "rust": _extract_symbols_rust,
842
+ "go": _extract_symbols_go,
843
+ "ruby": _extract_symbols_ruby,
844
+ "php": _extract_symbols_php,
845
+ "c": _extract_symbols_c,
846
+ "cpp": _extract_symbols_c,
847
+ }
848
+
849
+
850
+ class ContextBuilder:
851
+ """Constrói um dicionário de contexto para envio ao assistente de IA.
852
+
853
+ Ao contrário de ``_ContextBuilder`` (que coleta dados automaticamente
854
+ do editor e workspace via callbacks), esta classe aceita dados fornecidos
855
+ explicitamente pelo chamador - ideal para testes unitários e integrações
856
+ programáticas.
857
+
858
+ Suporta encadeamento fluente::
859
+
860
+ ctx = (
861
+ ContextBuilder()
862
+ .set_code(\"def foo(): pass\")
863
+ .set_language(\"python\")
864
+ .set_file_path(\"/tmp/foo.py\")
865
+ .set_cursor_position(line=1, col=0)
866
+ .build()
867
+ )
868
+
869
+ Uso típico em código de produção
870
+ ---------------------------------
871
+ from src.ia.context_builder import ContextBuilder
872
+
873
+ ctx = ContextBuilder().set_code(editor.get_text()).set_language(lang).build()
874
+ """
875
+
876
+ def __init__(self) -> None:
877
+ self._data: dict = {}
878
+
879
+ def set_code(self, code: str) -> ContextBuilder:
880
+ """Define o código-fonte a ser incluído no contexto."""
881
+ self._data["code"] = code
882
+ return self
883
+
884
+ def set_language(self, language: str) -> ContextBuilder:
885
+ """Define a linguagem do arquivo ativo (ex: ``\"python\"``)."""
886
+ self._data["language"] = language
887
+ return self
888
+
889
+ def set_file_path(self, path: str) -> ContextBuilder:
890
+ """Define o caminho do arquivo ativo."""
891
+ self._data["file_path"] = path
892
+ return self
893
+
894
+ def set_selection(self, text: str) -> ContextBuilder:
895
+ """Define o texto atualmente selecionado no editor."""
896
+ self._data["selection"] = text
897
+ return self
898
+
899
+ def set_cursor_position(self, *, line: int, col: int) -> ContextBuilder:
900
+ """Define a posição do cursor (linha e coluna, ambas 0-based ou 1-based)."""
901
+ self._data["cursor"] = {"line": line, "col": col}
902
+ return self
903
+
904
+ def set_diagnostics(self, diagnostics: list) -> ContextBuilder:
905
+ """Define a lista de diagnósticos do linter/LSP."""
906
+ self._data["diagnostics"] = diagnostics
907
+ return self
908
+
909
+ def reset(self) -> ContextBuilder:
910
+ """Limpa todos os dados acumulados, permitindo reutilização do builder."""
911
+ self._data = {}
912
+ return self
913
+
914
+ def build(self) -> dict:
915
+ """Retorna uma cópia do dicionário de contexto acumulado.
916
+
917
+ Chamadas repetidas sem alterações intermediárias retornam dicionários
918
+ equivalentes (idempotência). Modificar o retorno não afeta o estado
919
+ interno do builder.
920
+ """
921
+ return dict(self._data)