vexel-cli 0.1.0__tar.gz

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,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: vexel-cli
3
+ Version: 0.1.0
4
+ Summary: Deterministic context pruning for LLM agent loops — zero API dependencies
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+
9
+ # vexel-cli
10
+
11
+ Deterministic context pruning for LLM agent loops — zero API dependencies.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ uv tool install vexel-cli
17
+ ```
18
+
19
+ ## Commands
20
+
21
+ | Command | Description |
22
+ |---------|-------------|
23
+ | `vexel prune [file]` | Prune text from file or stdin |
24
+ | `vexel wrap -- <cmd>` | Run a command and prune its output |
25
+ | `vexel hook-post-tool` | PostToolUse hook (reads JSON from stdin) |
26
+ | `vexel install [--target cursor\|claude\|all]` | Install IDE configs |
27
+ | `vexel stats` | Show cumulative token savings |
28
+
29
+ ## Examples
30
+
31
+ ```bash
32
+ # Prune a noisy build log
33
+ vexel prune build.log
34
+
35
+ # JSON telemetry
36
+ cat output.txt | vexel prune --json
37
+
38
+ # Wrap a noisy test run so the IDE gets clean output
39
+ vexel wrap -- pytest -x --tb=long
40
+
41
+ # Install Vexel hooks into your project
42
+ vexel install
43
+ vexel install --target cursor
44
+ vexel install --global --target claude
45
+ ```
46
+
47
+ ## How it works
48
+
49
+ Vexel's pruning is fully deterministic (no LLM calls):
50
+
51
+ 1. **Collapse** consecutive duplicate lines
52
+ 2. **Deduplicate** repeated stack-trace frames
53
+ 3. **Preserve** error headers, exit codes, file paths, line numbers
54
+ 4. **Trim** to max lines from the tail, keeping important head lines
55
+ 5. **Redact** secrets (API keys, tokens, passwords)
56
+
57
+ For conversation arrays (`prune_messages`):
58
+
59
+ - **KEEP** all user/system/developer messages and anything with errors, paths, or constraints
60
+ - **COMPRESS** long tool/assistant blocks to their first sentence
61
+ - **DROP** exact duplicates (content or tool-signature match)
@@ -0,0 +1,53 @@
1
+ # vexel-cli
2
+
3
+ Deterministic context pruning for LLM agent loops — zero API dependencies.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ uv tool install vexel-cli
9
+ ```
10
+
11
+ ## Commands
12
+
13
+ | Command | Description |
14
+ |---------|-------------|
15
+ | `vexel prune [file]` | Prune text from file or stdin |
16
+ | `vexel wrap -- <cmd>` | Run a command and prune its output |
17
+ | `vexel hook-post-tool` | PostToolUse hook (reads JSON from stdin) |
18
+ | `vexel install [--target cursor\|claude\|all]` | Install IDE configs |
19
+ | `vexel stats` | Show cumulative token savings |
20
+
21
+ ## Examples
22
+
23
+ ```bash
24
+ # Prune a noisy build log
25
+ vexel prune build.log
26
+
27
+ # JSON telemetry
28
+ cat output.txt | vexel prune --json
29
+
30
+ # Wrap a noisy test run so the IDE gets clean output
31
+ vexel wrap -- pytest -x --tb=long
32
+
33
+ # Install Vexel hooks into your project
34
+ vexel install
35
+ vexel install --target cursor
36
+ vexel install --global --target claude
37
+ ```
38
+
39
+ ## How it works
40
+
41
+ Vexel's pruning is fully deterministic (no LLM calls):
42
+
43
+ 1. **Collapse** consecutive duplicate lines
44
+ 2. **Deduplicate** repeated stack-trace frames
45
+ 3. **Preserve** error headers, exit codes, file paths, line numbers
46
+ 4. **Trim** to max lines from the tail, keeping important head lines
47
+ 5. **Redact** secrets (API keys, tokens, passwords)
48
+
49
+ For conversation arrays (`prune_messages`):
50
+
51
+ - **KEEP** all user/system/developer messages and anything with errors, paths, or constraints
52
+ - **COMPRESS** long tool/assistant blocks to their first sentence
53
+ - **DROP** exact duplicates (content or tool-signature match)
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "vexel-cli"
7
+ version = "0.1.0"
8
+ description = "Deterministic context pruning for LLM agent loops — zero API dependencies"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ dependencies = []
13
+
14
+ [project.scripts]
15
+ vexel = "vexel_cli.cli:main"
16
+
17
+ [tool.setuptools.packages.find]
18
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Vexel CLI — deterministic context pruning, zero API dependencies."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,257 @@
1
+ """Vexel CLI — deterministic context pruning for LLM agent loops.
2
+
3
+ Zero external dependencies. Every command uses only the Python standard library.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from vexel_cli import __version__
16
+ from vexel_cli.core import prune_messages, prune_text
17
+
18
+ STATS_PATH = Path.home() / ".vexel" / "stats.json"
19
+ CHAR_THRESHOLD = 1500
20
+
21
+
22
+ def _load_stats() -> dict:
23
+ if STATS_PATH.exists():
24
+ try:
25
+ return json.loads(STATS_PATH.read_text(encoding="utf-8"))
26
+ except (json.JSONDecodeError, OSError):
27
+ pass
28
+ return {"runs": 0, "before_tokens": 0, "after_tokens": 0, "saved_tokens": 0}
29
+
30
+
31
+ def _save_stats(stats: dict) -> None:
32
+ STATS_PATH.parent.mkdir(parents=True, exist_ok=True)
33
+ STATS_PATH.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
34
+
35
+
36
+ def _record(before: int, after: int) -> None:
37
+ s = _load_stats()
38
+ s["runs"] = s.get("runs", 0) + 1
39
+ s["before_tokens"] = s.get("before_tokens", 0) + before
40
+ s["after_tokens"] = s.get("after_tokens", 0) + after
41
+ s["saved_tokens"] = s.get("saved_tokens", 0) + (before - after)
42
+ _save_stats(s)
43
+
44
+
45
+ # ── vexel prune ──────────────────────────────────────────────────────────
46
+
47
+ def cmd_prune(args: argparse.Namespace) -> None:
48
+ if args.file and args.file != "-":
49
+ text = Path(args.file).read_text(encoding="utf-8", errors="replace")
50
+ else:
51
+ text = sys.stdin.read()
52
+
53
+ result = prune_text(text, max_lines=args.max_lines)
54
+ _record(result["before_tokens"], result["after_tokens"])
55
+
56
+ if args.json:
57
+ json.dump(
58
+ {k: v for k, v in result.items() if k != "pruned"},
59
+ sys.stdout,
60
+ indent=2,
61
+ )
62
+ sys.stdout.write("\n")
63
+ else:
64
+ sys.stdout.write(result["pruned"])
65
+
66
+
67
+ # ── vexel wrap ───────────────────────────────────────────────────────────
68
+
69
+ def cmd_wrap(args: argparse.Namespace) -> None:
70
+ cmd = args.cmd
71
+ if cmd and cmd[0] == "--":
72
+ cmd = cmd[1:]
73
+ proc = subprocess.run(
74
+ cmd,
75
+ capture_output=True,
76
+ text=True,
77
+ )
78
+ combined = proc.stdout + proc.stderr
79
+ if len(combined) > CHAR_THRESHOLD:
80
+ result = prune_text(combined, max_lines=getattr(args, "max_lines", 80))
81
+ _record(result["before_tokens"], result["after_tokens"])
82
+ sys.stdout.write(result["pruned"])
83
+ else:
84
+ sys.stdout.write(proc.stdout)
85
+ sys.stderr.write(proc.stderr)
86
+ sys.exit(proc.returncode)
87
+
88
+
89
+ # ── vexel hook-post-tool ─────────────────────────────────────────────────
90
+
91
+ def cmd_hook_post_tool(_args: argparse.Namespace) -> None:
92
+ try:
93
+ payload = json.loads(sys.stdin.read())
94
+ except (json.JSONDecodeError, OSError):
95
+ sys.exit(0)
96
+
97
+ tool_response = payload.get("tool_response", "")
98
+ if not isinstance(tool_response, str):
99
+ tool_response = json.dumps(tool_response)
100
+
101
+ stdout_field = payload.get("stdout", "")
102
+ if isinstance(stdout_field, str) and len(stdout_field) > len(tool_response):
103
+ tool_response = stdout_field
104
+
105
+ if len(tool_response) <= CHAR_THRESHOLD:
106
+ sys.exit(0)
107
+
108
+ result = prune_text(tool_response)
109
+ _record(result["before_tokens"], result["after_tokens"])
110
+
111
+ output = {
112
+ "hookSpecificOutput": {
113
+ "updatedToolOutput": result["pruned"],
114
+ }
115
+ }
116
+ json.dump(output, sys.stdout)
117
+ sys.stdout.write("\n")
118
+
119
+
120
+ # ── vexel install ────────────────────────────────────────────────────────
121
+
122
+ def cmd_install(args: argparse.Namespace) -> None:
123
+ from vexel_cli.templates import (
124
+ CLAUDE_SETTINGS_HOOK,
125
+ CLAUDE_SKILL,
126
+ CURSOR_HOOKS,
127
+ CURSOR_RULE,
128
+ CURSOR_SKILL,
129
+ )
130
+
131
+ targets = args.target
132
+ base = Path.home() if args.is_global else Path.cwd()
133
+
134
+ installed: list[str] = []
135
+
136
+ if targets in ("cursor", "all"):
137
+ _install_cursor(base, CURSOR_RULE, CURSOR_SKILL, CURSOR_HOOKS)
138
+ installed.append("Cursor")
139
+
140
+ if targets in ("claude", "all"):
141
+ _install_claude(base, CLAUDE_SKILL, CLAUDE_SETTINGS_HOOK)
142
+ installed.append("Claude Code")
143
+
144
+ if installed:
145
+ print(f"Vexel installed for: {', '.join(installed)}")
146
+ print(f" Base: {base}")
147
+ else:
148
+ print("Nothing to install.")
149
+
150
+
151
+ def _write_if_absent(path: Path, content: str) -> bool:
152
+ if path.exists():
153
+ return False
154
+ path.parent.mkdir(parents=True, exist_ok=True)
155
+ path.write_text(content, encoding="utf-8")
156
+ return True
157
+
158
+
159
+ def _merge_json(path: Path, patch: dict) -> None:
160
+ existing: dict = {}
161
+ if path.exists():
162
+ try:
163
+ existing = json.loads(path.read_text(encoding="utf-8"))
164
+ except (json.JSONDecodeError, OSError):
165
+ pass
166
+ _deep_merge(existing, patch)
167
+ path.parent.mkdir(parents=True, exist_ok=True)
168
+ path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
169
+
170
+
171
+ def _deep_merge(base: dict, patch: dict) -> None:
172
+ for key, val in patch.items():
173
+ if key in base and isinstance(base[key], dict) and isinstance(val, dict):
174
+ _deep_merge(base[key], val)
175
+ elif key in base and isinstance(base[key], list) and isinstance(val, list):
176
+ existing_json = {json.dumps(e, sort_keys=True) for e in base[key] if isinstance(e, dict)}
177
+ for item in val:
178
+ if isinstance(item, dict) and json.dumps(item, sort_keys=True) not in existing_json:
179
+ base[key].append(item)
180
+ else:
181
+ base.setdefault(key, val)
182
+
183
+
184
+ def _install_cursor(base: Path, rule: str, skill: str, hooks: dict) -> None:
185
+ cursor = base / ".cursor"
186
+ _write_if_absent(cursor / "rules" / "vexel.mdc", rule)
187
+ _write_if_absent(cursor / "skills" / "vexel" / "SKILL.md", skill)
188
+ _merge_json(cursor / "hooks.json", hooks)
189
+
190
+
191
+ def _install_claude(base: Path, skill: str, settings_hook: dict) -> None:
192
+ claude = base / ".claude"
193
+ _write_if_absent(claude / "skills" / "vexel" / "SKILL.md", skill)
194
+ _merge_json(claude / "settings.json", settings_hook)
195
+
196
+
197
+ # ── vexel stats ──────────────────────────────────────────────────────────
198
+
199
+ def cmd_stats(_args: argparse.Namespace) -> None:
200
+ s = _load_stats()
201
+ runs = s.get("runs", 0)
202
+ saved = s.get("saved_tokens", 0)
203
+ before = s.get("before_tokens", 0)
204
+ pct = round(saved / before * 100, 1) if before else 0.0
205
+ print(f"Vexel stats ({STATS_PATH})")
206
+ print(f" Runs: {runs}")
207
+ print(f" Before: {before:,} tokens")
208
+ print(f" After: {s.get('after_tokens', 0):,} tokens")
209
+ print(f" Saved: {saved:,} tokens ({pct}%)")
210
+
211
+
212
+ # ── main ─────────────────────────────────────────────────────────────────
213
+
214
+ def main(argv: list[str] | None = None) -> None:
215
+ parser = argparse.ArgumentParser(
216
+ prog="vexel",
217
+ description="Deterministic context pruning for LLM agent loops",
218
+ )
219
+ parser.add_argument("--version", action="version", version=f"vexel {__version__}")
220
+ sub = parser.add_subparsers(dest="command")
221
+
222
+ p_prune = sub.add_parser("prune", help="Prune text from file or stdin")
223
+ p_prune.add_argument("file", nargs="?", default="-", help="File to prune (default: stdin)")
224
+ p_prune.add_argument("--json", action="store_true", help="Output JSON telemetry instead of pruned text")
225
+ p_prune.add_argument("--max-lines", type=int, default=80, help="Max output lines (default: 80)")
226
+
227
+ p_wrap = sub.add_parser("wrap", help="Run a command and prune its output")
228
+ p_wrap.add_argument("--max-lines", type=int, default=80, help="Max output lines")
229
+ p_wrap.add_argument("cmd", nargs=argparse.REMAINDER, help="Command to run (after --)")
230
+
231
+ p_hook = sub.add_parser("hook-post-tool", help="PostToolUse hook (reads JSON from stdin)")
232
+
233
+ p_install = sub.add_parser("install", help="Install Vexel IDE configs")
234
+ p_install.add_argument("--global", dest="is_global", action="store_true", help="Install to home directory")
235
+ p_install.add_argument("--target", choices=["cursor", "claude", "all"], default="all", help="IDE target")
236
+
237
+ sub.add_parser("stats", help="Show cumulative token savings")
238
+
239
+ args = parser.parse_args(argv)
240
+
241
+ if args.command == "prune":
242
+ cmd_prune(args)
243
+ elif args.command == "wrap":
244
+ cmd_wrap(args)
245
+ elif args.command == "hook-post-tool":
246
+ cmd_hook_post_tool(args)
247
+ elif args.command == "install":
248
+ cmd_install(args)
249
+ elif args.command == "stats":
250
+ cmd_stats(args)
251
+ else:
252
+ parser.print_help()
253
+ sys.exit(1)
254
+
255
+
256
+ if __name__ == "__main__":
257
+ main()
@@ -0,0 +1,237 @@
1
+ """Pure deterministic pruning logic — Python standard library only.
2
+
3
+ Ported from build_memora_context_management_system/backend/optimizer.py without
4
+ FastAPI, Pydantic, tiktoken, or any third-party import.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any
11
+
12
+ SECRET = re.compile(
13
+ r"(?i)(\b(?:api[_-]?key|token|password|secret|authorization)\b\s*[:=]\s*)"
14
+ r"(?:bearer\s+)?[^\s,;]+|\b(?:AIza[\w-]{20,}|sk-[\w-]{16,})\b"
15
+ )
16
+ PATH_RE = re.compile(
17
+ r"(?:^|\s)(?:[./~][\w./-]+|[\w.-]+/[\w./-]+\.(?:py|js|ts|json|yaml|yml))(?=\s|:|$)"
18
+ )
19
+ ERROR_RE = re.compile(
20
+ r"(?i)\b(?:traceback|exception|error|failed|failure|crash|assertion|stack trace)\b"
21
+ )
22
+ CONSTRAINT_RE = re.compile(
23
+ r"(?i)\b(?:must|never|do not|requirement|constraint|invariant|expected|acceptance)\b"
24
+ )
25
+ WORDS = re.compile(r"[a-z0-9]+")
26
+ _TOOL_SIG_HEX = re.compile(r"\b0x[0-9a-f]+\b", re.I)
27
+ _TOOL_SIG_DIGITS = re.compile(r"\d+")
28
+ _TOOL_SIGNATURE_MIN_CHARS = 120
29
+
30
+
31
+ def _approx_tokens(text: str) -> int:
32
+ return len(re.findall(r"\w+|[^\w\s]", text))
33
+
34
+
35
+ def _redact(text: str) -> str:
36
+ return SECRET.sub(
37
+ lambda m: f"{m.group(1)}[REDACTED]" if m.group(1) else "[REDACTED]",
38
+ text,
39
+ )
40
+
41
+
42
+ def _normalize(text: str) -> str:
43
+ return " ".join(WORDS.findall(_redact(text).lower()))
44
+
45
+
46
+ def _compress_text(text: str) -> str:
47
+ clean = _redact(text)
48
+ sentences = re.split(r"(?<=[.!?])\s+", clean)
49
+ return sentences[0][:400].strip() if sentences else clean[:400]
50
+
51
+
52
+ def _tool_signature(text: str) -> str:
53
+ clean = _redact(text)
54
+ if len(clean.strip()) < _TOOL_SIGNATURE_MIN_CHARS:
55
+ return ""
56
+ masked = _TOOL_SIG_HEX.sub("#", clean.lower())
57
+ masked = _TOOL_SIG_DIGITS.sub("#", masked)
58
+ return " ".join(WORDS.findall(masked))
59
+
60
+
61
+ def _has_error(text: str) -> bool:
62
+ return bool(ERROR_RE.search(text))
63
+
64
+
65
+ def _has_path(text: str) -> bool:
66
+ return bool(PATH_RE.search(text))
67
+
68
+
69
+ def _has_constraint(text: str) -> bool:
70
+ return bool(CONSTRAINT_RE.search(text))
71
+
72
+
73
+ def _is_protected(role: str, kind: str | None, text: str) -> bool:
74
+ if role in ("system", "developer", "user"):
75
+ return True
76
+ if kind == "constraint" or _has_constraint(text):
77
+ return True
78
+ if kind == "error" or _has_error(text):
79
+ return True
80
+ if kind == "file" or _has_path(text):
81
+ return True
82
+ return False
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # prune_text: standalone text pruning (for files / stdout / tool output)
87
+ # ---------------------------------------------------------------------------
88
+
89
+ _CONSECUTIVE_DUP = re.compile(r"^(.+?)(\n\1)+$", re.MULTILINE)
90
+ _FRAME_LINE = re.compile(
91
+ r"^\s*File \"[^\"]+\", line \d+",
92
+ )
93
+ _EXIT_CODE = re.compile(r"(?:exit(?:ed)?|return(?:ed)?|code)[:\s]+\d+", re.I)
94
+
95
+
96
+ def prune_text(text: str, *, max_lines: int = 80) -> dict[str, Any]:
97
+ before_tokens = _approx_tokens(text)
98
+ lines = text.splitlines(keepends=True)
99
+
100
+ # 1. Collapse consecutive duplicate lines.
101
+ seen_consecutive: str | None = None
102
+ deduped: list[str] = []
103
+ consecutive_collapsed = 0
104
+ for line in lines:
105
+ stripped = line.rstrip()
106
+ if stripped == seen_consecutive and stripped:
107
+ consecutive_collapsed += 1
108
+ continue
109
+ seen_consecutive = stripped
110
+ deduped.append(line)
111
+
112
+ # 2. Deduplicate repeated stack-trace frames.
113
+ frame_groups: dict[str, int] = {}
114
+ kept: list[str] = []
115
+ frames_collapsed = 0
116
+ i = 0
117
+ while i < len(deduped):
118
+ line = deduped[i]
119
+ if _FRAME_LINE.match(line):
120
+ block_lines = [line]
121
+ j = i + 1
122
+ # Collect indented continuation (the code line under "File ...").
123
+ while j < len(deduped) and not _FRAME_LINE.match(deduped[j]) and deduped[j].startswith((" ", "\t")) and deduped[j].strip():
124
+ block_lines.append(deduped[j])
125
+ j += 1
126
+ sig = _normalize("".join(block_lines))
127
+ if sig in frame_groups:
128
+ frames_collapsed += 1
129
+ i = j
130
+ continue
131
+ frame_groups[sig] = 1
132
+ kept.extend(block_lines)
133
+ i = j
134
+ else:
135
+ kept.append(line)
136
+ i += 1
137
+
138
+ # 3. Preserve error headers, exit codes, file paths — always keep those lines.
139
+ # 4. Trim to max_lines from the tail (most recent), keeping the head error/exit/path lines.
140
+ if len(kept) > max_lines:
141
+ head_keep: list[int] = []
142
+ for idx, line in enumerate(kept):
143
+ if _has_error(line) or _EXIT_CODE.search(line) or _has_path(line):
144
+ head_keep.append(idx)
145
+ tail_start = max(0, len(kept) - max_lines)
146
+ preserved_head = [kept[idx] for idx in head_keep if idx < tail_start]
147
+ budget = max_lines - len(preserved_head)
148
+ tail = kept[-budget:] if budget > 0 else []
149
+ kept = preserved_head + tail
150
+
151
+ pruned = _redact("".join(kept))
152
+ after_tokens = _approx_tokens(pruned)
153
+ saved = round((1 - after_tokens / before_tokens) * 100, 1) if before_tokens else 0.0
154
+
155
+ return {
156
+ "pruned": pruned,
157
+ "before_tokens": before_tokens,
158
+ "after_tokens": after_tokens,
159
+ "saved_pct": saved,
160
+ "dropped_blocks": consecutive_collapsed + frames_collapsed,
161
+ }
162
+
163
+
164
+ # ---------------------------------------------------------------------------
165
+ # prune_messages: conversation-level KEEP / COMPRESS / DROP
166
+ # ---------------------------------------------------------------------------
167
+
168
+ def prune_messages(messages: list[dict[str, Any]]) -> dict[str, Any]:
169
+ seen: set[str] = set()
170
+ seen_tool_sigs: set[str] = set()
171
+ output: list[dict[str, Any]] = []
172
+ decisions: list[dict[str, Any]] = []
173
+ before_tokens = 0
174
+ after_tokens = 0
175
+
176
+ for msg in messages:
177
+ role = msg.get("role", "")
178
+ kind = msg.get("kind")
179
+ content = msg.get("content", "")
180
+ original_tokens = _approx_tokens(content)
181
+ before_tokens += original_tokens
182
+
183
+ normalized = _normalize(content)
184
+ duplicate = bool(normalized) and normalized in seen
185
+ seen.add(normalized)
186
+
187
+ tool_sig = _tool_signature(content) if role == "tool" else ""
188
+ retry_dup = role == "tool" and bool(tool_sig) and tool_sig in seen_tool_sigs and not duplicate
189
+
190
+ is_protected = _is_protected(role, kind, content)
191
+
192
+ action = "KEEP"
193
+ reason = "protected" if is_protected else "conservative_keep"
194
+
195
+ if role in ("assistant", "tool"):
196
+ if duplicate or retry_dup:
197
+ action, reason = "DROP", "exact_duplicate"
198
+ elif not is_protected:
199
+ redacted = _redact(content)
200
+ if role == "tool" and len(content.strip()) > 200 and _approx_tokens(_compress_text(content)) < _approx_tokens(redacted):
201
+ action, reason = "COMPRESS", "deterministic_compress"
202
+ elif role == "assistant" and _approx_tokens(redacted) >= 100 and _approx_tokens(_compress_text(content)) < _approx_tokens(redacted):
203
+ action, reason = "COMPRESS", "deterministic_compress"
204
+
205
+ if action != "DROP" and tool_sig:
206
+ seen_tool_sigs.add(tool_sig)
207
+
208
+ result_content = content
209
+ if action == "COMPRESS":
210
+ result_content = _compress_text(content)
211
+ elif action == "DROP":
212
+ result_content = ""
213
+
214
+ result_tokens = _approx_tokens(result_content) if action != "DROP" else 0
215
+ after_tokens += result_tokens
216
+
217
+ if action != "DROP":
218
+ out_msg = dict(msg)
219
+ out_msg["content"] = result_content
220
+ output.append(out_msg)
221
+
222
+ decisions.append({
223
+ "role": role,
224
+ "action": action,
225
+ "reason": reason,
226
+ "original_tokens": original_tokens,
227
+ "resulting_tokens": result_tokens,
228
+ })
229
+
230
+ saved = round((1 - after_tokens / before_tokens) * 100, 1) if before_tokens else 0.0
231
+ return {
232
+ "messages": output,
233
+ "decisions": decisions,
234
+ "before_tokens": before_tokens,
235
+ "after_tokens": after_tokens,
236
+ "saved_pct": saved,
237
+ }
@@ -0,0 +1,86 @@
1
+ """IDE configuration templates for `vexel install`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ CURSOR_RULE = """\
6
+ ---
7
+ description: Vexel deterministic context pruning
8
+ alwaysApply: true
9
+ ---
10
+
11
+ ## Vexel Context Pruning
12
+
13
+ When tool output or conversation context exceeds 1 500 tokens, Vexel
14
+ deterministically prunes duplicate retry blocks, collapses repeated stack
15
+ frames, and compresses verbose assistant/tool messages — keeping error
16
+ headers, file paths, exit codes and all user/system/developer messages
17
+ intact.
18
+
19
+ ### Rules
20
+ - KEEP every user, system and developer message verbatim.
21
+ - KEEP lines containing errors, file paths, exit codes, or constraints.
22
+ - COMPRESS long tool/assistant blocks that are not protected.
23
+ - DROP exact duplicates (content or tool-signature match).
24
+ - Never drop a message whose content matches an error, constraint, or path pattern.
25
+ """
26
+
27
+ CURSOR_SKILL = """\
28
+ # Vexel Pruning Skill
29
+
30
+ Invoke `vexel prune` or `vexel wrap -- <command>` to reduce noisy tool
31
+ output before it enters the context window.
32
+
33
+ ## Usage
34
+
35
+ ```bash
36
+ # Prune a file or stdin
37
+ vexel prune build.log
38
+ cat output.txt | vexel prune --json
39
+
40
+ # Wrap a noisy command
41
+ vexel wrap -- pytest -x --tb=long
42
+
43
+ # Show cumulative savings
44
+ vexel stats
45
+ ```
46
+ """
47
+
48
+ CURSOR_HOOKS = {
49
+ "hooks": [
50
+ {
51
+ "event": "postToolUse",
52
+ "command": "vexel hook-post-tool",
53
+ "description": "Vexel prunes bulky tool output",
54
+ }
55
+ ]
56
+ }
57
+
58
+ CLAUDE_SKILL = """\
59
+ # Vexel Pruning Skill
60
+
61
+ Deterministic context pruning for Claude Code agent loops.
62
+
63
+ ## Commands
64
+
65
+ - `vexel prune [file]` — prune text from file or stdin
66
+ - `vexel wrap -- <cmd>` — run a command and prune its output
67
+ - `vexel hook-post-tool` — PostToolUse hook (reads JSON from stdin)
68
+ - `vexel stats` — cumulative token savings
69
+ - `vexel install` — install IDE configs for Cursor and/or Claude Code
70
+ """
71
+
72
+ CLAUDE_SETTINGS_HOOK = {
73
+ "hooks": {
74
+ "PostToolUse": [
75
+ {
76
+ "matcher": "Bash|Read|Grep",
77
+ "hooks": [
78
+ {
79
+ "type": "command",
80
+ "command": "vexel hook-post-tool",
81
+ }
82
+ ],
83
+ }
84
+ ]
85
+ }
86
+ }
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: vexel-cli
3
+ Version: 0.1.0
4
+ Summary: Deterministic context pruning for LLM agent loops — zero API dependencies
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+
9
+ # vexel-cli
10
+
11
+ Deterministic context pruning for LLM agent loops — zero API dependencies.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ uv tool install vexel-cli
17
+ ```
18
+
19
+ ## Commands
20
+
21
+ | Command | Description |
22
+ |---------|-------------|
23
+ | `vexel prune [file]` | Prune text from file or stdin |
24
+ | `vexel wrap -- <cmd>` | Run a command and prune its output |
25
+ | `vexel hook-post-tool` | PostToolUse hook (reads JSON from stdin) |
26
+ | `vexel install [--target cursor\|claude\|all]` | Install IDE configs |
27
+ | `vexel stats` | Show cumulative token savings |
28
+
29
+ ## Examples
30
+
31
+ ```bash
32
+ # Prune a noisy build log
33
+ vexel prune build.log
34
+
35
+ # JSON telemetry
36
+ cat output.txt | vexel prune --json
37
+
38
+ # Wrap a noisy test run so the IDE gets clean output
39
+ vexel wrap -- pytest -x --tb=long
40
+
41
+ # Install Vexel hooks into your project
42
+ vexel install
43
+ vexel install --target cursor
44
+ vexel install --global --target claude
45
+ ```
46
+
47
+ ## How it works
48
+
49
+ Vexel's pruning is fully deterministic (no LLM calls):
50
+
51
+ 1. **Collapse** consecutive duplicate lines
52
+ 2. **Deduplicate** repeated stack-trace frames
53
+ 3. **Preserve** error headers, exit codes, file paths, line numbers
54
+ 4. **Trim** to max lines from the tail, keeping important head lines
55
+ 5. **Redact** secrets (API keys, tokens, passwords)
56
+
57
+ For conversation arrays (`prune_messages`):
58
+
59
+ - **KEEP** all user/system/developer messages and anything with errors, paths, or constraints
60
+ - **COMPRESS** long tool/assistant blocks to their first sentence
61
+ - **DROP** exact duplicates (content or tool-signature match)
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/vexel_cli/__init__.py
4
+ src/vexel_cli/cli.py
5
+ src/vexel_cli/core.py
6
+ src/vexel_cli/templates.py
7
+ src/vexel_cli.egg-info/PKG-INFO
8
+ src/vexel_cli.egg-info/SOURCES.txt
9
+ src/vexel_cli.egg-info/dependency_links.txt
10
+ src/vexel_cli.egg-info/entry_points.txt
11
+ src/vexel_cli.egg-info/top_level.txt
12
+ tests/test_cli.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vexel = vexel_cli.cli:main
@@ -0,0 +1 @@
1
+ vexel_cli
@@ -0,0 +1,302 @@
1
+ """Tests for the vexel CLI — zero external dependencies beyond pytest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import textwrap
10
+ from pathlib import Path
11
+ from unittest import mock
12
+
13
+ import pytest
14
+
15
+ CLI_ROOT = Path(__file__).resolve().parent.parent
16
+ sys.path.insert(0, str(CLI_ROOT / "src"))
17
+
18
+ from vexel_cli.core import prune_messages, prune_text
19
+
20
+
21
+ # ── prune_text ───────────────────────────────────────────────────────────
22
+
23
+ class TestPruneText:
24
+ def test_collapse_consecutive_duplicates(self):
25
+ text = "line A\n" * 20 + "line B\n"
26
+ result = prune_text(text)
27
+ assert result["pruned"].count("line A") == 1
28
+ assert "line B" in result["pruned"]
29
+ assert result["dropped_blocks"] > 0
30
+
31
+ def test_stack_frame_dedup(self):
32
+ frame = ' File "app.py", line 10, in main\n raise ValueError("boom")\n'
33
+ text = "Traceback:\n" + frame * 5 + "ValueError: boom\n"
34
+ result = prune_text(text)
35
+ assert result["pruned"].count('File "app.py"') == 1
36
+ assert "ValueError: boom" in result["pruned"]
37
+
38
+ def test_preserves_error_header(self):
39
+ body = "\n".join(f"verbose line {i}" for i in range(200))
40
+ text = "ERROR: critical failure\n" + body
41
+ result = prune_text(text, max_lines=10)
42
+ assert "ERROR: critical failure" in result["pruned"]
43
+
44
+ def test_preserves_exit_code(self):
45
+ lines = [f"log {i}" for i in range(200)]
46
+ lines[0] = "exited with code 1"
47
+ text = "\n".join(lines)
48
+ result = prune_text(text, max_lines=10)
49
+ assert "exited with code 1" in result["pruned"]
50
+
51
+ def test_preserves_file_paths(self):
52
+ lines = [f"noise {i}" for i in range(200)]
53
+ lines[2] = " src/main.py:42 some info"
54
+ text = "\n".join(lines)
55
+ result = prune_text(text, max_lines=10)
56
+ assert "src/main.py" in result["pruned"]
57
+
58
+ def test_max_lines_respected(self):
59
+ text = "\n".join(f"line {i}" for i in range(500))
60
+ result = prune_text(text, max_lines=20)
61
+ assert result["pruned"].count("\n") <= 20
62
+
63
+ def test_telemetry_fields(self):
64
+ result = prune_text("hello world\nhello world\n")
65
+ assert "before_tokens" in result
66
+ assert "after_tokens" in result
67
+ assert "saved_pct" in result
68
+ assert isinstance(result["saved_pct"], float)
69
+
70
+ def test_redacts_secrets(self):
71
+ text = "api_key=sk-secret1234567890abcd stuff"
72
+ result = prune_text(text)
73
+ assert "sk-secret1234567890abcd" not in result["pruned"]
74
+ assert "[REDACTED]" in result["pruned"]
75
+
76
+ def test_empty_input(self):
77
+ result = prune_text("")
78
+ assert result["pruned"] == ""
79
+ assert result["saved_pct"] == 0.0
80
+
81
+
82
+ # ── prune_messages ───────────────────────────────────────────────────────
83
+
84
+ class TestPruneMessages:
85
+ def test_keeps_user_messages(self):
86
+ msgs = [
87
+ {"role": "user", "content": "Hello, how are you?"},
88
+ {"role": "user", "content": "What is 2+2?"},
89
+ ]
90
+ result = prune_messages(msgs)
91
+ assert len(result["messages"]) == 2
92
+ assert all(d["action"] == "KEEP" for d in result["decisions"])
93
+
94
+ def test_drops_exact_duplicate_tool(self):
95
+ msgs = [
96
+ {"role": "tool", "content": "output line A"},
97
+ {"role": "tool", "content": "output line A"},
98
+ ]
99
+ result = prune_messages(msgs)
100
+ assert len(result["messages"]) == 1
101
+ assert result["decisions"][1]["action"] == "DROP"
102
+
103
+ def test_compresses_long_tool(self):
104
+ long = "Some long first sentence. " + "verbose filler. " * 100
105
+ msgs = [{"role": "tool", "content": long}]
106
+ result = prune_messages(msgs)
107
+ assert result["decisions"][0]["action"] == "COMPRESS"
108
+ assert result["after_tokens"] < result["before_tokens"]
109
+
110
+ def test_keeps_error_in_tool(self):
111
+ msgs = [{"role": "tool", "content": "Traceback: something failed badly", "kind": "error"}]
112
+ result = prune_messages(msgs)
113
+ assert result["decisions"][0]["action"] == "KEEP"
114
+
115
+ def test_keeps_system_messages(self):
116
+ msgs = [{"role": "system", "content": "You are a helpful assistant."}]
117
+ result = prune_messages(msgs)
118
+ assert result["decisions"][0]["action"] == "KEEP"
119
+
120
+ def test_telemetry_shape(self):
121
+ result = prune_messages([{"role": "user", "content": "hi"}])
122
+ assert "before_tokens" in result
123
+ assert "after_tokens" in result
124
+ assert "saved_pct" in result
125
+ assert "decisions" in result
126
+ assert "messages" in result
127
+
128
+
129
+ # ── CLI entry point ──────────────────────────────────────────────────────
130
+
131
+ class TestCLIEntryPoint:
132
+ def test_prune_from_stdin(self, tmp_path):
133
+ from vexel_cli.cli import main
134
+ import io
135
+
136
+ text = "dup\n" * 50
137
+ with mock.patch("sys.stdin", io.StringIO(text)), \
138
+ mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
139
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
140
+ main(["prune"])
141
+ assert out.getvalue().count("dup") == 1
142
+
143
+ def test_prune_json_flag(self, tmp_path):
144
+ from vexel_cli.cli import main
145
+ import io
146
+
147
+ text = "line\n" * 10
148
+ with mock.patch("sys.stdin", io.StringIO(text)), \
149
+ mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
150
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
151
+ main(["prune", "--json"])
152
+ data = json.loads(out.getvalue())
153
+ assert "before_tokens" in data
154
+
155
+ def test_prune_file(self, tmp_path):
156
+ from vexel_cli.cli import main
157
+ import io
158
+
159
+ f = tmp_path / "input.txt"
160
+ f.write_text("hello\nhello\nhello\nworld\n", encoding="utf-8")
161
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
162
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
163
+ main(["prune", str(f)])
164
+ assert out.getvalue().count("hello") == 1
165
+ assert "world" in out.getvalue()
166
+
167
+ def test_hook_post_tool_passthrough(self, tmp_path):
168
+ from vexel_cli.cli import main
169
+ import io
170
+
171
+ payload = json.dumps({"tool_response": "short"})
172
+ with mock.patch("sys.stdin", io.StringIO(payload)), \
173
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
174
+ with pytest.raises(SystemExit) as exc:
175
+ main(["hook-post-tool"])
176
+ assert exc.value.code == 0
177
+
178
+ def test_hook_post_tool_prunes_long(self, tmp_path):
179
+ from vexel_cli.cli import main
180
+ import io
181
+
182
+ long = "verbose line\n" * 500
183
+ payload = json.dumps({"tool_response": long})
184
+ with mock.patch("sys.stdin", io.StringIO(payload)), \
185
+ mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
186
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
187
+ main(["hook-post-tool"])
188
+ data = json.loads(out.getvalue())
189
+ assert "hookSpecificOutput" in data
190
+ assert "updatedToolOutput" in data["hookSpecificOutput"]
191
+
192
+ def test_install_creates_files(self, tmp_path):
193
+ from vexel_cli.cli import main
194
+
195
+ with mock.patch("vexel_cli.cli.Path") as MockPath:
196
+ pass
197
+ # Use actual path
198
+ from vexel_cli.cli import main as real_main
199
+ import io
200
+
201
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out:
202
+ real_main(["install", "--target", "all", "--global"])
203
+
204
+ def test_install_cursor_only(self, tmp_path, monkeypatch):
205
+ from vexel_cli.cli import main
206
+ import io
207
+
208
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
209
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out:
210
+ main(["install", "--global", "--target", "cursor"])
211
+ assert "Cursor" in out.getvalue()
212
+ assert (tmp_path / ".cursor" / "rules" / "vexel.mdc").exists()
213
+ assert (tmp_path / ".cursor" / "skills" / "vexel" / "SKILL.md").exists()
214
+ assert (tmp_path / ".cursor" / "hooks.json").exists()
215
+
216
+ def test_install_claude_only(self, tmp_path, monkeypatch):
217
+ from vexel_cli.cli import main
218
+ import io
219
+
220
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
221
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out:
222
+ main(["install", "--global", "--target", "claude"])
223
+ assert "Claude Code" in out.getvalue()
224
+ assert (tmp_path / ".claude" / "skills" / "vexel" / "SKILL.md").exists()
225
+ assert (tmp_path / ".claude" / "settings.json").exists()
226
+
227
+ def test_install_no_overwrite(self, tmp_path, monkeypatch):
228
+ from vexel_cli.cli import main
229
+ import io
230
+
231
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
232
+ rule_path = tmp_path / ".cursor" / "rules" / "vexel.mdc"
233
+ rule_path.parent.mkdir(parents=True)
234
+ rule_path.write_text("USER CONTENT", encoding="utf-8")
235
+ with mock.patch("sys.stdout", new_callable=io.StringIO):
236
+ main(["install", "--global", "--target", "cursor"])
237
+ assert rule_path.read_text(encoding="utf-8") == "USER CONTENT"
238
+
239
+ def test_install_merges_hooks(self, tmp_path, monkeypatch):
240
+ from vexel_cli.cli import main
241
+ import io
242
+
243
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
244
+ hooks_path = tmp_path / ".cursor" / "hooks.json"
245
+ hooks_path.parent.mkdir(parents=True)
246
+ hooks_path.write_text(json.dumps({"hooks": [{"event": "other", "command": "echo hi"}]}), encoding="utf-8")
247
+ with mock.patch("sys.stdout", new_callable=io.StringIO):
248
+ main(["install", "--global", "--target", "cursor"])
249
+ data = json.loads(hooks_path.read_text(encoding="utf-8"))
250
+ assert len(data["hooks"]) == 2
251
+
252
+ def test_stats_empty(self, tmp_path):
253
+ from vexel_cli.cli import main
254
+ import io
255
+
256
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
257
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
258
+ main(["stats"])
259
+ assert "0 tokens" in out.getvalue()
260
+
261
+ def test_stats_after_prune(self, tmp_path):
262
+ from vexel_cli.cli import main
263
+ import io
264
+
265
+ stats_file = tmp_path / "stats.json"
266
+ text = "dup\n" * 50
267
+ with mock.patch("sys.stdin", io.StringIO(text)), \
268
+ mock.patch("sys.stdout", new_callable=io.StringIO), \
269
+ mock.patch("vexel_cli.cli.STATS_PATH", stats_file):
270
+ main(["prune"])
271
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
272
+ mock.patch("vexel_cli.cli.STATS_PATH", stats_file):
273
+ main(["stats"])
274
+ assert "Runs: 1" in out.getvalue()
275
+
276
+
277
+ # ── wrap command ─────────────────────────────────────────────────────────
278
+
279
+ class TestWrap:
280
+ def test_wrap_preserves_exit_code(self, tmp_path):
281
+ from vexel_cli.cli import main
282
+ import io
283
+
284
+ with mock.patch("sys.stdout", new_callable=io.StringIO), \
285
+ mock.patch("sys.stderr", new_callable=io.StringIO), \
286
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
287
+ with pytest.raises(SystemExit) as exc:
288
+ main(["wrap", "--", sys.executable, "-c", "import sys; sys.exit(42)"])
289
+ assert exc.value.code == 42
290
+
291
+ def test_wrap_prunes_noisy_output(self, tmp_path):
292
+ from vexel_cli.cli import main
293
+ import io
294
+
295
+ script = "print('err\\n' * 100)"
296
+ with mock.patch("sys.stdout", new_callable=io.StringIO) as out, \
297
+ mock.patch("sys.stderr", new_callable=io.StringIO), \
298
+ mock.patch("vexel_cli.cli.STATS_PATH", tmp_path / "stats.json"):
299
+ with pytest.raises(SystemExit) as exc:
300
+ main(["wrap", "--", sys.executable, "-c", script])
301
+ assert exc.value.code == 0
302
+ assert out.getvalue().count("err") >= 1