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.
@@ -0,0 +1,158 @@
1
+ """Format invariants and exact-recovery gate for lossy tool-output compaction.
2
+
3
+ A compactor may replace a tool result only when the shape that made it useful
4
+ survives. Three rules:
5
+
6
+ 1. the replacement must be smaller than the original (no inflation);
7
+ 2. structural invariants hold (JSON stays parseable if it was JSON, every diff
8
+ line survives, table headers/columns survive, source declarations survive);
9
+ 3. a lossy structural replacement carries an ``expand_ref`` anchor to the exact
10
+ original (``stash_block``).
11
+
12
+ Callers treat ``gate() -> None`` as "keep the raw output".
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ from typing import Optional, Tuple
20
+
21
+ KIND_JSON = "json"
22
+ KIND_DIFF = "diff"
23
+ KIND_TABLE = "table"
24
+ KIND_SOURCE = "source"
25
+ KIND_LOG = "log"
26
+ KIND_TEXT = "text"
27
+
28
+ _LOSSY_KINDS = frozenset({KIND_JSON, KIND_DIFF, KIND_TABLE, KIND_SOURCE})
29
+ _DECL_RE = re.compile(
30
+ r"^\s*(?:async\s+)?(?:def|class|function|export|import|from|const|let|var|"
31
+ r"public|private|protected|static|func|type|interface|struct|enum|impl|fn)\b"
32
+ )
33
+ _DIFF_PREFIXES = ("diff --git", "index ", "@@", "+", "-", "---", "+++")
34
+
35
+
36
+ def _looks_like_json(raw: str) -> bool:
37
+ head = raw.lstrip()[:1]
38
+ if head not in ("{", "["):
39
+ return False
40
+ try:
41
+ json.loads(raw)
42
+ return True
43
+ except Exception:
44
+ return False
45
+
46
+
47
+ def _looks_like_diff(raw: str) -> bool:
48
+ return "diff --git" in raw or bool(re.search(r"(?m)^@@ .* @@", raw))
49
+
50
+
51
+ def _looks_like_table(raw: str) -> bool:
52
+ lines = [line for line in raw.splitlines() if line.strip()][:6]
53
+ if len(lines) < 2:
54
+ return False
55
+ separator = re.compile(r"^\s*\|?[\s:|-]+\|[\s:|-]*$")
56
+ return sum(1 for line in lines if line.count("|") >= 2) >= 2 and any(
57
+ separator.match(line) for line in lines[1:3]
58
+ )
59
+
60
+
61
+ def _looks_like_source(raw: str) -> bool:
62
+ lines = [line for line in raw.splitlines() if line.strip()]
63
+ if len(lines) < 3:
64
+ return False
65
+ declarations = sum(1 for line in lines if _DECL_RE.match(line))
66
+ if declarations >= 3 and declarations / len(lines) >= 0.25:
67
+ return True
68
+ return lines[0].startswith("#!") and declarations >= 1
69
+
70
+
71
+ def classify_output(raw: str) -> str:
72
+ if not raw:
73
+ return KIND_TEXT
74
+ if _looks_like_json(raw):
75
+ return KIND_JSON
76
+ if _looks_like_diff(raw):
77
+ return KIND_DIFF
78
+ if _looks_like_table(raw):
79
+ return KIND_TABLE
80
+ if _looks_like_source(raw):
81
+ return KIND_SOURCE
82
+ if re.search(r"(?m)^\s*\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}", raw) or raw.count("\n") > 200:
83
+ return KIND_LOG
84
+ return KIND_TEXT
85
+
86
+
87
+ def check_invariant(raw: str, compacted: str, kind: Optional[str] = None) -> Tuple[bool, str]:
88
+ """True when the replacement preserves the raw output's useful shape."""
89
+ kind = kind or classify_output(raw)
90
+ if kind == KIND_JSON:
91
+ if _looks_like_json(compacted):
92
+ return True, "json-parses"
93
+ # A prose summary is allowed only with exact recovery (checked by gate).
94
+ return True, "json-summarized"
95
+ if kind == KIND_DIFF:
96
+ compacted_lines = set(compacted.splitlines())
97
+ missing = [
98
+ line for line in raw.splitlines()
99
+ if line.startswith(_DIFF_PREFIXES) and line.strip() and line not in compacted_lines
100
+ ]
101
+ if missing:
102
+ return False, f"diff line dropped: {missing[0][:80]}"
103
+ return True, "diff-lines-preserved"
104
+ if kind == KIND_TABLE:
105
+ rows = [line for line in raw.splitlines() if line.strip()]
106
+ header = rows[0]
107
+ separator = next((line for line in rows[1:3] if set(line.strip()) <= set("|:- ")), "")
108
+ compacted_lines = compacted.splitlines()
109
+ if not compacted_lines:
110
+ return False, "table replacement is empty"
111
+ if header and header not in compacted:
112
+ return False, "table header dropped"
113
+ if separator and separator not in compacted:
114
+ return False, "table separator dropped"
115
+ if header.count("|") != compacted_lines[0].count("|"):
116
+ return False, "column count changed"
117
+ return True, "table-shape-preserved"
118
+ if kind == KIND_SOURCE:
119
+ compacted_lines = set(compacted.splitlines())
120
+ missing = [
121
+ line for line in raw.splitlines()
122
+ if _DECL_RE.match(line) and line.strip() and line not in compacted_lines
123
+ ]
124
+ if missing:
125
+ return False, f"declaration dropped: {missing[0].strip()[:80]}"
126
+ return True, "declarations-preserved"
127
+ return True, "no-structural-invariant"
128
+
129
+
130
+ def ensure_recovery(raw: str, compacted: str, kind: Optional[str] = None) -> str:
131
+ """Append an exact-recovery anchor when the replacement is structurally lossy."""
132
+ kind = kind or classify_output(raw)
133
+ if kind not in _LOSSY_KINDS:
134
+ return compacted
135
+ try:
136
+ from src.stash import stash_block
137
+
138
+ _hash8, marker = stash_block(raw, source=f"compact:{kind}")
139
+ if not marker:
140
+ return compacted
141
+ candidate = f"{compacted.rstrip()}\n{marker}"
142
+ # Never inflate past the original: the anchor is a safety net, not a tax.
143
+ return candidate if len(candidate) < len(raw) else compacted
144
+ except Exception:
145
+ return compacted
146
+
147
+
148
+ def gate(raw: str, compacted: Optional[str]) -> Optional[str]:
149
+ """Accept, accept-with-anchor, or reject a compacted replacement."""
150
+ if not raw or not compacted or compacted == raw:
151
+ return None
152
+ if len(compacted) >= len(raw):
153
+ return None
154
+ kind = classify_output(raw)
155
+ ok, _reason = check_invariant(raw, compacted, kind)
156
+ if not ok:
157
+ return None
158
+ return ensure_recovery(raw, compacted, kind)
@@ -2197,6 +2197,54 @@ 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_import_neighborhood(self, rel_path: str, limit: int = 40) -> Dict[str, Any]:
2201
+ """Direct importers and imported files for one file (file-level edges).
2202
+
2203
+ Answers "who breaks if I rename/move this?" without a full impact walk,
2204
+ and "what does this file pull in?" without re-reading its imports.
2205
+ """
2206
+ raw = (rel_path or "").strip().replace("\\", "/")
2207
+ if not raw:
2208
+ return {"file": "", "importers": [], "imports": [], "counts": {"importers": 0, "imports": 0}}
2209
+ if os.path.isabs(raw):
2210
+ try:
2211
+ raw = os.path.relpath(raw, self.root_dir)
2212
+ except ValueError:
2213
+ pass
2214
+ raw = os.path.normpath(raw).replace("\\", "/")
2215
+ while raw.startswith("./"):
2216
+ raw = raw[2:]
2217
+ raw = raw.lstrip("/")
2218
+ key = f"file:{raw}"
2219
+
2220
+ def _files(values: Set[str]) -> List[str]:
2221
+ out = []
2222
+ for value in values or set():
2223
+ if isinstance(value, str) and value.startswith("file:"):
2224
+ out.append(value[5:])
2225
+ return sorted(set(out))
2226
+
2227
+ importers = _files(self.rev_edges.get(key, set()))
2228
+ imports = _files(self.edges.get(key, set()))
2229
+
2230
+ def _describe(paths: List[str]) -> List[Dict[str, Any]]:
2231
+ rows = []
2232
+ for path in paths[: max(1, int(limit or 40))]:
2233
+ rows.append({
2234
+ "file": path,
2235
+ "symbols": len(self.file_symbols.get(path, [])),
2236
+ "endpoints": len(self.file_endpoints.get(path, [])),
2237
+ })
2238
+ return rows
2239
+
2240
+ return {
2241
+ "file": raw,
2242
+ "importers": _describe(importers),
2243
+ "imports": _describe(imports),
2244
+ "counts": {"importers": len(importers), "imports": len(imports)},
2245
+ "provenance": "static",
2246
+ }
2247
+
2200
2248
  def get_static_impact(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
2201
2249
  """
2202
2250
  Static impact analysis over the AST graph: reverse-dependency walk
@@ -0,0 +1,180 @@
1
+ """Per-host capability matrix for TokenSafe features.
2
+
3
+ One table answers "what can this host actually enforce?" so the installer
4
+ registers only events the host contract supports and ``tokensafe doctor`` can
5
+ report the truth instead of a wish list.
6
+
7
+ Feature keys
8
+ ------------
9
+ hooks Lifecycle-hook surface installed by TokenSafe.
10
+ precompact Host emits a PreCompact event we can hook.
11
+ postcompact Host emits a PostCompact event we can hook.
12
+ session_injection SessionStart can carry additional context.
13
+ prompt_injection UserPromptSubmit can carry additional context.
14
+ statusline Host exposes a status-line surface.
15
+ transcript Transcript file exists and is parseable by the engine.
16
+ compaction_fallback The usage ledger can infer a compaction from prompt shrink.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any, Dict, List
22
+
23
+ HOST_CAPABILITIES: Dict[str, Dict[str, Any]] = {
24
+ "claude_code": {
25
+ "name": "Claude Code CLI",
26
+ "hooks": True,
27
+ "precompact": True,
28
+ "postcompact": True,
29
+ "session_injection": True,
30
+ "prompt_injection": True,
31
+ "statusline": True,
32
+ "transcript": True,
33
+ "compaction_fallback": True,
34
+ },
35
+ "zcode": {
36
+ "name": "ZCode (Z.ai Code)",
37
+ "hooks": True,
38
+ "precompact": False,
39
+ "postcompact": False,
40
+ "session_injection": True,
41
+ "prompt_injection": True,
42
+ "statusline": False,
43
+ "transcript": True,
44
+ "compaction_fallback": True,
45
+ },
46
+ "kimi": {
47
+ "name": "Kimi Code",
48
+ "hooks": True,
49
+ "precompact": False,
50
+ "postcompact": False,
51
+ "session_injection": True,
52
+ "prompt_injection": True,
53
+ "statusline": False,
54
+ "transcript": True,
55
+ "compaction_fallback": True,
56
+ },
57
+ "antigravity": {
58
+ "name": "Google Antigravity",
59
+ "hooks": True,
60
+ "precompact": False,
61
+ "postcompact": False,
62
+ "session_injection": True,
63
+ "prompt_injection": True,
64
+ "statusline": False,
65
+ "transcript": True,
66
+ "compaction_fallback": True,
67
+ },
68
+ "cursor": {
69
+ "name": "Cursor",
70
+ "hooks": True,
71
+ "precompact": False,
72
+ "postcompact": False,
73
+ "session_injection": False,
74
+ "prompt_injection": False,
75
+ "statusline": False,
76
+ "transcript": True,
77
+ "compaction_fallback": True,
78
+ },
79
+ "codex": {
80
+ "name": "OpenAI Codex",
81
+ "hooks": False,
82
+ "precompact": False,
83
+ "postcompact": False,
84
+ "session_injection": False,
85
+ "prompt_injection": False,
86
+ "statusline": False,
87
+ "transcript": True,
88
+ "compaction_fallback": True,
89
+ },
90
+ "claude_desktop": {
91
+ "name": "Claude Desktop",
92
+ "hooks": False,
93
+ "precompact": False,
94
+ "postcompact": False,
95
+ "session_injection": False,
96
+ "prompt_injection": False,
97
+ "statusline": False,
98
+ "transcript": False,
99
+ "compaction_fallback": False,
100
+ },
101
+ "windsurf": {
102
+ "name": "Windsurf",
103
+ "hooks": False,
104
+ "precompact": False,
105
+ "postcompact": False,
106
+ "session_injection": False,
107
+ "prompt_injection": False,
108
+ "statusline": False,
109
+ "transcript": False,
110
+ "compaction_fallback": False,
111
+ },
112
+ "cline": {
113
+ "name": "Cline / Roo Code",
114
+ "hooks": False,
115
+ "precompact": False,
116
+ "postcompact": False,
117
+ "session_injection": False,
118
+ "prompt_injection": False,
119
+ "statusline": False,
120
+ "transcript": False,
121
+ "compaction_fallback": False,
122
+ },
123
+ "copilot": {
124
+ "name": "GitHub Copilot",
125
+ "hooks": False,
126
+ "precompact": False,
127
+ "postcompact": False,
128
+ "session_injection": False,
129
+ "prompt_injection": False,
130
+ "statusline": False,
131
+ "transcript": False,
132
+ "compaction_fallback": False,
133
+ },
134
+ }
135
+
136
+ # Aliases used by hooks and CLI entry points.
137
+ ALIASES = {
138
+ "claude": "claude_code",
139
+ "claude-code": "claude_code",
140
+ "kimi_code": "kimi",
141
+ "kimi-code": "kimi",
142
+ "agy": "antigravity",
143
+ "roo": "cline",
144
+ "roo_code": "cline",
145
+ "cline_roo": "cline",
146
+ }
147
+
148
+
149
+ def canonical(host: str) -> str:
150
+ key = (host or "").strip().lower().replace(" ", "_")
151
+ return ALIASES.get(key, key)
152
+
153
+
154
+ def capabilities(host: str) -> Dict[str, Any]:
155
+ """Capability dict for a host; unknown hosts answer all-False."""
156
+ return dict(HOST_CAPABILITIES.get(canonical(host), {}))
157
+
158
+
159
+ def supports(host: str, feature: str) -> bool:
160
+ return bool(capabilities(host).get(feature, False))
161
+
162
+
163
+ def matrix_rows() -> List[Dict[str, Any]]:
164
+ """Stable rows for doctor/README rendering."""
165
+ rows = []
166
+ for key, caps in HOST_CAPABILITIES.items():
167
+ rows.append({"host": key, **caps})
168
+ return rows
169
+
170
+
171
+ def summarize(host: str) -> str:
172
+ """One-line human summary used by `tokensafe doctor`."""
173
+ caps = capabilities(host)
174
+ if not caps:
175
+ return f"{host}: unknown host"
176
+ enabled = [name for name in (
177
+ "precompact", "postcompact", "session_injection", "prompt_injection",
178
+ "statusline", "transcript", "compaction_fallback",
179
+ ) if caps.get(name)]
180
+ return f"{caps.get('name', host)}: hooks={bool(caps.get('hooks'))} · " + ", ".join(enabled)
package/src/installer.py CHANGED
@@ -399,7 +399,8 @@ class AgentInstaller:
399
399
  Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
400
400
  if agent_key == "codex":
401
401
  return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
402
- if agent_key not in ("claude_code", "cursor", "kimi", "zcode"):
402
+ from src.host_capabilities import supports
403
+ if not supports(agent_key, "hooks"):
403
404
  return False, "hooks not applicable for this agent"
404
405
 
405
406
  claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
@@ -475,6 +476,24 @@ class AgentInstaller:
475
476
  data, err = cls._load_json_with_backup(config_file)
476
477
  if err or data is None:
477
478
  return False, err or f"Failed to parse {config_file}"
479
+ # Zero-token savings statusline: register only when the field is free
480
+ # or already ours; a user's custom statusline is left untouched.
481
+ status_cmd = quote_hook_command([
482
+ PYTHON_BIN,
483
+ os.path.join(PROJECT_ROOT, "bin", "tokensafe"),
484
+ "statusline",
485
+ ])
486
+ current_status = data.get("statusLine")
487
+ status_owned = (
488
+ isinstance(current_status, dict)
489
+ and "tokensafe" in str(current_status.get("command", "")).lower()
490
+ )
491
+ status_changed = False
492
+ if (not current_status or status_owned) and (
493
+ not isinstance(current_status, dict) or current_status.get("command") != status_cmd
494
+ ):
495
+ data["statusLine"] = {"type": "command", "command": status_cmd, "padding": 0}
496
+ status_changed = True
478
497
  hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
479
498
  prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
480
499
  bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
@@ -490,6 +509,11 @@ class AgentInstaller:
490
509
  # transcript (opt-in via TOKENSAFE_FOLD_AT_REST=1; the hook itself
491
510
  # is a no-op while the flag is off).
492
511
  stop_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 15}]}
