codebase-explorer 2.2.0__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 (47) hide show
  1. cbe/__init__.py +9 -0
  2. cbe/__main__.py +4 -0
  3. cbe/aggregation.py +183 -0
  4. cbe/api_completion.py +410 -0
  5. cbe/batching.py +283 -0
  6. cbe/catalog_query.py +376 -0
  7. cbe/checks.py +390 -0
  8. cbe/cli.py +434 -0
  9. cbe/concrete_facts.py +321 -0
  10. cbe/data/LICENSE.tiktoken +30 -0
  11. cbe/data/o200k_base.tiktoken +199998 -0
  12. cbe/declarations.py +537 -0
  13. cbe/docs.py +929 -0
  14. cbe/generate.py +316 -0
  15. cbe/grammars.py +741 -0
  16. cbe/graph.py +857 -0
  17. cbe/graph_backends/__init__.py +43 -0
  18. cbe/graph_backends/_calls.py +262 -0
  19. cbe/graph_backends/_paths.py +42 -0
  20. cbe/graph_backends/identity.py +93 -0
  21. cbe/graph_backends/imports.py +256 -0
  22. cbe/graph_backends/joern.py +1021 -0
  23. cbe/graph_backends/resolution.py +288 -0
  24. cbe/graph_backends/toolchain.py +396 -0
  25. cbe/grounding.py +57 -0
  26. cbe/host_run.py +1752 -0
  27. cbe/model_settings.py +80 -0
  28. cbe/projection.py +305 -0
  29. cbe/prompts.py +316 -0
  30. cbe/records.py +200 -0
  31. cbe/skeleton.py +474 -0
  32. cbe/source_context.py +709 -0
  33. cbe/symbols.py +136 -0
  34. cbe/token_budget.py +68 -0
  35. cbe/treename.py +398 -0
  36. cbe/usage.py +300 -0
  37. cbe_install/__init__.py +11 -0
  38. cbe_install/cli.py +434 -0
  39. cbe_install/resources/agents/cbe-writer.md +16 -0
  40. cbe_install/resources/codebase-explorer/SKILL.md +101 -0
  41. cbe_install/resources/codebase-explorer/references/claude-code.md +63 -0
  42. cbe_install/resources/codebase-explorer/references/codex.md +37 -0
  43. codebase_explorer-2.2.0.dist-info/METADATA +233 -0
  44. codebase_explorer-2.2.0.dist-info/RECORD +47 -0
  45. codebase_explorer-2.2.0.dist-info/WHEEL +4 -0
  46. codebase_explorer-2.2.0.dist-info/entry_points.txt +3 -0
  47. codebase_explorer-2.2.0.dist-info/licenses/LICENSE +21 -0
