Repository navigation
Expand file tree
/
Copy pathstackradar.py
More file actions
7811 lines (7154 loc) · 360 KB
/
Copy pathstackradar.py
File metadata and controls
7811 lines (7154 loc) · 360 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
StackRadar — a local radar for your developer workspace.
Copyright (c) 2026 Yasir Jilani. Free for personal, non-commercial use under the
PolyForm Noncommercial License 1.0.0 (see LICENSE). Commercial use: see COMMERCIAL.md.
Scans a folder tree and tells you, for every project/repo/app it finds:
* what it is (purpose, language, framework), where it lives, how big it is
* how to run it + what it needs (dependencies, env, ports)
* which ports it should use and which are actually open right now
* API keys / secrets found (masked, never sent anywhere)
* risk flags (rough vulnerability check)
* when it was last run, running processes
* version control (git branch / remote / commits / dirty state)
* where it came from (git remote host, docker registry, "local only")
* AI / IDE traces (Claude Code, Cursor, VS Code, Windsurf, Antigravity...)
incl. LLM model + input/output token usage when logs exist
* document types + natural language of docs
* installed packages (project venv/node_modules + global npm/pip/brew/docker)
* terminal environment (shell, rc files, exports, aliases, PATH)
Plus: interactive lineage graph, and safe delete / move / rename actions
to reclaim space.
100% local. Python 3.9+ standard library only. Nothing ever leaves your machine.
Usage:
python3 stackradar.py [--port 8765] [--root PATH ...] [--depth 6] [--open]
"""
import argparse
import concurrent.futures
import getpass
import hashlib
import secrets as secretsmod
import glob as globmod
import json
import os
import platform
import re
import shutil
import signal
import socket
import sqlite3
import subprocess
import sys
import threading
import time
import traceback
import urllib.parse
import webbrowser
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# Where the UI files (index.html, static/, VERSION) live:
# - frozen by PyInstaller (desktop build): the bundle dir
# - run from a checkout: next to this file
# - installed as a package (pip / pipx / uv tool): the stackradar_app/ data folder beside this module
_HERE = os.path.dirname(os.path.abspath(__file__))
APP_DIR = getattr(sys, "_MEIPASS", None) or (
_HERE if os.path.isfile(os.path.join(_HERE, "index.html")) else os.path.join(_HERE, "stackradar_app"))
OS_NAME = platform.system() # 'Darwin' | 'Linux' | 'Windows'
def _read_version():
for d in (APP_DIR, os.path.dirname(os.path.abspath(__file__))):
try:
with open(os.path.join(d, "VERSION")) as f:
return f.read().strip()
except Exception:
continue
return "0.0.0"
VERSION = _read_version()
# per-launch secret: every state-changing request must carry it (blocks CSRF from
# other websites open in your browser). It is injected into index.html only.
API_TOKEN = secretsmod.token_urlsafe(24)
# dirs that we SIZE but never descend into (contents are not interesting)
CONTENT_SKIP_DIRS = {
"node_modules", "site-packages", ".git", "venv", ".venv", "env", ".env-dir",
"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".next", ".nuxt",
".cache", ".npm", ".turbo", ".venv-tmp",
}
# top-level hidden dirs we never even enter
TOP_SKIP_DIRS = {".Trash", ".trash", ".git", ".hg", ".svn"}
MAX_READ_BYTES = 300_000 # per file for pattern scanning
MAX_DETAIL_FILES = 600 # per project file-level work cap
MAX_LINE_LEN = 500
# ---------------------------------------------------------------------------
# small helpers
# ---------------------------------------------------------------------------
def fmt_bytes(n):
try:
n = float(n)
except Exception:
return "?"
for unit in ("B", "KB", "MB", "GB", "TB"):
if abs(n) < 1024 or unit == "TB":
return ("%.0f " if unit == "B" else "%.1f ") % n + unit
n /= 1024.0
return "?"
def fmt_ago(ts):
if not ts:
return "never / unknown"
d = time.time() - ts
if d < 90:
return "just now"
if d < 3600:
return "%d min ago" % int(d // 60)
if d < 86400:
return "%d h ago" % int(d // 3600)
if d < 86400 * 30:
return "%d days ago" % int(d // 86400)
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
def run_cmd(args, timeout=15, cwd=None):
"""Run a command, return (ok, stdout_text). Never raises."""
try:
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout, cwd=cwd)
return p.returncode == 0, (p.stdout or "") + (p.stderr or "")
except Exception:
return False, ""
def read_head(path, limit=MAX_READ_BYTES):
try:
with open(path, "rb") as f:
return f.read(limit).decode("utf-8", "replace")
except Exception:
return ""
def walk_files(root, cap_files=MAX_DETAIL_FILES, cap_bytes=4_000_000,
include_hidden=True, skip_dirs=None, skip_paths=None):
"""Collect file paths under root, pruning big dep dirs (and the folders in skip_paths, e.g. nested
projects that are scanned on their own). Returns (paths, truncated)."""
skip = set(skip_dirs or ()) | CONTENT_SKIP_DIRS | {".git"}
skip_p = set(skip_paths or ())
out, files, total = [], 0, 0
truncated = False
stack = [root]
while stack:
d = stack.pop()
try:
it = os.scandir(d)
except Exception:
continue
with it:
entries = sorted(it, key=lambda e: e.name)
for e in entries:
try:
name = e.name
if e.is_symlink():
continue
if e.is_dir(follow_symlinks=False):
if name in skip or e.path in skip_p:
continue
stack.append(e.path)
elif e.is_file(follow_symlinks=False):
if files >= cap_files:
truncated = True
break
files += 1
out.append(e.path)
try:
total += e.stat(follow_symlinks=False).st_size
except Exception:
pass
if total > cap_bytes:
truncated = True
break
except Exception:
continue
if truncated:
break
return out, truncated
def fast_dir_size(path):
"""Size of a whole tree without recording anything (for pruned dirs)."""
total, files = 0, 0
stack = [path]
while stack:
d = stack.pop()
try:
it = os.scandir(d)
except Exception:
continue
with it:
for e in it:
try:
if e.is_symlink():
continue
if e.is_dir(follow_symlinks=False):
stack.append(e.path)
elif e.is_file(follow_symlinks=False):
s = e.stat(follow_symlinks=False).st_size
total += s
files += 1
except Exception:
pass
return total, files
def mask_value(v):
v = v.strip().strip("'\"")
if len(v) <= 8:
return v[:1] + "…" if v else "…"
return v[:4] + "…" + v[-2:]
# ---------------------------------------------------------------------------
# language / docs detection
# ---------------------------------------------------------------------------
EXT_LANG = {
".js": "JavaScript", ".jsx": "JavaScript", ".mjs": "JavaScript", ".cjs": "JavaScript",
".ts": "TypeScript", ".tsx": "TypeScript",
".py": "Python", ".rs": "Rust", ".go": "Go", ".rb": "Ruby", ".php": "PHP",
".java": "Java", ".c": "C", ".cpp": "C++", ".cc": "C++", ".h": "C/C++ header",
".hpp": "C++", ".cs": "C#", ".swift": "Swift", ".kt": "Kotlin", ".kts": "Kotlin",
".scala": "Scala", ".lua": "Lua", ".pl": "Perl", ".r": "R", ".jl": "Julia",
".sh": "Shell", ".bash": "Shell", ".zsh": "Shell", ".ps1": "PowerShell",
".html": "HTML", ".htm": "HTML", ".css": "CSS", ".scss": "SCSS", ".sass": "Sass",
".sql": "SQL", ".vue": "Vue", ".svelte": "Svelte", ".ex": "Elixir", ".exs": "Elixir",
".erl": "Erlang", ".zig": "Zig", ".dart": "Dart", ".fs": "F#", ".fsx": "F#",
".m": "Objective-C", ".mm": "Objective-C++", ".groovy": "Groovy", ".nim": "Nim",
".hs": "Haskell", ".clj": "Clojure",
}
DOC_TYPES = {
".md": "Markdown", ".rst": "reStructuredText", ".adoc": "AsciiDoc",
".pdf": "PDF", ".doc": "Word (legacy)", ".docx": "Word", ".txt": "Plain text",
".rtf": "RTF", ".csv": "CSV", ".tsv": "TSV", ".json": "JSON", ".xml": "XML",
".yaml": "YAML", ".yml": "YAML", ".xlsx": "Excel", ".xls": "Excel (legacy)",
".pptx": "PowerPoint", ".ppt": "PowerPoint (legacy)",
".ipynb": "Jupyter notebook", ".html": "HTML",
}
SOURCE_EXTS = set(EXT_LANG) - {".html", ".htm", ".css", ".scss", ".sass", ".sql", ".zsh", ".ps1"}
_WORD_MAP = {
"en": ["the", "and", "for", "with", "this", "that", "you", "use", "run", "install", "app", "server", "test"],
"fr": ["le", "la", "les", "pour", "avec", "vous", "une", "est", "dans", "qui"],
"es": ["que", "para", "con", "los", "las", "una", "por", "como", "ser", "está"],
"de": ["und", "der", "die", "das", "für", "mit", "ist", "nicht", "auch", "eine"],
"pt": ["que", "para", "com", "uma", "por", "não", "ser", "está", "os", "das"],
"it": ["che", "per", "con", "una", "sono", "non", "anche", "della", "questo"],
"nl": ["en", "het", "een", "voor", "met", "zijn", "niet", "ook", "de", "dat"],
}
_WORD_RE = {}
for _lang, _words in _WORD_MAP.items():
_WORD_RE[_lang] = re.compile(r"\b(" + "|".join(re.escape(w) for w in _words) + r")\b", re.I)
def detect_natural_lang(text):
if not text or len(text) < 20:
return "n/a"
if re.search(r"[\u4e00-\u9fff]", text):
return "Chinese/Japanese (CJK)"
if re.search(r"[\u3040-\u30ff]", text):
return "Japanese"
if re.search(r"[\uac00-\ud7af]", text):
return "Korean"
if re.search(r"[\u0400-\u04ff]", text):
return "Cyrillic (Russian/Ukrainian/…)"
if re.search(r"[\u0600-\u06ff]", text):
return "Arabic"
if re.search(r"[\u0e00-\u0e7f]", text):
return "Thai"
if not re.search(r"[A-Za-z]", text):
return "non-Latin"
best, best_score = "English", 0
for lang, rx in _WORD_RE.items():
s = len(rx.findall(text.lower()))
if s > best_score:
best, best_score = lang, s
return best.capitalize() if best != "n/a" else "English (guess)"
# ---------------------------------------------------------------------------
# secret + risk patterns
# ---------------------------------------------------------------------------
SECRET_PATTERNS = [
# (name, regex, severity, value-group-index)
("AWS Access Key ID", re.compile(r"AKIA[0-9A-Z]{16}"), "high", 0),
("AWS Secret Key", re.compile(r"(?i)aws.{0,12}secret.{0,20}?[=:]\s*['\"]?([A-Za-z0-9/+=]{28,40})"), "high", 1),
("OpenAI API key", re.compile(r"sk-[A-Za-z0-9_-]{20,}"), "high", 0),
("Anthropic API key", re.compile(r"sk-ant-[A-Za-z0-9_-]{20,}"), "high", 0),
("Google API key", re.compile(r"AIza[0-9A-Za-z_-]{30,35}"), "high", 0),
("Slack token", re.compile(r"xox[baprs]-[0-9A-Za-z-]{10,}"), "high", 0),
("GitHub token", re.compile(r"(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{20,}"), "high", 0),
("Stripe key", re.compile(r"(sk|pk|rk)_(live|test)_[0-9a-zA-Z]{10,}"), "high", 0),
("JWT token", re.compile(r"eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9._-]{10,}"), "medium", 0),
("Private key block", re.compile(r"BEGIN (?:RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY"), "high", 0),
("DB connection string w/ password", re.compile(r"(?:postgres|mysql|mongodb(?:\+srv)?|redis|amqp)://[\w.+\-]+:[^\s'\" ]{3,}@[\w.\-]+"), "high", 0),
("Generic secret assignment", re.compile(r"(?i)(api[_-]?key|secret|access[_-]?token|auth[_-]?token|passwd|password)\s*[:=]\s*['\"]?([A-Za-z0-9+/_@\-]{12,40})['\"]?"), "medium", 2),
]
RISK_PATTERNS = [
("TLS verification disabled", re.compile(r"verify\s*=\s*False|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*[\"']?0|-k\s+$"), "high"),
("Web framework debug mode", re.compile(r"app\.run\(.*debug\s*=\s*True|DEBUG\s*=\s*(?:True|true|\"?1)"), "medium"),
("eval()/exec() usage", re.compile(r"\beval\s*\(|\bexec\s*\("), "medium"),
("pickle deserialization", re.compile(r"pickle\.loads?\(|cPickle\.loads?\("), "medium"),
("Unsafe YAML load", re.compile(r"yaml\.load\((?![^)]*Loader)"), "medium"),
("subprocess shell=True", re.compile(r"shell\s*=\s*True"), "low"),
("os.system usage", re.compile(r"os\.system\s*\("), "low"),
("Plain-HTTP external URL", re.compile(r"http://(?!localhost|127\.0\.0\.1|0\.0\.0\.0|example\.com|\[::1\])"), "low"),
("Wide-open bind 0.0.0.0", re.compile(r"(host|bind)[\"']?\s*[=:]\s*[\"']0\.0\.0\.0"), "info"),
]
SECRET_FILE_HINTS = re.compile(
r"(^|/)(\.env|.*\.env\..*|config.*\.(ini|cfg|conf|json|ya?ml|toml|properties)$|.*\.pem$|id_rsa$|credentials.*|secrets.*|.*\.sqlite$|.*\.db$)"
)
CODE_EXT_SCAN = {".py", ".js", ".ts", ".tsx", ".jsx", ".go", ".rb", ".sh", ".php", ".java", ".cs",
".yml", ".yaml", ".json", ".toml", ".ini", ".cfg", ".conf", ".properties", ".env",
".xml", ".sql", ".tf", ".tfvars", ".mjs", ".c", ".cpp", ".rs"}
def scan_secrets(files):
found = []
claimed = []
def _add(fp, line_no, name, sev, span, val):
# skip if this match overlaps a span already claimed by a specific pattern
for s, e in claimed:
if s < span[1] and e > span[0]:
return
if name == "Generic secret assignment" and len(val) < 12:
return
claimed.append(span)
found.append({"type": name, "severity": sev, "file": fp, "line": line_no,
"masked": mask_value(val)})
for fp in files:
text = read_head(fp)
if not text:
continue
for line_no, line in enumerate(text.splitlines(), 1):
if len(line) > MAX_LINE_LEN:
continue
claimed.clear()
# pass 1: specific patterns (in priority order)
for name, rx, sev, vgroup in SECRET_PATTERNS:
if name == "Generic secret assignment":
continue
for m in rx.finditer(line):
try:
val = m.group(vgroup) if vgroup <= len(m.groups()) else m.group(0)
except Exception:
val = m.group(0)
_add(fp, line_no, name, sev, (m.start(), m.end()), val)
if len(found) >= 60:
break
if len(found) >= 60:
break
if len(found) >= 60:
break
# pass 2: generic pattern, only in regions not claimed by pass 1
gname, grx, gsev, gv = SECRET_PATTERNS[-1]
for m in grx.finditer(line):
_add(fp, line_no, gname, gsev, (m.start(2), m.end(2)), m.group(2))
if len(found) >= 60:
break
if len(found) >= 60:
break
# dedupe by (file, line, type)
seen, out = set(), []
for f in found:
k = (f["file"], f["line"], f["type"])
if k not in seen:
seen.add(k)
out.append(f)
return out
def scan_risks(files, root, has_gitignore, gitignore_text, env_files):
flags = []
todos = 0
for fp in files:
text = read_head(fp)
if not text:
continue
todos += len(re.findall(r"TODO|FIXME|HACK", text))
for name, rx, sev in RISK_PATTERNS:
m = rx.search(text)
if m:
flags.append({"label": name, "severity": sev,
"file": os.path.relpath(fp, root)})
if len(flags) >= 30:
break
if len(flags) >= 30:
break
if env_files and has_gitignore and not re.search(r"(^|\n)\s*(\.env|.*\.env)\s*(\n|$)|\.env\*", gitignore_text):
flags.insert(0, {"label": ".env file not ignored by git — secrets may be committed", "severity": "high", "file": ".env"})
if env_files and not has_gitignore:
flags.insert(0, {"label": ".env file exists and there is no .gitignore at all", "severity": "high", "file": ".env"})
if not has_gitignore and not env_files:
flags.append({"label": "No .gitignore present", "severity": "low", "file": ".gitignore"})
sev_rank = {"high": 5, "medium": 2, "low": 1, "info": 0}
score = sum(sev_rank[f["severity"]] for f in flags)
if score >= 8:
level = "high"
elif score >= 3:
level = "medium"
else:
level = "low"
return flags, todos, level, score
# ---------------------------------------------------------------------------
# manifest parsing
# ---------------------------------------------------------------------------
def parse_package_json(path):
try:
data = json.loads(read_head(path, 500_000))
except Exception:
return {}
return data
def parse_toml_simple(path):
try:
import tomllib
with open(path, "rb") as f:
return tomllib.load(f)
except Exception:
return {}
def parse_requirements(path):
deps = []
for line in read_head(path, 200_000).splitlines():
line = line.strip()
if not line or line.startswith("#") or line.startswith("-"):
continue
m = re.match(r"([A-Za-z0-9._-]+)\s*([=<>!~]=?)\s*([^\s;#]+)", line)
if m:
deps.append({"name": m.group(1), "version": m.group(3)})
else:
m = re.match(r"([A-Za-z0-9._-]+)\s*[,<>=!~\s]", line)
if m:
deps.append({"name": m.group(1), "version": None})
return deps
def parse_compose_ports(text):
ports = []
for m in re.finditer(r"^\s*-\s*[\"']?(\d+)(?::(\d+))?[\"']?\s*$", text, re.M):
ports.append(int(m.group(2) or m.group(1)))
for m in re.finditer(r"ports\s*:\s*(\d+:\d+|\d+)", text):
p = m.group(1).split(":")
ports.append(int(p[0]))
return sorted(set(ports))
def parse_compose_images(text):
imgs = []
for m in re.finditer(r"image\s*:\s*[\"']?([\w.\-/:]+)", text):
imgs.append(m.group(1))
return imgs
# ---------------------------------------------------------------------------
# git
# ---------------------------------------------------------------------------
def scan_git(root):
gdir = os.path.join(root, ".git")
info = {"vcs": None, "branch": None, "remote": None, "remote_host": None,
"last_commit": None, "last_author": None, "last_date": None,
"commit_count": None, "dirty_files": None}
if not os.path.exists(gdir):
if os.path.exists(os.path.join(root, ".hg")):
info["vcs"] = "Mercurial"
elif os.path.exists(os.path.join(root, ".svn")):
info["vcs"] = "Subversion"
return info
info["vcs"] = "Git"
git = shutil.which("git")
if git:
ok, out = run_cmd([git, "-C", root, "branch", "--show-current"], timeout=8)
info["branch"] = out.strip() or None
ok, out = run_cmd([git, "-C", root, "remote"], timeout=8)
remotes = [r for r in out.split() if r]
origin = "origin" if remotes else (remotes[0] if remotes else None)
if origin:
ok, out = run_cmd([git, "-C", root, "remote", "get-url", origin], timeout=8)
url = out.strip()
if url:
info["remote"] = url
m = re.match(r"(?:https?|git|ssh)://([^/]+)/", url)
if m:
info["remote_host"] = m.group(1)
m = re.match(r"[\w.-]+@([\w.-]+):", url)
if m:
info["remote_host"] = m.group(1)
ok, out = run_cmd([git, "-C", root, "log", "-1", "--format=%H%x09%an%x09%at%x09%s"], timeout=8)
if ok and out.strip():
parts = out.strip().split("\t")
if len(parts) == 4:
info["last_commit"], info["last_author"] = parts[0][:10], parts[1]
try:
info["last_date"] = int(parts[2])
except Exception:
pass
info["last_subject"] = parts[3]
ok, out = run_cmd([git, "-C", root, "rev-list", "--count", "HEAD"], timeout=15)
if ok and out.strip().isdigit():
info["commit_count"] = int(out.strip())
ok, out = run_cmd([git, "-C", root, "status", "--porcelain"], timeout=15)
info["dirty_files"] = len([l for l in out.splitlines() if l.strip()])
else:
# no git binary: read config manually
cfg = read_head(os.path.join(gdir, "config"), 50_000)
m = re.search(r'\[remote "origin"\]\s*url\s*=\s*(\S+)', cfg)
if m:
info["remote"] = m.group(1)
mm = re.match(r"(?:https?|git|ssh)://([^/]+)/", m.group(1))
if mm:
info["remote_host"] = mm.group(1)
head = read_head(os.path.join(gdir, "HEAD"), 2_000)
m = re.match(r"ref:\s*refs/heads/(\S+)", head.strip())
if m:
info["branch"] = m.group(1)
return info
# ---------------------------------------------------------------------------
# AI / IDE traces + LLM token usage
# ---------------------------------------------------------------------------
AI_MARKERS = [
(".claude", "Claude Code (Anthropic)"),
("CLAUDE.md", "Claude Code (Anthropic)"),
(".cursor", "Cursor"),
(".cursorrules", "Cursor"),
("cursorrules", "Cursor"),
(".vscode", "VS Code"),
(".idea", "JetBrains IDE (IntelliJ/PyCharm/WebStorm/CLion)"),
(".windsurf", "Windsurf"),
(".gemini", "Gemini CLI"),
(".copilot", "GitHub Copilot"),
(".cline", "Cline"),
(".roo", "Roo Code"),
(".aider", "Aider"),
(".lingma", "Lingma"),
(".antigravity", "Antigravity (Google)"),
(".vibe", "Vibe coding"),
]
def _claude_project_encoding(path):
return re.sub(r"[^A-Za-z0-9]", "-", path)
def claude_usage_for(project_path):
"""Parse ~/.claude/projects/<encoded-path>/*.jsonl for token usage."""
base = os.path.expanduser(os.path.join("~", ".claude", "projects"))
enc = _claude_project_encoding(os.path.abspath(project_path))
result = {"model": None, "tokens_in": 0, "tokens_out": 0,
"cache_read": 0, "cache_write": 0, "sessions": 0, "last": None,
"user_msgs": 0, "assistant_msgs": 0}
d = os.path.join(base, enc)
if not os.path.isdir(d):
return None
total_bytes = 0
models = {}
for fp in globmod.glob(os.path.join(d, "*.jsonl")):
try:
sz = os.path.getsize(fp)
except Exception:
continue
if sz > 8_000_000 or total_bytes > 20_000_000:
continue
total_bytes += sz
result["sessions"] += 1
try:
mtime = os.path.getmtime(fp)
if result["last"] is None or mtime > result["last"]:
result["last"] = mtime
except Exception:
pass
with open(fp, "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line or '"usage"' not in line and '"model"' not in line and '"type"' not in line:
continue
try:
obj = json.loads(line)
except Exception:
continue
t = obj.get("type")
msg = obj.get("message") or {}
if t == "assistant" and isinstance(msg, dict):
result["assistant_msgs"] += 1
model = msg.get("model")
if model:
models[model] = models.get(model, 0) + 1
usage = msg.get("usage") or {}
if usage:
result["tokens_in"] += int(usage.get("input_tokens") or 0)
result["tokens_out"] += int(usage.get("output_tokens") or 0)
result["cache_read"] += int(usage.get("cache_read_input_tokens") or 0)
result["cache_write"] += int(usage.get("cache_creation_input_tokens") or 0)
elif t == "user":
result["user_msgs"] += 1
if models:
result["model"] = max(models.items(), key=lambda kv: kv[1])[0]
result["models"] = models
return result
def cursor_usage_best_effort():
"""Very best-effort: look for token usage in Cursor's sqlite state."""
cands = []
home = os.path.expanduser("~")
if OS_NAME == "Darwin":
cands.append(os.path.join(home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb"))
elif OS_NAME == "Windows":
appdata = os.environ.get("APPDATA", "")
if appdata:
cands.append(os.path.join(appdata, "Cursor", "User", "globalStorage", "state.vscdb"))
else:
cands.append(os.path.join(home, ".config", "Cursor", "User", "globalStorage", "state.vscdb"))
for db in cands:
if not os.path.isfile(db):
continue
try:
con = sqlite3.connect("file:" + db + "?mode=ro", uri=True, timeout=2)
cur = con.cursor()
cur.execute("SELECT key FROM ItemTable WHERE key LIKE '%chat%' OR key LIKE '%session%' OR key LIKE '%usage%' LIMIT 50")
keys = [r[0] for r in cur.fetchall()]
con.close()
if keys:
return {"db": db, "chat_keys": len(keys)}
except Exception:
continue
return None
# ---------------------------------------------------------------------------
# listeners / processes
# ---------------------------------------------------------------------------
def get_listeners_linux():
"""Use ss if available, else /proc. Returns [{port, pid, proc}]."""
out = []
if shutil.which("ss"):
ok, text = run_cmd(["ss", "-H", "-tlnp"], timeout=8)
if ok:
for line in text.splitlines():
parts = line.split()
if len(parts) < 5:
continue
laddr = parts[3]
m = re.match(r"^(.*):(\d+)$", laddr)
if not m:
continue
port = int(m.group(2))
pid, proc = None, None
pm = re.search(r"pid=(\d+)", line)
nm = re.search(r'name="([^"]+)"', line) or re.search(r'\("([^"]+)",pid=', line)
if pm:
pid = int(pm.group(1))
if nm:
proc = nm.group(1)
out.append({"port": port, "pid": pid, "proc": proc, "addr": m.group(1).strip("[]")})
if out:
return out
# /proc fallback
try:
inodes = {}
for f in ("/proc/net/tcp", "/proc/net/tcp6"):
if not os.path.isfile(f):
continue
for line in open(f).readlines()[1:]:
parts = line.split()
if len(parts) < 12 or parts[3] != "0A":
continue
try:
port = int(parts[1].split(":")[1], 16)
except Exception:
continue
# columns: sl local rem st tx:rx tr:tm retrnsmt uid timeout inode
inodes[parts[9]] = {"port": port, "pid": None, "proc": None, "addr": _hex_addr(parts[1])[0]}
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/comm" % pid) as f:
comm = f.read().strip()
for fd in os.listdir("/proc/%s/fd" % pid):
try:
link = os.readlink("/proc/%s/fd/%s" % (pid, fd))
except Exception:
continue
if link.startswith("socket:["):
key = link[8:-1]
if key in inodes:
inodes[key]["pid"] = int(pid)
inodes[key]["proc"] = comm
except Exception:
continue
out = list(inodes.values())
except Exception:
pass
return out
def get_listeners_mac():
"""lsof -F output: 'p<pid>' starts a process, 'c<command>' names it, each 'n<addr>' is one listening
socket (we ask lsof for LISTEN sockets only, so every n line with a port is a listener)."""
out, seen = [], set()
ok, text = run_cmd(["lsof", "-nP", "-iTCP", "-sTCP:LISTEN", "-Fpcn"], timeout=15)
if not text:
return out
pid, proc = None, None
for line in text.splitlines():
if not line:
continue
tag, val = line[0], line[1:]
if tag == "p":
try:
pid = int(val)
except ValueError:
pid = None
proc = None
elif tag == "c":
proc = val
elif tag == "n":
m = re.search(r"^(.*):(\d+)(?:\s|$)", val)
if m and pid:
port = int(m.group(2))
if (port, pid) in seen:
continue # same socket on IPv4 + IPv6
seen.add((port, pid))
out.append({"port": port, "pid": pid, "proc": proc, "addr": m.group(1).strip("[]")})
return out
def _windows_proc_names():
names = {}
ok, text = run_cmd(["tasklist", "/fo", "csv", "/nh"], timeout=10)
for line in (text or "").splitlines():
cols = [c.strip('"') for c in line.split('","')]
if len(cols) >= 2:
try:
names[int(cols[1])] = cols[0].strip('"')
except ValueError:
pass
return names
def get_listeners_windows():
out, seen = [], set()
ok, text = run_cmd(["netstat", "-ano", "-p", "TCP"], timeout=10)
if not ok:
ok, text = run_cmd(["netstat", "-ano"], timeout=10)
if not ok:
return out
names = None
for line in text.splitlines():
if "LISTENING" in line:
parts = line.split()
if len(parts) >= 5:
m = re.match(r"^(.*):(\d+)$", parts[1])
if m:
try:
port, pid = int(m.group(2)), int(parts[-1])
except Exception:
continue
if (port, pid) in seen:
continue
seen.add((port, pid))
if names is None:
names = _windows_proc_names()
out.append({"port": port, "pid": pid, "proc": names.get(pid), "addr": m.group(1).strip("[]")})
return out
def get_cwd_mac(pid):
ok, text = run_cmd(["lsof", "-a", "-p", str(pid), "-d", "cwd", "-Fn"], timeout=4)
for line in text.splitlines():
if line.startswith("n"):
return line[1:]
return None
def get_all_cwd_mac():
"""Single lsof pass: {pid: cwd}."""
res = {}
ok, text = run_cmd(["lsof", "-a", "-d", "cwd", "-Fn", "-w"], timeout=25)
if not ok:
return res
pid = None
for line in text.splitlines():
if line.startswith("p"):
try:
pid = int(line[1:])
except Exception:
pid = None
elif line.startswith("n") and pid:
res[pid] = line[1:]
return res
def get_processes_linux():
procs = []
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/cmdline" % pid, "rb") as f:
cmd = f.read().replace(b"\x00", b" ").decode("utf-8", "replace").strip()
cwd = os.readlink("/proc/%s/cwd" % pid)
with open("/proc/%s/comm" % pid) as f:
comm = f.read().strip()
procs.append({"pid": int(pid), "cmd": cmd[:300] or comm, "cwd": cwd})
except Exception:
continue
return procs
def get_processes_mac():
ok, text = run_cmd(["ps", "-axww", "-o", "pid=,comm="], timeout=10)
if not ok:
return []
procs = []
for line in text.splitlines():
parts = line.strip().split(None, 1)
if len(parts) == 2:
try:
procs.append({"pid": int(parts[0]), "cmd": parts[1][:300], "cwd": None})
except Exception:
continue
cwds = get_all_cwd_mac()
for p in procs:
p["cwd"] = cwds.get(p["pid"])
return procs
def get_processes_windows():
procs = []
ok, text = False, ""
if shutil.which("wmic"):
ok, text = run_cmd(["wmic", "process", "get", "ProcessId,CommandLine", "/format:csv"], timeout=15)
if not ok:
ok, text = run_cmd(["powershell", "-NoProfile", "-Command",
"Get-CimInstance Win32_Process | ForEach-Object { \"x,$($_.ProcessId),$($_.CommandLine)\" }"],
timeout=25)
if ok:
for line in text.splitlines():
parts = line.strip().split(",", 2)
if len(parts) == 3 and parts[1].isdigit() and parts[2]:
procs.append({"pid": int(parts[1]), "cmd": parts[2][:300], "cwd": None})
return procs
if ok:
for line in text.splitlines()[1:]:
m = re.match(r".*?(\d+),(.*)$", line.strip())
if m and m.group(2):
procs.append({"pid": int(m.group(1)), "cmd": m.group(2)[:300], "cwd": None})
return procs
# ---------------------------------------------------------------------------
# shell history (last-run heuristic)
# ---------------------------------------------------------------------------
def sanitize_cmd(s):
"""Redact secret-looking values out of a shell command line."""
if not s:
return s
for name, rx, sev, vgroup in SECRET_PATTERNS:
s = rx.sub(lambda m: (m.group(0)[:4] + "…REDACTED") if len(m.group(0)) > 8 else "REDACTED", s)
return s
def scan_shell_history(project_path, base_name):
hits = []
home = os.path.expanduser("~")
cands = [
os.path.join(home, ".zsh_history"),
os.path.join(home, ".bash_history"),
os.path.join(home, ".local", "share", "fish", "fish_history"),
]
rx = re.compile(re.escape(base_name) + r"(\b|[\\/])")
run_rx = re.compile(r"(cd\s|npm|pnpm|yarn|npx|pip|python|python3|uvicorn|flask|django|docker|cargo|go\s+run|bundle|make|gradle|just|poetry|uv\s)")
for fp in cands:
if not os.path.isfile(fp):
continue
text = read_head(fp, 2_000_000)
if fp.endswith("fish_history"):
try:
data = json.loads(text)
items = data.get("items") or []
for it in items[-3000:]:
cmd = it.get("cmd", "")
if rx.search(cmd) and run_rx.search(cmd):
hits.append({"cmd": sanitize_cmd(cmd[:200]), "ts": it.get("when", 0) / 1000 if it.get("when") else None, "src": "fish"})
except Exception:
pass
continue
for raw in text.splitlines()[-3000:]:
ts = None
cmd = raw
m = re.match(r"^#(\d{9,11})\n(.*)$", raw)
if m:
ts = int(m.group(1))
cmd = m.group(2)
else:
m = re.match(r"^\^H(\d{9,11}) \d+\n(.*)$", raw)
if m:
ts = int(m.group(1))
cmd = m.group(2)
if rx.search(cmd) and run_rx.search(cmd):
hits.append({"cmd": sanitize_cmd(cmd[:200]), "ts": ts, "src": os.path.basename(fp)})
hits.sort(key=lambda h: h.get("ts") or 0)
return hits[-25:]
# ---------------------------------------------------------------------------
# run command + port detection
# ---------------------------------------------------------------------------
def detect_run_command(root, manifest, text_samples):
"""Returns {command, why, expected_ports:[{port, source}], pkg_manager}."""
res = {"command": None, "why": None, "expected_ports": [], "pkg_manager": None}
pj = os.path.join(root, "package.json")
if os.path.isfile(pj):
data = parse_package_json(pj)
scripts = data.get("scripts") or {}
deps = {**(data.get("dependencies") or {}), **(data.get("devDependencies") or {})}
pm = "npm"
if os.path.isfile(os.path.join(root, "pnpm-lock.yaml")):
pm = "pnpm"
elif os.path.isfile(os.path.join(root, "yarn.lock")):
pm = "yarn"
elif os.path.isfile(os.path.join(root, "bun.lockb")) or os.path.isfile(os.path.join(root, "bun.lock")):
pm = "bun"
res["pkg_manager"] = pm
port = 3000
framework = None
if "next" in deps:
framework, port = "Next.js", 3000
elif "vite" in deps:
framework, port = "Vite", 5173
elif "react-scripts" in deps:
framework, port = "Create React App", 3000
elif "@sveltejs/kit" in deps:
framework, port = "SvelteKit", 5173
elif "nuxt" in deps:
framework, port = "Nuxt", 3000
elif "express" in deps or "fastify" in deps:
framework, port = "Node server (Express/Fastify)", 3000
elif "electron" in deps:
framework = "Electron app"
elif "cypress" in deps and "playwright" not in deps and len(deps) < 5:
framework = "Test suite"
if framework:
res["why"] = framework
cmd = None
if scripts.get("dev"):
cmd = "%s run dev" % pm
elif scripts.get("start"):
cmd = "%s run start" % pm
elif scripts.get("serve"):
cmd = "%s run serve" % pm
elif framework == "Electron app" and scripts.get("start"):
cmd = "%s start" % pm
if cmd:
res["command"] = cmd
if not res["why"]:
res["why"] = "package.json scripts"
if framework and framework != "Test suite":
res["expected_ports"].append({"port": port, "source": framework + " default"})
else:
res["command"] = "%s install # then check scripts in package.json" % pm
res["why"] = "package.json (no dev/start script)"
return res
if os.path.isfile(os.path.join(root, "manage.py")):
res["command"] = "python manage.py runserver"
res["why"] = "Django project (manage.py)"
res["expected_ports"].append({"port": 8000, "source": "Django default"})
return res
py_deps = []
for req in ("requirements.txt", "requirements-dev.txt"):