512
+ # Compaction survival: PreCompact arms the marker, PostCompact
513
+ # injects the recovery digest (one-shot). Hosts without these events
514
+ # fall back to the usage-ledger prompt-shrink detector.
515
+ precompact_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
516
+ postcompact_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
493
517
 
494
518
  def _sync_claude_event(event_name: str, default_entry: dict) -> bool:
495
519
  entries = hooks.get(event_name)
@@ -527,13 +551,15 @@ class AgentInstaller:
527
551
  _sync_claude_event("PreToolUse", stale_edit_entry),
528
552
  _sync_claude_event("PostToolUse", post_bash_entry),
529
553
  _sync_claude_event("PostToolUse", post_track_entry),
554
+ _sync_claude_event("PreCompact", precompact_entry),
555
+ _sync_claude_event("PostCompact", postcompact_entry),
530
556
  _sync_claude_event("Stop", stop_entry),
531
- ])
557
+ ]) or status_changed
532
558
  if not changed:
533
559
  return True, "TokenSafe Claude Code hooks already registered"
534
560
  data["hooks"] = hooks
535
561
  cls._atomic_write_json(config_file, data)
536
- return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write/stale + PostToolUse compact/tracking + Stop fold-at-rest)"
562
+ return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write/stale + PostToolUse compact/tracking + PreCompact/PostCompact recovery + Stop fold-at-rest)"
537
563
 
