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
@@ -0,0 +1,438 @@
1
+ """Checking and shaping what the model returns: a cited answer with looked-up line ranges, and readable tool output."""
2
+ import json
3
+ import re
4
+
5
+ from .evidence import CITATION
6
+ from .prompts import ACTIONS, ANSWER_CHARS, FINAL_ANSWER_CHARS, OVERVIEW_CHARS, POINT_CHARS, POINTS, SCHEMA
7
+ from .workspace import line_range, symbol_lines
8
+
9
+
10
+ # Notes added to an answer that was cut short, so the reader knows why it ends where it does.
11
+ REPEAT_NOTE = "[Answer stopped when it began repeating itself; only the text before the repetition is kept.]"
12
+ LIMIT_NOTE = "[Answer reached its length limit; it ends at its last complete sentence.]"
13
+
14
+
15
+ def trim_at_limit(text, limit):
16
+ """End an answer cut by its schema's maxLength at its last complete sentence. Returns (text, trimmed).
17
+
18
+ The cut lands mid-word, and Qwen often emits a stray Chinese token right at it.
19
+ """
20
+ # Shorter than the limit means the model stopped by itself, so there is nothing to trim.
21
+ if not isinstance(limit, int) or len(text) < limit:
22
+ return text, False
23
+ # Cut after the last sentence end; with none, fall back to the last whole word and mark the cut with an ellipsis.
24
+ end = max(text.rfind(mark) for mark in (". ", ".\n", "? ", "?\n", "! ", "!\n", ".)", ".`", "؟ ", "؟\n"))
25
+ if end > 0:
26
+ return text[:end + 1].rstrip(), True
27
+ return text[:text.rstrip().rfind(" ")].rstrip() + " …" if " " in text.strip() else text, True
28
+
29
+
30
+ # Sent back to the model after an unusable reply; {} is the problem that reply_problem found.
31
+ CORRECTION = ("Your previous reply was invalid: {}. No tool ran. Reply again with one JSON object containing exactly "
32
+ "action, path, content, and message as strings, where action is one of " + ", ".join(ACTIONS) + ".")
33
+
34
+
35
+ def reply_problem(reply, actions=ACTIONS):
36
+ """Describe why a model reply is not a usable action, or return None. actions are the ones on offer."""
37
+ if not isinstance(reply, dict):
38
+ return "the reply is not a JSON object"
39
+ missing = [key for key in SCHEMA["required"] if key not in reply]
40
+ if missing:
41
+ return "missing fields: " + ", ".join(missing)
42
+ extra = sorted(str(key) for key in reply if key not in SCHEMA["required"])
43
+ if extra:
44
+ return "unexpected fields: " + ", ".join(extra)[:120]
45
+ wrong = [key for key in SCHEMA["required"] if not isinstance(reply[key], str)]
46
+ if wrong:
47
+ return "fields must be strings: " + ", ".join(wrong)
48
+ if reply["action"] not in actions:
49
+ return f"unknown action {reply['action'][:40]!r}"
50
+ return None
51
+
52
+
53
+ def with_actions(schema, actions):
54
+ """A schema whose action field allows exactly actions; schema itself is left as it is."""
55
+ return {**schema, "properties": {**schema["properties"], "action": {"type": "string", "enum": list(actions)}}}
56
+
57
+
58
+ def cited_schema(paths=(), brief=False):
59
+ """Schema for questions and change requests: an answer, and points that each name a part of the code.
60
+
61
+ Explaining named files gets a short overview and points limited to those files. brief is for a plain question,
62
+ whose answer text is capped at ANSWER_CHARS; a change request keeps the room it needs to show new code.
63
+ """
64
+ # With named files, a point's path is limited to them, so the model cannot cite a file it was not shown.
65
+ point = {"type": "object", "additionalProperties": False,
66
+ "properties": {"path": {"type": "string", "enum": list(paths)} if paths else {"type": "string", "maxLength": 200},
67
+ "symbol": {"type": "string", "maxLength": 80},
68
+ "text": {"type": "string", "maxLength": POINT_CHARS}},
69
+ "required": ["path", "symbol", "text"]}
70
+ properties = {**SCHEMA["properties"],
71
+ "action": {"type": "string", "enum": list(ACTIONS)},
72
+ "content": {"type": "string", "maxLength": OVERVIEW_CHARS if paths else ANSWER_CHARS if brief else FINAL_ANSWER_CHARS},
73
+ "points": {"type": "array", "items": point, "maxItems": POINTS}}
74
+ return {**SCHEMA, "properties": properties, "required": SCHEMA["required"] + ["points"]}
75
+
76
+
77
+ def retrieved_rows(data):
78
+ """Evidence rows for a retrieval result: its passages, and the constant definitions shown with them."""
79
+ rows = []
80
+ for row in data["results"]:
81
+ rows.append({"path": row["source"], "line": row["start_line"], "end_line": row["end_line"], "text": row["text"]})
82
+ rows += [{"path": row["source"], "line": item["line"], "end_line": item["line"], "text": item["text"]}
83
+ for item in row.get("constants", ())]
84
+ return rows
85
+
86
+
87
+ def seen_span(path, span, evidence, symbol=""):
88
+ """Narrow a looked-up range to the lines the model saw, so a citation claims no more than was read."""
89
+ # Keep the largest overlap between the looked-up range and any range of that file the model was shown.
90
+ overlaps = []
91
+ for row in evidence:
92
+ if row["path"].removeprefix("repo/") == path:
93
+ start, end = max(span[0], row["line"]), min(span[1], row.get("end_line", row["line"]))
94
+ if start <= end:
95
+ overlaps.append((end - start, start, end))
96
+ if overlaps:
97
+ _, start, end = max(overlaps)
98
+ return start, end
99
+ # A search match names its enclosing function, so citing that function can point at the match the model saw.
100
+ named = next((row for row in evidence if row["path"].removeprefix("repo/") == path and symbol and row.get("in")
101
+ and row["in"].rsplit(".", 1)[-1] == symbol.rsplit(".", 1)[-1].removesuffix("()")), None)
102
+ return (named["line"], named["line"]) if named else span
103
+
104
+
105
+ def row_text(row, workspace=None, files=None):
106
+ """The text of the lines an evidence row covers.
107
+
108
+ Retained rows keep only a short snippet, to stay small in the prompt, so the lines are read again from the
109
+ workspace when it is given. files caches each file's lines for one answer. Reference documents outside the
110
+ workspace, which cannot be read this way, give their snippet or nothing.
111
+ """
112
+ if row.get("text"):
113
+ return str(row["text"])
114
+ if workspace is None:
115
+ return str(row.get("snippet") or "")
116
+ path = row["path"].removeprefix("repo/")
117
+ if files is None:
118
+ files = {}
119
+ if path not in files:
120
+ try:
121
+ files[path] = workspace.read(path).splitlines()
122
+ except (ValueError, OSError, UnicodeError):
123
+ files[path] = None
124
+ lines = files[path]
125
+ if lines is None:
126
+ return str(row.get("snippet") or "")
127
+ return "\n".join(lines[row["line"] - 1:row.get("end_line", row["line"])])
128
+
129
+
130
+ def observed_line(symbol, path, evidence, workspace=None, files=None):
131
+ """(path, line) of a line the model was shown that contains the symbol's name, or None. The point's own file comes first.
132
+
133
+ The model names the right thing but often the wrong place: the file that imports a constant instead of the one
134
+ that sets it, or the line of an import. When the lines it was actually shown contain the name, citing one of
135
+ those is both true and checkable, where the looked-up line would be flagged as never read. A dotted name such
136
+ as req.secure is matched by its last part, which is how it appears where it is defined.
137
+ """
138
+ short = symbol.strip("`'\" ").removesuffix("()").rsplit(".", 1)[-1]
139
+ if len(short) < 3:
140
+ return None
141
+ named = re.compile(rf"(?<![\w$]){re.escape(short)}(?![\w$])")
142
+ rows = sorted(evidence, key=lambda row: row["path"].removeprefix("repo/") != path) # Stable: the point's own file first.
143
+ for row in rows:
144
+ for offset, text in enumerate(row_text(row, workspace, files).splitlines()):
145
+ if named.search(text) and row["line"] + offset <= row.get("end_line", row["line"]):
146
+ return row["path"].removeprefix("repo/"), row["line"] + offset
147
+ return None
148
+
149
+
150
+ # Code-like names in an answer: anything in backticks, or a word with an underscore, a dot between words, or camelCase.
151
+ MENTION = re.compile(r"`([^`\n]{2,60})`|(?<![\w.$/])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+|[A-Za-z$]\w*_\w+|[a-z]+[A-Z]\w*)(?![\w$/])")
152
+ # The most citations added for one answer, and the heading they are listed under.
153
+ MENTIONS = 4
154
+ MENTION_HEADING = "Lines this answer refers to (cited by CodeHaven from the code it was shown):"
155
+
156
+
157
+ def cite_mentions(answer, workspace, evidence):
158
+ """Citation lines for the code names an answer mentions, taken from the lines the model was shown.
159
+
160
+ For an answer that cites nothing at all. The model often writes a correct sentence about checkout_total
161
+ without a citation; pointing at the shown line that names it lets the reader check the answer, which is
162
+ the point of the check. Names that appear on no shown line add nothing, so nothing is made up.
163
+ """
164
+ found, files = [], {}
165
+ for quoted, bare in MENTION.findall(answer):
166
+ name = (quoted or bare).strip()
167
+ # File names and paths are not code parts; a call such as f(x) is looked up as f.
168
+ name = re.sub(r"\(.*\)$", "", name)
169
+ if not name or "/" in name or re.search(r"\.(py|js|ts|go|java|rs|md|json|txt)$", name) or " " in name:
170
+ continue
171
+ seen = observed_line(name, "", evidence, workspace, files)
172
+ if seen and all(seen != (path, line) for path, line, _ in found):
173
+ found.append((seen[0], seen[1], name))
174
+ if len(found) >= MENTIONS:
175
+ break
176
+ return [f"- {path}:{line} `{name}`" for path, line, name in found]
177
+
178
+
179
+ def file_named(workspace, path, symbol, files):
180
+ """The workspace file a point names, when the point is about a whole file rather than a part of one.
181
+
182
+ Overviews often name files as their parts ("gpt.py"), sometimes beside the wrong folder. files() is a
183
+ one-item cache of the workspace listing, filled only when a name has to be looked up across the project.
184
+ """
185
+ name = symbol.strip("`'\" ").removeprefix("repo/").removeprefix("./")
186
+ # No symbol names no file; a symbol equal to the point's own path or file name means that file.
187
+ if not name or name in (path, path.rsplit("/", 1)[-1]):
188
+ return path if name else None
189
+ # Otherwise it must look like a file: it has an extension, and a bare name has a lowercase one (Store.add is not a file).
190
+ if not re.search(r"\.\w{1,8}$", name) or "/" not in name and not re.search(r"\.[a-z]{1,5}$", name):
191
+ return None
192
+ if not files:
193
+ files.append(workspace.files())
194
+ # Accepted only when exactly one workspace file matches the name.
195
+ matches = [f for f in files[0] if f == name or f.endswith("/" + name)]
196
+ return matches[0] if len(matches) == 1 else None
197
+
198
+
199
+ # Literal values an answer states as facts: a quoted string, or a number with two or more digits or a dot in it
200
+ # (0.08, 3.1.0, 302). Single digits and booleans are left out: they are often worked out rather than written in
201
+ # the code (cobra's ShellCompDirectiveError is 1 << iota), so a missing one would be a false alarm.
202
+ QUOTED_VALUE = re.compile(r"""(?<![\w])['"]([^'"\n]{2,40})['"](?![\w])""")
203
+ NUMBER_VALUE = re.compile(r"(?<![\w.:/-])(\d+\.\d+(?:\.\d+)*|\d{2,})(?![\w.]*\w)")
204
+ # A number right after one of these words is a line number the answer mentions, not a value from the code.
205
+ LINE_WORD = re.compile(r"\b(?:lines?(?:\s+(?:are|is|from|between))?|at|to|through|and)\s*$|-\s*$", re.I)
206
+ # Neither is the first number of a range such as "348-351", nor a percentage, which the code writes as a fraction.
207
+ NOT_A_VALUE_AFTER = re.compile(r"\s*(?:-\s*\d|%|percent\b)", re.I)
208
+ # Paths and file names are not values; citations already check those.
209
+ PATH_LIKE = re.compile(r"[/\\]|\.[A-Za-z]{1,5}$")
210
+ # How far around a cited range a value may sit: answers cite a definition and quote a value a line or two away.
211
+ VALUE_REACH = 3
212
+ VALUE_HEADING = "Where the values this answer reports are in the code (cited by CodeHaven):"
213
+
214
+
215
+ def literal_values(answer, task=""):
216
+ """(kind, value) for each literal an answer reports, once each, without those the question itself states."""
217
+ prose = CITATION.sub(" ", answer)
218
+ found = []
219
+ for value in QUOTED_VALUE.findall(prose):
220
+ if not PATH_LIKE.search(value) and value.strip() == value:
221
+ found.append(("text", value))
222
+ for match in NUMBER_VALUE.finditer(prose):
223
+ if not (LINE_WORD.search(prose[max(0, match.start() - 16):match.start()])
224
+ or NOT_A_VALUE_AFTER.match(prose, match.end())):
225
+ found.append(("number", match.group(1)))
226
+ unique = []
227
+ for kind, value in found:
228
+ if (kind, value) not in unique and not contains(kind, value, task):
229
+ unique.append((kind, value))
230
+ return unique
231
+
232
+
233
+ def contains(kind, value, text):
234
+ """True when value appears in text: a number not inside a longer number, a string exactly.
235
+
236
+ Only digits bound a number, so 422 is found in HTTP_422_UNPROCESSABLE_ENTITY, a constant that holds it.
237
+ """
238
+ if kind == "number":
239
+ return re.search(rf"(?<![\d.]){re.escape(value)}(?!\d|\.\d)", text) is not None
240
+ return value in text
241
+
242
+
243
+ def check_values(answer, task, workspace, evidence):
244
+ """Check each literal value an answer reports against the code. Returns (citation lines to add, invented values).
245
+
246
+ A value on or near a line the answer cites is fine. A value the model was shown, but on a line the answer does
247
+ not cite, gets a citation of the line it is on, so the answer can be checked where the value really is; nothing
248
+ is flagged, because the answer is often right and only cited the wrong line. A value on no line the model was
249
+ shown was not read from the code: it is returned as invented, and the answer is then marked unverified.
250
+ The check cannot tell a value read from the wrong place, such as a default from a neighbouring class, from the
251
+ right one; it confirms where a value comes from, not that it answers the question.
252
+ """
253
+ files = {}
254
+ near = []
255
+ for path, start, end in CITATION.findall(answer):
256
+ row = {"path": path.removeprefix("repo/"), "line": max(1, int(start) - VALUE_REACH),
257
+ "end_line": int(end or start) + VALUE_REACH}
258
+ near.append(row_text(row, workspace, files))
259
+ near_text = "\n".join(near)
260
+ shown = []
261
+ for row in evidence:
262
+ text = row_text(row, workspace, files)
263
+ shown += [(row["path"].removeprefix("repo/"), row["line"] + offset, line)
264
+ for offset, line in enumerate(text.splitlines()) if row["line"] + offset <= row.get("end_line", row["line"])]
265
+ added, invented = [], []
266
+ for kind, value in literal_values(answer, task):
267
+ if contains(kind, value, near_text):
268
+ continue
269
+ where = next(((path, number) for path, number, line in shown if contains(kind, value, line)), None)
270
+ if where is None:
271
+ invented.append(value)
272
+ elif all(where != (path, number) for path, number, _ in added):
273
+ added.append((where[0], where[1], value))
274
+ return [f"- {path}:{number} `{value}`" for path, number, value in added], invented
275
+
276
+
277
+ def with_points(reply, workspace, evidence=()):
278
+ """Fold points into a finish answer as "- path:start-end `symbol`: text" lines.
279
+
280
+ The line range comes from looking the symbol up in the file, so a citation is never a number the model
281
+ made up. Returns the reply and the (path, symbol) pairs that name nothing in their file.
282
+ """
283
+ # points is always removed, so what is left has exactly the fields of the plain SCHEMA that reply_problem expects.
284
+ points = reply.pop("points", None) if isinstance(reply, dict) else None
285
+ if not isinstance(points, list) or reply.get("action") != "finish" or not isinstance(reply.get("content"), str):
286
+ return reply, []
287
+ lines, missing, files = [], [], []
288
+ for point in points:
289
+ # A malformed or empty point is skipped; the rest of the answer is still used.
290
+ if not isinstance(point, dict) or not all(isinstance(point.get(key), str) for key in ("path", "symbol", "text")):
291
+ continue
292
+ path, symbol, text = point["path"].removeprefix("repo/"), point["symbol"].strip(), point["text"].strip()
293
+ if not text:
294
+ continue
295
+ whole = file_named(workspace, path, symbol, files)
296
+ try:
297
+ if whole: # A point about a whole file cites the file, narrowed to the lines the model saw.
298
+ path = whole
299
+ span = seen_span(path, (1, max(1, len(workspace.read(path).splitlines()))), evidence)
300
+ else:
301
+ span = symbol_lines(path, workspace.read(path), symbol)
302
+ span = span and seen_span(path, span, evidence, symbol)
303
+ # Looked up, but on lines the model never saw (or not found at all): cite a shown line that names it instead.
304
+ shown = any(row["path"].removeprefix("repo/") == path and span and row["line"] <= span[1]
305
+ and span[0] <= row.get("end_line", row["line"]) for row in evidence)
306
+ seen = None if shown else observed_line(symbol, path, evidence, workspace)
307
+ if seen:
308
+ path, span = seen[0], (seen[1], seen[1])
309
+ except (ValueError, OSError, UnicodeError):
310
+ # Not a workspace file; it may be a retrieved reference document such as user/team.md.
311
+ reference = next((row for row in evidence if row["path"] == point["path"]), None)
312
+ span = reference and (reference["line"], reference.get("end_line", reference["line"]))
313
+ if span is None:
314
+ line = f"- {path} `{symbol}` (not found in the file): {text}"
315
+ else:
316
+ line = f"- {path}:{span[0]}" + (f"-{span[1]}" if span[1] != span[0] else "") + f" `{symbol}`: {text}"
317
+ if line not in lines:
318
+ lines.append(line)
319
+ if span is None:
320
+ missing.append((path, symbol))
321
+ reply["content"] = "\n".join([reply["content"].strip(), *lines]).strip()
322
+ return reply, missing
323
+
324
+
325
+ def action_key(reply):
326
+ """Ignore narration when detecting repeated lookups; read content only matters as a line range."""
327
+ content = reply.get("content", "")
328
+ if reply.get("action") == "read":
329
+ try:
330
+ content = line_range(content)
331
+ except ValueError:
332
+ pass
333
+ return (reply.get("action"), reply.get("path", ""), content)
334
+
335
+
336
+ # Search matches printed to the terminal; the model still receives all of them.
337
+ SHOWN_ROWS = 20
338
+
339
+
340
+ def clip(text, width=100):
341
+ """Put text on one line and shorten it to at most width characters."""
342
+ text = " ".join(text.split())
343
+ return text if len(text) <= width else text[:width - 1] + "…"
344
+
345
+
346
+ def format_search(data):
347
+ """Readable terminal view of a search result; the model still receives the full JSON."""
348
+ matches = data["matches"]
349
+ limited = data.get("limit_reached") or data.get("candidate_limit_reached")
350
+ skipped = f", {data['files_skipped']} skipped" if data.get("files_skipped") else ""
351
+ lines = [f"Found {len(matches)} match{'es' if len(matches) != 1 else ''} for {json.dumps(data.get('query', ''))} "
352
+ f"in {data.get('scope', '.')} ({data.get('files_searched', 0)} files searched{skipped})"
353
+ + ("; results limited" if limited else "")]
354
+ width = max((len(f"{m['path']}:{m['line']}") for m in matches[:SHOWN_ROWS]), default=0)
355
+ lines += [f" {m['path'] + ':' + str(m['line']):<{width}} {clip(m['text'])}"
356
+ + (f" (in {m['in']})" if m.get("in") and not m.get("defines") else "") for m in matches[:SHOWN_ROWS]]
357
+ if len(matches) > SHOWN_ROWS:
358
+ lines.append(f" … {len(matches) - SHOWN_ROWS} more matches passed to the model")
359
+ return "\n".join(lines)
360
+
361
+
362
+ def format_retrieval(data):
363
+ """Readable terminal view of retrieved passages; the model still receives the full JSON."""
364
+ rows = data["results"]
365
+ limited = data.get("budget_limited") or data.get("results_limited")
366
+ lines = [f"Retrieved {len(rows)} passage{'s' if len(rows) != 1 else ''} "
367
+ f"({data.get('context_bytes', 0):,} of {data.get('context_budget_bytes', 0):,} bytes)"
368
+ + ("; results limited" if limited else "")]
369
+ labels = [f"{row['source']}:{row['start_line']}-{row['end_line']}" for row in rows]
370
+ width = max(map(len, labels), default=0)
371
+ for label, row in zip(labels, rows):
372
+ detail = (f"score {row.get('score', 0):.2f}" if row.get("kind", "match") == "match"
373
+ else f"{row.get('kind', 'passage')} via {row.get('via', '?')}")
374
+ if row.get("symbol"):
375
+ detail += f", {row['symbol']}" + ("" if row.get("symbol_complete") else " (partial)")
376
+ lines.append(f" {label:<{width}} {detail}")
377
+ return "\n".join(lines)
378
+
379
+
380
+ def format_metrics(metrics):
381
+ """One-line model timing and token summary from Ollama's reported metrics."""
382
+ parts = []
383
+ phases = [f"{name} {metrics[key]:.1f}s" for key, name in
384
+ (("load_seconds", "load"), ("prompt_seconds", "prompt"), ("generation_seconds", "generation"))
385
+ if key in metrics]
386
+ if "total_seconds" in metrics:
387
+ parts.append(f"{metrics['total_seconds']:.1f}s total" + (f" ({', '.join(phases)})" if phases else ""))
388
+ elif phases:
389
+ parts.append(", ".join(phases))
390
+ if "prompt_tokens" in metrics:
391
+ cached = metrics.get("cached_tokens")
392
+ parts.append(f"{metrics['prompt_tokens']:,} prompt tokens"
393
+ + (f" ({cached:,} cached)" if isinstance(cached, int) else ""))
394
+ if "generated_tokens" in metrics:
395
+ rate = metrics.get("tokens_per_second")
396
+ parts.append(f"{metrics['generated_tokens']:,} generated" + (f" at {rate:.1f} tok/s" if rate else ""))
397
+ return "Ollama metrics: " + ("; ".join(parts) or "no timings or token counts reported")
398
+
399
+
400
+ # The most imports of missing code one answer lists; more than this says the answer leans on a whole library.
401
+ MISSING_SHOWN = 6
402
+ MISSING_HEADING = ("Code these lines use that is not in this repository, so what it does is not shown here "
403
+ "(found by CodeHaven from the imports):")
404
+
405
+
406
+ def missing_code(answer, workspace, knowledge):
407
+ """Notes on the code an answer's cited lines use but the repository does not hold: a library that is not
408
+ installed in it, or a relative import of a file that is not there.
409
+
410
+ Only imports whose name appears on a cited line count, so a file's unrelated imports are left out. The notes
411
+ name the import's line in words, not as a path:line citation, so they are never mistaken for evidence the
412
+ answer relies on.
413
+ """
414
+ missing = getattr(getattr(knowledge, "dependencies", None), "missing", None)
415
+ if not missing or not answer:
416
+ return []
417
+ cited = {}
418
+ for path, start, end in CITATION.findall(answer):
419
+ if path in missing:
420
+ cited.setdefault(path, []).append((int(start), int(end or start)))
421
+ notes, seen = [], set()
422
+ for path, ranges in cited.items():
423
+ try:
424
+ lines = workspace.read(path).splitlines()
425
+ except (ValueError, OSError, UnicodeError):
426
+ continue
427
+ shown = "\n".join(line for start, end in ranges for line in lines[max(0, start - 1):end])
428
+ for row in missing[path]:
429
+ used = re.search(rf"(?<![\w.$]){re.escape(row['name'])}(?![\w$])", shown)
430
+ on_import = any(start <= row["line"] <= end for start, end in ranges)
431
+ if not (used or on_import) or (path, row["module"]) in seen:
432
+ continue
433
+ seen.add((path, row["module"]))
434
+ what = "a file this repository does not have" if row["local"] else "not part of this repository"
435
+ notes.append(f"- `{row['module']}` ({what}), imported as `{row['name']}` on line {row['line']} of {path}")
436
+ if len(notes) >= MISSING_SHOWN:
437
+ return notes
438
+ return notes
@@ -0,0 +1,106 @@
1
+ """Arabic questions: telling that a task is in Arabic, reading what it asks for, and matching its words in search.
2
+
3
+ Everything here works on text that normalise() has been through, so one spelling stands for all the ways a
4
+ word is typed: with or without short vowels, with any form of alef, and with a final ى or ة. The patterns
5
+ below are written in that spelling (اين, not أين).
6
+
7
+ Code is still written in Latin letters, so an Arabic question finds code through the names it mentions, through
8
+ search by meaning, and through Arabic comments, strings, and documentation in the project.
9
+ """
10
+ import re
11
+
12
+ MARKS = re.compile(r"[ؐ-ًؚ-ٰٟۖ-ۭـ]") # Short vowels and other marks, and the stretching dash.
13
+ FOLD = str.maketrans({"أ": "ا", "إ": "ا", "آ": "ا", "ٱ": "ا", "ى": "ي", "ة": "ه",
14
+ **{chr(0x0660 + digit): str(digit) for digit in range(10)}, # ٠-٩
15
+ **{chr(0x06F0 + digit): str(digit) for digit in range(10)}}) # ۰-۹
16
+ WORD = re.compile(r"[ء-ي]+")
17
+ LATIN_WORD = re.compile(r"[A-Za-z]+")
18
+ # Quoted text and code are what a question is about, not the language it is asked in.
19
+ QUOTED = re.compile(r"`[^`\n]*`|\"[^\"\n]*\"|'[^'\n]*'|«[^»\n]*»|\S*[/\\.]\S*|\S*[_\d]\S*")
20
+
21
+ PREFIXES = ("وال", "بال", "كال", "فال", "لل", "ال")
22
+ SUFFIXES = ("ها", "ان", "ات", "ون", "ين", "يه", "ه", "ي")
23
+
24
+ # "The text of every point" made the 7B model paste the code into each point; "what it does" keeps it a description.
25
+ ANSWER_IN_ARABIC = ("The user wrote in Arabic, so answer in Arabic: write content in Arabic, and in each point say in one "
26
+ "short Arabic sentence what that part does. Keep file paths, names from the code, and path:line "
27
+ "citations exactly as written, in Latin letters and Western digits; never translate a name from the code. "
28
+ "Do not repeat a sentence.")
29
+ WRITE_IN_ARABIC = "Write every sentence you return in Arabic, keeping names from the code exactly as they are written."
30
+
31
+ _POLITE = r"(?:من فضلك|لو سمحت|رجاء|فضلا|ممكن|هل يمكنك|هل يمكن|هل تستطيع|هل بامكانك|يا ريت)[\s،,]*(?:ان\s+)?"
32
+ POLITE = re.compile(rf"\W*{_POLITE}")
33
+ QUESTION = re.compile(r"\W*(?:ما|ماذا|ماهو|ماهي|من|اين|متي|لماذا|كيف|هل|كم|اي|اشرح|وضح|صف|لخص|اعرض|اظهر|اذكر|عدد|ابحث|جد|اوجد"
34
+ r"|حدد|افحص|راجع|اخبرني|قل لي|عرفني|ليه|ازاي|فين|ايه|وين|شو|ايش|وش)\b")
35
+ # Commands and the nouns made from them ("أصلح الخطأ", "هل يمكنك إصلاح الخطأ"). غير also means "not", so it
36
+ # counts only where a command stands: at the start. A command may carry "and" (وأصلح).
37
+ EDIT = re.compile(r"\b[وف]?(?:اصلح|صلح|صحح|عدل|حدث|اضف|احذف|ازل|امسح|انشئ|اكتب|نفذ|استبدل|اجعل|حول|انقل"
38
+ r"|اصلاح|تصحيح|تغيير|تعديل|تحديث|اضافه|حذف|ازاله|انشاء|كتابه|تنفيذ|استبدال|تحويل|نقل|اعاده)\b|^\W*غير\b")
39
+ NEGATED_EDIT = re.compile(r"\b(?:لا\s+ت|(?:بدون|دون|من غير)\s+(?:ال)?)\w+")
40
+ REVIEW = re.compile(rf"^\W*(?:{_POLITE})?(?:راجع|مراجعه|افحص|فحص|دقق|تدقيق|انقد)\b"
41
+ r"|\b(?:ابحث عن|جد|اوجد|ايجاد|اكتشف)\s+(?:اي\s+)?(?:ال)?(?:اخطاء|مشاكل|عيوب|ثغرات)\s+(?:في|ب)")
42
+
43
+ _LAST = r"(?:اخر|احدث|الاخير|الاخيره|السابق|السابقه)"
44
+ _COMMIT = r"(?:commit|كوميت|ايداع|الكوميت|الايداع|التزام|الالتزام)"
45
+ SINCE = re.compile(rf"\bمنذ\s+(?:{_LAST}\s+{_COMMIT}|{_COMMIT}\s+{_LAST})")
46
+ STAGED = re.compile(r"\b(?:ال)?(?:تغييرات|تعديلات)\s+ال(?:مرحله|مجهزه|مضافه)\b|\bstaged\b", re.I)
47
+ UNCOMMITTED = re.compile(r"\bغير\s+(?:ال)?(?:مودعه|مثبته|ملتزمه|محفوظه)\b|\bلم\s+(?:يتم\s+)?(?:ايداع|تثبيت|حفظ)"
48
+ r"|\b(?:تغييراتي|تعديلاتي)\b|\b(?:ال)?(?:تغييرات|تعديلات)\s+(?:الحاليه|المحليه|الاخيره)\b"
49
+ r"|\bماذا\s+(?:غيرت|عدلت)\b|\bما\s+الذي\s+(?:غيرته|عدلته|غيرت|عدلت)\b|\bgit\s+diff\b", re.I)
50
+ LAST_COMMIT = re.compile(rf"\b(?:{_LAST}\s+{_COMMIT}|{_COMMIT}\s+{_LAST})\b|\bgit\s+show\b", re.I)
51
+
52
+ GAPS = re.compile(r"\b(?:بدون|دون|بلا|ليس لها|ليس له|لا تملك|ينقصها|تنقصها)\s+(?:اي\s+)?(?:ال)?اختبار(?:ات)?\b"
53
+ r"|\bغير\s+(?:ال)?(?:مختبره|مختبر|مغطاه|مغطي)\b|\bلم\s+(?:يتم\s+)?(?:اختبار|تختبر|يختبر)"
54
+ r"|\b(?:فجوات|ثغرات|نواقص)\s+(?:ال)?اختبار(?:ات)?\b|\bتغطيه\s+(?:ال)?اختبار(?:ات)?\b")
55
+ TOUR = re.compile(r"\bجوله\s+(?:في|داخل|علي|حول)\b|\bجوله\s+(?:ال)?(?:مشروع|كود|مستودع)\b"
56
+ r"|\bمن\s+اين\s+(?:ابدا|ابدء|نبدا|يجب ان ابدا)\b|\b(?:ماذا|ما الذي)\s+(?:يجب ان\s+)?اقرا\s+اولا\b"
57
+ r"|\b(?:اي|ما)\s+(?:ال)?ملفات\s+(?:التي\s+)?(?:يجب ان\s+)?اقرا(?:ها)?\s+اولا\b|\bترتيب\s+(?:ال)?قراءه\b")
58
+
59
+ # Words that say nothing about which code a question concerns, as stem() returns them.
60
+ _COMMON = """ما ماذا من اين متي لماذا كيف هل كم اي في علي الي عن مع هذا هذه ذلك تلك هو هي التي الذي ان او و ثم لكن كل بعض
61
+ اشرح وضح صف اعرض اذكر اخبرني لي كود ملف داله دوال صنف مشروع مستودع يعمل تعمل يقوم تقوم"""
62
+
63
+
64
+ def normalise(text):
65
+ """One spelling for each word: no short vowels or stretching, one alef, ي for ى, ه for ة, and Western digits."""
66
+ return MARKS.sub("", text).translate(FOLD)
67
+
68
+
69
+ def stem(word):
70
+ """Drop "the" and the common endings from a normalised word, so الدوال finds دوال and ملفات finds ملف."""
71
+ for prefix in PREFIXES:
72
+ if word.startswith(prefix) and len(word) - len(prefix) >= 3:
73
+ word = word[len(prefix):]
74
+ break
75
+ for suffix in SUFFIXES:
76
+ if word.endswith(suffix) and len(word) - len(suffix) >= 3:
77
+ return word[:-len(suffix)]
78
+ return word
79
+
80
+
81
+ COMMON = frozenset(stem(word) for word in normalise(_COMMON).split())
82
+
83
+
84
+ def written_in(task):
85
+ """Whether a task is asked in Arabic. Quoted text, paths, and code names do not count either way."""
86
+ plain = QUOTED.sub(" ", task)
87
+ arabic, latin = len(WORD.findall(plain)), len(LATIN_WORD.findall(plain))
88
+ return arabic >= 2 and arabic * 2 >= latin or 0 < arabic >= latin
89
+
90
+
91
+ def counted(number, one, two, few, many):
92
+ """A count with its noun. Arabic has a form for one, for two, for 3 to 10 (few), and for 11 or more (many)."""
93
+ if number in (1, 2):
94
+ return one if number == 1 else two
95
+ return f"{number} {few if 3 <= number % 100 <= 10 else many}"
96
+
97
+
98
+ FUNCTIONS = ("دالة واحدة", "دالتان", "دوال", "دالة")
99
+ PARTS = ("جزء واحد", "جزءان", "أجزاء", "جزءًا")
100
+ FILES = ("ملف واحد", "ملفان", "ملفات", "ملفًا")
101
+ FUNCTIONS = ("دالة واحدة", "دالتان", "دوال", "دالة")
102
+
103
+
104
+ def note(task):
105
+ """What to add to a prompt so the model answers an Arabic task in Arabic; nothing for other tasks."""
106
+ return "\n\n" + ANSWER_IN_ARABIC if written_in(task) else ""