tokensafe 4.7.11 → 4.7.13
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.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +7 -3
- package/bin/tokensafe.js +17 -1
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +2 -0
- package/src/__init__.py +1 -1
- package/src/auto_inject.py +133 -4
- package/src/batch_editor.py +40 -9
- package/src/graph_engine.py +298 -27
- package/src/mcp_server.py +102 -13
- package/src/oumv_gateway.py +149 -6
- package/src/retrofit.py +99 -14
- package/src/scoped_search.py +126 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/src/graph_engine.py
CHANGED
|
@@ -64,6 +64,33 @@ _STATIC_ASSET_EXTS = {
|
|
|
64
64
|
".map", ".pdf", ".mp4", ".mp3",
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
# Build output that happens to share a source extension: Vite/webpack bundles
|
|
68
|
+
# (`index-otG6xuvO.js`), minified copies, and webview asset trees
|
|
69
|
+
# (`android/app/src/main/assets/public/assets/`). Indexing them made L1 report
|
|
70
|
+
# frontend.action calls from a compiled bundle instead of the source that produced it.
|
|
71
|
+
_BUNDLE_HASH_RE = re.compile(r"^[^/]+-[A-Za-z0-9_-]{8,}\.(?:m?js|cjs|css)$")
|
|
72
|
+
# Capacitor/Cordova copy the built web app into the native project; nothing under
|
|
73
|
+
# that tree is source. Elsewhere (web `public/`) only hash-named bundles are output.
|
|
74
|
+
_GENERATED_ASSET_PARTS = ("android/app/src/main/assets",)
|
|
75
|
+
|
|
76
|
+
# Directory snapshots and tool output trees: they hold copies of code, not the
|
|
77
|
+
# live code, so indexing them doubles the graph and every L1 answer.
|
|
78
|
+
_SNAPSHOT_DIRS = {"backups", "graphify-out", "oumv-debug-logs"}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _is_generated_asset(rel_path: str, filename: str) -> bool:
|
|
82
|
+
"""True for compiled/minified artifacts that only look like source files."""
|
|
83
|
+
lower = filename.lower()
|
|
84
|
+
if lower.endswith((".min.js", ".min.css", ".bundle.js", ".chunk.js")):
|
|
85
|
+
return True
|
|
86
|
+
normalized = "/" + rel_path.replace("\\", "/")
|
|
87
|
+
if any(part in normalized for part in _GENERATED_ASSET_PARTS):
|
|
88
|
+
return True
|
|
89
|
+
if not _BUNDLE_HASH_RE.match(filename):
|
|
90
|
+
return False
|
|
91
|
+
return "/public/assets/" in normalized or "/dist/assets/" in normalized
|
|
92
|
+
|
|
93
|
+
|
|
67
94
|
_BACKEND_ROUTE_PATTERNS = [
|
|
68
95
|
# (regex, default_method). Group 1 is always the route literal; the declaring
|
|
69
96
|
# receiver (if any) is read back from the match text with _RECEIVER_RE.
|
|
@@ -574,6 +601,7 @@ class CodeGraph:
|
|
|
574
601
|
finally:
|
|
575
602
|
con.close()
|
|
576
603
|
os.replace(tmp_path, path)
|
|
604
|
+
GraphEngine._prune_cache(cache_dir, path)
|
|
577
605
|
except Exception:
|
|
578
606
|
try:
|
|
579
607
|
os.unlink(tmp_path)
|
|
@@ -617,12 +645,23 @@ class CodeGraph:
|
|
|
617
645
|
current_files = set()
|
|
618
646
|
|
|
619
647
|
for dirpath, dirnames, filenames in os.walk(self.root_dir):
|
|
620
|
-
dirnames[:] = [
|
|
648
|
+
dirnames[:] = [
|
|
649
|
+
d for d in dirnames
|
|
650
|
+
if d not in IGNORED_DIRS and d not in _SNAPSHOT_DIRS and not d.startswith(".")
|
|
651
|
+
]
|
|
621
652
|
for filename in filenames:
|
|
622
653
|
_, ext = os.path.splitext(filename)
|
|
623
654
|
if ext.lower() in SUPPORTED_EXTS:
|
|
624
655
|
full_path = os.path.join(dirpath, filename)
|
|
625
656
|
rel_path = os.path.relpath(full_path, self.root_dir).replace("\\", "/")
|
|
657
|
+
if _is_generated_asset(rel_path, filename):
|
|
658
|
+
# A bundle indexed by an older scan must be dropped, not just skipped.
|
|
659
|
+
if rel_path in self.file_symbols or rel_path in self.file_stats:
|
|
660
|
+
self._purge_file(rel_path)
|
|
661
|
+
self.file_stats.pop(rel_path, None)
|
|
662
|
+
self.file_mtimes.pop(rel_path, None)
|
|
663
|
+
reindexed += 1
|
|
664
|
+
continue
|
|
626
665
|
current_files.add(rel_path)
|
|
627
666
|
|
|
628
667
|
try:
|
|
@@ -1744,6 +1783,43 @@ class CodeGraph:
|
|
|
1744
1783
|
items = [f"{g['file']} ({g['dependents']} deps)" for g in nodes_to_show]
|
|
1745
1784
|
return f"[TokenSafe Architecture Map | Core Hubs: {', '.join(items)}]"
|
|
1746
1785
|
|
|
1786
|
+
def _as_repo_rel(self, target: str) -> str:
|
|
1787
|
+
"""Normalises a caller-supplied target to a repo-relative path.
|
|
1788
|
+
|
|
1789
|
+
Absolute paths arrive from MCP callers that pass `path=`; a path outside
|
|
1790
|
+
this graph keeps only its basename so the candidate lookup can still say
|
|
1791
|
+
which file was meant instead of matching nothing.
|
|
1792
|
+
"""
|
|
1793
|
+
t = (target or "").replace("\\", "/").strip()
|
|
1794
|
+
if os.path.isabs(t):
|
|
1795
|
+
try:
|
|
1796
|
+
rel = os.path.relpath(t, self.root_dir).replace("\\", "/")
|
|
1797
|
+
except ValueError:
|
|
1798
|
+
return os.path.basename(t)
|
|
1799
|
+
if rel.startswith("../"):
|
|
1800
|
+
return os.path.basename(t)
|
|
1801
|
+
t = rel
|
|
1802
|
+
root_name = os.path.basename(self.root_dir)
|
|
1803
|
+
if root_name and t.startswith(root_name + "/"):
|
|
1804
|
+
t = t[len(root_name) + 1:]
|
|
1805
|
+
return t
|
|
1806
|
+
|
|
1807
|
+
def _file_facts(self, rel_path: str) -> Dict[str, Any]:
|
|
1808
|
+
"""Stable facts about an indexed file: symbol count, line count, OCC token."""
|
|
1809
|
+
facts: Dict[str, Any] = {
|
|
1810
|
+
"path": rel_path,
|
|
1811
|
+
"lines": 0,
|
|
1812
|
+
"symbols": len(self.file_symbols.get(rel_path, [])),
|
|
1813
|
+
}
|
|
1814
|
+
try:
|
|
1815
|
+
with open(os.path.join(self.root_dir, rel_path), "rb") as fh:
|
|
1816
|
+
data = fh.read()
|
|
1817
|
+
except OSError:
|
|
1818
|
+
return facts
|
|
1819
|
+
facts["version"] = "sha256:" + hashlib.sha256(data).hexdigest()
|
|
1820
|
+
facts["lines"] = data.count(b"\n") + (0 if data.endswith(b"\n") else 1)
|
|
1821
|
+
return facts
|
|
1822
|
+
|
|
1747
1823
|
def get_static_oumv_slice(self, level: str = "L0", target: Optional[str] = None) -> Dict[str, Any]:
|
|
1748
1824
|
"""
|
|
1749
1825
|
Level 1 Static OUMV Inspection:
|
|
@@ -1765,7 +1841,7 @@ class CodeGraph:
|
|
|
1765
1841
|
god_nodes = self.get_god_nodes(top_n=5)
|
|
1766
1842
|
endpoints_count = sum(len(eps) for eps in self.file_endpoints.values())
|
|
1767
1843
|
calls_count = sum(len(c) for c in self.file_api_calls.values())
|
|
1768
|
-
|
|
1844
|
+
pulse: Dict[str, Any] = {
|
|
1769
1845
|
"level": "L0",
|
|
1770
1846
|
"mode": "STATIC_OFFLINE_PULSE",
|
|
1771
1847
|
"status": "OFFLINE_STATIC",
|
|
@@ -1778,12 +1854,57 @@ class CodeGraph:
|
|
|
1778
1854
|
"topGodNodes": [g["file"] for g in god_nodes],
|
|
1779
1855
|
"evidence": evidence,
|
|
1780
1856
|
}
|
|
1857
|
+
clean = (target or "").strip() or None
|
|
1858
|
+
if clean:
|
|
1859
|
+
# A target on L0 is not noise: answer for it even at pulse level.
|
|
1860
|
+
rel = self._as_repo_rel(clean)
|
|
1861
|
+
pulse["target"] = rel
|
|
1862
|
+
if rel in self.file_symbols:
|
|
1863
|
+
pulse["targetResolved"] = True
|
|
1864
|
+
pulse["file"] = self._file_facts(rel)
|
|
1865
|
+
elif os.path.splitext(clean)[1].lower() in SUPPORTED_EXTS:
|
|
1866
|
+
pulse["targetResolved"] = False
|
|
1867
|
+
return pulse
|
|
1781
1868
|
|
|
1782
1869
|
# L1: Discovered API surface & Routes
|
|
1870
|
+
#
|
|
1871
|
+
# A file path is a legitimate L1 target: offline, "show me this file's
|
|
1872
|
+
# surface" is the question a caller has when the runtime is gone. It used
|
|
1873
|
+
# to be impossible — the path was compared as a substring against routes
|
|
1874
|
+
# and every file of the repo leaked into the answer.
|
|
1875
|
+
clean_target = (target or "").strip() or None
|
|
1876
|
+
rel_target = self._as_repo_rel(clean_target) if clean_target else None
|
|
1877
|
+
# A *file* target ends with a source extension. A plain path prefix without
|
|
1878
|
+
# one (`src/modules/contest`) keeps the old substring behaviour; only a file
|
|
1879
|
+
# that cannot be resolved is refused instead of dumping the repository.
|
|
1880
|
+
target_ext = os.path.splitext(clean_target)[1].lower() if clean_target else ""
|
|
1881
|
+
looks_like_file = bool(clean_target) and target_ext in SUPPORTED_EXTS
|
|
1882
|
+
file_target: Optional[str] = None
|
|
1883
|
+
file_candidates: List[str] = []
|
|
1884
|
+
if rel_target:
|
|
1885
|
+
if rel_target in self.file_symbols:
|
|
1886
|
+
file_target = rel_target
|
|
1887
|
+
elif looks_like_file:
|
|
1888
|
+
base = os.path.basename(rel_target).lower()
|
|
1889
|
+
file_candidates = sorted(
|
|
1890
|
+
p for p in self.file_symbols
|
|
1891
|
+
if p.lower() == base or p.lower().endswith("/" + base)
|
|
1892
|
+
)[:5]
|
|
1893
|
+
if len(file_candidates) == 1:
|
|
1894
|
+
file_target = file_candidates[0]
|
|
1895
|
+
t = clean_target.lower() if clean_target else ""
|
|
1896
|
+
|
|
1897
|
+
def _matches(rel_path: str, route: Optional[str]) -> bool:
|
|
1898
|
+
if not clean_target:
|
|
1899
|
+
return True
|
|
1900
|
+
if file_target:
|
|
1901
|
+
return rel_path == file_target
|
|
1902
|
+
return t in (route or "").lower() or t in rel_path.lower()
|
|
1903
|
+
|
|
1783
1904
|
endpoints = []
|
|
1784
1905
|
for rel_path, eps in self.file_endpoints.items():
|
|
1785
1906
|
for norm_route, sym, method in eps:
|
|
1786
|
-
if
|
|
1907
|
+
if _matches(rel_path, norm_route):
|
|
1787
1908
|
endpoints.append({
|
|
1788
1909
|
"route": norm_route,
|
|
1789
1910
|
"method": method,
|
|
@@ -1795,7 +1916,7 @@ class CodeGraph:
|
|
|
1795
1916
|
client_calls = []
|
|
1796
1917
|
for rel_path, calls in self.file_api_calls.items():
|
|
1797
1918
|
for norm_route, sym, method in calls:
|
|
1798
|
-
if
|
|
1919
|
+
if _matches(rel_path, norm_route):
|
|
1799
1920
|
client_calls.append({
|
|
1800
1921
|
"route": norm_route,
|
|
1801
1922
|
"method": method,
|
|
@@ -1807,14 +1928,17 @@ class CodeGraph:
|
|
|
1807
1928
|
# Cross-stack relationships (frontend call -> backend endpoint) with evidence
|
|
1808
1929
|
relationships = []
|
|
1809
1930
|
for link in self.api_links:
|
|
1810
|
-
if
|
|
1811
|
-
t = target.lower()
|
|
1931
|
+
if clean_target and not file_target:
|
|
1812
1932
|
hay = " ".join([
|
|
1813
1933
|
link["source"]["route"] or "", link["source"]["file"] or "",
|
|
1814
1934
|
link["target"]["route"] or "", link["target"]["file"] or "",
|
|
1815
1935
|
]).lower()
|
|
1816
1936
|
if t not in hay:
|
|
1817
1937
|
continue
|
|
1938
|
+
elif file_target and not any(
|
|
1939
|
+
link[side].get("file") == file_target for side in ("source", "target")
|
|
1940
|
+
):
|
|
1941
|
+
continue
|
|
1818
1942
|
relationships.append({
|
|
1819
1943
|
"source": link["source"],
|
|
1820
1944
|
"target": link["target"],
|
|
@@ -1826,23 +1950,34 @@ class CodeGraph:
|
|
|
1826
1950
|
})
|
|
1827
1951
|
|
|
1828
1952
|
matching_symbols = []
|
|
1829
|
-
if
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1953
|
+
if clean_target:
|
|
1954
|
+
if file_target:
|
|
1955
|
+
for sk in self.file_symbols.get(file_target, []):
|
|
1956
|
+
sym = self.symbols.get(sk)
|
|
1957
|
+
if sym:
|
|
1958
|
+
matching_symbols.append({
|
|
1959
|
+
"name": sym.name,
|
|
1960
|
+
"kind": sym.kind,
|
|
1961
|
+
"file": sym.file_path,
|
|
1962
|
+
"lines": [sym.line_start, sym.line_end],
|
|
1963
|
+
})
|
|
1964
|
+
else:
|
|
1965
|
+
for sk, sym in self.symbols.items():
|
|
1966
|
+
# Match both names and file paths, like get_static_impact: a target
|
|
1967
|
+
# that is a file path ("src/api/wheel.ts") must resolve to that
|
|
1968
|
+
# file's symbols, or every path-shaped target silently matches none.
|
|
1969
|
+
if t in sym.name.lower() or t in sym.file_path.lower():
|
|
1970
|
+
matching_symbols.append({
|
|
1971
|
+
"name": sym.name,
|
|
1972
|
+
"kind": sym.kind,
|
|
1973
|
+
"file": sym.file_path,
|
|
1974
|
+
"lines": [sym.line_start, sym.line_end],
|
|
1975
|
+
})
|
|
1842
1976
|
|
|
1843
1977
|
result = {
|
|
1844
1978
|
"level": "L1",
|
|
1845
|
-
"target":
|
|
1979
|
+
"target": rel_target or clean_target,
|
|
1980
|
+
"targetKind": "file" if file_target else ("target" if clean_target else "workspace"),
|
|
1846
1981
|
"mode": "STATIC_SURFACE",
|
|
1847
1982
|
"endpoints": endpoints[:30],
|
|
1848
1983
|
"clientCalls": client_calls[:30],
|
|
@@ -1850,6 +1985,40 @@ class CodeGraph:
|
|
|
1850
1985
|
"matchingSymbols": matching_symbols[:20],
|
|
1851
1986
|
"evidence": evidence,
|
|
1852
1987
|
}
|
|
1988
|
+
|
|
1989
|
+
if looks_like_file:
|
|
1990
|
+
if file_target:
|
|
1991
|
+
result["targetResolved"] = True
|
|
1992
|
+
facts = self._file_facts(file_target)
|
|
1993
|
+
result["file"] = facts
|
|
1994
|
+
if facts.get("version"):
|
|
1995
|
+
# Offline mutations are real: the gateway splices the symbol,
|
|
1996
|
+
# enforces this OCC token, runs the syntax guard and keeps a backup.
|
|
1997
|
+
result["mutation"] = {
|
|
1998
|
+
"available": True,
|
|
1999
|
+
"mode": "offline-direct",
|
|
2000
|
+
"expectedVersion": facts["version"],
|
|
2001
|
+
"howTo": (
|
|
2002
|
+
"oumv(action='mutate', path='<file>', symbol='<name>', "
|
|
2003
|
+
"replacement='<new declaration>', expectedVersion='<file.version>'). "
|
|
2004
|
+
"Without a live runtime the gateway performs the same OCC + syntax-guard + backup edit."
|
|
2005
|
+
),
|
|
2006
|
+
}
|
|
2007
|
+
else:
|
|
2008
|
+
# A path that resolves to nothing must answer "nothing", never the repo.
|
|
2009
|
+
result["targetResolved"] = False
|
|
2010
|
+
result["hint"] = (
|
|
2011
|
+
"No static index entry for this path (unsupported extension, generated asset, "
|
|
2012
|
+
"or an ignored directory). L1 only answers for indexed source files; use "
|
|
2013
|
+
"smart_read_file for the content."
|
|
2014
|
+
)
|
|
2015
|
+
if file_candidates:
|
|
2016
|
+
result["hint"] += " Did you mean one of `suggestions`?"
|
|
2017
|
+
result["suggestions"] = file_candidates
|
|
2018
|
+
result["endpoints"] = []
|
|
2019
|
+
result["clientCalls"] = []
|
|
2020
|
+
result["relationships"] = []
|
|
2021
|
+
result["matchingSymbols"] = []
|
|
1853
2022
|
if lvl != "L1":
|
|
1854
2023
|
# Asking for L2-L4 offline used to return this L1 payload with
|
|
1855
2024
|
# confidence "confirmed" and no marker, so callers could not tell a
|
|
@@ -2114,6 +2283,13 @@ class GraphEngine:
|
|
|
2114
2283
|
|
|
2115
2284
|
_instances: Dict[str, CodeGraph] = {}
|
|
2116
2285
|
_instances_lock = threading.RLock()
|
|
2286
|
+
# One lock per workspace root: a 15 s cold crawl used to hold the global lock,
|
|
2287
|
+
# so every other tool call (repo_map, smart_read_file, oumv) timed out at 8 s
|
|
2288
|
+
# while it waited for a repo it never asked about.
|
|
2289
|
+
_scan_locks: Dict[str, threading.Lock] = {}
|
|
2290
|
+
_warming: Set[str] = set()
|
|
2291
|
+
_CACHE_MAX_FILES = int(os.environ.get("TOKENSAFE_GRAPH_CACHE_MAX", "400"))
|
|
2292
|
+
_CACHE_MAX_BYTES = int(float(os.environ.get("TOKENSAFE_GRAPH_CACHE_MAX_MB", "2048")) * 1024 * 1024)
|
|
2117
2293
|
|
|
2118
2294
|
@classmethod
|
|
2119
2295
|
def find_project_root(cls, start_path: str) -> str:
|
|
@@ -2133,6 +2309,15 @@ class GraphEngine:
|
|
|
2133
2309
|
curr = parent
|
|
2134
2310
|
return os.path.abspath(start_path if os.path.isdir(start_path) else os.path.dirname(start_path))
|
|
2135
2311
|
|
|
2312
|
+
@classmethod
|
|
2313
|
+
def _scan_lock(cls, root_abs: str) -> threading.Lock:
|
|
2314
|
+
with cls._instances_lock:
|
|
2315
|
+
lock = cls._scan_locks.get(root_abs)
|
|
2316
|
+
if lock is None:
|
|
2317
|
+
lock = threading.Lock()
|
|
2318
|
+
cls._scan_locks[root_abs] = lock
|
|
2319
|
+
return lock
|
|
2320
|
+
|
|
2136
2321
|
@classmethod
|
|
2137
2322
|
def get_instance(cls, root_dir: str = ".") -> CodeGraph:
|
|
2138
2323
|
root_abs = os.path.abspath(root_dir)
|
|
@@ -2140,15 +2325,100 @@ class GraphEngine:
|
|
|
2140
2325
|
# smart_read_file(symbol=...) call. 60s keeps graphs fresh without the churn.
|
|
2141
2326
|
rescan_ttl = float(os.environ.get("TOKENSAFE_GRAPH_TTL", "60.0"))
|
|
2142
2327
|
with cls._instances_lock:
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
cls.
|
|
2147
|
-
|
|
2148
|
-
graph
|
|
2149
|
-
|
|
2328
|
+
graph = cls._instances.get(root_abs)
|
|
2329
|
+
if graph is None:
|
|
2330
|
+
with cls._scan_lock(root_abs):
|
|
2331
|
+
with cls._instances_lock:
|
|
2332
|
+
graph = cls._instances.get(root_abs)
|
|
2333
|
+
if graph is None:
|
|
2334
|
+
graph = CodeGraph(root_abs, use_disk_cache=True)
|
|
2150
2335
|
graph.scan()
|
|
2336
|
+
with cls._instances_lock:
|
|
2337
|
+
cls._instances[root_abs] = graph
|
|
2151
2338
|
return graph
|
|
2339
|
+
if time.time() - graph.last_scanned > rescan_ttl:
|
|
2340
|
+
lock = cls._scan_lock(root_abs)
|
|
2341
|
+
if lock.acquire(blocking=False):
|
|
2342
|
+
try:
|
|
2343
|
+
if time.time() - graph.last_scanned > rescan_ttl:
|
|
2344
|
+
graph.scan()
|
|
2345
|
+
finally:
|
|
2346
|
+
lock.release()
|
|
2347
|
+
# Another caller is already refreshing this root: serve the current
|
|
2348
|
+
# graph instead of stacking a second crawl behind it.
|
|
2349
|
+
return graph
|
|
2350
|
+
|
|
2351
|
+
@classmethod
|
|
2352
|
+
def warm_async(cls, root_dir: str = ".") -> bool:
|
|
2353
|
+
"""Starts one background crawl per root so the first graph tool call is warm.
|
|
2354
|
+
|
|
2355
|
+
Returns True when a crawl was started, False when one is already running.
|
|
2356
|
+
"""
|
|
2357
|
+
root_abs = os.path.abspath(root_dir)
|
|
2358
|
+
with cls._instances_lock:
|
|
2359
|
+
if root_abs in cls._warming:
|
|
2360
|
+
return False
|
|
2361
|
+
cls._warming.add(root_abs)
|
|
2362
|
+
|
|
2363
|
+
def _run() -> None:
|
|
2364
|
+
try:
|
|
2365
|
+
cls.get_instance(root_abs)
|
|
2366
|
+
except Exception:
|
|
2367
|
+
pass
|
|
2368
|
+
finally:
|
|
2369
|
+
with cls._instances_lock:
|
|
2370
|
+
cls._warming.discard(root_abs)
|
|
2371
|
+
|
|
2372
|
+
threading.Thread(target=_run, name="tokensafe-graph-warm", daemon=True).start()
|
|
2373
|
+
return True
|
|
2374
|
+
|
|
2375
|
+
@classmethod
|
|
2376
|
+
def _prune_cache(cls, cache_dir: str, keep_path: str, max_age_days: float = 30.0) -> int:
|
|
2377
|
+
"""Bounds the on-disk graph cache. One .db per root, forever, is a leak:
|
|
2378
|
+
a working machine had 4,994 files / 10 GB because nothing evicted them."""
|
|
2379
|
+
marker = os.path.join(cache_dir, ".pruned")
|
|
2380
|
+
try:
|
|
2381
|
+
if time.time() - os.path.getmtime(marker) < 3600:
|
|
2382
|
+
return 0
|
|
2383
|
+
except OSError:
|
|
2384
|
+
pass
|
|
2385
|
+
removed = 0
|
|
2386
|
+
try:
|
|
2387
|
+
keep_abs = os.path.abspath(keep_path)
|
|
2388
|
+
now = time.time()
|
|
2389
|
+
entries = []
|
|
2390
|
+
total = 0
|
|
2391
|
+
for name in os.listdir(cache_dir):
|
|
2392
|
+
if not name.endswith((".db", ".json")):
|
|
2393
|
+
continue
|
|
2394
|
+
path = os.path.join(cache_dir, name)
|
|
2395
|
+
try:
|
|
2396
|
+
st = os.stat(path)
|
|
2397
|
+
except OSError:
|
|
2398
|
+
continue
|
|
2399
|
+
entries.append((st.st_mtime, st.st_size, path))
|
|
2400
|
+
total += st.st_size
|
|
2401
|
+
entries.sort(reverse=True) # newest first
|
|
2402
|
+
for idx, (mtime, size, path) in enumerate(entries):
|
|
2403
|
+
if os.path.abspath(path) == keep_abs or (now - mtime) < 3600:
|
|
2404
|
+
continue
|
|
2405
|
+
too_old = (now - mtime) > max_age_days * 86400
|
|
2406
|
+
over_cap = idx >= cls._CACHE_MAX_FILES
|
|
2407
|
+
over_bytes = total > cls._CACHE_MAX_BYTES
|
|
2408
|
+
if not (too_old or over_cap or over_bytes):
|
|
2409
|
+
continue
|
|
2410
|
+
try:
|
|
2411
|
+
os.unlink(path)
|
|
2412
|
+
total -= size
|
|
2413
|
+
removed += 1
|
|
2414
|
+
except OSError:
|
|
2415
|
+
pass
|
|
2416
|
+
os.makedirs(cache_dir, exist_ok=True)
|
|
2417
|
+
with open(marker, "w", encoding="utf-8") as fh:
|
|
2418
|
+
fh.write(str(int(now)))
|
|
2419
|
+
except OSError:
|
|
2420
|
+
pass
|
|
2421
|
+
return removed
|
|
2152
2422
|
|
|
2153
2423
|
@classmethod
|
|
2154
2424
|
def for_file(cls, file_path: str) -> Tuple[CodeGraph, str]:
|
|
@@ -2158,6 +2428,7 @@ class GraphEngine:
|
|
|
2158
2428
|
rel_path = os.path.relpath(os.path.abspath(file_path), root).replace("\\", "/")
|
|
2159
2429
|
return graph, rel_path
|
|
2160
2430
|
|
|
2431
|
+
|
|
2161
2432
|
def main():
|
|
2162
2433
|
import sys
|
|
2163
2434
|
args = sys.argv[1:]
|