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.
Files changed (57) hide show
  1. codehaven-0.14.0.dist-info/METADATA +686 -0
  2. codehaven-0.14.0.dist-info/RECORD +57 -0
  3. codehaven-0.14.0.dist-info/WHEEL +5 -0
  4. codehaven-0.14.0.dist-info/entry_points.txt +3 -0
  5. codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
  6. codehaven-0.14.0.dist-info/top_level.txt +1 -0
  7. offline_agent/__init__.py +2 -0
  8. offline_agent/__main__.py +4 -0
  9. offline_agent/agent.py +815 -0
  10. offline_agent/answers.py +438 -0
  11. offline_agent/arabic.py +106 -0
  12. offline_agent/changes.py +228 -0
  13. offline_agent/chats.py +121 -0
  14. offline_agent/cli.py +379 -0
  15. offline_agent/coder.py +199 -0
  16. offline_agent/dependencies.py +132 -0
  17. offline_agent/doctor.py +190 -0
  18. offline_agent/documents.py +189 -0
  19. offline_agent/edits.py +204 -0
  20. offline_agent/errors.py +41 -0
  21. offline_agent/evaluation.py +284 -0
  22. offline_agent/evidence.py +187 -0
  23. offline_agent/exclusions.py +95 -0
  24. offline_agent/export.py +27 -0
  25. offline_agent/gui.css +237 -0
  26. offline_agent/gui.html +177 -0
  27. offline_agent/gui.js +1213 -0
  28. offline_agent/gui.py +967 -0
  29. offline_agent/gui_arabic.js +226 -0
  30. offline_agent/guides.py +203 -0
  31. offline_agent/history.py +126 -0
  32. offline_agent/index_cache.py +78 -0
  33. offline_agent/insights.py +333 -0
  34. offline_agent/javascript.py +200 -0
  35. offline_agent/knowledge.py +569 -0
  36. offline_agent/languages.py +396 -0
  37. offline_agent/memory.py +192 -0
  38. offline_agent/messages.py +51 -0
  39. offline_agent/model.py +498 -0
  40. offline_agent/more_languages.py +253 -0
  41. offline_agent/ocr.py +204 -0
  42. offline_agent/prompts.py +130 -0
  43. offline_agent/references/langgraph-approvals.md +38 -0
  44. offline_agent/references/langgraph-checkpoints.md +37 -0
  45. offline_agent/references/langgraph-graphs.md +42 -0
  46. offline_agent/references/langgraph.md +49 -0
  47. offline_agent/review.py +205 -0
  48. offline_agent/scans.py +325 -0
  49. offline_agent/semantic.py +264 -0
  50. offline_agent/slash.py +53 -0
  51. offline_agent/study.py +210 -0
  52. offline_agent/symbols.py +201 -0
  53. offline_agent/tasks.py +164 -0
  54. offline_agent/test_runner.py +264 -0
  55. offline_agent/trace.py +239 -0
  56. offline_agent/tracebacks.py +98 -0
  57. offline_agent/workspace.py +419 -0
