codehaven 0.14.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.
- codehaven-0.14.0.dist-info/METADATA +686 -0
- codehaven-0.14.0.dist-info/RECORD +57 -0
- codehaven-0.14.0.dist-info/WHEEL +5 -0
- codehaven-0.14.0.dist-info/entry_points.txt +3 -0
- codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
- codehaven-0.14.0.dist-info/top_level.txt +1 -0
- offline_agent/__init__.py +2 -0
- offline_agent/__main__.py +4 -0
- offline_agent/agent.py +815 -0
- offline_agent/answers.py +438 -0
- offline_agent/arabic.py +106 -0
- offline_agent/changes.py +228 -0
- offline_agent/chats.py +121 -0
- offline_agent/cli.py +379 -0
- offline_agent/coder.py +199 -0
- offline_agent/dependencies.py +132 -0
- offline_agent/doctor.py +190 -0
- offline_agent/documents.py +189 -0
- offline_agent/edits.py +204 -0
- offline_agent/errors.py +41 -0
- offline_agent/evaluation.py +284 -0
- offline_agent/evidence.py +187 -0
- offline_agent/exclusions.py +95 -0
- offline_agent/export.py +27 -0
- offline_agent/gui.css +237 -0
- offline_agent/gui.html +177 -0
- offline_agent/gui.js +1213 -0
- offline_agent/gui.py +967 -0
- offline_agent/gui_arabic.js +226 -0
- offline_agent/guides.py +203 -0
- offline_agent/history.py +126 -0
- offline_agent/index_cache.py +78 -0
- offline_agent/insights.py +333 -0
- offline_agent/javascript.py +200 -0
- offline_agent/knowledge.py +569 -0
- offline_agent/languages.py +396 -0
- offline_agent/memory.py +192 -0
- offline_agent/messages.py +51 -0
- offline_agent/model.py +498 -0
- offline_agent/more_languages.py +253 -0
- offline_agent/ocr.py +204 -0
- offline_agent/prompts.py +130 -0
- offline_agent/references/langgraph-approvals.md +38 -0
- offline_agent/references/langgraph-checkpoints.md +37 -0
- offline_agent/references/langgraph-graphs.md +42 -0
- offline_agent/references/langgraph.md +49 -0
- offline_agent/review.py +205 -0
- offline_agent/scans.py +325 -0
- offline_agent/semantic.py +264 -0
- offline_agent/slash.py +53 -0
- offline_agent/study.py +210 -0
- offline_agent/symbols.py +201 -0
- offline_agent/tasks.py +164 -0
- offline_agent/test_runner.py +264 -0
- offline_agent/trace.py +239 -0
- offline_agent/tracebacks.py +98 -0
- offline_agent/workspace.py +419 -0
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
"""Offline, in-memory BM25 retrieval over local reference documents."""
|
|
2
|
+
import functools
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import arabic, index_cache
|
|
12
|
+
from .model import Stopped
|
|
13
|
+
from .workspace import MAX_FILES, Workspace
|
|
14
|
+
from .dependencies import PythonDependencies
|
|
15
|
+
from .javascript import JS_EXTENSIONS, JavaScriptDependencies
|
|
16
|
+
from .languages import OtherDependencies
|
|
17
|
+
from .more_languages import MoreDependencies
|
|
18
|
+
from .exclusions import IgnoreConfigurationError
|
|
19
|
+
|
|
20
|
+
EXTENSIONS = {".md", ".txt", ".rst"}
|
|
21
|
+
CODE_EXTENSIONS = EXTENSIONS | JS_EXTENSIONS | {
|
|
22
|
+
".py", ".pyi", ".js", ".jsx", ".ts", ".tsx", ".java", ".go", ".rs",
|
|
23
|
+
".c", ".h", ".cpp", ".hpp", ".cc", ".cxx", ".hh", ".hxx", ".cs", ".rb", ".php", ".swift", ".kt",
|
|
24
|
+
".kts", ".scala", ".sh", ".bash", ".zsh", ".ps1", ".sql", ".html",
|
|
25
|
+
".css", ".scss", ".vue", ".svelte", ".json", ".yaml", ".yml", ".toml",
|
|
26
|
+
".ini", ".cfg", ".xml", ".graphql", ".gql", ".proto", ".r", ".lua",
|
|
27
|
+
".ex", ".exs", ".erl", ".hs", ".clj", ".dart", ".ipynb",
|
|
28
|
+
}
|
|
29
|
+
MAX_DOCUMENTS = MAX_FILES # The same bound as Workspace.files, so a mid-sized repository is indexed in full.
|
|
30
|
+
# The most passages and bytes of text one index holds. Building the index for a project at these limits takes
|
|
31
|
+
# about a quarter of a minute on a laptop; beyond them the index is reported as limited.
|
|
32
|
+
MAX_PASSAGES = 40_000
|
|
33
|
+
MAX_INDEX_BYTES = 25_000_000
|
|
34
|
+
BUNDLED_TOPICS = {"stategraph", "checkpoint", "checkpoints", "checkpointer", "interrupt", "interrupts"}
|
|
35
|
+
CODE_NAMES = {"Dockerfile", "Makefile", "CMakeLists.txt", "Justfile", "Gemfile"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@functools.lru_cache(maxsize=200_000)
|
|
39
|
+
def stem(word):
|
|
40
|
+
"""Reduce simple English endings, so "restocking" finds restock and "pricing" finds price."""
|
|
41
|
+
if len(word) > 4 and word.isascii():
|
|
42
|
+
word = re.sub(r"(?:ing|ed|es|(?<!s)s)$", "", word)
|
|
43
|
+
word = word[:-1] if len(word) > 3 and word.endswith("e") else word
|
|
44
|
+
elif arabic.WORD.fullmatch(word):
|
|
45
|
+
word = arabic.stem(word)
|
|
46
|
+
return word
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def tokens(text):
|
|
50
|
+
"""Lowercase word stems, split at underscores and camelCase, so applyDiscount and apply_discount match "apply discount"."""
|
|
51
|
+
text = arabic.normalise(text) # Arabic short vowels are not word characters, so they would split a word in two.
|
|
52
|
+
return [stem(word) for word in re.findall(r"[^\W_]+", re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", text).lower(), flags=re.UNICODE)]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def notebook_text(text):
|
|
56
|
+
"""A Jupyter notebook's JSON with its cell outputs blanked, line for line, so its code and Markdown are indexed and
|
|
57
|
+
every citation still points at the same line of the real file. Outputs hold results and pictures, not code.
|
|
58
|
+
|
|
59
|
+
Relies on the layout Jupyter writes, with "outputs": [ on a line of its own; anything else is left as it is.
|
|
60
|
+
"""
|
|
61
|
+
lines, kept, closing = text.split("\n"), [], None
|
|
62
|
+
for line in lines:
|
|
63
|
+
if closing is not None:
|
|
64
|
+
kept.append("")
|
|
65
|
+
if line.rstrip().rstrip(",") == closing:
|
|
66
|
+
closing = None
|
|
67
|
+
continue
|
|
68
|
+
opened = re.match(r'^(\s*)"outputs":\s*\[\s*$', line)
|
|
69
|
+
kept.append(line)
|
|
70
|
+
if opened:
|
|
71
|
+
closing = opened[1] + "]"
|
|
72
|
+
return "\n".join(kept)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def chunks(text):
|
|
76
|
+
"""Keep line citations even when a long line needs multiple chunks."""
|
|
77
|
+
buffer, start, end = [], 1, 1
|
|
78
|
+
size = 0
|
|
79
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
80
|
+
# A line over 1,600 characters is cut into pieces; max(1, ...) keeps an empty line as one empty piece.
|
|
81
|
+
for offset in range(0, max(1, len(line)), 1600):
|
|
82
|
+
piece = line[offset:offset + 1600]
|
|
83
|
+
# Close the chunk before it passes about 1,800 characters or 30 lines, so every passage stays small.
|
|
84
|
+
if buffer and (size + len(piece) + 1 > 1800 or number - start >= 30):
|
|
85
|
+
yield start, end, "\n".join(buffer)
|
|
86
|
+
buffer, size = [], 0
|
|
87
|
+
if not buffer:
|
|
88
|
+
start = number
|
|
89
|
+
buffer.append(piece)
|
|
90
|
+
size += len(piece) + 1
|
|
91
|
+
end = number
|
|
92
|
+
if buffer:
|
|
93
|
+
yield start, end, "\n".join(buffer)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class KnowledgeBase:
|
|
97
|
+
"""A BM25 index over the bundled notes, an optional reference folder, and the repository, with its import graph."""
|
|
98
|
+
def __init__(self, directory=None, *, workspace=None, context_budget=16_000, excludes=(), semantic=None, cancel=None,
|
|
99
|
+
cache=None, previous=None):
|
|
100
|
+
"""Read and chunk every allowed file once. The limits below keep memory and start-up time bounded.
|
|
101
|
+
|
|
102
|
+
cancel is an optional threading.Event: once it is set, indexing stops with Stopped between two files,
|
|
103
|
+
so the page's Stop button can end a long index and keep the repository that was open before.
|
|
104
|
+
|
|
105
|
+
cache is a file outside the repository where the keyword index is kept between runs (None keeps nothing on
|
|
106
|
+
disk), and previous is the index of an earlier build in this run. From either, a file whose size, modification
|
|
107
|
+
time, and text are unchanged keeps its passages and parsed outline, so only changed files are worked on again.
|
|
108
|
+
"""
|
|
109
|
+
if not 2000 <= context_budget <= 16_000:
|
|
110
|
+
raise ValueError("Retrieval budget must be between 2000 and 16000 bytes")
|
|
111
|
+
self.cache = Path(cache) if cache is not None else None
|
|
112
|
+
known = previous if previous is not None else index_cache.load(self.cache)
|
|
113
|
+
self.records = {} # "label/name" -> size, mtime, sha, text, and passages of each indexed file, for the next build.
|
|
114
|
+
self.reused = 0 # Files whose passages came from an earlier build.
|
|
115
|
+
self.context_budget = context_budget
|
|
116
|
+
self.semantic = semantic # Optional search by meaning; see semantic.py. None means key words only.
|
|
117
|
+
self.source_texts = {}
|
|
118
|
+
self.directory = directory
|
|
119
|
+
self.workspace_root = workspace.root if isinstance(workspace, Workspace) else workspace
|
|
120
|
+
self.excludes = workspace.excludes if isinstance(workspace, Workspace) else tuple(excludes)
|
|
121
|
+
self.scopes = workspace.scopes if isinstance(workspace, Workspace) else ()
|
|
122
|
+
# Reuse a supplied workspace so its cached exclusion decisions are shared.
|
|
123
|
+
repository = (workspace if isinstance(workspace, Workspace) else
|
|
124
|
+
Workspace(self.workspace_root, excludes=self.excludes, scopes=self.scopes)
|
|
125
|
+
if self.workspace_root is not None else None)
|
|
126
|
+
if repository is not None:
|
|
127
|
+
self.workspace_root = repository.root
|
|
128
|
+
self.excluded_reference_roots = 0
|
|
129
|
+
self.documents = 0
|
|
130
|
+
self.documents_by_source = {"builtin": 0, "user": 0, "repo": 0}
|
|
131
|
+
self.skipped = 0
|
|
132
|
+
self.limited = False
|
|
133
|
+
self.entries = []
|
|
134
|
+
self.frequencies = Counter()
|
|
135
|
+
# Three sources, in this order: the bundled notes, the user's reference folder, then the repository itself.
|
|
136
|
+
roots = [("builtin", Path(__file__).parent / "references", EXTENSIONS)]
|
|
137
|
+
if directory is not None:
|
|
138
|
+
directory = Path(directory).expanduser()
|
|
139
|
+
if directory.exists():
|
|
140
|
+
roots.append(("user", directory, EXTENSIONS))
|
|
141
|
+
else:
|
|
142
|
+
raise ValueError(f"Knowledge directory does not exist: {directory}")
|
|
143
|
+
if self.workspace_root is not None:
|
|
144
|
+
roots.append(("repo", self.workspace_root, CODE_EXTENSIONS))
|
|
145
|
+
total_bytes = 0
|
|
146
|
+
seen = set()
|
|
147
|
+
listings = [] # What was listed from the reference folder and the repository, for the stamp below.
|
|
148
|
+
code_files, manifests = {}, {}
|
|
149
|
+
for label, root, extensions in roots:
|
|
150
|
+
root = Path(root).resolve(strict=True)
|
|
151
|
+
# A reference folder inside the repository must obey the repository's own hide and exclude rules.
|
|
152
|
+
if label == "user" and repository is not None and root.is_relative_to(repository.root):
|
|
153
|
+
relative = root.relative_to(repository.root)
|
|
154
|
+
if relative.parts:
|
|
155
|
+
try:
|
|
156
|
+
repository.path(relative.as_posix())
|
|
157
|
+
except IgnoreConfigurationError:
|
|
158
|
+
raise
|
|
159
|
+
except ValueError:
|
|
160
|
+
self.excluded_reference_roots += 1
|
|
161
|
+
continue
|
|
162
|
+
workspace = repository if label == "repo" else Workspace(root, excludes=self.excludes)
|
|
163
|
+
names = workspace.files()
|
|
164
|
+
self.limited |= len(names) >= MAX_FILES
|
|
165
|
+
if label != "builtin":
|
|
166
|
+
listings.append((label, workspace, names))
|
|
167
|
+
for name in names:
|
|
168
|
+
if cancel is not None and cancel.is_set():
|
|
169
|
+
raise Stopped()
|
|
170
|
+
if label == "repo" and Path(name).name == "go.mod":
|
|
171
|
+
try:
|
|
172
|
+
manifests[name] = workspace.read(name) # Names the Go module, so its imports can be followed.
|
|
173
|
+
except (ValueError, OSError, UnicodeError):
|
|
174
|
+
pass
|
|
175
|
+
if (Path(name).suffix.lower() not in extensions
|
|
176
|
+
and not (label == "repo" and Path(name).name in CODE_NAMES)):
|
|
177
|
+
continue
|
|
178
|
+
# The resolved path identifies a file, so one reached from two roots, or through a link, is indexed once.
|
|
179
|
+
identity = workspace.path(name).resolve()
|
|
180
|
+
if label == "user" and repository is not None and identity.is_relative_to(repository.root):
|
|
181
|
+
try:
|
|
182
|
+
repository.path(identity.relative_to(repository.root).as_posix())
|
|
183
|
+
except IgnoreConfigurationError:
|
|
184
|
+
raise
|
|
185
|
+
except ValueError:
|
|
186
|
+
continue
|
|
187
|
+
if identity in seen:
|
|
188
|
+
continue
|
|
189
|
+
# At most MAX_PASSAGES passages and MAX_INDEX_BYTES of text are indexed; index_limited tells the caller when a limit cut in.
|
|
190
|
+
if self.documents >= MAX_DOCUMENTS or len(self.entries) >= MAX_PASSAGES:
|
|
191
|
+
self.limited = True
|
|
192
|
+
break
|
|
193
|
+
key = f"{label}/{name}"
|
|
194
|
+
old = known["files"].get(key)
|
|
195
|
+
try:
|
|
196
|
+
status = os.stat(identity)
|
|
197
|
+
# An unchanged file from this run's earlier build is not even read again: listing it already
|
|
198
|
+
# checked it, and its size and modification time are what the refresh stamp trusts too.
|
|
199
|
+
if old and "text" in old and (old["size"], old["mtime"]) == (status.st_size, status.st_mtime_ns):
|
|
200
|
+
text = old["text"]
|
|
201
|
+
else:
|
|
202
|
+
text = workspace.read(name)
|
|
203
|
+
except (ValueError, OSError, UnicodeError):
|
|
204
|
+
self.skipped += 1
|
|
205
|
+
continue
|
|
206
|
+
digest = old["sha"] if old and old.get("text") is text else hashlib.sha256(text.encode()).hexdigest()
|
|
207
|
+
if old and old["sha"] != digest:
|
|
208
|
+
old = None
|
|
209
|
+
size = len(text.encode())
|
|
210
|
+
if total_bytes + size > MAX_INDEX_BYTES:
|
|
211
|
+
self.limited = True
|
|
212
|
+
continue
|
|
213
|
+
total_bytes += size
|
|
214
|
+
self.documents += 1
|
|
215
|
+
self.documents_by_source[label] += 1
|
|
216
|
+
seen.add(identity)
|
|
217
|
+
if label == "repo":
|
|
218
|
+
self.source_texts["repo/" + name] = text
|
|
219
|
+
code_files[name] = text
|
|
220
|
+
self.reused += old is not None
|
|
221
|
+
passages = self._passages(key, notebook_text(text) if name.endswith(".ipynb") else text, old)
|
|
222
|
+
self.records[key] = {"size": status.st_size, "mtime": status.st_mtime_ns, "sha": digest, "text": text,
|
|
223
|
+
"passages": passages}
|
|
224
|
+
for entry in passages:
|
|
225
|
+
if len(self.entries) >= MAX_PASSAGES:
|
|
226
|
+
self.limited = True
|
|
227
|
+
break
|
|
228
|
+
self.entries.append(entry)
|
|
229
|
+
self.frequencies.update(entry["counts"].keys())
|
|
230
|
+
self.stamp = self.stamp_of(listings)
|
|
231
|
+
self.average_length = (sum(e["length"] for e in self.entries) / len(self.entries)
|
|
232
|
+
if self.entries else 1)
|
|
233
|
+
# A file's outline and imports depend on its own text and on which files exist, so with the same list of
|
|
234
|
+
# files an unchanged file keeps what the last build found for it.
|
|
235
|
+
names = hashlib.sha256("\0".join(sorted(code_files)).encode()).hexdigest()
|
|
236
|
+
same = known.get("names") == names
|
|
237
|
+
shas = {name: self.records["repo/" + name]["sha"] for name in code_files}
|
|
238
|
+
reuse = {kind: {name: tuple(row[1:]) for name, row in known.get(kind, {}).items()
|
|
239
|
+
if same and name in shas and len(row) == 5 and row[0] == shas[name]} for kind in ("python", "js")}
|
|
240
|
+
self.dependencies = PythonDependencies({name: text for name, text in code_files.items()
|
|
241
|
+
if Path(name).suffix in {".py", ".pyi"}}, reuse["python"])
|
|
242
|
+
# One import graph for all languages: the other analysers' results are merged into the Python one.
|
|
243
|
+
js = JavaScriptDependencies(code_files, reuse["js"])
|
|
244
|
+
self.analysed = {"names": names}
|
|
245
|
+
for kind, found in (("python", self.dependencies), ("js", js)):
|
|
246
|
+
self.analysed[kind] = {name: [shas[name], found.definitions[name], found.spans[name], found.edges[name],
|
|
247
|
+
found.missing[name]] for name in found.edges}
|
|
248
|
+
self.dependencies.edges.update(js.edges)
|
|
249
|
+
self.dependencies.definitions.update(js.definitions)
|
|
250
|
+
self.dependencies.spans.update(js.spans)
|
|
251
|
+
self.dependencies.missing.update(js.missing)
|
|
252
|
+
self.dependencies.parse_failures += js.parse_failures
|
|
253
|
+
other = OtherDependencies(code_files, manifests) # Go, Java, and Rust.
|
|
254
|
+
self.dependencies.edges.update(other.edges)
|
|
255
|
+
self.dependencies.definitions.update(other.definitions)
|
|
256
|
+
self.dependencies.spans.update(other.spans)
|
|
257
|
+
more = MoreDependencies(code_files) # C, C++, C#, Ruby, PHP, Swift, and Kotlin.
|
|
258
|
+
self.dependencies.edges.update(more.edges)
|
|
259
|
+
self.dependencies.definitions.update(more.definitions)
|
|
260
|
+
self.dependencies.spans.update(more.spans)
|
|
261
|
+
self.dependencies.missing.update(more.missing)
|
|
262
|
+
self.dependencies.parse_failures += more.parse_failures
|
|
263
|
+
self.passages_by_source = {}
|
|
264
|
+
for entry in self.entries:
|
|
265
|
+
self.passages_by_source.setdefault(entry["source"], []).append(entry)
|
|
266
|
+
# Where each function, class, method, and module constant is defined, so a name in the question can be looked up.
|
|
267
|
+
self.symbols = {}
|
|
268
|
+
for name in sorted(self.dependencies.definitions.keys() | self.dependencies.spans.keys()):
|
|
269
|
+
places = [(symbol, line) for symbol, line in self.dependencies.definitions.get(name, {}).items()]
|
|
270
|
+
places += [(span["name"], span["start"]) for span in self.dependencies.spans.get(name, [])]
|
|
271
|
+
for symbol, line in places:
|
|
272
|
+
found = self.symbols.setdefault(symbol, [])
|
|
273
|
+
if (name, line) not in found:
|
|
274
|
+
found.append((name, line))
|
|
275
|
+
if self.semantic is not None:
|
|
276
|
+
self.semantic.start(self.entries) # Embeds new or changed passages in the background.
|
|
277
|
+
# Written only when something was worked on afresh, so an unchanged repository costs no disk write.
|
|
278
|
+
if self.cache is not None and (self.reused < self.documents or known.get("names") != names):
|
|
279
|
+
index_cache.save(self.cache, self.records, self.analysed)
|
|
280
|
+
|
|
281
|
+
@staticmethod
|
|
282
|
+
def _passages(source, text, old):
|
|
283
|
+
"""The index entries of one file's passages: reused from old, an earlier build of the same text, or made afresh."""
|
|
284
|
+
if old and "passages" in old:
|
|
285
|
+
return old["passages"]
|
|
286
|
+
pieces = list(chunks(text))
|
|
287
|
+
made = []
|
|
288
|
+
# Saved on disk: the number and term counts of each passage, whose text is cut from the file again.
|
|
289
|
+
rows = old["chunks"] if old and "chunks" in old else (
|
|
290
|
+
(index, Counter(tokens(piece[2]))) for index, piece in enumerate(pieces))
|
|
291
|
+
for index, counts in rows:
|
|
292
|
+
# BM25 needs each passage's term counts and length, and for each term how many passages hold it (frequencies).
|
|
293
|
+
if not counts or not 0 <= index < len(pieces):
|
|
294
|
+
continue
|
|
295
|
+
start, end, passage = pieces[index]
|
|
296
|
+
made.append({"source": source, "start_line": start, "end_line": end, "text": passage, "chunk": index,
|
|
297
|
+
"counts": counts if isinstance(counts, Counter) else Counter(counts),
|
|
298
|
+
"length": sum(counts.values())})
|
|
299
|
+
return made
|
|
300
|
+
|
|
301
|
+
@staticmethod
|
|
302
|
+
def stamp_of(listings):
|
|
303
|
+
"""A fingerprint of the listed files: their names, sizes, and modification times. Nothing is read."""
|
|
304
|
+
digest = hashlib.sha256()
|
|
305
|
+
for label, workspace, names in listings:
|
|
306
|
+
for name in names:
|
|
307
|
+
try:
|
|
308
|
+
status = (workspace.root / name).stat()
|
|
309
|
+
row = (label, name, status.st_size, status.st_mtime_ns)
|
|
310
|
+
except OSError:
|
|
311
|
+
row = (label, name, None, None)
|
|
312
|
+
digest.update(repr(row).encode())
|
|
313
|
+
return digest.hexdigest()
|
|
314
|
+
|
|
315
|
+
def current_stamp(self):
|
|
316
|
+
"""The fingerprint of what is on disk now, listed afresh so changed ignore rules count too."""
|
|
317
|
+
listings = []
|
|
318
|
+
directory = Path(self.directory).expanduser() if self.directory is not None else None
|
|
319
|
+
for label, root in (("user", directory), ("repo", self.workspace_root)):
|
|
320
|
+
if root is not None and Path(root).exists():
|
|
321
|
+
workspace = Workspace(root, excludes=self.excludes, scopes=self.scopes if label == "repo" else ())
|
|
322
|
+
listings.append((label, workspace, workspace.files()))
|
|
323
|
+
return self.stamp_of(listings)
|
|
324
|
+
|
|
325
|
+
def refresh(self):
|
|
326
|
+
"""Pick up files that changed on disk since the index was built. Returns whether it was rebuilt.
|
|
327
|
+
|
|
328
|
+
Listing the files is far cheaper than reading and indexing them again, so an unchanged project, the
|
|
329
|
+
usual case between two questions, keeps its index.
|
|
330
|
+
"""
|
|
331
|
+
try:
|
|
332
|
+
if self.current_stamp() == self.stamp:
|
|
333
|
+
return False
|
|
334
|
+
except (ValueError, OSError):
|
|
335
|
+
pass # Whatever is wrong is reported by the rebuild below.
|
|
336
|
+
previous = {"files": self.records, **self.analysed}
|
|
337
|
+
self.__init__(self.directory, workspace=Workspace(self.workspace_root, excludes=self.excludes, scopes=self.scopes),
|
|
338
|
+
context_budget=self.context_budget,
|
|
339
|
+
excludes=self.excludes, semantic=self.semantic, cache=self.cache, previous=previous)
|
|
340
|
+
return True
|
|
341
|
+
|
|
342
|
+
def forget(self):
|
|
343
|
+
"""Delete the keyword index kept on disk, if there is one."""
|
|
344
|
+
index_cache.forget(self.cache)
|
|
345
|
+
|
|
346
|
+
def _expanded(self, entry, terms, definition_line=None):
|
|
347
|
+
"""Prefer complete syntactic symbols over arbitrary line chunks."""
|
|
348
|
+
source = entry["source"]
|
|
349
|
+
spans = self.dependencies.spans.get(source.removeprefix("repo/"), [])
|
|
350
|
+
lines = self.source_texts.get(source, "").splitlines()
|
|
351
|
+
choices = []
|
|
352
|
+
for span in spans:
|
|
353
|
+
if definition_line is not None:
|
|
354
|
+
relevant = span["start"] <= definition_line <= span["end"]
|
|
355
|
+
else:
|
|
356
|
+
relevant = span["start"] <= entry["end_line"] and span["end"] >= entry["start_line"]
|
|
357
|
+
if not relevant:
|
|
358
|
+
continue
|
|
359
|
+
text = "\n".join(lines[span["start"] - 1:span["end"]])
|
|
360
|
+
overlap = len(terms & set(tokens(text)))
|
|
361
|
+
if definition_line is not None:
|
|
362
|
+
# The innermost symbol around a definition is the one defined there: a method, not its whole class.
|
|
363
|
+
overlap = 0
|
|
364
|
+
if definition_line is not None or overlap:
|
|
365
|
+
choices.append((overlap, -(span["end"] - span["start"]), span, text))
|
|
366
|
+
if not choices:
|
|
367
|
+
return None
|
|
368
|
+
# Most query terms wins; on a tie the shortest span, which is the innermost symbol.
|
|
369
|
+
_, _, span, text = max(choices, key=lambda row: row[:2])
|
|
370
|
+
expanded = dict(entry, start_line=span["start"], end_line=span["end"], text=text,
|
|
371
|
+
symbol=span["name"], symbol_complete=True)
|
|
372
|
+
constants = self._constants(lines, text)
|
|
373
|
+
if constants:
|
|
374
|
+
expanded["constants"] = constants
|
|
375
|
+
return expanded
|
|
376
|
+
|
|
377
|
+
@staticmethod
|
|
378
|
+
def _constants(lines, text):
|
|
379
|
+
"""Values of the file's module constants a symbol uses, since the answer is often the value, not the name."""
|
|
380
|
+
found = []
|
|
381
|
+
for name in dict.fromkeys(re.findall(r"\b[A-Z][A-Z0-9_]{2,}\b", text)):
|
|
382
|
+
# An assignment at the start of a line (Python, or JavaScript const/let/var/export), not an == comparison.
|
|
383
|
+
definition = re.compile(rf"(?:export\s+)?(?:const\s+|let\s+|var\s+)?{name}\s*(?::[^=]+)?=(?!=)")
|
|
384
|
+
number = next((number for number, line in enumerate(lines, 1) if definition.match(line) and len(line) <= 160), None)
|
|
385
|
+
if number and lines[number - 1] not in text:
|
|
386
|
+
found.append({"name": name, "line": number, "text": lines[number - 1].strip()})
|
|
387
|
+
if len(found) >= 3:
|
|
388
|
+
break
|
|
389
|
+
return found
|
|
390
|
+
|
|
391
|
+
def named_definitions(self, query):
|
|
392
|
+
"""Definitions of the code names a question mentions, as (name, file, line), in the order they appear.
|
|
393
|
+
|
|
394
|
+
Only names written like code count: with an underscore, camelCase, ALL_CAPS, a dot, backticks, or (),
|
|
395
|
+
or a plain word right next to "function", "method", "class", or "constant". Keyword ranking often
|
|
396
|
+
misses these, because a name's definition can use it once while tests and callers repeat it."""
|
|
397
|
+
mentioned = []
|
|
398
|
+
for match in re.finditer(r"`([^`\n]{1,100})`|([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)(\s*\(\))?", query):
|
|
399
|
+
text = match.group(1) or match.group(2)
|
|
400
|
+
for name in re.findall(r"[A-Za-z_$][\w$]*", text)[-1:]: # Store.remove_item -> remove_item
|
|
401
|
+
coded = (match.group(1) or match.group(3) or "." in text or "_" in name.strip("_")
|
|
402
|
+
or re.search(r"[a-z][A-Z]", name) or re.fullmatch(r"[A-Z][A-Z0-9_]{2,}", name))
|
|
403
|
+
if not coded:
|
|
404
|
+
near = re.compile(rf"\b(?:function|method|class|constant)\s+{re.escape(name)}\b"
|
|
405
|
+
rf"|\b{re.escape(name)}\s+(?:function|method|class|constant)\b", re.I)
|
|
406
|
+
coded = near.search(query)
|
|
407
|
+
if coded and name not in mentioned and not name.startswith("__"):
|
|
408
|
+
mentioned.append(name)
|
|
409
|
+
found = []
|
|
410
|
+
for name in mentioned:
|
|
411
|
+
places = self.symbols.get(name, [])
|
|
412
|
+
if 1 <= len(places) <= 3: # A name defined in many files says little about which one is meant.
|
|
413
|
+
found += [(name, path, line) for path, line in places]
|
|
414
|
+
return found[:3]
|
|
415
|
+
|
|
416
|
+
def retrieve(self, query, budget=None):
|
|
417
|
+
"""The passages to show the model for a query, as a JSON string that fits the context budget.
|
|
418
|
+
|
|
419
|
+
budget, when given, is a smaller limit for this call only (at least 2000 bytes), such as the room left in a
|
|
420
|
+
prompt that preloaded files already fill.
|
|
421
|
+
|
|
422
|
+
In order: definitions of names the question mentions, the best-ranked matches (at most 4), passages of the
|
|
423
|
+
files those matches import (2 levels deep), then further matches if space is left. Ranking is BM25 over
|
|
424
|
+
key words, mixed with the meaning-search ranking when one is available."""
|
|
425
|
+
if not isinstance(query, str) or not query.strip() or len(query) > 1000:
|
|
426
|
+
raise ValueError("Retrieval query must contain 1 to 1000 characters")
|
|
427
|
+
budget = self.context_budget if budget is None else max(2000, min(budget, self.context_budget))
|
|
428
|
+
terms = set(tokens(query))
|
|
429
|
+
scored = []
|
|
430
|
+
count = len(self.entries)
|
|
431
|
+
for entry in self.entries:
|
|
432
|
+
score = 0.0
|
|
433
|
+
for term in terms:
|
|
434
|
+
frequency = entry["counts"].get(term, 0)
|
|
435
|
+
if not frequency:
|
|
436
|
+
continue
|
|
437
|
+
# BM25 with the usual k1 = 1.2 and b = 0.75: a rare term weighs more (inverse), repeats of a term add less
|
|
438
|
+
# and less, and a passage longer than average is scaled down. 2.2 is k1 + 1.
|
|
439
|
+
df = self.frequencies[term]
|
|
440
|
+
inverse = math.log(1 + (count - df + 0.5) / (df + 0.5))
|
|
441
|
+
norm = frequency + 1.2 * (0.25 + 0.75 * entry["length"] / self.average_length)
|
|
442
|
+
score += inverse * frequency * 2.2 / norm
|
|
443
|
+
if score > 0:
|
|
444
|
+
scored.append((score, entry))
|
|
445
|
+
near = self.semantic.rank(query, self.entries) if self.semantic is not None else []
|
|
446
|
+
if near:
|
|
447
|
+
# Reciprocal rank fusion: a passage's place in each ranking counts, not the two scores, which are
|
|
448
|
+
# on different scales. A passage near the top of both lists beats one that leads only one of them.
|
|
449
|
+
scored.sort(key=lambda pair: (-pair[0], pair[1]["source"], pair[1]["start_line"]))
|
|
450
|
+
fused = {}
|
|
451
|
+
# 60 is the customary fusion constant: it evens out the gap between neighbouring places. Only the top 64
|
|
452
|
+
# keyword matches take part.
|
|
453
|
+
for place, (_, entry) in enumerate(scored[:64]):
|
|
454
|
+
fused[id(entry)] = [1 / (60 + place), entry]
|
|
455
|
+
for place, (_, index) in enumerate(near):
|
|
456
|
+
entry = self.entries[index]
|
|
457
|
+
fused.setdefault(id(entry), [0.0, entry])[0] += 1 / (60 + place)
|
|
458
|
+
scored = [(score, entry) for score, entry in fused.values()]
|
|
459
|
+
# The bundled notes only cover LangGraph, so they must not crowd out the project on other questions.
|
|
460
|
+
if "langgraph" not in terms and not terms & BUNDLED_TOPICS and any(not e["source"].startswith("builtin/") for _, e in scored):
|
|
461
|
+
scored = [pair for pair in scored if not pair[1]["source"].startswith("builtin/")]
|
|
462
|
+
scored.sort(key=lambda pair: (-pair[0], pair[1]["source"], pair[1]["start_line"]))
|
|
463
|
+
# Give different files a chance before adding further passages from one file.
|
|
464
|
+
diverse, repeated, seen_sources = [], [], set()
|
|
465
|
+
for pair in scored:
|
|
466
|
+
source = pair[1]["source"]
|
|
467
|
+
(repeated if source in seen_sources else diverse).append(pair)
|
|
468
|
+
seen_sources.add(source)
|
|
469
|
+
candidates = (diverse + repeated)[:64]
|
|
470
|
+
result = {"results": [], "documents": self.documents, "chunks": count,
|
|
471
|
+
"documents_by_source": self.documents_by_source,
|
|
472
|
+
"skipped_documents": self.skipped, "index_limited": self.limited,
|
|
473
|
+
"excluded_reference_roots": self.excluded_reference_roots,
|
|
474
|
+
"meaning_search": bool(near),
|
|
475
|
+
"results_limited": False, "dependency_limit_reached": False,
|
|
476
|
+
"dependency_parse_failures": self.dependencies.parse_failures,
|
|
477
|
+
"context_budget_bytes": budget, "context_bytes": 0,
|
|
478
|
+
"budget_limited": False}
|
|
479
|
+
identities, selected = set(), []
|
|
480
|
+
|
|
481
|
+
def accept(entry, metadata, limit, definition_line=None):
|
|
482
|
+
"""Add one passage to the result if it fits within limit bytes. Returns "added", "duplicate", or "budget"."""
|
|
483
|
+
expanded = self._expanded(entry, terms, definition_line)
|
|
484
|
+
# Try the whole symbol first; if it is too big for the budget, fall back to the plain chunk.
|
|
485
|
+
variants = [expanded, dict(entry, symbol_complete=False)] if expanded else [entry]
|
|
486
|
+
for variant in variants:
|
|
487
|
+
if variant is None:
|
|
488
|
+
continue
|
|
489
|
+
identity = (variant["source"], variant["start_line"], variant["end_line"], variant["text"])
|
|
490
|
+
if identity in identities:
|
|
491
|
+
return "duplicate"
|
|
492
|
+
passage = {key: variant[key] for key in ("source", "start_line", "end_line", "text")}
|
|
493
|
+
passage.update({key: variant[key] for key in ("symbol", "symbol_complete", "constants") if key in variant})
|
|
494
|
+
passage.update(metadata)
|
|
495
|
+
result["results"].append(passage)
|
|
496
|
+
# Measured as real JSON with the passage in place; 128 bytes stay free for the counters filled in at the end.
|
|
497
|
+
if len(json.dumps(result, ensure_ascii=False).encode()) <= limit - 128:
|
|
498
|
+
identities.add(identity)
|
|
499
|
+
if metadata["kind"] == "match":
|
|
500
|
+
selected.append(variant)
|
|
501
|
+
return "added"
|
|
502
|
+
result["results"].pop()
|
|
503
|
+
result["budget_limited"] = True
|
|
504
|
+
return "budget"
|
|
505
|
+
|
|
506
|
+
# When the top matches import other files, 40% of the budget is held back for those dependencies.
|
|
507
|
+
has_dependencies = any(self.dependencies.edges.get(e["source"].removeprefix("repo/"))
|
|
508
|
+
for _, e in candidates[:4] if e["source"].startswith("repo/"))
|
|
509
|
+
primary_budget = int(budget * 0.6) if has_dependencies else budget
|
|
510
|
+
# A name the question mentions comes first, ahead of keyword matches, so its definition is never crowded out.
|
|
511
|
+
for name, path, line in self.named_definitions(query):
|
|
512
|
+
passage = next((p for p in self.passages_by_source.get("repo/" + path, [])
|
|
513
|
+
if p["start_line"] <= line <= p["end_line"]), None)
|
|
514
|
+
if passage is not None:
|
|
515
|
+
accept(passage, {"score": 0.0, "kind": "definition", "via": "question", "name": name},
|
|
516
|
+
primary_budget, line)
|
|
517
|
+
# At most 4 keyword matches at first; the others wait in deferred until the dependencies have had their share.
|
|
518
|
+
deferred = []
|
|
519
|
+
for score, entry in candidates:
|
|
520
|
+
if len(selected) >= 4:
|
|
521
|
+
deferred.append((score, entry))
|
|
522
|
+
continue
|
|
523
|
+
status = accept(entry, {"score": round(score, 4), "kind": "match"}, primary_budget)
|
|
524
|
+
if status == "budget":
|
|
525
|
+
deferred.append((score, entry))
|
|
526
|
+
# Breadth-first walk of the import graph from the matched files: 2 levels deep, at most 4 passages. [5:] drops "repo/".
|
|
527
|
+
queue = [(entry["source"][5:], 0) for entry in selected if entry["source"].startswith("repo/")]
|
|
528
|
+
visited = {name for name, _ in queue}
|
|
529
|
+
added = 0
|
|
530
|
+
for name, depth in queue:
|
|
531
|
+
edges = self.dependencies.edges.get(name, {})
|
|
532
|
+
if depth >= 2:
|
|
533
|
+
result["dependency_limit_reached"] |= any(target not in visited for target in edges)
|
|
534
|
+
continue
|
|
535
|
+
for target, symbols in edges.items():
|
|
536
|
+
passages = self.passages_by_source.get("repo/" + target, [])
|
|
537
|
+
if not passages:
|
|
538
|
+
continue
|
|
539
|
+
definitions = self.dependencies.definitions.get(target, {})
|
|
540
|
+
# Show the passage holding each imported name's definition; when no name is known, the file's first passage.
|
|
541
|
+
definition_lines = list(dict.fromkeys(definitions[s] for s in symbols if s in definitions)) or [None]
|
|
542
|
+
for line in definition_lines:
|
|
543
|
+
passage = next((p for p in passages if line is not None
|
|
544
|
+
and p["start_line"] <= line <= p["end_line"]), passages[0])
|
|
545
|
+
if added >= 4:
|
|
546
|
+
result["dependency_limit_reached"] = True
|
|
547
|
+
break
|
|
548
|
+
status = accept(passage, {"score": 0.0, "kind": "dependency",
|
|
549
|
+
"via": "repo/" + name, "depth": depth + 1},
|
|
550
|
+
budget, line)
|
|
551
|
+
if status == "added":
|
|
552
|
+
added += 1
|
|
553
|
+
elif status == "budget":
|
|
554
|
+
result["dependency_limit_reached"] = True
|
|
555
|
+
if target not in visited:
|
|
556
|
+
visited.add(target)
|
|
557
|
+
queue.append((target, depth + 1))
|
|
558
|
+
# Reclaim unused dependency space, while avoiding unexplored new import graphs.
|
|
559
|
+
for score, entry in deferred:
|
|
560
|
+
if len(selected) >= 4:
|
|
561
|
+
break
|
|
562
|
+
name = entry["source"].removeprefix("repo/")
|
|
563
|
+
if self.dependencies.edges.get(name) and name not in visited:
|
|
564
|
+
continue
|
|
565
|
+
accept(entry, {"score": round(score, 4), "kind": "match"}, budget)
|
|
566
|
+
result["results_limited"] = len(scored) > len(selected) or result["budget_limited"]
|
|
567
|
+
for _ in range(3): # The count is part of the JSON it measures, so repeat until its own digits settle.
|
|
568
|
+
result["context_bytes"] = len(json.dumps(result, ensure_ascii=False).encode())
|
|
569
|
+
return json.dumps(result, ensure_ascii=False)
|