-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgraph_proxy.ts
More file actions
276 lines (249 loc) · 10.4 KB
/
Copy pathgraph_proxy.ts
File metadata and controls
276 lines (249 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* graphify integration proxy (v0.13.0)
* =====================================
*
* Spawns + speaks to a `graphify.serve` MCP subprocess so SC's MCP tools
* can query the structural knowledge graph that graphify built. Adds three
* new SC tools (zc_graph_query, zc_graph_path, zc_graph_neighbors) that
* forward to graphify's exposed MCP methods (query_graph, get_node,
* get_neighbors, shortest_path).
*
* WHY THIS EXISTS
* ---------------
* graphify (https://github.com/safishamsi/graphify) builds a structural
* knowledge graph of a codebase using tree-sitter AST + Claude subagents
* and exposes it as MCP. SC's strength is persistent state + multi-agent
* coordination + telemetry; graphify's strength is structural map of code
* + multimodal corpus. They stack multiplicatively for token savings on
* architectural questions:
*
* "How does auth work?"
* Without either: read 5-10 auth files (~25k tokens)
* SC alone: BM25/vector chunks (~2k tokens)
* graphify alone: god-node + community (~500 tokens orient)
* STACKED: graph orient → SC fetch precise ~1.5k tokens
*
* DESIGN
* ------
* - graphify is OPTIONAL. SC works without Python or graphify installed.
* - When called, we look for `graphify-out/graph.json` in the project.
* If absent: return a helpful "run /graphify ." hint.
* If present: spawn `python -m graphify.serve graphify-out/graph.json`
* over stdio, send a JSON-RPC request, return the response.
* - Lazy spawn — no graphify subprocess until first zc_graph_* call.
* - Subprocess is reused across calls within a session (cached handle).
*
* SECURITY
* --------
* - graphify subprocess runs with the SAME UID as the SC server (no
* privilege escalation).
* - Project path is normalized + validated before being passed (no shell
* interpolation; uses spawn with arg array).
* - Subprocess timeout: 10 s per call.
* - Stderr output is captured + logged at WARN level (debugging surface).
*/
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import { join, isAbsolute, resolve } from "node:path";
import { logger } from "./logger.js";
// ─── Cache: per-project graphify subprocess + JSON-RPC channel ─────────────
interface GraphifyHandle {
proc: ChildProcessWithoutNullStreams;
buffer: string;
pendingResolvers: Map<number, (val: unknown) => void>;
pendingRejecters: Map<number, (err: Error) => void>;
nextRequestId: number;
}
const _handles = new Map<string, GraphifyHandle>();
const SUBPROCESS_TIMEOUT_MS = 10_000;
const PYTHON_CMD = process.env.ZC_PYTHON_CMD || (process.platform === "win32" ? "python" : "python3");
/** Normalize + validate project path — defense against weird inputs. */
function normalizeProjectPath(projectPath: string): string {
if (typeof projectPath !== "string" || !projectPath) {
throw new Error("graph_proxy: projectPath must be a non-empty string");
}
if (!isAbsolute(projectPath)) {
throw new Error(`graph_proxy: projectPath must be absolute, got: ${projectPath}`);
}
return resolve(projectPath);
}
/** Locate graphify-out/graph.json relative to a project. Returns null if absent. */
export function findGraphifyOutput(projectPath: string): string | null {
const candidate = join(projectPath, "graphify-out", "graph.json");
try {
if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
} catch { /* fall through */ }
return null;
}
/** Locate GRAPH_REPORT.md alongside graph.json. Returns null if absent. */
export function findGraphReport(projectPath: string): string | null {
const candidate = join(projectPath, "graphify-out", "GRAPH_REPORT.md");
try {
if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
} catch { /* fall through */ }
return null;
}
/**
* Lazily spawn (or reuse) a graphify.serve subprocess for a project.
* Returns null if graphify-out/graph.json is missing (caller should hint).
*/
async function ensureHandle(projectPath: string): Promise<GraphifyHandle | null> {
projectPath = normalizeProjectPath(projectPath);
const existing = _handles.get(projectPath);
if (existing && !existing.proc.killed) return existing;
const graphPath = findGraphifyOutput(projectPath);
if (!graphPath) return null;
let proc: ChildProcessWithoutNullStreams;
try {
proc = spawn(PYTHON_CMD, ["-m", "graphify.serve", graphPath], {
cwd: projectPath,
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env },
});
} catch (e) {
logger.warn("retrieval", "graphify_spawn_failed", { error: (e as Error).message });
return null;
}
const handle: GraphifyHandle = {
proc,
buffer: "",
pendingResolvers: new Map(),
pendingRejecters: new Map(),
nextRequestId: 1,
};
proc.stdout.setEncoding("utf8");
proc.stdout.on("data", (chunk) => {
handle.buffer += chunk;
// graphify uses NDJSON or JSON-RPC over stdio. Try parsing complete lines.
let nl;
while ((nl = handle.buffer.indexOf("\n")) !== -1) {
const line = handle.buffer.slice(0, nl).trim();
handle.buffer = handle.buffer.slice(nl + 1);
if (!line) continue;
try {
const msg = JSON.parse(line) as { id?: number; result?: unknown; error?: { message?: string } };
if (typeof msg.id !== "number") continue;
const resolveFn = handle.pendingResolvers.get(msg.id);
const rejectFn = handle.pendingRejecters.get(msg.id);
if (resolveFn && rejectFn) {
handle.pendingResolvers.delete(msg.id);
handle.pendingRejecters.delete(msg.id);
if (msg.error) rejectFn(new Error(msg.error.message ?? "graphify error"));
else resolveFn(msg.result);
}
} catch {
// malformed line — log + continue
logger.debug("retrieval", "graphify_parse_skip", { line: line.slice(0, 200) });
}
}
});
proc.stderr.setEncoding("utf8");
proc.stderr.on("data", (chunk: string) => {
logger.warn("retrieval", "graphify_stderr", { msg: chunk.toString().slice(0, 500) });
});
proc.on("exit", (code) => {
logger.info("retrieval", "graphify_subprocess_exit", { code });
_handles.delete(projectPath);
// Reject any in-flight requests
for (const [, reject] of handle.pendingRejecters) {
reject(new Error(`graphify subprocess exited with code ${code}`));
}
handle.pendingResolvers.clear();
handle.pendingRejecters.clear();
});
_handles.set(projectPath, handle);
return handle;
}
/**
* Send a JSON-RPC request to the graphify subprocess and await its reply.
* Returns null on timeout, missing subprocess, or error.
*/
async function callGraphify(
projectPath: string,
method: string,
params: Record<string, unknown>,
): Promise<unknown | null> {
const handle = await ensureHandle(projectPath);
if (!handle) return null;
const id = handle.nextRequestId++;
const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";
const responsePromise = new Promise<unknown>((resolve, reject) => {
handle.pendingResolvers.set(id, resolve);
handle.pendingRejecters.set(id, reject);
});
try {
handle.proc.stdin.write(msg);
} catch (e) {
handle.pendingResolvers.delete(id);
handle.pendingRejecters.delete(id);
logger.warn("retrieval", "graphify_write_failed", { error: (e as Error).message });
return null;
}
const timeoutPromise = new Promise<null>((resolve) => {
setTimeout(() => {
handle.pendingResolvers.delete(id);
handle.pendingRejecters.delete(id);
logger.warn("retrieval", "graphify_call_timeout", { method, id });
resolve(null);
}, SUBPROCESS_TIMEOUT_MS);
});
return Promise.race([responsePromise, timeoutPromise]).catch((e) => {
logger.warn("retrieval", "graphify_call_error", { method, error: (e as Error).message });
return null;
});
}
// ─── Public API ────────────────────────────────────────────────────────────
export interface GraphQueryResult {
ok: boolean;
hint?: string; // human-readable guidance when graphify isn't set up
data?: unknown; // forwarded from graphify
error?: string;
}
/**
* Query the graph in natural language. Forwards to graphify's `query_graph`.
* Returns matching nodes with relationships and confidence tags.
*/
export async function graphQuery(projectPath: string, query: string): Promise<GraphQueryResult> {
if (!findGraphifyOutput(projectPath)) {
return {
ok: false,
hint: `No graphify graph found at ${join(projectPath, "graphify-out", "graph.json")}. ` +
`Run \`/graphify .\` in this project (requires the graphify CLI: \`pip install graphifyy && graphify install\`). ` +
`Then retry zc_graph_query.`,
};
}
const result = await callGraphify(projectPath, "query_graph", { query });
if (result === null) return { ok: false, error: "graphify call failed (see logs)" };
return { ok: true, data: result };
}
/**
* Find the shortest path between two named nodes. Forwards to graphify's
* `shortest_path`. Useful for "how does X connect to Y" questions.
*/
export async function graphPath(projectPath: string, from: string, to: string): Promise<GraphQueryResult> {
if (!findGraphifyOutput(projectPath)) {
return { ok: false, hint: `No graphify graph found. Run \`/graphify .\` first.` };
}
const result = await callGraphify(projectPath, "shortest_path", { from, to });
if (result === null) return { ok: false, error: "graphify call failed" };
return { ok: true, data: result };
}
/**
* Get the immediate neighbors of a named node. Forwards to graphify's
* `get_neighbors`. Useful for "what's related to X" questions.
*/
export async function graphNeighbors(projectPath: string, node: string): Promise<GraphQueryResult> {
if (!findGraphifyOutput(projectPath)) {
return { ok: false, hint: `No graphify graph found. Run \`/graphify .\` first.` };
}
const result = await callGraphify(projectPath, "get_neighbors", { node });
if (result === null) return { ok: false, error: "graphify call failed" };
return { ok: true, data: result };
}
/** Shut down all cached graphify subprocesses (called on SC server exit). */
export function shutdownAllGraphifyHandles(): void {
for (const [, handle] of _handles) {
try { handle.proc.kill(); } catch { /* ignore */ }
}
_handles.clear();
}