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,228 @@
1
+ """Read what changed in a Git repository, so "what changed in my last commit?" can be answered from the diff.
2
+
3
+ Everything here only reads: git is asked for a diff, never to stage, commit, check out, or fetch, and it is told
4
+ not to refresh its index file, so not even .git is written. Nothing uses the network. Files the workspace rules
5
+ hide, such as .env or --exclude patterns, are left out of the diff just as they are left out of reads.
6
+
7
+ The repository's own settings are untrusted, so the ones that could make git start another program while
8
+ diffing (an external diff tool, a text converter, a file-system monitor, signature checks) are switched off.
9
+ """
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+
15
+ from . import arabic
16
+
17
+ GIT_SECONDS = 20
18
+ OUTPUT_BYTES = 400_000 # The most read from one git command.
19
+ # Changed files listed, untracked files named, and characters of a commit message's body shown.
20
+ LISTED_FILES, UNTRACKED_SHOWN, MESSAGE_CHARS = 30, 12, 400
21
+ CONTEXT_LINES = 2 # Less than git's usual 3, so more of a small prompt goes to the changed lines themselves.
22
+
23
+ SINCE = re.compile(r"\bsince\s+(?:the|my|our)?\s*(?:last|latest|previous|most recent)\s+commit\b", re.I)
24
+ STAGED = re.compile(r"\bstaged\b(?!\s+rollout)|\bgit\s+diff\s+--(?:cached|staged)\b", re.I)
25
+ UNCOMMITTED = re.compile(
26
+ r"\b(?:uncommitted|unstaged)\s+(?:changes|edits|work|code|files|lines|diff)\b|\bnot\s+(?:yet\s+)?committed\b"
27
+ r"|\bgit\s+diff\b|\bworking[ -](?:tree|copy|directory)\s+(?:changes|diff)\b"
28
+ r"|\b(?:my|our)\s+(?:current|local|latest|recent|pending)?\s*(?:changes|edits|diff)\b"
29
+ r"|\bwhat\s+(?:have|did)\s+i\s+(?:just\s+)?(?:change|changed|edit|edited|modify|modified)\b"
30
+ r"|\bchanges\s+i(?:'ve|\s+have)?\s+(?:just\s+)?made\b", re.I)
31
+ LAST_COMMIT = re.compile(r"\b(?:last|latest|most\s+recent|previous|newest)\s+commit\b|\bgit\s+show\b|\bHEAD\s+commit\b", re.I)
32
+ NAMED_COMMIT = re.compile(r"\bcommit\s+`?([0-9a-f]{7,40})\b`?|`?\b([0-9a-f]{7,40})\b`?\s+commit\b", re.I)
33
+
34
+
35
+ class NoChanges(ValueError):
36
+ """There is nothing to explain; the message says why and is shown as the answer."""
37
+
38
+
39
+ def requested(task):
40
+ """What a task asks about: ("uncommitted", None), ("staged", None), ("commit", ref), or None for other tasks."""
41
+ named = NAMED_COMMIT.search(task)
42
+ if named:
43
+ return "commit", (named.group(1) or named.group(2)).lower()
44
+ plain = arabic.normalise(task) # The same questions asked in Arabic are read from this.
45
+ if SINCE.search(task) or arabic.SINCE.search(plain):
46
+ return "uncommitted", None
47
+ if STAGED.search(task) or arabic.STAGED.search(plain):
48
+ return "staged", None
49
+ if LAST_COMMIT.search(task) or arabic.LAST_COMMIT.search(plain):
50
+ return "commit", "HEAD"
51
+ if UNCOMMITTED.search(task) or arabic.UNCOMMITTED.search(plain):
52
+ return "uncommitted", None
53
+ return None
54
+
55
+
56
+ def git(root, *arguments):
57
+ """Run one read-only git command in root and return its output as text."""
58
+ program = shutil.which("git")
59
+ if program is None:
60
+ raise NoChanges("Git is not installed on this computer, so CodeHaven cannot read commits or changes.")
61
+ # --no-optional-locks (and GIT_OPTIONAL_LOCKS=0 below): the index file is not refreshed, so .git is not written.
62
+ # core.fsmonitor and core.hooksPath: a setting of the repository must not make git start another program.
63
+ # core.quotePath=false keeps non-ASCII file names as they are. No pager, colours, or signature checks.
64
+ command = [program, "-C", str(root), "--no-pager", "--no-optional-locks",
65
+ "-c", "core.fsmonitor=false", "-c", f"core.hooksPath={os.devnull}", "-c", "core.quotePath=false",
66
+ "-c", "log.showSignature=false", "-c", "color.ui=false", *arguments]
67
+ # Never stop to ask for a password, and treat path arguments as plain names, not patterns.
68
+ env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GIT_LITERAL_PATHSPECS": "1", "GIT_OPTIONAL_LOCKS": "0"}
69
+ try:
70
+ done = subprocess.run(command, capture_output=True, stdin=subprocess.DEVNULL, timeout=GIT_SECONDS, env=env)
71
+ except subprocess.TimeoutExpired as exc:
72
+ raise ValueError("git took too long to answer and was stopped.") from exc
73
+ if done.returncode != 0:
74
+ last = [line.strip() for line in done.stderr.decode("utf-8", "replace").splitlines() if line.strip()]
75
+ raise ValueError("git could not read the repository" + (f": {last[-1][:200]}" if last else "."))
76
+ return done.stdout[:OUTPUT_BYTES].decode("utf-8", "replace")
77
+
78
+
79
+ # For every diff: no external diff tool or text converter (both would run a program), a rename shown as a
80
+ # delete plus an add, paths relative to the workspace root, and no colour codes.
81
+ DIFF = ("--no-ext-diff", "--no-textconv", "--no-renames", "--relative", "--no-color")
82
+
83
+
84
+ def parse_hunks(diff):
85
+ """[(start, end, lines)] for each hunk of one file's diff, numbered as in the file after the change."""
86
+ hunks = []
87
+ for line in diff.splitlines():
88
+ header = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
89
+ if header:
90
+ # In "@@ -a,b +c,d @@", c is the hunk's first line after the change and d its line count, which is 1 when left out.
91
+ start, count = int(header[1]), int(header[2]) if header[2] is not None else 1
92
+ hunks.append([max(1, start), max(1, start + max(count, 1) - 1), []])
93
+ elif hunks and line[:1] in ("+", "-", " "):
94
+ hunks[-1][2].append(line)
95
+ return [tuple(hunk) for hunk in hunks]
96
+
97
+
98
+ def allowed(workspace, name):
99
+ """True when the workspace rules let this file be read: not hidden, excluded, or outside the root."""
100
+ try:
101
+ workspace.path(name)
102
+ return True
103
+ except (ValueError, OSError):
104
+ return False
105
+
106
+
107
+ def describe(workspace, request, limit, prefer=()):
108
+ """Read the changes a task asks about.
109
+
110
+ Returns {"label", "text", "evidence", "paths"}: text is what the model is shown, at most about limit bytes;
111
+ evidence has one row per shown hunk, so an answer can cite the changed lines; paths are the changed files
112
+ that still exist and were shown. Raises NoChanges when there is nothing to explain.
113
+ """
114
+ kind, ref = request
115
+ root = workspace.root
116
+ try:
117
+ inside = git(root, "rev-parse", "--is-inside-work-tree").strip() == "true"
118
+ except NoChanges:
119
+ raise
120
+ except ValueError:
121
+ inside = False
122
+ if not inside:
123
+ raise NoChanges("This folder is not a Git repository, so there are no commits or uncommitted changes to explain.")
124
+ try:
125
+ head = git(root, "rev-parse", "--verify", "--quiet", "HEAD^{commit}").strip()
126
+ except ValueError:
127
+ head = ""
128
+ if not head:
129
+ raise NoChanges("This Git repository has no commits yet, so there is nothing to compare with.")
130
+ untracked = []
131
+ if kind == "commit":
132
+ try:
133
+ commit = git(root, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}").strip()
134
+ except ValueError:
135
+ commit = ""
136
+ if not commit:
137
+ raise NoChanges(f"Git has no commit named {ref} in this repository.")
138
+ # The fields are separated by NUL bytes (%x00), which cannot occur inside them; the padding guards against a short reply.
139
+ short, author, day, subject, body = (git(root, "log", "-1", "--no-show-signature", "--date=short",
140
+ "--format=%h%x00%an%x00%ad%x00%s%x00%b", commit).split("\0") + [""] * 5)[:5]
141
+ parents = git(root, "log", "-1", "--no-show-signature", "--format=%P", commit).split()
142
+ # A first commit has no parent: it is compared with git's empty tree, so all its files show as added.
143
+ base = parents[0] if parents else git(root, "hash-object", "-t", "tree", os.devnull).strip()
144
+ span = (base, commit)
145
+ label = f"commit {short} ({day}, by {author})" + (" (the last commit)" if commit == head else "")
146
+ intro = f"Changes made by {label}. Its message (untrusted data): {subject.strip()[:200]!r}"
147
+ message = " ".join(body.split())[:MESSAGE_CHARS]
148
+ intro += f" {message!r}" if message else ""
149
+ if len(parents) > 1:
150
+ intro += "\nIt is a merge commit; the changes are shown against its first parent."
151
+ elif kind == "staged":
152
+ span, label = ("--cached", "HEAD"), "staged changes"
153
+ intro = "Staged changes (added with git add, not yet committed), compared with the last commit."
154
+ else:
155
+ span, label = ("HEAD",), "uncommitted changes"
156
+ intro = "Uncommitted changes (staged and unstaged) compared with the last commit."
157
+ untracked = [name for name in git(root, "ls-files", "--others", "--exclude-standard", "-z").split("\0")
158
+ if name and allowed(workspace, name)]
159
+ status = {}
160
+ # With -z the output is letter, name, letter, name, ... separated by NUL bytes, which is safe for any file name.
161
+ fields = git(root, "diff", *DIFF, "--name-status", "-z", *span).split("\0")
162
+ for letter, name in zip(fields[::2], fields[1::2]):
163
+ status[name] = {"A": "added", "D": "deleted", "M": "modified", "T": "type changed"}.get(letter[:1], "changed")
164
+ counts = {}
165
+ # Each --numstat row is "added<TAB>removed<TAB>name"; a binary file has "-" for both counts.
166
+ for row in git(root, "diff", *DIFF, "--numstat", "-z", *span).split("\0"):
167
+ parts = row.split("\t", 2)
168
+ if len(parts) == 3:
169
+ counts[parts[2]] = (parts[0], parts[1])
170
+ hidden = sum(1 for name in status if not allowed(workspace, name))
171
+ names = [name for name in status if allowed(workspace, name)]
172
+ if not names and not untracked:
173
+ if hidden:
174
+ raise NoChanges(f"The only files changed in the {label} are hidden or excluded, so CodeHaven does not read them.")
175
+ if kind == "commit":
176
+ raise NoChanges(f"The {label} changes no files.")
177
+ raise NoChanges(f"There are no {label}: the files match the last commit."
178
+ + (" Ask about the last commit to see what it changed." if kind != "commit" else ""))
179
+ # Files the task names come first; then the smallest diffs, so as many files as possible are shown.
180
+ def size(name):
181
+ """Lines added plus removed in one file; a binary file, counted as "-", is 0."""
182
+ added, removed = counts.get(name, ("0", "0"))
183
+ return (int(added) if added.isdigit() else 0) + (int(removed) if removed.isdigit() else 0)
184
+ names.sort(key=lambda name: (name not in prefer, size(name), name))
185
+ added = sum(int(counts[n][0]) for n in names if n in counts and counts[n][0].isdigit())
186
+ removed = sum(int(counts[n][1]) for n in names if n in counts and counts[n][1].isdigit())
187
+ lines = [intro, f"{len(names)} file{'s' if len(names) != 1 else ''} changed: {added} lines added, {removed} removed."]
188
+ for name in names[:LISTED_FILES]:
189
+ plus, minus = counts.get(name, ("?", "?"))
190
+ lines.append(f"- {name}: {status[name]}" + (" (binary)" if plus == "-" else f", +{plus} -{minus}"))
191
+ if len(names) > LISTED_FILES:
192
+ lines.append(f"- ... and {len(names) - LISTED_FILES} more files")
193
+ if hidden:
194
+ lines.append(f"{hidden} hidden or excluded file{'s' if hidden != 1 else ''} also changed and "
195
+ f"{'are' if hidden != 1 else 'is'} not shown.")
196
+ if untracked:
197
+ lines.append("New files Git does not track yet (read them to see their content): "
198
+ + ", ".join(untracked[:UNTRACKED_SHOWN])
199
+ + (f", and {len(untracked) - UNTRACKED_SHOWN} more" if len(untracked) > UNTRACKED_SHOWN else ""))
200
+ lines.append("In the changed lines below, + marks an added line, - a removed line, and other lines are unchanged context.")
201
+ text = "\n".join(lines)
202
+ evidence, paths, omitted = [], [], []
203
+ for name in names:
204
+ if counts.get(name, ("", ""))[0] == "-":
205
+ continue # Binary: nothing to show beyond its name.
206
+ hunks = parse_hunks(git(root, "diff", *DIFF, f"--unified={CONTEXT_LINES}", "--src-prefix=a/", "--dst-prefix=b/",
207
+ *span, "--", name))
208
+ shown = 0
209
+ for start, end, body in hunks:
210
+ where = (f"\n{name} ({status[name]}), removed lines:" if status[name] == "deleted"
211
+ else f"\n{name} ({status[name]}), lines {start}-{end} after the change:")
212
+ block = where + "\n" + "\n".join(body)
213
+ # Whole hunks only: stop at the first one that does not fit; the file is then named as not fully shown.
214
+ if len((text + block).encode()) > limit:
215
+ break
216
+ text += block
217
+ shown += 1
218
+ if status[name] != "deleted":
219
+ evidence.append({"path": name, "line": start, "end_line": end,
220
+ "text": "\n".join(line[1:] for line in body if line[:1] != "-")})
221
+ if shown and status[name] != "deleted" and name not in paths:
222
+ paths.append(name)
223
+ if shown < len(hunks):
224
+ omitted.append(name)
225
+ if omitted:
226
+ text += ("\nNot all changed lines fit here. Not fully shown: " + ", ".join(omitted[:LISTED_FILES])
227
+ + ". Say so in the answer; the user can ask about one of these files by name.")
228
+ return {"label": label, "text": text, "evidence": evidence, "paths": paths, "files": len(names)}
offline_agent/chats.py ADDED
@@ -0,0 +1,121 @@
1
+ """Saved chats: the conversations about one repository, kept on this computer so a thread can be reopened later.
2
+
3
+ Used by the browser page. On by default; --no-remember turns it off, and then nothing is saved to disk. Chats
4
+ live in one JSON file per repository under ~/CodeHaven/chats, readable by this user only, never inside the
5
+ repository, and nothing leaves the computer. Chats about an uploaded file are never saved.
6
+
7
+ A saved chat is a record of what was said, not a checked fact: the code may have changed since, so its
8
+ citations open the files as they are now. Reopening a chat gives follow-up questions the same memory of it that
9
+ they had when it was live.
10
+ """
11
+ import contextlib
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import secrets
17
+ import tempfile
18
+ from datetime import datetime
19
+ from pathlib import Path
20
+
21
+ CHATS_FOLDER = Path.home() / "CodeHaven" / "chats"
22
+ CHATS, TURNS = 30, 60 # Per repository, and per chat; the oldest go first.
23
+ QUESTION_BYTES, ANSWER_BYTES, TITLE_CHARS = 2000, 12_000, 70
24
+ CHAT_ID = re.compile(r"[0-9a-f]{12}")
25
+
26
+
27
+ def clip(text, limit):
28
+ """Cut text to about limit UTF-8 bytes without splitting a character; a cut is marked with an ellipsis."""
29
+ raw = text.encode()
30
+ return text if len(raw) <= limit else raw[:limit].decode("utf-8", "ignore") + " …"
31
+
32
+
33
+ def new_id():
34
+ """A random id for a new chat: 12 hex characters, the shape CHAT_ID checks."""
35
+ return secrets.token_hex(6)
36
+
37
+
38
+ class Chats:
39
+ """The saved chats for one repository."""
40
+
41
+ def __init__(self, workspace, folder=None):
42
+ """Work out this repository's chat file and load what it holds."""
43
+ self.root = str(workspace.root)
44
+ self.folder = Path(folder).expanduser() if folder else CHATS_FOLDER
45
+ # The file name is the folder's name, for people, plus a hash of its full path, so same-named folders never share a file.
46
+ name = re.sub(r"[^\w.-]", "_", workspace.root.name, flags=re.ASCII)[:40] or "repository"
47
+ self.path = self.folder / f"{name}-{hashlib.sha256(self.root.encode()).hexdigest()[:12]}.json"
48
+ self.chats = self.load()
49
+
50
+ def load(self):
51
+ """The chats saved on disk. Only a file for this repository counts, and entries not shaped like a chat are dropped."""
52
+ try:
53
+ data = json.loads(self.path.read_text(encoding="utf-8"))
54
+ except (OSError, ValueError):
55
+ return [] # Missing or damaged: start empty; the next save replaces it.
56
+ chats = data.get("chats") if isinstance(data, dict) and data.get("repository") == self.root else None
57
+ kept = []
58
+ for chat in chats if isinstance(chats, list) else []:
59
+ if (isinstance(chat, dict) and isinstance(chat.get("id"), str) and CHAT_ID.fullmatch(chat["id"])
60
+ and isinstance(chat.get("title"), str) and isinstance(chat.get("updated"), str)
61
+ and isinstance(chat.get("turns"), list) and chat["turns"]
62
+ and all(isinstance(turn, dict) and isinstance(turn.get("question"), str)
63
+ and isinstance(turn.get("answer"), str) and isinstance(turn.get("issues"), list)
64
+ and all(isinstance(issue, str) for issue in turn["issues"]) for turn in chat["turns"])):
65
+ kept.append(chat)
66
+ return kept
67
+
68
+ def save(self):
69
+ """Write the chats for this user only, replacing the file in one step so a crash cannot leave half of it."""
70
+ if not self.chats:
71
+ with contextlib.suppress(FileNotFoundError):
72
+ self.path.unlink()
73
+ return
74
+ self.folder.mkdir(parents=True, exist_ok=True, mode=0o700)
75
+ data = json.dumps({"repository": self.root, "chats": self.chats}, ensure_ascii=False, indent=1)
76
+ handle, partial = tempfile.mkstemp(prefix=".chats-", dir=self.folder) # Created readable by this user only.
77
+ try:
78
+ with os.fdopen(handle, "w", encoding="utf-8") as file:
79
+ file.write(data)
80
+ os.replace(partial, self.path)
81
+ except BaseException:
82
+ with contextlib.suppress(OSError):
83
+ os.unlink(partial)
84
+ raise
85
+
86
+ def get(self, chat_id):
87
+ """The saved chat with this id, or ValueError if it is gone."""
88
+ chat = next((chat for chat in self.chats if chat["id"] == chat_id), None)
89
+ if chat is None:
90
+ raise ValueError("That saved chat no longer exists.")
91
+ return chat
92
+
93
+ def record(self, chat_id, question, answer, issues=()):
94
+ """Add one question and answer to a chat, creating the chat on its first question. Newest chat first."""
95
+ if not CHAT_ID.fullmatch(chat_id) or not question.strip() or not answer.strip():
96
+ return
97
+ chat = next((chat for chat in self.chats if chat["id"] == chat_id), None)
98
+ if chat is None:
99
+ title = " ".join(question.split())
100
+ chat = {"id": chat_id, "title": title[:TITLE_CHARS] + ("…" if len(title) > TITLE_CHARS else ""), "turns": []}
101
+ chat["turns"] = (chat["turns"] + [{"question": clip(question.strip(), QUESTION_BYTES),
102
+ "answer": clip(answer.strip(), ANSWER_BYTES),
103
+ "issues": [str(issue)[:300] for issue in issues][:10]}])[-TURNS:]
104
+ chat["updated"] = datetime.now().isoformat(timespec="seconds")
105
+ self.chats = ([chat] + [other for other in self.chats if other["id"] != chat_id])[:CHATS]
106
+ self.save()
107
+
108
+ def listing(self):
109
+ """The chats as the sidebar lists them, newest first: id, title, last use, and number of questions."""
110
+ return [{"id": chat["id"], "title": chat["title"], "updated": chat["updated"], "questions": len(chat["turns"])}
111
+ for chat in self.chats]
112
+
113
+ def delete(self, chat_id):
114
+ """Delete one saved chat; an id that is not there is ignored."""
115
+ self.chats = [chat for chat in self.chats if chat["id"] != chat_id]
116
+ self.save()
117
+
118
+ def forget(self):
119
+ """Delete every saved chat for this repository, and its file."""
120
+ self.chats = []
121
+ self.save()