tokensafe 4.16.0 → 4.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/hooks.json +124 -0
- package/.claude-plugin/marketplace.json +15 -0
- package/.claude-plugin/plugin.json +21 -0
- package/.codex-plugin/plugin.json +1 -1
- package/.mcp.json +10 -0
- package/README.md +14 -0
- package/bin/tokensafe-claude-hook +18 -0
- package/bin/tokensafe-mcp +17 -0
- package/hooks/claude_code_hook.py +59 -0
- package/hooks/kimi_hook.py +27 -0
- package/hooks/pre_invocation.py +19 -0
- package/hooks/session_start.py +21 -0
- package/kimi.plugin.json +1 -1
- package/package.json +5 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/agent_firewall.py +2 -1
- package/src/angular_cli.py +14 -6
- package/src/auto_inject.py +581 -12
- package/src/batch_editor.py +62 -22
- package/src/cli.py +104 -0
- package/src/command_sanitizer.py +19 -7
- package/src/compaction_recovery.py +335 -0
- package/src/format_invariants.py +158 -0
- package/src/graph_engine.py +48 -0
- package/src/host_capabilities.py +180 -0
- package/src/installer.py +39 -5
- package/src/mcp_server.py +146 -7
- package/src/session_brief.py +1 -1
- package/src/statusline.py +44 -0
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_recall.py +565 -0
- package/src/usage_ledger.py +13 -0
- package/src/version_checker.py +1 -1
package/src/batch_editor.py
CHANGED
|
@@ -265,30 +265,70 @@ def _target_occurrence_lines(content: str, target: str, limit: int = 5) -> List[
|
|
|
265
265
|
return out
|
|
266
266
|
|
|
267
267
|
|
|
268
|
-
def _find_closest_line_hint(target: str, content: str, max_lines_preview: int =
|
|
269
|
-
"""
|
|
270
|
-
|
|
271
|
-
|
|
268
|
+
def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 7) -> str:
|
|
269
|
+
"""Suggest the closest block when an exact target misses.
|
|
270
|
+
|
|
271
|
+
A single-line hint cannot describe a drifted multi-line edit, so the matcher
|
|
272
|
+
slides a window of the target's length (plus/minus one line) across the file
|
|
273
|
+
and scores whole blocks with difflib. This is advisory only: the caller must
|
|
274
|
+
retry with the named range; nothing is applied automatically.
|
|
275
|
+
"""
|
|
276
|
+
target_lines = [line.rstrip() for line in target.splitlines()]
|
|
277
|
+
if not target_lines:
|
|
272
278
|
return "Target string is empty."
|
|
279
|
+
file_lines = content.splitlines()
|
|
280
|
+
if not file_lines:
|
|
281
|
+
return "Target string not found anywhere in file."
|
|
282
|
+
|
|
283
|
+
target_block = "\n".join(target_lines)
|
|
284
|
+
span = len(target_lines)
|
|
285
|
+
first = target_lines[0].strip()
|
|
286
|
+
candidates = []
|
|
287
|
+
for idx, line in enumerate(file_lines):
|
|
288
|
+
if first:
|
|
289
|
+
first_ratio = difflib.SequenceMatcher(None, first, line.strip()).ratio()
|
|
290
|
+
if first_ratio < 0.45:
|
|
291
|
+
continue
|
|
292
|
+
for size in (span, max(1, span - 1), span + 1):
|
|
293
|
+
if idx + size > len(file_lines):
|
|
294
|
+
continue
|
|
295
|
+
block = "\n".join(part.rstrip() for part in file_lines[idx:idx + size])
|
|
296
|
+
ratio = difflib.SequenceMatcher(None, target_block, block).ratio()
|
|
297
|
+
candidates.append((ratio, idx, size))
|
|
298
|
+
if len(candidates) > 900:
|
|
299
|
+
break
|
|
273
300
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
301
|
+
if not candidates:
|
|
302
|
+
return "Target string not found anywhere in file."
|
|
303
|
+
candidates.sort(key=lambda item: (item[0], -item[1]), reverse=True)
|
|
304
|
+
best_ratio, best_idx, best_size = candidates[0]
|
|
305
|
+
if best_ratio < 0.55:
|
|
306
|
+
return "Target string not found anywhere in file."
|
|
307
|
+
|
|
308
|
+
start = best_idx + 1
|
|
309
|
+
end = best_idx + best_size
|
|
310
|
+
rival = next(
|
|
311
|
+
(
|
|
312
|
+
item for item in candidates[1:]
|
|
313
|
+
if item[0] >= best_ratio - 0.03 and abs(item[1] - best_idx) >= best_size
|
|
314
|
+
),
|
|
315
|
+
None,
|
|
316
|
+
)
|
|
317
|
+
ambiguity = ""
|
|
318
|
+
if rival and best_ratio < 0.97:
|
|
319
|
+
ambiguity = f" (a second candidate is at line {rival[1] + 1}, similarity {rival[0]:.0%})"
|
|
320
|
+
|
|
321
|
+
preview_start = max(0, best_idx - 1)
|
|
322
|
+
preview_end = min(len(file_lines), best_idx + best_size + 1)
|
|
323
|
+
preview = []
|
|
324
|
+
for index in range(preview_start, preview_end):
|
|
325
|
+
marker = ">> " if best_idx <= index < best_idx + best_size else " "
|
|
326
|
+
preview.append(f"{marker}L{index + 1}: {file_lines[index]}")
|
|
327
|
+
return (
|
|
328
|
+
f"Closest block at lines {start}-{end} (similarity {best_ratio:.0%}){ambiguity}:\n"
|
|
329
|
+
+ "\n".join(preview)
|
|
330
|
+
+ f"\nRetry with start_line={start}, end_line={end}."
|
|
331
|
+
)
|
|
292
332
|
|
|
293
333
|
|
|
294
334
|
def _dominant_newline(text: str) -> str:
|
package/src/cli.py
CHANGED
|
@@ -110,6 +110,8 @@ def _print_help():
|
|
|
110
110
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
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
|
+
print(" recall <query> [--sessions this|project|all] [--json] [--id S:N] BM25 search over prior session transcripts")
|
|
114
|
+
print(" statusline Zero-token savings line for the host status bar")
|
|
113
115
|
print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
|
|
114
116
|
print(" dict lint|coverage|show|apply String catalogs: suspect keys only, byte-preserving write-back")
|
|
115
117
|
print(" status One-screen health check: hooks, weekly savings, tier, sync")
|
|
@@ -371,6 +373,78 @@ def main(argv: Optional[List[str]] = None):
|
|
|
371
373
|
print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
|
|
372
374
|
print()
|
|
373
375
|
|
|
376
|
+
elif command == "statusline":
|
|
377
|
+
from src.statusline import render_statusline
|
|
378
|
+
line = render_statusline()
|
|
379
|
+
if line:
|
|
380
|
+
print(line)
|
|
381
|
+
|
|
382
|
+
elif command in ("recall", "transcript-recall"):
|
|
383
|
+
query, scope, turn_id = "", "project", ""
|
|
384
|
+
since = until = transcript_path = ""
|
|
385
|
+
limit = 10
|
|
386
|
+
as_json = "--json" in args
|
|
387
|
+
idx = 1
|
|
388
|
+
while idx < len(args):
|
|
389
|
+
arg = args[idx]
|
|
390
|
+
value = ""
|
|
391
|
+
key = arg
|
|
392
|
+
if arg.startswith("--") and "=" in arg:
|
|
393
|
+
key, value = arg.split("=", 1)
|
|
394
|
+
if key in ("--sessions", "--scope") and not value and idx + 1 < len(args):
|
|
395
|
+
value = args[idx + 1]
|
|
396
|
+
idx += 1
|
|
397
|
+
if key in ("--limit",) and not value and idx + 1 < len(args):
|
|
398
|
+
value = args[idx + 1]
|
|
399
|
+
idx += 1
|
|
400
|
+
if key in ("--since", "--until", "--transcript", "--id") and not value and idx + 1 < len(args):
|
|
401
|
+
value = args[idx + 1]
|
|
402
|
+
idx += 1
|
|
403
|
+
if key in ("--sessions", "--scope"):
|
|
404
|
+
scope = value or scope
|
|
405
|
+
elif key == "--limit":
|
|
406
|
+
try:
|
|
407
|
+
limit = int(value)
|
|
408
|
+
except ValueError:
|
|
409
|
+
pass
|
|
410
|
+
elif key == "--since":
|
|
411
|
+
since = value
|
|
412
|
+
elif key == "--until":
|
|
413
|
+
until = value
|
|
414
|
+
elif key == "--transcript":
|
|
415
|
+
transcript_path = value
|
|
416
|
+
elif key == "--id":
|
|
417
|
+
turn_id = value
|
|
418
|
+
elif not arg.startswith("-") and not query:
|
|
419
|
+
query = arg
|
|
420
|
+
idx += 1
|
|
421
|
+
from src.transcript_recall import drill_down, search
|
|
422
|
+
session_id = os.environ.get("TOKENSAFE_SESSION_ID", "")
|
|
423
|
+
if turn_id:
|
|
424
|
+
result = drill_down(
|
|
425
|
+
turn_id,
|
|
426
|
+
scope="all",
|
|
427
|
+
cwd=os.getcwd(),
|
|
428
|
+
session_id=session_id,
|
|
429
|
+
transcript_path=transcript_path,
|
|
430
|
+
)
|
|
431
|
+
else:
|
|
432
|
+
result = search(
|
|
433
|
+
query=query,
|
|
434
|
+
scope=scope,
|
|
435
|
+
cwd=os.getcwd(),
|
|
436
|
+
session_id=session_id,
|
|
437
|
+
transcript_path=transcript_path,
|
|
438
|
+
since=since,
|
|
439
|
+
until=until,
|
|
440
|
+
limit=limit,
|
|
441
|
+
)
|
|
442
|
+
if as_json:
|
|
443
|
+
import json as _json
|
|
444
|
+
print(_json.dumps(result, indent=2, ensure_ascii=False))
|
|
445
|
+
else:
|
|
446
|
+
print(result.get("text") or result.get("reason") or "(no results)")
|
|
447
|
+
|
|
374
448
|
elif command in ("usage", "output"):
|
|
375
449
|
# MetricsTracker is imported at module level on purpose: a function-local
|
|
376
450
|
# import would shadow it for the whole main() and break earlier branches
|
|
@@ -907,6 +981,10 @@ def main(argv: Optional[List[str]] = None):
|
|
|
907
981
|
print(f" install: {action['install']}")
|
|
908
982
|
if action.get("run"):
|
|
909
983
|
print(f" run: {action['run']}")
|
|
984
|
+
middleware = action.get("middleware") or {}
|
|
985
|
+
if middleware:
|
|
986
|
+
files = ", ".join(middleware.get("files") or []) or "-"
|
|
987
|
+
print(f" middleware: {middleware.get('status')} ({files})")
|
|
910
988
|
if action.get("reason"):
|
|
911
989
|
print(f" reason: {action['reason']}")
|
|
912
990
|
if action.get("snippet"):
|
|
@@ -950,6 +1028,10 @@ def main(argv: Optional[List[str]] = None):
|
|
|
950
1028
|
app = action.get("app")
|
|
951
1029
|
where = f" [{app}]" if app not in (None, ".", "") else ""
|
|
952
1030
|
print(f" {prefix}{action['kind']}{where}: {status}")
|
|
1031
|
+
middleware = action.get("middleware") or {}
|
|
1032
|
+
if middleware:
|
|
1033
|
+
files = ", ".join(middleware.get("files") or []) or "-"
|
|
1034
|
+
print(f" middleware: {middleware.get('status')} ({files})")
|
|
953
1035
|
if action.get("run"):
|
|
954
1036
|
print(f" run: {action['run']}")
|
|
955
1037
|
if action.get("reason"):
|
|
@@ -1574,6 +1656,28 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1574
1656
|
|
|
1575
1657
|
print(EnvironmentAuditor.format_cli_report())
|
|
1576
1658
|
|
|
1659
|
+
# Honest per-host feature matrix: what is enforced vs merely available.
|
|
1660
|
+
try:
|
|
1661
|
+
from src.host_capabilities import matrix_rows
|
|
1662
|
+
print("\n\033[1m\033[36m⚡ HOST CAPABILITIES ⚡\033[0m")
|
|
1663
|
+
for row in matrix_rows():
|
|
1664
|
+
flags = []
|
|
1665
|
+
for key, label in (
|
|
1666
|
+
("hooks", "hooks"),
|
|
1667
|
+
("precompact", "pre-compact"),
|
|
1668
|
+
("postcompact", "post-compact"),
|
|
1669
|
+
("session_injection", "session-inject"),
|
|
1670
|
+
("prompt_injection", "prompt-inject"),
|
|
1671
|
+
("statusline", "statusline"),
|
|
1672
|
+
("transcript", "transcript"),
|
|
1673
|
+
):
|
|
1674
|
+
if row.get(key):
|
|
1675
|
+
flags.append(label)
|
|
1676
|
+
print(f" {row['host']:<15} {' · '.join(flags) if flags else 'MCP/rules only'}")
|
|
1677
|
+
print()
|
|
1678
|
+
except Exception:
|
|
1679
|
+
pass
|
|
1680
|
+
|
|
1577
1681
|
conflicts = CompetitorAuditor.audit()
|
|
1578
1682
|
if conflicts:
|
|
1579
1683
|
print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
|
package/src/command_sanitizer.py
CHANGED
|
@@ -1078,13 +1078,25 @@ class CommandSanitizer:
|
|
|
1078
1078
|
return None
|
|
1079
1079
|
from src.format_parsers.ansi import strip_ansi
|
|
1080
1080
|
raw = strip_ansi(raw)
|
|
1081
|
+
|
|
1082
|
+
# Every replacement passes the format-invariant gate: no inflation, no
|
|
1083
|
+
# dropped diff/table/declaration lines, and structural lossy output gets
|
|
1084
|
+
# an exact-recovery anchor. A rejected candidate keeps the raw output.
|
|
1085
|
+
from src.format_invariants import gate as _format_gate
|
|
1086
|
+
|
|
1087
|
+
def _accept(candidate: Optional[str]) -> Optional[Tuple[str, int, int]]:
|
|
1088
|
+
if not candidate:
|
|
1089
|
+
return None
|
|
1090
|
+
gated = _format_gate(raw, candidate)
|
|
1091
|
+
return (gated, len(raw), len(gated)) if gated else None
|
|
1092
|
+
|
|
1081
1093
|
if resolved_exit is None:
|
|
1082
1094
|
# Unknown exit status: refuse to mute anything that looks like a failure,
|
|
1083
1095
|
# but allow noise-only stripping (tracebacks stay intact) when it saves >=15%.
|
|
1084
1096
|
if re.search(r"Traceback|AssertionError|\bERROR\b|FAILED|exit code [1-9]", raw):
|
|
1085
1097
|
stripped = cls._strip_failure_noise(raw)
|
|
1086
1098
|
if len(stripped) < len(raw) * 0.85:
|
|
1087
|
-
return
|
|
1099
|
+
return _accept(stripped)
|
|
1088
1100
|
return None
|
|
1089
1101
|
resolved_exit = 0
|
|
1090
1102
|
elif resolved_exit != 0:
|
|
@@ -1092,24 +1104,24 @@ class CommandSanitizer:
|
|
|
1092
1104
|
from src.test_parsers import TestOutputParser
|
|
1093
1105
|
compacted_test, was_test = TestOutputParser.compact(raw)
|
|
1094
1106
|
if was_test and len(compacted_test) < len(raw) * 0.85:
|
|
1095
|
-
return
|
|
1107
|
+
return _accept(compacted_test)
|
|
1096
1108
|
|
|
1097
1109
|
from src.build_parsers import BuildOutputParser
|
|
1098
1110
|
compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
|
|
1099
1111
|
if was_build and len(compacted_build) < len(raw) * 0.85:
|
|
1100
|
-
return
|
|
1112
|
+
return _accept(compacted_build)
|
|
1101
1113
|
|
|
1102
1114
|
# Failed run: failure noise (progress dots / blank runs / verbose PASSED lines)
|
|
1103
1115
|
# is stripped while every traceback frame stays intact; skip when it saves <15%.
|
|
1104
1116
|
stripped = cls._strip_failure_noise(raw)
|
|
1105
1117
|
if len(stripped) >= len(raw) * 0.85:
|
|
1106
1118
|
return None
|
|
1107
|
-
return
|
|
1119
|
+
return _accept(stripped)
|
|
1108
1120
|
# Check build output parser first (vite, next, webpack, cargo, go build)
|
|
1109
1121
|
from src.build_parsers import BuildOutputParser
|
|
1110
1122
|
compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
|
|
1111
1123
|
if was_build and len(compacted_build) < len(raw) * 0.8:
|
|
1112
|
-
return
|
|
1124
|
+
return _accept(compacted_build)
|
|
1113
1125
|
|
|
1114
1126
|
# Docker build logs: the reducer already folds STEP/#n stage lines and keeps
|
|
1115
1127
|
# errors, but only `tokensafe wrap` and the result ledger used it — this path
|
|
@@ -1118,9 +1130,9 @@ class CommandSanitizer:
|
|
|
1118
1130
|
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
1119
1131
|
reduced_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
|
|
1120
1132
|
if was_docker and len(reduced_docker) < len(raw) * 0.8:
|
|
1121
|
-
return
|
|
1133
|
+
return _accept(reduced_docker)
|
|
1122
1134
|
|
|
1123
1135
|
compacted = cls.compact_test_output(raw, resolved_exit)
|
|
1124
1136
|
if compacted is raw or len(compacted) >= len(raw) * 0.6:
|
|
1125
1137
|
return None
|
|
1126
|
-
return
|
|
1138
|
+
return _accept(compacted)
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Post-compaction recovery: re-orient the model after a host compaction.
|
|
2
|
+
|
|
3
|
+
Claude Code (and compatible hosts) emit ``PreCompact``/``PostCompact`` hooks;
|
|
4
|
+
other hosts only reveal the event as a prompt shrink in their transcript. Both
|
|
5
|
+
paths land here:
|
|
6
|
+
|
|
7
|
+
* ``mark_pending`` writes a short-lived per-session marker;
|
|
8
|
+
* ``build_digest`` reuses the history compactor's orientation digest and adds
|
|
9
|
+
ranked pointers to the turns the compaction dropped;
|
|
10
|
+
* ``consume_digest`` returns the digest once and clears the marker.
|
|
11
|
+
|
|
12
|
+
The digest is deliberately tiny (<= ~1.4 KB): five one-line pointers plus the
|
|
13
|
+
three-line orientation digest. Full turns stay in the transcript and are
|
|
14
|
+
expandable with ``tokensafe recall --id <session>:<index>``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import time
|
|
23
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
|
24
|
+
|
|
25
|
+
from src.paths import resolve_data_dir
|
|
26
|
+
|
|
27
|
+
MARKER_TTL_SECONDS = 900
|
|
28
|
+
DEFAULT_MAX_CHARS = 1400
|
|
29
|
+
MAX_POINTERS = 5
|
|
30
|
+
POINTER_CHARS = 130
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _marker_dir() -> str:
|
|
34
|
+
return os.path.join(resolve_data_dir(), "compaction_pending")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _marker_path(session_id: str) -> str:
|
|
38
|
+
key = hashlib.sha256(str(session_id or "default").encode("utf-8")).hexdigest()[:16]
|
|
39
|
+
return os.path.join(_marker_dir(), f"{key}.json")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def mark_pending(
|
|
43
|
+
session_id: str,
|
|
44
|
+
transcript_path: str = "",
|
|
45
|
+
agent: str = "",
|
|
46
|
+
reason: str = "",
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Arm a one-shot recovery digest for the session (best-effort)."""
|
|
49
|
+
if not session_id:
|
|
50
|
+
return
|
|
51
|
+
try:
|
|
52
|
+
from src.atomic_io import write_text_atomic
|
|
53
|
+
|
|
54
|
+
os.makedirs(_marker_dir(), exist_ok=True)
|
|
55
|
+
payload = {
|
|
56
|
+
"session_id": str(session_id),
|
|
57
|
+
"transcript_path": str(transcript_path or ""),
|
|
58
|
+
"agent": str(agent or ""),
|
|
59
|
+
"reason": str(reason or ""),
|
|
60
|
+
"pending_since_ms": int(time.time() * 1000),
|
|
61
|
+
}
|
|
62
|
+
write_text_atomic(_marker_path(session_id), json.dumps(payload) + "\n")
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def read_pending(session_id: str) -> Optional[Dict[str, Any]]:
|
|
68
|
+
"""Read a fresh marker without consuming it."""
|
|
69
|
+
if not session_id:
|
|
70
|
+
return None
|
|
71
|
+
path = _marker_path(session_id)
|
|
72
|
+
try:
|
|
73
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
74
|
+
payload = json.load(fh)
|
|
75
|
+
except Exception:
|
|
76
|
+
return None
|
|
77
|
+
if not isinstance(payload, dict):
|
|
78
|
+
return None
|
|
79
|
+
age = time.time() - (int(payload.get("pending_since_ms") or 0) / 1000.0)
|
|
80
|
+
if age < 0 or age > MARKER_TTL_SECONDS:
|
|
81
|
+
try:
|
|
82
|
+
os.unlink(path)
|
|
83
|
+
except OSError:
|
|
84
|
+
pass
|
|
85
|
+
return None
|
|
86
|
+
return payload
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def take_pending(session_id: str) -> Optional[Dict[str, Any]]:
|
|
90
|
+
"""Consume a fresh marker; a stale marker is discarded."""
|
|
91
|
+
payload = read_pending(session_id)
|
|
92
|
+
if payload is None:
|
|
93
|
+
return None
|
|
94
|
+
try:
|
|
95
|
+
os.unlink(_marker_path(session_id))
|
|
96
|
+
except OSError:
|
|
97
|
+
pass
|
|
98
|
+
return payload
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def sweep_stale(now: Optional[float] = None) -> int:
|
|
102
|
+
"""Drop markers left behind by sessions that ended between Pre/PostCompact."""
|
|
103
|
+
current = now if now is not None else time.time()
|
|
104
|
+
removed = 0
|
|
105
|
+
try:
|
|
106
|
+
names = os.listdir(_marker_dir())
|
|
107
|
+
except OSError:
|
|
108
|
+
return 0
|
|
109
|
+
for name in names:
|
|
110
|
+
if not name.endswith(".json"):
|
|
111
|
+
continue
|
|
112
|
+
path = os.path.join(_marker_dir(), name)
|
|
113
|
+
try:
|
|
114
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
115
|
+
payload = json.load(fh)
|
|
116
|
+
age = current - (int(payload.get("pending_since_ms") or 0) / 1000.0)
|
|
117
|
+
if age <= MARKER_TTL_SECONDS:
|
|
118
|
+
continue
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
121
|
+
try:
|
|
122
|
+
os.unlink(path)
|
|
123
|
+
removed += 1
|
|
124
|
+
except OSError:
|
|
125
|
+
pass
|
|
126
|
+
return removed
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ---------------------------------------------------------------------------
|
|
130
|
+
# digest
|
|
131
|
+
# ---------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _flatten_ids(value: Any) -> Iterable[str]:
|
|
135
|
+
"""Collect uuid/id strings from a preservedMessages-shaped value."""
|
|
136
|
+
if isinstance(value, str):
|
|
137
|
+
yield value
|
|
138
|
+
return
|
|
139
|
+
if isinstance(value, (list, tuple, set)):
|
|
140
|
+
for item in value:
|
|
141
|
+
yield from _flatten_ids(item)
|
|
142
|
+
return
|
|
143
|
+
if isinstance(value, dict):
|
|
144
|
+
for key in ("uuid", "id", "messageId", "message_id", "turn_id"):
|
|
145
|
+
item = value.get(key)
|
|
146
|
+
if isinstance(item, str) and item:
|
|
147
|
+
yield item
|
|
148
|
+
# The caller only passes preserved*-shaped values, so every nested
|
|
149
|
+
# string/list is part of the preserved set (e.g. {"allUuids": [...]}).
|
|
150
|
+
for item in value.values():
|
|
151
|
+
yield from _flatten_ids(item)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _boundary(records: Sequence[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
155
|
+
for rec in reversed(records):
|
|
156
|
+
if not isinstance(rec, dict):
|
|
157
|
+
continue
|
|
158
|
+
if str(rec.get("type") or "") == "system" and str(rec.get("subtype") or "") == "compact_boundary":
|
|
159
|
+
return rec
|
|
160
|
+
if rec.get("compactMetadata") or rec.get("compact_metadata"):
|
|
161
|
+
return rec
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _preserved_ids(boundary: Optional[Dict[str, Any]]) -> set:
|
|
166
|
+
if not boundary:
|
|
167
|
+
return set()
|
|
168
|
+
ids: set = set()
|
|
169
|
+
for key, value in boundary.items():
|
|
170
|
+
if "preserved" in str(key).lower():
|
|
171
|
+
ids.update(_flatten_ids(value))
|
|
172
|
+
meta = boundary.get("compactMetadata") or boundary.get("compact_metadata") or {}
|
|
173
|
+
if isinstance(meta, dict):
|
|
174
|
+
for key, value in meta.items():
|
|
175
|
+
if "preserved" in str(key).lower():
|
|
176
|
+
ids.update(_flatten_ids(value))
|
|
177
|
+
return ids
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _orientation(records: Sequence[Dict[str, Any]]) -> Dict[str, str]:
|
|
181
|
+
"""Three-line orientation digest from the shared history compactor."""
|
|
182
|
+
try:
|
|
183
|
+
from src.history_compactor import (
|
|
184
|
+
HistoryCompactor,
|
|
185
|
+
_COMMAND_KEYS,
|
|
186
|
+
_COMMAND_TOOLS,
|
|
187
|
+
_EDIT_TOOLS,
|
|
188
|
+
_PATH_KEYS,
|
|
189
|
+
_READ_TOOLS,
|
|
190
|
+
_arg_value,
|
|
191
|
+
_extract_step_tool_calls,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
read_files, edited_files, commands = set(), set(), []
|
|
195
|
+
for rec in records:
|
|
196
|
+
if not isinstance(rec, dict):
|
|
197
|
+
continue
|
|
198
|
+
try:
|
|
199
|
+
calls = _extract_step_tool_calls(rec)
|
|
200
|
+
except Exception:
|
|
201
|
+
continue
|
|
202
|
+
for name, args in calls:
|
|
203
|
+
if name in _READ_TOOLS:
|
|
204
|
+
path = _arg_value(args, _PATH_KEYS)
|
|
205
|
+
if path:
|
|
206
|
+
read_files.add(os.path.basename(path))
|
|
207
|
+
elif name in _EDIT_TOOLS:
|
|
208
|
+
path = _arg_value(args, _PATH_KEYS)
|
|
209
|
+
if path:
|
|
210
|
+
edited_files.add(os.path.basename(path))
|
|
211
|
+
elif name in _COMMAND_TOOLS:
|
|
212
|
+
command = _arg_value(args, _COMMAND_KEYS)
|
|
213
|
+
if command:
|
|
214
|
+
head = command.split()[0] if command.split() else command
|
|
215
|
+
if head not in commands:
|
|
216
|
+
commands.append(head)
|
|
217
|
+
_text, digest = HistoryCompactor.build_orientation_digest(
|
|
218
|
+
list(records), read_files, edited_files, commands
|
|
219
|
+
)
|
|
220
|
+
return digest if isinstance(digest, dict) else {}
|
|
221
|
+
except Exception:
|
|
222
|
+
return {}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _snippet(text: str, limit: int = POINTER_CHARS) -> str:
|
|
226
|
+
clean = " ".join((text or "").split())
|
|
227
|
+
if len(clean) > limit:
|
|
228
|
+
clean = clean[: limit - 1] + "…"
|
|
229
|
+
return clean
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def build_digest(
|
|
233
|
+
transcript_path: str,
|
|
234
|
+
agent: str = "",
|
|
235
|
+
max_chars: int = DEFAULT_MAX_CHARS,
|
|
236
|
+
) -> Optional[str]:
|
|
237
|
+
"""Orientation digest + pointers to the turns the last compaction dropped."""
|
|
238
|
+
if not transcript_path or not os.path.exists(transcript_path):
|
|
239
|
+
return None
|
|
240
|
+
from src.transcript_recall import read_records, rank_turns, turns_from_records
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
records = read_records(transcript_path)
|
|
244
|
+
except Exception:
|
|
245
|
+
return None
|
|
246
|
+
if not records:
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
boundary = _boundary(records)
|
|
250
|
+
preserved = _preserved_ids(boundary)
|
|
251
|
+
boundary_index = int((boundary or {}).get("_record_index") or len(records))
|
|
252
|
+
turns = list(turns_from_records(records, transcript_path, agent))
|
|
253
|
+
if not turns:
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
if boundary is not None:
|
|
257
|
+
candidates = [
|
|
258
|
+
turn for turn in turns
|
|
259
|
+
if turn.record_index < boundary_index
|
|
260
|
+
and (not turn.uuid or turn.uuid not in preserved)
|
|
261
|
+
and turn.key not in preserved
|
|
262
|
+
][-200:]
|
|
263
|
+
else:
|
|
264
|
+
candidates = turns[-40:]
|
|
265
|
+
|
|
266
|
+
orientation = _orientation(records)
|
|
267
|
+
goal = str(orientation.get("active_goal") or "")
|
|
268
|
+
focus = str(orientation.get("next_focus") or "")
|
|
269
|
+
last_user = ""
|
|
270
|
+
first_user = ""
|
|
271
|
+
for turn in turns:
|
|
272
|
+
if turn.role == "user" and turn.text:
|
|
273
|
+
first_user = turn.text
|
|
274
|
+
break
|
|
275
|
+
for turn in reversed(turns):
|
|
276
|
+
if turn.role == "user" and turn.text:
|
|
277
|
+
last_user = turn.text
|
|
278
|
+
break
|
|
279
|
+
# Both the original task and the newest instruction are query terms: the
|
|
280
|
+
# compaction usually drops the earlier goal, which is exactly what must
|
|
281
|
+
# survive.
|
|
282
|
+
query = " ".join(part for part in (goal, focus, first_user[:400], last_user[:400]) if part)
|
|
283
|
+
|
|
284
|
+
ranked = rank_turns(query, candidates, limit=MAX_POINTERS) if candidates else []
|
|
285
|
+
lines: List[str] = ["[TokenSafe Post-Compaction Recovery]"]
|
|
286
|
+
if orientation:
|
|
287
|
+
lines.append(f"Goal: {goal or 'resume the current task'}")
|
|
288
|
+
lines.append(f"Last state: {orientation.get('last_state') or 'previous turns folded'}")
|
|
289
|
+
lines.append(f"Next focus: {focus or 'continue without re-reading folded files'}")
|
|
290
|
+
if ranked:
|
|
291
|
+
lines.append("Dropped context (expand one with tokensafe recall --id <session>:<index>):")
|
|
292
|
+
for _score, turn in ranked:
|
|
293
|
+
line = f"- [{turn.role} #{turn.index}] {_snippet(turn.text or turn.tool_text)} (id {turn.key})"
|
|
294
|
+
if sum(len(part) + 1 for part in lines) + len(line) > max_chars - 40:
|
|
295
|
+
break
|
|
296
|
+
lines.append(line)
|
|
297
|
+
elif not orientation:
|
|
298
|
+
return None
|
|
299
|
+
return "\n".join(lines)[:max_chars]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def consume_digest(
|
|
303
|
+
session_id: str,
|
|
304
|
+
transcript_path: str = "",
|
|
305
|
+
agent: str = "",
|
|
306
|
+
) -> Optional[str]:
|
|
307
|
+
"""Build the digest for a pending compaction once, then clear the marker."""
|
|
308
|
+
marker = take_pending(session_id)
|
|
309
|
+
if marker is None:
|
|
310
|
+
# One-shot: a PostCompact that repeats (or fires without PreCompact)
|
|
311
|
+
# must not re-inject the same pointers every turn.
|
|
312
|
+
return None
|
|
313
|
+
path = str(marker.get("transcript_path") or transcript_path or "")
|
|
314
|
+
if not path:
|
|
315
|
+
return None
|
|
316
|
+
digest = build_digest(path, str((marker or {}).get("agent") or agent or ""))
|
|
317
|
+
if digest:
|
|
318
|
+
try:
|
|
319
|
+
from src.metrics import MetricsTracker
|
|
320
|
+
|
|
321
|
+
tracker = MetricsTracker()
|
|
322
|
+
tracker.record_event(
|
|
323
|
+
session_id=session_id,
|
|
324
|
+
event_type="COMPACTION_RECOVERY",
|
|
325
|
+
original_tokens=0,
|
|
326
|
+
optimized_tokens=0,
|
|
327
|
+
details={
|
|
328
|
+
"agent": (marker or {}).get("agent") or agent,
|
|
329
|
+
"reason": (marker or {}).get("reason") or "",
|
|
330
|
+
"chars": len(digest),
|
|
331
|
+
},
|
|
332
|
+
)
|
|
333
|
+
except Exception:
|
|
334
|
+
pass
|
|
335
|
+
return digest
|