cleave-ctx 1.0.0__py3-none-any.whl
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.
cleave_ctx/__init__.py
ADDED
|
@@ -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"
|
cleave_ctx/client.py
ADDED
|
@@ -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,6 @@
|
|
|
1
|
+
cleave_ctx/__init__.py,sha256=52jzdx2n7CkiFFA2iaEdYvUfLkb6zBQm0ZoWZzRvkWk,439
|
|
2
|
+
cleave_ctx/client.py,sha256=F3WMkaStSZg_hpmzA0PVo9I18inYy1Z36-_nznMLCoo,10417
|
|
3
|
+
cleave_ctx-1.0.0.dist-info/METADATA,sha256=OzAsp4O5dWDiefB_6cU8FDEfc2v5ClcmTj31cr_DQ58,1203
|
|
4
|
+
cleave_ctx-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
cleave_ctx-1.0.0.dist-info/top_level.txt,sha256=42UfDF6z9u8A9kwAMjBCtMZ4JVok0DS4hX5iBxBZhW8,11
|
|
6
|
+
cleave_ctx-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cleave_ctx
|