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
@@ -3,11 +3,15 @@ History Compactor: Summarizes older multi-turn tool interactions in Antigravity
3
3
  into a dense Consolidated State Ledger (CSL), eliminating the quadratic context explosion.
4
4
  """
5
5
 
6
+ import copy
6
7
  import os
7
8
  import json
8
9
  import re
10
+ import threading
11
+ import time
12
+ from collections import OrderedDict
9
13
  from typing import Dict, Any, Optional, List, Tuple
10
- from src.tokenizer import count_tokens
14
+ from tokensafe.tokenizer import count_tokens
11
15
 
12
16
 
13
17
  def _block_text(content: Any) -> str:
@@ -275,10 +279,66 @@ _INJECTED_PROMPT_MARKERS = (
275
279
  )
276
280
 
277
281
 
282
+ # Harness messages that arrive with the user role but were not typed by the
283
+ # user. Matched at the start only: a user may paste such text mid-prompt.
284
+ _INJECTED_PROMPT_PREFIXES = (
285
+ "<local-command",
286
+ "<command-name>",
287
+ "<command-message>",
288
+ "<task-notification",
289
+ "<agent-message",
290
+ "<side-sessions-event",
291
+ "<ci-monitor-event",
292
+ "[request interrupted",
293
+ "caveat: the messages below were generated",
294
+ "this session is being continued from a previous conversation",
295
+ )
296
+
297
+
278
298
  def _is_injected_prompt(text: str) -> bool:
279
299
  """True for harness-injected reminders that arrive as user-role messages."""
280
300
  lowered = text.lower()
281
- return any(marker in lowered for marker in _INJECTED_PROMPT_MARKERS)
301
+ if any(marker in lowered for marker in _INJECTED_PROMPT_MARKERS):
302
+ return True
303
+ return lowered.lstrip().startswith(_INJECTED_PROMPT_PREFIXES)
304
+
305
+
306
+ def _typed_text(blocks: Any) -> str:
307
+ """Text the author typed: text blocks only, never tool results."""
308
+ if isinstance(blocks, str):
309
+ return blocks
310
+ if not isinstance(blocks, list):
311
+ return ""
312
+ parts: List[str] = []
313
+ for block in blocks:
314
+ if isinstance(block, str):
315
+ parts.append(block)
316
+ elif isinstance(block, dict) and block.get("type") in (None, "text", "input_text"):
317
+ t = block.get("text")
318
+ if isinstance(t, str) and t:
319
+ parts.append(t)
320
+ return " ".join(parts).strip()
321
+
322
+
323
+ def _goal_text(step: dict) -> str:
324
+ """The prompt a user step carries, or "" when the step is not a prompt.
325
+
326
+ Claude Code (and the Anthropic message format generally) sends every tool
327
+ result back as a user-role message, so "the last user message" was most
328
+ often a tool's output; meta and tool-result records are skipped, and
329
+ only typed text blocks count.
330
+ """
331
+ if not isinstance(step, dict):
332
+ return ""
333
+ if step.get("isMeta") or step.get("toolUseResult") is not None:
334
+ return ""
335
+ message = step.get("message")
336
+ if isinstance(message, dict) and "content" in message:
337
+ return _typed_text(message.get("content"))
338
+ content = step.get("content")
339
+ if isinstance(content, list):
340
+ return _typed_text(content)
341
+ return _extract_step_text(step)
282
342
 
283
343
 
284
344
  def _clean_goal_text(text: str) -> str:
@@ -286,7 +346,7 @@ def _clean_goal_text(text: str) -> str:
286
346
  if not text:
287
347
  return ""
288
348
  # Strip XML-style wrapper tags commonly injected into agent transcripts
289
- cleaned = re.sub(r"</?(?:USER_REQUEST|CONTEXT_SUMMARY|ADDITIONAL_METADATA|SYSTEM_MESSAGE)[^>]*>", " ", text)
349
+ cleaned = re.sub(r"</?(?:USER_REQUEST|CONTEXT_SUMMARY|ADDITIONAL_METADATA|SYSTEM_MESSAGE|pasted_content)[^>]*>", " ", text)
290
350
  # Remove markdown headers or bolding
291
351
  cleaned = re.sub(r"^[#\s*\->]+", "", cleaned.strip())
292
352
  # Take first meaningful non-empty line
@@ -300,73 +360,172 @@ def _clean_goal_text(text: str) -> str:
300
360
  first_line = first_line[:117] + "..."
301
361
  return first_line
302
362
 
363
+ def _step_role(step: dict) -> str:
364
+ role = str(step.get("role") or "")
365
+ if not role and isinstance(step.get("message"), dict):
366
+ role = str(step["message"].get("role") or "")
367
+ return role
368
+
369
+
370
+ def _is_user_step(step: dict) -> bool:
371
+ return (
372
+ str(step.get("source") or "") == "USER_EXPLICIT"
373
+ or str(step.get("type") or "") == "USER_INPUT"
374
+ or _step_role(step) == "user"
375
+ )
376
+
377
+
378
+ def _tool_summary(tool: Optional[Tuple[str, dict]]) -> Optional[Dict[str, str]]:
379
+ """The parts of a tool call the digest uses, small enough to persist."""
380
+ if not tool:
381
+ return None
382
+ name, args = tool
383
+ return {
384
+ "name": str(name),
385
+ "path": _arg_value(args, _PATH_KEYS),
386
+ "cmd": _arg_value(args, _COMMAND_KEYS),
387
+ }
388
+
389
+
390
+ _FOLD_STATE_VERSION = 2
391
+ _FOLD_CACHE_MAX = 16
392
+ _FOLD_HEAD_BYTES = 256
393
+ _FOLD_TAIL_BYTES = 64
394
+ _FOLD_STATE_MAX_AGE = 14 * 86400
395
+
396
+
397
+ def _new_fold_state() -> Dict[str, Any]:
398
+ return {
399
+ "v": _FOLD_STATE_VERSION,
400
+ "ino": None,
401
+ "offset": 0,
402
+ "head": "",
403
+ "tail": "",
404
+ "lines": 0,
405
+ "steps": 0,
406
+ "orig_tokens": 0,
407
+ "read_files": [],
408
+ "edited_files": [],
409
+ "executed_commands": [],
410
+ "key_turns": [],
411
+ "goal": "",
412
+ "fallback_goal": "",
413
+ "last_tool": None,
414
+ }
415
+
416
+
417
+ def _apply_transcript_line(state: Dict[str, Any], line: str) -> None:
418
+ """Folds one transcript line into the running state. Mirrors what the
419
+ whole-file pass computed, so the result does not depend on how the file
420
+ was split into reads."""
421
+ line = line.strip()
422
+ if not line:
423
+ return
424
+ state["lines"] += 1
425
+ try:
426
+ step = json.loads(line)
427
+ except Exception:
428
+ return
429
+ state["steps"] += 1
430
+ if not isinstance(step, dict):
431
+ return
432
+ # A model-io record whose newest message is the user's prompt is the turn
433
+ # boundary the digest looks for.
434
+ if step.get("type") == "model_io" and _model_io_parts(step)[2]:
435
+ step["role"] = "user"
436
+
437
+ text = _extract_step_text(step)
438
+ if text:
439
+ state["orig_tokens"] += count_tokens(text)
440
+ if len(state["key_turns"]) < 5:
441
+ first_ln = text.splitlines()[0].strip()
442
+ if len(first_ln) > 8:
443
+ state["key_turns"].append(first_ln[:100])
444
+
445
+ if _is_user_step(step):
446
+ prompt = _goal_text(step)
447
+ if prompt and not _is_injected_prompt(prompt):
448
+ cleaned = _clean_goal_text(prompt)
449
+ if cleaned:
450
+ state["goal"] = cleaned
451
+ if not state["fallback_goal"] and not _is_injected_prompt(text):
452
+ cleaned = _clean_goal_text(text)
453
+ if cleaned and len(cleaned) > 15:
454
+ state["fallback_goal"] = cleaned
455
+
456
+ calls = _extract_step_tool_calls(step)
457
+ if calls:
458
+ state["last_tool"] = _tool_summary(calls[-1])
459
+ for name, args in calls:
460
+ if name in _READ_TOOLS:
461
+ p = _arg_value(args, _PATH_KEYS)
462
+ if p:
463
+ base = os.path.basename(p)
464
+ if base not in state["read_files"]:
465
+ state["read_files"].append(base)
466
+ elif name in _EDIT_TOOLS:
467
+ p = _arg_value(args, _PATH_KEYS)
468
+ if p:
469
+ base = os.path.basename(p)
470
+ if base not in state["edited_files"]:
471
+ state["edited_files"].append(base)
472
+ elif name in _COMMAND_TOOLS:
473
+ cmd = _arg_value(args, _COMMAND_KEYS)
474
+ if cmd:
475
+ clean_cmd = cmd.split()[0] if cmd.split() else cmd
476
+ if clean_cmd not in state["executed_commands"]:
477
+ state["executed_commands"].append(clean_cmd)
478
+
479
+
480
+ def _apply_transcript_bytes(state: Dict[str, Any], data: bytes) -> None:
481
+ text = data.decode("utf-8", errors="replace")
482
+ # Text-mode reads used universal newlines; keep the same line split.
483
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
484
+ for line in text.split("\n"):
485
+ _apply_transcript_line(state, line)
486
+
487
+
488
+ def _fold_state_dir() -> str:
489
+ from tokensafe.paths import resolve_data_dir
490
+ return os.path.join(resolve_data_dir(), "fold_state")
491
+
492
+
493
+ def _fold_state_file(key: str) -> str:
494
+ import hashlib
495
+ digest = hashlib.sha1(key.encode("utf-8", "surrogatepass")).hexdigest()[:24]
496
+ return os.path.join(_fold_state_dir(), digest + ".json")
497
+
498
+
303
499
  class HistoryCompactor:
304
500
  """Folds past conversation tool steps into a compact state ledger with an orientation digest."""
305
501
 
306
- @classmethod
307
- def build_orientation_digest(
308
- cls,
309
- steps: List[dict],
310
- read_files: set,
311
- edited_files: set,
312
- executed_commands: List[str]
502
+ # Per-transcript running fold state: (byte offset of the last complete
503
+ # line, aggregates of every line before it). A prompt hook that re-read
504
+ # the whole transcript on every turn did O(n^2) work over a session.
505
+ _fold_cache: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()
506
+ _fold_lock = threading.Lock()
507
+
508
+ @staticmethod
509
+ def _compose_digest(
510
+ active_goal: str,
511
+ last_tool: Optional[Dict[str, str]],
512
+ read_files,
513
+ edited_files,
514
+ executed_commands: List[str],
313
515
  ) -> Tuple[str, Dict[str, str]]:
314
- """
315
- Builds a concise 3-line Post-Compaction Orientation Digest:
316
- 1. Active Goal: extracted from latest user prompt
317
- 2. Last State: the most recent action/operation performed
318
- 3. Next Focus: clear immediate resumption directive
319
- """
320
- # 1. Active Goal
321
- active_goal = ""
322
- for step in reversed(steps):
323
- source = str(step.get("source") or "")
324
- stype = str(step.get("type") or "")
325
- role = str(step.get("role") or "")
326
- if not role and isinstance(step.get("message"), dict):
327
- role = str(step["message"].get("role") or "")
328
-
329
- if source == "USER_EXPLICIT" or stype == "USER_INPUT" or role == "user":
330
- raw_txt = _extract_step_text(step)
331
- if _is_injected_prompt(raw_txt):
332
- continue
333
- cleaned = _clean_goal_text(raw_txt)
334
- if cleaned:
335
- active_goal = cleaned
336
- break
337
-
338
- if not active_goal:
339
- # Fallback to key turns if any
340
- for step in steps:
341
- raw_txt = _extract_step_text(step)
342
- if _is_injected_prompt(raw_txt):
343
- continue
344
- cleaned = _clean_goal_text(raw_txt)
345
- if cleaned and len(cleaned) > 15:
346
- active_goal = cleaned
347
- break
348
-
349
516
  if not active_goal:
350
517
  active_goal = "Resume multi-step task execution"
351
518
 
352
519
  # 2. Last State
353
520
  last_state = ""
354
- last_tool = None
355
- # Find the last tool call executed across all steps
356
- for step in reversed(steps):
357
- tcs = _extract_step_tool_calls(step)
358
- if tcs:
359
- last_tool = tcs[-1]
360
- break
361
-
362
521
  if last_tool:
363
- tname, targs = last_tool
364
- p = _arg_value(targs, _PATH_KEYS)
522
+ tname = last_tool.get("name") or ""
523
+ p = last_tool.get("path") or ""
365
524
  base_p = os.path.basename(p) if p else ""
366
525
  if tname in _EDIT_TOOLS:
367
526
  last_state = f"Modified {base_p or 'target files'}; changes applied"
368
527
  elif tname in _COMMAND_TOOLS:
369
- cmd = _arg_value(targs, _COMMAND_KEYS)
528
+ cmd = last_tool.get("cmd") or ""
370
529
  short_cmd = cmd.split()[0] if cmd.split() else cmd
371
530
  last_state = f"Executed {short_cmd}; output processed"
372
531
  elif tname in _READ_TOOLS:
@@ -409,33 +568,193 @@ class HistoryCompactor:
409
568
  return "\n".join(digest_lines), digest_dict
410
569
 
411
570
  @classmethod
412
- def measure_transcript(cls, transcript_path: str) -> int:
571
+ def build_orientation_digest(
572
+ cls,
573
+ steps: List[dict],
574
+ read_files: set,
575
+ edited_files: set,
576
+ executed_commands: List[str]
577
+ ) -> Tuple[str, Dict[str, str]]:
578
+ """
579
+ Builds a concise 3-line Post-Compaction Orientation Digest:
580
+ 1. Active Goal: extracted from latest user prompt
581
+ 2. Last State: the most recent action/operation performed
582
+ 3. Next Focus: clear immediate resumption directive
583
+ """
584
+ # 1. Active Goal
585
+ active_goal = ""
586
+ for step in reversed(steps):
587
+ if _is_user_step(step):
588
+ raw_txt = _goal_text(step)
589
+ if not raw_txt or _is_injected_prompt(raw_txt):
590
+ continue
591
+ cleaned = _clean_goal_text(raw_txt)
592
+ if cleaned:
593
+ active_goal = cleaned
594
+ break
595
+
596
+ if not active_goal:
597
+ # Fallback to key turns if any
598
+ for step in steps:
599
+ raw_txt = _extract_step_text(step)
600
+ if _is_injected_prompt(raw_txt):
601
+ continue
602
+ cleaned = _clean_goal_text(raw_txt)
603
+ if cleaned and len(cleaned) > 15:
604
+ active_goal = cleaned
605
+ break
606
+
607
+ last_tool = None
608
+ # Find the last tool call executed across all steps
609
+ for step in reversed(steps):
610
+ tcs = _extract_step_tool_calls(step)
611
+ if tcs:
612
+ last_tool = _tool_summary(tcs[-1])
613
+ break
614
+
615
+ return cls._compose_digest(active_goal, last_tool, read_files, edited_files, executed_commands)
616
+
617
+ # ------------------------------------------------------------------
618
+ # Incremental transcript state
619
+
620
+ @staticmethod
621
+ def _read_span(fh, start: int, length: int) -> bytes:
622
+ if length <= 0:
623
+ return b""
624
+ fh.seek(max(0, start))
625
+ return fh.read(length)
626
+
627
+ @classmethod
628
+ def _state_matches(cls, state: Dict[str, Any], fh, st) -> bool:
629
+ import hashlib
630
+ if not isinstance(state, dict) or state.get("v") != _FOLD_STATE_VERSION:
631
+ return False
632
+ if state.get("ino") != [st.st_dev, st.st_ino]:
633
+ return False
634
+ offset = state.get("offset")
635
+ if not isinstance(offset, int) or offset < 0 or offset > st.st_size:
636
+ return False
637
+ head = cls._read_span(fh, 0, min(_FOLD_HEAD_BYTES, offset))
638
+ tail_start = max(0, offset - _FOLD_TAIL_BYTES)
639
+ tail = cls._read_span(fh, tail_start, offset - tail_start)
640
+ return (
641
+ hashlib.sha1(head).hexdigest() == state.get("head")
642
+ and hashlib.sha1(tail).hexdigest() == state.get("tail")
643
+ )
644
+
645
+ @classmethod
646
+ def _stamp(cls, state: Dict[str, Any], fh, st) -> None:
647
+ import hashlib
648
+ offset = state["offset"]
649
+ state["ino"] = [st.st_dev, st.st_ino]
650
+ state["head"] = hashlib.sha1(cls._read_span(fh, 0, min(_FOLD_HEAD_BYTES, offset))).hexdigest()
651
+ tail_start = max(0, offset - _FOLD_TAIL_BYTES)
652
+ state["tail"] = hashlib.sha1(cls._read_span(fh, tail_start, offset - tail_start)).hexdigest()
653
+
654
+ @staticmethod
655
+ def _load_state(key: str) -> Optional[Dict[str, Any]]:
656
+ try:
657
+ with open(_fold_state_file(key), "r", encoding="utf-8") as f:
658
+ data = json.load(f)
659
+ return data if isinstance(data, dict) else None
660
+ except Exception:
661
+ return None
662
+
663
+ @staticmethod
664
+ def _save_state(key: str, state: Dict[str, Any]) -> None:
665
+ try:
666
+ path = _fold_state_file(key)
667
+ folder = os.path.dirname(path)
668
+ os.makedirs(folder, exist_ok=True)
669
+ if not os.path.exists(path):
670
+ # A new session: drop state files nobody has touched for weeks.
671
+ cutoff = time.time() - _FOLD_STATE_MAX_AGE
672
+ for name in os.listdir(folder):
673
+ old = os.path.join(folder, name)
674
+ try:
675
+ if name.endswith(".json") and os.path.getmtime(old) < cutoff:
676
+ os.remove(old)
677
+ except OSError:
678
+ pass
679
+ tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.tmp"
680
+ with open(tmp, "w", encoding="utf-8") as f:
681
+ json.dump(state, f, ensure_ascii=False)
682
+ os.replace(tmp, path)
683
+ except Exception:
684
+ pass
685
+
686
+ @classmethod
687
+ def _transcript_state(cls, transcript_path: str, persist: bool = False) -> Optional[Dict[str, Any]]:
688
+ """Running fold state for the whole transcript, reading only the bytes
689
+ appended since the last call. A rewritten, truncated or replaced file
690
+ is detected (inode, size, hashes of the head and of the bytes before
691
+ the saved offset) and re-read from the start. With persist=True the
692
+ state also survives across processes (one hook process per prompt).
693
+ Returns None when the file cannot be read."""
694
+ if not transcript_path:
695
+ return None
696
+ key = os.path.abspath(transcript_path)
697
+ try:
698
+ with open(transcript_path, "rb") as fh:
699
+ st = os.fstat(fh.fileno())
700
+ with cls._fold_lock:
701
+ state = cls._fold_cache.get(key)
702
+ if state is not None:
703
+ cls._fold_cache.move_to_end(key)
704
+ if state is not None and not cls._state_matches(state, fh, st):
705
+ state = None
706
+ if state is None and persist:
707
+ state = cls._load_state(key)
708
+ if state is not None and not cls._state_matches(state, fh, st):
709
+ state = None
710
+ fresh = state is None
711
+ state = copy.deepcopy(state) if state is not None else _new_fold_state()
712
+ offset = state["offset"]
713
+ fh.seek(offset)
714
+ data = fh.read(max(0, st.st_size - offset))
715
+ cut = data.rfind(b"\n") + 1
716
+ complete, partial = data[:cut], data[cut:]
717
+ changed = bool(complete) or fresh
718
+ if changed:
719
+ _apply_transcript_bytes(state, complete)
720
+ state["offset"] = offset + len(complete)
721
+ cls._stamp(state, fh, st)
722
+ with cls._fold_lock:
723
+ cls._fold_cache[key] = state
724
+ cls._fold_cache.move_to_end(key)
725
+ while len(cls._fold_cache) > _FOLD_CACHE_MAX:
726
+ cls._fold_cache.popitem(last=False)
727
+ if changed and persist:
728
+ cls._save_state(key, state)
729
+ except Exception:
730
+ return None
731
+ if partial.strip():
732
+ # A last line without its newline still counts (as the whole-file
733
+ # read did); it is not cached, since the writer may still be
734
+ # appending to it.
735
+ state = copy.deepcopy(state)
736
+ _apply_transcript_bytes(state, partial)
737
+ return state
738
+
739
+ @classmethod
740
+ def transcript_turns(cls, transcript_path: str, persist: bool = False) -> int:
741
+ """Number of non-empty transcript lines, counted incrementally."""
742
+ state = cls._transcript_state(transcript_path, persist=persist)
743
+ return int(state["lines"]) if state else 0
744
+
745
+ @classmethod
746
+ def measure_transcript(cls, transcript_path: str, persist: bool = False) -> int:
413
747
  """Lightweight transcript mass probe: returns the token count of all
