tokensafe 4.16.2 → 4.16.3

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.
@@ -9,7 +9,7 @@
9
9
  "name": "tokensafe",
10
10
  "source": "./",
11
11
  "description": "Enforced context optimization for Claude Code: blocking guards, PostToolUse output compaction, symbol/AST slicing, post-compaction recovery, and measured savings.",
12
- "version": "4.16.0"
12
+ "version": "4.16.3"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.16.0",
3
+ "version": "4.16.3",
4
4
  "description": "Local runtime firewall and zero-loss context optimizer for AI coding agents: enforced tool-output compaction, symbol/AST slicing, post-compaction recovery, and measured savings.",
5
5
  "author": {
6
6
  "name": "TokenSafe",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.16.2",
2
+ "version": "4.16.3",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
package/README.md CHANGED
@@ -211,14 +211,19 @@ Why TokenSafe agents ship working code on the first pass without burning quotas
211
211
 
212
212
  Deeper mechanics (language matrix, AST syntax trees, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
213
213
 
214
- ## Context survival, recall, and host coverage
214
+ ## Reads, ingress, recovery, and host coverage
215
215
 
216
- Compaction is the most expensive event in a long session: the host rewrites the prompt, re-bills it uncached, and drops turns the task still depends on. TokenSafe now survives it explicitly.
216
+ Compaction is the most expensive event in a long session, and a full re-read after every edit is the most common one. TokenSafe now handles both explicitly.
217
217
 
218
218
  | Feature | Surface | What it does |
219
219
  |---|---|---|
220
+ | **Diff-on-change reads** | `smart_read_file(path, diff_since=<mtime\|sha256>)` | A changed file returns only bounded unified-diff hunks (≤5 hunks, ≤40% of the file); a rewrite falls back to a normal read. A session-scoped raw baseline makes the diff possible. |
220
221
  | **Post-compaction recovery** | Claude Code `PreCompact` / `PostCompact`; fallback detector on every host with a transcript | Reinjects a small digest: goal, last state, next focus, and up to five ranked pointers to the turns the compaction dropped. Each pointer expands with `tokensafe recall --id <session>:<index>`. |
221
222
  | **Transcript recall** | CLI `tokensafe recall '<query>' [--sessions this\|project\|all]`, MCP `session_context(action='recall_transcript')` | BM25F search over prior Claude/Codex/Kimi/ZCode/Cursor/Antigravity transcripts. No index copy; snippets are secret-redacted and output is budget-capped. |
223
+ | **Lossless ingress staging** | `TOKENSAFE_INGRESS_THRESHOLD` (default 8000 tokens), MCP `session_context(action='ingress_show')`, CLI `tokensafe ingress show` | A long prompt is stored redacted with a recovery handle; the model gets a TOCP summary plus a section index and reads exact sections on demand. `tokensafe ingress stats` reports the fetch rate. |
224
+ | **Blast-radius hint** | `apply_edits` result | After a successful edit on a warm graph, one advisory line names direct importers and static callers; no crawl, no mandatory follow-up call. |
225
+ | **Out-of-context compute** | `run_helper(action='compute')` | A restricted Python program runs over repository files (AST import/name allowlist, repo path jail, rlimits, 5 s budget) and returns only its JSON result. Inputs never enter the context. |
226
+ | **Image peek** | `smart_read_file(path='shot.png', include_image=true)` | Returns a downscaled (≤1024 px, ≤512 KiB base64) MCP image block plus one metadata line; hosts without vision keep the text. |
222
227
  | **Zero-token statusline** | Claude Code | `tokensafe statusline` renders today's measured savings in the host status bar. The line never enters the conversation. |
223
228
  | **Claude Code plugin** | `/plugin marketplace add <owner>/tokensafe` then `/plugin install tokensafe@tokensafe` | Marketplace manifest, nine lifecycle hooks (including compact events), and an MCP entry. The plugin fails open if the Python engine is absent. |
224
229
  | **Host capability matrix** | `tokensafe doctor` | States exactly which host supports hooks, compact events, context injection, statusline, and transcript parsing, so partial coverage is never sold as full. |
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.16.2",
3
+ "version": "4.16.3",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.16.2",
4
+ "version": "4.16.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.16.2",
4
+ "version": "4.16.3",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.16.2",
6
+ "version": "4.16.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.16.2",
26
+ "version": "4.16.3",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.16.2",
42
+ "version": "4.16.3",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -182,6 +182,28 @@ def compact_for_injection(prompt: str, agent: str, session_id: str, transcript_p
182
182
  meta: Dict[str, Any] = {"agent": agent, "compacted": False}
183
183
  if not prompt or len(prompt.strip()) < 5:
184
184
  return "", meta
185
+ # Lossless ingress staging: a long prompt gets a compact summary plus a
186
+ # recovery handle, so the exact text stays retrievable instead of being
187
+ # irreversibly summarized.
188
+ try:
189
+ from src.ingress_staging import stage as _stage_ingress
190
+
191
+ staged = _stage_ingress(prompt, agent=agent, session_id=session_id)
192
+ if staged:
193
+ meta.update({
194
+ "compacted": True,
195
+ "ingress_staged": True,
196
+ "ingress_hash": staged["hash"],
197
+ "ingress_sections": len(staged["sections"]),
198
+ "original_tokens": staged["original_tokens"],
199
+ "injected_tokens": staged["injected_tokens"],
200
+ "saved_tokens": staged["saved_tokens"],
201
+ "reduction_pct": staged["reduction_pct"],
202
+ "tier": "INGRESS",
203
+ })
204
+ return staged["context_text"], meta
205
+ except Exception:
206
+ pass
185
207
  try:
186
208
  from src.compactor import PromptCompactor
187
209
  from src.tokenizer import count_tokens
@@ -251,6 +251,24 @@ class AgentFirewall:
251
251
 
252
252
  return False, None, 0
253
253
 
254
+ @classmethod
255
+ def was_delivered(cls, session_id: str, file_path: str, tracker: MetricsTracker = None) -> bool:
256
+ """Cheap read-history probe (no metrics, no hit increments)."""
257
+ if not session_id or not file_path or not os.path.exists(file_path):
258
+ return False
259
+ try:
260
+ tracker = tracker or MetricsTracker()
261
+ cls._ensure_table(tracker)
262
+ with tracker._get_connection() as conn:
263
+ row = conn.execute(
264
+ "SELECT 1 FROM subagent_file_cache "
265
+ "WHERE session_id = ? AND file_path = ? LIMIT 1",
266
+ (session_id, os.path.abspath(file_path)),
267
+ ).fetchone()
268
+ return row is not None
269
+ except Exception:
270
+ return False
271
+
254
272
  @classmethod
255
273
  def record_cache(
256
274
  cls,
package/src/cli.py CHANGED
@@ -111,6 +111,8 @@ def _print_help():
111
111
  print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
112
112
  print(" usage [--json] [--session ID] Per-session context report: peak, host compactions, cache-miss events")
113
113
  print(" recall <query> [--sessions this|project|all] [--json] [--id S:N] BM25 search over prior session transcripts")
114
+ print(" ingress show <hash> [--section N|--query TEXT] Read an exact section of a staged long prompt")
115
+ print(" ingress stats Ingress staging/fetch counters and fetch rate")
114
116
  print(" statusline Zero-token savings line for the host status bar")
115
117
  print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
116
118
  print(" dict lint|coverage|show|apply String catalogs: suspect keys only, byte-preserving write-back")
@@ -379,6 +381,62 @@ def main(argv: Optional[List[str]] = None):
379
381
  if line:
380
382
  print(line)
381
383
 
384
+ elif command in ("ingress", "ingress-staging"):
385
+ sub = args[1] if len(args) > 1 else "stats"
386
+ as_json = "--json" in args
387
+ if sub in ("show", "get"):
388
+ hash_ref = args[2] if len(args) > 2 else ""
389
+ if not hash_ref:
390
+ print("Usage: tokensafe ingress show <hash> [--section N] [--query TEXT] [--max-tokens N] [--json]")
391
+ sys.exit(1)
392
+ section = None
393
+ query = ""
394
+ max_tokens = 1500
395
+ idx = 3
396
+ while idx < len(args):
397
+ arg = args[idx]
398
+ if arg in ("--section", "--query", "--max-tokens") and idx + 1 < len(args):
399
+ value = args[idx + 1]
400
+ idx += 1
401
+ if arg == "--section":
402
+ try:
403
+ section = int(value)
404
+ except ValueError:
405
+ pass
406
+ elif arg == "--query":
407
+ query = value
408
+ else:
409
+ try:
410
+ max_tokens = int(value)
411
+ except ValueError:
412
+ pass
413
+ idx += 1
414
+ from src.ingress_staging import show
415
+ result = show(hash_ref, section=section, query=query, max_tokens=max_tokens)
416
+ if as_json:
417
+ import json as _json
418
+ print(_json.dumps(result, indent=2, ensure_ascii=False))
419
+ elif result.get("ok") and result.get("text"):
420
+ print(result["text"])
421
+ elif result.get("ok"):
422
+ for item in result.get("sections") or []:
423
+ lines = item.get("lines") or ["", ""]
424
+ print(f" {item['index']}. {item.get('title') or 'section'} "
425
+ f"(~{item.get('tokens')} tok, L{lines[0]}-L{lines[1]})")
426
+ else:
427
+ print(result.get("reason") or "not found")
428
+ else:
429
+ from src.ingress_staging import stats
430
+ result = stats()
431
+ if as_json:
432
+ import json as _json
433
+ print(_json.dumps(result, indent=2, ensure_ascii=False))
434
+ else:
435
+ print(
436
+ f"Ingress: {result['staged']} staged · {result['fetched']} fetched · "
437
+ f"fetch rate {result['fetch_rate_pct']}%"
438
+ )
439
+
382
440
  elif command in ("recall", "transcript-recall"):
383
441
  query, scope, turn_id = "", "project", ""
384
442
  since = until = transcript_path = ""
@@ -2197,6 +2197,46 @@ class CodeGraph:
2197
2197
  return hits, {"scanned_files": scanned, "total_files": total, "partial": True}
2198
2198
  return hits, {"scanned_files": scanned, "total_files": total, "partial": scanned < total}
2199
2199
 
2200
+ def get_file_impact_summary(self, rel_path: str, limit: int = 5) -> Dict[str, Any]:
2201
+ """Cheap post-edit impact: direct importers, static callers, endpoints.
2202
+
2203
+ Pure in-memory lookups; callers must only use a warm graph (never trigger
2204
+ a scan for a one-line hint).
2205
+ """
2206
+ raw = (rel_path or "").strip().replace("\\", "/")
2207
+ if not raw:
2208
+ return {"file": "", "importers": [], "callers": [], "endpoints": 0,
2209
+ "counts": {"importers": 0, "callers": 0}, "provenance": "static"}
2210
+ if os.path.isabs(raw):
2211
+ try:
2212
+ raw = os.path.relpath(raw, self.root_dir)
2213
+ except ValueError:
2214
+ pass
2215
+ raw = os.path.normpath(raw).replace("\\", "/")
2216
+ while raw.startswith("./"):
2217
+ raw = raw[2:]
2218
+ raw = raw.lstrip("/")
2219
+
2220
+ importers = sorted({
2221
+ edge[5:] for edge in self.rev_edges.get(f"file:{raw}", set())
2222
+ if isinstance(edge, str) and edge.startswith("file:")
2223
+ })
2224
+ callers = set()
2225
+ for symbol_key in self.file_symbols.get(raw, []):
2226
+ name = str(symbol_key).split("::")[-1].split(".")[-1]
2227
+ for caller in self.rev_edges.get(f"call:{name}", set()):
2228
+ if isinstance(caller, str) and "::" in caller:
2229
+ callers.add(caller.split("::")[0])
2230
+ caller_files = sorted(callers)
2231
+ return {
2232
+ "file": raw,
2233
+ "importers": importers[: max(1, int(limit or 5))],
2234
+ "callers": caller_files[: max(1, int(limit or 5))],
2235
+ "endpoints": len(self.file_endpoints.get(raw, [])),
2236
+ "counts": {"importers": len(importers), "callers": len(caller_files)},
2237
+ "provenance": "static",
2238
+ }
2239
+
2200
2240
  def get_import_neighborhood(self, rel_path: str, limit: int = 40) -> Dict[str, Any]:
2201
2241
  """Direct importers and imported files for one file (file-level edges).
2202
2242
 
@@ -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 src.tokenizer import count_tokens
54
+
55
+ return count_tokens(text)
56
+
57
+
58
+ def _redact(text: str) -> str:
59
+ try:
60
+ from src.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 src.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 src.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 src.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 src.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 src.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 src.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 src.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
+ }