tokensafe 4.16.3 → 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 +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 +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/{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
@@ -20,12 +20,13 @@ character.
20
20
 
21
21
  from __future__ import annotations
22
22
 
23
+ import bisect
23
24
  import os
24
25
  import re
25
26
  from dataclasses import dataclass
26
27
  from typing import Any, Dict, List, Optional, Tuple
27
28
 
28
- from src.stash import stash_block
29
+ from tokensafe.stash import stash_block
29
30
 
30
31
  # Directories that conventionally hold message catalogs.
31
32
  _CATALOG_DIR_RE = re.compile(
@@ -114,6 +115,15 @@ class _Parser:
114
115
  self.text = text
115
116
  self.pos = 0
116
117
  self.entries: List[CatalogEntry] = []
118
+ self._nl_offsets: Optional[List[int]] = None
119
+
120
+ def _line(self, index: int) -> int:
121
+ """Equals `_line_of(self.text, index)`, via one shared newline table."""
122
+ offsets = self._nl_offsets
123
+ if offsets is None:
124
+ offsets = [m.start() for m in re.finditer("\n", self.text)]
125
+ self._nl_offsets = offsets
126
+ return bisect.bisect_left(offsets, index) + 1
117
127
 
118
128
  # -- trivia ---------------------------------------------------------
119
129
  def _skip_trivia(self) -> None:
@@ -138,7 +148,7 @@ class _Parser:
138
148
  def _expect(self, ch: str) -> None:
139
149
  if self._peek() != ch:
140
150
  raise CatalogParseError(
141
- f"expected {ch!r} at offset {self.pos} (line {_line_of(self.text, self.pos)})"
151
+ f"expected {ch!r} at offset {self.pos} (line {self._line(self.pos)})"
142
152
  )
143
153
  self.pos += 1
144
154
 
@@ -147,7 +157,7 @@ class _Parser:
147
157
  quote = self._peek()
148
158
  if quote not in ("'", '"'):
149
159
  raise CatalogParseError(
150
- f"expected string at offset {self.pos} (line {_line_of(self.text, self.pos)})"
160
+ f"expected string at offset {self.pos} (line {self._line(self.pos)})"
151
161
  )
152
162
  start = self.pos
153
163
  i = self.pos + 1
@@ -169,7 +179,7 @@ class _Parser:
169
179
  m = re.match(r"[A-Za-z_$][\w$]*", self.text[self.pos:])
170
180
  if not m:
171
181
  raise CatalogParseError(
172
- f"expected identifier at offset {self.pos} (line {_line_of(self.text, self.pos)})"
182
+ f"expected identifier at offset {self.pos} (line {self._line(self.pos)})"
173
183
  )
174
184
  self.pos += m.end()
175
185
  return m.group(0)
@@ -214,7 +224,7 @@ class _Parser:
214
224
  return
215
225
  raise CatalogParseError(
216
226
  f"expected ':' after key {key!r} at offset {self.pos} "
217
- f"(line {_line_of(self.text, self.pos)})"
227
+ f"(line {self._line(self.pos)})"
218
228
  )
219
229
  self.pos += 1
220
230
  path = f"{prefix}.{key}" if prefix else key
@@ -227,7 +237,7 @@ class _Parser:
227
237
  self.pos += 1
228
238
  return
229
239
  raise CatalogParseError(
230
- f"expected ',' or '}}' at offset {self.pos} (line {_line_of(self.text, self.pos)})"
240
+ f"expected ',' or '}}' at offset {self.pos} (line {self._line(self.pos)})"
231
241
  )
232
242
 
233
243
  def _parse_key(self) -> str:
@@ -241,7 +251,7 @@ class _Parser:
241
251
  c = self._peek()
242
252
  if c in ("'", '"'):
243
253
  value, start, end, quote = self._parse_string()
244
- self.entries.append(CatalogEntry(path, value, start, end, quote, _line_of(self.text, start)))
254
+ self.entries.append(CatalogEntry(path, value, start, end, quote, self._line(start)))
245
255
  return
246
256
  if c == "{":
247
257
  self.pos += 1
@@ -257,7 +267,7 @@ class _Parser:
257
267
  self.pos += 1
258
268
  if self.pos == start:
259
269
  raise CatalogParseError(
260
- f"unexpected {c!r} at offset {self.pos} (line {_line_of(self.text, self.pos)})"
270
+ f"unexpected {c!r} at offset {self.pos} (line {self._line(self.pos)})"
261
271
  )
262
272
 
263
273
  def _parse_array_body(self, prefix: str) -> None:
@@ -279,7 +289,7 @@ class _Parser:
279
289
  self.pos += 1
280
290
  return
281
291
  raise CatalogParseError(
282
- f"expected ',' or ']' at offset {self.pos} (line {_line_of(self.text, self.pos)})"
292
+ f"expected ',' or ']' at offset {self.pos} (line {self._line(self.pos)})"
283
293
  )
284
294
 
285
295
 
@@ -9,7 +9,7 @@ Filters high-volume JSON log streams (Winston, Bunyan, Zap, Logstash, Docker JSO
9
9
 
10
10
  import json
11
11
  from typing import Tuple, Dict, Any, List
12
- from src.stash import stash_block
12
+ from tokensafe.stash import stash_block
13
13
 
14
14
 
15
15
  class JSONLogReducer:
@@ -15,8 +15,8 @@ import sqlite3
15
15
  import time
16
16
  import hashlib
17
17
  from typing import Tuple, Dict, Any, List, Optional
18
- from src.stash import stash_block
19
- from src.paths import resolve_data_dir
18
+ from tokensafe.stash import stash_block
19
+ from tokensafe.paths import resolve_data_dir
20
20
 
21
21
 
22
22
  class LockfileReducer:
@@ -360,7 +360,7 @@ class LockfileReducer:
360
360
 
361
361
  # 2. Check L3 Team Sync
362
362
  try:
363
- from src.team_cache import TeamCache
363
+ from tokensafe.team_cache import TeamCache
364
364
  team_val = TeamCache.get("LOCKFILE_INDEX", entry_key, timeout=0.5)
365
365
  if team_val:
366
366
  res = json.loads(team_val)
@@ -418,7 +418,7 @@ class LockfileReducer:
418
418
 
419
419
  # Broadcast to L3 without leaking local filesystem paths or private byte counts
420
420
  try:
421
- from src.team_cache import TeamCache
421
+ from tokensafe.team_cache import TeamCache
422
422
  team_payload = dict(res)
423
423
  team_payload.pop("lockfile_path", None)
424
424
  team_payload.pop("_lockfile_bytes", None)
@@ -13,7 +13,7 @@ import io
13
13
  import json
14
14
  import re
15
15
  from typing import Tuple, Dict, Any, List, Optional
16
- from src.stash import stash_block
16
+ from tokensafe.stash import stash_block
17
17
 
18
18
 
19
19
  class TabularReducer:
@@ -14,8 +14,13 @@ import sqlite3
14
14
  import time
15
15
  from typing import List, Dict, Any, Optional, Tuple
16
16
 
17
- from src.context_index import index_db_path
18
- from src.paths import resolve_data_dir
17
+ from tokensafe.context_index import (
18
+ _ensure_line_spans,
19
+ delete_line_rows,
20
+ index_db_path,
21
+ insert_line_rows,
22
+ )
23
+ from tokensafe.paths import resolve_data_dir
19
24
 
20
25
  # Ignored directories and extensions reused for clean index
21
26
  IGNORED_DIRS = {
@@ -41,7 +46,7 @@ CODE_EXTS = {
41
46
  }
42
47
 
43
48
 
44
- from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
49
+ from tokensafe.paths import resolve_data_dir, ensure_tokensafe_gitignore
45
50
 
46
51
 
47
52
  def _resolve_fts_db_path(project_root: str) -> str:
@@ -106,6 +111,8 @@ class CodeFTSIndex:
106
111
  tokenize = "unicode61"
107
112
  );
108
113
  """)
114
+ # Per-file rowid spans: deletes skip the full FTS5 scan.
115
+ _ensure_line_spans(con)
109
116
  finally:
110
117
  con.close()
111
118
  except Exception:
@@ -169,7 +176,8 @@ class CodeFTSIndex:
169
176
  continue
170
177
 
171
178
  # Remove previous lines for this file
172
- con.execute("DELETE FROM code_lines WHERE rel_path = ?;", (rel_path,))
179
+ cur = con.cursor()
180
+ delete_line_rows(cur, rel_path)
173
181
 
174
182
  # Insert lines with content (bounded to avoid huge minified/base64 lines)
175
183
  line_batch = [
@@ -177,12 +185,8 @@ class CodeFTSIndex:
177
185
  for idx, line in enumerate(lines)
178
186
  if line.strip() and len(line) <= 10000
179
187
  ]
180
- if line_batch:
181
- con.executemany(
182
- "INSERT INTO code_lines (rel_path, line_no, content) VALUES (?, ?, ?);",
183
- line_batch
184
- )
185
- indexed_lines += len(line_batch)
188
+ insert_line_rows(cur, rel_path, line_batch)
189
+ indexed_lines += len(line_batch)
186
190
 
187
191
  con.execute(
188
192
  "INSERT OR REPLACE INTO file_meta (rel_path, mtime, size) VALUES (?, ?, ?);",
@@ -193,8 +197,9 @@ class CodeFTSIndex:
193
197
  # Prune deleted files
194
198
  deleted_paths = set(known_meta.keys()) - found_paths
195
199
  if deleted_paths:
200
+ cur = con.cursor()
196
201
  for del_path in deleted_paths:
197
- con.execute("DELETE FROM code_lines WHERE rel_path = ?;", (del_path,))
202
+ delete_line_rows(cur, del_path)
198
203
  con.execute("DELETE FROM file_meta WHERE rel_path = ?;", (del_path,))
199
204
 
200
205
  con.commit()
@@ -327,5 +332,9 @@ class CodeFTSIndex:
327
332
  with self._get_connection() as con:
328
333
  con.execute("DELETE FROM code_lines")
329
334
  con.execute("DELETE FROM file_meta")
335
+ try:
336
+ con.execute("DELETE FROM code_line_spans")
337
+ except sqlite3.OperationalError:
338
+ pass # spans table never created: nothing to clear
330
339
  except Exception:
331
340
  pass
@@ -11,10 +11,10 @@ import os
11
11
  import re
12
12
  import json
13
13
  from typing import Dict, List, Any, Tuple, Optional
14
- from src.tokenizer import count_tokens
15
- from src.skeletonizer import Skeletonizer
16
- from src.compactor import PromptCompactor
17
- from src.metrics import MetricsTracker
14
+ from tokensafe.tokenizer import count_tokens
15
+ from tokensafe.skeletonizer import Skeletonizer
16
+ from tokensafe.compactor import PromptCompactor
17
+ from tokensafe.metrics import MetricsTracker
18
18
 
19
19
 
20
20
  class ContextGovernor:
@@ -120,39 +120,91 @@ class ContextGovernor:
120
120
  return any(isinstance(b, dict) and b.get("type") == "tool_result" for b in c)
121
121
  return False
122
122
 
123
+ @staticmethod
124
+ def _first_text_line(content: Any) -> str:
125
+ """First non-empty line of a message's text, for string or block content.
126
+
127
+ `"".splitlines()[0]` raised IndexError on an empty user message (ingest
128
+ emits one for a message holding only a document block), and the governor
129
+ is not wrapped in a try, so the proxy request died with no response.
130
+ """
131
+ texts: List[str] = []
132
+ if isinstance(content, str):
133
+ texts.append(content)
134
+ elif isinstance(content, list):
135
+ for blk in content:
136
+ if isinstance(blk, dict) and blk.get("type") == "text" and isinstance(blk.get("text"), str):
137
+ texts.append(blk["text"])
138
+ for text in texts:
139
+ for line in text.splitlines():
140
+ if line.strip():
141
+ return line.strip()[:80]
142
+ return ""
143
+
144
+ @classmethod
145
+ def _epoch_summary(cls, middle_turns: List[Dict[str, Any]], label: str) -> str:
146
+ """Deterministic ledger for folded turns: same turns in, same bytes out."""
147
+ intents: List[str] = []
148
+ tool_counts: Dict[str, int] = {}
149
+ tool_results = 0
150
+ tool_errors = 0
151
+ for m in middle_turns:
152
+ role = m.get("role")
153
+ if role == "user" and not cls._starts_with_tool_result(m):
154
+ line = cls._first_text_line(m.get("content", ""))
155
+ if line:
156
+ intents.append(f"- {line}")
157
+ for tc in m.get("tool_calls") or []:
158
+ if isinstance(tc, dict):
159
+ name = str((tc.get("function") or {}).get("name") or "tool")
160
+ tool_counts[name] = tool_counts.get(name, 0) + 1
161
+ if role == "tool":
162
+ tool_results += 1
163
+ if m.get("_tokensafe_is_error"):
164
+ tool_errors += 1
165
+ lines = [f"[{label}: Consolidated {len(middle_turns)} turns]", "Historical turn goals:"]
166
+ lines.extend(intents[:8] or ["- (none recorded)"])
167
+ if tool_counts:
168
+ used = ", ".join(f"{n}×{c}" for n, c in sorted(tool_counts.items(), key=lambda kv: (-kv[1], kv[0]))[:12])
169
+ lines.append(f"Tools used: {used}")
170
+ if tool_results:
171
+ lines.append(
172
+ f"Tool results folded: {tool_results}"
173
+ + (f" ({tool_errors} failed)" if tool_errors else "")
174
+ + ". Their full output is no longer in context; re-run or re-read what you still need."
175
+ )
176
+ lines.append("...")
177
+ return "\n".join(lines)
178
+
179
+ @classmethod
180
+ def _rollover_cut(cls, governed_messages: List[Dict[str, Any]]) -> int:
181
+ sys_offset = 1 if governed_messages[0].get("role") in ("system", "developer") else 0
182
+ start_idx = max(sys_offset, len(governed_messages) - 3)
183
+ # Never cut inside a tool_use -> tool_result boundary
184
+ while start_idx > sys_offset and cls._starts_with_tool_result(governed_messages[start_idx]):
185
+ start_idx -= 1
186
+ return start_idx
187
+
123
188
  @classmethod
124
189
  def _consolidate_middle_turns(
125
190
  cls,
126
191
  governed_messages: List[Dict[str, Any]],
127
192
  label: str = "Context Governor Ledger",
193
+ cut: Optional[int] = None,
128
194
  ) -> List[Dict[str, Any]]:
129
195
  sys_msg = (
130
196
  governed_messages[0]
131
197
  if governed_messages[0].get("role") in ("system", "developer")
132
198
  else None
133
199
  )
134
- start_idx = max(1 if sys_msg else 0, len(governed_messages) - 3)
135
- # Never cut inside a tool_use -> tool_result boundary
136
- while start_idx > (1 if sys_msg else 0) and cls._starts_with_tool_result(governed_messages[start_idx]):
137
- start_idx -= 1
200
+ start_idx = cls._rollover_cut(governed_messages) if cut is None else cut
138
201
 
139
202
  recent_turns = governed_messages[start_idx:]
140
203
  middle_turns = governed_messages[(1 if sys_msg else 0):start_idx]
141
204
  if not middle_turns:
142
205
  return governed_messages
143
206
 
144
- middle_user_intents = []
145
- for m in middle_turns:
146
- c = m.get("content", "")
147
- if m.get("role") == "user" and isinstance(c, str):
148
- first_line = c.splitlines()[0][:80]
149
- if first_line:
150
- middle_user_intents.append(f"- {first_line}")
151
-
152
- summary_note = (
153
- f"[{label}: Consolidated {len(middle_turns)} turns]\n"
154
- f"Historical turn goals:\n" + "\n".join(middle_user_intents[:8]) + "\n..."
155
- )
207
+ summary_note = cls._epoch_summary(middle_turns, label)
156
208
  consolidated = []
157
209
  if sys_msg:
158
210
  consolidated.append(sys_msg)
@@ -160,6 +212,45 @@ class ContextGovernor:
160
212
  consolidated.extend(recent_turns)
161
213
  return consolidated
162
214
 
215
+ # Append-only epochs: the client resends its FULL history every turn, so a
216
+ # rollover recomputed per request moved the cut and rewrote the ledger each
217
+ # time ("Consolidated N turns" changed), breaking the prompt cache right after
218
+ # the system prompt on every call. The boundary of the last rollover is kept
219
+ # per conversation; while the folded prefix is byte-identical, the same cut is
220
+ # reused and only turns appended after it change.
221
+ _EPOCHS: "Dict[str, Dict[str, Any]]" = {}
222
+ _EPOCHS_MAX = 32
223
+
224
+ @staticmethod
225
+ def _digest(obj: Any) -> str:
226
+ import hashlib
227
+ return hashlib.sha256(
228
+ json.dumps(obj, sort_keys=True, ensure_ascii=False, default=str).encode("utf-8")
229
+ ).hexdigest()
230
+
231
+ @classmethod
232
+ def _conversation_key(cls, session_id: str, messages: List[Dict[str, Any]]) -> str:
233
+ return f"{session_id}:{cls._digest(messages[:2])}"
234
+
235
+ @classmethod
236
+ def _reuse_epoch(cls, key: str, messages: List[Dict[str, Any]]) -> Optional[int]:
237
+ epoch = cls._EPOCHS.get(key)
238
+ if not epoch:
239
+ return None
240
+ cut = int(epoch.get("cut", 0))
241
+ if cut <= 0 or cut >= len(messages):
242
+ return None
243
+ if cls._digest(messages[:cut]) != epoch.get("prefix"):
244
+ return None
245
+ return cut
246
+
247
+ @classmethod
248
+ def _store_epoch(cls, key: str, messages: List[Dict[str, Any]], cut: int) -> None:
249
+ cls._EPOCHS.pop(key, None)
250
+ cls._EPOCHS[key] = {"cut": cut, "prefix": cls._digest(messages[:cut])}
251
+ while len(cls._EPOCHS) > cls._EPOCHS_MAX:
252
+ cls._EPOCHS.pop(next(iter(cls._EPOCHS)), None)
253
+
163
254
  @classmethod
164
255
  def govern_messages(
165
256
  cls,
@@ -213,14 +304,35 @@ class ContextGovernor:
213
304
  current_tokens = cls._calculate_total_tokens(governed_messages)
214
305
  actions_taken.append("ast_fold_tail_code")
215
306
 
216
- # Atomic Epoch Rollover only when still above epoch limit
307
+ # Atomic Epoch Rollover only when still above epoch limit. An earlier
308
+ # rollover of this conversation is reused while its folded prefix is
309
+ # unchanged, so the ledger and everything before the cut stay
310
+ # byte-identical across turns (prompt cache holds). A new cut is taken
311
+ # only when the reused epoch is itself over the limit again.
217
312
  if current_tokens > max_budget and len(governed_messages) > 6:
218
- governed_messages = cls._consolidate_middle_turns(
219
- governed_messages, label="Epoch Ledger"
220
- )
221
- actions_taken.append("epoch_rollover")
222
- epoch_rollover = True
223
- current_tokens = cls._calculate_total_tokens(governed_messages)
313
+ conv_key = cls._conversation_key(session_id, governed_messages)
314
+ cut = cls._reuse_epoch(conv_key, governed_messages)
315
+ if cut is not None:
316
+ candidate = cls._consolidate_middle_turns(governed_messages, label="Epoch Ledger", cut=cut)
317
+ candidate_tokens = cls._calculate_total_tokens(candidate)
318
+ if candidate_tokens <= max_budget:
319
+ governed_messages = candidate
320
+ current_tokens = candidate_tokens
321
+ actions_taken.append("epoch_reuse")
322
+ epoch_rollover = True
323
+ else:
324
+ cut = None
325
+ if cut is None:
326
+ new_cut = cls._rollover_cut(governed_messages)
327
+ consolidated = cls._consolidate_middle_turns(
328
+ governed_messages, label="Epoch Ledger", cut=new_cut
329
+ )
330
+ if consolidated is not governed_messages:
331
+ cls._store_epoch(conv_key, governed_messages, new_cut)
332
+ governed_messages = consolidated
333
+ actions_taken.append("epoch_rollover")
334
+ epoch_rollover = True
335
+ current_tokens = cls._calculate_total_tokens(governed_messages)
224
336
  else:
225
337
  # Explicit tight-budget cascading reduction
226
338
  folded_any = False
@@ -414,7 +526,7 @@ class ContextBudget:
414
526
  measured_source = "caller.prompt_tokens"
415
527
  if measured is None and (transcript_path or discover_transcript):
416
528
  try:
417
- from src.burn_monitor import collect_live_burn_snapshot
529
+ from tokensafe.burn_monitor import collect_live_burn_snapshot
418
530
  snap = collect_live_burn_snapshot(
419
531
  agent="auto",
420
532
  session_id=session_id or "",
@@ -423,7 +535,7 @@ class ContextBudget:
423
535
  candidate = int(snap.get("last_input_tokens") or 0)
424
536
  if candidate <= 0 and transcript_path:
425
537
  try:
426
- from src.transcript_analyzer import analyze_transcript
538
+ from tokensafe.transcript_analyzer import analyze_transcript
427
539
  candidate = int(analyze_transcript(transcript_path).get("last_input_tokens") or 0)
428
540
  except Exception:
429
541
  candidate = 0
@@ -442,7 +554,7 @@ class ContextBudget:
442
554
  transcript_mass = int(history_tokens or 0)
443
555
  if transcript_mass <= 0 and transcript_path:
444
556
  try:
445
- from src.history_compactor import HistoryCompactor
557
+ from tokensafe.history_compactor import HistoryCompactor
446
558
  transcript_mass = HistoryCompactor.measure_transcript(transcript_path)
447
559
  except Exception:
448
560
  transcript_mass = 0
@@ -533,7 +645,7 @@ class ContextBudget:
533
645
  "caveat": caveat,
534
646
  }
535
647
  try:
536
- from src.quality_score import ContextQualityScore
648
+ from tokensafe.quality_score import ContextQualityScore
537
649
  res["quality_score"] = ContextQualityScore.calculate(budget=res)
538
650
  except Exception:
539
651
  pass