tokensafe 4.16.3 → 5.0.1

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.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +1 -1
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2487
  26. package/src/mcp_server.py +11 -5437
  27. package/src/proxy.py +11 -1834
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +21 -18
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +51 -10
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +729 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/{src → tokensafe}/ingress_staging.py +9 -9
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5668 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/{src → tokensafe}/read_baseline.py +1 -1
  100. package/{src → tokensafe}/repo_compute.py +1 -1
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -0,0 +1,1087 @@
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 (incl. pg_dump output): DDL statements only — INSERT/UPDATE history and
12
+ COPY data are dropped; a target table yields its CREATE TABLE plus its own
13
+ indexes, ALTER TABLE constraints, triggers, owned sequences and comments,
14
+ with referenced types and FK target tables as the 1-hop section.
15
+
16
+ Standard library only. `target` semantics follow the `symbol` argument of
17
+ smart_read_file so agents use one familiar entry point.
18
+ """
19
+
20
+ import json
21
+ import os
22
+ import re
23
+ import hashlib
24
+ import sqlite3
25
+ import time
26
+ import threading
27
+ from collections import OrderedDict
28
+
29
+ from tokensafe.tokenizer import count_tokens
30
+ from tokensafe.paths import resolve_data_dir
31
+ from typing import Any, Dict, List, Optional, Tuple
32
+
33
+ # Bump whenever slicing output changes: it is part of every L1/L2/L3 cache key,
34
+ # so a code change can never serve a slice computed by an older slicer.
35
+ _SLICER_VERSION = "2"
36
+ # Safety cap on the $ref closure (number of distinct referenced components).
37
+ # Cycles are handled by a visited set; this only bounds pathological specs.
38
+ _MAX_REF_CLOSURE = 2000
39
+ # SQL: bytes of source read (COPY data blocks are skipped but still scanned).
40
+ _MAX_SQL_BYTES = 32 * 1024 * 1024
41
+ # OpenAPI JSON detection parses the whole document up to this size.
42
+ _OPENAPI_JSON_PARSE_MAX = 16 * 1024 * 1024
43
+ _HTTP_METHODS = ("get", "post", "put", "patch", "delete", "options", "head", "trace")
44
+
45
+ _OPENAPI_JSON_VERSION_RE = re.compile(rb'"(?:openapi|swagger)"\s*:\s*"?\d')
46
+ _OPENAPI_JSON_BODY_RE = re.compile(rb'"(?:paths|components|definitions)"\s*:\s*\{')
47
+ _OPENAPI_YAML_VERSION_RE = re.compile(r"""^["']?(?:openapi|swagger)["']?[ \t]*:[ \t]*["']?\d""", re.MULTILINE)
48
+ _OPENAPI_YAML_BODY_RE = re.compile(r"""^["']?(?:paths|components|definitions)["']?[ \t]*:""", re.MULTILINE)
49
+ _YAML_REF_RE = re.compile(r"""\$ref["']?\s*:\s*["']?#/([^"'\s,}\]]+)""")
50
+ _SQL_IDENT = r'(?:"(?:[^"]|"")+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*)'
51
+ _SQL_QNAME = _SQL_IDENT + r"(?:\s*\.\s*" + _SQL_IDENT + r"){0,2}"
52
+
53
+
54
+ class SchemaSlicer:
55
+ """Detects schema files and produces targeted, token-cheap slices with L1/L2/L3 caching."""
56
+
57
+ _mem_cache: "OrderedDict[str, Tuple[str, Dict[str, Any]]]" = OrderedDict()
58
+ _mem_lock = threading.Lock()
59
+ _db_init_done = False
60
+ _db_init_lock = threading.Lock()
61
+
62
+ @classmethod
63
+ def clear_memory_cache(cls):
64
+ with cls._mem_lock:
65
+ cls._mem_cache.clear()
66
+
67
+ @classmethod
68
+ def _mem_put(cls, key: str, val: Tuple[str, Dict[str, Any]], max_items: int = 80) -> None:
69
+ """Stores entry in LRU memory cache with fixed cap."""
70
+ with cls._mem_lock:
71
+ cls._mem_cache[key] = val
72
+ cls._mem_cache.move_to_end(key)
73
+ if len(cls._mem_cache) > max_items:
74
+ cls._mem_cache.popitem(last=False)
75
+
76
+ @classmethod
77
+ def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 2000) -> None:
78
+ """Evicts oldest entries when schema cache exceeds max_rows."""
79
+ try:
80
+ row = conn.execute("SELECT COUNT(*) FROM schema_cache;").fetchone()
81
+ count = row[0] if row else 0
82
+ if count > max_rows:
83
+ excess = count - max_rows
84
+ conn.execute(
85
+ "DELETE FROM schema_cache WHERE cache_key IN ("
86
+ "SELECT cache_key FROM schema_cache ORDER BY cached_at ASC LIMIT ?"
87
+ ");", (excess,)
88
+ )
89
+ except Exception:
90
+ pass
91
+
92
+ @classmethod
93
+ def _get_db_path(cls) -> str:
94
+ data_dir = resolve_data_dir()
95
+ os.makedirs(data_dir, exist_ok=True)
96
+ return os.path.join(data_dir, "type_cache.db")
97
+
98
+ @classmethod
99
+ def _init_db(cls):
100
+ db_path = cls._get_db_path()
101
+ with cls._db_init_lock:
102
+ if cls._db_init_done == db_path and os.path.exists(db_path):
103
+ return
104
+ conn = None
105
+ try:
106
+ conn = sqlite3.connect(db_path, timeout=5.0)
107
+ conn.execute("PRAGMA journal_mode=WAL;")
108
+ conn.execute("PRAGMA busy_timeout=5000;")
109
+ conn.execute("""
110
+ CREATE TABLE IF NOT EXISTS schema_cache (
111
+ cache_key TEXT PRIMARY KEY,
112
+ schema_kind TEXT NOT NULL,
113
+ fingerprint TEXT NOT NULL,
114
+ target TEXT NOT NULL,
115
+ sliced_text TEXT NOT NULL,
116
+ info_json TEXT NOT NULL,
117
+ cached_at INTEGER NOT NULL
118
+ );
119
+ """)
120
+ conn.commit()
121
+ cls._db_init_done = db_path
122
+ except Exception:
123
+ pass
124
+ finally:
125
+ if conn:
126
+ try:
127
+ conn.close()
128
+ except Exception:
129
+ pass
130
+
131
+ @classmethod
132
+ def compute_schema_fingerprint(cls, path: str, kind: str) -> str:
133
+ """
134
+ Computes deterministic composite fingerprint:
135
+ - For single file: SHA-256(content)[:16]
136
+ - For multi-file Prisma (prisma/schema/*.prisma): content hashes of all .prisma files
137
+ - For OpenAPI with local $ref: content hashes of root + referenced local files
138
+ """
139
+ abs_p = os.path.abspath(path)
140
+ base_dir = os.path.dirname(abs_p)
141
+
142
+ # Multi-file Prisma check
143
+ if kind == "prisma" and os.path.basename(base_dir).lower() == "schema":
144
+ try:
145
+ prisma_files = sorted([
146
+ os.path.join(base_dir, f) for f in os.listdir(base_dir) if f.endswith(".prisma")
147
+ ])
148
+ if len(prisma_files) > 1:
149
+ hasher = hashlib.sha256()
150
+ for pf in prisma_files:
151
+ with open(pf, "rb") as pff:
152
+ pf_bytes = pff.read()
153
+ pf_hash = hashlib.sha256(pf_bytes).hexdigest()
154
+ hasher.update(f"{os.path.basename(pf)}:{pf_hash}".encode("utf-8"))
155
+ return hasher.hexdigest()[:16]
156
+ except Exception:
157
+ pass
158
+
159
+ # Single file hash or OpenAPI $ref
160
+ try:
161
+ with open(abs_p, "rb") as f:
162
+ content = f.read()
163
+ h = hashlib.sha256(content).hexdigest()[:16]
164
+ if kind == "openapi" and b"$ref" in content:
165
+ ref_matches = re.findall(rb'["\']?\$ref["\']?\s*:\s*["\'](\.[^"\'#]+)', content)
166
+ if ref_matches:
167
+ hasher = hashlib.sha256(content)
168
+ for rm in sorted(set(ref_matches)):
169
+ ref_rel = rm.decode("utf-8", errors="ignore")
170
+ cand = os.path.normpath(os.path.join(base_dir, ref_rel))
171
+ if os.path.isfile(cand):
172
+ try:
173
+ with open(cand, "rb") as cf:
174
+ cand_bytes = cf.read()
175
+ cand_hash = hashlib.sha256(cand_bytes).hexdigest()
176
+ hasher.update(f"{ref_rel}:{cand_hash}".encode("utf-8"))
177
+ except Exception:
178
+ pass
179
+ return hasher.hexdigest()[:16]
180
+ return h
181
+ except Exception:
182
+ return "unknown_fp"
183
+
184
+ @classmethod
185
+ def detect(cls, path: str) -> Optional[str]:
186
+ """Returns the schema kind for `path` (openapi|prisma|graphql|sql) or None."""
187
+ ext = os.path.splitext(path)[1].lower()
188
+ if ext == ".prisma":
189
+ return "prisma"
190
+ if ext in (".graphql", ".gql"):
191
+ return "graphql"
192
+ if ext == ".sql":
193
+ return "sql"
194
+ if ext == ".json":
195
+ try:
196
+ return "openapi" if cls._is_openapi_json(path) else None
197
+ except Exception:
198
+ return None
199
+ if ext in (".yaml", ".yml"):
200
+ try:
201
+ return "openapi" if cls._is_openapi_yaml(path) else None
202
+ except Exception:
203
+ return None
204
+ return None
205
+
206
+ @staticmethod
207
+ def _is_openapi_json(path: str) -> bool:
208
+ """True only for a real OpenAPI/Swagger document.
209
+
210
+ Requires a top-level `openapi`/`swagger` version key plus a top-level
211
+ `paths`, `components` or `definitions` object. A nested `paths` key
212
+ (tsconfig.json `compilerOptions.paths`) or an `openapi` npm script does
213
+ not qualify.
214
+ """
215
+ size = os.path.getsize(path)
216
+ with open(path, "rb") as f:
217
+ data = f.read(min(size, _OPENAPI_JSON_PARSE_MAX))
218
+ if not _OPENAPI_JSON_VERSION_RE.search(data):
219
+ return False # cheap rejection for package.json, tsconfig.json, lockfiles...
220
+ if size > _OPENAPI_JSON_PARSE_MAX:
221
+ # Too large to parse on every read: version marker plus a body object is
222
+ # the best cheap evidence; nested-key false positives are not plausible
223
+ # at this size together with a version-valued `openapi`/`swagger` key.
224
+ return bool(_OPENAPI_JSON_BODY_RE.search(data))
225
+ try:
226
+ doc = json.loads(data.decode("utf-8-sig", errors="replace"))
227
+ except ValueError:
228
+ return False
229
+ if not isinstance(doc, dict):
230
+ return False
231
+ version = doc.get("openapi", doc.get("swagger"))
232
+ if not isinstance(version, (str, int, float)) or isinstance(version, bool):
233
+ return False
234
+ if not re.match(r"\d", str(version)):
235
+ return False
236
+ return any(isinstance(doc.get(k), dict) for k in ("paths", "components", "definitions"))
237
+
238
+ @staticmethod
239
+ def _is_openapi_yaml(path: str) -> bool:
240
+ """True only when `openapi:`/`swagger:` and `paths:`/`components:`/`definitions:`
241
+ are top-level (column 0) keys; an indented `swagger:` service or option does not count."""
242
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
243
+ text = f.read(_OPENAPI_JSON_PARSE_MAX)
244
+ return bool(_OPENAPI_YAML_VERSION_RE.search(text) and _OPENAPI_YAML_BODY_RE.search(text))
245
+
246
+ @classmethod
247
+ def slice_file(cls, path: str, target: str = "") -> Tuple[str, Dict[str, Any]]:
248
+ """Returns (sliced_text, info). Empty `target` yields a compact overview with L1/L2/L3 caching."""
249
+ kind = cls.detect(path)
250
+ if not kind:
251
+ return "", {"kind": None}
252
+
253
+ # 1. Compute composite fingerprint and case-preserving cache key
254
+ norm_target = target.strip()
255
+ fp = cls.compute_schema_fingerprint(path, kind)
256
+ cache_key = f"v{_SLICER_VERSION}::{kind}::{fp}::{norm_target}"
257
+
258
+ # 2. Check L1 Memory
259
+ with cls._mem_lock:
260
+ if cache_key in cls._mem_cache:
261
+ cls._mem_cache.move_to_end(cache_key)
262
+ hit_text, hit_info = cls._mem_cache[cache_key]
263
+ hit_info = dict(hit_info)
264
+ hit_info["source"] = "L1_memory"
265
+ return hit_text, hit_info
266
+
267
+ # 3. Check L2 SQLite
268
+ cls._init_db()
269
+ db_path = cls._get_db_path()
270
+ l2_conn = None
271
+ try:
272
+ l2_conn = sqlite3.connect(db_path, timeout=5.0)
273
+ l2_conn.execute("PRAGMA busy_timeout=5000;")
274
+ row = l2_conn.execute(
275
+ "SELECT sliced_text, info_json FROM schema_cache WHERE cache_key = ?",
276
+ (cache_key,)
277
+ ).fetchone()
278
+ if row:
279
+ text_cached, info_raw = row[0], row[1]
280
+ info_dict = json.loads(info_raw)
281
+ info_dict["source"] = "L2_sqlite"
282
+ cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
283
+ return text_cached, info_dict
284
+ except Exception:
285
+ pass
286
+ finally:
287
+ if l2_conn:
288
+ try:
289
+ l2_conn.close()
290
+ except Exception:
291
+ pass
292
+
293
+ # 4. Check L3 Team Sync
294
+ try:
295
+ from tokensafe.team_cache import TeamCache
296
+ team_val = TeamCache.get("SCHEMA_CONTRACTS", cache_key, timeout=0.5)
297
+ if team_val:
298
+ parsed_team = json.loads(team_val)
299
+ text_cached = parsed_team.get("sliced", "")
300
+ info_dict = parsed_team.get("info", {})
301
+ info_dict["source"] = "L3_team_cache"
302
+ cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
303
+ # Store back to L2
304
+ back_conn = None
305
+ try:
306
+ back_conn = sqlite3.connect(db_path, timeout=5.0)
307
+ back_conn.execute("""
308
+ INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
309
+ VALUES (?, ?, ?, ?, ?, ?, ?)
310
+ """, (cache_key, kind, fp, norm_target, text_cached, json.dumps(info_dict), int(time.time())))
311
+ cls._maybe_evict(back_conn)
312
+ back_conn.commit()
313
+ except Exception:
314
+ pass
315
+ finally:
316
+ if back_conn:
317
+ try:
318
+ back_conn.close()
319
+ except Exception:
320
+ pass
321
+ return text_cached, info_dict
322
+ except Exception:
323
+ pass
324
+
325
+ # 5. Compute fresh slice
326
+ raw_text = ""
327
+ try:
328
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
329
+ raw_text = f.read()
330
+ except OSError:
331
+ pass
332
+
333
+ sliced = ""
334
+ if kind == "openapi":
335
+ sliced, info = cls._slice_openapi(path, target.strip())
336
+ elif kind == "prisma":
337
+ sliced, info = cls._slice_prisma(path, target.strip())
338
+ elif kind == "graphql":
339
+ sliced, info = cls._slice_graphql(path, target.strip())
340
+ elif kind == "sql":
341
+ sliced, info = cls._slice_sql(path, target.strip())
342
+ else:
343
+ return "", {"kind": None}
344
+
345
+ if not target.strip() and count_tokens(sliced) >= count_tokens(raw_text):
346
+ return raw_text, info
347
+
348
+ if info.get("error") or info.get("mode") == "missing":
349
+ return sliced, info
350
+
351
+ # 6. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
352
+ info["source"] = "parsed_live"
353
+ cls._mem_put(cache_key, (sliced, info), max_items=80)
354
+
355
+ save_conn = None
356
+ try:
357
+ save_conn = sqlite3.connect(db_path, timeout=5.0)
358
+ save_conn.execute("""
359
+ INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
360
+ VALUES (?, ?, ?, ?, ?, ?, ?)
361
+ """, (cache_key, kind, fp, norm_target, sliced, json.dumps(info), int(time.time())))
362
+ cls._maybe_evict(save_conn)
363
+ save_conn.commit()
364
+ except Exception:
365
+ pass
366
+ finally:
367
+ if save_conn:
368
+ try:
369
+ save_conn.close()
370
+ except Exception:
371
+ pass
372
+
373
+ try:
374
+ from tokensafe.team_cache import TeamCache
375
+ payload = json.dumps({"sliced": sliced, "info": info}, ensure_ascii=False)
376
+ TeamCache.put("SCHEMA_CONTRACTS", cache_key, payload, tokens_saved=max(40, count_tokens(raw_text) - count_tokens(sliced)))
377
+ except Exception:
378
+ pass
379
+
380
+ return sliced, info
381
+
382
+ # ------------------------------------------------------------------ OpenAPI
383
+
384
+ @staticmethod
385
+ def _decode_pointer_token(tok: str) -> str:
386
+ from urllib.parse import unquote
387
+ return unquote(tok).replace("~1", "/").replace("~0", "~")
388
+
389
+ @classmethod
390
+ def _pointer_parts(cls, pointer: str) -> List[str]:
391
+ return [cls._decode_pointer_token(p) for p in pointer.split("/") if p != ""]
392
+
393
+ @classmethod
394
+ def _ref_key(cls, pointer: str) -> str:
395
+ """'components/schemas/User' and 'definitions/User' -> 'User'; any other
396
+ component keeps its kind so names cannot collide ('responses/NotFound')."""
397
+ parts = cls._pointer_parts(pointer)
398
+ if len(parts) == 3 and parts[0] == "components" and parts[1] == "schemas":
399
+ return parts[2]
400
+ if len(parts) == 2 and parts[0] == "definitions":
401
+ return parts[1]
402
+ if parts and parts[0] == "components":
403
+ parts = parts[1:]
404
+ return "/".join(parts)
405
+
406
+ @classmethod
407
+ def _resolve_json_pointer(cls, doc: Any, pointer: str) -> Any:
408
+ node = doc
409
+ for part in cls._pointer_parts(pointer):
410
+ if isinstance(node, dict) and part in node:
411
+ node = node[part]
412
+ elif isinstance(node, list) and part.isdigit() and int(part) < len(node):
413
+ node = node[int(part)]
414
+ else:
415
+ return None
416
+ return node
417
+
418
+ @classmethod
419
+ def _json_ref_closure(cls, spec: Dict[str, Any], root: Any) -> Tuple[Dict[str, Any], bool]:
420
+ """Full transitive closure of local `#/...` $refs reachable from `root`.
421
+
422
+ Iterative walk with a visited set (cycles terminate) and a generous size
423
+ cap; there is no depth limit, so deep chains A -> B -> C -> ... resolve.
424
+ Returns (closure, truncated).
425
+ """
426
+ acc: Dict[str, Any] = {}
427
+ seen = set()
428
+ stack: List[Any] = [root]
429
+ while stack:
430
+ node = stack.pop()
431
+ if isinstance(node, dict):
432
+ ref = node.get("$ref")
433
+ if isinstance(ref, str) and ref.startswith("#/"):
434
+ pointer = ref[2:]
435
+ if pointer not in seen:
436
+ seen.add(pointer)
437
+ resolved = cls._resolve_json_pointer(spec, pointer)
438
+ if resolved is not None:
439
+ if len(acc) >= _MAX_REF_CLOSURE:
440
+ return acc, True
441
+ acc[cls._ref_key(pointer)] = resolved
442
+ stack.append(resolved)
443
+ stack.extend(reversed(list(node.values())))
444
+ elif isinstance(node, list):
445
+ stack.extend(reversed(node))
446
+ return acc, False
447
+
448
+ @staticmethod
449
+ def _split_method_target(target: str) -> Optional[Tuple[str, str]]:
450
+ """'/users get' or '/users:get' -> ('/users', 'get'); anything else -> None."""
451
+ parts = re.split(r"[\s:]+", target, maxsplit=1)
452
+ if len(parts) == 2 and parts[0].startswith("/") and parts[1].lower() in _HTTP_METHODS:
453
+ return parts[0], parts[1].lower()
454
+ return None
455
+
456
+ @staticmethod
457
+ def _closure_info(info: Dict[str, Any], refs: List[str], truncated: bool) -> Dict[str, Any]:
458
+ info["refs"] = refs
459
+ if truncated:
460
+ info["truncated"] = True
461
+ return info
462
+
463
+ @classmethod
464
+ def _slice_openapi(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
465
+ ext = os.path.splitext(path)[1].lower()
466
+ if ext in (".yaml", ".yml"):
467
+ return cls._slice_openapi_yaml(path, target)
468
+ try:
469
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
470
+ spec = json.load(f)
471
+ except Exception as e:
472
+ return f"[TokenSafe SchemaSlicer] Cannot parse OpenAPI JSON: {e}", {"kind": "openapi", "error": True}
473
+ if not isinstance(spec, dict):
474
+ return "[TokenSafe SchemaSlicer] OpenAPI document is not a JSON object", {"kind": "openapi", "error": True}
475
+
476
+ def schema_pool() -> Dict[str, Any]:
477
+ comps = spec.get("components") or {}
478
+ return (comps.get("schemas") or {}) or (spec.get("definitions") or {})
479
+
480
+ def closure_lines(root: Any, exclude: Optional[str] = None) -> Tuple[List[str], List[str], bool]:
481
+ acc, truncated = cls._json_ref_closure(spec, root)
482
+ if exclude is not None:
483
+ acc.pop(exclude, None)
484
+ lines: List[str] = []
485
+ if acc:
486
+ lines.append("\n# Referenced schemas ($ref closure)")
487
+ lines.append(json.dumps(acc, indent=2, ensure_ascii=False))
488
+ if truncated:
489
+ lines.append(f"# ($ref closure truncated at {_MAX_REF_CLOSURE} components)")
490
+ return lines, list(acc), truncated
491
+
492
+ paths = spec.get("paths") or {}
493
+ if not isinstance(paths, dict):
494
+ paths = {}
495
+
496
+ # Method-scoped path FIRST (e.g. "/users get" or "/users:get"), before plain target.startswith("/")
497
+ if target:
498
+ split = cls._split_method_target(target)
499
+ if split:
500
+ p, method = split
501
+ item = paths.get(p) or {}
502
+ op = item.get(method) if isinstance(item, dict) else None
503
+ if op is not None:
504
+ extra, refs, truncated = closure_lines(op)
505
+ out = [f"# OpenAPI operation: {method.upper()} {p}",
506
+ json.dumps({method: op}, indent=2, ensure_ascii=False)] + extra
507
+ return "\n".join(out), cls._closure_info({"kind": "openapi", "mode": "operation"}, refs, truncated)
508
+ return cls._openapi_overview(spec, missing=target)
509
+
510
+ if target.startswith("/"):
511
+ item = paths.get(target)
512
+ if item is None:
513
+ return cls._openapi_overview(spec, missing=target)
514
+ extra, refs, truncated = closure_lines(item)
515
+ out = [f"# OpenAPI path: {target}", json.dumps({target: item}, indent=2, ensure_ascii=False)] + extra
516
+ return "\n".join(out), cls._closure_info({"kind": "openapi", "mode": "path"}, refs, truncated)
517
+ if target:
518
+ pool = schema_pool()
519
+ if target in pool:
520
+ extra, refs, truncated = closure_lines(pool[target], exclude=target)
521
+ body = {"name": target, **(pool[target] if isinstance(pool[target], dict) else {"schema": pool[target]})}
522
+ out = [f"# OpenAPI schema: {target}", json.dumps(body, indent=2, ensure_ascii=False)] + extra
523
+ return "\n".join(out), cls._closure_info({"kind": "openapi", "mode": "schema"}, refs, truncated)
524
+ return cls._openapi_overview(spec, missing=target)
525
+ return cls._openapi_overview(spec)
526
+
527
+ @classmethod
528
+ def _openapi_overview(cls, spec: Dict[str, Any], missing: str = "") -> Tuple[str, Dict[str, Any]]:
529
+ lines = [f"# OpenAPI {spec.get('openapi') or spec.get('swagger') or ''} — overview"]
530
+ if missing:
531
+ lines.append(f"# (target '{missing}' not found — showing the spec index)")
532
+ paths = spec.get("paths") or {}
533
+ lines.append(f"\n## Paths ({len(paths)})")
534
+ for p, item in list(paths.items())[:120]:
535
+ methods = [m.upper() for m in (item or {}) if m in _HTTP_METHODS]
536
+ lines.append(f" {'/'.join(methods) or '-'} {p}")
537
+ pool = (spec.get("components") or {}).get("schemas") or spec.get("definitions") or {}
538
+ names = list(pool.keys())
539
+ lines.append(f"\n## Schemas ({len(names)})")
540
+ lines.append(" " + ", ".join(names[:150]))
541
+ lines.append("\nSlice a specific entry: symbol='/users/{id}' (path), '/users get' (operation) or 'User' (schema).")
542
+ return "\n".join(lines), {"kind": "openapi", "mode": "overview"}
543
+
544
+ # Mapping key at the start of a YAML line: quoted or plain, followed by ':' + space/EOL.
545
+ _YAML_KEY_RE = re.compile(
546
+ r"""^[ ]*(?:"((?:[^"\\]|\\.)*)"|'((?:[^']|'')*)'|([^\s#'"\-\[{][^#]*?|-[^\s#][^#]*?))[ \t]*:(?:[ \t]|$)"""
547
+ )
548
+
549
+ @classmethod
550
+ def _yaml_children(cls, lines: List[str], start: int, end: int) -> "OrderedDict[str, Tuple[int, int]]":
551
+ """Mapping keys exactly one indentation level inside lines[start:end].
552
+
553
+ Returns key -> (first_line, end_line) where the block runs up to the next
554
+ sibling key. Indentation-based (YAML forbids tabs for indentation), so it
555
+ needs no YAML library and tolerates block scalars and flow values.
556
+ """
557
+ children: "OrderedDict[str, Tuple[int, int]]" = OrderedDict()
558
+ child_indent: Optional[int] = None
559
+ cur_key: Optional[str] = None
560
+ cur_start = start
561
+ stop = end
562
+ for i in range(start, end):
563
+ ln = lines[i]
564
+ st = ln.strip()
565
+ if not st or st.startswith("#"):
566
+ continue
567
+ ind = len(ln) - len(ln.lstrip(" "))
568
+ if ind == 0 and (st.startswith("---") or st.startswith("...") or st.startswith("%")):
569
+ continue
570
+ if child_indent is None:
571
+ child_indent = ind
572
+ if ind < child_indent:
573
+ stop = i
574
+ break
575
+ if ind != child_indent:
576
+ continue
577
+ m = cls._YAML_KEY_RE.match(ln)
578
+ if not m:
579
+ continue
580
+ if m.group(1) is not None:
581
+ key = m.group(1)
582
+ elif m.group(2) is not None:
583
+ key = m.group(2).replace("''", "'")
584
+ else:
585
+ key = m.group(3).strip()
586
+ if cur_key is not None:
587
+ children[cur_key] = (cur_start, i)
588
+ cur_key, cur_start = key, i
589
+ if cur_key is not None:
590
+ children[cur_key] = (cur_start, stop)
591
+ return children
592
+
593
+ @classmethod
594
+ def _slice_openapi_yaml(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
595
+ import textwrap
596
+
597
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
598
+ lines = f.read().splitlines()
599
+ kids_cache: Dict[Tuple[int, int], "OrderedDict[str, Tuple[int, int]]"] = {}
600
+
601
+ def kids(block: Optional[Tuple[int, int]]) -> "OrderedDict[str, Tuple[int, int]]":
602
+ rng = (0, len(lines)) if block is None else (block[0] + 1, block[1])
603
+ if rng not in kids_cache:
604
+ kids_cache[rng] = cls._yaml_children(lines, rng[0], rng[1])
605
+ return kids_cache[rng]
606
+
607
+ def text(block: Tuple[int, int]) -> str:
608
+ return textwrap.dedent("\n".join(lines[block[0]:block[1]])).rstrip()
609
+
610
+ def resolve(pointer: str) -> Optional[Tuple[int, int]]:
611
+ block: Optional[Tuple[int, int]] = None
612
+ for part in cls._pointer_parts(pointer):
613
+ block = kids(block).get(part)
614
+ if block is None:
615
+ return None
616
+ return block
617
+
618
+ top = kids(None)
619
+ paths = kids(top["paths"]) if "paths" in top else OrderedDict()
620
+ comps = kids(top["components"]) if "components" in top else OrderedDict()
621
+ if "schemas" in comps:
622
+ schemas = kids(comps["schemas"])
623
+ elif "definitions" in top:
624
+ schemas = kids(top["definitions"])
625
+ else:
626
+ schemas = OrderedDict()
627
+
628
+ def closure_lines(root_text: str, exclude: Optional[str] = None) -> Tuple[List[str], List[str], bool]:
629
+ """Same transitive $ref closure as the JSON path: visited set + size cap, no depth limit."""
630
+ acc: "OrderedDict[str, str]" = OrderedDict()
631
+ seen = set()
632
+ queue = [root_text]
633
+ truncated = False
634
+ while queue and not truncated:
635
+ for m in _YAML_REF_RE.finditer(queue.pop(0)):
636
+ pointer = m.group(1)
637
+ if pointer in seen:
638
+ continue
639
+ seen.add(pointer)
640
+ blk = resolve(pointer)
641
+ if blk is None:
642
+ continue
643
+ if len(acc) >= _MAX_REF_CLOSURE:
644
+ truncated = True
645
+ break
646
+ body = text(blk)
647
+ acc[cls._ref_key(pointer)] = body
648
+ queue.append(body)
649
+ if exclude is not None:
650
+ acc.pop(exclude, None)
651
+ out: List[str] = []
652
+ if acc:
653
+ out.append("\n# Referenced schemas ($ref closure)")
654
+ out.extend(acc.values())
655
+ if truncated:
656
+ out.append(f"# ($ref closure truncated at {_MAX_REF_CLOSURE} components)")
657
+ return out, list(acc), truncated
658
+
659
+ def index_lines() -> List[str]:
660
+ out = [f"## Paths ({len(paths)})"]
661
+ for p, blk in list(paths.items())[:120]:
662
+ methods = [m.upper() for m in kids(blk) if m.lower() in _HTTP_METHODS]
663
+ out.append(f" {'/'.join(methods) or '-'} {p}")
664
+ out.append(f"\n## Schemas ({len(schemas)})")
665
+ out.append(" " + ", ".join(list(schemas)[:150]))
666
+ return out
667
+
668
+ if not target:
669
+ out = ["# OpenAPI (YAML) — overview", ""] + index_lines()
670
+ out.append("\nSlice a specific entry: symbol='/users/{id}' (path), '/users get' (operation) or 'User' (schema).")
671
+ return "\n".join(out), {"kind": "openapi", "mode": "overview"}
672
+
673
+ def missing() -> Tuple[str, Dict[str, Any]]:
674
+ return "\n".join([f"# target '{target}' not found"] + index_lines()), {"kind": "openapi", "mode": "missing"}
675
+
676
+ split = cls._split_method_target(target)
677
+ if split:
678
+ p, method = split
679
+ item = paths.get(p)
680
+ op = next((b for k, b in kids(item).items() if k.lower() == method), None) if item else None
681
+ if op is None:
682
+ return missing()
683
+ body = text(op)
684
+ extra, refs, truncated = closure_lines(body)
685
+ out = [f"# OpenAPI operation: {method.upper()} {p}", body] + extra
686
+ return "\n".join(out), cls._closure_info({"kind": "openapi", "mode": "operation"}, refs, truncated)
687
+
688
+ if not target.startswith("/") and target in schemas:
689
+ body = text(schemas[target])
690
+ extra, refs, truncated = closure_lines(body, exclude=target)
691
+ out = [f"# OpenAPI schema: {target}", body] + extra
692
+ return "\n".join(out), cls._closure_info({"kind": "openapi", "mode": "schema"}, refs, truncated)
693
+
694
+ norm = target if target.startswith("/") else "/" + target
695
+ blk = paths.get(norm) or paths.get(target.rstrip(":"))
696
+ if not blk:
697
+ return missing()
698
+ body = text(blk)
699
+ extra, refs, truncated = closure_lines(body)
700
+ out = [f"# OpenAPI path: {norm}", body] + extra
701
+ return "\n".join(out), cls._closure_info({"kind": "openapi", "mode": "path"}, refs, truncated)
702
+
703
+ # ------------------------------------------------------------------ Prisma
704
+
705
+ @classmethod
706
+ def _slice_prisma(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
707
+ abs_p = os.path.abspath(path)
708
+ base_dir = os.path.dirname(abs_p)
709
+ if os.path.basename(base_dir).lower() == "schema":
710
+ try:
711
+ prisma_files = sorted(
712
+ os.path.join(base_dir, f) for f in os.listdir(base_dir) if f.endswith(".prisma")
713
+ )
714
+ except OSError:
715
+ prisma_files = [abs_p]
716
+ if not prisma_files:
717
+ prisma_files = [abs_p]
718
+ else:
719
+ prisma_files = [abs_p]
720
+ src_parts = []
721
+ for pf in prisma_files:
722
+ with open(pf, "r", encoding="utf-8", errors="replace") as f:
723
+ src_parts.append(f.read())
724
+ src = "\n\n".join(src_parts)
725
+ block_re = re.compile(r"^(model|enum|type)\s+(\w+)\s*\{(.*?)^\}", re.MULTILINE | re.DOTALL)
726
+ blocks: Dict[str, Tuple[str, str]] = {}
727
+ order: List[str] = []
728
+ for m in block_re.finditer(src):
729
+ name = m.group(2)
730
+ blocks[name] = (m.group(1), m.group(0))
731
+ order.append(name)
732
+ if not target:
733
+ lines = [f"# Prisma schema — overview ({len(blocks)} definitions)", ""]
734
+ for name in order[:150]:
735
+ kind_name, body = blocks[name]
736
+ fields = len(re.findall(r"^\s{2,}\w+", body, re.MULTILINE))
737
+ lines.append(f" {kind_name} {name} ({fields} fields)")
738
+ lines.append("\nSlice a model: symbol='User'.")
739
+ return "\n".join(lines), {"kind": "prisma", "mode": "overview"}
740
+ if target not in blocks:
741
+ return f"# target '{target}' not found. Definitions: {', '.join(order[:100])}", {"kind": "prisma", "mode": "missing"}
742
+ kind_name, body = blocks[target]
743
+ out = [f"# Prisma {kind_name} {target}", body]
744
+ # 1-hop: capitalized field types that are themselves defined blocks
745
+ refs = set()
746
+ for fm in re.finditer(r"^\s{2,}\w+\s+([A-Z]\w*)(?:\?|\[\])?(?:\s|$)", body, re.MULTILINE):
747
+ if fm.group(1) in blocks and fm.group(1) != target:
748
+ refs.add(fm.group(1))
749
+ if refs:
750
+ out.append("\n# 1-hop related definitions")
751
+ for r in sorted(refs):
752
+ out.append(blocks[r][1])
753
+ return "\n".join(out), {"kind": "prisma", "mode": "model", "refs": sorted(refs)}
754
+
755
+ # ------------------------------------------------------------------ GraphQL
756
+
757
+ @classmethod
758
+ def _slice_graphql(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
759
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
760
+ src = f.read()
761
+ src = re.sub(r'"""[\s\S]*?"""', '""', src) # drop block descriptions for overview scanning
762
+ block_re = re.compile(r"^(type|input|interface|enum)\s+(\w+)([^{}]*?)\{(.*?)\}", re.MULTILINE | re.DOTALL)
763
+ blocks: Dict[str, Tuple[str, str]] = {}
764
+ order: List[str] = []
765
+ for m in block_re.finditer(src):
766
+ name = m.group(2)
767
+ blocks[name] = (m.group(1), m.group(0))
768
+ order.append(name)
769
+ for m in re.finditer(r"^(scalar|union)\s+(\w+)([^\n]*)", src, re.MULTILINE):
770
+ name = m.group(2)
771
+ if name not in blocks:
772
+ blocks[name] = (m.group(1), m.group(0).strip())
773
+ order.append(name)
774
+ if not target:
775
+ lines = [f"# GraphQL SDL — overview ({len(blocks)} definitions)", ""]
776
+ for name in order[:150]:
777
+ kind_name, _ = blocks[name]
778
+ lines.append(f" {kind_name} {name}")
779
+ lines.append("\nSlice a type: symbol='User'.")
780
+ return "\n".join(lines), {"kind": "graphql", "mode": "overview"}
781
+ if target not in blocks:
782
+ return f"# target '{target}' not found. Definitions: {', '.join(order[:100])}", {"kind": "graphql", "mode": "missing"}
783
+ kind_name, body = blocks[target]
784
+ out = [f"# GraphQL {kind_name} {target}", body]
785
+ refs = set()
786
+ for fm in re.finditer(r":\s*\[?([A-Z]\w*)[!\]]*(?:\s|$)", body):
787
+ if fm.group(1) in blocks and fm.group(1) != target:
788
+ refs.add(fm.group(1))
789
+ if refs:
790
+ out.append("\n# 1-hop related types")
791
+ for r in sorted(refs):
792
+ out.append(blocks[r][1])
793
+ return "\n".join(out), {"kind": "graphql", "mode": "type", "refs": sorted(refs)}
794
+
795
+ # ------------------------------------------------------------------ SQL
796
+
797
+ # Kept for compatibility: statements whose head marks them as schema DDL.
798
+ _SQL_DDL_RE = re.compile(
799
+ r"^\s*(?:CREATE|ALTER|COMMENT\s+ON)\b",
800
+ re.IGNORECASE,
801
+ )
802
+ # Lexer hot spots: comments, quoted strings/identifiers, statement ends, $tag$ quotes.
803
+ _SQL_TOKEN_RE = re.compile(r"""--|/\*|'|"|;|\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$""")
804
+ _SQL_COPY_STDIN_RE = re.compile(r"^COPY\b[\s\S]*\bFROM\s+STDIN\b", re.IGNORECASE)
805
+ _SQL_COPY_END_RE = re.compile(r"^\\\.[ \t\r]*$", re.MULTILINE)
806
+ _SQL_OWNER_ONLY_RE = re.compile(r"^ALTER\b[\s\S]*\bOWNER\s+TO\s+\S+\s*$", re.IGNORECASE)
807
+
808
+ _SQL_CLASSIFIERS = [
809
+ ("table", re.compile(
810
+ rf"^CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+|FOREIGN\s+)?"
811
+ rf"TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?P<name>{_SQL_QNAME})", re.IGNORECASE)),
812
+ ("view", re.compile(
813
+ rf"^CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMP(?:ORARY)?\s+)?(?:RECURSIVE\s+)?(?:MATERIALIZED\s+)?"
814
+ rf"VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?(?P<name>{_SQL_QNAME})", re.IGNORECASE)),
815
+ ("index", re.compile(
816
+ rf"^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:(?:IF\s+NOT\s+EXISTS\s+)?(?P<name>{_SQL_QNAME})\s+)?"
817
+ rf"ON\s+(?:ONLY\s+)?(?P<table>{_SQL_QNAME})", re.IGNORECASE)),
818
+ ("sequence", re.compile(
819
+ rf"^CREATE\s+(?:(?:TEMP(?:ORARY)?|UNLOGGED)\s+)?SEQUENCE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?P<name>{_SQL_QNAME})",
820
+ re.IGNORECASE)),
821
+ ("sequence_owner", re.compile(
822
+ rf"^ALTER\s+SEQUENCE\s+(?:IF\s+EXISTS\s+)?(?P<name>{_SQL_QNAME})[\s\S]*?\bOWNED\s+BY\s+(?P<column>{_SQL_QNAME})",
823
+ re.IGNORECASE)),
824
+ ("alter_table", re.compile(
825
+ rf"^ALTER\s+(?:FOREIGN\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(?P<table>{_SQL_QNAME})", re.IGNORECASE)),
826
+ ("type", re.compile(rf"^CREATE\s+TYPE\s+(?P<name>{_SQL_QNAME})", re.IGNORECASE)),
827
+ ("domain", re.compile(rf"^CREATE\s+DOMAIN\s+(?P<name>{_SQL_QNAME})", re.IGNORECASE)),
828
+ ("function", re.compile(
829
+ rf"^CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE|AGGREGATE)\s+(?P<name>{_SQL_QNAME})", re.IGNORECASE)),
830
+ ("trigger", re.compile(
831
+ rf"^CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+(?P<name>{_SQL_IDENT})[\s\S]*?"
832
+ rf"\bON\s+(?:ONLY\s+)?(?P<table>{_SQL_QNAME})", re.IGNORECASE)),
833
+ ("policy", re.compile(
834
+ rf"^CREATE\s+POLICY\s+(?P<name>{_SQL_IDENT})\s+ON\s+(?P<table>{_SQL_QNAME})", re.IGNORECASE)),
835
+ ("rule", re.compile(
836
+ rf"^CREATE\s+(?:OR\s+REPLACE\s+)?RULE\s+(?P<name>{_SQL_IDENT})[\s\S]*?\bTO\s+(?P<table>{_SQL_QNAME})",
837
+ re.IGNORECASE)),
838
+ ("comment", re.compile(
839
+ rf"^COMMENT\s+ON\s+(?:TABLE|VIEW|MATERIALIZED\s+VIEW|FOREIGN\s+TABLE)\s+(?P<table>{_SQL_QNAME})", re.IGNORECASE)),
840
+ ("comment", re.compile(rf"^COMMENT\s+ON\s+COLUMN\s+(?P<column>{_SQL_QNAME})", re.IGNORECASE)),
841
+ ("schema", re.compile(rf"^CREATE\s+SCHEMA\s+(?:IF\s+NOT\s+EXISTS\s+)?(?P<name>{_SQL_IDENT})", re.IGNORECASE)),
842
+ ("ddl", re.compile(r"^(?:CREATE|ALTER)\b", re.IGNORECASE)),
843
+ ]
844
+ _SQL_REFERENCES_RE = re.compile(rf"\bREFERENCES\s+(?:ONLY\s+)?(?P<table>{_SQL_QNAME})", re.IGNORECASE)
845
+
846
+ @staticmethod
847
+ def _strip_sql_leading_noise(stmt: str) -> str:
848
+ """Drops leading comments (pg_dump '--' headers, /* */) and psql meta-command lines."""
849
+ s = stmt
850
+ while True:
851
+ s = s.lstrip()
852
+ if s.startswith("--") or s.startswith("\\"):
853
+ nl = s.find("\n")
854
+ s = "" if nl < 0 else s[nl + 1:]
855
+ elif s.startswith("/*"):
856
+ e = s.find("*/")
857
+ s = "" if e < 0 else s[e + 2:]
858
+ else:
859
+ return s.rstrip()
860
+
861
+ @classmethod
862
+ def _iter_sql_statements(cls, src: str):
863
+ """Yields statements split on top-level ';'.
864
+
865
+ Semicolons inside '...' / E'...' strings, "quoted" identifiers, -- and
866
+ /* nested */ comments and $$ / $tag$ dollar-quoted bodies do not split.
867
+ After `COPY ... FROM stdin;` the inline data block up to the `\\.` line is
868
+ skipped, so row data can never be mistaken for SQL.
869
+ """
870
+ n = len(src)
871
+ pos = start = 0
872
+ while pos < n:
873
+ m = cls._SQL_TOKEN_RE.search(src, pos)
874
+ if not m:
875
+ break
876
+ tok, i = m.group(0), m.start()
877
+ if tok == "--":
878
+ nl = src.find("\n", i)
879
+ pos = n if nl < 0 else nl + 1
880
+ elif tok == "/*":
881
+ depth, j = 1, i + 2
882
+ while depth and j < n:
883
+ a, b = src.find("/*", j), src.find("*/", j)
884
+ if b < 0:
885
+ j = n
886
+ break
887
+ if 0 <= a < b:
888
+ depth, j = depth + 1, a + 2
889
+ else:
890
+ depth, j = depth - 1, b + 2
891
+ pos = j
892
+ elif tok == "'":
893
+ backslash = i > 0 and src[i - 1] in "eE" and not (i > 1 and (src[i - 2].isalnum() or src[i - 2] == "_"))
894
+ j = i + 1
895
+ while True:
896
+ k = src.find("'", j)
897
+ if k < 0:
898
+ j = n
899
+ break
900
+ if backslash:
901
+ bs, t = 0, k - 1
902
+ while t > i and src[t] == "\\":
903
+ bs, t = bs + 1, t - 1
904
+ if bs % 2:
905
+ j = k + 1
906
+ continue
907
+ if src.startswith("'", k + 1):
908
+ j = k + 2
909
+ continue
910
+ j = k + 1
911
+ break
912
+ pos = j
913
+ elif tok == '"':
914
+ j = i + 1
915
+ while True:
916
+ k = src.find('"', j)
917
+ if k < 0:
918
+ j = n
919
+ break
920
+ if src.startswith('"', k + 1):
921
+ j = k + 2
922
+ continue
923
+ j = k + 1
924
+ break
925
+ pos = j
926
+ elif tok == ";":
927
+ stmt = cls._strip_sql_leading_noise(src[start:i])
928
+ pos = i + 1
929
+ if stmt:
930
+ if cls._SQL_COPY_STDIN_RE.match(stmt):
931
+ end = cls._SQL_COPY_END_RE.search(src, pos)
932
+ pos = n if end is None else end.end()
933
+ yield stmt
934
+ start = pos
935
+ else: # $$ or $tag$
936
+ if i > 0 and (src[i - 1].isalnum() or src[i - 1] == "_"):
937
+ pos = i + 1 # `$` inside an identifier (foo$bar), not a quote
938
+ continue
939
+ close = src.find(tok, m.end())
940
+ pos = n if close < 0 else close + len(tok)
941
+ tail = cls._strip_sql_leading_noise(src[start:])
942
+ if tail:
943
+ yield tail
944
+
945
+ @staticmethod
946
+ def _sql_name_parts(qname: Optional[str]) -> Tuple[str, ...]:
947
+ """'"public"."Users"' / public.users / `users` -> ('public', 'users'), case-folded."""
948
+ if not qname:
949
+ return ()
950
+ out = []
951
+ for p in re.findall(_SQL_IDENT, qname):
952
+ if p[0] == '"':
953
+ p = p[1:-1].replace('""', '"')
954
+ elif p[0] in "`[":
955
+ p = p[1:-1]
956
+ out.append(p.lower())
957
+ return tuple(out)
958
+
959
+ @staticmethod
960
+ def _sql_display(qname: str) -> str:
961
+ parts = []
962
+ for p in re.findall(_SQL_IDENT, qname):
963
+ if p[0] == '"':
964
+ p = p[1:-1].replace('""', '"')
965
+ elif p[0] in "`[":
966
+ p = p[1:-1]
967
+ parts.append(p)
968
+ return ".".join(parts)
969
+
970
+ @staticmethod
971
+ def _sql_suffix_match(obj: Tuple[str, ...], tgt: Tuple[str, ...]) -> bool:
972
+ return bool(obj) and bool(tgt) and len(tgt) <= len(obj) and obj[-len(tgt):] == tgt
973
+
974
+ @classmethod
975
+ def _classify_sql(cls, stmt: str) -> Optional[Dict[str, Any]]:
976
+ if not cls._SQL_DDL_RE.match(stmt):
977
+ return None
978
+ if cls._SQL_OWNER_ONLY_RE.match(stmt):
979
+ return None # pg_dump `ALTER ... OWNER TO role` noise
980
+ for kind, rx in cls._SQL_CLASSIFIERS:
981
+ m = rx.match(stmt)
982
+ if not m:
983
+ continue
984
+ g = m.groupdict()
985
+ entry: Dict[str, Any] = {"kind": kind, "text": stmt, "name": (), "display": "", "table": ()}
986
+ if g.get("name"):
987
+ entry["name"] = cls._sql_name_parts(g["name"])
988
+ entry["display"] = cls._sql_display(g["name"])
989
+ if g.get("table"):
990
+ entry["table"] = cls._sql_name_parts(g["table"])
991
+ if g.get("column"):
992
+ entry["table"] = cls._sql_name_parts(g["column"])[:-1]
993
+ entry["references"] = [cls._sql_name_parts(r.group("table")) for r in cls._SQL_REFERENCES_RE.finditer(stmt)]
994
+ return entry
995
+ return None
996
+
997
+ @classmethod
998
+ def _slice_sql(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
999
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
1000
+ src = f.read(_MAX_SQL_BYTES)
1001
+ entries = [e for e in (cls._classify_sql(s) for s in cls._iter_sql_statements(src)) if e]
1002
+
1003
+ # Sequences owned by a table column (pg_dump: ALTER SEQUENCE ... OWNED BY t.col).
1004
+ owners = {e["name"]: e["table"] for e in entries if e["kind"] == "sequence_owner" and e["name"]}
1005
+ for e in entries:
1006
+ if e["kind"] == "sequence" and e["name"] in owners:
1007
+ e["table"] = owners[e["name"]]
1008
+
1009
+ tables = [e["display"] for e in entries if e["kind"] == "table"]
1010
+ if not target:
1011
+ counts: Dict[str, int] = {}
1012
+ for e in entries:
1013
+ counts[e["kind"]] = counts.get(e["kind"], 0) + 1
1014
+ summary = ", ".join(f"{k}: {v}" for k, v in sorted(counts.items()))
1015
+ lines = [f"# SQL DDL skeleton — {len(entries)} DDL statements, {len(tables)} tables (DML/COPY data omitted)",
1016
+ f"# {summary}" if summary else "", ""]
1017
+ for t in tables[:150]:
1018
+ lines.append(f" {t}")
1019
+ others = [f"{e['kind']} {e['display']}" for e in entries if e["kind"] in ("view", "type", "domain", "function")]
1020
+ if others:
1021
+ lines.append("")
1022
+ for o in others[:100]:
1023
+ lines.append(f" {o}")
1024
+ lines.append("\nSlice a table: symbol='users' (or 'public.users').")
1025
+ return "\n".join(lines), {"kind": "sql", "mode": "overview", "tables": tables}
1026
+
1027
+ tgt = cls._sql_name_parts(target)
1028
+ if not tgt:
1029
+ return f"# target '{target}' not found among {len(entries)} DDL statements", {"kind": "sql", "mode": "missing"}
1030
+
1031
+ defining = {"table", "view", "type", "domain", "function", "sequence", "index", "schema"}
1032
+ selected: List[int] = []
1033
+ primary_tables: List[Tuple[str, ...]] = []
1034
+ for idx, e in enumerate(entries):
1035
+ if e["kind"] in defining and cls._sql_suffix_match(e["name"], tgt):
1036
+ selected.append(idx)
1037
+ if e["kind"] in ("table", "view"):
1038
+ primary_tables.append(e["name"])
1039
+ elif e["table"] and cls._sql_suffix_match(e["table"], tgt):
1040
+ selected.append(idx) # its indexes, constraints, triggers, owned sequences, comments
1041
+
1042
+ if not selected:
1043
+ # Last resort: DDL that mentions the identifier (a column or constraint name).
1044
+ word = re.compile(r'(?<![\w$])"?' + re.escape(tgt[-1]) + r'"?(?![\w$])', re.IGNORECASE)
1045
+ mentions = [e["text"] for e in entries if word.search(e["text"])]
1046
+ if not mentions:
1047
+ return f"# target '{target}' not found among {len(entries)} DDL statements", {"kind": "sql", "mode": "missing"}
1048
+ return ";\n\n".join(mentions) + ";", {"kind": "sql", "mode": "mentions", "statements": len(mentions)}
1049
+
1050
+ chosen = set(selected)
1051
+ main_text = "\n".join(entries[i]["text"] for i in selected)
1052
+ # 1-hop: user-defined types used by the selected definitions, and tables they reference by FK.
1053
+ hop: List[int] = []
1054
+ for idx, e in enumerate(entries):
1055
+ if idx in chosen:
1056
+ continue
1057
+ if e["kind"] in ("type", "domain") and e["name"]:
1058
+ if re.search(cls._sql_name_pattern(e["name"]), main_text, re.IGNORECASE):
1059
+ hop.append(idx)
1060
+ fk_targets = []
1061
+ for i in selected:
1062
+ for ref in entries[i]["references"]:
1063
+ if ref and ref not in fk_targets and not any(cls._sql_suffix_match(t, ref) for t in primary_tables):
1064
+ fk_targets.append(ref)
1065
+ for idx, e in enumerate(entries):
1066
+ if idx in chosen or idx in hop or e["kind"] != "table":
1067
+ continue
1068
+ if any(cls._sql_suffix_match(e["name"], ref) or cls._sql_suffix_match(ref, e["name"]) for ref in fk_targets):
1069
+ hop.append(idx)
1070
+
1071
+ out = ";\n\n".join(entries[i]["text"] for i in selected) + ";"
1072
+ if hop:
1073
+ out += "\n\n-- 1-hop related definitions (referenced types and FK target tables)\n"
1074
+ out += ";\n\n".join(entries[i]["text"] for i in sorted(hop)) + ";"
1075
+ info = {"kind": "sql", "mode": "ddl", "statements": len(selected),
1076
+ "refs": [entries[i]["display"] for i in sorted(hop)]}
1077
+ return out, info
1078
+
1079
+ @staticmethod
1080
+ def _sql_name_pattern(parts: Tuple[str, ...]) -> str:
1081
+ """Regex for a (possibly schema-qualified, possibly quoted) reference to `parts`."""
1082
+ quoted = [r'"?' + re.escape(p) + r'"?' for p in parts]
1083
+ last = quoted[-1]
1084
+ if len(quoted) > 1:
1085
+ head = r"\s*\.\s*".join(quoted[:-1])
1086
+ return r"(?<![\w$])(?:" + head + r"\s*\.\s*)?" + last + r"(?![\w$])"
1087
+ return r"(?<![\w$.])" + last + r"(?![\w$])"