414
748
  step content without building a ledger. Used by the Context Budget HUD
415
749
  to count REAL history mass on early turns where the full fold is not
416
750
  yet active (< 3 turns) and by hooks that only need the estimate."""
417
751
  if not transcript_path or not os.path.exists(transcript_path):
418
752
  return 0
419
- total = 0
420
- try:
421
- with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
422
- for line in f:
423
- line = line.strip()
424
- if not line:
425
- continue
426
- try:
427
- step = json.loads(line)
428
- except Exception:
429
- continue
430
- text = _extract_step_text(step)
431
- if text:
432
- total += count_tokens(text)
433
- except Exception:
434
- return 0
435
- return total
753
+ state = cls._transcript_state(transcript_path, persist=persist)
754
+ return int(state["orig_tokens"]) if state else 0
436
755
 
437
756
  @classmethod
438
- def fold_transcript(cls, transcript_path: str, invocation_num: int) -> Tuple[Optional[str], int, int, Dict[str, Any]]:
757
+ def fold_transcript(cls, transcript_path: str, invocation_num: int, persist: bool = False) -> Tuple[Optional[str], int, int, Dict[str, Any]]:
439
758
  """
440
759
  Parses transcriptPath and generates a Consolidated State Ledger if turns >= 3.
441
760
  Returns: (consolidated_ledger, orig_history_tokens, folded_tokens, stats_dict)