538
564
  if agent_key == "zcode":
539
565
  config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
@@ -689,8 +715,16 @@ class AgentInstaller:
689
715
  data, err = cls._load_json_with_backup(config_file)
690
716
  if err or data is None:
691
717
  return False, err or f"Failed to parse {config_file}"
718
+ status_changed = False
719
+ current_status = data.get("statusLine")
720
+ if isinstance(current_status, dict) and "tokensafe" in str(current_status.get("command", "")).lower():
721
+ data.pop("statusLine", None)
722
+ status_changed = True
692
723
  hooks = data.get("hooks")
693
724
  if not isinstance(hooks, dict):
725
+ if status_changed:
726
+ cls._atomic_write_json(config_file, data)
727
+ return True, "Removed TokenSafe status line from Claude Code settings.json"
694
728
  return True, "No hooks in Claude Code settings.json"
695
729
 
696
730
  changed = False
@@ -718,13 +752,13 @@ class AgentInstaller:
718
752
  hooks.pop(event_name, None)
719
753
  changed = True
720
754
 
721
- if changed:
755
+ if changed or status_changed:
722
756
  if not hooks:
723
757
  data.pop("hooks", None)
724
758
  else:
725
759
  data["hooks"] = hooks
726
760
  cls._atomic_write_json(config_file, data)
727
- return True, "Removed TokenSafe hooks from Claude Code settings.json"
761
+ return True, "Removed TokenSafe hooks/status line from Claude Code settings.json"
728
762
  return True, "No TokenSafe hooks found in Claude Code settings.json"
729
763
 
730
764
  if agent_key == "zcode":