tracebase-cli 0.3.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.
@@ -0,0 +1,286 @@
1
+ """MCP server (stdio): lets the developer's AI agent (Claude Code, Codex, Gemini CLI, opencode, Cursor, an Ollama
2
+ model through ollmcp, …) find their own code in their old projects and copy it into the current project.
3
+
4
+ Flow: find_code -> preview_copy (diff, nothing written) -> the USER approves -> apply_copy writes it.
5
+ apply_copy asks the user directly through MCP elicitation when the agent supports it, so the agent cannot approve
6
+ on the user's behalf. Tracebase itself uses no AI and makes no internet requests.
7
+ Started by the agent with `tracebase mcp` (see `tracebase connect`)."""
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ from pydantic import BaseModel, Field
14
+
15
+ try: # mcp >= 2
16
+ from mcp.server.mcpserver import Context, MCPServer as FastMCP
17
+ from mcp_types import ToolAnnotations
18
+ except ImportError: # mcp 1.x
19
+ from mcp.server.fastmcp import Context, FastMCP
20
+ from mcp.types import ToolAnnotations
21
+
22
+ from . import plans, project, reuse
23
+ from .client import Client, TracebaseError
24
+ from .ui import diff
25
+
26
+ INSTRUCTIONS = """Tracebase indexes ALL of the developer's past projects on their own machine.
27
+ When the developer asks to reuse something they built before ("copy the login logic from my old projects",
28
+ "implement role based access control like I did before"), DO NOT search the web and DO NOT write it from scratch:
29
+ 1. call find_code to see their past implementations (repo, path, symbol),
30
+ 2. call preview_copy for the one that fits: it shows exactly what would be copied into this project
31
+ (the code plus what it depends on: models, migrations, wiring) as a diff. Nothing is written yet.
32
+ 3. show the user that summary and ASK whether to implement it here,
33
+ 4. only if the user says yes, call apply_copy with the plan_id. Tracebase may ask the user to confirm again.
34
+ Mention the source repo/path of anything you reuse, and list the "still to do" steps after applying.
35
+
36
+ Tracebase also collects the developer's production logs (Log Detective). When they ask what broke, why something
37
+ is failing, or about an error ("why did checkout fail last night?", "what's E-5?"):
38
+ 1. call find_errors (optionally with service / since / query) to see the error groups,
39
+ 2. call explain_error for the relevant one: the likely cause, the failing code from their repos, the commit that
40
+ last changed that line, what happened in other services at the same time, and a suggested fix,
41
+ 3. explain it to them. If they want it fixed, edit the code in the current project as usual (show the change first).
42
+ Never paste their logs into a web search."""
43
+
44
+ READ_ONLY = ToolAnnotations(read_only_hint=True, destructive_hint=False, open_world_hint=False)
45
+ WRITES = ToolAnnotations(read_only_hint=False, destructive_hint=True, idempotent_hint=False, open_world_hint=False)
46
+
47
+
48
+ class Approval(BaseModel):
49
+ write: bool = Field(default=True, description="Write these changes into the project")
50
+
51
+
52
+ def _fmt_examples(res: dict) -> str:
53
+ if not res.get("examples"):
54
+ return "No related code found in the developer's indexed projects."
55
+ out = [f"Current project: {res.get('stack_text') or 'unknown'} · searched for: {res.get('query')}", ""]
56
+ for e in res["examples"]:
57
+ fw = f", {e['framework']}" if e.get("framework") else ""
58
+ out.append(f"[{e['id']}] repo={e['repo']} path={e['path']} symbol={e['symbol']} "
59
+ f"lines {e['lines'][0]}-{e['lines'][1]} ({e['language']}{fw})")
60
+ out.append(f"```{e['language'] or ''}\n{e['code']}\n```")
61
+ return "\n".join(out)
62
+
63
+
64
+ def can_elicit(ctx: Context | None) -> bool:
65
+ """Does the connected agent support asking the user directly (MCP elicitation)?"""
66
+ try:
67
+ s = ctx.request_context.session
68
+ caps = getattr(s, "client_capabilities", None) or getattr(getattr(s, "client_params", None), "capabilities", None)
69
+ return bool(caps and getattr(caps, "elicitation", None) is not None)
70
+ except Exception:
71
+ return False
72
+
73
+
74
+ def _applied(workspace: Path, plan: dict, done: list[tuple[str, str]]) -> str:
75
+ lines = [f"Copied from {plan['repo']} into {workspace.name}:"]
76
+ lines += [f"- {note} {target}" for note, target in done]
77
+ if any(n == "updated" for n, _ in done):
78
+ lines.append("Originals of updated files are backed up in .tracebase/backups/.")
79
+ todo = plans.todo_text(plan)
80
+ if todo:
81
+ lines.append("\nStill to do (tell the user, or do it if they ask):")
82
+ lines += [f"- {t}" for t in todo]
83
+ return "\n".join(lines)
84
+
85
+
86
+ def build_server(api: Client, workspace: Path | None = None) -> FastMCP:
87
+ mcp = FastMCP("tracebase", instructions=INSTRUCTIONS)
88
+ workspace = (workspace or Path(os.environ.get("TRACEBASE_WORKSPACE") or os.getcwd())).resolve()
89
+
90
+ def ctx(task: str = "", n: int = 2) -> dict | None:
91
+ return project.context(workspace, task, max_files=n, budget=8000) if workspace.is_dir() else None
92
+
93
+ def manifest_ctx() -> dict | None:
94
+ c = ctx()
95
+ return {"name": c["name"], "tree": c["tree"], "files": {k: v for k, v in c["files"].items() if "/" not in k}} if c else None
96
+
97
+ @mcp.tool(annotations=READ_ONLY)
98
+ def find_code(task: str, languages: list[str] | None = None, frameworks: list[str] | None = None,
99
+ limit: int = 6) -> str:
100
+ """Find the developer's own past implementations of something (e.g. "login", "role based access
101
+ control", "stripe webhook") across all their old projects. Prefers the current project's language and
102
+ framework. Returns code with repo and path, to pass to preview_copy."""
103
+ try:
104
+ c = None if (languages or frameworks) else ctx(task)
105
+ return _fmt_examples(api.examples(task, project=c, languages=languages, frameworks=frameworks, limit=limit))
106
+ except TracebaseError as e:
107
+ return f"Tracebase error: {e}"
108
+
109
+ @mcp.tool(annotations=READ_ONLY)
110
+ def preview_copy(repo: str, path: str, symbol: str | None = None, renames: list[str] | None = None,
111
+ request: str = "") -> str:
112
+ """Prepare copying a file (or one function/class of it, via `symbol`) from an old project into the
113
+ current project, plus what it needs from that project (models, methods it calls, migrations, wiring
114
+ such as route/middleware registration). Writes NOTHING: returns a plan_id, a summary and the diff.
115
+ Show the summary to the user and ask whether to implement it; call apply_copy only if they agree.
116
+ The old project's name is replaced by this project's automatically; `renames` adapts domain words in
117
+ every spelling and in file names, e.g. ["Doctor=Staff", "appointment=booking"]."""
118
+ try:
119
+ b = api.bundle(repo, [path], manifest_ctx(), symbol=symbol, renames=renames)
120
+ changes = reuse.plan_changes(workspace, b)
121
+ except (TracebaseError, reuse.CopyError) as e:
122
+ return f"Tracebase error: {e}"
123
+ todo = [c for c in changes if c.new_text is not None]
124
+ if not todo and not any(c.manual for c in changes):
125
+ return f"Nothing to copy: everything from {b['repo']}/{path} is already in {workspace.name}."
126
+ plan = plans.save(workspace, b, changes, request)
127
+ out = [f"plan_id: {plan['id']} (nothing written yet)", "", plans.summary(plan)]
128
+ for c in todo:
129
+ out.append(f"\n{diff(c.target, c.old_text, c.new_text, max_lines=160)}")
130
+ out.append(f"\nAsk the user whether to implement this in {workspace.name}. If yes: apply_copy(plan_id=\"{plan['id']}\"). "
131
+ f"They can also review it themselves with `tracebase apply {plan['id']}` in a terminal.")
132
+ return "\n".join(out)
133
+
134
+ @mcp.tool(annotations=WRITES)
135
+ async def apply_copy(plan_id: str, user_confirmed: bool = False, ctx: Context | None = None) -> str:
136
+ """Write a plan made by preview_copy into the project, after the user approved it. Asks the user to
137
+ confirm through the agent's approval prompt when the agent supports it. Set user_confirmed=true ONLY
138
+ if the user explicitly said yes to this plan in the conversation. Originals are backed up to
139
+ .tracebase/backups/; a plan whose files changed since the preview is refused."""
140
+ try:
141
+ plan = plans.load(workspace, plan_id)
142
+ bad = plans.stale(workspace, plan)
143
+ if bad:
144
+ return "Tracebase error: these files changed after the preview, call preview_copy again: " + ", ".join(bad)
145
+ if can_elicit(ctx):
146
+ res = await ctx.elicit(f"Tracebase: write this into {workspace.name}?\n\n{plans.summary(plan)}", Approval)
147
+ if res.action != "accept" or not getattr(res.data, "write", False):
148
+ return (f"The user declined. Nothing was written. The plan is kept: they can still apply it "
149
+ f"with `tracebase apply {plan_id}`.")
150
+ elif not user_confirmed:
151
+ return ("Not written: the user has not approved this yet. Show them the preview summary and ask. "
152
+ "If they say yes, call apply_copy again with user_confirmed=true. They can also run "
153
+ f"`tracebase apply {plan_id}` in a terminal to review and write it themselves.")
154
+ done = plans.apply(workspace, plan)
155
+ if api is not None:
156
+ api.event("copied", plan["repo"], project=workspace.name, files=[t for _, t in done],
157
+ picked=", ".join(plan["picked"]), adapted=plan.get("adapted") or [], via="AI agent (MCP)")
158
+ return _applied(workspace, plan, done)
159
+ except reuse.CopyError as e:
160
+ return f"Tracebase error: {e}"
161
+
162
+ @mcp.tool(annotations=READ_ONLY)
163
+ def find_errors(service: str | None = None, since: str | None = "24h", query: str | None = None,
164
+ status: str | None = None, limit: int = 15) -> str:
165
+ """Production errors from the developer's logs, grouped (thousands of identical errors = one group with an
166
+ id like E-5). `since`: "last night", "2h", "yesterday 18:00", "7d" or null for any time. `query` filters the
167
+ message text, `status`: new / regressed / known / resolved / ignored."""
168
+ try:
169
+ groups = api.errors(service=service, since=since, status=status, q=query, limit=limit)
170
+ except TracebaseError as e:
171
+ return f"Tracebase error: {e}"
172
+ if not groups:
173
+ return "No errors found" + (f" since {since}" if since else "") + "."
174
+ return "\n".join(
175
+ f"{g['code']} [{g['status']}{', SPIKING' if g.get('spike') else ''}] service={g['service']} "
176
+ f"count={g.get('window_count') if since else g['count']} first={g['first_seen']} last={g['last_seen']}: {g['title']}"
177
+ for g in groups) + "\n\nCall explain_error(error_id) for the cause, the failing code and a fix."
178
+
179
+ @mcp.tool(annotations=READ_ONLY)
180
+ def explain_error(error_id: str) -> str:
181
+ """Investigate one error group (e.g. "E-5"): likely cause, impact, the failing lines of code in the
182
+ developer's repos, the git commit that last changed them, notable events in other services at the same time
183
+ (restarts, deploys, backups) and suggested fixes. Computed on their machine from their own logs and code."""
184
+ gid = error_id.strip().upper()
185
+ gid = gid if gid.startswith("E-") else f"E-{gid}"
186
+ try:
187
+ g = api.error(gid)
188
+ r = api.explain_error(gid)
189
+ except TracebaseError as e:
190
+ return f"Tracebase error: {e}"
191
+ out = [f"{gid} in {g['service']}: {g['title']}",
192
+ f"{g['count']} times, first {g['first_seen']}, last {g['last_seen']}, status {g['status']}",
193
+ f"\nLikely cause: {r['cause']}", f"Impact: {r['impact']}"]
194
+ if r.get("events"):
195
+ out.append("\nOther services around that time:")
196
+ out += [f"- {e['ts']} {e['service']}: {e['message'][:160]}" for e in r["events"][:8]]
197
+ for c in r.get("code") or []:
198
+ out.append(f"\nCode at {c['repo']}/{c['path']}:{c['line']}" + (f" ({c['func']})" if c.get("func") else ""))
199
+ out.append("```\n" + "\n".join(f"{'>>' if l['n'] == c['line'] else ' '} {l['n']:>4} {l['text']}"
200
+ for l in c["snippet"]) + "\n```")
201
+ if r.get("commit"):
202
+ cm = r["commit"]
203
+ out.append(f"\nThat line was last changed by commit {cm['sha']} \"{cm['message']}\" ({cm['author']}, {cm['date']}"
204
+ + (f", {cm['minutes_before_first_error']} min before the first error" if cm.get("minutes_before_first_error") is not None else "") + ")")
205
+ if r.get("fix"):
206
+ out.append("\nSuggested fix:")
207
+ out += [f"{i}. {f}" for i, f in enumerate(r["fix"], 1)]
208
+ if g.get("samples"):
209
+ out.append("\nSample log line:\n" + g["samples"][0]["message"][:800])
210
+ return "\n".join(out)
211
+
212
+ @mcp.tool(annotations=READ_ONLY)
213
+ def get_code_bundle(repo: str, path: str, symbol: str | None = None) -> str:
214
+ """Show a file from an old project PLUS everything it needs from that project, without planning a copy
215
+ (use this when you want to adapt the code yourself instead of copying it)."""
216
+ try:
217
+ b = api.bundle(repo, [path], manifest_ctx(), symbol=symbol)
218
+ except TracebaseError as e:
219
+ return f"Tracebase error: {e}"
220
+ out = [f"Bundle from {b['repo']} ({len(b['files'])} files):"]
221
+ for f in b["files"]:
222
+ state = "EXISTS in current project" if f["exists_in_project"] else "new"
223
+ out.append(f"\n## {f['path']} [{f['role']}, {state}] — {f['reason']}")
224
+ if f["role"] == "wiring" and f["snippets"]:
225
+ out.append("Relevant lines:\n" + "\n".join(f" {s['line'].strip()}" +
226
+ (f" (inside: {s['inside']})" if s.get("inside") else "")
227
+ for s in f["snippets"]))
228
+ else:
229
+ out.append(f"```{f['language'] or ''}\n{f['content']}\n```")
230
+ if b.get("packages"):
231
+ out.append("\nPackages used: " + ", ".join(f"{p['name']} {p['version']}" for p in b["packages"]))
232
+ if b.get("env"):
233
+ out.append("Env vars read: " + ", ".join(b["env"]))
234
+ return "\n".join(out)
235
+
236
+ @mcp.tool(annotations=READ_ONLY)
237
+ def search_code(query: str, repo: str | None = None, language: str | None = None, limit: int = 8) -> str:
238
+ """Keyword + meaning search over all the developer's past repositories, e.g. "send password reset email"."""
239
+ try:
240
+ res = api.search(query, repo=repo, language=language, limit=limit)
241
+ except TracebaseError as e:
242
+ return f"Tracebase error: {e}"
243
+ if not res["results"]:
244
+ return "No matches."
245
+ return "\n\n".join(
246
+ f"repo={r['repo']} path={r['path']} lines {r['lines'][0]}-{r['lines'][1]} {r['symbol']} ({r['language']})\n"
247
+ f"```\n{r['preview']}\n```" for r in res["results"])
248
+
249
+ @mcp.tool(annotations=READ_ONLY)
250
+ def read_code(repo: str, path: str, start_line: int | None = None, end_line: int | None = None) -> str:
251
+ """Read a file (or a line range) from one of the developer's past repositories."""
252
+ try:
253
+ res = api.read(repo, path, start_line, end_line)
254
+ except TracebaseError as e:
255
+ return f"Tracebase error: {e}"
256
+ body = "\n".join(f"{ln['n']:>5} {ln['text']}" for ln in res["lines"])
257
+ return f"{res['repo']}/{res['path']} (lines {res['start']}-{res['end']} of {res['total_lines']})\n{body}"
258
+
259
+ @mcp.tool(annotations=READ_ONLY)
260
+ def list_repos() -> str:
261
+ """List the developer's indexed repositories."""
262
+ try:
263
+ repos = api.repos()
264
+ except TracebaseError as e:
265
+ return f"Tracebase error: {e}"
266
+ return "\n".join(f"{r['name']} ({r['kind']}, {r['files']} files): {', '.join(list(r.get('languages', {}))[:4])}"
267
+ for r in repos) or "No repositories indexed."
268
+
269
+ @mcp.prompt()
270
+ def copy(what: str) -> str:
271
+ """Find something you built before in your old projects and copy it into this one (asks before writing)."""
272
+ return (f"Find my own past implementation of \"{what}\" in my old projects with the tracebase tools "
273
+ "(find_code, then preview_copy for the best match). Show me what would be copied and ask me before "
274
+ "writing anything. Do not search the web.")
275
+
276
+ @mcp.prompt()
277
+ def why(what: str = "what broke last night") -> str:
278
+ """Find out why something failed in production, from your own logs and code."""
279
+ return (f"Use the tracebase tools (find_errors, then explain_error) to find out {what}. Show me the cause, the "
280
+ "failing code and the commit that changed it, and suggest a fix. Do not search the web.")
281
+
282
+ return mcp
283
+
284
+
285
+ def run(api: Client) -> None:
286
+ build_server(api).run() # stdio
tracebase_cli/merge.py ADDED
@@ -0,0 +1,312 @@
1
+ """Deterministic merging of code copied from an old project into a file that already exists in the new one.
2
+ No AI: functions/methods are found with brace matching (PHP, JS, TS, Go, Java…) or indentation (Python).
3
+
4
+ add_functions() add the methods/functions the new file doesn't have yet (+ their missing imports)
5
+ insert_lines() put wiring lines (e.g. a middleware alias) next to the same neighbour line they had before
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ FUNC_START = re.compile(
12
+ r"^(?P<indent>[ \t]*)(?:(?:export|default|public|protected|private|static|async|final|abstract|override)\s+)*"
13
+ r"(?:function\s+(?P<name>\w+)\s*\(|(?:const|let|var)\s+(?P<arrow>\w+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*=>)",
14
+ re.M)
15
+ IMPORT_LINE = re.compile(r"^(use\s|import\s|from\s\S+\s+import\s|const\s+\w+\s*=\s*require\(|<\?php)")
16
+ PY_START = re.compile(r"^(?P<indent>[ \t]*)(?:async\s+)?(?:def|class)\s+(?P<name>\w+)", re.M)
17
+ GO_START = re.compile(r"^func\s+(?:\([^)]*\)\s*)?(?P<name>\w+)\s*[\[(]", re.M)
18
+ JAVA_START = re.compile(
19
+ r"^(?P<indent>[ \t]+)(?:@\w+(?:\([^)]*\))?\s+)*(?:(?:public|protected|private|static|final|synchronized|abstract|default)\s+)+"
20
+ r"(?:<[^>]+>\s+)?[\w<>\[\],.? ]+?\s+(?P<name>\w+)\s*\(", re.M)
21
+ RUBY_START = re.compile(r"^(?P<indent>[ \t]*)def\s+(?P<name>(?:self\.)?[\w?!=]+)", re.M)
22
+
23
+
24
+ def _brace_end(text: str, start: int) -> int | None:
25
+ """Index just after the brace that closes the first '{' at/after `start` (strings & comments skipped)."""
26
+ i, n, depth, seen = start, len(text), 0, False
27
+ while i < n:
28
+ ch = text[i]
29
+ if ch in "'\"`":
30
+ q = ch
31
+ i += 1
32
+ while i < n and text[i] != q:
33
+ i += 2 if text[i] == "\\" else 1
34
+ elif text.startswith("//", i) or (ch == "#" and not text.startswith("#[", i)):
35
+ i = text.find("\n", i)
36
+ i = n if i < 0 else i
37
+ elif text.startswith("/*", i):
38
+ i = text.find("*/", i + 2)
39
+ i = n if i < 0 else i + 1
40
+ elif ch == "{":
41
+ depth += 1
42
+ seen = True
43
+ elif ch == "}":
44
+ depth -= 1
45
+ if seen and depth == 0:
46
+ return i + 1
47
+ elif ch == ";" and not seen:
48
+ return None # declaration without a body (interface / abstract)
49
+ i += 1
50
+ return None
51
+
52
+
53
+ def _leading_comments(text: str, start: int) -> int:
54
+ """Move `start` back over the docblock / comments / decorators / attributes directly above it."""
55
+ lines_before = text[:start].split("\n")
56
+ lines_before.pop() # partial current line
57
+ keep = len(lines_before)
58
+ in_block = False
59
+ for j in range(len(lines_before) - 1, -1, -1):
60
+ t = lines_before[j].strip()
61
+ if in_block:
62
+ keep = j
63
+ if t.startswith("/*"):
64
+ in_block = False
65
+ continue
66
+ if t.endswith("*/"):
67
+ keep = j
68
+ in_block = not t.startswith("/*")
69
+ continue
70
+ if t.startswith(("//", "#", "@", "*")) and not t.startswith("#!"):
71
+ keep = j
72
+ continue
73
+ break
74
+ return len("\n".join(lines_before[:keep])) + (1 if keep else 0)
75
+
76
+
77
+ def functions(text: str, lang: str) -> dict[str, tuple[int, int]]:
78
+ """name -> (start, end) offsets, including the docblock above it."""
79
+ out: dict[str, tuple[int, int]] = {}
80
+ if lang == "python":
81
+ lines = text.splitlines(keepends=True)
82
+ offs = [0]
83
+ for ln in lines:
84
+ offs.append(offs[-1] + len(ln))
85
+ for m in PY_START.finditer(text):
86
+ ind = len(m.group("indent"))
87
+ li = text.count("\n", 0, m.start())
88
+ end_li = li + 1
89
+ while end_li < len(lines):
90
+ ln = lines[end_li]
91
+ if ln.strip() and len(ln) - len(ln.lstrip()) <= ind and not ln.lstrip().startswith((")", "]")):
92
+ break
93
+ end_li += 1
94
+ while end_li > li + 1 and not lines[end_li - 1].strip():
95
+ end_li -= 1
96
+ out.setdefault(m.group("name"), (_leading_comments(text, m.start()), offs[end_li]))
97
+ return out
98
+ if lang == "ruby":
99
+ lines = text.splitlines(keepends=True)
100
+ offs = [0]
101
+ for ln in lines:
102
+ offs.append(offs[-1] + len(ln))
103
+ for m in RUBY_START.finditer(text):
104
+ ind = m.group("indent")
105
+ li = text.count("\n", 0, m.start())
106
+ end_li = next((j for j in range(li + 1, len(lines)) if re.match(rf"^{re.escape(ind)}end\b", lines[j])), None)
107
+ if end_li is not None:
108
+ out.setdefault(m.group("name"), (_leading_comments(text, m.start()), offs[end_li + 1]))
109
+ return out
110
+ starts = {"go": GO_START, "java": JAVA_START, "kotlin": JAVA_START}.get(lang, FUNC_START)
111
+ for m in starts.finditer(text):
112
+ name = m.group("name") or (m.groupdict().get("arrow"))
113
+ end = _brace_end(text, m.end())
114
+ if not end:
115
+ continue
116
+ if end < len(text) and text[end] == ";":
117
+ end += 1
118
+ out.setdefault(name, (_leading_comments(text, m.start()), end))
119
+ return out
120
+
121
+
122
+ def _go_specs(text: str) -> list[str]:
123
+ specs = re.findall(r'^import\s+((?:\w+\s+)?"[^"]+")', text, re.M)
124
+ for block in re.findall(r"^import\s*\((.*?)^\)", text, re.M | re.S):
125
+ specs += [s.strip() for s in re.findall(r'^\s*((?:\w+\s+)?"[^"]+")', block, re.M)]
126
+ return specs
127
+
128
+
129
+ def imports(text: str, lang: str) -> list[str]:
130
+ if lang == "go":
131
+ return [f"import {s}" for s in _go_specs(text)]
132
+ if lang in ("java", "kotlin"):
133
+ return re.findall(r"^import\s+(?:static\s+)?[\w.*]+;?", text, re.M)
134
+ if lang == "ruby":
135
+ return re.findall(r"""^require(?:_relative)?\s+['"][^'"]+['"]""", text, re.M)
136
+ if lang == "php":
137
+ return re.findall(r"^use\s+[\w\\]+(?:\s+as\s+\w+)?\s*;", text, re.M) # top-level only (no indent)
138
+ if lang == "python":
139
+ return re.findall(r"^(?:from\s+\S+\s+import\s+[^\n]+|import\s+[^\n]+)", text, re.M)
140
+ return re.findall(r"^import\s[^\n]*?(?:from\s+)?['\"][^'\"]+['\"];?|^const\s+\w+\s*=\s*require\([^)]*\);?", text, re.M)
141
+
142
+
143
+ def _insert_go_imports(text: str, new: list[str]) -> str:
144
+ have = {s.split()[-1] for s in _go_specs(text)}
145
+ specs = [n.removeprefix("import").strip() for n in new]
146
+ specs = [s for s in specs if s.split()[-1] not in have]
147
+ if not specs:
148
+ return text
149
+ block = re.search(r"^import\s*\((.*?)^\)", text, re.M | re.S)
150
+ if block:
151
+ indent = re.search(r"^([ \t]+)\S", block.group(1), re.M)
152
+ ind = indent.group(1) if indent else "\t"
153
+ at = block.end() - 1
154
+ return text[:at] + "".join(f"{ind}{s}\n" for s in specs) + text[at:]
155
+ single = list(re.finditer(r'^import\s+(?:\w+\s+)?"[^"]+"\s*$', text, re.M))
156
+ if single: # turn single imports into a block
157
+ olds = [m.group(0).removeprefix("import").strip() for m in single]
158
+ start, end = single[0].start(), single[-1].end()
159
+ return text[:start] + "import (\n" + "".join(f"\t{s}\n" for s in olds + specs) + ")" + text[end:]
160
+ m = re.search(r"^package\s+\w+\s*\n", text, re.M)
161
+ at = m.end() if m else 0
162
+ return text[:at] + "\nimport (\n" + "".join(f"\t{s}\n" for s in specs) + ")\n" + text[at:]
163
+
164
+
165
+ def _insert_imports(text: str, new: list[str], lang: str) -> str:
166
+ if not new:
167
+ return text
168
+ if lang == "go":
169
+ return _insert_go_imports(text, new)
170
+ existing = list(re.finditer("|".join(re.escape(i) for i in imports(text, lang)) or r"(?!x)x", text))
171
+ block = "\n".join(new)
172
+ if existing:
173
+ at = existing[-1].end()
174
+ return text[:at] + "\n" + block + text[at:]
175
+ if lang in ("java", "kotlin"):
176
+ m = re.search(r"^package\s+[^;\n]+;?\s*\n", text, re.M)
177
+ if m:
178
+ return text[:m.end()] + "\n" + block + "\n" + text[m.end():]
179
+ if lang == "php":
180
+ m = re.search(r"^namespace\s+[^;]+;\s*\n", text, re.M) or re.search(r"^<\?php\s*\n", text)
181
+ if m:
182
+ return text[:m.end()] + "\n" + block + "\n" + text[m.end():]
183
+ return block + "\n" + text
184
+
185
+
186
+ def add_functions(existing: str, incoming: str, lang: str, only: list[str] | None = None) -> tuple[str, list[str]]:
187
+ """Copy the functions/methods of `incoming` that `existing` lacks. Returns (new text, added names)."""
188
+ have = functions(existing, lang)
189
+ theirs = functions(incoming, lang)
190
+ names = [n for n in theirs if n not in have and (only is None or n in only)]
191
+ if not names:
192
+ return existing, []
193
+ chunks = []
194
+ for n in names:
195
+ s, e = theirs[n]
196
+ chunks.append(incoming[s:e].rstrip("\n"))
197
+ body = "\n\n".join(chunks)
198
+ # put them inside the class when there is one (before its final closing brace), else at the end
199
+ if lang == "ruby" and re.search(r"^(class|module)\s+\w", existing, re.M):
200
+ close = existing.rstrip().rfind("\nend")
201
+ inner = "\n".join((" " + ln if ln.strip() and not ln.startswith(" ") else ln) for ln in body.split("\n"))
202
+ out = existing[:close].rstrip("\n") + "\n\n" + inner + existing[close:]
203
+ elif lang not in ("python", "go") and re.search(
204
+ r"^\s*(?:(?:public|protected|private|final|abstract|static|export|default)\s+)*class\s+\w+", existing, re.M):
205
+ close = existing.rstrip().rfind("}")
206
+ out = existing[:close].rstrip("\n") + "\n\n" + body + "\n" + existing[close:]
207
+ else:
208
+ out = existing.rstrip("\n") + "\n\n" + body + "\n"
209
+ # imports the copied code needs
210
+ copied = "\n".join(chunks)
211
+ wanted = []
212
+ have_imports = {i.strip() for i in imports(existing, lang)}
213
+ for imp in imports(incoming, lang):
214
+ if imp.strip() in have_imports:
215
+ continue
216
+ if lang == "go":
217
+ spec = imp.removeprefix("import").strip().split()
218
+ names_in = [spec[0]] if len(spec) == 2 else [spec[-1].strip('"').rstrip("/").split("/")[-1].split(".")[0]]
219
+ elif lang in ("java", "kotlin", "php"):
220
+ names_in = re.findall(r"(\w+)\s*;?\s*$", imp.split(" as ")[-1])
221
+ elif lang == "ruby":
222
+ names_in = [re.sub(r"\W", "", imp.split()[-1]).upper()] # require 'jwt' -> JWT
223
+ else:
224
+ names_in = re.findall(r"\b(\w+)\b", re.sub(r"from\s+['\"].*$|^import|require\(.*\)", "", imp))
225
+ if any(re.search(rf"\b{re.escape(x)}\b", copied, re.I if lang == "ruby" else 0)
226
+ for x in names_in if x not in ("import", "from", "const")):
227
+ wanted.append(imp.strip())
228
+ return _insert_imports(out, wanted, lang), names
229
+
230
+
231
+ def insert_lines(existing: str, snippets: list[dict]) -> tuple[str, list[str], list[dict]]:
232
+ """Insert wiring lines next to the neighbour line they had in the old file.
233
+ Returns (new text, inserted lines, snippets that must be added by hand)."""
234
+ text = existing
235
+ added, manual = [], []
236
+ for sn in snippets:
237
+ line = sn["line"].rstrip()
238
+ if line.strip() in {ln.strip() for ln in text.splitlines()}:
239
+ continue
240
+ if sn["kind"] == "import":
241
+ t = line.strip()
242
+ lang = "php" if t.startswith("use ") else \
243
+ "go" if re.match(r'^import\s+(\w+\s+)?"[^"]+"$', t) else \
244
+ "java" if re.match(r"^import\s+(static\s+)?[\w.*]+;$", t) else \
245
+ ("python" if re.match(r"^(from\s+\S+\s+import|import\s+[\w.]+\s*$)", t) else "js")
246
+ if lang == "go" and any(t.removeprefix("import").strip().split()[-1] == s.split()[-1] for s in _go_specs(text)):
247
+ continue
248
+ text = _insert_imports(text, [t], lang)
249
+ added.append(line.strip())
250
+ continue
251
+ lines = text.split("\n")
252
+ if sn["kind"] == "nested":
253
+ # inside a block (route group, func main, routes.draw do): only next to the same neighbour line
254
+ idx = None
255
+ for nb in sn.get("before") or []: # nearest neighbour first
256
+ if not nb.strip() or IMPORT_LINE.match(nb.strip()):
257
+ continue
258
+ idx = next((i for i, ln in enumerate(lines) if ln.strip() == nb.strip()), None)
259
+ if idx is not None:
260
+ break
261
+ if idx is None:
262
+ manual.append(sn)
263
+ continue
264
+ lines.insert(idx + 1, line)
265
+ text = "\n".join(lines)
266
+ added.append(line.strip())
267
+ continue
268
+ anchor = None
269
+ for nb in sn.get("before") or []:
270
+ if sn["kind"] == "statement" and IMPORT_LINE.match(nb.strip()):
271
+ break # code goes after the imports, not between them
272
+ idx = next((i for i, ln in enumerate(lines) if ln.strip() == nb.strip()), None)
273
+ if idx is not None:
274
+ anchor = idx
275
+ break
276
+ if anchor is not None:
277
+ lines.insert(anchor + 1, line)
278
+ elif sn["kind"] == "statement":
279
+ while lines and not lines[-1].strip():
280
+ lines.pop()
281
+ lines += ["", line, ""]
282
+ else:
283
+ manual.append(sn)
284
+ continue
285
+ text = "\n".join(lines)
286
+ added.append(line.strip())
287
+ return text, added, manual
288
+
289
+
290
+ RUBY_MACRO = re.compile(r"^([ \t]+)(has_secure_password|has_many|has_one|belongs_to|has_and_belongs_to_many)\b[^\n]*", re.M)
291
+
292
+
293
+ def add_ruby_macros(existing: str, incoming: str, used_by: str) -> tuple[str, list[str]]:
294
+ """Rails class declarations the copied code relies on: `has_secure_password` (gives .authenticate),
295
+ `has_many :roles` (gives .roles). Added after the class line when something uses what they provide."""
296
+ added = []
297
+ for m in RUBY_MACRO.finditer(incoming):
298
+ line = m.group(0).strip()
299
+ if line in existing:
300
+ continue
301
+ name = m.group(2)
302
+ provides = ["authenticate", "password"] if name == "has_secure_password" else \
303
+ re.findall(r":(\w+)", line)[:1]
304
+ if any(re.search(rf"[.&]\s*{re.escape(w)}\b|\b{re.escape(w)}\.", used_by) for w in provides):
305
+ added.append(line)
306
+ if not added:
307
+ return existing, []
308
+ cls = re.search(r"^class\s+[^\n]+\n", existing, re.M)
309
+ if not cls:
310
+ return existing, []
311
+ at = cls.end()
312
+ return existing[:at] + "".join(f" {ln}\n" for ln in added) + existing[at:], added