cleave-ctx 0.0.0-stage → 1.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.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # cleave-ctx (JavaScript / TypeScript SDK)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 JS/TS SDK
12
+ npm install cleave-ctx
13
+ ```
14
+
15
+ ## Quickstart
16
+
17
+ ```ts
18
+ import { Cleave } from "cleave-ctx";
19
+
20
+ const ctx = new Cleave(".");
21
+ try {
22
+ const files = await ctx.locate("verifySessionCookie", { limit: 10 });
23
+ console.log(files[0].path, files[0].score);
24
+
25
+ const bundle = await ctx.context("verifySessionCookie", {
26
+ budget: 4800,
27
+ depth: 2,
28
+ });
29
+ console.log(bundle.text);
30
+
31
+ await ctx.updateFiles(["src/auth.ts"]);
32
+ } finally {
33
+ await ctx.close();
34
+ }
35
+ ```
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "cleave-ctx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Zero-GPU polyglot code localization and token-budgeted context management powered by Cleave",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "import": "./src/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "src/",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test test/cleave.test.mjs"
20
+ },
21
+ "engines": {
22
+ "node": ">=18.0.0"
23
+ },
24
+ "keywords": [
25
+ "code-search",
26
+ "context",
27
+ "ast",
28
+ "bm25",
29
+ "mcp",
30
+ "llm"
31
+ ],
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/narensen/Cleave.git"
36
+ }
37
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,103 @@
1
+ export class CleaveError extends Error {}
2
+
3
+ export interface CleaveOptions {
4
+ /** Extra workspace roots for federated symbol search and cross-repo context. */
5
+ workspaces?: string[];
6
+ /** Explicit path to the compiled `cleave` binary. */
7
+ binary?: string;
8
+ }
9
+
10
+ export interface FileHit {
11
+ path: string;
12
+ score: number;
13
+ hit_count: number;
14
+ top_symbols: string[];
15
+ }
16
+
17
+ export interface TokenSavings {
18
+ delivered_chars: number;
19
+ delivered_tokens_est: number;
20
+ naive_chars: number;
21
+ naive_tokens_est: number;
22
+ saved_pct: number;
23
+ }
24
+
25
+ export interface ContextOptions {
26
+ /** Maximum character budget for assembled context (default: 4800). */
27
+ budget?: number;
28
+ /** Graph BFS depth for dependency signatures (default: 2). */
29
+ depth?: number;
30
+ /** Include affected test symbols (default: true). */
31
+ includeTests?: boolean;
32
+ }
33
+
34
+ export interface ContextBundle {
35
+ query: string;
36
+ budgetChars: number;
37
+ text: string;
38
+ focus: Record<string, unknown>[];
39
+ relations: Record<string, unknown>[];
40
+ affectedTests: Record<string, unknown>[];
41
+ omitted: number;
42
+ stats: TokenSavings;
43
+ raw: Record<string, unknown>;
44
+ }
45
+
46
+ export interface BuildReport {
47
+ parsed: string[];
48
+ removed: string[];
49
+ unchanged: number;
50
+ total_files: number;
51
+ total_nodes: number;
52
+ total_edges: number;
53
+ }
54
+
55
+ export interface UpdateReport {
56
+ updated: string[];
57
+ removed: string[];
58
+ flipped_from_planned: string[];
59
+ flipped_files: string[];
60
+ moves: Record<string, string>;
61
+ }
62
+
63
+ export function resolveBinary(explicit?: string): string;
64
+
65
+ export class Cleave {
66
+ readonly root: string;
67
+ readonly workspaces: string[];
68
+ readonly binary: string;
69
+
70
+ constructor(root: string, options?: CleaveOptions);
71
+
72
+ locate(
73
+ query: string,
74
+ options?: { limit?: number; ablation?: string }
75
+ ): Promise<FileHit[]>;
76
+
77
+ context(query: string, options?: ContextOptions): Promise<ContextBundle>;
78
+
79
+ search(
80
+ query: string,
81
+ options?: { limit?: number }
82
+ ): Promise<Record<string, unknown>[]>;
83
+
84
+ impact(
85
+ target: string,
86
+ options?: { depth?: number; limit?: number }
87
+ ): Promise<Record<string, unknown>>;
88
+
89
+ taint(
90
+ target?: string,
91
+ options?: { depth?: number }
92
+ ): Promise<Record<string, unknown>>;
93
+
94
+ source(symbolId: string): Promise<Record<string, unknown>>;
95
+
96
+ updateFiles(relPaths: Iterable<string>): Promise<UpdateReport>;
97
+
98
+ reindex(): Promise<BuildReport[]>;
99
+
100
+ close(): Promise<void>;
101
+
102
+ [Symbol.asyncDispose](): Promise<void>;
103
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,250 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import readline from "node:readline";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ export class CleaveError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "CleaveError";
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Locate the compiled `cleave` binary via explicit path, `CLEAVE_BIN`, PATH, or local Cargo target/.
16
+ * @param {string} [explicit]
17
+ * @returns {string}
18
+ */
19
+ export function resolveBinary(explicit) {
20
+ if (explicit) {
21
+ if (fs.existsSync(explicit)) return explicit;
22
+ throw new CleaveError(`cleave binary not found at ${explicit}`);
23
+ }
24
+
25
+ if (process.env.CLEAVE_BIN && fs.existsSync(process.env.CLEAVE_BIN)) {
26
+ return process.env.CLEAVE_BIN;
27
+ }
28
+
29
+ const exe = process.platform === "win32" ? "cleave.exe" : "cleave";
30
+ const pathDirs = (process.env.PATH || "").split(path.delimiter);
31
+ for (const dir of pathDirs) {
32
+ if (!dir) continue;
33
+ const cand = path.join(dir, exe);
34
+ if (fs.existsSync(cand)) return cand;
35
+ }
36
+
37
+ const here = path.dirname(fileURLToPath(import.meta.url));
38
+ const repoRoot = path.resolve(here, "..", "..", "..");
39
+ for (const profile of ["release", "debug"]) {
40
+ const cand = path.join(repoRoot, "target", profile, exe);
41
+ if (fs.existsSync(cand)) return cand;
42
+ }
43
+
44
+ throw new CleaveError(
45
+ "Could not locate the `cleave` binary. Build it with `cargo build --release`, add it to PATH, or set CLEAVE_BIN=/path/to/cleave."
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Stateful, zero-GPU repository context manager backed by a persistent Rust `cleave` worker.
51
+ */
52
+ export class Cleave {
53
+ /**
54
+ * @param {string} root Primary repository directory
55
+ * @param {{ workspaces?: string[], binary?: string }} [options]
56
+ */
57
+ constructor(root, options = {}) {
58
+ this.root = path.resolve(root);
59
+ this.workspaces = (options.workspaces || []).map((w) => path.resolve(w));
60
+ this.binary = resolveBinary(options.binary);
61
+ this._proc = null;
62
+ this._rl = null;
63
+ this._stderr = "";
64
+ this._reqId = 0;
65
+ this._pending = new Map();
66
+ this._initPromise = null;
67
+ }
68
+
69
+ async _ensureStarted() {
70
+ if (this._proc && this._proc.exitCode === null) {
71
+ if (this._initPromise) await this._initPromise;
72
+ return;
73
+ }
74
+
75
+ const args = ["mcp", this.root];
76
+ for (const ws of this.workspaces) {
77
+ args.push("--workspace", ws);
78
+ }
79
+
80
+ const proc = spawn(this.binary, args, {
81
+ stdio: ["pipe", "pipe", "pipe"],
82
+ });
83
+ this._proc = proc;
84
+ this._stderr = "";
85
+
86
+ proc.stderr.on("data", (chunk) => {
87
+ this._stderr += chunk.toString();
88
+ });
89
+
90
+ const rl = readline.createInterface({ input: proc.stdout });
91
+ this._rl = rl;
92
+ rl.on("line", (line) => {
93
+ if (!line.trim()) return;
94
+ let msg;
95
+ try {
96
+ msg = JSON.parse(line);
97
+ } catch {
98
+ return;
99
+ }
100
+ const pending = this._pending.get(msg.id);
101
+ if (!pending) return;
102
+ this._pending.delete(msg.id);
103
+ if (msg.error) {
104
+ pending.reject(new CleaveError(msg.error.message || JSON.stringify(msg.error)));
105
+ } else {
106
+ pending.resolve(msg.result);
107
+ }
108
+ });
109
+
110
+ proc.on("exit", (code) => {
111
+ const err = new CleaveError(
112
+ `cleave worker exited (code ${code}): ${this._stderr.trim()}`
113
+ );
114
+ for (const [, p] of this._pending) {
115
+ p.reject(err);
116
+ }
117
+ this._pending.clear();
118
+ this._proc = null;
119
+ this._initPromise = null;
120
+ });
121
+
122
+ this._initPromise = this._sendRpc("initialize", {});
123
+ await this._initPromise;
124
+ }
125
+
126
+ _sendRpc(method, params) {
127
+ return new Promise((resolve, reject) => {
128
+ if (!this._proc || !this._proc.stdin.writable) {
129
+ reject(new CleaveError("cleave worker is not running"));
130
+ return;
131
+ }
132
+ const id = ++this._reqId;
133
+ this._pending.set(id, { resolve, reject });
134
+ const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params });
135
+ this._proc.stdin.write(payload + "\n");
136
+ });
137
+ }
138
+
139
+ async _callTool(name, args) {
140
+ await this._ensureStarted();
141
+ const res = await this._sendRpc("tools/call", { name, arguments: args });
142
+ const text = res?.content?.[0]?.text ?? "";
143
+ if (res?.isError) {
144
+ throw new CleaveError(text || `cleave tool \`${name}\` failed`);
145
+ }
146
+ return { text, data: res?.structuredContent ?? {} };
147
+ }
148
+
149
+ async locate(query, options = {}) {
150
+ const { data } = await this._callTool("cleave_locate", {
151
+ query,
152
+ limit: options.limit ?? 10,
153
+ ablation: options.ablation ?? "auto",
154
+ });
155
+ return data.files ?? [];
156
+ }
157
+
158
+ async context(query, options = {}) {
159
+ const { text, data } = await this._callTool("smart_context", {
160
+ query,
161
+ budget: options.budget ?? 4800,
162
+ depth: options.depth ?? 2,
163
+ include_tests: options.includeTests ?? true,
164
+ });
165
+ return {
166
+ query: data.query ?? query,
167
+ budgetChars: data.budget_chars ?? (options.budget ?? 4800),
168
+ text,
169
+ focus: data.focus ?? [],
170
+ relations: data.relations ?? [],
171
+ affectedTests: data.affected_tests ?? [],
172
+ omitted: data.omitted ?? 0,
173
+ stats: data.stats ?? {
174
+ delivered_chars: 0,
175
+ delivered_tokens_est: 0,
176
+ naive_chars: 0,
177
+ naive_tokens_est: 0,
178
+ saved_pct: 0,
179
+ },
180
+ raw: data,
181
+ };
182
+ }
183
+
184
+ async search(query, options = {}) {
185
+ const { data } = await this._callTool("cleave_search", {
186
+ query,
187
+ limit: options.limit ?? 20,
188
+ });
189
+ return data.hits ?? [];
190
+ }
191
+
192
+ async impact(target, options = {}) {
193
+ const { data } = await this._callTool("cleave_impact", {
194
+ target,
195
+ depth: options.depth ?? 3,
196
+ limit: options.limit ?? 40,
197
+ });
198
+ return data;
199
+ }
200
+
201
+ async taint(target, options = {}) {
202
+ const args = { depth: options.depth ?? 4 };
203
+ if (target) args.target = target;
204
+ const { data } = await this._callTool("cleave_taint", args);
205
+ return data;
206
+ }
207
+
208
+ async source(symbolId) {
209
+ const { data } = await this._callTool("cleave_source", { id: symbolId });
210
+ return data;
211
+ }
212
+
213
+ async updateFiles(relPaths) {
214
+ const { data } = await this._callTool("cleave_update", {
215
+ paths: Array.from(relPaths),
216
+ });
217
+ return data;
218
+ }
219
+
220
+ async reindex() {
221
+ const { data } = await this._callTool("cleave_reindex", {});
222
+ return data.reports ?? [];
223
+ }
224
+
225
+ async close() {
226
+ if (!this._proc) return;
227
+ const proc = this._proc;
228
+ this._proc = null;
229
+ this._initPromise = null;
230
+ if (this._rl) {
231
+ this._rl.close();
232
+ this._rl = null;
233
+ }
234
+ await new Promise((resolve) => {
235
+ const timer = setTimeout(() => {
236
+ proc.kill();
237
+ resolve();
238
+ }, 2000);
239
+ proc.once("exit", () => {
240
+ clearTimeout(timer);
241
+ resolve();
242
+ });
243
+ proc.stdin.end();
244
+ });
245
+ }
246
+
247
+ async [Symbol.asyncDispose]() {
248
+ await this.close();
249
+ }
250
+ }