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.
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 +8 -3
  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 -2429
  26. package/src/mcp_server.py +11 -5024
  27. package/src/proxy.py +11 -1803
  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 +42 -17
  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 +68 -9
  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 +769 -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/tokensafe/ingress_staging.py +384 -0
  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 +5664 -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/tokensafe/read_baseline.py +192 -0
  100. package/tokensafe/repo_compute.py +332 -0
  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
@@ -22,7 +22,7 @@ from collections import OrderedDict
22
22
  from dataclasses import dataclass, field
23
23
  from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
24
24
 
25
- from src.format_parsers.i18n_strings import (
25
+ from tokensafe.format_parsers.i18n_strings import (
26
26
  CatalogEntry,
27
27
  StringCatalogReducer,
28
28
  locale_namespace_from_path,
@@ -154,34 +154,46 @@ def list_locales(messages_dir: str) -> List[str]:
154
154
  return []
155
155
 
156
156
 
157
- _LOCALE_CACHE: "OrderedDict[Tuple[str, str, float], LocaleCatalog]" = OrderedDict()
157
+ _LOCALE_CACHE: "OrderedDict[Tuple[str, str, Tuple], LocaleCatalog]" = OrderedDict()
158
158
  _LOCALE_CACHE_MAX = 24
159
159
 
160
160
 
161
161
  def load_locale(messages_dir: str, locale: str) -> LocaleCatalog:
162
- """Parses every catalog file of a locale. Cached by directory mtime."""
162
+ """Parses every catalog file of a locale.
163
+
164
+ Cached by each file's (name, mtime_ns, size). A directory mtime only
165
+ changes when files are added or removed, so an edit made in place (an
166
+ editor save, git checkout) kept serving the old text and `dict apply`
167
+ wrote that stale text back over the fresh edit.
168
+ """
163
169
  messages_dir = os.path.abspath(messages_dir)
164
170
  locale_dir = os.path.join(messages_dir, locale)
165
171
  try:
166
- mtime = os.path.getmtime(locale_dir)
172
+ names = sorted(
173
+ (d for d in os.scandir(locale_dir)
174
+ if d.is_file() and d.name.lower().endswith(CATALOG_EXTS)),
175
+ key=lambda d: d.name,
176
+ )
167
177
  except OSError:
168
- mtime = 0.0
169
- key = (messages_dir, locale, mtime)
178
+ names = []
179
+ signature = []
180
+ for dirent in names:
181
+ try:
182
+ st = dirent.stat()
183
+ except OSError:
184
+ continue
185
+ signature.append((dirent.name, st.st_mtime_ns, st.st_size))
186
+ key = (messages_dir, locale, tuple(signature))
170
187
  cached = _LOCALE_CACHE.get(key)
171
188
  if cached is not None:
172
189
  _LOCALE_CACHE.move_to_end(key)
173
190
  return cached
174
191
 
175
192
  catalog = LocaleCatalog(messages_dir=messages_dir, locale=locale)
176
- try:
177
- names = sorted(os.scandir(locale_dir), key=lambda d: d.name)
178
- except OSError:
179
- names = []
180
193
  for dirent in names:
181
- if not dirent.is_file() or not dirent.name.lower().endswith(CATALOG_EXTS):
182
- continue
183
194
  try:
184
- with open(dirent.path, "r", encoding="utf-8", errors="replace") as handle:
195
+ # newline="" keeps CRLF catalogs CRLF when apply writes them back.
196
+ with open(dirent.path, "r", encoding="utf-8", errors="replace", newline="") as handle:
185
197
  text = handle.read()
186
198
  except OSError:
187
199
  continue
@@ -546,8 +558,21 @@ def apply(
546
558
  diffs.extend(diff)
547
559
  if not dry_run:
548
560
  abspath = os.path.join(catalog.messages_dir, relpath)
561
+ try:
562
+ with open(abspath, "r", encoding="utf-8", errors="replace", newline="") as handle:
563
+ on_disk = handle.read()
564
+ except OSError:
565
+ on_disk = None
566
+ if on_disk != text:
567
+ # Changed since it was parsed: writing would revert that edit.
568
+ for c in changed:
569
+ if c["file"] == relpath:
570
+ refused[c["path"]] = "refused: file changed on disk since it was read; re-run"
571
+ changed = [c for c in changed if c["file"] != relpath]
572
+ del diffs[len(diffs) - len(diff):]
573
+ continue
549
574
  tmp = abspath + ".tokensafe.tmp"
550
- with open(tmp, "w", encoding="utf-8") as handle:
575
+ with open(tmp, "w", encoding="utf-8", newline="") as handle:
551
576
  handle.write(new_text)
552
577
  os.replace(tmp, abspath)
553
578
  written.append(relpath)
@@ -16,7 +16,7 @@ import shutil
16
16
  import hashlib
17
17
  import subprocess
18
18
  from typing import Dict, Any, Tuple, Optional
19
- from src.paths import resolve_data_dir
19
+ from tokensafe.paths import resolve_data_dir
20
20
 
21
21
  # Supported extensions
22
22
  IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}
@@ -0,0 +1,384 @@
1
+ """Lossless ingress staging for long prompts.
2
+
3
+ A prompt over the threshold is stored verbatim (after secret redaction) in the
4
+ local stash, and the model receives a compact TOCP summary plus a section index
5
+ and a recovery handle. Sections are re-derived deterministically on retrieval,
6
+ so a later `ingress_show` returns exact source text rather than a summary.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ from dataclasses import dataclass
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ DEFAULT_THRESHOLD = 8000
17
+ MIN_THRESHOLD = 1000
18
+ MAX_INDEX_SECTIONS = 12
19
+ MAX_INDEX_CHARS = 4096
20
+ MAX_SECTION_TOKENS = 1200
21
+ DEFAULT_SHOW_TOKENS = 1500
22
+ MAX_SHOW_TOKENS = 6000
23
+
24
+ _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$")
25
+ _FENCE_RE = re.compile(r"^\s*```")
26
+
27
+
28
+ @dataclass
29
+ class Section:
30
+ index: int
31
+ title: str
32
+ start_line: int
33
+ end_line: int
34
+ text: str
35
+ tokens: int
36
+
37
+ def preview(self, limit: int = 100) -> str:
38
+ first = " ".join(self.text.strip().splitlines()[:2]).strip()
39
+ return first[: limit - 1] + "…" if len(first) > limit else first
40
+
41
+
42
+ def threshold() -> int:
43
+ raw = os.environ.get("TOKENSAFE_INGRESS_THRESHOLD", "").strip()
44
+ if not raw:
45
+ return DEFAULT_THRESHOLD
46
+ try:
47
+ return max(MIN_THRESHOLD, int(raw))
48
+ except ValueError:
49
+ return DEFAULT_THRESHOLD
50
+
51
+
52
+ def _count(text: str) -> int:
53
+ from tokensafe.tokenizer import count_tokens
54
+
55
+ return count_tokens(text)
56
+
57
+
58
+ def _redact(text: str) -> str:
59
+ try:
60
+ from tokensafe.compactor import SecretRedactor
61
+
62
+ result = SecretRedactor.redact_text(text)
63
+ if isinstance(result, tuple):
64
+ return str(result[0] or "")
65
+ return str(result or "")
66
+ except Exception:
67
+ return text
68
+
69
+
70
+ def _split_long(lines: List[str], start_line: int, max_tokens: int) -> List[Section]:
71
+ """Split an oversized block by lines, keeping a two-line overlap."""
72
+ sections: List[Section] = []
73
+ buffer: List[str] = []
74
+ buffer_start = start_line
75
+
76
+ def flush(end_line: int) -> None:
77
+ nonlocal buffer, buffer_start
78
+ if not buffer:
79
+ return
80
+ text = "\n".join(buffer)
81
+ sections.append(Section(len(sections), "", buffer_start, end_line, text, _count(text)))
82
+ buffer = []
83
+
84
+ for offset, line in enumerate(lines):
85
+ candidate = "\n".join(buffer + [line])
86
+ if buffer and _count(candidate) > max_tokens:
87
+ flush(start_line + offset - 1)
88
+ buffer = buffer[-2:] if len(buffer) >= 2 else []
89
+ buffer_start = start_line + offset - len(buffer)
90
+ buffer.append(line)
91
+ flush(start_line + len(lines) - 1)
92
+ return sections
93
+
94
+
95
+ def split_sections(text: str, max_section_tokens: int = MAX_SECTION_TOKENS) -> List[Section]:
96
+ """Deterministic markdown/code/paragraph split into retrievable sections."""
97
+ if not text or not text.strip():
98
+ return []
99
+ lines = text.splitlines()
100
+ blocks: List[tuple] = [] # (start_line, [lines])
101
+ current: List[str] = []
102
+ current_start = 1
103
+ current_has_heading = False
104
+ in_fence = False
105
+
106
+ def flush(end_line: int) -> None:
107
+ nonlocal current, current_start, current_has_heading
108
+ if current:
109
+ blocks.append((current_start, current))
110
+ current = []
111
+ current_has_heading = False
112
+
113
+ for idx, line in enumerate(lines, 1):
114
+ if _FENCE_RE.match(line):
115
+ if not in_fence:
116
+ if not current_has_heading:
117
+ flush(idx - 1)
118
+ current_start = idx
119
+ in_fence = True
120
+ current.append(line)
121
+ else:
122
+ current.append(line)
123
+ flush(idx)
124
+ in_fence = False
125
+ continue
126
+ if in_fence:
127
+ current.append(line)
128
+ continue
129
+ heading = _HEADING_RE.match(line)
130
+ if heading:
131
+ flush(idx - 1)
132
+ current_start = idx
133
+ current_has_heading = True
134
+ current.append(line)
135
+ continue
136
+ if not line.strip():
137
+ current.append(line)
138
+ # A markdown section keeps its blank lines; plain text splits on paragraphs.
139
+ if not current_has_heading:
140
+ flush(idx)
141
+ continue
142
+ current.append(line)
143
+ flush(len(lines))
144
+
145
+ sections: List[Section] = []
146
+ for start, block_lines in blocks:
147
+ # Trim leading/trailing blank lines without losing interior text.
148
+ while block_lines and not block_lines[0].strip():
149
+ block_lines = block_lines[1:]
150
+ start += 1
151
+ while block_lines and not block_lines[-1].strip():
152
+ block_lines = block_lines[:-1]
153
+ if not block_lines:
154
+ continue
155
+ title = ""
156
+ heading = _HEADING_RE.match(block_lines[0])
157
+ if heading:
158
+ title = heading.group(2).strip()
159
+ text_block = "\n".join(block_lines)
160
+ if _count(text_block) > max_section_tokens and len(block_lines) > 3:
161
+ for part in _split_long(block_lines, start, max_section_tokens):
162
+ part.index = len(sections)
163
+ sections.append(part)
164
+ else:
165
+ sections.append(Section(len(sections), title, start, start + len(block_lines) - 1, text_block, _count(text_block)))
166
+ return sections
167
+
168
+
169
+ def _handle_text(hash8: str, sections: List[Section]) -> str:
170
+ lines = [
171
+ f"[Ingress staged #{hash8} · {len(sections)} section(s)]",
172
+ ]
173
+ for section in sections[:MAX_INDEX_SECTIONS]:
174
+ title = section.title or section.preview(60) or f"section {section.index}"
175
+ lines.append(f"{section.index}. {title} (~{section.tokens} tok, L{section.start_line}-{section.end_line})")
176
+ if len(sections) > MAX_INDEX_SECTIONS:
177
+ lines.append(f"… {len(sections) - MAX_INDEX_SECTIONS} more sections")
178
+ lines.append(
179
+ f"Read one: session_context(action='ingress_show', hash='{hash8}', section=N); "
180
+ f"or query: session_context(action='ingress_show', hash='{hash8}', query='...')"
181
+ )
182
+ text = "\n".join(lines)
183
+ return text[:MAX_INDEX_CHARS]
184
+
185
+
186
+ def stage(prompt: str, agent: str = "", session_id: str = "") -> Optional[Dict[str, Any]]:
187
+ """Stage a long prompt; returns handle/summary metadata or None below threshold."""
188
+ if not prompt or not prompt.strip():
189
+ return None
190
+ original_tokens = _count(prompt)
191
+ if original_tokens < threshold():
192
+ return None
193
+ redacted = _redact(prompt)
194
+ try:
195
+ from tokensafe.stash import stash_block
196
+
197
+ hash8, _marker = stash_block(redacted, source="ingress")
198
+ except Exception:
199
+ return None
200
+ if not hash8:
201
+ return None
202
+ sections = split_sections(redacted)
203
+ summary = ""
204
+ try:
205
+ from tokensafe.compactor import PromptCompactor
206
+
207
+ compaction = PromptCompactor.compact(redacted, enable_distill=False)
208
+ if compaction.get("saved_tokens", 0) >= 5:
209
+ summary = f"[TOCP Compressed Intent]: {compaction['compact_text']}"
210
+ except Exception:
211
+ summary = ""
212
+ handle = _handle_text(hash8, sections)
213
+ context_text = f"{summary}\n{handle}" if summary else handle
214
+ injected_tokens = _count(context_text)
215
+ try:
216
+ from tokensafe.metrics import MetricsTracker
217
+
218
+ MetricsTracker().record_event(
219
+ session_id=session_id or f"ingress:{agent or 'unknown'}",
220
+ event_type="INGRESS_STAGE",
221
+ original_tokens=original_tokens,
222
+ optimized_tokens=injected_tokens,
223
+ details={
224
+ "agent": agent,
225
+ "hash": hash8,
226
+ "sections": len(sections),
227
+ "redacted": redacted != prompt,
228
+ },
229
+ )
230
+ except Exception:
231
+ pass
232
+ return {
233
+ "hash": hash8,
234
+ "sections": sections,
235
+ "context_text": context_text,
236
+ "handle_text": handle,
237
+ "summary_text": summary,
238
+ "original_tokens": original_tokens,
239
+ "injected_tokens": injected_tokens,
240
+ "saved_tokens": max(0, original_tokens - injected_tokens),
241
+ "reduction_pct": round((1 - injected_tokens / original_tokens) * 100, 1) if original_tokens else 0.0,
242
+ }
243
+
244
+
245
+ def append_handle(compacted_text: str, staged: Optional[Dict[str, Any]]) -> str:
246
+ """Proxy helper: keep the recovery handle attached to an in-place replacement."""
247
+ if not staged:
248
+ return compacted_text
249
+ return f"{compacted_text}\n{staged.get('handle_text') or ''}".strip()
250
+
251
+
252
+ def _rank_sections(query: str, sections: List[Section]) -> List[Section]:
253
+ from tokensafe.transcript_recall import tokenize
254
+
255
+ query_terms = set(tokenize(query))
256
+ if not query_terms:
257
+ return sections[:1]
258
+ scored = []
259
+ for section in sections:
260
+ terms = set(tokenize(section.text))
261
+ score = len(query_terms & terms)
262
+ if score:
263
+ scored.append((score, section.index, section))
264
+ scored.sort(key=lambda item: (item[0], -item[1]), reverse=True)
265
+ return [item[2] for item in scored[:2]]
266
+
267
+
268
+ def _truncate(text: str, max_tokens: int) -> tuple:
269
+ tokens = _count(text)
270
+ if tokens <= max_tokens:
271
+ return text, tokens, False
272
+ # Cut by characters in proportion, then verify; no tokenizer encode/decode needed.
273
+ keep_chars = max(200, int(len(text) * (max_tokens / max(1, tokens)) * 0.95))
274
+ trimmed = text[:keep_chars]
275
+ while _count(trimmed) > max_tokens and len(trimmed) > 200:
276
+ trimmed = trimmed[: int(len(trimmed) * 0.9)]
277
+ return trimmed + f"\n… [section truncated: {max_tokens} of {tokens} tokens]", max_tokens, True
278
+
279
+
280
+ def show(
281
+ hash_or_ref: str,
282
+ section: Optional[int] = None,
283
+ query: str = "",
284
+ max_tokens: int = DEFAULT_SHOW_TOKENS,
285
+ session_id: str = "",
286
+ ) -> Dict[str, Any]:
287
+ """Return a section (or the index) from a staged prompt."""
288
+ from tokensafe.stash import retrieve_block
289
+
290
+ content = retrieve_block(str(hash_or_ref or ""))
291
+ if content is None:
292
+ return {"ok": False, "reason": "ingress handle not found or expired (7-day retention)"}
293
+ sections = split_sections(content)
294
+ max_tokens = max(200, min(int(max_tokens or DEFAULT_SHOW_TOKENS), MAX_SHOW_TOKENS))
295
+ selected: List[Section] = []
296
+ if section is not None:
297
+ try:
298
+ wanted = int(section)
299
+ except (TypeError, ValueError):
300
+ wanted = -1
301
+ selected = [s for s in sections if s.index == wanted]
302
+ elif query:
303
+ selected = _rank_sections(query, sections)
304
+ if not selected:
305
+ index = [
306
+ {
307
+ "index": s.index,
308
+ "title": s.title or s.preview(60),
309
+ "tokens": s.tokens,
310
+ "lines": [s.start_line, s.end_line],
311
+ }
312
+ for s in sections
313
+ ]
314
+ payload = {
315
+ "ok": True,
316
+ "hash": str(hash_or_ref),
317
+ "sections": index,
318
+ "note": "pass `section` or `query` to retrieve exact text",
319
+ }
320
+ return payload
321
+ parts = []
322
+ total_tokens = 0
323
+ truncated = False
324
+ for item in selected:
325
+ text, tokens, cut = _truncate(item.text, max_tokens)
326
+ total_tokens += tokens
327
+ truncated = truncated or cut
328
+ parts.append(f"// [Ingress section {item.index} L{item.start_line}-L{item.end_line}]\n{text}")
329
+ payload = {
330
+ "ok": True,
331
+ "hash": str(hash_or_ref),
332
+ "sections": [{"index": s.index, "title": s.title, "lines": [s.start_line, s.end_line], "tokens": s.tokens} for s in selected],
333
+ "text": "\n\n".join(parts),
334
+ "tokens": total_tokens,
335
+ "truncated": truncated,
336
+ }
337
+ try:
338
+ from tokensafe.metrics import MetricsTracker
339
+
340
+ MetricsTracker().record_event(
341
+ session_id=session_id or "ingress",
342
+ event_type="INGRESS_FETCH",
343
+ original_tokens=0,
344
+ optimized_tokens=total_tokens,
345
+ details={"hash": str(hash_or_ref), "section": section, "query": bool(query), "truncated": truncated},
346
+ )
347
+ except Exception:
348
+ pass
349
+ return payload
350
+
351
+
352
+ def stats() -> Dict[str, Any]:
353
+ """Distinct staged/fetched handles and the fetch rate."""
354
+ staged: set = set()
355
+ fetched: set = set()
356
+ try:
357
+ from tokensafe.metrics import MetricsTracker
358
+
359
+ tracker = MetricsTracker()
360
+ with tracker._get_connection() as conn:
361
+ rows = conn.execute(
362
+ "SELECT event_type, details FROM events "
363
+ "WHERE event_type IN ('INGRESS_STAGE','INGRESS_FETCH')"
364
+ ).fetchall()
365
+ import json
366
+
367
+ for row in rows:
368
+ event_type = row["event_type"] if isinstance(row, dict) else row[0]
369
+ raw = row["details"] if isinstance(row, dict) else row[1]
370
+ try:
371
+ details = json.loads(raw or "{}")
372
+ except Exception:
373
+ continue
374
+ hash8 = str(details.get("hash") or "")
375
+ if not hash8:
376
+ continue
377
+ (staged if event_type == "INGRESS_STAGE" else fetched).add(hash8)
378
+ except Exception:
379
+ pass
380
+ return {
381
+ "staged": len(staged),
382
+ "fetched": len(fetched),
383
+ "fetch_rate_pct": round(len(fetched & staged) / len(staged) * 100, 1) if staged else 0.0,
384
+ }