tokensafe 4.16.2 → 5.0.0
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -3
- package/bin/agy-tokens +1 -1
- package/bin/tokensafe +1 -1
- package/bin/tokensafe-acp.js +1 -1
- package/bin/tokensafe-mcp +1 -1
- package/bin/tokensafe.js +1 -1
- package/hooks/claude_code_hook.py +49 -45
- package/hooks/cursor_hook.py +8 -8
- package/hooks/kimi_hook.py +23 -23
- package/hooks/post_tool_use.py +6 -6
- package/hooks/pre_invocation.py +21 -17
- package/hooks/pre_tool_use.py +27 -27
- package/hooks/session_start.py +17 -17
- package/hooks/stop_hook.py +3 -3
- package/hooks/zcode_hook.py +2 -2
- package/kimi.plugin.json +2 -2
- package/mcp_config.json +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/__init__.py +9 -5
- package/src/cli.py +11 -2429
- package/src/mcp_server.py +11 -5024
- package/src/proxy.py +11 -1803
- package/tokensafe/__init__.py +6 -0
- package/{src → tokensafe}/acp/__init__.py +2 -2
- package/{src → tokensafe}/acp/server.py +5 -5
- package/{src → tokensafe}/adapter_core.py +42 -17
- package/{src → tokensafe}/agent/__init__.py +1 -1
- package/{src → tokensafe}/agent/context.py +4 -4
- package/{src → tokensafe}/agent/loop.py +4 -4
- package/{src → tokensafe}/agent/providers.py +2 -2
- package/{src → tokensafe}/agent/tools.py +2 -2
- package/{src → tokensafe}/agent_firewall.py +68 -9
- package/{src → tokensafe}/angular_cli.py +4 -4
- package/{src → tokensafe}/auto_inject.py +37 -5
- package/{src → tokensafe}/batch_editor.py +185 -28
- package/tokensafe/batch_search.py +1191 -0
- package/{src → tokensafe}/bench/go_target.py +1 -1
- package/{src → tokensafe}/bench/mechanics.py +1 -1
- package/{src → tokensafe}/bench/react_target.py +1 -1
- package/{src → tokensafe}/bench/runner.py +4 -4
- package/{src → tokensafe}/benchmark.py +12 -12
- package/{src → tokensafe}/benchmark_real.py +18 -18
- package/{src → tokensafe}/build_parsers.py +3 -3
- package/{src → tokensafe}/bundle_probe.py +1 -1
- package/{src → tokensafe}/burn_monitor.py +3 -3
- package/{src → tokensafe}/cache_normalizer.py +1 -1
- package/tokensafe/cli.py +2490 -0
- package/{src → tokensafe}/command_sanitizer.py +94 -26
- package/{src → tokensafe}/compaction_recovery.py +5 -5
- package/{src → tokensafe}/compactor.py +148 -95
- package/{src → tokensafe}/context_index.py +194 -28
- package/{src → tokensafe}/cross_stack.py +2 -2
- package/{src → tokensafe}/dashboard.py +3 -3
- package/{src → tokensafe}/delegation.py +4 -4
- package/{src → tokensafe}/dependency_prefetcher.py +1 -1
- package/{src → tokensafe}/diff_slicer.py +2 -2
- package/{src → tokensafe}/distiller.py +7 -7
- package/{src → tokensafe}/distiller_cache.py +3 -3
- package/{src → tokensafe}/egress_counter.py +1 -1
- package/{src → tokensafe}/environment_auditor.py +7 -7
- package/{src → tokensafe}/file_state.py +2 -2
- package/{src → tokensafe}/format_invariants.py +1 -1
- package/tokensafe/format_parsers/__init__.py +20 -0
- package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
- package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
- package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
- package/{src → tokensafe}/format_parsers/json_log.py +1 -1
- package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
- package/{src → tokensafe}/format_parsers/tabular.py +1 -1
- package/{src → tokensafe}/fts_index.py +20 -11
- package/{src → tokensafe}/governor.py +143 -31
- package/{src → tokensafe}/graph_engine.py +769 -126
- package/{src → tokensafe}/guard.py +80 -25
- package/{src → tokensafe}/history_compactor.py +407 -133
- package/{src → tokensafe}/i18n_catalog.py +39 -14
- package/{src → tokensafe}/image_downscale.py +1 -1
- package/tokensafe/ingress_staging.py +384 -0
- package/{src → tokensafe}/installer.py +118 -61
- package/{src → tokensafe}/license_manager.py +9 -67
- package/{src → tokensafe}/live_relay.py +2 -2
- package/{src → tokensafe}/loop_detector.py +2 -2
- package/{src → tokensafe}/mcp_config_manager.py +2 -2
- package/{src → tokensafe}/mcp_proxy.py +4 -4
- package/tokensafe/mcp_server.py +5664 -0
- package/{src → tokensafe}/metrics.py +56 -21
- package/{src → tokensafe}/mistakes.py +4 -4
- package/{src → tokensafe}/oumv_brief.py +21 -3
- package/{src → tokensafe}/oumv_gateway.py +146 -49
- package/{src → tokensafe}/oumv_policy.py +1 -1
- package/{src → tokensafe}/paths.py +1 -1
- package/{src → tokensafe}/project_memory.py +4 -4
- package/tokensafe/proxy.py +2075 -0
- package/{src → tokensafe}/quality_score.py +4 -4
- package/tokensafe/read_baseline.py +192 -0
- package/tokensafe/repo_compute.py +332 -0
- package/{src → tokensafe}/result_ledger.py +19 -19
- package/{src → tokensafe}/retrofit.py +6 -6
- package/{src → tokensafe}/savings.py +3 -3
- package/tokensafe/schema_slicer.py +1087 -0
- package/{src → tokensafe}/scoped_search.py +144 -6
- package/{src → tokensafe}/secret_redactor.py +22 -0
- package/{src → tokensafe}/session_brief.py +8 -8
- package/{src → tokensafe}/skeletonizer.py +89 -26
- package/{src → tokensafe}/slicer.py +3 -2
- package/{src → tokensafe}/snapshot.py +1 -1
- package/{src → tokensafe}/stash.py +1 -1
- package/{src → tokensafe}/statusline.py +1 -1
- package/{src → tokensafe}/superseded.py +22 -4
- package/{src → tokensafe}/team_cache.py +3 -3
- package/{src → tokensafe}/telemetry_sync.py +63 -11
- package/{src → tokensafe}/test_parsers.py +3 -3
- package/{src → tokensafe}/thinking_fold.py +3 -3
- package/{src → tokensafe}/tokenizer.py +37 -1
- package/{src → tokensafe}/tool_pruner.py +3 -3
- package/{src → tokensafe}/transcript_analyzer.py +1 -1
- package/{src → tokensafe}/transcript_recall.py +8 -8
- package/{src → tokensafe}/type_slicer.py +3 -3
- package/{src → tokensafe}/usage_ledger.py +4 -4
- package/{src → tokensafe}/version_checker.py +6 -6
- package/{src → tokensafe}/web_reader.py +86 -8
- package/{src → tokensafe}/workspace_roots.py +2 -2
- package/src/batch_search.py +0 -589
- package/src/format_parsers/__init__.py +0 -20
- package/src/schema_slicer.py +0 -578
- /package/{src → tokensafe}/agent/pricing.py +0 -0
- /package/{src → tokensafe}/atomic_io.py +0 -0
- /package/{src → tokensafe}/backend_release.py +0 -0
- /package/{src → tokensafe}/bench/__init__.py +0 -0
- /package/{src → tokensafe}/bench/driver.py +0 -0
- /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
- /package/{src → tokensafe}/bench_scenarios.json +0 -0
- /package/{src → tokensafe}/competitors.py +0 -0
- /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
- /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
- /package/{src → tokensafe}/globmatch.py +0 -0
- /package/{src → tokensafe}/host_capabilities.py +0 -0
- /package/{src → tokensafe}/json_repair.py +0 -0
- /package/{src → tokensafe}/route_index.py +0 -0
- /package/{src → tokensafe}/scaffold.py +0 -0
- /package/{src → tokensafe}/session_context.py +0 -0
- /package/{src → tokensafe}/ssl_context.py +0 -0
- /package/{src → tokensafe}/stdio_io.py +0 -0
- /package/{src → tokensafe}/syntax_guard.py +0 -0
- /package/{src → tokensafe}/toml_mcp_config.py +0 -0
- /package/{src → tokensafe}/treesitter_backend.py +0 -0
- /package/{src → tokensafe}/win_paths.py +0 -0
package/src/schema_slicer.py
DELETED
|
@@ -1,578 +0,0 @@
|
|
|
1
|
-
"""Schema-aware slicer for heavy declarative files that break AST code tooling.
|
|
2
|
-
|
|
3
|
-
Opening a 5,000-line OpenAPI spec, Prisma schema, GraphQL SDL or SQL migration
|
|
4
|
-
dump costs 20k-50k tokens; generic AST skeletonization does not apply to them.
|
|
5
|
-
SchemaSlicer returns a compact overview when no target is given, and a targeted
|
|
6
|
-
slice (the requested entry + 1-hop references) when one is:
|
|
7
|
-
|
|
8
|
-
- OpenAPI/Swagger (JSON + YAML): one path + its $ref schema closure, or one schema.
|
|
9
|
-
- Prisma: one model block + 1-hop relation targets.
|
|
10
|
-
- GraphQL SDL: one type block + 1-hop field types.
|
|
11
|
-
- SQL: DDL statements only (CREATE TABLE/INDEX/ALTER/TYPE) — INSERT/UPDATE
|
|
12
|
-
history is dropped; a target table filters further.
|
|
13
|
-
|
|
14
|
-
Standard library only. `target` semantics follow the `symbol` argument of
|
|
15
|
-
smart_read_file so agents use one familiar entry point.
|
|
16
|
-
"""
|
|
17
|
-
|
|
18
|
-
import json
|
|
19
|
-
import os
|
|
20
|
-
import re
|
|
21
|
-
import hashlib
|
|
22
|
-
import sqlite3
|
|
23
|
-
import time
|
|
24
|
-
import threading
|
|
25
|
-
from collections import OrderedDict
|
|
26
|
-
|
|
27
|
-
from src.tokenizer import count_tokens
|
|
28
|
-
from src.paths import resolve_data_dir
|
|
29
|
-
from typing import Any, Dict, List, Optional, Tuple
|
|
30
|
-
|
|
31
|
-
_MAX_REF_CHAIN = 15
|
|
32
|
-
_MAX_SQL_BYTES = 4 * 1024 * 1024
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
class SchemaSlicer:
|
|
36
|
-
"""Detects schema files and produces targeted, token-cheap slices with L1/L2/L3 caching."""
|
|
37
|
-
|
|
38
|
-
_mem_cache: "OrderedDict[str, Tuple[str, Dict[str, Any]]]" = OrderedDict()
|
|
39
|
-
_mem_lock = threading.Lock()
|
|
40
|
-
_db_init_done = False
|
|
41
|
-
_db_init_lock = threading.Lock()
|
|
42
|
-
|
|
43
|
-
@classmethod
|
|
44
|
-
def clear_memory_cache(cls):
|
|
45
|
-
with cls._mem_lock:
|
|
46
|
-
cls._mem_cache.clear()
|
|
47
|
-
|
|
48
|
-
@classmethod
|
|
49
|
-
def _mem_put(cls, key: str, val: Tuple[str, Dict[str, Any]], max_items: int = 80) -> None:
|
|
50
|
-
"""Stores entry in LRU memory cache with fixed cap."""
|
|
51
|
-
with cls._mem_lock:
|
|
52
|
-
cls._mem_cache[key] = val
|
|
53
|
-
cls._mem_cache.move_to_end(key)
|
|
54
|
-
if len(cls._mem_cache) > max_items:
|
|
55
|
-
cls._mem_cache.popitem(last=False)
|
|
56
|
-
|
|
57
|
-
@classmethod
|
|
58
|
-
def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 2000) -> None:
|
|
59
|
-
"""Evicts oldest entries when schema cache exceeds max_rows."""
|
|
60
|
-
try:
|
|
61
|
-
row = conn.execute("SELECT COUNT(*) FROM schema_cache;").fetchone()
|
|
62
|
-
count = row[0] if row else 0
|
|
63
|
-
if count > max_rows:
|
|
64
|
-
excess = count - max_rows
|
|
65
|
-
conn.execute(
|
|
66
|
-
"DELETE FROM schema_cache WHERE cache_key IN ("
|
|
67
|
-
"SELECT cache_key FROM schema_cache ORDER BY cached_at ASC LIMIT ?"
|
|
68
|
-
");", (excess,)
|
|
69
|
-
)
|
|
70
|
-
except Exception:
|
|
71
|
-
pass
|
|
72
|
-
|
|
73
|
-
@classmethod
|
|
74
|
-
def _get_db_path(cls) -> str:
|
|
75
|
-
data_dir = resolve_data_dir()
|
|
76
|
-
os.makedirs(data_dir, exist_ok=True)
|
|
77
|
-
return os.path.join(data_dir, "type_cache.db")
|
|
78
|
-
|
|
79
|
-
@classmethod
|
|
80
|
-
def _init_db(cls):
|
|
81
|
-
db_path = cls._get_db_path()
|
|
82
|
-
with cls._db_init_lock:
|
|
83
|
-
if cls._db_init_done == db_path and os.path.exists(db_path):
|
|
84
|
-
return
|
|
85
|
-
conn = None
|
|
86
|
-
try:
|
|
87
|
-
conn = sqlite3.connect(db_path, timeout=5.0)
|
|
88
|
-
conn.execute("PRAGMA journal_mode=WAL;")
|
|
89
|
-
conn.execute("PRAGMA busy_timeout=5000;")
|
|
90
|
-
conn.execute("""
|
|
91
|
-
CREATE TABLE IF NOT EXISTS schema_cache (
|
|
92
|
-
cache_key TEXT PRIMARY KEY,
|
|
93
|
-
schema_kind TEXT NOT NULL,
|
|
94
|
-
fingerprint TEXT NOT NULL,
|
|
95
|
-
target TEXT NOT NULL,
|
|
96
|
-
sliced_text TEXT NOT NULL,
|
|
97
|
-
info_json TEXT NOT NULL,
|
|
98
|
-
cached_at INTEGER NOT NULL
|
|
99
|
-
);
|
|
100
|
-
""")
|
|
101
|
-
conn.commit()
|
|
102
|
-
cls._db_init_done = db_path
|
|
103
|
-
except Exception:
|
|
104
|
-
pass
|
|
105
|
-
finally:
|
|
106
|
-
if conn:
|
|
107
|
-
try:
|
|
108
|
-
conn.close()
|
|
109
|
-
except Exception:
|
|
110
|
-
pass
|
|
111
|
-
|
|
112
|
-
@classmethod
|
|
113
|
-
def compute_schema_fingerprint(cls, path: str, kind: str) -> str:
|
|
114
|
-
"""
|
|
115
|
-
Computes deterministic composite fingerprint:
|
|
116
|
-
- For single file: SHA-256(content)[:16]
|
|
117
|
-
- For multi-file Prisma (prisma/schema/*.prisma): content hashes of all .prisma files
|
|
118
|
-
- For OpenAPI with local $ref: content hashes of root + referenced local files
|
|
119
|
-
"""
|
|
120
|
-
abs_p = os.path.abspath(path)
|
|
121
|
-
base_dir = os.path.dirname(abs_p)
|
|
122
|
-
|
|
123
|
-
# Multi-file Prisma check
|
|
124
|
-
if kind == "prisma" and os.path.basename(base_dir).lower() == "schema":
|
|
125
|
-
try:
|
|
126
|
-
prisma_files = sorted([
|
|
127
|
-
os.path.join(base_dir, f) for f in os.listdir(base_dir) if f.endswith(".prisma")
|
|
128
|
-
])
|
|
129
|
-
if len(prisma_files) > 1:
|
|
130
|
-
hasher = hashlib.sha256()
|
|
131
|
-
for pf in prisma_files:
|
|
132
|
-
with open(pf, "rb") as pff:
|
|
133
|
-
pf_bytes = pff.read()
|
|
134
|
-
pf_hash = hashlib.sha256(pf_bytes).hexdigest()
|
|
135
|
-
hasher.update(f"{os.path.basename(pf)}:{pf_hash}".encode("utf-8"))
|
|
136
|
-
return hasher.hexdigest()[:16]
|
|
137
|
-
except Exception:
|
|
138
|
-
pass
|
|
139
|
-
|
|
140
|
-
# Single file hash or OpenAPI $ref
|
|
141
|
-
try:
|
|
142
|
-
with open(abs_p, "rb") as f:
|
|
143
|
-
content = f.read()
|
|
144
|
-
h = hashlib.sha256(content).hexdigest()[:16]
|
|
145
|
-
if kind == "openapi" and b"$ref" in content:
|
|
146
|
-
ref_matches = re.findall(rb'["\']?\$ref["\']?\s*:\s*["\'](\.[^"\'#]+)', content)
|
|
147
|
-
if ref_matches:
|
|
148
|
-
hasher = hashlib.sha256(content)
|
|
149
|
-
for rm in sorted(set(ref_matches)):
|
|
150
|
-
ref_rel = rm.decode("utf-8", errors="ignore")
|
|
151
|
-
cand = os.path.normpath(os.path.join(base_dir, ref_rel))
|
|
152
|
-
if os.path.isfile(cand):
|
|
153
|
-
try:
|
|
154
|
-
with open(cand, "rb") as cf:
|
|
155
|
-
cand_bytes = cf.read()
|
|
156
|
-
cand_hash = hashlib.sha256(cand_bytes).hexdigest()
|
|
157
|
-
hasher.update(f"{ref_rel}:{cand_hash}".encode("utf-8"))
|
|
158
|
-
except Exception:
|
|
159
|
-
pass
|
|
160
|
-
return hasher.hexdigest()[:16]
|
|
161
|
-
return h
|
|
162
|
-
except Exception:
|
|
163
|
-
return "unknown_fp"
|
|
164
|
-
|
|
165
|
-
@classmethod
|
|
166
|
-
def detect(cls, path: str) -> Optional[str]:
|
|
167
|
-
"""Returns the schema kind for `path` (openapi|prisma|graphql|sql) or None."""
|
|
168
|
-
ext = os.path.splitext(path)[1].lower()
|
|
169
|
-
if ext == ".prisma":
|
|
170
|
-
return "prisma"
|
|
171
|
-
if ext in (".graphql", ".gql"):
|
|
172
|
-
return "graphql"
|
|
173
|
-
if ext == ".sql":
|
|
174
|
-
return "sql"
|
|
175
|
-
if ext == ".json":
|
|
176
|
-
try:
|
|
177
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
178
|
-
head = f.read(4096)
|
|
179
|
-
return "openapi" if re.search(r'"(?:openapi|swagger|paths)"\s*:', head) else None
|
|
180
|
-
except Exception:
|
|
181
|
-
return None
|
|
182
|
-
if ext in (".yaml", ".yml"):
|
|
183
|
-
try:
|
|
184
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
185
|
-
head = f.read(4096)
|
|
186
|
-
return "openapi" if re.search(r"^\s*(openapi|swagger)\s*:", head, re.MULTILINE) else None
|
|
187
|
-
except Exception:
|
|
188
|
-
return None
|
|
189
|
-
return None
|
|
190
|
-
|
|
191
|
-
@classmethod
|
|
192
|
-
def slice_file(cls, path: str, target: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
193
|
-
"""Returns (sliced_text, info). Empty `target` yields a compact overview with L1/L2/L3 caching."""
|
|
194
|
-
kind = cls.detect(path)
|
|
195
|
-
if not kind:
|
|
196
|
-
return "", {"kind": None}
|
|
197
|
-
|
|
198
|
-
# 1. Compute composite fingerprint and case-preserving cache key
|
|
199
|
-
norm_target = target.strip()
|
|
200
|
-
fp = cls.compute_schema_fingerprint(path, kind)
|
|
201
|
-
cache_key = f"{kind}::{fp}::{norm_target}"
|
|
202
|
-
|
|
203
|
-
# 2. Check L1 Memory
|
|
204
|
-
with cls._mem_lock:
|
|
205
|
-
if cache_key in cls._mem_cache:
|
|
206
|
-
cls._mem_cache.move_to_end(cache_key)
|
|
207
|
-
hit_text, hit_info = cls._mem_cache[cache_key]
|
|
208
|
-
hit_info = dict(hit_info)
|
|
209
|
-
hit_info["source"] = "L1_memory"
|
|
210
|
-
return hit_text, hit_info
|
|
211
|
-
|
|
212
|
-
# 3. Check L2 SQLite
|
|
213
|
-
cls._init_db()
|
|
214
|
-
db_path = cls._get_db_path()
|
|
215
|
-
l2_conn = None
|
|
216
|
-
try:
|
|
217
|
-
l2_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
218
|
-
l2_conn.execute("PRAGMA busy_timeout=5000;")
|
|
219
|
-
row = l2_conn.execute(
|
|
220
|
-
"SELECT sliced_text, info_json FROM schema_cache WHERE cache_key = ?",
|
|
221
|
-
(cache_key,)
|
|
222
|
-
).fetchone()
|
|
223
|
-
if row:
|
|
224
|
-
text_cached, info_raw = row[0], row[1]
|
|
225
|
-
info_dict = json.loads(info_raw)
|
|
226
|
-
info_dict["source"] = "L2_sqlite"
|
|
227
|
-
cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
|
|
228
|
-
return text_cached, info_dict
|
|
229
|
-
except Exception:
|
|
230
|
-
pass
|
|
231
|
-
finally:
|
|
232
|
-
if l2_conn:
|
|
233
|
-
try:
|
|
234
|
-
l2_conn.close()
|
|
235
|
-
except Exception:
|
|
236
|
-
pass
|
|
237
|
-
|
|
238
|
-
# 4. Check L3 Team Sync
|
|
239
|
-
try:
|
|
240
|
-
from src.team_cache import TeamCache
|
|
241
|
-
team_val = TeamCache.get("SCHEMA_CONTRACTS", cache_key, timeout=0.5)
|
|
242
|
-
if team_val:
|
|
243
|
-
parsed_team = json.loads(team_val)
|
|
244
|
-
text_cached = parsed_team.get("sliced", "")
|
|
245
|
-
info_dict = parsed_team.get("info", {})
|
|
246
|
-
info_dict["source"] = "L3_team_cache"
|
|
247
|
-
cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
|
|
248
|
-
# Store back to L2
|
|
249
|
-
back_conn = None
|
|
250
|
-
try:
|
|
251
|
-
back_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
252
|
-
back_conn.execute("""
|
|
253
|
-
INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
|
|
254
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
255
|
-
""", (cache_key, kind, fp, norm_target, text_cached, json.dumps(info_dict), int(time.time())))
|
|
256
|
-
cls._maybe_evict(back_conn)
|
|
257
|
-
back_conn.commit()
|
|
258
|
-
except Exception:
|
|
259
|
-
pass
|
|
260
|
-
finally:
|
|
261
|
-
if back_conn:
|
|
262
|
-
try:
|
|
263
|
-
back_conn.close()
|
|
264
|
-
except Exception:
|
|
265
|
-
pass
|
|
266
|
-
return text_cached, info_dict
|
|
267
|
-
except Exception:
|
|
268
|
-
pass
|
|
269
|
-
|
|
270
|
-
# 5. Compute fresh slice
|
|
271
|
-
raw_text = ""
|
|
272
|
-
try:
|
|
273
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
274
|
-
raw_text = f.read()
|
|
275
|
-
except OSError:
|
|
276
|
-
pass
|
|
277
|
-
|
|
278
|
-
sliced = ""
|
|
279
|
-
if kind == "openapi":
|
|
280
|
-
sliced, info = cls._slice_openapi(path, target.strip())
|
|
281
|
-
elif kind == "prisma":
|
|
282
|
-
sliced, info = cls._slice_prisma(path, target.strip())
|
|
283
|
-
elif kind == "graphql":
|
|
284
|
-
sliced, info = cls._slice_graphql(path, target.strip())
|
|
285
|
-
elif kind == "sql":
|
|
286
|
-
sliced, info = cls._slice_sql(path, target.strip())
|
|
287
|
-
else:
|
|
288
|
-
return "", {"kind": None}
|
|
289
|
-
|
|
290
|
-
if not target.strip() and count_tokens(sliced) >= count_tokens(raw_text):
|
|
291
|
-
return raw_text, info
|
|
292
|
-
|
|
293
|
-
if info.get("error") or info.get("mode") == "missing":
|
|
294
|
-
return sliced, info
|
|
295
|
-
|
|
296
|
-
# 6. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
|
|
297
|
-
info["source"] = "parsed_live"
|
|
298
|
-
cls._mem_put(cache_key, (sliced, info), max_items=80)
|
|
299
|
-
|
|
300
|
-
save_conn = None
|
|
301
|
-
try:
|
|
302
|
-
save_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
303
|
-
save_conn.execute("""
|
|
304
|
-
INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
|
|
305
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
306
|
-
""", (cache_key, kind, fp, norm_target, sliced, json.dumps(info), int(time.time())))
|
|
307
|
-
cls._maybe_evict(save_conn)
|
|
308
|
-
save_conn.commit()
|
|
309
|
-
except Exception:
|
|
310
|
-
pass
|
|
311
|
-
finally:
|
|
312
|
-
if save_conn:
|
|
313
|
-
try:
|
|
314
|
-
save_conn.close()
|
|
315
|
-
except Exception:
|
|
316
|
-
pass
|
|
317
|
-
|
|
318
|
-
try:
|
|
319
|
-
from src.team_cache import TeamCache
|
|
320
|
-
payload = json.dumps({"sliced": sliced, "info": info}, ensure_ascii=False)
|
|
321
|
-
TeamCache.put("SCHEMA_CONTRACTS", cache_key, payload, tokens_saved=max(40, count_tokens(raw_text) - count_tokens(sliced)))
|
|
322
|
-
except Exception:
|
|
323
|
-
pass
|
|
324
|
-
|
|
325
|
-
return sliced, info
|
|
326
|
-
|
|
327
|
-
# ------------------------------------------------------------------ OpenAPI
|
|
328
|
-
|
|
329
|
-
@classmethod
|
|
330
|
-
def _slice_openapi(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
|
|
331
|
-
ext = os.path.splitext(path)[1].lower()
|
|
332
|
-
if ext in (".yaml", ".yml"):
|
|
333
|
-
return cls._slice_openapi_yaml(path, target)
|
|
334
|
-
try:
|
|
335
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
336
|
-
spec = json.load(f)
|
|
337
|
-
except Exception as e:
|
|
338
|
-
return f"[TokenSafe SchemaSlicer] Cannot parse OpenAPI JSON: {e}", {"kind": "openapi", "error": True}
|
|
339
|
-
|
|
340
|
-
def schema_pool() -> Dict[str, Any]:
|
|
341
|
-
comps = spec.get("components") or {}
|
|
342
|
-
return (comps.get("schemas") or {}) or (spec.get("definitions") or {})
|
|
343
|
-
|
|
344
|
-
def resolve_refs(node: Any, pool: Dict[str, Any], acc: Dict[str, Any], depth: int = 0) -> None:
|
|
345
|
-
if depth > _MAX_REF_CHAIN or len(acc) >= _MAX_REF_CHAIN:
|
|
346
|
-
return
|
|
347
|
-
if isinstance(node, dict):
|
|
348
|
-
ref = node.get("$ref")
|
|
349
|
-
if isinstance(ref, str) and ref.startswith("#/"):
|
|
350
|
-
name = ref.rsplit("/", 1)[-1]
|
|
351
|
-
if name not in acc and name in pool:
|
|
352
|
-
acc[name] = pool[name]
|
|
353
|
-
resolve_refs(pool[name], pool, acc, depth + 1)
|
|
354
|
-
for v in node.values():
|
|
355
|
-
resolve_refs(v, pool, acc, depth + 1)
|
|
356
|
-
elif isinstance(node, list):
|
|
357
|
-
for v in node:
|
|
358
|
-
resolve_refs(v, pool, acc, depth + 1)
|
|
359
|
-
|
|
360
|
-
# Check method-scoped path FIRST (e.g. "/users get" or "/users:get"), before plain target.startswith("/")
|
|
361
|
-
if target:
|
|
362
|
-
parts = re.split(r"[\s:]+", target, maxsplit=1)
|
|
363
|
-
if len(parts) == 2 and parts[0].startswith("/") and parts[1].lower() in ("get", "post", "put", "patch", "delete", "options", "head"):
|
|
364
|
-
item = (spec.get("paths") or {}).get(parts[0]) or {}
|
|
365
|
-
op = item.get(parts[1].lower())
|
|
366
|
-
if op is not None:
|
|
367
|
-
pool = schema_pool()
|
|
368
|
-
acc: Dict[str, Any] = {}
|
|
369
|
-
resolve_refs(op, pool, acc)
|
|
370
|
-
out = [f"# OpenAPI operation: {parts[1].upper()} {parts[0]}", json.dumps({parts[1].lower(): op}, indent=2, ensure_ascii=False)]
|
|
371
|
-
if acc:
|
|
372
|
-
out.append("\n# Referenced schemas ($ref closure)")
|
|
373
|
-
out.append(json.dumps(acc, indent=2, ensure_ascii=False))
|
|
374
|
-
return "\n".join(out), {"kind": "openapi", "mode": "operation", "refs": list(acc)}
|
|
375
|
-
return cls._openapi_overview(spec, missing=target)
|
|
376
|
-
|
|
377
|
-
if target.startswith("/"):
|
|
378
|
-
item = (spec.get("paths") or {}).get(target)
|
|
379
|
-
if item is None:
|
|
380
|
-
return cls._openapi_overview(spec, missing=target)
|
|
381
|
-
pool = schema_pool()
|
|
382
|
-
acc: Dict[str, Any] = {}
|
|
383
|
-
resolve_refs(item, pool, acc)
|
|
384
|
-
out = [f"# OpenAPI path: {target}", json.dumps({target: item}, indent=2, ensure_ascii=False)]
|
|
385
|
-
if acc:
|
|
386
|
-
out.append("\n# Referenced schemas ($ref closure)")
|
|
387
|
-
out.append(json.dumps(acc, indent=2, ensure_ascii=False))
|
|
388
|
-
return "\n".join(out), {"kind": "openapi", "mode": "path", "refs": list(acc)}
|
|
389
|
-
if target:
|
|
390
|
-
pool = schema_pool()
|
|
391
|
-
if target in pool:
|
|
392
|
-
acc: Dict[str, Any] = {}
|
|
393
|
-
resolve_refs(pool[target], pool, acc)
|
|
394
|
-
body = {"name": target, **(pool[target] if isinstance(pool[target], dict) else {"schema": pool[target]})}
|
|
395
|
-
out = [f"# OpenAPI schema: {target}", json.dumps(body, indent=2, ensure_ascii=False)]
|
|
396
|
-
others = {k: v for k, v in acc.items() if k != target}
|
|
397
|
-
if others:
|
|
398
|
-
out.append("\n# Referenced schemas ($ref closure)")
|
|
399
|
-
out.append(json.dumps(others, indent=2, ensure_ascii=False))
|
|
400
|
-
return "\n".join(out), {"kind": "openapi", "mode": "schema", "refs": list(others)}
|
|
401
|
-
return cls._openapi_overview(spec, missing=target)
|
|
402
|
-
return cls._openapi_overview(spec)
|
|
403
|
-
|
|
404
|
-
@classmethod
|
|
405
|
-
def _openapi_overview(cls, spec: Dict[str, Any], missing: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
406
|
-
lines = [f"# OpenAPI {spec.get('openapi') or spec.get('swagger') or ''} — overview"]
|
|
407
|
-
if missing:
|
|
408
|
-
lines.append(f"# (target '{missing}' not found — showing the spec index)")
|
|
409
|
-
paths = spec.get("paths") or {}
|
|
410
|
-
lines.append(f"\n## Paths ({len(paths)})")
|
|
411
|
-
for p, item in list(paths.items())[:120]:
|
|
412
|
-
methods = [m.upper() for m in (item or {}) if m in ("get", "post", "put", "patch", "delete", "options", "head")]
|
|
413
|
-
lines.append(f" {'/'.join(methods) or '-'} {p}")
|
|
414
|
-
pool = (spec.get("components") or {}).get("schemas") or spec.get("definitions") or {}
|
|
415
|
-
names = list(pool.keys())
|
|
416
|
-
lines.append(f"\n## Schemas ({len(names)})")
|
|
417
|
-
lines.append(" " + ", ".join(names[:150]))
|
|
418
|
-
lines.append("\nSlice a specific entry: symbol='/users/{id}' (path), '/users get' (operation) or 'User' (schema).")
|
|
419
|
-
return "\n".join(lines), {"kind": "openapi", "mode": "overview"}
|
|
420
|
-
|
|
421
|
-
@classmethod
|
|
422
|
-
def _slice_openapi_yaml(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
|
|
423
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
424
|
-
lines = f.readlines()
|
|
425
|
-
# Top-level paths block: lines matching " /path:" under "paths:"
|
|
426
|
-
in_paths = False
|
|
427
|
-
blocks: Dict[str, List[str]] = {}
|
|
428
|
-
current: Optional[str] = None
|
|
429
|
-
for ln in lines:
|
|
430
|
-
if re.match(r"^paths\s*:", ln):
|
|
431
|
-
in_paths = True
|
|
432
|
-
continue
|
|
433
|
-
if in_paths:
|
|
434
|
-
if re.match(r"^[A-Za-z_#-]", ln): # next top-level key ends paths
|
|
435
|
-
in_paths = False
|
|
436
|
-
current = None
|
|
437
|
-
else:
|
|
438
|
-
m = re.match(r"^ (\s*/[^\s:]+)\s*:", ln)
|
|
439
|
-
if m:
|
|
440
|
-
current = m.group(1)
|
|
441
|
-
blocks[current] = [ln]
|
|
442
|
-
elif current:
|
|
443
|
-
blocks[current].append(ln)
|
|
444
|
-
if not target:
|
|
445
|
-
lines_out = [f"# OpenAPI (YAML) — overview", "", "## Paths"]
|
|
446
|
-
for p in list(blocks)[:120]:
|
|
447
|
-
lines_out.append(f" {p.rstrip(':')}")
|
|
448
|
-
lines_out.append("\nSlice a specific path: symbol='/users/{id}'.")
|
|
449
|
-
return "\n".join(lines_out), {"kind": "openapi", "mode": "overview"}
|
|
450
|
-
norm = target if target.startswith("/") else "/" + target
|
|
451
|
-
blk = blocks.get(norm) or blocks.get(target.rstrip(":"))
|
|
452
|
-
if not blk:
|
|
453
|
-
return "\n".join([f"# target '{target}' not found", "## Paths"] + [f" {p.rstrip(':')}" for p in list(blocks)[:120]]), {"kind": "openapi", "mode": "missing"}
|
|
454
|
-
return f"# OpenAPI path: {norm}\n" + "".join(blk), {"kind": "openapi", "mode": "path"}
|
|
455
|
-
|
|
456
|
-
# ------------------------------------------------------------------ Prisma
|
|
457
|
-
|
|
458
|
-
@classmethod
|
|
459
|
-
def _slice_prisma(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
|
|
460
|
-
abs_p = os.path.abspath(path)
|
|
461
|
-
base_dir = os.path.dirname(abs_p)
|
|
462
|
-
if os.path.basename(base_dir).lower() == "schema":
|
|
463
|
-
try:
|
|
464
|
-
prisma_files = sorted(
|
|
465
|
-
os.path.join(base_dir, f) for f in os.listdir(base_dir) if f.endswith(".prisma")
|
|
466
|
-
)
|
|
467
|
-
except OSError:
|
|
468
|
-
prisma_files = [abs_p]
|
|
469
|
-
if not prisma_files:
|
|
470
|
-
prisma_files = [abs_p]
|
|
471
|
-
else:
|
|
472
|
-
prisma_files = [abs_p]
|
|
473
|
-
src_parts = []
|
|
474
|
-
for pf in prisma_files:
|
|
475
|
-
with open(pf, "r", encoding="utf-8", errors="replace") as f:
|
|
476
|
-
src_parts.append(f.read())
|
|
477
|
-
src = "\n\n".join(src_parts)
|
|
478
|
-
block_re = re.compile(r"^(model|enum|type)\s+(\w+)\s*\{(.*?)^\}", re.MULTILINE | re.DOTALL)
|
|
479
|
-
blocks: Dict[str, Tuple[str, str]] = {}
|
|
480
|
-
order: List[str] = []
|
|
481
|
-
for m in block_re.finditer(src):
|
|
482
|
-
name = m.group(2)
|
|
483
|
-
blocks[name] = (m.group(1), m.group(0))
|
|
484
|
-
order.append(name)
|
|
485
|
-
if not target:
|
|
486
|
-
lines = [f"# Prisma schema — overview ({len(blocks)} definitions)", ""]
|
|
487
|
-
for name in order[:150]:
|
|
488
|
-
kind_name, body = blocks[name]
|
|
489
|
-
fields = len(re.findall(r"^\s{2,}\w+", body, re.MULTILINE))
|
|
490
|
-
lines.append(f" {kind_name} {name} ({fields} fields)")
|
|
491
|
-
lines.append("\nSlice a model: symbol='User'.")
|
|
492
|
-
return "\n".join(lines), {"kind": "prisma", "mode": "overview"}
|
|
493
|
-
if target not in blocks:
|
|
494
|
-
return f"# target '{target}' not found. Definitions: {', '.join(order[:100])}", {"kind": "prisma", "mode": "missing"}
|
|
495
|
-
kind_name, body = blocks[target]
|
|
496
|
-
out = [f"# Prisma {kind_name} {target}", body]
|
|
497
|
-
# 1-hop: capitalized field types that are themselves defined blocks
|
|
498
|
-
refs = set()
|
|
499
|
-
for fm in re.finditer(r"^\s{2,}\w+\s+([A-Z]\w*)(?:\?|\[\])?(?:\s|$)", body, re.MULTILINE):
|
|
500
|
-
if fm.group(1) in blocks and fm.group(1) != target:
|
|
501
|
-
refs.add(fm.group(1))
|
|
502
|
-
if refs:
|
|
503
|
-
out.append("\n# 1-hop related definitions")
|
|
504
|
-
for r in sorted(refs):
|
|
505
|
-
out.append(blocks[r][1])
|
|
506
|
-
return "\n".join(out), {"kind": "prisma", "mode": "model", "refs": sorted(refs)}
|
|
507
|
-
|
|
508
|
-
# ------------------------------------------------------------------ GraphQL
|
|
509
|
-
|
|
510
|
-
@classmethod
|
|
511
|
-
def _slice_graphql(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
|
|
512
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
513
|
-
src = f.read()
|
|
514
|
-
src = re.sub(r'"""[\s\S]*?"""', '""', src) # drop block descriptions for overview scanning
|
|
515
|
-
block_re = re.compile(r"^(type|input|interface|enum)\s+(\w+)([^{}]*?)\{(.*?)\}", re.MULTILINE | re.DOTALL)
|
|
516
|
-
blocks: Dict[str, Tuple[str, str]] = {}
|
|
517
|
-
order: List[str] = []
|
|
518
|
-
for m in block_re.finditer(src):
|
|
519
|
-
name = m.group(2)
|
|
520
|
-
blocks[name] = (m.group(1), m.group(0))
|
|
521
|
-
order.append(name)
|
|
522
|
-
for m in re.finditer(r"^(scalar|union)\s+(\w+)([^\n]*)", src, re.MULTILINE):
|
|
523
|
-
name = m.group(2)
|
|
524
|
-
if name not in blocks:
|
|
525
|
-
blocks[name] = (m.group(1), m.group(0).strip())
|
|
526
|
-
order.append(name)
|
|
527
|
-
if not target:
|
|
528
|
-
lines = [f"# GraphQL SDL — overview ({len(blocks)} definitions)", ""]
|
|
529
|
-
for name in order[:150]:
|
|
530
|
-
kind_name, _ = blocks[name]
|
|
531
|
-
lines.append(f" {kind_name} {name}")
|
|
532
|
-
lines.append("\nSlice a type: symbol='User'.")
|
|
533
|
-
return "\n".join(lines), {"kind": "graphql", "mode": "overview"}
|
|
534
|
-
if target not in blocks:
|
|
535
|
-
return f"# target '{target}' not found. Definitions: {', '.join(order[:100])}", {"kind": "graphql", "mode": "missing"}
|
|
536
|
-
kind_name, body = blocks[target]
|
|
537
|
-
out = [f"# GraphQL {kind_name} {target}", body]
|
|
538
|
-
refs = set()
|
|
539
|
-
for fm in re.finditer(r":\s*\[?([A-Z]\w*)[!\]]*(?:\s|$)", body):
|
|
540
|
-
if fm.group(1) in blocks and fm.group(1) != target:
|
|
541
|
-
refs.add(fm.group(1))
|
|
542
|
-
if refs:
|
|
543
|
-
out.append("\n# 1-hop related types")
|
|
544
|
-
for r in sorted(refs):
|
|
545
|
-
out.append(blocks[r][1])
|
|
546
|
-
return "\n".join(out), {"kind": "graphql", "mode": "type", "refs": sorted(refs)}
|
|
547
|
-
|
|
548
|
-
# ------------------------------------------------------------------ SQL
|
|
549
|
-
|
|
550
|
-
_SQL_DDL_RE = re.compile(
|
|
551
|
-
r"^\s*(CREATE\s+(?:UNIQUE\s+)?(?:TABLE|INDEX|MATERIALIZED\s+VIEW|VIEW|TYPE|SCHEMA)|ALTER\s+TABLE)\b",
|
|
552
|
-
re.IGNORECASE,
|
|
553
|
-
)
|
|
554
|
-
|
|
555
|
-
@classmethod
|
|
556
|
-
def _slice_sql(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
|
|
557
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
558
|
-
src = f.read(_MAX_SQL_BYTES)
|
|
559
|
-
# Split into statements on ';' (string-literal safe enough for DDL scans:
|
|
560
|
-
# quoted ';' inside INSERT values never appears in DDL we keep).
|
|
561
|
-
statements = [s.strip() for s in src.split(";") if s.strip()]
|
|
562
|
-
ddl = [s for s in statements if cls._SQL_DDL_RE.match(s)]
|
|
563
|
-
if not target:
|
|
564
|
-
tables = []
|
|
565
|
-
for s in ddl:
|
|
566
|
-
m = re.search(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[\"'`]?([\w.]+)[\"'`]?", s, re.IGNORECASE)
|
|
567
|
-
if m:
|
|
568
|
-
tables.append(m.group(1))
|
|
569
|
-
lines = [f"# SQL DDL skeleton — {len(ddl)} DDL statements, {len(tables)} tables (DML history omitted)", ""]
|
|
570
|
-
for t in tables[:150]:
|
|
571
|
-
lines.append(f" {t}")
|
|
572
|
-
lines.append("\nSlice a table: symbol='users'.")
|
|
573
|
-
return "\n".join(lines), {"kind": "sql", "mode": "overview", "tables": tables}
|
|
574
|
-
t_lower = target.lower().lstrip('"\'`')
|
|
575
|
-
matched = [s for s in ddl if re.search(r"[\"'`]?[\w.]*" + re.escape(t_lower) + r"[\"`]?", s, re.IGNORECASE)]
|
|
576
|
-
if not matched:
|
|
577
|
-
return f"# target '{target}' not found among {len(ddl)} DDL statements", {"kind": "sql", "mode": "missing"}
|
|
578
|
-
return ";\n\n".join(matched) + ";", {"kind": "sql", "mode": "ddl", "statements": len(matched)}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|