contextgate-core 0.6.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.
- contextgate_core/__init__.py +48 -0
- contextgate_core/ab_compare.py +566 -0
- contextgate_core/bridge.py +345 -0
- contextgate_core/cli.py +560 -0
- contextgate_core/data_contracts.py +89 -0
- contextgate_core/downstream.py +165 -0
- contextgate_core/eval_retrieval.py +173 -0
- contextgate_core/gate.py +430 -0
- contextgate_core/gate_bench.py +148 -0
- contextgate_core/gateway.py +442 -0
- contextgate_core/hook.py +116 -0
- contextgate_core/ledger.py +228 -0
- contextgate_core/mcp_server.py +291 -0
- contextgate_core/pipeline.py +1756 -0
- contextgate_core/protocol.py +112 -0
- contextgate_core/py.typed +0 -0
- contextgate_core/registry.py +109 -0
- contextgate_core/repo_indexer.py +1128 -0
- contextgate_core/token_audit.py +242 -0
- contextgate_core-0.6.0.dist-info/METADATA +426 -0
- contextgate_core-0.6.0.dist-info/RECORD +25 -0
- contextgate_core-0.6.0.dist-info/WHEEL +5 -0
- contextgate_core-0.6.0.dist-info/entry_points.txt +5 -0
- contextgate_core-0.6.0.dist-info/licenses/LICENSE +21 -0
- contextgate_core-0.6.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1128 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Zero-LLM repository indexer + task-capsule compiler (Pre-Ingestion Repo Intelligence).
|
|
3
|
+
|
|
4
|
+
* Python via stdlib `ast` (regex fallback on SyntaxError); TS/JS and Markdown via structural regexes.
|
|
5
|
+
* Stored in `<root>/.smarty/index.db` (stdlib sqlite3 + FTS5 `bm25()`); incremental by mtime/size/sha1.
|
|
6
|
+
* Line spans are never trusted blindly: every query first refreshes changed files, so spans always
|
|
7
|
+
match the file content hash recorded in the index.
|
|
8
|
+
* Only `git ls-files` (or a pruned walk) is indexed; secret-looking files are skipped and slices redacted.
|
|
9
|
+
* No network, no LLM, standard library only.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import ast
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import sqlite3
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
from typing import Any, Iterable, Iterator
|
|
25
|
+
|
|
26
|
+
SCHEMA_VERSION = 4
|
|
27
|
+
INDEX_DIR = ".smarty"
|
|
28
|
+
DB_NAME = "index.db"
|
|
29
|
+
|
|
30
|
+
LANG_BY_EXT = {".py": "python", ".ts": "ts", ".tsx": "ts", ".js": "ts", ".jsx": "ts", ".mjs": "ts", ".md": "markdown"}
|
|
31
|
+
IGNORE_DIRS = {
|
|
32
|
+
"node_modules", "NLP-start", ".venv", "venv", "env", "__pycache__", ".pytest_cache", "out", "dist",
|
|
33
|
+
"build", ".git", ".smarty", ".idea", ".vscode", ".mypy_cache", ".tox", "site-packages",
|
|
34
|
+
}
|
|
35
|
+
IGNORE_FILES = {"package-lock.json", "yarn.lock", "pnpm-lock.yaml"}
|
|
36
|
+
SECRET_FILE_RE = re.compile(r"(^|/)(\.env(\..*)?|.*\.(pem|key|p12|pfx)|id_rsa.*|.*secrets?.*\.(json|ya?ml))$", re.I)
|
|
37
|
+
MAX_FILE_BYTES = 1_000_000
|
|
38
|
+
|
|
39
|
+
STOPWORDS = frozenset(
|
|
40
|
+
"a an the and or of to in on for with without from by is are was were be been this that it its as at "
|
|
41
|
+
"into over under please can could would should how what why when where which who i me my we our you "
|
|
42
|
+
"your do does did done make get set use using add fix update change new code file files function "
|
|
43
|
+
"so then also just but if than too very really some any".split()
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Retrieval tuning (defaults; to be tuned with eval_retrieval.py, not guessed)
|
|
47
|
+
BM25_WEIGHTS = (8.0, 3.0, 2.0, 1.5, 1.0) # name, signature, doc, path, calls
|
|
48
|
+
RECENCY_BOOST = 1.35
|
|
49
|
+
TEST_PENALTY = 0.6 # demote tests/specs unless the query is about tests
|
|
50
|
+
_TEST_PATH_RE = re.compile(r"(^|/)(tests?|__tests__|spec)/|(^|/)test_[^/]*$|[._]test\.[a-z]+$|[._]spec\.[a-z]+$")
|
|
51
|
+
MAX_PER_FILE = 2
|
|
52
|
+
NAME_MATCH_BOOST = 0.3 # rank bonus per distinct query term in a symbol's NAME (0 = pure BM25); +0.12 top-1 on an unseen TS repo, neutral here
|
|
53
|
+
# Graph / doc levers (set to 1.0 / 0.0 to disable; tuned by eval_retrieval.py --golden, not guessed)
|
|
54
|
+
GRAPH_CALLEE_BOOST = 1.25 # a hit that is called by another hit is probably the real implementation
|
|
55
|
+
IMPORT_NEIGHBOR_BOOST = 1.15 # a hit in a file imported by another matching file
|
|
56
|
+
CENTRALITY_WEIGHT = 0.08 # mild prior for files many others import: 1 + w*log1p(in-degree)
|
|
57
|
+
DOC_PENALTY = 0.85 # markdown sections rank below code unless the query is about docs
|
|
58
|
+
_DOC_QUERY_TERMS = frozenset({"readme", "doc", "documentation", "markdown", "changelog", "guide"})
|
|
59
|
+
MIN_CONFIDENCE = 0.34 # 0.25 let weak chatty-prompt matches through in real sessions
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ── token estimation ──────────────────────────────────────────────────────────
|
|
63
|
+
_ESTIMATOR = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _heuristic_tokens(text: str) -> int:
|
|
67
|
+
n = 0
|
|
68
|
+
for piece in re.findall(r"\w+|[^\w\s]", text):
|
|
69
|
+
n += max(1, math.ceil(len(piece) / 6)) if piece[0].isalnum() or piece[0] == "_" else 1
|
|
70
|
+
return n
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def est_tokens(text: str) -> int:
|
|
74
|
+
"""Use the project's BPE-calibrated estimator when importable, else a local heuristic."""
|
|
75
|
+
global _ESTIMATOR
|
|
76
|
+
if _ESTIMATOR is None:
|
|
77
|
+
_ESTIMATOR = _heuristic_tokens
|
|
78
|
+
if not os.environ.get("SMARTY_LIGHT_TOKENS"):
|
|
79
|
+
try:
|
|
80
|
+
from .pipeline import estimate_tokens # noqa: WPS433
|
|
81
|
+
|
|
82
|
+
_ESTIMATOR = estimate_tokens
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
return _ESTIMATOR(text)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ── identifier tokenization (shared by index + query) ────────────────────────
|
|
89
|
+
_IDENT_PART = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _stem(w: str) -> str:
|
|
93
|
+
for suf in ("ion", "ing", "ed", "es", "s"):
|
|
94
|
+
if len(w) > len(suf) + 3 and w.endswith(suf):
|
|
95
|
+
if suf == "s" and w.endswith(("ss", "us", "is")):
|
|
96
|
+
continue # keep compress/class/status/analysis intact so stem(compression) == stem(compress)
|
|
97
|
+
return w[: -len(suf)]
|
|
98
|
+
return w
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def tokenize(text: str, drop_stop: bool = False) -> list[str]:
|
|
102
|
+
out: list[str] = []
|
|
103
|
+
for word in re.findall(r"[A-Za-z0-9_]+", text or ""):
|
|
104
|
+
parts = [p.lower() for p in _IDENT_PART.findall(word.replace("_", " "))]
|
|
105
|
+
cand = parts + ([word.lower()] if len(parts) > 1 else [])
|
|
106
|
+
for c in cand:
|
|
107
|
+
if drop_stop and c in STOPWORDS:
|
|
108
|
+
continue
|
|
109
|
+
out.append(_stem(c))
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ── acronym / abbreviation aliases (query-side expansion, both directions) ────
|
|
115
|
+
# multi-word expansions only fire when ALL words are present in the query (avoids "context" -> mcp);
|
|
116
|
+
# single-word abbreviations (msg <-> message) alias in both directions unconditionally.
|
|
117
|
+
ACRONYMS: dict[str, tuple[str, ...]] = {
|
|
118
|
+
"mmr": ("maximal", "marginal", "relevance"), "tfidf": ("term", "frequency", "inverse", "document"),
|
|
119
|
+
"rag": ("retrieval", "augmented", "generation"), "bpe": ("byte", "pair", "encoding"),
|
|
120
|
+
"ast": ("abstract", "syntax", "tree"), "mcp": ("model", "context", "protocol"),
|
|
121
|
+
"llm": ("language", "model"), "nlp": ("natural", "language", "processing"), "hf": ("hugging", "face"),
|
|
122
|
+
"cfg": ("config",), "conf": ("config",), "msg": ("message",), "req": ("request",), "resp": ("response",),
|
|
123
|
+
"ctx": ("context",), "idx": ("index",), "impl": ("implementation",), "init": ("initialize",),
|
|
124
|
+
"repo": ("repository",), "env": ("environment",), "auth": ("authentication",), "db": ("database",),
|
|
125
|
+
"fn": ("function",), "param": ("parameter",), "arg": ("argument",), "cmd": ("command",), "err": ("error",),
|
|
126
|
+
} # deliberately excludes ambiguous short tokens (doc, dir, util, sig): aliasing them added noise in evals
|
|
127
|
+
_ACR_PHRASES: list[tuple[str, tuple[str, ...]]] = [] # (acronym stem, expansion stems) for multi-word
|
|
128
|
+
_WORD_ALIAS: dict[str, set[str]] = {} # single-word, bidirectional
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _build_alias_tables() -> None:
|
|
132
|
+
for acr, words in ACRONYMS.items():
|
|
133
|
+
a = _stem(acr)
|
|
134
|
+
ws = tuple(_stem(w) for w in words)
|
|
135
|
+
if len(ws) > 1:
|
|
136
|
+
_ACR_PHRASES.append((a, ws))
|
|
137
|
+
else:
|
|
138
|
+
_WORD_ALIAS.setdefault(a, set()).add(ws[0])
|
|
139
|
+
_WORD_ALIAS.setdefault(ws[0], set()).add(a)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def expand_terms(terms: list[str]) -> tuple[dict[str, set[str]], dict[str, set[str]]]:
|
|
143
|
+
"""term -> alternative tokens. Returns (match_alias, count_alias).
|
|
144
|
+
|
|
145
|
+
match_alias widens FTS candidate retrieval (e.g. acronym in query -> its words, which docstrings may spell out).
|
|
146
|
+
count_alias is the strict subset allowed to satisfy the precision gate / coverage: the acronym->words direction is
|
|
147
|
+
excluded because expansion words ('context', 'model') are common and caused false name matches (mcp -> context)."""
|
|
148
|
+
present = set(terms)
|
|
149
|
+
match: dict[str, set[str]] = {}
|
|
150
|
+
count: dict[str, set[str]] = {}
|
|
151
|
+
for t in terms:
|
|
152
|
+
if t in _WORD_ALIAS:
|
|
153
|
+
match.setdefault(t, set()).update(_WORD_ALIAS[t])
|
|
154
|
+
count.setdefault(t, set()).update(_WORD_ALIAS[t])
|
|
155
|
+
for a, ws in _ACR_PHRASES:
|
|
156
|
+
if a in present:
|
|
157
|
+
match.setdefault(a, set()).update(ws)
|
|
158
|
+
if all(w in present for w in ws):
|
|
159
|
+
for w in ws:
|
|
160
|
+
match.setdefault(w, set()).add(a)
|
|
161
|
+
count.setdefault(w, set()).add(a)
|
|
162
|
+
for m in (match, count):
|
|
163
|
+
for t, alts in m.items():
|
|
164
|
+
alts.discard(t)
|
|
165
|
+
return ({t: v for t, v in match.items() if v}, {t: v for t, v in count.items() if v})
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _term_hits(terms: list[str], alias: dict[str, set[str]], tokens: set[str]) -> int:
|
|
169
|
+
return sum(1 for t in terms if t in tokens or (alias.get(t, set()) & tokens))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
_build_alias_tables()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ── symbol model ──────────────────────────────────────────────────────────────
|
|
176
|
+
def _sym(name: str, kind: str, start: int, end: int, sig: str = "", doc: str = "", calls: Iterable[str] = ()) -> dict:
|
|
177
|
+
return {"name": name, "kind": kind, "start": start, "end": max(start, end), "sig": sig[:200],
|
|
178
|
+
"doc": (doc or "").strip().split("\n")[0][:160], "calls": list(calls)[:12]}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _call_names(node: ast.AST) -> list[str]:
|
|
182
|
+
seen: dict[str, None] = {}
|
|
183
|
+
for n in ast.walk(node):
|
|
184
|
+
if isinstance(n, ast.Call):
|
|
185
|
+
f = n.func
|
|
186
|
+
nm = f.id if isinstance(f, ast.Name) else f.attr if isinstance(f, ast.Attribute) else None
|
|
187
|
+
if nm and nm not in seen:
|
|
188
|
+
seen[nm] = None
|
|
189
|
+
return list(seen)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _py_sig(node: ast.AST) -> str:
|
|
193
|
+
if isinstance(node, ast.ClassDef):
|
|
194
|
+
bases = ", ".join(ast.unparse(b) for b in node.bases)
|
|
195
|
+
fields = [s.target.id for s in node.body if isinstance(s, ast.AnnAssign) and isinstance(s.target, ast.Name)]
|
|
196
|
+
extra = f" fields: {', '.join(fields[:12])}" if fields else ""
|
|
197
|
+
return f"class {node.name}({bases}){extra}"
|
|
198
|
+
prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def"
|
|
199
|
+
ret = f" -> {ast.unparse(node.returns)}" if node.returns is not None else ""
|
|
200
|
+
return f"{prefix} {node.name}({ast.unparse(node.args)}){ret}"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _py_start(node: Any) -> int:
|
|
204
|
+
return min([node.lineno] + [d.lineno for d in getattr(node, "decorator_list", [])])
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _parse_python(src: str) -> tuple[list[dict], list[str]]:
|
|
208
|
+
try:
|
|
209
|
+
tree = ast.parse(src)
|
|
210
|
+
except (SyntaxError, ValueError):
|
|
211
|
+
return _parse_python_regex(src), []
|
|
212
|
+
syms: list[dict] = []
|
|
213
|
+
imports: list[str] = []
|
|
214
|
+
|
|
215
|
+
def visit(body: list[ast.stmt], prefix: str, in_class: bool) -> None:
|
|
216
|
+
for node in body:
|
|
217
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
218
|
+
syms.append(_sym(prefix + node.name, "method" if in_class else "function", _py_start(node),
|
|
219
|
+
node.end_lineno or node.lineno, _py_sig(node), ast.get_docstring(node) or "",
|
|
220
|
+
_call_names(node)))
|
|
221
|
+
elif isinstance(node, ast.ClassDef):
|
|
222
|
+
syms.append(_sym(prefix + node.name, "class", _py_start(node), node.end_lineno or node.lineno,
|
|
223
|
+
_py_sig(node), ast.get_docstring(node) or ""))
|
|
224
|
+
visit(node.body, f"{prefix}{node.name}.", True)
|
|
225
|
+
elif not in_class and isinstance(node, (ast.Assign, ast.AnnAssign)):
|
|
226
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
227
|
+
for t in targets:
|
|
228
|
+
if isinstance(t, ast.Name) and t.id.isupper() and len(t.id) > 1:
|
|
229
|
+
syms.append(_sym(t.id, "constant", node.lineno, node.end_lineno or node.lineno,
|
|
230
|
+
f"{t.id} = ..."))
|
|
231
|
+
elif not in_class and isinstance(node, ast.Import):
|
|
232
|
+
imports.extend(a.name.split(".")[0] for a in node.names)
|
|
233
|
+
elif not in_class and isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
|
|
234
|
+
imports.append(node.module.split(".")[0])
|
|
235
|
+
|
|
236
|
+
visit(tree.body, "", False)
|
|
237
|
+
return syms, sorted(set(imports))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _parse_python_regex(src: str) -> list[dict]:
|
|
241
|
+
lines = src.split("\n")
|
|
242
|
+
syms = []
|
|
243
|
+
pat = re.compile(r"^(\s*)(async\s+def|def|class)\s+(\w+)")
|
|
244
|
+
for i, line in enumerate(lines, 1):
|
|
245
|
+
m = pat.match(line)
|
|
246
|
+
if not m:
|
|
247
|
+
continue
|
|
248
|
+
indent = len(m.group(1))
|
|
249
|
+
end = i
|
|
250
|
+
for j in range(i, len(lines)):
|
|
251
|
+
nxt = lines[j]
|
|
252
|
+
if j > i - 1 and nxt.strip() and (len(nxt) - len(nxt.lstrip())) <= indent and j >= i:
|
|
253
|
+
end = j
|
|
254
|
+
break
|
|
255
|
+
end = j + 1
|
|
256
|
+
syms.append(_sym(m.group(3), "class" if m.group(2) == "class" else "function", i, end, line.strip()))
|
|
257
|
+
return syms
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
_TS_DECL = re.compile(
|
|
261
|
+
r"^\s*(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?"
|
|
262
|
+
r"(?P<kind>class|interface|enum|type|namespace)\s+(?P<name>\w+)")
|
|
263
|
+
_TS_FUNC = re.compile(r"^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\*?\s*(?P<name>\w+)\s*[(<]")
|
|
264
|
+
_TS_ARROW = re.compile(
|
|
265
|
+
r"^(?:export\s+)?(?:const|let)\s+(?P<name>\w+)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*(?::[^=]+?)?=>")
|
|
266
|
+
_MODS = r"(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set)\s+)*"
|
|
267
|
+
_TS_MEMBER = re.compile(r"^\s*" + _MODS + r"(?P<name>[A-Za-z_$][\w$]*)\s*(?:<[^>(]*>)?\s*\(")
|
|
268
|
+
_TS_PROP_FN = re.compile(
|
|
269
|
+
r"^\s*" + _MODS + r"(?P<name>[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?"
|
|
270
|
+
r"(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^=]+?)?=>")
|
|
271
|
+
_TS_TEST = re.compile(r"^\s*(?P<fn>test|it|describe|suite)(?:\.(?:describe|only|skip|serial|parallel|fixme|slow))*\s*\(\s*['\"`]")
|
|
272
|
+
_TS_TEST_TITLE = re.compile(r"""^\s*(?:test|it|describe|suite)(?:\.\w+)*\s*\(\s*(?P<q>['"`])(?P<title>.*?)(?P=q)""")
|
|
273
|
+
_TS_KEYWORDS = frozenset(
|
|
274
|
+
"if for while switch catch return function else do try new await super typeof delete throw import require "
|
|
275
|
+
"with yield".split())
|
|
276
|
+
_TS_CALL_STOP = _TS_KEYWORDS | frozenset(
|
|
277
|
+
"push map filter join then log error warn info from keys values entries resolve reject some find includes split "
|
|
278
|
+
"slice trim replace expect async Promise String Number Boolean Object Array Error JSON parse stringify forEach "
|
|
279
|
+
"reduce get set has add delete test describe it".split())
|
|
280
|
+
_TS_IMPORT = re.compile(r"""(?:from\s+|require\()\s*['"]([^'"]+)['"]""")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _mask_ts(src: str) -> str:
|
|
284
|
+
"""Blank out string/template/comment/regex contents (keeping newlines, braces of real code and quote delimiters)
|
|
285
|
+
so brace/paren counting and structural regexes can't be fooled by literals. Output has the same length."""
|
|
286
|
+
out: list[str] = []
|
|
287
|
+
i, n = 0, len(src)
|
|
288
|
+
tpl: list[int] = [] # brace depth per active `${ ... }` expression inside template literals
|
|
289
|
+
mode = "code" # code | sq | dq | tpl | line | block | regex
|
|
290
|
+
prev = "" # last significant code char (regex-vs-division heuristic)
|
|
291
|
+
in_class = False # inside [...] of a regex literal
|
|
292
|
+
|
|
293
|
+
def blank(c: str) -> str:
|
|
294
|
+
return c if c == "\n" else " "
|
|
295
|
+
|
|
296
|
+
while i < n:
|
|
297
|
+
c = src[i]
|
|
298
|
+
nxt = src[i + 1] if i + 1 < n else ""
|
|
299
|
+
vis = not tpl # delimiters stay visible only for top-level literals
|
|
300
|
+
if mode == "code":
|
|
301
|
+
if c in "'\"":
|
|
302
|
+
mode = "sq" if c == "'" else "dq"
|
|
303
|
+
out.append(c if vis else " ")
|
|
304
|
+
elif c == "`":
|
|
305
|
+
mode = "tpl"
|
|
306
|
+
out.append(c if vis else " ")
|
|
307
|
+
elif c == "/" and nxt == "/":
|
|
308
|
+
mode = "line"
|
|
309
|
+
out.append(" ")
|
|
310
|
+
i += 1
|
|
311
|
+
elif c == "/" and nxt == "*":
|
|
312
|
+
mode = "block"
|
|
313
|
+
out.append(" ")
|
|
314
|
+
i += 1
|
|
315
|
+
elif c == "/" and (prev == "" or prev in "(,=:[!&|?{};"):
|
|
316
|
+
mode, in_class = "regex", False
|
|
317
|
+
out.append(c if vis else " ")
|
|
318
|
+
elif tpl:
|
|
319
|
+
if c == "{":
|
|
320
|
+
tpl[-1] += 1
|
|
321
|
+
elif c == "}":
|
|
322
|
+
if tpl[-1] == 0:
|
|
323
|
+
tpl.pop()
|
|
324
|
+
mode = "tpl"
|
|
325
|
+
else:
|
|
326
|
+
tpl[-1] -= 1
|
|
327
|
+
out.append(blank(c))
|
|
328
|
+
else:
|
|
329
|
+
out.append(c)
|
|
330
|
+
if not c.isspace():
|
|
331
|
+
prev = c
|
|
332
|
+
elif mode in ("sq", "dq"):
|
|
333
|
+
q = "'" if mode == "sq" else '"'
|
|
334
|
+
if c == "\\":
|
|
335
|
+
out.append(blank(c) + (blank(nxt) if nxt else ""))
|
|
336
|
+
i += 1
|
|
337
|
+
elif c == q:
|
|
338
|
+
mode, prev = "code", "a"
|
|
339
|
+
out.append(c if vis else " ")
|
|
340
|
+
elif c == "\n":
|
|
341
|
+
mode = "code"
|
|
342
|
+
out.append("\n")
|
|
343
|
+
else:
|
|
344
|
+
out.append(" ")
|
|
345
|
+
elif mode == "tpl":
|
|
346
|
+
if c == "\\":
|
|
347
|
+
out.append(blank(c) + (blank(nxt) if nxt else ""))
|
|
348
|
+
i += 1
|
|
349
|
+
elif c == "`":
|
|
350
|
+
mode, prev = "code", "a"
|
|
351
|
+
out.append(c if vis else " ")
|
|
352
|
+
elif c == "$" and nxt == "{":
|
|
353
|
+
tpl.append(0)
|
|
354
|
+
mode = "code"
|
|
355
|
+
out.append(" ")
|
|
356
|
+
i += 1
|
|
357
|
+
else:
|
|
358
|
+
out.append(blank(c))
|
|
359
|
+
elif mode == "line":
|
|
360
|
+
if c == "\n":
|
|
361
|
+
mode = "code"
|
|
362
|
+
out.append(blank(c))
|
|
363
|
+
elif mode == "block":
|
|
364
|
+
if c == "*" and nxt == "/":
|
|
365
|
+
mode = "code"
|
|
366
|
+
out.append(" ")
|
|
367
|
+
i += 1
|
|
368
|
+
else:
|
|
369
|
+
out.append(blank(c))
|
|
370
|
+
else: # regex literal
|
|
371
|
+
if c == "\\":
|
|
372
|
+
out.append(blank(c) + (blank(nxt) if nxt else ""))
|
|
373
|
+
i += 1
|
|
374
|
+
elif c == "\n":
|
|
375
|
+
mode = "code"
|
|
376
|
+
out.append("\n")
|
|
377
|
+
elif c == "[":
|
|
378
|
+
in_class = True
|
|
379
|
+
out.append(" ")
|
|
380
|
+
elif c == "]":
|
|
381
|
+
in_class = False
|
|
382
|
+
out.append(" ")
|
|
383
|
+
elif c == "/" and not in_class:
|
|
384
|
+
mode, prev = "code", "a"
|
|
385
|
+
out.append(c if vis else " ")
|
|
386
|
+
else:
|
|
387
|
+
out.append(" ")
|
|
388
|
+
i += 1
|
|
389
|
+
return "".join(out)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _depths(masked: list[str]) -> tuple[list[int], list[int], list[int]]:
|
|
393
|
+
"""Per line: brace depth before/after the line, and paren+bracket depth before the line."""
|
|
394
|
+
before, after, pbefore = [], [], []
|
|
395
|
+
d = p = 0
|
|
396
|
+
for ln in masked:
|
|
397
|
+
before.append(d)
|
|
398
|
+
pbefore.append(p)
|
|
399
|
+
d += ln.count("{") - ln.count("}")
|
|
400
|
+
p += ln.count("(") + ln.count("[") - ln.count(")") - ln.count("]")
|
|
401
|
+
after.append(d)
|
|
402
|
+
return before, after, pbefore
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _span_end(masked: list[str], before: list[int], after: list[int], i: int) -> int:
|
|
406
|
+
"""0-based index of the line where the construct starting at line i closes (depth returns to its start level)."""
|
|
407
|
+
base = before[i]
|
|
408
|
+
scan_from = i + 1
|
|
409
|
+
if after[i] <= base: # no opening brace here: maybe Allman style (`{` on the next line)
|
|
410
|
+
j = i + 1
|
|
411
|
+
while j < len(masked) and not masked[j].strip():
|
|
412
|
+
j += 1
|
|
413
|
+
if j < len(masked) and masked[j].lstrip().startswith("{") and ";" not in masked[i]:
|
|
414
|
+
scan_from = j + 1
|
|
415
|
+
else:
|
|
416
|
+
return i
|
|
417
|
+
for k in range(scan_from, min(len(masked), i + 4000)):
|
|
418
|
+
if after[k] <= base:
|
|
419
|
+
return k
|
|
420
|
+
return i
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _ts_calls(masked: list[str], start: int, end: int) -> list[str]:
|
|
424
|
+
text = "\n".join(masked[start:min(end + 1, start + 400)])
|
|
425
|
+
names = re.findall(r"(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(", text) + re.findall(r"\.([A-Za-z_$][\w$]*)\s*\(", text)
|
|
426
|
+
return [n for n in dict.fromkeys(names) if len(n) >= 3 and n not in _TS_CALL_STOP][:12]
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _ts_doc(lines: list[str], idx: int) -> str:
|
|
430
|
+
j = idx - 1
|
|
431
|
+
if j >= 0 and lines[j].strip().endswith("*/"):
|
|
432
|
+
while j >= 0 and "/**" not in lines[j]:
|
|
433
|
+
j -= 1
|
|
434
|
+
for k in range(max(j, 0), idx):
|
|
435
|
+
t = lines[k].strip().lstrip("/*").strip().rstrip("*/").strip()
|
|
436
|
+
if t and not t.startswith("@"):
|
|
437
|
+
return t
|
|
438
|
+
elif j >= 0 and lines[j].strip().startswith("//"):
|
|
439
|
+
return lines[j].strip().lstrip("/").strip()
|
|
440
|
+
return ""
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _parse_ts(src: str) -> tuple[list[dict], list[str]]:
|
|
444
|
+
lines = src.split("\n")
|
|
445
|
+
masked = _mask_ts(src).split("\n")
|
|
446
|
+
before, after, pbefore = _depths(masked)
|
|
447
|
+
imports = sorted(set(_TS_IMPORT.findall(src)))
|
|
448
|
+
syms: list[dict] = []
|
|
449
|
+
classes: list[tuple[str, int, int]] = []
|
|
450
|
+
suites: list[tuple[str, int, int]] = []
|
|
451
|
+
|
|
452
|
+
def add(name: str, kind: str, i: int, end: int, sig: str) -> None:
|
|
453
|
+
syms.append(_sym(name, kind, i + 1, end + 1, sig, _ts_doc(lines, i), _ts_calls(masked, i, end)))
|
|
454
|
+
|
|
455
|
+
for i, line in enumerate(masked):
|
|
456
|
+
top = before[i] == 0 and pbefore[i] == 0
|
|
457
|
+
m = _TS_DECL.match(line)
|
|
458
|
+
if m:
|
|
459
|
+
kind, name = m.group("kind"), m.group("name")
|
|
460
|
+
end = _span_end(masked, before, after, i)
|
|
461
|
+
add(name, kind, i, end, lines[i].strip().rstrip("{").strip())
|
|
462
|
+
if kind == "class":
|
|
463
|
+
classes.append((name, i, end))
|
|
464
|
+
continue
|
|
465
|
+
if top and (m := (_TS_FUNC.match(line) or _TS_ARROW.match(line))):
|
|
466
|
+
add(m.group("name"), "function", i, _span_end(masked, before, after, i), lines[i].strip().rstrip("{").strip())
|
|
467
|
+
continue
|
|
468
|
+
if _TS_TEST.match(line) and (t := _TS_TEST_TITLE.match(lines[i])):
|
|
469
|
+
fn, title = _TS_TEST.match(line).group("fn"), t.group("title").strip()
|
|
470
|
+
end = _span_end(masked, before, after, i)
|
|
471
|
+
owner = next((s for s in reversed(suites) if s[1] < i <= s[2]), None)
|
|
472
|
+
is_suite = fn in ("describe", "suite") or ".describe" in line[:line.index("(")] # test.describe(...)
|
|
473
|
+
name = f"{owner[0]} > {title}" if owner else title
|
|
474
|
+
add(name, "suite" if is_suite else "test", i, end, f"{fn}('{title}')")
|
|
475
|
+
if is_suite:
|
|
476
|
+
suites.append((name, i, end))
|
|
477
|
+
for cname, cs, ce in classes:
|
|
478
|
+
for idx in range(cs + 1, ce + 1):
|
|
479
|
+
if before[idx] != before[cs] + 1 or pbefore[idx] != pbefore[cs]:
|
|
480
|
+
continue # only direct class members, never statements nested in method bodies
|
|
481
|
+
m = _TS_MEMBER.match(masked[idx]) or _TS_PROP_FN.match(masked[idx])
|
|
482
|
+
if not m or m.group("name") in _TS_KEYWORDS:
|
|
483
|
+
continue
|
|
484
|
+
add(f"{cname}.{m.group('name')}", "method", idx, _span_end(masked, before, after, idx),
|
|
485
|
+
lines[idx].strip().rstrip("{").strip())
|
|
486
|
+
return syms, imports
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _parse_markdown(src: str) -> tuple[list[dict], list[str]]:
|
|
490
|
+
lines = src.split("\n")
|
|
491
|
+
heads: list[tuple[int, int, str]] = []
|
|
492
|
+
fence = False
|
|
493
|
+
for i, line in enumerate(lines, 1):
|
|
494
|
+
if line.lstrip().startswith("```"):
|
|
495
|
+
fence = not fence
|
|
496
|
+
elif not fence and (m := re.match(r"^(#{1,6})\s+(.*\S)", line)):
|
|
497
|
+
heads.append((i, len(m.group(1)), m.group(2)))
|
|
498
|
+
syms = []
|
|
499
|
+
for idx, (ln, lvl, title) in enumerate(heads):
|
|
500
|
+
end = len(lines)
|
|
501
|
+
for ln2, lvl2, _ in heads[idx + 1:]:
|
|
502
|
+
if lvl2 <= lvl:
|
|
503
|
+
end = ln2 - 1
|
|
504
|
+
break
|
|
505
|
+
body = next((l.strip() for l in lines[ln:end] if l.strip() and not l.startswith("#")), "")
|
|
506
|
+
syms.append(_sym(title, "section", ln, end, "#" * lvl + " " + title, body))
|
|
507
|
+
return syms, []
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def parse_file(lang: str, src: str) -> tuple[list[dict], list[str]]:
|
|
511
|
+
if lang == "python":
|
|
512
|
+
return _parse_python(src)
|
|
513
|
+
if lang == "ts":
|
|
514
|
+
return _parse_ts(src)
|
|
515
|
+
return _parse_markdown(src)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
# ── file discovery ────────────────────────────────────────────────────────────
|
|
519
|
+
def _git(root: str, *args: str) -> list[str] | None:
|
|
520
|
+
try:
|
|
521
|
+
p = subprocess.run(["git", "-C", root, *args], capture_output=True, text=True, timeout=10)
|
|
522
|
+
except (OSError, subprocess.SubprocessError):
|
|
523
|
+
return None
|
|
524
|
+
return p.stdout.splitlines() if p.returncode == 0 else None
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def iter_repo_files(root: str) -> Iterator[str]:
|
|
528
|
+
"""Yield repo-relative POSIX paths of indexable files (git-tracked + untracked-unignored, else a pruned walk)."""
|
|
529
|
+
listed = _git(root, "ls-files", "--cached", "--others", "--exclude-standard") if os.path.isdir(
|
|
530
|
+
os.path.join(root, ".git")) else None
|
|
531
|
+
if listed is None:
|
|
532
|
+
listed = []
|
|
533
|
+
for dp, dns, fns in os.walk(root):
|
|
534
|
+
dns[:] = [d for d in dns if d not in IGNORE_DIRS]
|
|
535
|
+
for fn in fns:
|
|
536
|
+
listed.append(os.path.relpath(os.path.join(dp, fn), root).replace(os.sep, "/"))
|
|
537
|
+
for rel in listed:
|
|
538
|
+
parts = rel.split("/")
|
|
539
|
+
if any(p in IGNORE_DIRS for p in parts[:-1]) or parts[-1] in IGNORE_FILES:
|
|
540
|
+
continue
|
|
541
|
+
if os.path.splitext(rel)[1].lower() not in LANG_BY_EXT or SECRET_FILE_RE.search(rel):
|
|
542
|
+
continue
|
|
543
|
+
yield rel
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
# ── storage ───────────────────────────────────────────────────────────────────
|
|
547
|
+
def _connect(root: str) -> sqlite3.Connection:
|
|
548
|
+
d = os.path.join(root, INDEX_DIR)
|
|
549
|
+
os.makedirs(d, exist_ok=True)
|
|
550
|
+
gi = os.path.join(d, ".gitignore")
|
|
551
|
+
if not os.path.exists(gi):
|
|
552
|
+
with open(gi, "w") as f:
|
|
553
|
+
f.write("*\n")
|
|
554
|
+
con = sqlite3.connect(os.path.join(d, DB_NAME))
|
|
555
|
+
con.row_factory = sqlite3.Row
|
|
556
|
+
con.executescript(
|
|
557
|
+
"""
|
|
558
|
+
CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT);
|
|
559
|
+
CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, sha1 TEXT, mtime_ns INTEGER, size INTEGER,
|
|
560
|
+
lang TEXT, tokens_raw INTEGER, tokens_skeleton INTEGER, imports TEXT);
|
|
561
|
+
CREATE TABLE IF NOT EXISTS symbols(id INTEGER PRIMARY KEY, path TEXT, name TEXT, kind TEXT,
|
|
562
|
+
start INTEGER, end INTEGER, sig TEXT, doc TEXT, calls TEXT);
|
|
563
|
+
CREATE INDEX IF NOT EXISTS symbols_path ON symbols(path);
|
|
564
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS symbols_fts USING fts5(name, sig, doc, path, calls);
|
|
565
|
+
"""
|
|
566
|
+
)
|
|
567
|
+
row = con.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
|
|
568
|
+
if row and row["v"] != str(SCHEMA_VERSION):
|
|
569
|
+
con.executescript("DELETE FROM files; DELETE FROM symbols; DELETE FROM symbols_fts;")
|
|
570
|
+
con.execute("INSERT OR REPLACE INTO meta VALUES('schema', ?)", (str(SCHEMA_VERSION),))
|
|
571
|
+
return con
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _drop_file(con: sqlite3.Connection, path: str) -> None:
|
|
575
|
+
ids = [r[0] for r in con.execute("SELECT id FROM symbols WHERE path=?", (path,))]
|
|
576
|
+
con.executemany("DELETE FROM symbols_fts WHERE rowid=?", [(i,) for i in ids])
|
|
577
|
+
con.execute("DELETE FROM symbols WHERE path=?", (path,))
|
|
578
|
+
con.execute("DELETE FROM files WHERE path=?", (path,))
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _store_file(con: sqlite3.Connection, rel: str, lang: str, src: str, sha1: str, st: os.stat_result) -> None:
|
|
582
|
+
_drop_file(con, rel)
|
|
583
|
+
syms, imports = parse_file(lang, src)
|
|
584
|
+
skeleton = sum(est_tokens(s["sig"]) + 2 for s in syms)
|
|
585
|
+
con.execute("INSERT INTO files VALUES(?,?,?,?,?,?,?,?)",
|
|
586
|
+
(rel, sha1, st.st_mtime_ns, st.st_size, lang, est_tokens(src), skeleton, json.dumps(imports)))
|
|
587
|
+
path_tokens = " ".join(tokenize(rel.replace("/", " ").replace(".", " ")))
|
|
588
|
+
for s in syms:
|
|
589
|
+
cur = con.execute("INSERT INTO symbols(path,name,kind,start,end,sig,doc,calls) VALUES(?,?,?,?,?,?,?,?)",
|
|
590
|
+
(rel, s["name"], s["kind"], s["start"], s["end"], s["sig"], s["doc"], json.dumps(s["calls"])))
|
|
591
|
+
con.execute("INSERT INTO symbols_fts(rowid,name,sig,doc,path,calls) VALUES(?,?,?,?,?,?)",
|
|
592
|
+
(cur.lastrowid, " ".join(tokenize(s["name"].replace(".", " "))), " ".join(tokenize(s["sig"])),
|
|
593
|
+
" ".join(tokenize(s["doc"])), path_tokens, " ".join(tokenize(" ".join(s["calls"])))))
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def refresh(root: str, con: sqlite3.Connection | None = None) -> dict[str, int]:
|
|
597
|
+
"""Incrementally sync the index with the working tree. Cheap when nothing changed (stat only)."""
|
|
598
|
+
root = os.path.abspath(root)
|
|
599
|
+
own = con is None
|
|
600
|
+
con = con or _connect(root)
|
|
601
|
+
existing = {r["path"]: r for r in con.execute("SELECT path, sha1, mtime_ns, size FROM files")}
|
|
602
|
+
seen: set[str] = set()
|
|
603
|
+
stats = {"scanned": 0, "reparsed": 0, "unchanged": 0, "removed": 0}
|
|
604
|
+
for rel in iter_repo_files(root):
|
|
605
|
+
full = os.path.join(root, rel)
|
|
606
|
+
try:
|
|
607
|
+
st = os.stat(full)
|
|
608
|
+
except OSError:
|
|
609
|
+
continue
|
|
610
|
+
if st.st_size > MAX_FILE_BYTES:
|
|
611
|
+
continue
|
|
612
|
+
seen.add(rel)
|
|
613
|
+
stats["scanned"] += 1
|
|
614
|
+
old = existing.get(rel)
|
|
615
|
+
if old and old["mtime_ns"] == st.st_mtime_ns and old["size"] == st.st_size:
|
|
616
|
+
stats["unchanged"] += 1
|
|
617
|
+
continue
|
|
618
|
+
try:
|
|
619
|
+
raw = open(full, "rb").read()
|
|
620
|
+
except OSError:
|
|
621
|
+
continue
|
|
622
|
+
sha1 = hashlib.sha1(raw).hexdigest()
|
|
623
|
+
if old and old["sha1"] == sha1:
|
|
624
|
+
con.execute("UPDATE files SET mtime_ns=?, size=? WHERE path=?", (st.st_mtime_ns, st.st_size, rel))
|
|
625
|
+
stats["unchanged"] += 1
|
|
626
|
+
continue
|
|
627
|
+
_store_file(con, rel, LANG_BY_EXT[os.path.splitext(rel)[1].lower()], raw.decode("utf-8", "replace"), sha1, st)
|
|
628
|
+
stats["reparsed"] += 1
|
|
629
|
+
for gone in set(existing) - seen:
|
|
630
|
+
_drop_file(con, gone)
|
|
631
|
+
stats["removed"] += 1
|
|
632
|
+
con.commit()
|
|
633
|
+
if own:
|
|
634
|
+
con.close()
|
|
635
|
+
return stats
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
# ── retrieval ─────────────────────────────────────────────────────────────────
|
|
639
|
+
def modified_files(root: str) -> set[str]:
|
|
640
|
+
if not os.path.isdir(os.path.join(root, ".git")):
|
|
641
|
+
return set()
|
|
642
|
+
out: set[str] = set()
|
|
643
|
+
for line in _git(root, "status", "--porcelain") or []:
|
|
644
|
+
if len(line) > 3:
|
|
645
|
+
out.add(line[3:].split(" -> ")[-1].strip().strip('"'))
|
|
646
|
+
return out
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
# ── import / call graph ───────────────────────────────────────────────────────
|
|
651
|
+
def _resolve_deps(con: sqlite3.Connection) -> tuple[dict[str, set[str]], dict[str, int]]:
|
|
652
|
+
"""File-level import graph resolved against indexed files -> (deps: path -> imported paths, in-degree)."""
|
|
653
|
+
files = con.execute("SELECT path, lang, imports FROM files").fetchall()
|
|
654
|
+
paths = {f["path"] for f in files}
|
|
655
|
+
by_base: dict[str, list[str]] = {}
|
|
656
|
+
for p in paths:
|
|
657
|
+
if p.endswith(".py"):
|
|
658
|
+
base = os.path.basename(p)[:-3]
|
|
659
|
+
by_base.setdefault(os.path.basename(os.path.dirname(p)) if base == "__init__" else base, []).append(p)
|
|
660
|
+
deps: dict[str, set[str]] = {}
|
|
661
|
+
indeg: dict[str, int] = {}
|
|
662
|
+
for f in files:
|
|
663
|
+
out: set[str] = set()
|
|
664
|
+
try:
|
|
665
|
+
imports = json.loads(f["imports"] or "[]")
|
|
666
|
+
except ValueError:
|
|
667
|
+
imports = []
|
|
668
|
+
for spec in imports:
|
|
669
|
+
if f["lang"] == "python":
|
|
670
|
+
cands = by_base.get(spec, [])
|
|
671
|
+
if len(cands) == 1:
|
|
672
|
+
out.add(cands[0])
|
|
673
|
+
elif f["lang"] == "ts" and spec.startswith("."):
|
|
674
|
+
base = os.path.normpath(os.path.join(os.path.dirname(f["path"]), spec)).replace(os.sep, "/")
|
|
675
|
+
for ext in ("", ".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):
|
|
676
|
+
if base + ext in paths:
|
|
677
|
+
out.add(base + ext)
|
|
678
|
+
break
|
|
679
|
+
out.discard(f["path"])
|
|
680
|
+
deps[f["path"]] = out
|
|
681
|
+
for d in out:
|
|
682
|
+
indeg[d] = indeg.get(d, 0) + 1
|
|
683
|
+
return deps, indeg
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def _graph_multipliers(con: sqlite3.Connection, rows: list[sqlite3.Row], wants_tests: bool) -> dict[int, float]:
|
|
687
|
+
"""Per-symbol score multipliers from the call graph, import neighbours and file centrality."""
|
|
688
|
+
if GRAPH_CALLEE_BOOST == 1.0 and IMPORT_NEIGHBOR_BOOST == 1.0 and CENTRALITY_WEIGHT == 0.0:
|
|
689
|
+
return {}
|
|
690
|
+
deps, indeg = _resolve_deps(con)
|
|
691
|
+
mult: dict[int, float] = {r["id"]: 1.0 for r in rows}
|
|
692
|
+
by_simple: dict[str, list[int]] = {}
|
|
693
|
+
for r in rows:
|
|
694
|
+
by_simple.setdefault(r["name"].split(".")[-1], []).append(r["id"])
|
|
695
|
+
row_paths = {r["id"]: r["path"] for r in rows}
|
|
696
|
+
matched_files = set(row_paths.values())
|
|
697
|
+
callee_boosted: set[int] = set()
|
|
698
|
+
for r in rows:
|
|
699
|
+
try:
|
|
700
|
+
calls = json.loads(r["calls"] or "[]")
|
|
701
|
+
except ValueError:
|
|
702
|
+
calls = []
|
|
703
|
+
for c in calls:
|
|
704
|
+
if len(c) < 4:
|
|
705
|
+
continue
|
|
706
|
+
for tid in by_simple.get(c, []):
|
|
707
|
+
if tid != r["id"] and tid not in callee_boosted:
|
|
708
|
+
callee_boosted.add(tid)
|
|
709
|
+
mult[tid] *= GRAPH_CALLEE_BOOST
|
|
710
|
+
imported_by_match = {d for p in matched_files for d in deps.get(p, ()) if d in matched_files}
|
|
711
|
+
for r in rows:
|
|
712
|
+
if not wants_tests and _TEST_PATH_RE.search(r["path"]):
|
|
713
|
+
continue
|
|
714
|
+
if r["path"] in imported_by_match:
|
|
715
|
+
mult[r["id"]] *= IMPORT_NEIGHBOR_BOOST
|
|
716
|
+
mult[r["id"]] *= 1.0 + CENTRALITY_WEIGHT * math.log1p(indeg.get(r["path"], 0))
|
|
717
|
+
return mult
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def search(root: str, query: str, k: int = 5, recency: bool = True, max_per_file: int = MAX_PER_FILE,
|
|
721
|
+
con: sqlite3.Connection | None = None, auto_refresh: bool = True) -> dict[str, Any]:
|
|
722
|
+
"""Rank symbols for a query. Returns {hits, coverage, terms}."""
|
|
723
|
+
root = os.path.abspath(root)
|
|
724
|
+
own = con is None
|
|
725
|
+
con = con or _connect(root)
|
|
726
|
+
if auto_refresh:
|
|
727
|
+
refresh(root, con)
|
|
728
|
+
terms = list(dict.fromkeys(tokenize(query, drop_stop=True)))
|
|
729
|
+
if not terms:
|
|
730
|
+
if own:
|
|
731
|
+
con.close()
|
|
732
|
+
return {"hits": [], "coverage": 0.0, "terms": []}
|
|
733
|
+
match_alias, alias = expand_terms(terms) # `alias` (strict) drives gate/coverage; match_alias only widens retrieval
|
|
734
|
+
match_terms = list(dict.fromkeys(terms + [a for t in terms for a in sorted(match_alias.get(t, ()))]))
|
|
735
|
+
match = " OR ".join(f'"{t}"' for t in match_terms)
|
|
736
|
+
w = ", ".join(str(x) for x in BM25_WEIGHTS)
|
|
737
|
+
rows = con.execute(
|
|
738
|
+
f"SELECT s.*, -bm25(symbols_fts, {w}) AS score, "
|
|
739
|
+
"(symbols_fts.name||' '||symbols_fts.sig||' '||symbols_fts.doc||' '||symbols_fts.path||' '||symbols_fts.calls) "
|
|
740
|
+
"AS fts_text, (symbols_fts.name||' '||symbols_fts.sig||' '||symbols_fts.path) AS strict_text, "
|
|
741
|
+
"symbols_fts.name AS name_text "
|
|
742
|
+
"FROM symbols_fts JOIN symbols s ON s.id=symbols_fts.rowid "
|
|
743
|
+
"WHERE symbols_fts MATCH ? ORDER BY score DESC LIMIT 60", (match,)).fetchall()
|
|
744
|
+
# Intent is judged on prose only: path-like/kebab tokens ("NexusAI-Test-Framework", "src/test/x") must not flip it.
|
|
745
|
+
intent_terms = set(tokenize(re.sub(r"\S*[/\\-]\S*", " ", query), drop_stop=True))
|
|
746
|
+
wants_tests = any(t.startswith("test") or t in ("spec", "pytest", "fixture") for t in intent_terms)
|
|
747
|
+
wants_docs = any(t in _DOC_QUERY_TERMS for t in intent_terms)
|
|
748
|
+
gmult = _graph_multipliers(con, rows, wants_tests)
|
|
749
|
+
mods = modified_files(root) if recency else set()
|
|
750
|
+
ranked = []
|
|
751
|
+
name_hits: dict[int, int] = {}
|
|
752
|
+
for r in rows:
|
|
753
|
+
name_hits[r["id"]] = _term_hits(terms, alias, set(tokenize(r["name_text"])))
|
|
754
|
+
score = r["score"] * (1.0 + NAME_MATCH_BOOST * name_hits[r["id"]]) * (RECENCY_BOOST if r["path"] in mods else 1.0) * gmult.get(r["id"], 1.0)
|
|
755
|
+
if not wants_docs and r["kind"] == "section":
|
|
756
|
+
score *= DOC_PENALTY
|
|
757
|
+
if not wants_tests and _TEST_PATH_RE.search(r["path"]):
|
|
758
|
+
score *= TEST_PENALTY
|
|
759
|
+
ranked.append((score, r))
|
|
760
|
+
ranked.sort(key=lambda t: -t[0])
|
|
761
|
+
|
|
762
|
+
hits: list[dict] = []
|
|
763
|
+
per_file: dict[str, int] = {}
|
|
764
|
+
for score, r in ranked:
|
|
765
|
+
if len(hits) >= k:
|
|
766
|
+
break
|
|
767
|
+
if per_file.get(r["path"], 0) >= max_per_file:
|
|
768
|
+
continue
|
|
769
|
+
if any(h["path"] == r["path"] and h["start"] <= r["start"] and r["end"] <= h["end"] for h in hits):
|
|
770
|
+
continue # nested inside an already-selected span
|
|
771
|
+
per_file[r["path"]] = per_file.get(r["path"], 0) + 1
|
|
772
|
+
hits.append({"path": r["path"], "name": r["name"], "kind": r["kind"], "start": r["start"], "end": r["end"],
|
|
773
|
+
"sig": r["sig"], "score": round(score, 4), "modified": r["path"] in mods,
|
|
774
|
+
"matched": name_hits[r["id"]], # precision gate: NAME tokens only
|
|
775
|
+
"matched_any": _term_hits(terms, alias, set(tokenize(r["strict_text"]))), # name+signature+path
|
|
776
|
+
"eligible": (wants_tests or not _TEST_PATH_RE.search(r["path"])) and (wants_docs or r["kind"] != "section"),
|
|
777
|
+
"_tokens": set(tokenize(r["fts_text"]))})
|
|
778
|
+
top_tokens: set[str] = set()
|
|
779
|
+
for h in hits[:3]:
|
|
780
|
+
top_tokens |= h["_tokens"]
|
|
781
|
+
coverage = _term_hits(terms, alias, top_tokens) / len(terms)
|
|
782
|
+
for h in hits:
|
|
783
|
+
h.pop("_tokens", None)
|
|
784
|
+
# Precision gate inputs: how many DISTINCT query terms the best non-test hit matches in its NAME
|
|
785
|
+
# (signature/path matches are too weak: every symbol in repo_indexer.py matches "repo")
|
|
786
|
+
strong = max((h["matched"] for h in hits if h["eligible"]), default=0)
|
|
787
|
+
needed = 1 if len(terms) == 1 else 2
|
|
788
|
+
idents = [w.lower().strip(".") for w in re.findall(r"[A-Za-z_][\w.]*", query)
|
|
789
|
+
if "_" in w or re.search(r"[a-z][A-Z]", w) or "." in w.strip(".")]
|
|
790
|
+
ident_hit = any(h["eligible"] and (i == h["name"].lower() or i in h["name"].lower().split(".")
|
|
791
|
+
or i == os.path.basename(h["path"]).lower())
|
|
792
|
+
for h in hits for i in idents)
|
|
793
|
+
if own:
|
|
794
|
+
con.close()
|
|
795
|
+
return {"hits": hits, "coverage": round(coverage, 3), "terms": terms, "strong": strong, "needed": needed,
|
|
796
|
+
"ident_hit": ident_hit}
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
# ── slices & capsule ──────────────────────────────────────────────────────────
|
|
800
|
+
_SECRET_PATTERNS = [
|
|
801
|
+
re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S),
|
|
802
|
+
re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
|
|
803
|
+
re.compile(r"\bgh[pousr]_[A-Za-z0-9]{30,}\b"),
|
|
804
|
+
re.compile(r"\bsk-[A-Za-z0-9_\-]{20,}\b"),
|
|
805
|
+
re.compile(r"\bxox[baprs]-[A-Za-z0-9\-]{10,}\b"),
|
|
806
|
+
re.compile(r"\beyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b"),
|
|
807
|
+
re.compile(r"""(?i)\b((?:api[_-]?key|secret|token|passw(?:or)?d)\w*\s*[:=]\s*)(['"])[^'"\n]{8,}\2"""),
|
|
808
|
+
]
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def redact_secrets(text: str) -> str:
|
|
812
|
+
for i, pat in enumerate(_SECRET_PATTERNS):
|
|
813
|
+
text = pat.sub((lambda m: m.group(1) + m.group(2) + "[REDACTED]" + m.group(2)) if i == 6 else "[REDACTED]", text)
|
|
814
|
+
return text
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def safe_path(root: str, rel: str) -> str:
|
|
818
|
+
"""Resolve `rel` under `root`; raise ValueError on traversal/absolute escape or secret files."""
|
|
819
|
+
root_real = os.path.realpath(root)
|
|
820
|
+
full = os.path.realpath(os.path.join(root_real, rel))
|
|
821
|
+
if full != root_real and not full.startswith(root_real + os.sep):
|
|
822
|
+
raise ValueError(f"path escapes workspace root: {rel!r}")
|
|
823
|
+
if SECRET_FILE_RE.search(rel.replace(os.sep, "/")):
|
|
824
|
+
raise ValueError(f"refusing to read secret-like file: {rel!r}")
|
|
825
|
+
return full
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def get_slice(root: str, path: str, start: int, end: int, context: int = 0, redact: bool = True) -> dict[str, Any]:
|
|
829
|
+
full = safe_path(root, path)
|
|
830
|
+
with open(full, encoding="utf-8", errors="replace") as f:
|
|
831
|
+
lines = f.read().split("\n")
|
|
832
|
+
s, e = max(1, start - context), min(len(lines), end + context)
|
|
833
|
+
body = "\n".join(f"{n}| {lines[n - 1]}" for n in range(s, e + 1))
|
|
834
|
+
return {"path": path, "start": s, "end": e, "text": redact_secrets(body) if redact else body}
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _escape_tag(text: str) -> str:
|
|
838
|
+
return text.replace("</retrieved_context", "<\\/retrieved_context")
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def build_capsule(root: str, query: str, token_budget: int = 450, k: int = 5, body_k: int = 3,
|
|
842
|
+
max_body_lines: int = 60, min_confidence: float = MIN_CONFIDENCE,
|
|
843
|
+
exclude: Iterable[tuple[str, str]] = ()) -> dict[str, Any]:
|
|
844
|
+
"""Compile a budgeted <retrieved_context> capsule. Empty (with reason) when confidence is too low.
|
|
845
|
+
`exclude` = (path, name) pairs already delivered this session (session ledger dedupe)."""
|
|
846
|
+
res = search(root, query, k=k + len(list(exclude)))
|
|
847
|
+
skip = set(exclude)
|
|
848
|
+
hits = [h for h in res["hits"] if (h["path"], h["name"]) not in skip][:k]
|
|
849
|
+
if not hits:
|
|
850
|
+
return {"capsule": "", "tokens": 0, "confidence": 0.0, "hits": [], "reason": "no_match"}
|
|
851
|
+
# Gate (all must hold): (a) >=2 distinct query terms hit one non-test symbol's NAME,
|
|
852
|
+
# or the prompt names an exact identifier; (b) overall coverage of the top hits clears min_confidence.
|
|
853
|
+
if not (res["ident_hit"] or res["strong"] >= res["needed"]) or res["coverage"] < min_confidence:
|
|
854
|
+
return {"capsule": "", "tokens": 0, "confidence": res["coverage"], "hits": hits, "reason": "low_confidence"}
|
|
855
|
+
hits = [h for h in hits if h["matched_any"] >= 1] # drop zero-match noise from the symbol list
|
|
856
|
+
if not hits:
|
|
857
|
+
return {"capsule": "", "tokens": 0, "confidence": res["coverage"], "hits": [], "reason": "no_match"}
|
|
858
|
+
|
|
859
|
+
head = (f'<retrieved_context source="nlp-smarty" confidence="{res["coverage"]}" '
|
|
860
|
+
'note="lexical retrieval; may be incomplete - verify with grep if unsure">')
|
|
861
|
+
parts = [head, "symbols:"]
|
|
862
|
+
for h in hits:
|
|
863
|
+
parts.append(f"- {h['path']}:L{h['start']}-{h['end']} {h['kind']} {h['sig'] or h['name']}")
|
|
864
|
+
used = est_tokens("\n".join(parts)) + 8
|
|
865
|
+
delivered = []
|
|
866
|
+
# bodies: code before docs (stable sort keeps score order within each group)
|
|
867
|
+
for h in sorted(hits, key=lambda x: x["kind"] == "section")[:body_k]:
|
|
868
|
+
remaining = token_budget - used
|
|
869
|
+
if remaining < 40:
|
|
870
|
+
break
|
|
871
|
+
sl = get_slice(root, h["path"], h["start"], min(h["end"], h["start"] + max_body_lines - 1))
|
|
872
|
+
text = _escape_tag(sl["text"])
|
|
873
|
+
lines = text.split("\n")
|
|
874
|
+
keep: list[str] = []
|
|
875
|
+
cost = est_tokens(f"[{h['path']}:L{h['start']}-{h['end']}]")
|
|
876
|
+
for ln in lines:
|
|
877
|
+
c = est_tokens(ln) + 1
|
|
878
|
+
if cost + c > remaining:
|
|
879
|
+
break
|
|
880
|
+
keep.append(ln)
|
|
881
|
+
cost += c
|
|
882
|
+
if not keep:
|
|
883
|
+
break
|
|
884
|
+
if len(keep) < (h["end"] - h["start"] + 1):
|
|
885
|
+
keep.append(f"... (truncated; full span L{h['start']}-{h['end']})")
|
|
886
|
+
block = f"[{h['path']}:L{h['start']}-{h['end']}]\n" + "\n".join(keep)
|
|
887
|
+
parts.append(block)
|
|
888
|
+
used += cost
|
|
889
|
+
delivered.append((h["path"], h["name"]))
|
|
890
|
+
parts.append("</retrieved_context>")
|
|
891
|
+
capsule = "\n".join(parts)
|
|
892
|
+
return {"capsule": capsule, "tokens": est_tokens(capsule), "confidence": res["coverage"], "hits": hits,
|
|
893
|
+
"delivered": delivered, "reason": "ok"}
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def find_symbol(root: str, name: str, limit: int = 10, con: sqlite3.Connection | None = None) -> list[dict]:
|
|
897
|
+
"""Exact (case-insensitive) then prefix/suffix match on symbol name, e.g. 'optimize' or 'PromptCache.lookup'."""
|
|
898
|
+
root = os.path.abspath(root)
|
|
899
|
+
own = con is None
|
|
900
|
+
con = con or _connect(root)
|
|
901
|
+
refresh(root, con)
|
|
902
|
+
n = name.strip()
|
|
903
|
+
rows = con.execute(
|
|
904
|
+
"SELECT path,name,kind,start,end,sig FROM symbols WHERE lower(name)=lower(?) "
|
|
905
|
+
"OR lower(name) LIKE lower(?) ESCAPE '\\' OR lower(name) LIKE lower(?) ESCAPE '\\' "
|
|
906
|
+
"ORDER BY (lower(name)=lower(?)) DESC, length(name), path LIMIT ?",
|
|
907
|
+
(n, n.replace("%", r"\%").replace("_", r"\_") + "%", "%." + n.replace("%", r"\%").replace("_", r"\_"), n, limit),
|
|
908
|
+
).fetchall()
|
|
909
|
+
out = [dict(r) for r in rows]
|
|
910
|
+
if own:
|
|
911
|
+
con.close()
|
|
912
|
+
return out
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
MAX_SCAN_FILES = 5000
|
|
916
|
+
_IDENT_RE = re.compile(r"[A-Za-z_$][\w$]*")
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def find_references(root: str, name: str, limit: int = 40, token_budget: int = 700, include_tests: bool = True,
|
|
920
|
+
con: sqlite3.Connection | None = None) -> dict[str, Any]:
|
|
921
|
+
"""Where is `name` used? Definitions first, then callers (call-graph), then other whole-word mentions as file:line
|
|
922
|
+
snippets (code before tests before docs), all within a token budget. A grep replacement that is ranked, deduped and
|
|
923
|
+
bounded. `name` may be dotted ('BasePage.click'); mentions are matched on the last part, definitions on the full name."""
|
|
924
|
+
root = os.path.abspath(root)
|
|
925
|
+
parts = name.strip().split(".")
|
|
926
|
+
simple = parts[-1]
|
|
927
|
+
if not _IDENT_RE.fullmatch(simple) or not all(_IDENT_RE.fullmatch(x) for x in parts):
|
|
928
|
+
raise ValueError("name must be an identifier such as 'click' or 'BasePage.click'")
|
|
929
|
+
own = con is None
|
|
930
|
+
con = con or _connect(root)
|
|
931
|
+
refresh(root, con)
|
|
932
|
+
dotted = len(parts) > 1
|
|
933
|
+
defs = [dict(r) for r in con.execute(
|
|
934
|
+
"SELECT path,name,kind,start,end,sig FROM symbols WHERE name=? OR (? = 0 AND name LIKE ? ESCAPE '\\') "
|
|
935
|
+
"ORDER BY path,start", (name.strip(), int(dotted), "%." + simple.replace("_", r"\_")))]
|
|
936
|
+
def_ids = {(d["path"], d["start"]) for d in defs}
|
|
937
|
+
pat = re.compile(r"(?<![\w$])" + re.escape(simple) + r"(?![\w$])")
|
|
938
|
+
paths = [r["path"] for r in con.execute("SELECT path FROM files ORDER BY path")][:MAX_SCAN_FILES]
|
|
939
|
+
|
|
940
|
+
def bucket(path: str) -> int:
|
|
941
|
+
if path.lower().endswith(".md"):
|
|
942
|
+
return 2
|
|
943
|
+
return 1 if _TEST_PATH_RE.search(path) else 0
|
|
944
|
+
call_pat = re.compile(r"(?<![\w$])" + re.escape(simple) + r"\s*\(")
|
|
945
|
+
quoted_pat = re.compile(r"""['"`]""" + re.escape(simple) + r"""['"`]""")
|
|
946
|
+
|
|
947
|
+
def form(line: str) -> int:
|
|
948
|
+
"""0 call site, 1 other code, 2 string literal, 3 comment: real usages first."""
|
|
949
|
+
if re.match(r"\s*(//|/\*|\*|#)", line):
|
|
950
|
+
return 3
|
|
951
|
+
if call_pat.search(line):
|
|
952
|
+
return 0
|
|
953
|
+
return 2 if quoted_pat.search(line) else 1
|
|
954
|
+
cls_pat = re.compile(r"(?<![\w$])" + re.escape(parts[-2]) + r"(?![\w$])") if dotted else None
|
|
955
|
+
knows: dict[str, bool] = {} # for 'Class.method': files that mention Class are far likelier to be real usages
|
|
956
|
+
mentions: list[tuple[int, str, int, str, int]] = []
|
|
957
|
+
for path in paths:
|
|
958
|
+
if not include_tests and _TEST_PATH_RE.search(path):
|
|
959
|
+
continue
|
|
960
|
+
try:
|
|
961
|
+
with open(os.path.join(root, path), encoding="utf-8", errors="replace") as f:
|
|
962
|
+
text = f.read()
|
|
963
|
+
except OSError:
|
|
964
|
+
continue
|
|
965
|
+
if not pat.search(text):
|
|
966
|
+
continue
|
|
967
|
+
knows[path] = bool(cls_pat and cls_pat.search(text))
|
|
968
|
+
for i, line in enumerate(text.split("\n"), 1):
|
|
969
|
+
if (path, i) not in def_ids and pat.search(line):
|
|
970
|
+
mentions.append((bucket(path), path, i, redact_secrets(line.strip())[:140], form(line)))
|
|
971
|
+
best = {} # a file is ranked by its best usage; inside a file the best usages come first
|
|
972
|
+
for b, pth, _, _, f in mentions:
|
|
973
|
+
best[pth] = min(best.get(pth, 9), f)
|
|
974
|
+
mentions.sort(key=lambda m: (m[0], 0 if (not dotted or knows.get(m[1])) else 1, best[m[1]], m[1], m[4], m[2]))
|
|
975
|
+
# Callers = the innermost symbol around each code usage (calls and other code, not strings/comments). Derived from the
|
|
976
|
+
# usage lines rather than the stored call lists, which drop common names (warn/log/error) and over-credit containers.
|
|
977
|
+
spans: dict[str, list] = {}
|
|
978
|
+
for pth in {m[1] for m in mentions}:
|
|
979
|
+
spans[pth] = [dict(r) for r in con.execute("SELECT name,kind,start,end FROM symbols WHERE path=?", (pth,))]
|
|
980
|
+
found: dict[tuple, dict] = {}
|
|
981
|
+
for _, pth, ln, _snip, fm in mentions:
|
|
982
|
+
if fm > 1 or pth.lower().endswith(".md"):
|
|
983
|
+
continue # strings/comments and prose are mentions, not callers
|
|
984
|
+
around = [x for x in spans[pth] if x["start"] <= ln <= x["end"]]
|
|
985
|
+
if not around:
|
|
986
|
+
continue
|
|
987
|
+
inner = min(around, key=lambda x: (x["end"] - x["start"], x["start"]))
|
|
988
|
+
if (pth, inner["start"]) in def_ids:
|
|
989
|
+
continue # the usage is inside the definition itself (e.g. the method delegating to locator.click)
|
|
990
|
+
key = (pth, inner["name"], inner["start"])
|
|
991
|
+
c = found.setdefault(key, {"path": pth, "name": inner["name"], "kind": inner["kind"], "start": inner["start"],
|
|
992
|
+
"end": inner["end"], "lines": 0})
|
|
993
|
+
c["lines"] += 1
|
|
994
|
+
callers = list(found.values())
|
|
995
|
+
if not include_tests:
|
|
996
|
+
callers = [c for c in callers if not _TEST_PATH_RE.search(c["path"])]
|
|
997
|
+
callers.sort(key=lambda c: (bucket(c["path"]), c["path"], c["start"]))
|
|
998
|
+
if own:
|
|
999
|
+
con.close()
|
|
1000
|
+
counts = {"definitions": len(defs), "callers": len(callers), "mentions": len(mentions)}
|
|
1001
|
+
|
|
1002
|
+
out: list[str] = []
|
|
1003
|
+
used = 0
|
|
1004
|
+
|
|
1005
|
+
def emit(line: str) -> bool:
|
|
1006
|
+
nonlocal used
|
|
1007
|
+
c = est_tokens(line) + 1
|
|
1008
|
+
if used + c > token_budget and out:
|
|
1009
|
+
return False
|
|
1010
|
+
out.append(line)
|
|
1011
|
+
used += c
|
|
1012
|
+
return True
|
|
1013
|
+
truncated = False
|
|
1014
|
+
exhausted = False
|
|
1015
|
+
if defs:
|
|
1016
|
+
emit("definitions:")
|
|
1017
|
+
for d in defs:
|
|
1018
|
+
exhausted = exhausted or not emit(f"- {d['path']}:L{d['start']}-{d['end']} {d['kind']} {d['name']}")
|
|
1019
|
+
else:
|
|
1020
|
+
emit(f"definitions: none indexed for '{name}'")
|
|
1021
|
+
MAX_CALLERS = 8 # callers are structure; the line-level mentions below are the substance, so keep callers short
|
|
1022
|
+
if callers and not exhausted:
|
|
1023
|
+
shown_c = callers[:MAX_CALLERS]
|
|
1024
|
+
emit(f"callers (showing {len(shown_c)} of {len(callers)}):" if len(callers) > MAX_CALLERS else f"callers ({len(callers)}):")
|
|
1025
|
+
for c in shown_c:
|
|
1026
|
+
if not emit(f"- {c['path']}:L{c['start']}-{c['end']} {c['name']}"):
|
|
1027
|
+
exhausted = True
|
|
1028
|
+
break
|
|
1029
|
+
truncated |= len(callers) > MAX_CALLERS
|
|
1030
|
+
if mentions and not exhausted:
|
|
1031
|
+
emit(f"mentions ({len(mentions)}):")
|
|
1032
|
+
by_file: dict[str, list] = {}
|
|
1033
|
+
for m in mentions: # already ranked: files by relevance, lines inside a file best-usage first
|
|
1034
|
+
by_file.setdefault(m[1], []).append(m)
|
|
1035
|
+
shown = 0
|
|
1036
|
+
for path, ms in by_file.items():
|
|
1037
|
+
if shown >= limit:
|
|
1038
|
+
break
|
|
1039
|
+
if not emit(f"{path}:"):
|
|
1040
|
+
exhausted = True
|
|
1041
|
+
break
|
|
1042
|
+
# pick the best usages first (<=4 per file so one noisy file can't eat the budget, and never more than the
|
|
1043
|
+
# global limit), THEN show them in line order
|
|
1044
|
+
chosen = sorted(ms[:min(4, limit - shown)], key=lambda m: m[2])
|
|
1045
|
+
for _, _, ln, snippet, _f in chosen:
|
|
1046
|
+
if not emit(f" L{ln}: {snippet}"):
|
|
1047
|
+
exhausted = True
|
|
1048
|
+
break
|
|
1049
|
+
shown += 1
|
|
1050
|
+
if exhausted:
|
|
1051
|
+
break
|
|
1052
|
+
truncated |= shown < len(mentions)
|
|
1053
|
+
truncated |= exhausted
|
|
1054
|
+
if truncated:
|
|
1055
|
+
out.append("... (truncated; narrow the name, set include_tests=false, or use smarty_get_slice)")
|
|
1056
|
+
return {"text": "\n".join(out), "counts": counts, "truncated": truncated, "tokens": est_tokens("\n".join(out)),
|
|
1057
|
+
"definitions": defs, "callers": callers}
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def repo_map(root: str, token_budget: int = 800) -> str:
|
|
1061
|
+
"""Compact file -> top-level symbols map (modified files first). Stops at the token budget."""
|
|
1062
|
+
root = os.path.abspath(root)
|
|
1063
|
+
con = _connect(root)
|
|
1064
|
+
refresh(root, con)
|
|
1065
|
+
mods = modified_files(root)
|
|
1066
|
+
files = con.execute("SELECT path, lang, tokens_raw FROM files").fetchall()
|
|
1067
|
+
top = {}
|
|
1068
|
+
for r in con.execute("SELECT path,name,kind,start,end FROM symbols WHERE kind IN "
|
|
1069
|
+
"('class','function','interface','enum','constant','type','suite') ORDER BY path, start"):
|
|
1070
|
+
top.setdefault(r["path"], []).append(r)
|
|
1071
|
+
con.close()
|
|
1072
|
+
order = sorted((f for f in files if f["lang"] != "markdown"), key=lambda f: (f["path"] not in mods, f["path"]))
|
|
1073
|
+
lines = ["# repo_map (nlp-smarty) - file: symbols L<start>-<end>; * = modified"]
|
|
1074
|
+
used = est_tokens(lines[0])
|
|
1075
|
+
for f in order:
|
|
1076
|
+
syms = top.get(f["path"], [])
|
|
1077
|
+
shown = ", ".join(f"{s['name']} L{s['start']}-{s['end']}" for s in syms[:14])
|
|
1078
|
+
more = f" (+{len(syms) - 14} more)" if len(syms) > 14 else ""
|
|
1079
|
+
line = f"{'*' if f['path'] in mods else ''}{f['path']}: {shown}{more}" if syms else f"{f['path']}"
|
|
1080
|
+
c = est_tokens(line) + 1
|
|
1081
|
+
if used + c > token_budget:
|
|
1082
|
+
lines.append(f"... (map truncated at {token_budget} tokens; use smarty_find_symbol / smarty_get_context)")
|
|
1083
|
+
break
|
|
1084
|
+
lines.append(line)
|
|
1085
|
+
used += c
|
|
1086
|
+
return "\n".join(lines)
|
|
1087
|
+
|
|
1088
|
+
|
|
1089
|
+
def stats(root: str) -> dict[str, Any]:
|
|
1090
|
+
con = _connect(os.path.abspath(root))
|
|
1091
|
+
f = con.execute("SELECT COUNT(*) n, COALESCE(SUM(tokens_raw),0) raw, COALESCE(SUM(tokens_skeleton),0) sk FROM files").fetchone()
|
|
1092
|
+
n_sym = con.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
|
|
1093
|
+
con.close()
|
|
1094
|
+
return {"files": f["n"], "symbols": n_sym, "tokens_raw": f["raw"], "tokens_skeleton": f["sk"],
|
|
1095
|
+
"skeleton_reduction_pct": round(100 * (1 - f["sk"] / f["raw"]), 1) if f["raw"] else 0.0}
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1099
|
+
os.environ.setdefault("SMARTY_LIGHT_TOKENS", "1") # CLI/hook path: skip the heavy BPE estimator for speed + consistency
|
|
1100
|
+
ap = argparse.ArgumentParser(prog="repo_indexer", description=__doc__.split("\n")[1])
|
|
1101
|
+
ap.add_argument("--root", default=".")
|
|
1102
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
1103
|
+
sub.add_parser("index", help="build/refresh the index")
|
|
1104
|
+
sub.add_parser("stats", help="index statistics")
|
|
1105
|
+
q = sub.add_parser("query", help="search and print a capsule")
|
|
1106
|
+
q.add_argument("text")
|
|
1107
|
+
q.add_argument("--budget", type=int, default=450)
|
|
1108
|
+
q.add_argument("--k", type=int, default=5)
|
|
1109
|
+
s = sub.add_parser("slice", help="print a numbered file slice")
|
|
1110
|
+
s.add_argument("path")
|
|
1111
|
+
s.add_argument("start", type=int)
|
|
1112
|
+
s.add_argument("end", type=int)
|
|
1113
|
+
a = ap.parse_args(argv)
|
|
1114
|
+
if a.cmd == "index":
|
|
1115
|
+
print(json.dumps({**refresh(a.root), **stats(a.root)}))
|
|
1116
|
+
elif a.cmd == "stats":
|
|
1117
|
+
print(json.dumps(stats(a.root)))
|
|
1118
|
+
elif a.cmd == "query":
|
|
1119
|
+
out = build_capsule(a.root, a.text, token_budget=a.budget, k=a.k)
|
|
1120
|
+
print(out["capsule"] or f"[no capsule: {out['reason']} confidence={out['confidence']}]")
|
|
1121
|
+
print(f"\n# tokens={out['tokens']} confidence={out['confidence']}", file=sys.stderr)
|
|
1122
|
+
elif a.cmd == "slice":
|
|
1123
|
+
print(get_slice(a.root, a.path, a.start, a.end)["text"])
|
|
1124
|
+
return 0
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
if __name__ == "__main__":
|
|
1128
|
+
sys.exit(main())
|