cleave-ctx 1.0.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,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: cleave-ctx
3
+ Version: 1.0.0
4
+ Summary: Zero-GPU polyglot code localization and token-budgeted context management powered by Cleave
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/narensen/Cleave
7
+ Keywords: code-search,context,ast,bm25,mcp,llm
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Software Development :: Libraries
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+
15
+ # cleave-ctx (Python SDK)
16
+
17
+ Zero-GPU polyglot code localization and token-budgeted context management powered by [Cleave](https://github.com/narensen/Cleave).
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ # 1. Install the Rust engine binary
23
+ cargo install cleave-ctx
24
+
25
+ # 2. Install the Python SDK
26
+ pip install cleave-ctx
27
+ ```
28
+
29
+ ## Quickstart
30
+
31
+ ```python
32
+ from cleave_ctx import Cleave
33
+
34
+ with Cleave(".") as ctx:
35
+ files = ctx.locate("verify_jwt_token", limit=10)
36
+ print(files[0].path, files[0].score)
37
+
38
+ bundle = ctx.context("verify_jwt_token", budget=4800, depth=2)
39
+ print(bundle.text)
40
+ print(f"Saved {bundle.stats.saved_pct:.1f}% tokens")
41
+
42
+ ctx.update_files(["src/auth.py"])
43
+ ```
@@ -0,0 +1,29 @@
1
+ # cleave-ctx (Python SDK)
2
+
3
+ Zero-GPU polyglot code localization and token-budgeted context management powered by [Cleave](https://github.com/narensen/Cleave).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ # 1. Install the Rust engine binary
9
+ cargo install cleave-ctx
10
+
11
+ # 2. Install the Python SDK
12
+ pip install cleave-ctx
13
+ ```
14
+
15
+ ## Quickstart
16
+
17
+ ```python
18
+ from cleave_ctx import Cleave
19
+
20
+ with Cleave(".") as ctx:
21
+ files = ctx.locate("verify_jwt_token", limit=10)
22
+ print(files[0].path, files[0].score)
23
+
24
+ bundle = ctx.context("verify_jwt_token", budget=4800, depth=2)
25
+ print(bundle.text)
26
+ print(f"Saved {bundle.stats.saved_pct:.1f}% tokens")
27
+
28
+ ctx.update_files(["src/auth.py"])
29
+ ```
@@ -0,0 +1,25 @@
1
+ """Cleave — zero-GPU polyglot code localization and token-budgeted context management."""
2
+
3
+ from .client import (
4
+ BuildReport,
5
+ Cleave,
6
+ CleaveError,
7
+ ContextBundle,
8
+ FileHit,
9
+ TokenSavings,
10
+ UpdateReport,
11
+ resolve_binary,
12
+ )
13
+
14
+ __all__ = [
15
+ "BuildReport",
16
+ "Cleave",
17
+ "CleaveError",
18
+ "ContextBundle",
19
+ "FileHit",
20
+ "TokenSavings",
21
+ "UpdateReport",
22
+ "resolve_binary",
23
+ ]
24
+
25
+ __version__ = "1.0.0"
@@ -0,0 +1,303 @@
1
+ """Persistent stdio JSON-RPC client for the Rust `cleave` context engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any, Iterable, Optional, Sequence
12
+
13
+
14
+ class CleaveError(RuntimeError):
15
+ """Raised when the underlying `cleave` engine returns an error."""
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class FileHit:
20
+ path: str
21
+ score: float
22
+ hit_count: int
23
+ top_symbols: list[str] = field(default_factory=list)
24
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
25
+
26
+ @classmethod
27
+ def from_dict(cls, data: dict[str, Any]) -> "FileHit":
28
+ return cls(
29
+ path=str(data.get("path", "")),
30
+ score=float(data.get("score", 0.0)),
31
+ hit_count=int(data.get("hit_count", 0)),
32
+ top_symbols=list(data.get("top_symbols", [])),
33
+ raw=data,
34
+ )
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class TokenSavings:
39
+ delivered_chars: int
40
+ delivered_tokens_est: int
41
+ naive_chars: int
42
+ naive_tokens_est: int
43
+ saved_pct: float
44
+
45
+ @classmethod
46
+ def from_dict(cls, data: dict[str, Any]) -> "TokenSavings":
47
+ return cls(
48
+ delivered_chars=int(data.get("delivered_chars", 0)),
49
+ delivered_tokens_est=int(data.get("delivered_tokens_est", 0)),
50
+ naive_chars=int(data.get("naive_chars", 0)),
51
+ naive_tokens_est=int(data.get("naive_tokens_est", 0)),
52
+ saved_pct=float(data.get("saved_pct", 0.0)),
53
+ )
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class ContextBundle:
58
+ query: str
59
+ budget_chars: int
60
+ text: str
61
+ focus: list[dict[str, Any]]
62
+ relations: list[dict[str, Any]]
63
+ affected_tests: list[dict[str, Any]]
64
+ omitted: int
65
+ stats: TokenSavings
66
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class BuildReport:
71
+ parsed: list[str]
72
+ removed: list[str]
73
+ unchanged: int
74
+ total_files: int
75
+ total_nodes: int
76
+ total_edges: int
77
+
78
+ @classmethod
79
+ def from_dict(cls, data: dict[str, Any]) -> "BuildReport":
80
+ return cls(
81
+ parsed=list(data.get("parsed", [])),
82
+ removed=list(data.get("removed", [])),
83
+ unchanged=int(data.get("unchanged", 0)),
84
+ total_files=int(data.get("total_files", 0)),
85
+ total_nodes=int(data.get("total_nodes", 0)),
86
+ total_edges=int(data.get("total_edges", 0)),
87
+ )
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class UpdateReport:
92
+ updated: list[str]
93
+ removed: list[str]
94
+ flipped_from_planned: list[str]
95
+ flipped_files: list[str]
96
+ moves: dict[str, str]
97
+
98
+ @classmethod
99
+ def from_dict(cls, data: dict[str, Any]) -> "UpdateReport":
100
+ return cls(
101
+ updated=list(data.get("updated", [])),
102
+ removed=list(data.get("removed", [])),
103
+ flipped_from_planned=list(data.get("flipped_from_planned", [])),
104
+ flipped_files=list(data.get("flipped_files", [])),
105
+ moves=dict(data.get("moves", {})),
106
+ )
107
+
108
+
109
+ def resolve_binary(explicit: Optional[str | os.PathLike[str]] = None) -> str:
110
+ """Locate the compiled `cleave` binary via explicit path, `CLEAVE_BIN`, PATH, or local target/."""
111
+ if explicit is not None:
112
+ p = Path(explicit)
113
+ if p.is_file():
114
+ return str(p)
115
+ raise FileNotFoundError(f"cleave binary not found at {p}")
116
+
117
+ env_bin = os.environ.get("CLEAVE_BIN")
118
+ if env_bin and Path(env_bin).is_file():
119
+ return env_bin
120
+
121
+ on_path = shutil.which("cleave")
122
+ if on_path:
123
+ return on_path
124
+
125
+ # Check repo-local cargo target directories when developing from source.
126
+ repo_root = Path(__file__).resolve().parents[3]
127
+ for profile in ("release", "debug"):
128
+ cand = repo_root / "target" / profile / ("cleave.exe" if os.name == "nt" else "cleave")
129
+ if cand.is_file():
130
+ return str(cand)
131
+
132
+ raise FileNotFoundError(
133
+ "Could not locate the `cleave` binary. Build it with `cargo build --release`, "
134
+ "add it to PATH, or set CLEAVE_BIN=/path/to/cleave."
135
+ )
136
+
137
+
138
+ class Cleave:
139
+ """Stateful, zero-GPU repository context manager backed by a persistent Rust `cleave` worker."""
140
+
141
+ def __init__(
142
+ self,
143
+ root: str | os.PathLike[str],
144
+ *,
145
+ workspaces: Sequence[str | os.PathLike[str]] = (),
146
+ binary: Optional[str | os.PathLike[str]] = None,
147
+ ) -> None:
148
+ self.root = Path(root).resolve()
149
+ self.workspaces = [Path(w).resolve() for w in workspaces]
150
+ self.binary = resolve_binary(binary)
151
+ self._proc: Optional[subprocess.Popen[str]] = None
152
+ self._req_id = 0
153
+
154
+ def __enter__(self) -> "Cleave":
155
+ self._ensure_started()
156
+ return self
157
+
158
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
159
+ self.close()
160
+
161
+ def _ensure_started(self) -> subprocess.Popen[str]:
162
+ if self._proc is not None and self._proc.poll() is None:
163
+ return self._proc
164
+
165
+ cmd = [self.binary, "mcp", str(self.root)]
166
+ for ws in self.workspaces:
167
+ cmd.extend(["--workspace", str(ws)])
168
+
169
+ self._proc = subprocess.Popen(
170
+ cmd,
171
+ stdin=subprocess.PIPE,
172
+ stdout=subprocess.PIPE,
173
+ stderr=subprocess.PIPE,
174
+ text=True,
175
+ bufsize=1,
176
+ )
177
+ self._rpc("initialize", {})
178
+ return self._proc
179
+
180
+ def close(self) -> None:
181
+ """Shut down the persistent `cleave` worker subprocess cleanly."""
182
+ if self._proc is None:
183
+ return
184
+ try:
185
+ if self._proc.stdin:
186
+ self._proc.stdin.close()
187
+ self._proc.wait(timeout=3.0)
188
+ except Exception:
189
+ self._proc.kill()
190
+ self._proc.wait(timeout=3.0)
191
+ finally:
192
+ if self._proc.stdout:
193
+ self._proc.stdout.close()
194
+ if self._proc.stderr:
195
+ self._proc.stderr.close()
196
+ self._proc = None
197
+
198
+ def _rpc(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
199
+ proc = self._ensure_started()
200
+ assert proc.stdin is not None and proc.stdout is not None
201
+ self._req_id += 1
202
+ req_id = self._req_id
203
+ payload = {"jsonrpc": "2.0", "id": req_id, "method": method, "params": params}
204
+ proc.stdin.write(json.dumps(payload) + "\n")
205
+ proc.stdin.flush()
206
+
207
+ line = proc.stdout.readline()
208
+ if not line:
209
+ stderr = proc.stderr.read() if proc.stderr else ""
210
+ raise CleaveError(f"cleave worker exited unexpectedly: {stderr.strip()}")
211
+ resp = json.loads(line)
212
+ if "error" in resp:
213
+ raise CleaveError(resp["error"].get("message", str(resp["error"])))
214
+ return resp["result"]
215
+
216
+ def _call_tool(self, name: str, arguments: dict[str, Any]) -> tuple[str, dict[str, Any]]:
217
+ result = self._rpc("tools/call", {"name": name, "arguments": arguments})
218
+ content = result.get("content", [])
219
+ text = content[0].get("text", "") if content else ""
220
+ if result.get("isError"):
221
+ raise CleaveError(text or f"cleave tool `{name}` failed")
222
+ structured = result.get("structuredContent") or {}
223
+ return text, structured
224
+
225
+ def locate(
226
+ self,
227
+ query: str,
228
+ *,
229
+ limit: int = 10,
230
+ ablation: str = "auto",
231
+ ) -> list[FileHit]:
232
+ """Rank candidate files for a query using zero-GPU AST+BM25F localization."""
233
+ _, data = self._call_tool(
234
+ "cleave_locate",
235
+ {"query": query, "limit": limit, "ablation": ablation},
236
+ )
237
+ return [FileHit.from_dict(item) for item in data.get("files", [])]
238
+
239
+ def context(
240
+ self,
241
+ query: str,
242
+ *,
243
+ budget: int = 4800,
244
+ depth: int = 2,
245
+ include_tests: bool = True,
246
+ ) -> ContextBundle:
247
+ """Assemble a token-budgeted focus slice plus 1-2 hop dependency signatures."""
248
+ text, data = self._call_tool(
249
+ "smart_context",
250
+ {
251
+ "query": query,
252
+ "budget": budget,
253
+ "depth": depth,
254
+ "include_tests": include_tests,
255
+ },
256
+ )
257
+ return ContextBundle(
258
+ query=str(data.get("query", query)),
259
+ budget_chars=int(data.get("budget_chars", budget)),
260
+ text=text,
261
+ focus=list(data.get("focus", [])),
262
+ relations=list(data.get("relations", [])),
263
+ affected_tests=list(data.get("affected_tests", [])),
264
+ omitted=int(data.get("omitted", 0)),
265
+ stats=TokenSavings.from_dict(data.get("stats", {})),
266
+ raw=data,
267
+ )
268
+
269
+ def search(self, query: str, *, limit: int = 20) -> list[dict[str, Any]]:
270
+ """Search ranked AST symbols across the primary repository and attached workspaces."""
271
+ _, data = self._call_tool("cleave_search", {"query": query, "limit": limit})
272
+ return list(data.get("hits", []))
273
+
274
+ def impact(self, target: str, *, depth: int = 3, limit: int = 40) -> dict[str, Any]:
275
+ """Compute reverse transitive callers, entrypoints, and affected tests."""
276
+ _, data = self._call_tool(
277
+ "cleave_impact",
278
+ {"target": target, "depth": depth, "limit": limit},
279
+ )
280
+ return data
281
+
282
+ def taint(self, target: Optional[str] = None, *, depth: int = 4) -> dict[str, Any]:
283
+ """Run lightweight static source-to-sink taint tracing."""
284
+ args: dict[str, Any] = {"depth": depth}
285
+ if target is not None:
286
+ args["target"] = target
287
+ _, data = self._call_tool("cleave_taint", args)
288
+ return data
289
+
290
+ def source(self, symbol_id: str) -> dict[str, Any]:
291
+ """Fetch the exact source line span for a symbol node ID."""
292
+ _, data = self._call_tool("cleave_source", {"id": symbol_id})
293
+ return data
294
+
295
+ def reindex(self) -> list[BuildReport]:
296
+ """Incrementally rebuild `.cleave/` across all loaded workspaces."""
297
+ _, data = self._call_tool("cleave_reindex", {})
298
+ return [BuildReport.from_dict(r) for r in data.get("reports", [])]
299
+
300
+ def update_files(self, rel_paths: Iterable[str]) -> UpdateReport:
301
+ """Incrementally re-parse and update specific edited relative file paths."""
302
+ _, data = self._call_tool("cleave_update", {"paths": list(rel_paths)})
303
+ return UpdateReport.from_dict(data)
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: cleave-ctx
3
+ Version: 1.0.0
4
+ Summary: Zero-GPU polyglot code localization and token-budgeted context management powered by Cleave
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/narensen/Cleave
7
+ Keywords: code-search,context,ast,bm25,mcp,llm
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Software Development :: Libraries
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+
15
+ # cleave-ctx (Python SDK)
16
+
17
+ Zero-GPU polyglot code localization and token-budgeted context management powered by [Cleave](https://github.com/narensen/Cleave).
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ # 1. Install the Rust engine binary
23
+ cargo install cleave-ctx
24
+
25
+ # 2. Install the Python SDK
26
+ pip install cleave-ctx
27
+ ```
28
+
29
+ ## Quickstart
30
+
31
+ ```python
32
+ from cleave_ctx import Cleave
33
+
34
+ with Cleave(".") as ctx:
35
+ files = ctx.locate("verify_jwt_token", limit=10)
36
+ print(files[0].path, files[0].score)
37
+
38
+ bundle = ctx.context("verify_jwt_token", budget=4800, depth=2)
39
+ print(bundle.text)
40
+ print(f"Saved {bundle.stats.saved_pct:.1f}% tokens")
41
+
42
+ ctx.update_files(["src/auth.py"])
43
+ ```
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ cleave_ctx/__init__.py
4
+ cleave_ctx/client.py
5
+ cleave_ctx.egg-info/PKG-INFO
6
+ cleave_ctx.egg-info/SOURCES.txt
7
+ cleave_ctx.egg-info/dependency_links.txt
8
+ cleave_ctx.egg-info/top_level.txt
9
+ tests/test_cleave_py.py
@@ -0,0 +1 @@
1
+ cleave_ctx
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cleave-ctx"
7
+ version = "1.0.0"
8
+ description = "Zero-GPU polyglot code localization and token-budgeted context management powered by Cleave"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ keywords = ["code-search", "context", "ast", "bm25", "mcp", "llm"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Software Development :: Libraries",
18
+ ]
19
+
20
+ [project.urls]
21
+ Repository = "https://github.com/narensen/Cleave"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["."]
25
+ include = ["cleave_ctx*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,55 @@
1
+ import tempfile
2
+ import unittest
3
+ from pathlib import Path
4
+
5
+ from cleave_ctx import Cleave
6
+
7
+
8
+ class TestCleavePythonSDK(unittest.TestCase):
9
+ def test_locate_context_search_impact_and_incremental_update(self) -> None:
10
+ with tempfile.TemporaryDirectory(prefix="cleave_py_sdk_") as tmp:
11
+ root = Path(tmp)
12
+ (root / "src").mkdir()
13
+ (root / "src" / "auth.py").write_text(
14
+ "def verify_jwt_token(token: str) -> bool:\n"
15
+ " return token.startswith('Bearer ')\n"
16
+ )
17
+ (root / "src" / "routes.py").write_text(
18
+ "from src.auth import verify_jwt_token\n\n"
19
+ "def handle_login(req):\n"
20
+ " return verify_jwt_token(req)\n"
21
+ )
22
+
23
+ with Cleave(root) as ctx:
24
+ files = ctx.locate("verify_jwt_token", limit=5)
25
+ self.assertTrue(files)
26
+ self.assertEqual(files[0].path, "src/auth.py")
27
+
28
+ bundle = ctx.context("verify_jwt_token", budget=2400, depth=2)
29
+ self.assertIn("verify_jwt_token", bundle.text)
30
+ self.assertTrue(bundle.focus)
31
+ self.assertGreater(bundle.stats.delivered_chars, 0)
32
+
33
+ hits = ctx.search("handle_login", limit=5)
34
+ self.assertTrue(any(h["hit"]["node"]["name"] == "handle_login" for h in hits))
35
+
36
+ impact = ctx.impact("verify_jwt_token", depth=2, limit=10)
37
+ self.assertIn("target", impact)
38
+
39
+ (root / "src" / "billing.py").write_text(
40
+ "def calculate_invoice_tax(amount: float) -> float:\n"
41
+ " return amount * 0.08\n"
42
+ )
43
+ upd = ctx.update_files(["src/billing.py"])
44
+ self.assertEqual(upd.updated, ["src/billing.py"])
45
+
46
+ files2 = ctx.locate("calculate_invoice_tax", limit=5)
47
+ self.assertEqual(files2[0].path, "src/billing.py")
48
+
49
+ reports = ctx.reindex()
50
+ self.assertEqual(len(reports), 1)
51
+ self.assertEqual(reports[0].total_files, 3)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ unittest.main()