cbe/concrete_facts.py ADDED
@@ -0,0 +1,321 @@
1
+ """Deterministic concrete facts frozen from Python syntax.
2
+
3
+ Parameter defaults, named constants, flattened option tables, format
4
+ templates and literal raises are projected with the stdlib ``ast`` alone:
5
+ the source is parsed, never executed, and no model is consulted. Fact text
6
+ is source syntax with a line number, not a verified runtime value.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import re
13
+ from typing import Any, Iterator
14
+
15
+
16
+ MAX_TEXT_CHARS = 160
17
+ MAX_CONSTANT_ITEMS = 12
18
+ MAX_TABLE_DEPTH = 6
19
+
20
+ KIND_ORDER = ("param_default", "constant", "option", "template", "raise")
21
+
22
+ # Placeholder grammars: str.format braces, %-named and single-letter %-codes.
23
+ # ``{{``/``%%`` escapes are excluded by the lookaround guards.
24
+ _BRACE_PLACEHOLDER = re.compile(r"(?<!\{)\{([A-Za-z_][A-Za-z0-9_]*)(?::[^{}]*)?\}(?!\})")
25
+ _PERCENT_NAMED = re.compile(r"%\(([A-Za-z_][A-Za-z0-9_]*)\)[#0\- +]*\d*(?:\.\d+)?[A-Za-z%]")
26
+ _PERCENT_BARE = re.compile(r"(?<!%)%[A-Za-z]")
27
+
28
+
29
+ def _capped(text: str) -> tuple[str, bool]:
30
+ if len(text) <= MAX_TEXT_CHARS:
31
+ return text, False
32
+ return text[: MAX_TEXT_CHARS - 1] + "…", True
33
+
34
+
35
+ def _fact(kind: str, symbol: str, text: str, line: int,
36
+ placeholders: list[str] | None = None) -> dict[str, Any]:
37
+ capped, truncated = _capped(text)
38
+ row: dict[str, Any] = {"kind": kind, "symbol": symbol, "text": capped, "line": line}
39
+ if placeholders:
40
+ row["placeholders"] = placeholders
41
+ if truncated:
42
+ row["truncated"] = True
43
+ return row
44
+
45
+
46
+ def _placeholders(literal: str) -> list[str]:
47
+ """Unique placeholder tokens in source order, as written."""
48
+ tokens: list[str] = []
49
+ for pattern in (_BRACE_PLACEHOLDER, _PERCENT_NAMED, _PERCENT_BARE):
50
+ for match in pattern.finditer(literal):
51
+ if match.group(0) not in tokens:
52
+ tokens.append(match.group(0))
53
+ return tokens
54
+
55
+
56
+ def _bind_counts(stmts: list[ast.stmt]) -> dict[str, int]:
57
+ """Direct rebinding counts for one scope; nested scopes are not walked."""
58
+ counts: dict[str, int] = {}
59
+ for stmt in stmts:
60
+ targets: list[ast.expr] = []
61
+ if isinstance(stmt, ast.Assign):
62
+ targets = list(stmt.targets)
63
+ elif isinstance(stmt, (ast.AnnAssign, ast.AugAssign)):
64
+ targets = [stmt.target]
65
+ for target in targets:
66
+ for node in ast.walk(target):
67
+ if isinstance(node, ast.Name):
68
+ counts[node.id] = counts.get(node.id, 0) + 1
69
+ return counts
70
+
71
+
72
+ def _assigned_names(stmt: ast.stmt) -> tuple[list[str], ast.expr | None]:
73
+ if isinstance(stmt, ast.Assign) and all(
74
+ isinstance(target, ast.Name) for target in stmt.targets):
75
+ return [target.id for target in stmt.targets], stmt.value
76
+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
77
+ return [stmt.target.id], stmt.value
78
+ return [], None
79
+
80
+
81
+ def _constant_text(value: ast.expr) -> str | None:
82
+ """Render a small literal assignment; tables and sets stay out."""
83
+ try:
84
+ literal = ast.literal_eval(value)
85
+ except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
86
+ return None
87
+ if isinstance(literal, (tuple, list, dict)) and len(literal) > MAX_CONSTANT_ITEMS:
88
+ return None
89
+ if isinstance(literal, (set, frozenset, bytes, complex)):
90
+ return None
91
+ return ast.unparse(value)
92
+
93
+
94
+ def _table_entries(node: ast.expr) -> list[tuple[str, ast.expr]] | None:
95
+ """Direct (key, value) pairs of a dict literal or a table-shaped call.
96
+
97
+ Shape only: ``{...}``, ``dict(...)`` and bare-name all-keyword calls
98
+ such as ``Namespace(...)``. ``**`` seeds, starred args, non-string
99
+ dict keys and attribute calls are not tables.
100
+ """
101
+ if isinstance(node, ast.Dict):
102
+ pairs: list[tuple[str, ast.expr]] = []
103
+ for key, item in zip(node.keys, node.values):
104
+ if not (isinstance(key, ast.Constant) and isinstance(key.value, str) and key.value):
105
+ return None
106
+ pairs.append((key.value, item))
107
+ return pairs
108
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
109
+ if any(keyword.arg is None for keyword in node.keywords):
110
+ return None
111
+ if any(isinstance(arg, ast.Starred) for arg in node.args) or len(node.args) > 1:
112
+ return None
113
+ pairs = []
114
+ if node.args:
115
+ seed = _table_entries(node.args[0])
116
+ if seed is None:
117
+ return None
118
+ pairs.extend(seed)
119
+ if not node.keywords and not pairs:
120
+ return None
121
+ pairs.extend((keyword.arg, keyword.value) for keyword in node.keywords)
122
+ return pairs
123
+ return None
124
+
125
+
126
+ def _flatten_table(node: ast.expr, prefix: str, out: list[tuple[str, ast.expr]],
127
+ depth: int = 0) -> bool:
128
+ """Flatten nested tables into (dotted path, leaf) pairs.
129
+
130
+ Returns False when ``node`` is not a table; the caller keeps such a
131
+ node whole as one leaf instead of losing the enclosing table.
132
+ """
133
+ if depth > MAX_TABLE_DEPTH:
134
+ return False
135
+ pairs = _table_entries(node)
136
+ if pairs is None:
137
+ return False
138
+ for key, item in pairs:
139
+ path = f"{prefix}.{key}" if prefix else key
140
+ if not _flatten_table(item, path, out, depth + 1):
141
+ out.append((path, item))
142
+ return True
143
+
144
+
145
+ def _table_leaves(name: str, value: ast.expr) -> list[tuple[str, ast.expr]]:
146
+ """Table leaves for one assignment, or [] when the value is not a table.
147
+
148
+ A flattened shape counts as an option table only when it has at least
149
+ two entries and real structure: a call value (``dict(...)`` itself or
150
+ ``Option(...)`` leaves) or a nested level in some path. Flat literal
151
+ dicts stay constants.
152
+ """
153
+ out: list[tuple[str, ast.expr]] = []
154
+ if not _flatten_table(value, "", out):
155
+ return []
156
+ if len(out) < 2:
157
+ return []
158
+ structured = (isinstance(value, ast.Call)
159
+ or any("." in path for path, _ in out)
160
+ or any(isinstance(leaf, ast.Call) for _, leaf in out))
161
+ return out if structured else []
162
+
163
+
164
+ def _signature_text(name: str, args: ast.arguments) -> str | None:
165
+ """Render ``name(a, b=default, *, c=default)``; None without any default."""
166
+ positional = [*args.posonlyargs, *args.args]
167
+ defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
168
+ parts: list[str] = []
169
+ for arg, default in zip(positional, defaults):
170
+ parts.append(arg.arg if default is None else f"{arg.arg}={ast.unparse(default)}")
171
+ if args.posonlyargs:
172
+ parts.insert(len(args.posonlyargs), "/")
173
+ if args.vararg or args.kwonlyargs:
174
+ parts.append(f"*{args.vararg.arg}" if args.vararg else "*")
175
+ for arg, default in zip(args.kwonlyargs, args.kw_defaults):
176
+ parts.append(arg.arg if default is None else f"{arg.arg}={ast.unparse(default)}")
177
+ if args.kwarg:
178
+ parts.append(f"**{args.kwarg.arg}")
179
+ if not any(default is not None for default in defaults) and not any(
180
+ default is not None for default in args.kw_defaults):
181
+ return None
182
+ return f"{name}({', '.join(parts)})"
183
+
184
+
185
+ def _raise_text(node: ast.Raise) -> str | None:
186
+ """``raise Error('literal message')`` only; unraised and formatted args stay out."""
187
+ if not isinstance(node.exc, ast.Call) or not node.exc.args:
188
+ return None
189
+ message = node.exc.args[0]
190
+ if not (isinstance(message, ast.Constant) and isinstance(message.value, str)):
191
+ return None
192
+ return f"raise {ast.unparse(node.exc)}"
193
+
194
+
195
+ def _own_statements(node: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[ast.stmt]:
196
+ """Statements of one function body, excluding nested defs and classes."""
197
+ stack: list[ast.stmt] = list(reversed(node.body))
198
+ while stack:
199
+ current = stack.pop()
200
+ if isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
201
+ continue
202
+ yield current
203
+ stack.extend(reversed(list(ast.iter_child_nodes(current))))
204
+
205
+
206
+ class _Collector:
207
+ """Gather facts per kind, tagged with the catalogue symbol they belong to.
208
+
209
+ The owner is None for file-level facts or the catalogue signature name
210
+ (``function``, ``Class`` or ``Class.method``) for symbol-level facts.
211
+ """
212
+
213
+ def __init__(self) -> None:
214
+ self.buckets: dict[str, list[tuple[str | None, dict[str, Any]]]] = {
215
+ kind: [] for kind in KIND_ORDER
216
+ }
217
+
218
+ def add(self, kind: str, owner: str | None, fact: dict[str, Any]) -> None:
219
+ self.buckets[kind].append((owner, fact))
220
+
221
+ def result(self) -> dict[str, Any]:
222
+ ordered = [(owner, fact) for kind in KIND_ORDER for owner, fact in self.buckets[kind]]
223
+ symbols: dict[str, list[dict[str, Any]]] = {}
224
+ for owner, fact in ordered:
225
+ if owner is not None:
226
+ symbols.setdefault(owner, []).append(fact)
227
+ return {
228
+ "file": [fact for owner, fact in ordered if owner is None],
229
+ "symbols": symbols,
230
+ "rows": [fact for _, fact in ordered],
231
+ }
232
+
233
+ def visit_module(self, tree: ast.Module) -> None:
234
+ binds = _bind_counts(tree.body)
235
+ for node in tree.body:
236
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
237
+ self.visit_function(node, node.name)
238
+ elif isinstance(node, ast.ClassDef):
239
+ self.visit_class(node)
240
+ else:
241
+ self.visit_assignment(node, None, binds)
242
+
243
+ def visit_class(self, node: ast.ClassDef) -> None:
244
+ binds = _bind_counts(node.body)
245
+ for child in node.body:
246
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
247
+ self.visit_function(child, f"{node.name}.{child.name}")
248
+ else:
249
+ self.visit_assignment(child, node.name, binds, prefix=node.name)
250
+
251
+ def visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef, owner: str) -> None:
252
+ signature = _signature_text(node.name, node.args)
253
+ if signature is not None:
254
+ self.add("param_default", owner,
255
+ _fact("param_default", node.name, signature, node.lineno))
256
+ positional = [*node.args.posonlyargs, *node.args.args]
257
+ defaults = [None] * (len(positional) - len(node.args.defaults)) + list(node.args.defaults)
258
+ for arg, default in [*zip(positional, defaults),
259
+ *zip(node.args.kwonlyargs, node.args.kw_defaults)]:
260
+ self._visit_default(arg.arg, default, node)
261
+ statements = list(_own_statements(node))
262
+ local_binds = _bind_counts(statements)
263
+ for statement in statements:
264
+ if isinstance(statement, ast.Raise):
265
+ text = _raise_text(statement)
266
+ if text is not None:
267
+ self.add("raise", owner,
268
+ _fact("raise", node.name, text, statement.lineno))
269
+ continue
270
+ self.visit_assignment(statement, owner, local_binds)
271
+
272
+ def _visit_default(self, name: str, default: ast.expr | None,
273
+ node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
274
+ if (isinstance(default, ast.Constant) and isinstance(default.value, str)
275
+ and _placeholders(default.value)):
276
+ self.add("template", node.name, _fact(
277
+ "template", name, ast.unparse(default), node.lineno,
278
+ placeholders=_placeholders(default.value)))
279
+
280
+ def visit_assignment(self, stmt: ast.stmt, owner: str | None,
281
+ binds: dict[str, int], prefix: str | None = None) -> None:
282
+ names, value = _assigned_names(stmt)
283
+ if value is None:
284
+ return
285
+ for name in names:
286
+ if binds.get(name, 0) > 1:
287
+ continue
288
+ symbol = f"{prefix}.{name}" if prefix else name
289
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
290
+ placeholders = _placeholders(value.value)
291
+ if placeholders:
292
+ self.add("template", owner, _fact(
293
+ "template", symbol, ast.unparse(value), stmt.lineno,
294
+ placeholders=placeholders))
295
+ continue
296
+ leaves = _table_leaves(name, value)
297
+ if leaves:
298
+ for path, leaf in leaves:
299
+ self.add("option", owner, _fact(
300
+ "option", f"{symbol}.{path}", ast.unparse(leaf), leaf.lineno))
301
+ continue
302
+ constant = _constant_text(value)
303
+ if constant is not None:
304
+ self.add("constant", owner, _fact(
305
+ "constant", symbol, constant, stmt.lineno))
306
+
307
+
308
+ def file_facts(path: str, source: str) -> dict[str, Any]:
309
+ """Extract the concrete facts of one Python file.
310
+
311
+ Returns ``{"file": [...], "symbols": {...}, "rows": [...]}``. Symbol
312
+ keys mirror ``batching._signatures`` (top-level ``name`` and
313
+ ``Class.method``); ``rows`` is every fact in kind priority order.
314
+ """
315
+ try:
316
+ tree = ast.parse(source, filename=path)
317
+ except (SyntaxError, ValueError, MemoryError, RecursionError):
318
+ return {"file": [], "symbols": {}, "rows": []}
319
+ collector = _Collector()
320
+ collector.visit_module(tree)
321
+ return collector.result()
@@ -0,0 +1,30 @@
1
+ The adjacent o200k_base.tiktoken is the public encoding resource used by
2
+ OpenAI's tiktoken. It is bundled so token counting works without a network
3
+ request or a pre-existing user cache.
4
+
5
+ Source: https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken
6
+ Upstream definition: https://github.com/openai/tiktoken/blob/main/tiktoken_ext/openai_public.py
7
+ Expected SHA-256: 446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d
8
+ Upstream license: https://github.com/openai/tiktoken/blob/main/LICENSE
9
+
10
+ MIT License
11
+
12
+ Copyright (c) 2022 OpenAI, Shantanu Jain
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.