@@ -443,72 +762,27 @@ class HistoryCompactor:
443
762
  if invocation_num < 3 or not transcript_path or not os.path.exists(transcript_path):
444
763
  return None, 0, 0, {}
445
764
 
446
- try:
447
- steps = []
448
- with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
449
- for line in f:
450
- line = line.strip()
451
- if line:
452
- try:
453
- parsed = json.loads(line)
454
- except Exception:
455
- continue
456
- # A model-io record whose newest message is the user's
457
- # prompt is the turn boundary the digest looks for.
458
- if (
459
- isinstance(parsed, dict)
460
- and parsed.get("type") == "model_io"
461
- and _model_io_parts(parsed)[2]
462
- ):
463
- parsed["role"] = "user"
464
- steps.append(parsed)
465
- except Exception:
466
- return None, 0, 0, {}
467
-
468
- if len(steps) < 4:
765
+ state = cls._transcript_state(transcript_path, persist=persist)
766
+ if state is None or state["steps"] < 4:
469
767
  return None, 0, 0, {}
470
768
 
471
- read_files = set()
472
- edited_files = set()
473
- executed_commands = []
474
- key_turns: List[str] = []
475
- orig_tokens = 0
476
-
477
- for step in steps:
478
- if not isinstance(step, dict):
479
- continue
480
- text = _extract_step_text(step)
481
- if text:
482
- orig_tokens += count_tokens(text)
483
- if len(key_turns) < 5:
484
- first_ln = text.splitlines()[0].strip()
485
- if len(first_ln) > 8:
486
- key_turns.append(first_ln[:100])
487
-
488
- # Inspect tool calls (Antigravity tool_calls / Claude Code tool_use)
489
- for name, args in _extract_step_tool_calls(step):
490
- if name in _READ_TOOLS:
491
- p = _arg_value(args, _PATH_KEYS)
492
- if p:
493
- read_files.add(os.path.basename(p))
494
- elif name in _EDIT_TOOLS:
495
- p = _arg_value(args, _PATH_KEYS)
496
- if p:
497
- edited_files.add(os.path.basename(p))
498
- elif name in _COMMAND_TOOLS:
499
- cmd = _arg_value(args, _COMMAND_KEYS)
500
- if cmd:
501
- clean_cmd = cmd.split()[0] if cmd.split() else cmd
502
- if clean_cmd not in executed_commands:
503
- executed_commands.append(clean_cmd)
769
+ read_files = set(state["read_files"])
770
+ edited_files = set(state["edited_files"])
771
+ executed_commands = list(state["executed_commands"])
772
+ key_turns = list(state["key_turns"])
773
+ orig_tokens = int(state["orig_tokens"])
504
774
 
505
775
  # Only fold if history has accumulated significant mass (> 1,000 tokens)
506
776
  if orig_tokens < 1000:
507
777
  return None, 0, 0, {}
508
778
 
509
779
  # Build Consolidated State Ledger & Post-Compaction Orientation Digest
510
- digest_text, digest_dict = cls.build_orientation_digest(
511
- steps, read_files, edited_files, executed_commands
780
+ digest_text, digest_dict = cls._compose_digest(
781
+ state["goal"] or state["fallback_goal"],
782
+ state["last_tool"],
783
+ read_files,
784
+ edited_files,
785
+ executed_commands,
512
786
  )
513
787
 
514
788
  ledger_lines = ["[TOCP State Ledger]:"]