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.
tracebase_cli/main.py ADDED
@@ -0,0 +1,708 @@
1
+ """tracebase: find code you already wrote and copy it into the project you're working on.
2
+
3
+ tracebase copy "login logic" find it in your old projects and copy it here (+ what it needs)
4
+ tracebase copy "role based access control" e.g. middleware + User.hasRole + Role model + migration + wiring
5
+ tracebase copy "appointments" --rename Appointment=Booking adapt names while copying
6
+ tracebase find "jwt refresh" show your past implementations, with code
7
+ tracebase search "send password reset email" search across all your repos
8
+ tracebase connect claude let your AI agent use it (claude, codex, gemini, opencode, cursor, ollama)
9
+ tracebase pending / apply <id> review and write copies your agent prepared
10
+ tracebase login <token> --url http://nas:8080 use your team's shared Tracebase
11
+
12
+ tracebase errors --since "last night" production errors, grouped (Log Detective)
13
+ tracebase why E-5 why it happened: cause, the failing code, the commit, the fix
14
+ docker logs app 2>&1 | tracebase ingest - --service app send logs from anywhere
15
+ tracebase data what is stored; export / purge / forget (admin)
16
+
17
+ Everything stays on your machine: no AI writes the code and nothing is sent to the internet. Tracebase finds
18
+ your code, copies it, and merges it into existing files (missing methods, imports, wiring lines). It never
19
+ writes a file without showing you the diff first.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import os
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+ import time
30
+ from pathlib import Path
31
+
32
+ from . import __version__, connect, plans, project, reuse, ui
33
+ from .client import CONFIG, Client, TracebaseError, load_config, save_config
34
+
35
+
36
+ def _edit(content: str, suffix: str) -> str:
37
+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or ("nano" if shutil.which("nano") else "vi")
38
+ with tempfile.NamedTemporaryFile("w", suffix=suffix, delete=False) as f:
39
+ f.write(content)
40
+ tmp = f.name
41
+ try:
42
+ subprocess.call([*editor.split(), tmp])
43
+ return Path(tmp).read_text()
44
+ finally:
45
+ os.unlink(tmp)
46
+
47
+
48
+ def candidates(examples: list[dict], repo: str | None = None) -> list[dict]:
49
+ """One entry per file (best-ranked symbol first)."""
50
+ out, seen = [], set()
51
+ for e in examples:
52
+ if repo and e["repo"] != repo and not e["repo"].endswith("/" + repo):
53
+ continue
54
+ key = (e["repo"], e["path"])
55
+ if key in seen:
56
+ continue
57
+ seen.add(key)
58
+ out.append(e)
59
+ return out
60
+
61
+
62
+ def _print_candidate(n: int, e: dict, preview: int = 0) -> None:
63
+ fw = f" · {e['framework']}" if e.get("framework") else ""
64
+ meta = f"{e['symbol']} ({e['language']}{fw})"
65
+ ui.info(f"{ui.bold(str(n))}. {ui.teal(e['repo'])} {e['path']}:{e['lines'][0]}-{e['lines'][1]} {ui.dim(meta)}")
66
+ for ln in e["code"].splitlines()[:preview]:
67
+ ui.info(ui.dim(" │ ") + ln)
68
+
69
+
70
+ # ---------------------------------------------------------------- copy
71
+ def cmd_copy(args: argparse.Namespace, api: Client) -> int:
72
+ root = Path(args.path).resolve()
73
+ task = " ".join(args.task).strip()
74
+ ctx = project.context(root, task)
75
+
76
+ with ui.Spinner("Searching your projects"):
77
+ found = api.examples(task, project=ctx, limit=12)
78
+ cands = candidates(found["examples"], args.repo)[:8]
79
+ about = f"({found.get('query', task)} · this project: {found.get('stack_text') or '?'})"
80
+ ui.header(f"Found in your projects {ui.dim(about)}")
81
+ if not cands:
82
+ ui.error("Nothing matching found in your indexed projects.")
83
+ return 1
84
+ for n, e in enumerate(cands, 1):
85
+ _print_candidate(n, e, preview=6 if n == 1 else 0)
86
+
87
+ if args.pick:
88
+ pick = args.pick
89
+ elif args.yes:
90
+ pick = 1
91
+ else:
92
+ while True:
93
+ try:
94
+ ans = input(f"\nCopy which one? [1-{len(cands)}, q] (1) ").strip().lower() or "1"
95
+ except EOFError:
96
+ return 0
97
+ if ans == "q":
98
+ return 0
99
+ if ans.isdigit() and 1 <= int(ans) <= len(cands):
100
+ pick = int(ans)
101
+ break
102
+ if not 1 <= pick <= len(cands):
103
+ ui.error(f"--pick must be between 1 and {len(cands)}")
104
+ return 2
105
+ chosen = cands[pick - 1]
106
+
107
+ manifests = {k: v for k, v in ctx["files"].items() if "/" not in k}
108
+ with ui.Spinner("Collecting what it needs"):
109
+ bundle = api.bundle(chosen["repo"], [chosen["path"]], {"name": ctx["name"], "tree": ctx["tree"], "files": manifests},
110
+ symbol=chosen.get("symbol"), renames=args.rename)
111
+ changes = reuse.plan_changes(root, bundle)
112
+ ui.header(f"Copy from {ui.teal(bundle['repo'])} into {ui.bold(root.name)}")
113
+ labels = {"create": ui.green("new "), "merge": ui.yellow("merge "), "wire": ui.yellow("wire "),
114
+ "same": ui.dim("same "), "manual": ui.cyan("manual"), "deps": ui.yellow("deps "), "env": ui.yellow("env ")}
115
+ for c in changes:
116
+ extra = f" (+ {', '.join(c.added)})" if c.kind in ("merge", "deps", "env") else ""
117
+ ui.info(f"{labels.get(c.kind, c.kind)} {c.target} {ui.dim(c.reason + extra)}")
118
+ if bundle.get("adapted"):
119
+ ui.info(ui.cyan("adapted to this project: ") + "; ".join(bundle["adapted"]))
120
+ todo = [c for c in changes if c.new_text is not None]
121
+ if not todo:
122
+ ui.info(ui.dim("Nothing to write: everything is already in this project."))
123
+ if args.dry_run or not todo:
124
+ return 0
125
+ if not args.yes and ui.ask(f"\nReview and copy {len(todo)} file(s)?", "yn", "y") != "y":
126
+ return 0
127
+
128
+ written, _ = _review(root, todo, args.yes)
129
+ if written:
130
+ api.event("copied", bundle["repo"], project=root.name, files=[c.target for c, _ in written],
131
+ picked=chosen["path"], adapted=bundle.get("adapted") or [])
132
+ text = "\n".join(c.new_text or "" for c, _ in written)
133
+ env = [k for c, _ in written if c.kind == "env" for k in c.added] or reuse.env_missing(root, bundle, text)
134
+ _followups(changes, reuse.packages_needed(bundle, text), env)
135
+ return 0
136
+
137
+
138
+ def _review(root: Path, todo: list[reuse.Change], yes: bool) -> tuple[list, list]:
139
+ """Show each diff and write the ones the user approves. Returns (written [(change, note)], skipped)."""
140
+ backup_dir = root / ".tracebase" / "backups" / time.strftime("%Y%m%d-%H%M%S")
141
+ written, skipped, apply_all = [], [], yes
142
+ for i, c in enumerate(todo):
143
+ ui.header(f"{c.target} {ui.dim('from ' + c.source)}")
144
+ print(ui.diff(c.target, c.old_text, c.new_text))
145
+ choice = "y" if apply_all else ui.ask(f"Write {c.target}? (y)es (n)o (e)dit (a)ll (q)uit", "yneaq", "y")
146
+ if choice == "e":
147
+ c.new_text = _edit(c.new_text, Path(c.target).suffix)
148
+ choice = "y"
149
+ if choice == "a":
150
+ apply_all, choice = True, "y"
151
+ if choice == "q":
152
+ skipped += [x.target for x in todo[i:]]
153
+ break
154
+ if choice == "y":
155
+ written.append((c, reuse.apply(root, c, backup_dir)))
156
+ ui.info(ui.green("✓ written"))
157
+ else:
158
+ skipped.append(c.target)
159
+
160
+ ui.header("Done")
161
+ for c, note in written:
162
+ ui.info(f"{ui.green('✓')} {note:8} {c.target}")
163
+ for t in skipped:
164
+ ui.info(f"{ui.dim('–')} skipped {ui.dim(t)}")
165
+ if any(n == "updated" for _, n in written):
166
+ ui.info(ui.dim(f"Originals backed up to {backup_dir.relative_to(root)}/"))
167
+ return written, skipped
168
+
169
+
170
+ def _followups(changes: list[reuse.Change], pkgs: list[dict], env: list[str]) -> None:
171
+ manual = [(c, sn) for c in changes for sn in c.manual]
172
+ if manual or pkgs or env:
173
+ ui.header("Still to do by hand")
174
+ for c, sn in manual:
175
+ where = f" (it was inside: {sn['inside']})" if sn.get("inside") else ""
176
+ ui.info(f"• {c.target}: add {ui.bold(sn['line'].strip())}{ui.dim(where)}")
177
+ for step in plans.install_steps(pkgs):
178
+ ui.info(f"• {step}")
179
+ if env:
180
+ ui.info(f"• set in your .env: {', '.join(env)}")
181
+ ui.info(ui.dim("Review with `git diff` and adjust names to this project before committing."))
182
+
183
+
184
+ # ---------------------------------------------------------------- plans made by AI agents (MCP)
185
+ def cmd_pending(args: argparse.Namespace, api: Client) -> int:
186
+ root = Path(args.path).resolve()
187
+ items = plans.pending(root)
188
+ if not items:
189
+ ui.info(ui.dim("No pending copies in this project."))
190
+ return 0
191
+ for p in items:
192
+ ui.header(f"{ui.bold(p['id'])} {ui.dim(p['created'])} {p.get('request') or ''}")
193
+ print(plans.summary(p))
194
+ ui.info(ui.dim("\nReview and write one with `tracebase apply <id>`, or drop it with `tracebase discard <id>`."))
195
+ return 0
196
+
197
+
198
+ def cmd_apply(args: argparse.Namespace, api: Client) -> int:
199
+ root = Path(args.path).resolve()
200
+ if not args.id:
201
+ items = plans.pending(root)
202
+ if len(items) != 1:
203
+ ui.error("Which one? " + (", ".join(p["id"] for p in items) if items else "no pending copies here"))
204
+ return 2
205
+ args.id = items[0]["id"]
206
+ plan = plans.load(root, args.id)
207
+ bad = plans.stale(root, plan)
208
+ if bad:
209
+ ui.error("These files changed after the preview, ask your agent to preview again: " + ", ".join(bad))
210
+ return 1
211
+ ui.header(f"Pending copy {plan['id']}")
212
+ print(plans.summary(plan))
213
+ changes = plans.changes(plan)
214
+ todo = [c for c in changes if c.new_text is not None]
215
+ if not args.yes and ui.ask(f"\nReview and copy {len(todo)} file(s)?", "yn", "y") != "y":
216
+ return 0
217
+ written, _ = _review(root, todo, args.yes)
218
+ if written:
219
+ plans.discard(root, plan["id"])
220
+ api.event("copied", plan["repo"], project=root.name, files=[c.target for c, _ in written],
221
+ picked=", ".join(plan["picked"]), adapted=plan.get("adapted") or [], via="tracebase apply")
222
+ _followups(changes, plan["packages"], plan["env"])
223
+ return 0
224
+
225
+
226
+ def cmd_discard(args: argparse.Namespace, api: Client) -> int:
227
+ root = Path(args.path).resolve()
228
+ plans.load(root, args.id)
229
+ plans.discard(root, args.id)
230
+ ui.info(f"Discarded {args.id}.")
231
+ return 0
232
+
233
+
234
+ # ---------------------------------------------------------------- connect an AI agent
235
+ def cmd_connect(args: argparse.Namespace, api: Client) -> int:
236
+ home = Path.home()
237
+ if args.print:
238
+ print(connect.snippet())
239
+ return 0
240
+ if not args.agent:
241
+ found = connect.detected()
242
+ ui.header("Connect Tracebase to your AI agent")
243
+ for k, (_, label, exe) in connect.AGENTS.items():
244
+ mark = ui.green("● installed") if k in found else ui.dim("○ not found")
245
+ ui.info(f" tracebase connect {k:9} {label:36} {mark}")
246
+ ui.info(ui.dim("\nAny other MCP client: `tracebase connect --print` shows the config to paste."))
247
+ return 0
248
+ targets = connect.detected() if args.agent == "all" else [args.agent]
249
+ if not targets:
250
+ ui.error("No supported agent found on PATH.")
251
+ return 1
252
+ for k in targets:
253
+ fn, label, _ = connect.AGENTS[k]
254
+ try:
255
+ ui.info(f"{ui.green('✓')} {label}: {fn(home)}")
256
+ except Exception as e:
257
+ ui.error(f"{label}: {e}")
258
+ return 1
259
+ ui.info(ui.dim("Restart the agent, open your project folder in it and ask e.g. "
260
+ "\"copy the login logic from my old projects\". It will show you the code and ask before writing."))
261
+ return 0
262
+
263
+
264
+ # ---------------------------------------------------------------- read-only commands
265
+ def cmd_find(args: argparse.Namespace, api: Client) -> int:
266
+ task = " ".join(args.task)
267
+ ctx = None if args.anywhere else project.context(Path(args.path).resolve(), task, max_files=4)
268
+ with ui.Spinner("Searching your projects"):
269
+ res = api.examples(task, project=ctx, limit=args.limit)
270
+ if ctx:
271
+ ui.info(ui.dim(f"this project: {res.get('stack_text') or '?'}"))
272
+ for e in res["examples"]:
273
+ ui.header(f"[{e['id']}] {e['repo']}/{e['path']}:{e['lines'][0]}-{e['lines'][1]} {ui.dim(e['symbol'] or '')}")
274
+ body = e["code"].splitlines()
275
+ print("\n".join(f" {ui.dim(str(e['lines'][0] + n).rjust(4))} {ln}" for n, ln in enumerate(body[:args.lines])))
276
+ if len(body) > args.lines:
277
+ ui.info(ui.dim(f"… {len(body) - args.lines} more lines"))
278
+ return 0 if res["examples"] else 1
279
+
280
+
281
+ def cmd_search(args: argparse.Namespace, api: Client) -> int:
282
+ res = api.search(" ".join(args.query), repo=args.repo, language=args.language, limit=args.limit)
283
+ for r in res["results"]:
284
+ meta = f"{r['language']} · {r['score']:.2f}"
285
+ print(f"{ui.teal(r['repo'])} {r['path']}:{r['lines'][0]}-{r['lines'][1]} {ui.bold(r['symbol'] or '')} {ui.dim(meta)}")
286
+ if not res["results"]:
287
+ print(ui.dim("no matches"))
288
+ return 0
289
+
290
+
291
+ def cmd_show(args: argparse.Namespace, api: Client) -> int:
292
+ res = api.read(args.repo, args.file, args.start, args.end)
293
+ for ln in res["lines"]:
294
+ print(f"{ui.dim(str(ln['n']).rjust(5))} {ln['text']}")
295
+ return 0
296
+
297
+
298
+ def cmd_status(args: argparse.Namespace, api: Client) -> int:
299
+ h = api.health()
300
+ repos = api.repos()
301
+ print(f"{ui.green('●')} Tracebase {h.get('version')} at {api.url}")
302
+ if h.get("team"):
303
+ me = api.me()
304
+ print(f" team server · signed in as {ui.bold(me['name'])} ({me['role']}) · repos: {', '.join(me['repos'])}")
305
+ print(f" {len(repos)} repos visible" + ("" if h.get("team") else f", indexed from {h.get('repos_dir')}"))
306
+ return 0
307
+
308
+
309
+ # ---------------------------------------------------------------- Log Detective
310
+ STATUS_COLOR = {"new": ui.yellow, "regressed": ui.red, "known": ui.dim, "resolved": ui.green, "ignored": ui.dim}
311
+
312
+
313
+ def _gid(v: str) -> str:
314
+ v = v.strip().upper()
315
+ return v if v.startswith("E-") else f"E-{v}"
316
+
317
+
318
+ def cmd_errors(args: argparse.Namespace, api: Client) -> int:
319
+ since = None if args.all else args.since
320
+ groups = api.errors(service=args.service, since=since, status=args.status, q=args.grep, limit=args.limit)
321
+ if not groups:
322
+ print(ui.dim("no errors" + (f" since {since}" if since else "")))
323
+ return 0
324
+ head = f"Errors{' since ' + since if since else ''}" + (f" in {args.service}" if args.service else "")
325
+ ui.header(head)
326
+ for g in groups:
327
+ n = g.get("window_count") if since else g["count"]
328
+ flag = ui.red(" ▲ spike") if g.get("spike") else ""
329
+ st = STATUS_COLOR.get(g["status"], str)(g["status"])
330
+ print(f" {ui.bold(g['code'].ljust(6))} {ui.teal(g['service'][:14].ljust(14))} {str(n).rjust(6)}x "
331
+ f"{st.ljust(18 if ui.COLOR else 9)} {g['title'][:70]}{flag}")
332
+ print(ui.dim(f"\n tracebase why {groups[0]['code']} explain one (cause, failing code, fix)"))
333
+ return 0
334
+
335
+
336
+ def cmd_why(args: argparse.Namespace, api: Client) -> int:
337
+ gid = _gid(args.id)
338
+ g = api.error(gid)
339
+ with ui.Spinner(f"Investigating {gid}"):
340
+ r = api.explain_error(gid, refresh=args.refresh)
341
+ ui.header(f"{gid} {g['service']} · {g['title'][:90]}")
342
+ print(f" {ui.dim(str(g['count']) + ' times · first ' + g['first_seen'].replace('T', ' ') + ' · last ' + g['last_seen'].replace('T', ' ') + ' · ' + g['status'])}")
343
+ print(f"\n{ui.bold('Why')}\n {r['cause']}")
344
+ print(f"\n{ui.bold('Impact')}\n {r['impact']}")
345
+ if r.get("events"):
346
+ print(f"\n{ui.bold('Around the same time in other services')}")
347
+ for e in r["events"][:6]:
348
+ print(f" {ui.dim(e['ts'].replace('T', ' ')[5:19])} {ui.teal(e['service'])} {e['message'][:100]}")
349
+ for c in (r.get("code") or [])[:2]:
350
+ print(f"\n{ui.bold('Code')} {ui.teal(c['repo'])}/{c['path']}:{c['line']}" + (f" {ui.dim(c['func'])}" if c.get("func") else ""))
351
+ for ln in c["snippet"]:
352
+ mark = ui.red("›") if ln["n"] == c["line"] else " "
353
+ text = ui.red(ln["text"]) if ln["n"] == c["line"] else ln["text"]
354
+ print(f" {mark}{ui.dim(str(ln['n']).rjust(4))} {text}")
355
+ cm = r.get("commit")
356
+ if cm:
357
+ when = cm.get("minutes_before_first_error")
358
+ lag = f", {when} min before the first error" if when is not None and 0 <= when < 1440 else ""
359
+ print(f"\n{ui.bold('Last changed by')} {ui.yellow(cm['sha'])} {cm['message']} {ui.dim(cm['author'] + ', ' + cm['date'] + lag)}")
360
+ if r.get("fix"):
361
+ print(f"\n{ui.bold('Fix')}")
362
+ for i, f in enumerate(r["fix"], 1):
363
+ print(f" {i}. {f}")
364
+ src = "rules + your code and git history" if r.get("source") == "rules" else f"local LLM ({r.get('source')})"
365
+ print(ui.dim(f"\n explained by {src} · mark it: tracebase resolve {gid} [--as known|ignored]"))
366
+ return 0
367
+
368
+
369
+ def cmd_resolve(args: argparse.Namespace, api: Client) -> int:
370
+ gid = _gid(args.id)
371
+ api.set_error_status(gid, args.status)
372
+ print(f"{ui.green('✓')} {gid} marked {args.status}" +
373
+ (ui.dim(" (it reopens as 'regressed' if it happens again)") if args.status == "resolved" else ""))
374
+ return 0
375
+
376
+
377
+ def cmd_ingest(args: argparse.Namespace, api: Client) -> int:
378
+ total = {"events": 0, "errors": 0, "new_groups": []}
379
+ for f in args.files:
380
+ text = sys.stdin.read() if f == "-" else Path(f).read_text(errors="replace")
381
+ svc = args.service or (None if f == "-" else Path(f).name.split(".")[0]) # payments.log -> payments
382
+ res = api.ingest(text, service=svc)
383
+ for k in ("events", "errors"):
384
+ total[k] += res.get(k, 0)
385
+ total["new_groups"] += res.get("new_groups", [])
386
+ print(f"{ui.green('✓')} {total['events']} log lines, {total['errors']} errors/warnings"
387
+ + (f", new: {', '.join(total['new_groups'])}" if total["new_groups"] else ""))
388
+ return 0
389
+
390
+
391
+ def cmd_alerts(args: argparse.Namespace, api: Client) -> int:
392
+ items = api.alerts(unread=not args.all)
393
+ if not items:
394
+ print(ui.dim("no unread alerts" if not args.all else "no alerts"))
395
+ for a in items:
396
+ sev = ui.red("●") if a["severity"] == "critical" else ui.yellow("●")
397
+ print(f"{sev} {ui.dim(a['created_at'][5:16])} {a['title']}")
398
+ for line in (a.get("body") or "").splitlines()[:2]:
399
+ print(f" {ui.dim(line[:110])}")
400
+ if args.read and items:
401
+ api.read_alerts()
402
+ print(ui.dim("marked as read"))
403
+ return 0
404
+
405
+
406
+ # ---------------------------------------------------------------- team mode
407
+ def cmd_login(args: argparse.Namespace, api: Client) -> int:
408
+ url = (args.url or api.url).rstrip("/")
409
+ me = Client(url, token=args.token).me() # verify before saving
410
+ save_config({"url": url, "token": args.token})
411
+ ui.info(f"{ui.green('✓')} Signed in to {url} as {ui.bold(me['name'])} ({me['role']}). "
412
+ f"Saved to {CONFIG} (only you can read it).")
413
+ ui.info(ui.dim("Your AI agent's `tracebase mcp` uses this login too: no token goes into its config."))
414
+ return 0
415
+
416
+
417
+ def cmd_logout(args: argparse.Namespace, api: Client) -> int:
418
+ cfg = load_config()
419
+ if cfg.pop("token", None):
420
+ save_config(cfg)
421
+ ui.info("Signed out.")
422
+ return 0
423
+
424
+
425
+ def cmd_team(args: argparse.Namespace, api: Client) -> int:
426
+ if args.action == "list":
427
+ for m in api.members():
428
+ seen = m.get("last_seen") or "never"
429
+ print(f"{ui.bold(m['name']):24} {m['role']:7} repos: {', '.join(m['repos']):40} {ui.dim('last seen ' + seen)}")
430
+ return 0
431
+ if args.action == "audit":
432
+ for e in reversed(api.audit(args.user, args.what, args.limit)):
433
+ d = e["detail"]
434
+ what = d.get("task") or d.get("question") or ", ".join(d.get("files") or d.get("paths") or []) or \
435
+ ", ".join(f"{k}={v}" for k, v in d.items())
436
+ print(f"{ui.dim(e['at'])} {ui.bold(e['user']):14} {e['action']:14} {ui.teal(e['repo'] or '')} {what[:90]}")
437
+ return 0
438
+ if not args.name:
439
+ ui.error(f"tracebase team {args.action} needs a member name")
440
+ return 2
441
+ if args.action == "add":
442
+ res = api.add_member(args.name, args.repos or ["*"], "admin" if args.admin else "member")
443
+ ui.info(f"{ui.green('✓')} Added {ui.bold(args.name)} with access to: {', '.join(args.repos or ['*'])}")
444
+ ui.info(f"Token (shown once, send it privately): {ui.bold(res['token'])}")
445
+ ui.info(ui.dim(f"They run: tracebase login {res['token']} --url {api.url}"))
446
+ elif args.action == "repos":
447
+ api.set_member_repos(args.name, args.repos or ["*"])
448
+ ui.info(f"{ui.green('✓')} {args.name} now sees: {', '.join(args.repos or ['*'])}")
449
+ elif args.action == "rotate":
450
+ res = api.rotate_member(args.name)
451
+ ui.info(f"{ui.green('✓')} New token for {args.name} (the old one stopped working): {ui.bold(res['token'])}")
452
+ elif args.action == "remove":
453
+ api.remove_member(args.name)
454
+ ui.info(f"{ui.green('✓')} Removed {args.name}; their token no longer works.")
455
+ return 0
456
+
457
+
458
+ # ---------------------------------------------------------------- data & privacy (admin)
459
+ def _size(n: int) -> str:
460
+ for unit in ("B", "KB", "MB", "GB"):
461
+ if n < 1024:
462
+ return f"{n:.0f} {unit}"
463
+ n /= 1024
464
+ return f"{n:.1f} TB"
465
+
466
+
467
+ def _confirm(question: str, yes: bool) -> bool:
468
+ if yes:
469
+ return True
470
+ if not sys.stdin.isatty():
471
+ ui.error("refusing to delete without confirmation: pass --yes")
472
+ return False
473
+ return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
474
+
475
+
476
+ def _deleted(res: dict) -> str:
477
+ d = res.get("deleted") or res.get("would_delete") or {}
478
+ return ", ".join(f"{v} {k.replace('_', ' ')}" for k, v in d.items() if v) or "nothing"
479
+
480
+
481
+ def cmd_data(args: argparse.Namespace, api: Client) -> int:
482
+ a = args.action
483
+ if a == "summary":
484
+ s = api.data_summary()
485
+ db, c = s["database"], s["counts"]
486
+ print(f"{ui.bold('Database')} {db['path']} {_size(db['size_bytes'])} "
487
+ + (ui.green("encrypted") if db["encrypted"] else ui.yellow("not encrypted (set TRACEBASE_DB_KEY)")))
488
+ print(f"{ui.bold('Code')} {c['repos']} repos, {c['files']} files, {c['chunks']} code chunks, "
489
+ f"{c['secrets']} secrets findings")
490
+ span = f" ({s['logs']['oldest'] or '-'} → {s['logs']['newest'] or '-'})" if c["log_events"] else ""
491
+ print(f"{ui.bold('Logs')} {c['log_events']} log lines{span}, {c['error_groups']} error groups, "
492
+ f"{c['alerts']} alerts")
493
+ print(f"{ui.bold('Team')} {c['users']} members, {c['audit']} audit entries")
494
+ r = s["redaction"]
495
+ print(f"{ui.bold('Redaction')} " + (ui.green("on") + (", IPs too" if r["ips"] else ", IPs kept")
496
+ + (", custom patterns" if r["custom_patterns"] else "")
497
+ if r["enabled"] else ui.yellow("off: personal data in logs is stored")))
498
+ print(f"{ui.bold('Retention')} " + ", ".join(f"{k.replace('_', ' ')} {v}d" if v else f"{k.replace('_', ' ')} forever"
499
+ for k, v in s["retention_days"].items()))
500
+ ex = s["excluded"]
501
+ if ex["repos"] or ex["services"]:
502
+ print(f"{ui.bold('Forgotten')} repos: {', '.join(ex['repos']) or '-'} · services: {', '.join(ex['services']) or '-'}")
503
+ o = s["outbound"]
504
+ print(f"{ui.bold('Outbound')} alert webhook: {'on' if o['alert_webhook'] else 'off'} · "
505
+ f"LLM: {o['llm']['provider']} at {o['llm']['base_url']}")
506
+ return 0
507
+ if a == "prune":
508
+ print(f"{ui.green('✓')} Retention applied: deleted {_deleted(api.data_prune())}")
509
+ return 0
510
+ if a == "export":
511
+ out_path = args.output or f"tracebase-export-{args.service or 'all'}.ndjson"
512
+ if out_path == "-":
513
+ n = api.export(sys.stdout, service=args.service, match=args.match)
514
+ else:
515
+ fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) # personal data: owner-only
516
+ with os.fdopen(fd, "w", encoding="utf-8") as out:
517
+ n = api.export(out, service=args.service, match=args.match)
518
+ if out_path != "-":
519
+ ui.info(f"{ui.green('✓')} {n} records written to {out_path} (only you can read it)")
520
+ return 0
521
+ if a == "wipe":
522
+ if not _confirm("Delete EVERYTHING Tracebase stored (code index, logs, errors, alerts"
523
+ + ("" if args.keep_team else ", members, audit log") + ")?", args.yes):
524
+ return 1
525
+ api.wipe(keep_team=args.keep_team)
526
+ ui.info(f"{ui.green('✓')} All stored data deleted. The code index is rebuilt from the repos folder on the next run.")
527
+ return 0
528
+ if not args.name:
529
+ ui.error(f"tracebase data {a} needs a name (or text to match)")
530
+ return 2
531
+ if a == "forget-repo":
532
+ if not _confirm(f"Delete the index of {args.name} and stop indexing it?", args.yes):
533
+ return 1
534
+ res = api.forget_repo(args.name)
535
+ ui.info(f"{ui.green('✓')} Forgot {args.name}: deleted {_deleted(res)}. It won't be indexed again "
536
+ f"(`tracebase data restore-repo {args.name}` to undo). The folder on disk is untouched.")
537
+ elif a == "restore-repo":
538
+ api.restore_repo(args.name)
539
+ ui.info(f"{ui.green('✓')} {args.name} will be indexed again on the next run.")
540
+ elif a == "forget-service":
541
+ if not _confirm(f"Delete all logs, errors and alerts of {args.name}?", args.yes):
542
+ return 1
543
+ res = api.forget_service(args.name, exclude=args.stop)
544
+ ui.info(f"{ui.green('✓')} Deleted {_deleted(res)} of {args.name}."
545
+ + (" New logs for it are dropped." if args.stop else ""))
546
+ elif a == "restore-service":
547
+ api.restore_service(args.name)
548
+ ui.info(f"{ui.green('✓')} Logs for {args.name} are accepted again.")
549
+ elif a == "purge":
550
+ preview = api.purge(args.name, service=args.service, dry_run=True)
551
+ if not any((preview.get("would_delete") or {}).values()):
552
+ ui.info("Nothing stored contains that text.")
553
+ return 0
554
+ if args.dry_run or not _confirm(f"Delete {_deleted(preview)} containing that text?", args.yes):
555
+ ui.info(f"Would delete: {_deleted(preview)}")
556
+ return 0
557
+ ui.info(f"{ui.green('✓')} Deleted {_deleted(api.purge(args.name, service=args.service))}")
558
+ return 0
559
+
560
+
561
+ def cmd_mcp(args: argparse.Namespace, api: Client) -> int:
562
+ from .mcp_server import run
563
+ run(api)
564
+ return 0
565
+
566
+
567
+ def main(argv: list[str] | None = None) -> int:
568
+ p = argparse.ArgumentParser(prog="tracebase", description="Find code you already wrote and copy it here.",
569
+ formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__.split("\n", 2)[2])
570
+ p.add_argument("--url", help="Tracebase server (default $TRACEBASE_URL or http://localhost:8080)")
571
+ p.add_argument("--version", action="version", version=f"tracebase {__version__}")
572
+ sub = p.add_subparsers(dest="cmd", required=True)
573
+
574
+ c = sub.add_parser("copy", help="find code in your old projects and copy it into this one")
575
+ c.add_argument("task", nargs="+", help='what to copy, e.g. "login logic"')
576
+ c.add_argument("--path", default=".", help="project to copy into (default: current folder)")
577
+ c.add_argument("--from", dest="repo", help="only take code from this repo")
578
+ c.add_argument("--pick", type=int, help="pick result N without asking")
579
+ c.add_argument("--dry-run", action="store_true", help="show what would be copied, write nothing")
580
+ c.add_argument("--rename", action="append", default=[], metavar="OLD=NEW",
581
+ help="rename a word in the copied code and file names, every spelling (e.g. Doctor=Staff); repeatable")
582
+ c.add_argument("-y", "--yes", action="store_true", help="take the best match and write without asking")
583
+ c.set_defaults(fn=cmd_copy)
584
+
585
+ f = sub.add_parser("find", help="show your past implementations of something, with code")
586
+ f.add_argument("task", nargs="+")
587
+ f.add_argument("--path", default=".")
588
+ f.add_argument("--anywhere", action="store_true", help="don't prefer this project's language/framework")
589
+ f.add_argument("--limit", type=int, default=5)
590
+ f.add_argument("--lines", type=int, default=40)
591
+ f.set_defaults(fn=cmd_find)
592
+
593
+ s = sub.add_parser("search", help="search across all your repos")
594
+ s.add_argument("query", nargs="+")
595
+ s.add_argument("--repo")
596
+ s.add_argument("--language")
597
+ s.add_argument("--limit", type=int, default=10)
598
+ s.set_defaults(fn=cmd_search)
599
+
600
+ sh = sub.add_parser("show", help="print a file from one of your repos")
601
+ sh.add_argument("repo")
602
+ sh.add_argument("file")
603
+ sh.add_argument("--start", type=int)
604
+ sh.add_argument("--end", type=int)
605
+ sh.set_defaults(fn=cmd_show)
606
+
607
+ pe = sub.add_parser("pending", help="copies your AI agent prepared and that wait for your approval")
608
+ pe.add_argument("--path", default=".")
609
+ pe.set_defaults(fn=cmd_pending)
610
+
611
+ ap = sub.add_parser("apply", help="review a pending copy and write it into this project")
612
+ ap.add_argument("id", nargs="?")
613
+ ap.add_argument("--path", default=".")
614
+ ap.add_argument("-y", "--yes", action="store_true", help="write without asking")
615
+ ap.set_defaults(fn=cmd_apply)
616
+
617
+ di = sub.add_parser("discard", help="drop a pending copy")
618
+ di.add_argument("id")
619
+ di.add_argument("--path", default=".")
620
+ di.set_defaults(fn=cmd_discard)
621
+
622
+ co = sub.add_parser("connect", help="connect Tracebase to your AI agent (Claude Code, Codex, Gemini, opencode, Ollama…)")
623
+ co.add_argument("agent", nargs="?", choices=[*connect.AGENTS, "all"])
624
+ co.add_argument("--print", action="store_true", help="print MCP config for any other client")
625
+ co.set_defaults(fn=cmd_connect)
626
+
627
+ lo = sub.add_parser("login", help="sign in to a team Tracebase server with your token")
628
+ lo.add_argument("token")
629
+ lo.add_argument("--url", default=argparse.SUPPRESS, help="the team server, e.g. http://nas.local:8080")
630
+ lo.set_defaults(fn=cmd_login)
631
+ sub.add_parser("logout", help="forget the saved token").set_defaults(fn=cmd_logout)
632
+
633
+ tm = sub.add_parser("team", help="team server admin: members, repo access, audit log")
634
+ tm.add_argument("action", choices=["list", "add", "repos", "rotate", "remove", "audit"])
635
+ tm.add_argument("name", nargs="?")
636
+ tm.add_argument("--repos", nargs="+", metavar="PATTERN", help='repos they can see, e.g. "freelance/*" shop-api')
637
+ tm.add_argument("--admin", action="store_true", help="make them an admin")
638
+ tm.add_argument("--user", help="audit: only this member")
639
+ tm.add_argument("--what", help="audit: only this action (find, bundle, copied, ask…)")
640
+ tm.add_argument("--limit", type=int, default=50)
641
+ tm.set_defaults(fn=cmd_team)
642
+
643
+ er = sub.add_parser("errors", help="production errors, grouped (Log Detective)")
644
+ er.add_argument("--since", default="24h", help='"last night", "2h", "yesterday 18:00", ... (default 24h)')
645
+ er.add_argument("--all", action="store_true", help="any time")
646
+ er.add_argument("--service")
647
+ er.add_argument("--status", choices=["new", "regressed", "known", "resolved", "ignored"])
648
+ er.add_argument("--grep", help="only errors whose message contains this")
649
+ er.add_argument("--limit", type=int, default=20)
650
+ er.set_defaults(fn=cmd_errors)
651
+ wy = sub.add_parser("why", help="explain an error: cause, failing code, the commit, fix")
652
+ wy.add_argument("id", help="E-5 or 5")
653
+ wy.add_argument("--refresh", action="store_true", help="investigate again instead of the saved explanation")
654
+ wy.set_defaults(fn=cmd_why)
655
+ rs = sub.add_parser("resolve", help="mark an error resolved (or known / ignored)")
656
+ rs.add_argument("id")
657
+ rs.add_argument("--as", dest="status", default="resolved", choices=["resolved", "known", "ignored", "new"])
658
+ rs.set_defaults(fn=cmd_resolve)
659
+ ig = sub.add_parser("ingest", help="send log files (or stdin: -) to Tracebase")
660
+ ig.add_argument("files", nargs="+")
661
+ ig.add_argument("--service", help="service name (default: from the log lines / file name)")
662
+ ig.set_defaults(fn=cmd_ingest)
663
+ al = sub.add_parser("alerts", help="new error types and error spikes")
664
+ al.add_argument("--all", action="store_true", help="include read alerts")
665
+ al.add_argument("--read", action="store_true", help="mark them as read")
666
+ al.set_defaults(fn=cmd_alerts)
667
+
668
+ da = sub.add_parser("data", help="what is stored, export it, delete it (admin)",
669
+ description="Data & privacy: see what Tracebase stores, export it, and delete it.",
670
+ epilog="""examples:
671
+ tracebase data what is stored, encryption, redaction, retention
672
+ tracebase data export --service shop-api everything stored about a service (NDJSON)
673
+ tracebase data purge "CUST-10442" erase every log line / error / alert containing it
674
+ tracebase data forget-repo client-a/old-site delete a repo's index and stop indexing it
675
+ tracebase data forget-service payments --stop delete a service's logs and drop new ones
676
+ tracebase data prune apply the retention periods now""",
677
+ formatter_class=argparse.RawDescriptionHelpFormatter)
678
+ da.add_argument("action", nargs="?", default="summary",
679
+ choices=["summary", "export", "purge", "forget-repo", "restore-repo", "forget-service",
680
+ "restore-service", "prune", "wipe"])
681
+ da.add_argument("name", nargs="?", help="repo, service, or the text to purge")
682
+ da.add_argument("--service", help="export / purge: only this service")
683
+ da.add_argument("--match", help="export: only records containing this text")
684
+ da.add_argument("-o", "--output", help="export: file to write (- for stdout)")
685
+ da.add_argument("--stop", action="store_true", help="forget-service: also drop new logs for it")
686
+ da.add_argument("--dry-run", action="store_true", help="purge: only count what would be deleted")
687
+ da.add_argument("--keep-team", action=argparse.BooleanOptionalAction, default=True,
688
+ help="wipe: keep members and the audit log (default)")
689
+ da.add_argument("-y", "--yes", action="store_true", help="delete without asking")
690
+ da.set_defaults(fn=cmd_data)
691
+
692
+ sub.add_parser("status", help="check the connection to the Tracebase server").set_defaults(fn=cmd_status)
693
+ sub.add_parser("mcp", help="MCP server (stdio) for your AI assistant").set_defaults(fn=cmd_mcp)
694
+
695
+ args = p.parse_args(argv)
696
+ api = Client(args.url)
697
+ try:
698
+ return args.fn(args, api)
699
+ except (TracebaseError, reuse.CopyError) as e:
700
+ ui.error(str(e))
701
+ return 1
702
+ except KeyboardInterrupt:
703
+ print()
704
+ return 130
705
+
706
+
707
+ if __name__ == "__main__":
708
+ sys.exit(main())