offline_agent/scans.py ADDED
@@ -0,0 +1,325 @@
1
+ """Three whole-project answers made by plain code, with no model: the libraries a project uses, a security and
2
+ secrets scan, and what a change to one function or class would affect.
3
+
4
+ Each finding cites the line it comes from, and the lines are kept as evidence, so the answer can be checked like
5
+ any other. Nothing is run, imported, or installed.
6
+
7
+ - Dependencies: the packages the project's manifests declare (pyproject.toml, requirements*.txt, package.json,
8
+ go.mod, Cargo.toml, Gemfile, composer.json, *.csproj), and the outside modules its code imports, with how many
9
+ files import each. An import no manifest declares is pointed out.
10
+ - Security scan: hard-coded keys and passwords, eval and exec, shell commands built from strings, and SQL built from
11
+ strings, found with line patterns. A pattern finds candidates, not proof: read each cited line. A secret's value
12
+ is never shown, only its first characters.
13
+ - Impact: for a named function, method, or class, the places that call it (with the function each is in), the
14
+ files that import it, and the tests that mention it.
15
+ """
16
+ import json
17
+ import re
18
+ from collections import defaultdict
19
+ from pathlib import Path, PurePosixPath
20
+
21
+ from . import trace
22
+ from .insights import CODE, is_test
23
+
24
+ DEPENDENCIES = re.compile(r"\b(?:which|what|list|show)\b.*\b(?:librar(?:y|ies)|dependenc(?:y|ies)|packages|third[- ]party)\b"
25
+ r"|\b(?:external|third[- ]party)\s+(?:librar(?:y|ies)|dependenc(?:y|ies)|packages|code)\b"
26
+ r"|^\W*dependenc(?:y|ies)(?:\s+list)?\W*$", re.I)
27
+ SECURITY = re.compile(r"\bsecurity\s+(?:scan|check|review|audit|issues?|risks?|problems?)\b|\b(?:scan|check|look)\b.*\b(?:secrets?|"
28
+ r"vulnerabilit(?:y|ies)|security)\b|\bhard[- ]?coded\s+(?:keys?|secrets?|passwords?|credentials?|tokens?)\b"
29
+ r"|\b(?:any|find)\s+(?:secrets|vulnerabilities|injection)\b", re.I)
30
+ NAME = r"`?([A-Za-z_$][\w$.]*\w)`?(?:\(\))?"
31
+ IMPACT = re.compile(rf"\bwhat\s+(?:would\s+|will\s+|could\s+|might\s+)?(?:breaks?|break|be\s+affected|is\s+affected|depends\s+on)\b.*?"
32
+ rf"\b(?:change|changing|modify|modifying|edit|editing|remove|removing|rename|renaming|delete|deleting)\s+"
33
+ rf"(?:the\s+)?(?:function\s+|method\s+|class\s+)?{NAME}"
34
+ rf"|\b(?:impact|effect|blast\s+radius)\s+of\s+(?:changing|modifying|removing|renaming)\s+"
35
+ rf"(?:the\s+)?(?:function\s+|method\s+|class\s+)?{NAME}"
36
+ rf"|\bwho\s+(?:depends\s+on|uses)\s+(?:the\s+)?(?:function\s+|method\s+|class\s+)?{NAME}", re.I)
37
+ # Findings listed, places of one kind listed, and the longest line shown.
38
+ FINDINGS, PLACES, LINE_CHARS = 40, 12, 140
39
+
40
+
41
+ def requested(task):
42
+ """("dependencies", None), ("security", None), ("impact", name), or None for any other task."""
43
+ if (found := IMPACT.search(task)) and (name := next((group for group in found.groups() if group), None)):
44
+ return "impact", name.rstrip(".")
45
+ if SECURITY.search(task):
46
+ return "security", None
47
+ if DEPENDENCIES.search(task):
48
+ return "dependencies", None
49
+ return None
50
+
51
+
52
+ def run(kind, name, workspace, knowledge):
53
+ """The answer for one kind of scan: {"text", "evidence"}."""
54
+ if kind == "dependencies":
55
+ return dependencies(workspace, knowledge)
56
+ if kind == "security":
57
+ return security(workspace)
58
+ return impact(workspace, knowledge, name)
59
+
60
+
61
+ def shown(text):
62
+ """One line of code, trimmed to fit a list."""
63
+ text = " ".join(text.split())
64
+ return text if len(text) <= LINE_CHARS else text[:LINE_CHARS - 1] + "…"
65
+
66
+
67
+ def evidence(path, line, text):
68
+ """One evidence row: the cited line, so the answer's citations are checked against what was read."""
69
+ return {"path": path, "line": line, "end_line": line, "text": text}
70
+
71
+
72
+ # Manifest file name (or suffix) -> how to find the declared packages: a pattern whose first group is the name.
73
+ MANIFESTS = [
74
+ (re.compile(r"^requirements[\w.-]*\.txt$"), re.compile(r"^\s*([A-Za-z0-9][\w.-]*)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;]|$)")),
75
+ (re.compile(r"^go\.mod$"), re.compile(r"^\s*(?:require\s+)?([\w.-]+\.[a-z]{2,}/[\w./-]+)\s+v[\d.]")),
76
+ (re.compile(r"^Gemfile$"), re.compile(r"""^\s*gem\s+['"]([\w.-]+)['"]""")),
77
+ (re.compile(r"\.csproj$"), re.compile(r"""<PackageReference\s+Include=['"]([\w.-]+)['"]""")),
78
+ ]
79
+ # A Python requirement inside pyproject.toml: a quoted string in a dependencies list, such as "httpx>=0.27".
80
+ PYPROJECT_ITEM = re.compile(r"""^\s*(?:dependencies\s*=\s*\[)?\s*['"]([A-Za-z0-9][\w.-]*)\s*(?:\[[^\]]*\])?\s*[<>=!~;,'"]""")
81
+ # Import names that are spelled differently from the package that provides them.
82
+ ALIASES = {"yaml": "pyyaml", "pil": "pillow", "sklearn": "scikit-learn", "cv2": "opencv-python", "bs4": "beautifulsoup4",
83
+ "dateutil": "python-dateutil", "jose": "python-jose", "jwt": "pyjwt", "dotenv": "python-dotenv",
84
+ "google": "google-api-python-client", "attr": "attrs", "magic": "python-magic", "serial": "pyserial"}
85
+
86
+
87
+ def normal(name):
88
+ """A package name in the form that two spellings of it share: lower case, with - _ . the same."""
89
+ return re.sub(r"[-_.]+", "-", name.lower())
90
+
91
+
92
+ def declared(workspace):
93
+ """[(package, manifest path, line)] for every package the project's manifests declare."""
94
+ found = []
95
+ for path in workspace.files():
96
+ file = PurePosixPath(path).name
97
+ try:
98
+ if file not in ("pyproject.toml", "package.json", "Cargo.toml", "composer.json") and not any(
99
+ pattern.search(file) for pattern, _ in MANIFESTS):
100
+ continue
101
+ text = workspace.read(path)
102
+ except (ValueError, OSError, UnicodeError):
103
+ continue
104
+ lines = text.splitlines()
105
+ if file in ("package.json", "composer.json"):
106
+ try:
107
+ data = json.loads(text)
108
+ except ValueError:
109
+ continue
110
+ sections = ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies", "require", "require-dev")
111
+ for section in sections:
112
+ for package in (data.get(section) or {}) if isinstance(data, dict) else {}:
113
+ if package == "php" or package.startswith("ext-"):
114
+ continue
115
+ line = next((number for number, row in enumerate(lines, 1) if f'"{package}"' in row), 1)
116
+ found.append((package, path, line))
117
+ continue
118
+ table = ""
119
+ for number, row in enumerate(lines, 1):
120
+ if file in ("pyproject.toml", "Cargo.toml"):
121
+ if re.match(r"^\s*\[", row):
122
+ table = row.strip()
123
+ continue
124
+ if file == "Cargo.toml":
125
+ match = re.match(r"^\s*([\w-]+)\s*=", row) if "dependencies" in table else None
126
+ else:
127
+ inside = table in ("[project]", "[project.optional-dependencies]") or "dependencies" in table
128
+ match = PYPROJECT_ITEM.match(row) if inside and not re.match(r"^\s*(?:name|version|requires-python)\s*=", row) else None
129
+ else:
130
+ pattern = next(item for name_pattern, item in MANIFESTS if name_pattern.search(file))
131
+ match = pattern.search(row) if not row.lstrip().startswith(("#", "//", "-")) else None
132
+ if match:
133
+ found.append((match[1], path, number))
134
+ return found
135
+
136
+
137
+ def dependencies(workspace, knowledge):
138
+ """The libraries the project declares and the outside modules its code imports."""
139
+ packages = declared(workspace)
140
+ missing = getattr(getattr(knowledge, "dependencies", None), "missing", None) or {}
141
+ used = defaultdict(list) # top-level module -> [(path, line)]
142
+ for path, rows in missing.items():
143
+ for row in rows:
144
+ if row.get("local"):
145
+ continue
146
+ module = row["module"]
147
+ top = module.split("/")[0] if not module.startswith("@") else "/".join(module.split("/")[:2])
148
+ top = top.split(".")[0] if PurePosixPath(path).suffix in (".py", ".pyi") else top
149
+ if (path, row["line"]) not in used[top]:
150
+ used[top].append((path, row["line"]))
151
+ known = {normal(package) for package, _, _ in packages}
152
+ rows, lines = [], []
153
+ if packages:
154
+ # Manifests at the top of the project list every package; ones in subfolders, such as examples, are summarised.
155
+ by_file = defaultdict(list)
156
+ for package, path, line in packages:
157
+ by_file[path].append((package, line))
158
+ top = sorted(path for path in by_file if "/" not in path)
159
+ for path in top:
160
+ lines.append(f"Declared in {path} ({len(by_file[path])}):")
161
+ for package, line in by_file[path][:FINDINGS]:
162
+ lines.append(f"- `{package}` ({path}:{line})")
163
+ rows.append(evidence(path, line, package))
164
+ nested = sorted(path for path in by_file if "/" in path)
165
+ if nested:
166
+ lines.append(("" if top else "") + f"Manifests in subfolders ({len(nested)}):")
167
+ for path in nested[:PLACES]:
168
+ package, line = by_file[path][0]
169
+ lines.append(f"- {path}: {len(by_file[path])} package{'s' if len(by_file[path]) != 1 else ''}, "
170
+ f"first `{package}` at {path}:{line}")
171
+ rows.append(evidence(path, line, package))
172
+ else:
173
+ lines.append("No manifest (pyproject.toml, requirements.txt, package.json, go.mod, Cargo.toml, Gemfile, "
174
+ "composer.json, or .csproj) declares any packages.")
175
+ if used:
176
+ lines.append("")
177
+ lines.append(f"Imported by the code from outside the repository ({len(used)}), most widely used first:")
178
+ for module, places in sorted(used.items(), key=lambda item: (-len({p for p, _ in item[1]}), item[0]))[:FINDINGS]:
179
+ files = len({path for path, _ in places})
180
+ path, line = places[0]
181
+ note = "" if normal(module) in known or normal(ALIASES.get(module.lower(), module)) in known or not packages \
182
+ else "; not declared in a manifest"
183
+ lines.append(f"- `{module}`: {files} file{'s' if files != 1 else ''}, first at {path}:{line}{note}")
184
+ rows.append(evidence(path, line, module))
185
+ lines.append("")
186
+ lines.append("Found from the manifests and the parsed imports, without running anything. Standard-library and "
187
+ "built-in modules are not listed.")
188
+ return {"text": "\n".join(lines), "evidence": rows}
189
+
190
+
191
+ SECRET_VALUE = r"""['"]([^'"\s]{8,})['"]"""
192
+ RULES = [
193
+ ("Hard-coded secret", re.compile(r"\b(AKIA[0-9A-Z]{16})\b")),
194
+ ("Hard-coded secret", re.compile(r"(-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----)")),
195
+ ("Hard-coded secret", re.compile(r"\b(gh[pousr]_[A-Za-z0-9]{36,}|xox[baprs]-[A-Za-z0-9-]{10,}|sk-[A-Za-z0-9]{20,})\b")),
196
+ ("Hard-coded secret", re.compile(r"(?i)\b[\w-]*(?:password|passwd|secret|api[_-]?key|access[_-]?key|auth[_-]?token|token)"
197
+ r"[\w-]*['\"]?\s*[:=]\s*" + SECRET_VALUE)),
198
+ ("Code run from a string", re.compile(r"(?<![\w.])(?:eval|exec)\s*\((?!\s*\))|\bnew\s+Function\s*\(")),
199
+ ("Shell command", re.compile(r"\bshell\s*=\s*True\b|\bos\.(?:system|popen)\s*\(|\bchild_process\.exec(?:Sync)?\s*\(|"
200
+ r"(?<![\w.])exec(?:Sync)?\s*\(\s*(?:`[^`]*\$\{|['\"][^'\"]*['\"]\s*\+)")),
201
+ ("SQL built from a string", re.compile(r"\.(?:execute|executemany|raw|query)\s*\(\s*(?:f['\"]|['\"][^'\"]*['\"]\s*(?:%|\+)|"
202
+ r"['\"][^'\"]*['\"]\s*\.format\(|`[^`]*\$\{)", re.I)),
203
+ ("Unsafe loading", re.compile(r"\bpickle\.loads?\s*\(|\byaml\.load\s*\((?![^)]*Loader\s*=\s*yaml\.SafeLoader)|\bmarshal\.loads\s*\(")),
204
+ ("TLS check turned off", re.compile(r"\bverify\s*=\s*False\b|rejectUnauthorized\s*:\s*false")),
205
+ ]
206
+ # Values that are plainly placeholders, not real secrets.
207
+ PLACEHOLDER = re.compile(r"(?i)^(?:x+|\*+|changeme|change_me|example|sample|dummy|test|testing|password|secret|your[\w-]*|"
208
+ r"<[^>]*>|\$\{[^}]*\}|%\([^)]*\)s|\{\{[^}]*\}\})$|example|placeholder|xxxx|dummy")
209
+ SCANNED = CODE | {".env", ".ini", ".cfg", ".toml", ".yaml", ".yml", ".json", ".properties", ".sh", ".bash", ".zsh", ".tf"}
210
+
211
+
212
+ def masked(text, value):
213
+ """The line with a secret's value replaced by its first 4 characters and stars."""
214
+ return text.replace(value, value[:4] + "*" * min(12, max(4, len(value) - 4))) if value else text
215
+
216
+
217
+ def security(workspace):
218
+ """Lines that look like a security risk, most serious kind first, each cited and with any secret masked."""
219
+ findings = []
220
+ for path in workspace.files():
221
+ suffix = PurePosixPath(path).suffix.lower()
222
+ if suffix not in SCANNED and PurePosixPath(path).name not in ("Dockerfile",):
223
+ continue
224
+ try:
225
+ lines = workspace.read(path).splitlines()
226
+ except (ValueError, OSError, UnicodeError):
227
+ continue
228
+ for number, line in enumerate(lines, 1):
229
+ if len(line) > 2000:
230
+ continue
231
+ for kind, rule in RULES:
232
+ match = rule.search(line)
233
+ if not match:
234
+ continue
235
+ value = match.group(1) if match.groups() else ""
236
+ if kind == "Hard-coded secret" and value and (PLACEHOLDER.search(value) or re.search(r"(?i)environ|getenv|process\.env", line)):
237
+ continue
238
+ findings.append((kind, path, number, masked(line, value if kind == "Hard-coded secret" else "")))
239
+ break
240
+ order = [kind for kind, _ in RULES]
241
+ findings.sort(key=lambda row: (order.index(row[0]), is_test(row[1]), row[1], row[2]))
242
+ if not findings:
243
+ return {"text": "No line matched the security patterns (hard-coded keys and passwords, eval and exec, shell "
244
+ "commands, SQL built from strings, unsafe loading, turned-off TLS checks). Patterns cannot prove "
245
+ "code is safe; they only find the common mistakes.", "evidence": []}
246
+ lines, rows, current = [f"{len(findings)} line{'s' if len(findings) != 1 else ''} to check, most serious kind first. "
247
+ "These are pattern matches, not proof: read each cited line."], [], None
248
+ for kind, path, number, text in findings[:FINDINGS]:
249
+ if kind != current:
250
+ lines += ["", kind + ":"]
251
+ current = kind
252
+ lines.append(f"- {path}:{number}{' (test)' if is_test(path) else ''}: `{shown(text)}`")
253
+ rows.append(evidence(path, number, text))
254
+ if len(findings) > FINDINGS:
255
+ lines += ["", f"... and {len(findings) - FINDINGS} more."]
256
+ lines += ["", "Secrets are shown masked. A real secret in the code should be revoked and moved to an environment "
257
+ "variable or a secrets store, since it is in the project's history too."]
258
+ return {"text": "\n".join(lines), "evidence": rows}
259
+
260
+
261
+ def impact(workspace, knowledge, name):
262
+ """What a change to name would affect: its callers, the files that import it, and the tests that mention it."""
263
+ every = trace.functions(knowledge) if knowledge is not None else []
264
+ places = trace.locate(name, every)
265
+ short = name.rsplit(".", 1)[-1]
266
+ if not places:
267
+ definitions = (getattr(knowledge, "symbols", {}) or {}).get(short, []) if knowledge is not None else []
268
+ if not definitions:
269
+ return {"text": f"No function, method, or class named {name} was found in the parsed code.", "evidence": []}
270
+ places = [(path, {"name": short, "start": line, "end": line}) for path, line in definitions]
271
+ target = places[0]
272
+ path, span = target
273
+ lines = [f"`{span['name']}` is defined at {path}:{span['start']}-{span['end']}."]
274
+ rows = [evidence(path, span["start"], span["name"])]
275
+ if len(places) > 1:
276
+ lines.append("Other definitions with that name, not followed here: "
277
+ + ", ".join(f"{other}:{info['start']}" for other, info in places[1:4]) + ".")
278
+ # Every indexed code file is looked through, not a capped search: in a large project the first matches of a name
279
+ # are often documentation, which would crowd out the calls and the tests.
280
+ texts = getattr(knowledge, "source_texts", {}) if knowledge is not None else {}
281
+ call = re.compile(rf"(?<![\w$]){re.escape(short)}\s*\(")
282
+ word = re.compile(rf"(?<![\w$]){re.escape(short)}(?![\w$])")
283
+ calls, tests = [], []
284
+ for source in sorted(texts):
285
+ other = source.removeprefix("repo/")
286
+ if Path(other).suffix.lower() not in CODE or trace.family(other) != trace.family(path):
287
+ continue
288
+ testing = is_test(other)
289
+ for number, row in enumerate(texts[source].splitlines(), 1):
290
+ if (other, number) == (path, span["start"]) or re.match(r"\s*(?:#|//|/?\*)", row):
291
+ continue
292
+ if testing and word.search(row):
293
+ tests.append({"path": other, "line": number, "text": row})
294
+ elif not testing and call.search(row) and not re.search(rf"\b(?:def|function|func|fn)\s+{re.escape(short)}\b", row):
295
+ inside = next((info["name"] for where, info in every if where == other
296
+ and info["start"] <= number <= info["end"] and info["end"] - info["start"] < 400), "")
297
+ calls.append((other, number, inside))
298
+ edges = getattr(getattr(knowledge, "dependencies", None), "edges", None) or {}
299
+ importers = sorted(other for other, targets in edges.items() if path in targets
300
+ and (short in targets[path] or "" in targets[path] or span["name"].split(".")[0] in targets[path]))
301
+ lines.append("")
302
+ if calls:
303
+ lines.append(f"Called from ({len(calls)} place{'s' if len(calls) != 1 else ''} outside the tests):")
304
+ for where, line, inside in calls[:PLACES]:
305
+ lines.append(f"- {where}:{line}" + (f", in `{inside}`" if inside else ""))
306
+ rows.append(evidence(where, line, short))
307
+ else:
308
+ lines.append("No call to it was found by name. It may be called through a variable, a decorator, or from outside "
309
+ "this project.")
310
+ if importers:
311
+ lines.append("")
312
+ lines.append(f"Files that import {path} ({len(importers)}):")
313
+ lines += [f"- {other}" for other in importers[:PLACES]]
314
+ lines.append("")
315
+ if tests:
316
+ test_files = sorted({match["path"] for match in tests})
317
+ lines.append(f"Tests that mention it ({len(test_files)} file{'s' if len(test_files) != 1 else ''}), to run after the change:")
318
+ for match in sorted(tests, key=lambda row: (row["path"], row["line"]))[:PLACES]:
319
+ lines.append(f"- {match['path']}:{match['line']}")
320
+ rows.append(evidence(match["path"], match["line"], match.get("text", "")))
321
+ else:
322
+ lines.append("No test mentions it by name, so a change to it is not checked by a test that names it.")
323
+ lines += ["", "Found by parsing and searching the code, not by running it: calls made through a variable or "
324
+ "inheritance are not seen."]
325
+ return {"text": "\n".join(lines), "evidence": rows}
@@ -0,0 +1,264 @@
1
+ """Search by meaning: passages are compared with the question as vectors from a local embedding model.
2
+
3
+ Keyword search finds "late fee" only where those words appear. An embedding model turns a passage into a list
4
+ of numbers that sits near passages with a similar meaning, so "where do we charge people who cancel late?" can
5
+ find a function named cancellation_penalty. CodeHaven mixes both rankings, so exact names still win.
6
+
7
+ The embedding model is a second, small Ollama model on this computer, reached over loopback like the chat model:
8
+ nothing leaves the machine. It is optional. Without one installed, or with --no-semantic, search works from key
9
+ words as before. Any failure here switches meaning search off for the session rather than failing an answer.
10
+
11
+ Vectors are kept in ~/CodeHaven/index, one file per repository, so only changed passages are embedded again.
12
+ The file holds numbers and hashes, never code text, is readable by this user only, and is not written with
13
+ --no-remember. Nothing is ever written inside the repository.
14
+ """
15
+ import contextlib
16
+ import hashlib
17
+ import json
18
+ import math
19
+ import os
20
+ import re
21
+ import tempfile
22
+ import threading
23
+ from array import array
24
+ from operator import mul
25
+ from pathlib import Path
26
+
27
+ INDEX_FOLDER = Path.home() / "CodeHaven" / "index"
28
+ # Tried in this order when --embed-model is not given; any other installed embedding model comes after them.
29
+ PREFERRED = ("nomic-embed-text", "embeddinggemma", "mxbai-embed-large", "bge-m3", "snowflake-arctic-embed", "all-minilm")
30
+ # Some models are trained with a short label before each text, and rank noticeably worse without it.
31
+ PREFIXES = {"nomic-embed-text": ("search_document: ", "search_query: "),
32
+ "embeddinggemma": ("title: none | text: ", "task: search result | query: "),
33
+ "mxbai-embed-large": ("", "Represent this sentence for searching relevant passages: ")}
34
+ BATCH = 16
35
+ PASSAGE_CHARS = 2000 # Passages are at most about 1,800 characters; this only guards against a surprise.
36
+ CANDIDATES = 24 # How many of the nearest passages take part in ranking.
37
+ FLOOR = 0.2 # Below this similarity a passage is unrelated, whatever its rank.
38
+ SAVE_EVERY = 480
39
+ FOLLOW_UP_WAIT = 3 # Seconds a question waits for passages changed since the last one.
40
+
41
+ # math.sumprod exists from Python 3.12; older versions use the slower plain sum.
42
+ dot = getattr(math, "sumprod", None) or (lambda a, b: sum(map(mul, a, b)))
43
+
44
+
45
+ def base_name(model):
46
+ """A model's plain name, without registry path or tag: "library/nomic-embed-text:latest" gives "nomic-embed-text"."""
47
+ return model.split(":", 1)[0].rsplit("/", 1)[-1].lower()
48
+
49
+
50
+ def choose_model(client, wanted=None):
51
+ """The embedding model to use: the one asked for, or the first preferred one installed. None when there is none.
52
+
53
+ Cloud-backed models are never used. A model asked for by name that is missing or cannot embed is an error.
54
+ """
55
+ from .model import cloud_name
56
+ if not hasattr(client, "request"):
57
+ return None
58
+ try:
59
+ listed = client.request("/api/tags").get("models", [])
60
+ except ValueError:
61
+ if wanted:
62
+ raise
63
+ return None # Meaning search is an extra: a server that cannot list models just leaves it off.
64
+ installed = []
65
+ for item in listed if isinstance(listed, list) else []:
66
+ name = item.get("name") if isinstance(item, dict) else None
67
+ if not isinstance(name, str) or cloud_name(name) or item.get("remote_host") or item.get("remote_model"):
68
+ continue
69
+ capabilities = item.get("capabilities")
70
+ # A server that does not list capabilities leaves only the model's name to judge by.
71
+ embeds = "embedding" in capabilities if isinstance(capabilities, list) else bool(re.search(r"embed|minilm|bge", name))
72
+ installed.append((name, embeds))
73
+ if wanted:
74
+ match = next((pair for pair in installed if pair[0] in (wanted, wanted + ":latest")), None)
75
+ if match is None:
76
+ raise ValueError(f"Embedding model {wanted!r} is not installed. Run: ollama pull {wanted} while online.")
77
+ if not match[1]:
78
+ raise ValueError(f"{wanted!r} is a chat model, not an embedding model; try nomic-embed-text.")
79
+ return match[0]
80
+ names = [name for name, embeds in installed if embeds]
81
+ rank = lambda name: next((i for i, known in enumerate(PREFERRED) if base_name(name) == known), len(PREFERRED))
82
+ return min(names, key=lambda name: (rank(name), name), default=None)
83
+
84
+
85
+ def normalised(vector):
86
+ """The vector scaled to length 1, as compact 32-bit floats, so the dot product of two is their cosine similarity."""
87
+ length = math.sqrt(sum(value * value for value in vector)) or 1.0
88
+ return array("f", (value / length for value in vector))
89
+
90
+
91
+ class Semantic:
92
+ """Vectors for one repository's passages, built in the background and ranked against a question."""
93
+
94
+ def __init__(self, client, model, *, cache=None, output=None):
95
+ """Set up for one embedding model and load the vectors saved at cache (a file path; None keeps nothing on disk)."""
96
+ self.client, self.model = client, model
97
+ self.cache = Path(cache) if cache else None
98
+ self.output = output or (lambda *_: None)
99
+ self.document_prefix, self.query_prefix = PREFIXES.get(base_name(model), ("", ""))
100
+ # vectors: passage key -> vector, for every passage embedded so far. keys: the current passages' keys, in index order.
101
+ self.vectors, self.keys = {}, []
102
+ self.failed = None
103
+ # generation counts index rebuilds, so an outdated background build can tell it was replaced. done is set while
104
+ # no build is running.
105
+ self.generation, self.thread, self.done = 0, None, threading.Event()
106
+ self.done.set()
107
+ self.lock = threading.Lock()
108
+ if hasattr(client, "companions"):
109
+ client.companions.add(model) # Not "another model competing for memory": it is ours.
110
+ self.load()
111
+
112
+ @staticmethod
113
+ def cache_path(workspace, model, folder=None):
114
+ """The vectors file for one repository and model: a readable folder name plus a hash of the full path and model."""
115
+ name = re.sub(r"[^\w.-]", "_", workspace.root.name, flags=re.ASCII)[:40] or "repository"
116
+ mark = hashlib.sha256(f"{workspace.root}\0{model}".encode()).hexdigest()[:12]
117
+ return (Path(folder).expanduser() if folder else INDEX_FOLDER) / f"{name}-{mark}.vectors"
118
+
119
+ def key(self, text):
120
+ """A passage's identity: a hash of the model and the text, so changed text or another model is embedded afresh."""
121
+ return hashlib.sha256(f"{self.model}\0{text}".encode()).hexdigest()[:24]
122
+
123
+ def embed(self, texts):
124
+ """Unit-length vectors for the texts, in order, from the local embedding model. ValueError for an unusable reply."""
125
+ result = self.client.request("/api/embed", {"model": self.model, "input": texts, "truncate": True, "keep_alive": "30m"})
126
+ vectors = result.get("embeddings")
127
+ if (not isinstance(vectors, list) or len(vectors) != len(texts)
128
+ or not all(isinstance(v, list) and v and all(isinstance(x, (int, float)) for x in v) for v in vectors)):
129
+ raise ValueError("The embedding model returned no usable vectors")
130
+ return [normalised(vector) for vector in vectors]
131
+
132
+ def start(self, entries):
133
+ """Give every passage its key and embed, in the background, the ones not known yet."""
134
+ with self.lock:
135
+ self.generation += 1
136
+ generation = self.generation
137
+ for entry in entries:
138
+ entry["vector_key"] = self.key(entry["text"])
139
+ self.keys = [entry["vector_key"] for entry in entries]
140
+ # Keyed by hash, so identical passages are embedded once.
141
+ missing = {}
142
+ for entry in entries:
143
+ if entry["vector_key"] not in self.vectors:
144
+ missing.setdefault(entry["vector_key"], entry["text"])
145
+ self.done.clear()
146
+ if not missing or self.failed:
147
+ self.done.set()
148
+ return
149
+ self.thread = threading.Thread(target=self.build, args=(generation, list(missing.items())), daemon=True)
150
+ self.thread.start()
151
+
152
+ def build(self, generation, missing):
153
+ """Background thread: embed the missing passages in batches, saving now and then so a stopped run keeps its work."""
154
+ added = 0
155
+ try:
156
+ for offset in range(0, len(missing), BATCH):
157
+ if generation != self.generation:
158
+ return # The files changed again; a newer build has taken over.
159
+ batch = missing[offset:offset + BATCH]
160
+ vectors = self.embed([self.document_prefix + text[:PASSAGE_CHARS] for _, text in batch])
161
+ for (key, _), vector in zip(batch, vectors):
162
+ self.vectors[key] = vector
163
+ added += len(batch)
164
+ if added % SAVE_EVERY == 0:
165
+ self.save()
166
+ self.save()
167
+ except (ValueError, OSError) as exc:
168
+ self.failed = str(exc)
169
+ self.output(f"Meaning search is off for this session ({exc}); answers use key-word search.")
170
+ finally:
171
+ if generation == self.generation:
172
+ self.done.set()
173
+
174
+ def wait(self, timeout=None, progress=None):
175
+ """Wait for the background build. With progress, report every few seconds. Returns True once it is complete."""
176
+ if progress is None:
177
+ return self.done.wait(timeout)
178
+ waited = 0
179
+ while not self.done.wait(5):
180
+ waited += 5
181
+ ready, total = self.coverage()
182
+ progress(f"Preparing meaning search: {ready} of {total} passages ready ({waited}s).")
183
+ if timeout is not None and waited >= timeout:
184
+ return False
185
+ return True
186
+
187
+ def coverage(self):
188
+ """(passages that have a vector, all passages) for the current index; used in progress messages."""
189
+ keys = self.keys
190
+ return sum(1 for key in keys if key in self.vectors), len(keys)
191
+
192
+ def rank(self, query, entries):
193
+ """Indexes of the passages nearest in meaning to the query, nearest first, as (similarity, index)."""
194
+ if self.failed or not self.vectors:
195
+ return []
196
+ self.done.wait(FOLLOW_UP_WAIT)
197
+ try:
198
+ wanted = self.embed([self.query_prefix + query[:PASSAGE_CHARS]])[0]
199
+ except (ValueError, OSError) as exc:
200
+ self.failed = str(exc)
201
+ self.output(f"Meaning search is off for this session ({exc}); answers use key-word search.")
202
+ return []
203
+ scored = []
204
+ for index, entry in enumerate(entries):
205
+ vector = self.vectors.get(entry.get("vector_key"))
206
+ if vector is not None and len(vector) == len(wanted):
207
+ # Both vectors have length 1, so their dot product is the cosine similarity.
208
+ similarity = dot(wanted, vector)
209
+ if similarity >= FLOOR:
210
+ scored.append((similarity, index))
211
+ scored.sort(key=lambda pair: (-pair[0], pair[1]))
212
+ return scored[:CANDIDATES]
213
+
214
+ def load(self):
215
+ """Read saved vectors. A missing, damaged, or mismatched file just means everything is embedded again."""
216
+ if self.cache is None:
217
+ return
218
+ try:
219
+ with open(self.cache, "rb") as handle:
220
+ # Layout: one JSON header line (model, dimensions, keys), then every vector as raw 32-bit floats, in key order.
221
+ header = json.loads(handle.readline(4_000_000))
222
+ raw = handle.read()
223
+ keys, size = header["keys"], header["dimensions"]
224
+ if header.get("model") != self.model or not isinstance(size, int) or not 1 <= size <= 8192:
225
+ return
226
+ values = array("f")
227
+ values.frombytes(raw)
228
+ if len(values) != len(keys) * size:
229
+ return
230
+ self.vectors = {key: values[index * size:(index + 1) * size] for index, key in enumerate(keys) if isinstance(key, str)}
231
+ except (OSError, ValueError, KeyError, TypeError):
232
+ self.vectors = {}
233
+
234
+ def save(self):
235
+ """Keep the vectors of the current passages, for this user only, replacing the file in one step."""
236
+ if self.cache is None:
237
+ return
238
+ keys = [key for key in dict.fromkeys(self.keys) if key in self.vectors]
239
+ if not keys:
240
+ return
241
+ # The flat layout needs every vector to have the same length.
242
+ size = len(self.vectors[keys[0]])
243
+ keys = [key for key in keys if len(self.vectors[key]) == size]
244
+ try:
245
+ self.cache.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
246
+ handle, partial = tempfile.mkstemp(prefix=".vectors-", dir=self.cache.parent) # Readable by this user only.
247
+ try:
248
+ with os.fdopen(handle, "wb") as file:
249
+ file.write(json.dumps({"model": self.model, "dimensions": size, "keys": keys}).encode() + b"\n")
250
+ for key in keys:
251
+ file.write(self.vectors[key].tobytes())
252
+ os.replace(partial, self.cache)
253
+ except BaseException:
254
+ with contextlib.suppress(OSError):
255
+ os.unlink(partial)
256
+ raise
257
+ except OSError:
258
+ pass # A cache that cannot be written only costs time on the next start.
259
+
260
+ def forget(self):
261
+ """Delete the saved vectors file, if there is one."""
262
+ with contextlib.suppress(OSError):
263
+ if self.cache is not None:
264
+ self.cache.unlink()
offline_agent/slash.py ADDED
@@ -0,0 +1,53 @@
1
+ """Slash commands: short forms of the requests CodeHaven has a purpose-built answer for, in the page and the terminal.
2
+
3
+ /trace checkout_total is the same as typing "Trace checkout_total". Each command only writes the request out in
4
+ full, so it is answered exactly as the typed request would be. /help lists them.
5
+ """
6
+ COMMANDS = {
7
+ "trace": ("Trace {}", "a function: what it calls and who calls it", True),
8
+ "review": ("Review {}", "a file, one function at a time", True),
9
+ "why": ("Why is {} here?", "a line, from Git history (give path:line)", True),
10
+ "impact": ("What breaks if I change {}?", "a function: its callers, importers, and tests", True),
11
+ "explain": ("Explain {}", "a file, function, or anything else", True),
12
+ "tour": ("Give me a project tour", "a reading order for the project", False),
13
+ "report": ("Write a project report", "reading order, structure, libraries, test gaps, and security, in one", False),
14
+ "onboard": ("Write an onboarding guide for a new developer", "how to run, test, and read the project", False),
15
+ "diagram": ("Draw an architecture diagram", "a Mermaid diagram of the imports (or /diagram name for calls)", False),
16
+ "deps": ("Which libraries does this project use?", "the libraries it declares and imports", False),
17
+ "scan": ("Run a security scan", "hard-coded secrets and risky code", False),
18
+ "gaps": ("Which functions have no tests?", "functions no test mentions", False),
19
+ "changes": ("Explain my uncommitted changes", "your Git changes", False),
20
+ "review-changes": ("Review my changes", "only the functions your changes touched", False),
21
+ "commit": ("Write a commit message for my changes", "a commit message, to copy", False),
22
+ "pr": ("Write a PR description for my changes", "a pull request description, to copy", False),
23
+ }
24
+
25
+
26
+ def expand(text):
27
+ """The full request for a slash command, the help text for /help, or text itself when it is not a command.
28
+
29
+ Raises ValueError for a command that needs an argument and has none, or an unknown command."""
30
+ stripped = text.strip()
31
+ if not stripped.startswith("/") or stripped.startswith("//"):
32
+ return text
33
+ name, _, argument = stripped[1:].partition(" ")
34
+ name, argument = name.lower(), argument.strip()
35
+ if name == "help":
36
+ return None
37
+ if name not in COMMANDS:
38
+ raise ValueError(f"Unknown command /{name}. Type /help to see the commands.")
39
+ template, _, needs = COMMANDS[name]
40
+ if name == "diagram" and argument:
41
+ return f"Draw a Mermaid diagram of the calls of {argument}"
42
+ if needs and not argument:
43
+ raise ValueError(f"/{name} needs something to work on, such as /{name} {'store.py' if name == 'review' else 'checkout_total'}.")
44
+ return template.format(argument) if needs else template
45
+
46
+
47
+ def help_text(extra=()):
48
+ """One line per command, for /help."""
49
+ lines = ["Commands (each is a short form of a request you could type in full):"]
50
+ for name, (_, what, needs) in COMMANDS.items():
51
+ lines.append(f" /{name}{' <name>' if needs else ''}: {what}")
52
+ lines += [f" {line}" for line in extra]
53
+ return "\n".join(lines)