Skip to content

Find code by asking what it does. A CLI for coding agents that uses Jev to discover relevant files and source context.

Run frozen Python helpers in bundled CPython

David Zhang52f6e1536cba
diff --git a/packages/core/assets/python/inspect.py b/packages/core/assets/python/inspect.py
new file mode 100644
index 0000000..956ca16
--- /dev/null
+++ b/packages/core/assets/python/inspect.py
@@ -0,0 +1,29 @@
+"""Disposable Python declaration boundaries; no query-specific symbol selection."""
+import ast,json,sys
+source=sys.stdin.read()
+tree=ast.parse(source)
+lines=source.splitlines(keepends=True)
+units=[]
+def visit(nodes,prefix=''):
+ for node in nodes:
+ if not isinstance(node,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)):
+ continue
+ start=min([node.lineno,*[d.lineno for d in node.decorator_list]])
+ end=node.end_lineno
+ name=prefix+node.name
+ text=''.join(lines[start-1:end])
+ children=[n for n in node.body if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef))]
+ if isinstance(node,ast.ClassDef) and children:
+ cursor=start
+ for child in children:
+ child_start=min([child.lineno,*[d.lineno for d in child.decorator_list]])
+ if cursor<child_start:
+ units.append(dict(name=name+'.context',startLine=cursor,endLine=child_start-1))
+ visit([child],name+'.')
+ cursor=child.end_lineno+1
+ if cursor<=end:
+ units.append(dict(name=name+'.context',startLine=cursor,endLine=end))
+ else:
+ units.append(dict(name=name,startLine=start,endLine=end))
+visit(tree.body)
+print(json.dumps(units))
diff --git a/packages/core/assets/python/neighborhood.py b/packages/core/assets/python/neighborhood.py
new file mode 100644
index 0000000..154edae
--- /dev/null
+++ b/packages/core/assets/python/neighborhood.py
@@ -0,0 +1,27 @@
+"""Disposable structural context around positively selected Python method ranges."""
+import ast,json,sys
+request=json.load(sys.stdin)
+tree=ast.parse(request['source'])
+parents={child:node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)}
+ranges=request['ranges']
+extra=[]
+def start(node):
+ return min([node.lineno,*[d.lineno for d in getattr(node,'decorator_list',[])]])
+def add(first,last):
+ if first<=last:extra.append(dict(startLine=first,endLine=last))
+for node in ast.walk(tree):
+ if not isinstance(node,(ast.FunctionDef,ast.AsyncFunctionDef)):
+ continue
+ owner=parents.get(node)
+ if not isinstance(owner,ast.ClassDef):
+ continue
+ if not any(r['startLine']<=node.end_lineno and r['endLine']>=start(node) for r in ranges):
+ continue
+ siblings=[n for n in owner.body if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef))]
+ header_end=min([start(n)-1 for n in siblings],default=owner.end_lineno)
+ add(start(owner),min(header_end,start(owner)+39))
+ index=siblings.index(node)
+ for neighbor in siblings[max(0,index-1):index+2]:
+ if neighbor is not node and neighbor.end_lineno-start(neighbor)+1<=40:
+ add(start(neighbor),neighbor.end_lineno)
+print(json.dumps(extra))
diff --git a/packages/core/assets/python/preview.py b/packages/core/assets/python/preview.py
new file mode 100644
index 0000000..6a7224c
--- /dev/null
+++ b/packages/core/assets/python/preview.py
@@ -0,0 +1,102 @@
+"""Disposable query-assisted content windows. Never a file-admission filter."""
+import ast,json,sys,unicodedata
+
+def preview(query,path,text,budget=16384):
+ if not isinstance(budget,int) or budget<256:raise ValueError('Preview allowance must be at least 256 bytes')
+ lines=text.split('\n');source_bytes=len(text.encode())
+ line_offsets=[];offset=0
+ for line in lines:line_offsets.append(offset);offset+=len(line.encode())+1
+ if source_bytes<=budget:
+ return {'text':text,'spans':[{'startLine':1,'endLine':len(lines),'text':text,'basis':'complete source','sourceByteStart':0,'sourceByteEnd':source_bytes}],'truncated':False,'sourceBytes':source_bytes,'previewBytes':source_bytes,'method':'complete source','matchedDeclarations':0,'unrepresentedMatches':0}
+ tokens=set();token=''
+ for char in unicodedata.normalize('NFKC',query)+' ':
+ if ('_'+char).isidentifier():token+=char
+ else:
+ if token.isidentifier():tokens.add(token)
+ token=''
+ matches=[];parse_error=False
+ if path.endswith(('.py','.pyi')):
+ try:
+ tree=ast.parse(text);parents={c:p for p in ast.walk(tree) for c in ast.iter_child_nodes(p)}
+ for node in ast.walk(tree):
+ if not isinstance(node,(ast.ClassDef,ast.FunctionDef,ast.AsyncFunctionDef)) or node.name not in tokens:continue
+ start=min([node.lineno,*[d.lineno for d in node.decorator_list]])
+ owner=parents.get(node);context=None
+ while owner is not None:
+ if isinstance(owner,ast.ClassDef):
+ context=(min([owner.lineno,*[d.lineno for d in owner.decorator_list]]),owner.body[0].lineno-1);break
+ owner=parents.get(owner)
+ first=node.body[0];body=first;body_column=0
+ if isinstance(first,ast.Expr) and isinstance(getattr(first.value,'value',None),str) and len(node.body)>1:
+ body=node.body[1]
+ if body.lineno==first.lineno:body_column=body.col_offset
+ matches.append({'start':start,'end':node.end_lineno,'context':context,'header_end':first.lineno-1,'header_line':node.lineno,'header_column_end':first.col_offset if first.lineno==node.lineno else 0,'body_start':body.lineno,'body_column':body_column})
+ except (SyntaxError,ValueError,RecursionError,AttributeError):parse_error=True
+ matches.sort(key=lambda m:(m['start'],m['end']))
+ spans=[];parts=[];used=0;seen=set()
+ def add(start,end,allowance,basis,from_end=False):
+ nonlocal used
+ if start>end:return False
+ start=max(1,start);end=min(end,len(lines));allowance=min(allowance,budget-used)
+ header=f'--- source lines {start}-{end}; {basis}; may be clipped ---\n'
+ remaining=allowance-len(header.encode())-1
+ if remaining<=0:return False
+ selected=[];size=0;partial=False
+ source_lines=lines[start-1:end]
+ for line in reversed(source_lines) if from_end else source_lines:
+ cost=len(line.encode())+(1 if selected else 0)
+ if size+cost>remaining:
+ if not selected:
+ raw=line.encode();line=(raw[-remaining:] if from_end else raw[:remaining]).decode('utf-8',errors='ignore')
+ if line:selected=[line];partial=True
+ break
+ selected.append(line);size+=cost
+ if not selected:return False
+ if from_end:selected.reverse();start=end-len(selected)+1
+ actual_end=start+len(selected)-1;body='\n'.join(selected)
+ identity=(start,actual_end,body)
+ if identity in seen:return True
+ # The actual range replaces the requested range; clipping is explicit.
+ label=f'--- source lines {start}-{actual_end}; {basis}'+('; partial line' if partial else '')+' ---\n'
+ rendered=label+body+'\n'
+ if len(rendered.encode())>allowance:return False
+ byte_start=line_offsets[start-1]+(len(lines[start-1].encode())-len(body.encode()) if partial and from_end else 0)
+ seen.add(identity);spans.append({'sourceByteStart':byte_start,'sourceByteEnd':byte_start+len(body.encode()),'startLine':start,'endLine':actual_end,'text':body,'basis':basis,'partialLine':partial});parts.append(rendered);used+=len(rendered.encode());return True
+ def add_inline(line_number,start_byte,end_byte,allowance,basis):
+ nonlocal used
+ raw=lines[line_number-1].encode();end_byte=min(end_byte,len(raw));allowance=min(allowance,budget-used)
+ longest=f'--- source line {line_number}, bytes {start_byte}-{end_byte}; {basis}; partial line ---\n'
+ room=allowance-len(longest.encode())-1
+ if room<=0:return False
+ body=raw[start_byte:end_byte][:room].decode('utf-8',errors='ignore')
+ if not body:return False
+ actual_end=start_byte+len(body.encode())
+ label=f'--- source line {line_number}, bytes {start_byte}-{actual_end}; {basis}; partial line ---\n'
+ rendered=label+body+'\n';assert len(rendered.encode())<=allowance
+ identity=(line_number,start_byte,actual_end,body)
+ if identity in seen:return True
+ seen.add(identity);parts.append(rendered);used+=len(rendered.encode());spans.append({'sourceByteStart':line_offsets[line_number-1]+start_byte,'sourceByteEnd':line_offsets[line_number-1]+actual_end,'startLine':line_number,'endLine':line_number,'columnStartByte':start_byte,'columnEndByte':actual_end,'text':body,'basis':basis,'partialLine':True});return True
+ add(1,len(lines),budget//4,'opening context')
+ unrepresented=0
+ if matches:
+ per_match=max(1,int((budget-used)*.75)//len(matches))
+ for match in matches:
+ context=match['context'];context_cost=0
+ if context:
+ before=used;add(context[0],context[1],min(per_match//3,512),'enclosing class context');context_cost=used-before
+ before=used
+ add(match['start'],match['header_end'],min((per_match-context_cost)//3,512),'query-named declaration header')
+ if match['header_column_end']:add_inline(match['header_line'],0,match['header_column_end'],min((per_match-context_cost)//3,512),'query-named declaration header')
+ header_cost=used-before;remaining=per_match-context_cost-header_cost
+ if match['body_column']:
+ before=used;represented=add_inline(match['body_start'],match['body_column'],len(lines[match['body_start']-1].encode()),remaining,'query-named implementation')
+ if match['end']>match['body_start']:add(match['body_start']+1,match['end'],remaining-(used-before),'query-named implementation continuation')
+ else:represented=add(match['body_start'],match['end'],remaining,'query-named implementation')
+ if not represented:unrepresented+=1
+ # Non-matching files still have real content previews; the query never excludes them.
+ positions=sorted(set([len(lines)//3+1,2*len(lines)//3+1,max(1,len(lines)-31)]))
+ for i,start in enumerate(positions):add(start,min(start+31,len(lines)),(budget-used)//(len(positions)-i),'distributed context',from_end=i==len(positions)-1)
+ return {'text':''.join(parts),'spans':spans,'truncated':True,'sourceBytes':source_bytes,'previewBytes':used,'method':'query-assisted source windows','matchedDeclarations':len(matches),'unrepresentedMatches':unrepresented,'parseUnavailable':parse_error,'scope':'Sampled content only; missing terms or unseen ranges do not establish irrelevance. No additional source files read.'}
+
+if __name__=='__main__':
+ data=json.load(sys.stdin);json.dump(preview(data['query'],data['path'],data['text'],data.get('budget',16384)),sys.stdout)
diff --git a/packages/core/package.json b/packages/core/package.json
index ebbb8b3..98665e3 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -15,7 +15,7 @@
"ai": "7.0.107",
"ignore": "7.0.5",
"typescript": "5.9.3",
- "web-tree-sitter": "0.25.10"
+ "pyodide": "0.25.1"
},
"devDependencies": {
"@repo/typescript-config": "workspace:*",
diff --git a/packages/core/src/python-worker.mjs b/packages/core/src/python-worker.mjs
new file mode 100644
index 0000000..ea57db5
--- /dev/null
+++ b/packages/core/src/python-worker.mjs
@@ -0,0 +1,50 @@
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import { loadPyodide } from "pyodide";
+
+const indexURL = new URL(".", import.meta.resolve("pyodide/package.json"));
+// Only these trusted bundled programs execute; repository content is stdin data.
+const runtime = await loadPyodide({
+ indexURL: fileURLToPath(indexURL),
+ stdout: () => {},
+ stderr: () => {},
+});
+const sources = Object.fromEntries(
+ await Promise.all(
+ ["inspect", "preview", "neighborhood"].map(async (name) => [
+ name,
+ await readFile(new URL(`../assets/python/${name}.py`, import.meta.url), "utf8"),
+ ]),
+ ),
+);
+runtime.globals.set("helper_sources_json", JSON.stringify(sources));
+runtime.runPython(`import io, json, sys, contextlib
+helper_programs = {name: compile(source, name, 'exec') for name, source in json.loads(helper_sources_json).items()}
+def run_helper(name, request):
+ previous = sys.stdin
+ output = io.StringIO()
+ try:
+ sys.stdin = io.StringIO(request)
+ with contextlib.redirect_stdout(output):
+ exec(helper_programs[name], {'__name__': '__main__'})
+ return json.dumps({'result': json.loads(output.getvalue())})
+ except Exception as error:
+ return json.dumps({'sourceError': type(error).__name__})
+ finally:
+ sys.stdin = previous
+`);
+process.on("message", ({ id, helper, input }) => {
+ try {
+ runtime.globals.set("helper_name", helper);
+ runtime.globals.set("helper_input", input);
+ process.send({
+ id,
+ ...JSON.parse(runtime.runPython("run_helper(helper_name, helper_input)")),
+ });
+ } catch (error) {
+ process.send({ id, error: String(error) });
+ }
+});
+
+// The parent may exit with an idle interpreter; do not leave an orphan process.
+process.on("disconnect", () => process.exit(0));
diff --git a/packages/core/src/python.ts b/packages/core/src/python.ts
new file mode 100644
index 0000000..8dced9e
--- /dev/null
+++ b/packages/core/src/python.ts
@@ -0,0 +1,98 @@
+import { fork, type ChildProcess } from "node:child_process";
+
+type Helper = "inspect" | "preview" | "neighborhood";
+type Pending = {
+ helper: Helper;
+ input: string;
+ signal?: AbortSignal;
+ resolve: (value: unknown) => void;
+ reject: (error: Error) => void;
+ cleanup: () => void;
+};
+type Runtime = { worker: ChildProcess; pending: Map<number, Pending> };
+let runtime: Runtime | undefined;
+let nextId = 0;
+
+function stop(owner: Runtime, error: Error, cancellation = false) {
+ if (runtime === owner) runtime = undefined;
+ for (const request of owner.pending.values()) {
+ request.cleanup();
+ if (cancellation && !request.signal?.aborted) {
+ // Helpers have no side effects; unrelated requests can survive a cancelled interpreter.
+ runPython(request.helper, request.input, request.signal).then(
+ request.resolve,
+ request.reject,
+ );
+ } else request.reject(error);
+ }
+ owner.pending.clear();
+ owner.worker.kill();
+}
+function start(): Runtime {
+ const owner: Runtime = {
+ worker: fork(new URL("./python-worker.mjs", import.meta.url), [], {
+ execPath: process.versions.bun ? "node" : process.execPath,
+ execArgv: [],
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
+ }),
+ pending: new Map(),
+ };
+ // Runtime loader diagnostics must not bypass the CLI output contract.
+ owner.worker.on(
+ "message",
+ (message: { id: number; result?: unknown; sourceError?: string; error?: string }) => {
+ const request = owner.pending.get(message.id);
+ if (!request) return;
+ owner.pending.delete(message.id);
+ request.cleanup();
+ if (message.error) request.reject(new Error(`Python helper failed: ${message.error}`));
+ else request.resolve(message.sourceError ? null : message.result);
+ if (!owner.pending.size) {
+ owner.worker.unref();
+ owner.worker.channel?.unref?.();
+ }
+ },
+ );
+ owner.worker.on("error", (error) => stop(owner, error));
+ owner.worker.on("exit", (code) => {
+ if (runtime === owner) stop(owner, new Error(`Python worker exited (${code})`));
+ });
+ owner.worker.unref();
+ owner.worker.channel?.unref?.();
+ return owner;
+}
+
+/** One serialized interpreter; idle workers never keep a CLI alive. Cancellation discards its state. */
+export function runPython<T>(
+ helper: Helper,
+ input: string,
+ signal?: AbortSignal,
+): Promise<T | null> {
+ signal?.throwIfAborted();
+ const owner = (runtime ??= start());
+ return new Promise((resolve, reject) => {
+ const id = nextId++;
+ const abort = () =>
+ stop(
+ owner,
+ signal?.reason instanceof Error
+ ? signal.reason
+ : new DOMException("Python parsing cancelled", "AbortError"),
+ true,
+ );
+ owner.pending.set(id, {
+ helper,
+ input,
+ signal,
+ resolve: resolve as (value: unknown) => void,
+ reject,
+ cleanup: () => signal?.removeEventListener("abort", abort),
+ });
+ signal?.addEventListener("abort", abort, { once: true });
+ owner.worker.ref();
+ owner.worker.channel?.ref?.();
+ owner.worker.send({ id, helper, input }, (error) => {
+ if (error) stop(owner, error);
+ });
+ });
+}
diff --git a/packages/core/src/retrieve.ts b/packages/core/src/retrieve.ts
index 82b4d4e..1441a6a 100644
--- a/packages/core/src/retrieve.ts
+++ b/packages/core/src/retrieve.ts
@@ -223,9 +223,9 @@ export async function retrieve(input: SearchInput, evaluator: Evaluator): Promis
declarationIndexTruncated: false,
};
if (truncated && /\.pyi?$/.test(source.path) && bytes.length <= 1_000_000) {
- const sampled = await pythonPreview(source, input.query, 16384);
+ const sampled = await pythonPreview(source, input.query, 16384, input.signal);
if (
- sampled.truncated &&
+ sampled?.truncated &&
sampled.text &&
Buffer.byteLength(sampled.text) <= 16384 &&
Buffer.byteLength(JSON.stringify(sampled.text)) <= 24000
@@ -240,7 +240,10 @@ export async function retrieve(input: SearchInput, evaluator: Evaluator): Promis
/\.(?:pyi?|[cm]?[jt]s|[jt]sx)$/.test(source.path) &&
bytes.length <= 1_000_000
) {
- const syntax = await inspect(source, { maxUnitBytes: Math.max(4, bytes.length) });
+ const syntax = await inspect(source, {
+ signal: input.signal,
+ maxUnitBytes: Math.max(4, bytes.length),
+ });
preview.declarations = syntax.units
.filter((unit) => !unit.partial)
.map((unit) => ({ name: unit.name, ...unit.range }));
@@ -387,123 +390,149 @@ export async function retrieve(input: SearchInput, evaluator: Evaluator): Promis
if (failed?.status === "rejected") throw failed.reason;
}
try {
- await discover(["."]);
- let anchor: { path: string; classes: string[] } | undefined;
- for (const candidate of sortedCandidates()) {
- if (candidate.score <= 0.5 || stop) break;
- const source = await unchanged(candidate);
- if (!source) continue;
- const size = Buffer.byteLength(source.source);
- const units = (
- await inspect(source, {
- maxParseBytes: Math.max(1, size),
- maxUnitBytes: Math.max(4, size),
- })
- ).units;
- const classes = [
- ...new Set(
- units
- .filter((unit) => unit.name.endsWith(".context"))
- .map((unit) => unit.name.split(".")[0]!),
- ),
- ];
- if (classes.length && Buffer.byteLength(JSON.stringify(classes)) < 4000) {
- anchor = { path: candidate.path, classes };
- break;
+ try {
+ await discover(["."]);
+ let anchor: { path: string; classes: string[] } | undefined;
+ for (const candidate of sortedCandidates()) {
+ if (candidate.score <= 0.5 || stop) break;
+ const source = await unchanged(candidate);
+ if (!source) continue;
+ const size = Buffer.byteLength(source.source);
+ const units = (
+ await inspect(source, {
+ signal: input.signal,
+ maxParseBytes: Math.max(1, size),
+ maxUnitBytes: Math.max(4, size),
+ })
+ ).units;
+ const classes = [
+ ...new Set(
+ units
+ .filter((unit) => unit.name.endsWith(".context"))
+ .map((unit) => unit.name.split(".")[0]!),
+ ),
+ ];
+ if (classes.length && Buffer.byteLength(JSON.stringify(classes)) < 4000) {
+ anchor = { path: candidate.path, classes };
+ break;
+ }
}
- }
- if (anchor && !stop) {
- // Only one relationship reconsideration, anchored before new candidates are admitted.
- const items: NavigationItem[] = [];
- for (const item of pruned.values()) {
- if (stop) break;
- items.push(await withDirectoryContent(item));
+ if (anchor && !stop) {
+ // Only one relationship reconsideration, anchored before new candidates are admitted.
+ const items: NavigationItem[] = [];
+ for (const item of pruned.values()) {
+ if (stop) break;
+ items.push(await withDirectoryContent(item));
+ }
+ const seeds = (await score(items, anchor))
+ .filter((decision) => decision.score > 0.5)
+ .map((decision) => decision.item.path);
+ await discover(seeds, anchor);
}
- const seeds = (await score(items, anchor))
- .filter((decision) => decision.score > 0.5)
- .map((decision) => decision.item.path);
- await discover(seeds, anchor);
- }
- const ordered = [...candidates.values()];
- // All admitted paths survive even if subsequent source inspection is unavailable.
- for (const candidate of ordered)
- files.set(candidate.path, {
- ...candidate,
- roles: [],
- leads: [],
- selected: [],
- rendered: [],
- excerpts: [],
- sourceOmitted: false,
- });
- const select = async (evidence?: () => Promise<Evidence[] | undefined>) =>
- parallel(ordered, async (candidate) => {
+ const ordered = [...candidates.values()];
+ // All admitted paths survive even if subsequent source inspection is unavailable.
+ for (const candidate of ordered)
+ files.set(candidate.path, {
+ ...candidate,
+ roles: [],
+ leads: [],
+ selected: [],
+ rendered: [],
+ excerpts: [],
+ sourceOmitted: false,
+ });
+ const select = async (evidence?: () => Promise<Evidence[] | undefined>) =>
+ parallel(ordered, async (candidate) => {
+ const source = await unchanged(candidate);
+ if (!source) return;
+ if (Buffer.byteLength(source.source) > 1_000_000) {
+ issue("source_inspection_limit");
+ return;
+ }
+ const selection = await selectFile(
+ source,
+ input.query,
+ candidate.score,
+ evaluator,
+ async () => {
+ if (input.signal.aborted) throw new EvaluationFailure("cancelled");
+ const current = await unchanged(candidate);
+ if (input.signal.aborted) throw new EvaluationFailure("cancelled");
+ if (!current) return null;
+ return { evidence: await evidence?.() };
+ },
+ files.get(candidate.path),
+ input.signal,
+ );
+ files.set(candidate.path, selection.file);
+ declarations.set(candidate.path, selection.declarations);
+ for (const entry of selection.issues) issue(entry.kind, entry.count);
+ });
+ await select();
+ const evidence: Evidence[] = [];
+ // Declaration entries are inserted when selection completes, as in the frozen locations map.
+ for (const path of declarations.keys()) {
+ const candidate = candidates.get(path)!;
+ if (stop || input.signal.aborted) break;
+ if (!files.get(candidate.path)!.excerpts.length) continue;
+ // Context donors obey the same current eligibility/hash check as target files.
+ if (!(await unchanged(candidate))) continue;
+ evidence.push(
+ ...files.get(candidate.path)!.excerpts.map((excerpt) => ({
+ path: candidate.path,
+ ...excerpt.range,
+ source: excerpt.source,
+ })),
+ );
+ }
+
+ if (evidence.length && Buffer.byteLength(JSON.stringify(evidence)) <= 64_000 && !stop)
+ await select(async () => {
+ const current = new Set<string>();
+ for (const path of new Set(evidence.map((entry) => entry.path))) {
+ const candidate = candidates.get(path)!;
+ if (await unchanged(candidate)) current.add(path);
+ }
+ const fresh = evidence.filter((entry) => current.has(entry.path));
+ return fresh.length ? fresh : undefined;
+ });
+ await parallel(ordered, async (candidate) => {
const source = await unchanged(candidate);
if (!source) return;
- if (Buffer.byteLength(source.source) > 1_000_000) {
- issue("source_inspection_limit");
- return;
+ const preview = previews.get(candidate.path)!;
+ try {
+ const scores = await evaluator.evaluate(
+ roleRequest(input.query, candidate.path, preview),
+ );
+ files.get(candidate.path)!.roles = Object.keys(scores).filter(
+ (role) => scores[role]! > 0.5,
+ );
+ } catch (error) {
+ issue(error instanceof EvaluationFailure ? error.kind : "provider");
}
- const selection = await selectFile(
- source,
- input.query,
- candidate.score,
- evaluator,
- async () => {
- if (input.signal.aborted) throw new EvaluationFailure("cancelled");
- const current = await unchanged(candidate);
- if (input.signal.aborted) throw new EvaluationFailure("cancelled");
- if (!current) return null;
- return { evidence: await evidence?.() };
- },
- files.get(candidate.path),
- );
- files.set(candidate.path, selection.file);
- declarations.set(candidate.path, selection.declarations);
- for (const entry of selection.issues) issue(entry.kind, entry.count);
});
- await select();
- const evidence: Evidence[] = [];
- // Declaration entries are inserted when selection completes, as in the frozen locations map.
- for (const path of declarations.keys()) {
- const candidate = candidates.get(path)!;
- if (stop || input.signal.aborted) break;
- if (!files.get(candidate.path)!.excerpts.length) continue;
- // Context donors obey the same current eligibility/hash check as target files.
- if (!(await unchanged(candidate))) continue;
- evidence.push(
- ...files.get(candidate.path)!.excerpts.map((excerpt) => ({
- path: candidate.path,
- ...excerpt.range,
- source: excerpt.source,
- })),
- );
+ if (issues.has("authentication") && !files.size)
+ throw new EvaluationFailure("authentication");
+ } catch (error) {
+ if (
+ !input.signal.aborted ||
+ (error !== input.signal.reason && !(error instanceof Error && error.name === "AbortError"))
+ )
+ throw error;
+ issue("cancelled");
}
-
- if (evidence.length && Buffer.byteLength(JSON.stringify(evidence)) <= 64_000 && !stop)
- await select(async () => {
- const current = new Set<string>();
- for (const path of new Set(evidence.map((entry) => entry.path))) {
- const candidate = candidates.get(path)!;
- if (await unchanged(candidate)) current.add(path);
- }
- const fresh = evidence.filter((entry) => current.has(entry.path));
- return fresh.length ? fresh : undefined;
- });
- await parallel(ordered, async (candidate) => {
- const source = await unchanged(candidate);
- if (!source) return;
- const preview = previews.get(candidate.path)!;
- try {
- const scores = await evaluator.evaluate(roleRequest(input.query, candidate.path, preview));
- files.get(candidate.path)!.roles = Object.keys(scores).filter(
- (role) => scores[role]! > 0.5,
- );
- } catch (error) {
- issue(error instanceof EvaluationFailure ? error.kind : "provider");
- }
- });
- if (issues.has("authentication") && !files.size) throw new EvaluationFailure("authentication");
+ // Cancellation can occur before the selection phase creates admitted-file records.
+ for (const candidate of candidates.values())
+ if (!files.has(candidate.path))
+ files.set(candidate.path, {
+ ...candidate,
+ roles: [],
+ leads: [],
+ selected: [],
+ rendered: [],
+ excerpts: [],
+ sourceOmitted: false,
+ });
const context = await repositoryContext(
reader,
sortedCandidates().map((candidate) => files.get(candidate.path)!),
diff --git a/packages/core/src/selection.ts b/packages/core/src/selection.ts
index 7574fb9..04f24d6 100644
--- a/packages/core/src/selection.ts
+++ b/packages/core/src/selection.ts
@@ -39,6 +39,7 @@ export async function selectFile(
evaluator: Evaluator,
prepare?: () => Promise<{ evidence?: Evidence[] } | null>,
previous?: FileEvidence,
+ signal?: AbortSignal,
): Promise<SelectionResult> {
const issues = new Map<string, number>();
const warn = (kind: string) => issues.set(kind, (issues.get(kind) ?? 0) + 1);
@@ -83,12 +84,13 @@ export async function selectFile(
}
function partialLine(unit: SourceUnit) {
return (
- unit.sourceByteStart !== offsets[unit.range.startLine - 1] ||
- unit.sourceByteEnd !== offsets[unit.range.endLine]
+ unit.sourceByteStart !== (offsets[unit.range.startLine - 1] ?? bytes.length) ||
+ unit.sourceByteEnd !== (offsets[unit.range.endLine] ?? bytes.length)
);
}
const giantLine = lines.some((line) => Buffer.byteLength(line) > sourceUnitBytes);
const syntax = await inspect(snapshot, {
+ signal,
maxUnitBytes: giantLine ? sourceUnitBytes : Math.max(sourceUnitBytes, bytes.length),
});
// Giant lines retain byte coordinates; ordinary fallback uses complete-source line fragments.
@@ -123,6 +125,7 @@ export async function selectFile(
}
return blocks;
});
+ const selectedCoordinates: Range[] = [];
const selected: Span[] = (previous?.selected ?? []).map(spanForRange);
const contextSpans: Span[] = (previous?.rendered ?? []).map(spanForRange);
const leads = new Map<string, ReadingLead>();
@@ -154,6 +157,7 @@ export async function selectFile(
if (prepared === null) {
invalidated = true;
selected.length = 0;
+ selectedCoordinates.length = 0;
contextSpans.length = 0;
leads.clear();
break;
@@ -194,11 +198,14 @@ export async function selectFile(
const span = { start: unit.sourceByteStart, end: unit.sourceByteEnd };
selected.push(span);
contextSpans.push(span);
+ if (!partialLine(unit)) selectedCoordinates.push(unit.range);
}
if (value > 0.25 && !unit.name.endsWith(".context"))
addLead({
name: unit.name,
- range: rangeForSpan({ start: unit.sourceByteStart, end: unit.sourceByteEnd }),
+ range: partialLine(unit)
+ ? rangeForSpan({ start: unit.sourceByteStart, end: unit.sourceByteEnd })
+ : unit.range,
score: value,
});
}
@@ -209,14 +216,24 @@ export async function selectFile(
}
}
const chosen = mergeSpans(selected),
- wholeRanges: Range[] = [],
+ wholeRanges: Range[] = [...selectedCoordinates],
rendered: Span[] = [];
for (const span of mergeSpans(contextSpans)) {
const range = rangeForSpan(span);
if (range.sourceByteStart !== undefined) rendered.push(span);
else wholeRanges.push(range);
}
- const neighborhood = wholeRanges.length ? await pythonNeighborhood(snapshot, wholeRanges) : [];
+ let neighborhood: Range[] = [];
+ try {
+ if (wholeRanges.length) neighborhood = await pythonNeighborhood(snapshot, wholeRanges, signal);
+ } catch (error) {
+ if (
+ !signal?.aborted ||
+ (error !== signal.reason && !(error instanceof Error && error.name === "AbortError"))
+ )
+ throw error;
+ warn("cancelled");
+ }
const windows = [...wholeRanges, ...neighborhood].map((range) => ({
startLine: Math.max(1, range.startLine - 3),
endLine: Math.min(lines.length, range.endLine + 3),
diff --git a/packages/core/src/source.ts b/packages/core/src/source.ts
index 43a2ba1..3952fc1 100644
--- a/packages/core/src/source.ts
+++ b/packages/core/src/source.ts
@@ -1,7 +1,5 @@
-import { fileURLToPath } from "node:url";
-import { readFile } from "node:fs/promises";
-import { Parser, Language, type Node as SyntaxNode } from "web-tree-sitter";
import ts from "typescript";
+import { runPython } from "./python.ts";
export type Range = { startLine: number; endLine: number };
import type { Snapshot } from "./filesystem";
@@ -20,206 +18,6 @@ export type Inspection = {
fallback?: "unsupported" | "syntax" | "size";
};
-function children(node: SyntaxNode): SyntaxNode[] {
- return node.namedChildren.filter((child): child is SyntaxNode => child !== null);
-}
-
-type Declaration = {
- direct: boolean;
- name: string;
- kind: string;
- range: Range;
- headerLine: number;
- body: Range[];
- bodyColumns: number[];
- docstring: boolean;
- children: Declaration[];
- parent?: Declaration;
-};
-let pythonLanguage: Promise<Language> | undefined;
-function outsideReferenceSyntax(node: SyntaxNode): boolean {
- switch (node.type) {
- case "type_alias_statement":
- return true;
- case "function_definition":
- case "class_definition":
- return node.childForFieldName("type_parameters") !== null;
- case "interpolation":
- case "format_expression":
- case "format_specifier": {
- let owner = node.parent;
- while (owner && owner.type !== "string") owner = owner.parent;
- const start = owner
- ? (children(owner).find((child) => child.type === "string_start")?.text ?? "")
- : "";
- const delimiter = /^[a-z]*("""|'''|"|')/i.exec(start)?.[1];
- if (!/f/i.test(start) || !delimiter) return false;
- // Literal format text permits escaped line continuations; expression text never does.
- if (node.type === "format_specifier")
- return delimiter.length === 1 && /(?:^|[^\\])(?:\\\\)*\r?\n/.test(node.text);
- const expression = node.childForFieldName("expression")?.text ?? "";
- return (
- expression.includes(delimiter) ||
- expression.includes("\\") ||
- (delimiter.length === 1 && /[\r\n]/.test(expression))
- );
- }
- case "comment": {
- for (let parent = node.parent; parent; parent = parent.parent) {
- if (parent.type === "interpolation") return true;
- if (parent.type === "string") break;
- }
- return false;
- }
- case "print_statement":
- // A redirection-shaped print is also a valid Python 3 shift/tuple expression.
- return !children(node).some((child) => child.type === "chevron");
- case "exec_statement":
- return true;
- case "raise_statement":
- return children(node).some((child) => child.type === "expression_list");
- case "except_clause":
- return node.children.some((child) => child?.type === ",");
- case "comparison_operator":
- return node.children.some((child) => child?.type === "<>");
- case "integer":
- return /[lL]$/.test(node.text) || /^0[0-9_]*[1-9][0-9_]*$/.test(node.text);
- case "string_start":
- return node.text.startsWith("`") || /^(?:ur|ru)["']/i.test(node.text);
- case "tuple_pattern":
- case "list_pattern": {
- let parent = node.parent;
- while (parent && ["tuple_pattern", "list_pattern", "default_parameter"].includes(parent.type))
- parent = parent.parent;
- return parent?.type === "parameters" || parent?.type === "lambda_parameters";
- }
- default:
- return false;
- }
-}
-async function parsePython(source: string) {
- pythonLanguage ??= (async () => {
- await Parser.init({
- wasmBinary: await readFile(
- fileURLToPath(import.meta.resolve("web-tree-sitter/tree-sitter.wasm")),
- ),
- });
- return Language.load(
- fileURLToPath(new URL("../assets/tree-sitter-python.wasm", import.meta.url)),
- );
- })();
- const language = await pythonLanguage;
- const parser = new Parser();
- parser.setLanguage(language);
- try {
- const tree = parser.parse(source);
- if (!tree) return null;
- let invalid = tree.rootNode.hasError;
- const pending = [tree.rootNode];
- while (!invalid && pending.length) {
- const node = pending.pop()!;
- const nodes = children(node);
- // The grammar spans multiple Python versions; consumers share the frozen Python 3.11 boundary.
- if (
- outsideReferenceSyntax(node) ||
- (node.type === "block" && !nodes.some((child) => child.type !== "comment"))
- )
- invalid = true;
- else pending.push(...nodes);
- }
- if (invalid) {
- tree.delete();
- return null;
- }
- return tree;
- } finally {
- parser.delete();
- }
-}
-function nodeRange(node: SyntaxNode): Range {
- let last = node;
- while (last.type !== "comment") {
- const child = last.children.findLast((child) => child !== null && child.type !== "comment");
- if (!child) break;
- last = child;
- }
- return {
- startLine: node.startPosition.row + 1,
- endLine: last.endPosition.row + (last.endPosition.column === 0 ? 0 : 1),
- };
-}
-function isDocstring(node: SyntaxNode | undefined): boolean {
- if (!node) return false;
- if (node.type === "parenthesized_expression") return isDocstring(children(node)[0]);
- if (node.type === "concatenated_string") return children(node).every(isDocstring);
- return node.type === "string" && /^[rRuU]*['"]/.test(node.text);
-}
-function declarations(root: SyntaxNode, source: string): Declaration[] {
- const result: Declaration[] = [];
- const walk = (node: SyntaxNode, parent?: Declaration, direct = false) => {
- let declaration = node;
- if (node.type === "decorated_definition") declaration = node.childForFieldName("definition")!;
- if (declaration.type === "class_definition" || declaration.type === "function_definition") {
- const rawBody = children(declaration.childForFieldName("body")!).filter(
- (n) => n.type !== "comment",
- );
- const body = rawBody.map((n) =>
- n.type === "decorated_definition" ? n.childForFieldName("definition")! : n,
- );
- const first = body[0];
- const value: Declaration = {
- direct,
- name: declaration.childForFieldName("name")!.text.normalize("NFKC"),
- kind: declaration.type,
- range: nodeRange(node),
- headerLine: declaration.startPosition.row + 1,
- body: body.map(nodeRange),
- bodyColumns: body.map((n) =>
- Buffer.byteLength(source.slice(n.startIndex - n.startPosition.column, n.startIndex)),
- ),
- docstring:
- first?.type === "expression_statement" &&
- isDocstring(first.namedChildren[0] ?? undefined),
- children: [],
- parent,
- };
- result.push(value);
- if (parent && direct) parent.children.push(value);
- for (const child of rawBody) walk(child, value, true);
- return;
- }
- for (const child of children(node)) walk(child, parent);
- };
- for (const child of children(root)) walk(child, undefined, true);
- return result;
-}
-function pythonUnits(root: SyntaxNode, source: string) {
- const all = declarations(root, source);
- const units: { name: string; range: Range }[] = [];
- const visit = (declaration: Declaration, prefix = "") => {
- const name = prefix + declaration.name;
- if (declaration.kind === "class_definition" && declaration.children.length) {
- let cursor = declaration.range.startLine;
- for (const child of declaration.children) {
- if (cursor < child.range.startLine)
- units.push({
- name: name + ".context",
- range: { startLine: cursor, endLine: child.range.startLine - 1 },
- });
- visit(child, name + ".");
- cursor = child.range.endLine + 1;
- }
- if (cursor <= declaration.range.endLine)
- units.push({
- name: name + ".context",
- range: { startLine: cursor, endLine: declaration.range.endLine },
- });
- } else units.push({ name, range: declaration.range });
- };
- // The reference only promotes direct module and class body declarations.
- for (const declaration of all) if (!declaration.parent && declaration.direct) visit(declaration);
- return units;
-}
type SourceText = { bytes: Buffer; offsets: number[]; lineCount: number };
function sourceText(source: string): SourceText {
const lines = source.split("\n"),
@@ -236,8 +34,8 @@ function textUnits(
): SourceUnit[] {
const { bytes: raw, offsets, lineCount } = text;
const units: SourceUnit[] = [];
- const first = offsets[range.startLine - 1]!;
- const end = Math.min(raw.length, offsets[range.endLine]!);
+ const first = Math.min(raw.length, offsets[range.startLine - 1] ?? raw.length);
+ const end = Math.min(raw.length, offsets[range.endLine] ?? raw.length);
let start = first,
line = range.startLine;
while (start < end) {
@@ -269,7 +67,7 @@ function textUnits(
export async function inspect(
snapshot: Snapshot,
- options: { maxUnitBytes?: number; maxParseBytes?: number } = {},
+ options: { maxUnitBytes?: number; maxParseBytes?: number; signal?: AbortSignal } = {},
): Promise<Inspection> {
const maxUnitBytes = options.maxUnitBytes ?? 24_000;
const maxParseBytes = options.maxParseBytes ?? 1_000_000;
@@ -307,15 +105,15 @@ export async function inspect(
let syntaxFallback = false;
if (/\.pyi?$/.test(path)) {
// A missing/incompatible packaged parser is a setup failure, never syntax fallback.
- const tree = await parsePython(source);
- if (!tree) return fallback("syntax");
- try {
- units = pythonUnits(tree.rootNode, source);
- comments = pythonComments;
- mode = "python";
- } finally {
- tree.delete();
- }
+ const parsed = await runPython<Array<Range & { name: string }>>(
+ "inspect",
+ source,
+ options.signal,
+ );
+ if (parsed === null) return fallback("syntax");
+ units = parsed.map(({ name, startLine, endLine }) => ({ name, range: { startLine, endLine } }));
+ comments = pythonComments;
+ mode = "python";
} else if (/\.(?:[cm]?[jt]s|[jt]sx)$/.test(path)) {
const kind = path.endsWith(".tsx")
? ts.ScriptKind.TSX
@@ -384,53 +182,45 @@ export async function inspect(
mode,
comments,
units: units.flatMap((unit) => {
- const bytes =
- Math.min(text.bytes.length, text.offsets[unit.range.endLine]!) -
- text.offsets[unit.range.startLine - 1]!;
- return textUnits(text, unit.range, unit.name, maxUnitBytes, bytes > maxUnitBytes);
+ // Frozen helpers report CPython line coordinates, while the caller slices on LF.
+ // Keep those coordinates even for CR-only source or an empty LF slice.
+ const start = Math.min(
+ text.bytes.length,
+ text.offsets[unit.range.startLine - 1] ?? text.bytes.length,
+ );
+ const end = Math.min(
+ text.bytes.length,
+ text.offsets[unit.range.endLine] ?? text.bytes.length,
+ );
+ if (end - start <= maxUnitBytes)
+ return [
+ {
+ id: `${unit.name}:${start}:${end}`,
+ name: unit.name,
+ range: unit.range,
+ sourceByteStart: start,
+ sourceByteEnd: end,
+ },
+ ];
+ return textUnits(text, unit.range, unit.name, maxUnitBytes, true);
}),
};
}
/** Additive policy only: callers retain selected ranges separately. */
-export async function pythonNeighborhood(snapshot: Snapshot, selected: Range[]): Promise<Range[]> {
+export async function pythonNeighborhood(
+ snapshot: Snapshot,
+ selected: Range[],
+ signal?: AbortSignal,
+): Promise<Range[]> {
if (!/\.pyi?$/.test(snapshot.path) || Buffer.byteLength(snapshot.source) > 1_000_000) return [];
- const tree = await parsePython(snapshot.source);
- if (!tree) return [];
- try {
- const extra: Range[] = [];
- for (const declaration of declarations(tree.rootNode, snapshot.source)) {
- const owner = declaration.parent;
- if (
- !declaration.direct ||
- declaration.kind !== "function_definition" ||
- owner?.kind !== "class_definition"
- )
- continue;
- if (
- !selected.some(
- (range) =>
- range.startLine <= declaration.range.endLine &&
- range.endLine >= declaration.range.startLine,
- )
- )
- continue;
- const siblings = owner.children;
- const headerEnd = Math.min(...siblings.map((child) => child.range.startLine - 1));
- if (owner.range.startLine <= headerEnd)
- extra.push({
- startLine: owner.range.startLine,
- endLine: Math.min(headerEnd, owner.range.startLine + 39),
- });
- const index = siblings.indexOf(declaration);
- for (const neighbor of siblings.slice(Math.max(0, index - 1), index + 2))
- if (neighbor !== declaration && neighbor.range.endLine - neighbor.range.startLine + 1 <= 40)
- extra.push(neighbor.range);
- }
- return extra;
- } finally {
- tree.delete();
- }
+ return (
+ (await runPython<Range[]>(
+ "neighborhood",
+ JSON.stringify({ source: snapshot.source, ranges: selected }),
+ signal,
+ )) ?? []
+ );
}
export type PreviewSpan = Range & {
@@ -454,271 +244,60 @@ export type SourcePreview = {
parseUnavailable?: boolean;
scope?: string;
};
-function utf8Slice(raw: Buffer, start: number, end: number) {
- while (start < end && (raw[start]! & 0xc0) === 0x80) start++;
- while (end > start && end < raw.length && (raw[end]! & 0xc0) === 0x80) end--;
- return raw.subarray(start, end).toString("utf8");
-}
-
-/** Query terms prioritize preview windows; they never exclude a file. */
+/** The frozen preview program owns both Python and generic text windows. */
export async function pythonPreview(
snapshot: Snapshot,
query: string,
budget = 16_384,
-): Promise<SourcePreview> {
+ signal?: AbortSignal,
+): Promise<SourcePreview | null> {
if (!Number.isSafeInteger(budget) || budget < 256)
throw new Error("Preview allowance must be at least 256 bytes");
- const { source, path } = snapshot,
- lines = source.split("\n"),
- sourceBytes = Buffer.byteLength(source);
- const offsets: number[] = [];
- let offset = 0;
- for (const line of lines) {
- offsets.push(offset);
- offset += Buffer.byteLength(line) + 1;
- }
- if (sourceBytes <= budget)
- return {
- text: source,
- spans: [
- {
- startLine: 1,
- endLine: lines.length,
- text: source,
- basis: "complete source",
- sourceByteStart: 0,
- sourceByteEnd: sourceBytes,
- },
- ],
- truncated: false,
- sourceBytes,
- previewBytes: sourceBytes,
- method: "complete source",
- matchedDeclarations: 0,
- unrepresentedMatches: 0,
- };
- const tokens = new Set(
- (query.normalize("NFKC").match(/[\p{ID_Continue}]+/gu) ?? []).filter((token) =>
- /^[_\p{ID_Start}][_\p{ID_Continue}]*$/u.test(token),
- ),
- );
- let matches: Declaration[] = [],
- parseUnavailable = false;
- if (/\.pyi?$/.test(path)) {
- if (sourceBytes > 1_000_000) parseUnavailable = true;
- else {
- const tree = await parsePython(source);
- try {
- if (!tree) parseUnavailable = true;
- else matches = declarations(tree.rootNode, source).filter((d) => tokens.has(d.name));
- } finally {
- tree?.delete();
- }
- }
- }
- matches.sort(
- (a, b) => a.range.startLine - b.range.startLine || a.range.endLine - b.range.endLine,
+ const result = await runPython<SourcePreview>(
+ "preview",
+ JSON.stringify({ text: snapshot.source, path: snapshot.path, query, budget }),
+ signal,
);
- const spans: PreviewSpan[] = [],
- parts: string[] = [],
- seen = new Set<string>();
- let used = 0;
- const add = (first: number, last: number, allowance: number, basis: string, fromEnd = false) => {
- if (first > last) return false;
- let start = Math.max(1, first);
- const end = Math.min(last, lines.length);
- allowance = Math.min(allowance, budget - used);
- const room =
- allowance -
- Buffer.byteLength(`--- source lines ${start}-${end}; ${basis}; may be clipped ---\n`) -
- 1;
- if (room <= 0) return false;
- const selected: string[] = [];
- let size = 0,
- partial = false;
- const candidates = lines.slice(start - 1, end);
- if (fromEnd) candidates.reverse();
- for (let line of candidates) {
- const cost = Buffer.byteLength(line) + (selected.length ? 1 : 0);
- if (size + cost > room) {
- if (!selected.length) {
- const raw = Buffer.from(line);
- line = utf8Slice(
- raw,
- fromEnd ? Math.max(0, raw.length - room) : 0,
- fromEnd ? raw.length : Math.min(room, raw.length),
- );
- if (line) {
- selected.push(line);
- partial = true;
- }
- }
- break;
- }
- selected.push(line);
- size += cost;
- }
- if (!selected.length) return false;
- if (fromEnd) {
- selected.reverse();
- start = end - selected.length + 1;
- }
- const actualEnd = start + selected.length - 1,
- text = selected.join("\n"),
- identity = JSON.stringify([start, actualEnd, text]);
- if (seen.has(identity)) return true;
- const rendered = `--- source lines ${start}-${actualEnd}; ${basis}${partial ? "; partial line" : ""} ---\n${text}\n`;
- if (Buffer.byteLength(rendered) > allowance) return false;
- const sourceByteStart =
- offsets[start - 1]! +
- (partial && fromEnd ? Buffer.byteLength(lines[start - 1]!) - Buffer.byteLength(text) : 0);
- spans.push({
- sourceByteStart,
- sourceByteEnd: sourceByteStart + Buffer.byteLength(text),
- startLine: start,
- endLine: actualEnd,
- text,
- basis,
- partialLine: partial,
- });
- parts.push(rendered);
- seen.add(identity);
- used += Buffer.byteLength(rendered);
- return true;
- };
- const addInline = (
- line: number,
- start: number,
- end: number,
- allowance: number,
- basis: string,
- ) => {
- const raw = Buffer.from(lines[line - 1]!);
- end = Math.min(end, raw.length);
- allowance = Math.min(allowance, budget - used);
- const room =
- allowance -
- Buffer.byteLength(
- `--- source line ${line}, bytes ${start}-${end}; ${basis}; partial line ---\n`,
- ) -
- 1;
- if (room <= 0) return false;
- const text = utf8Slice(raw, start, Math.min(end, start + room));
- if (!text) return false;
- const actualEnd = start + Buffer.byteLength(text),
- identity = JSON.stringify([line, start, actualEnd, text]);
- if (seen.has(identity)) return true;
- const rendered = `--- source line ${line}, bytes ${start}-${actualEnd}; ${basis}; partial line ---\n${text}\n`;
- spans.push({
- sourceByteStart: offsets[line - 1]! + start,
- sourceByteEnd: offsets[line - 1]! + actualEnd,
- startLine: line,
- endLine: line,
- columnStartByte: start,
- columnEndByte: actualEnd,
- text,
- basis,
- partialLine: true,
- });
- parts.push(rendered);
- seen.add(identity);
- used += Buffer.byteLength(rendered);
- return true;
- };
- add(1, lines.length, Math.floor(budget / 4), "opening context");
- let unrepresented = 0;
- if (matches.length) {
- const perMatch = Math.max(1, (Math.floor((budget - used) * 0.75) / matches.length) | 0);
- for (const match of matches) {
- let owner = match.parent;
- while (owner && owner.kind !== "class_definition") owner = owner.parent;
- let contextCost = 0;
- if (owner) {
- const before = used;
- add(
- owner.range.startLine,
- owner.body[0]!.startLine - 1,
- Math.min(Math.floor(perMatch / 3), 512),
- "enclosing class context",
- );
- contextCost = used - before;
- }
- const before = used,
- first = match.body[0]!;
- add(
- match.range.startLine,
- first.startLine - 1,
- Math.min(Math.floor((perMatch - contextCost) / 3), 512),
- "query-named declaration header",
- );
- if (first.startLine === match.headerLine)
- addInline(
- match.headerLine,
- 0,
- match.bodyColumns[0]!,
- Math.min(Math.floor((perMatch - contextCost) / 3), 512),
- "query-named declaration header",
- );
- const remaining = perMatch - contextCost - (used - before),
- bodyIndex = match.docstring && match.body.length > 1 ? 1 : 0,
- body = match.body[bodyIndex]!;
- const bodyColumn =
- bodyIndex === 1 && body.startLine === first.startLine ? match.bodyColumns[1]! : 0;
- let represented: boolean;
- if (bodyColumn) {
- const before = used;
- represented = addInline(
- body.startLine,
- bodyColumn,
- Buffer.byteLength(lines[body.startLine - 1]!),
- remaining,
- "query-named implementation",
- );
- if (match.range.endLine > body.startLine)
- add(
- body.startLine + 1,
- match.range.endLine,
- remaining - (used - before),
- "query-named implementation continuation",
+ if (result?.truncated) {
+ const raw = Buffer.from(snapshot.source),
+ lines = snapshot.source.split("\n");
+ if (
+ !result.spans.length ||
+ result.spans.some((span) => {
+ if (
+ !Number.isInteger(span.startLine) ||
+ !Number.isInteger(span.endLine) ||
+ span.startLine < 1 ||
+ span.endLine < span.startLine ||
+ span.endLine > lines.length
+ )
+ return true;
+ if (
+ !Number.isInteger(span.sourceByteStart) ||
+ !Number.isInteger(span.sourceByteEnd) ||
+ span.sourceByteStart < 0 ||
+ span.sourceByteEnd < span.sourceByteStart ||
+ span.sourceByteEnd > raw.length ||
+ raw.subarray(span.sourceByteStart, span.sourceByteEnd).toString() !== span.text
+ )
+ return true;
+ const original = lines.slice(span.startLine - 1, span.endLine).join("\n");
+ if (span.columnStartByte !== undefined)
+ return (
+ span.startLine !== span.endLine ||
+ !Number.isInteger(span.columnStartByte) ||
+ !Number.isInteger(span.columnEndByte) ||
+ span.columnStartByte < 0 ||
+ span.columnEndByte! < span.columnStartByte ||
+ Buffer.from(original).subarray(span.columnStartByte, span.columnEndByte).toString() !==
+ span.text
);
- } else
- represented = add(
- body.startLine,
- match.range.endLine,
- remaining,
- "query-named implementation",
- );
- if (!represented) unrepresented++;
- }
+ return span.partialLine ? !original.includes(span.text) : original !== span.text;
+ })
+ )
+ return null;
}
- const positions = [
- ...new Set([
- Math.floor(lines.length / 3) + 1,
- Math.floor((2 * lines.length) / 3) + 1,
- Math.max(1, lines.length - 31),
- ]),
- ].sort((a, b) => a - b);
- for (const [index, start] of positions.entries())
- add(
- start,
- Math.min(start + 31, lines.length),
- Math.floor((budget - used) / (positions.length - index)),
- "distributed context",
- index === positions.length - 1,
- );
- return {
- text: parts.join(""),
- spans,
- truncated: true,
- sourceBytes,
- previewBytes: used,
- method: "query-assisted source windows",
- matchedDeclarations: matches.length,
- unrepresentedMatches: unrepresented,
- parseUnavailable,
- scope:
- "Sampled content only; missing terms or unseen ranges do not establish irrelevance. No additional source files read.",
- };
+ return result;
}
/** Byte spans include original line endings; never widen a partial unit to whole lines. */
diff --git a/packages/typescript-config/base.json b/packages/typescript-config/base.json
index 23ac7b9..e3a0325 100644
--- a/packages/typescript-config/base.json
+++ b/packages/typescript-config/base.json
@@ -8,6 +8,7 @@
"noUncheckedIndexedAccess": true,
"isolatedModules": true,
"skipLibCheck": true,
- "noEmit": true
+ "noEmit": true,
+ "allowImportingTsExtensions": true
}
}
diff --git a/test/parser/cpython.test.ts b/test/parser/cpython.test.ts
new file mode 100644
index 0000000..4349ae3
--- /dev/null
+++ b/test/parser/cpython.test.ts
@@ -0,0 +1,117 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { inspect } from "../../packages/core/src/source.ts";
+
+test("CPython decorator coordinates and invalid AST syntax match the frozen language boundary", async () => {
+ const snapshot = (source: string) => ({ path: "sample.py", source, contentHash: "fixture" });
+ const decorated = await inspect(snapshot("@(\n decorator\n)\ndef target():\n return 1\n"));
+ assert.deepEqual(
+ decorated.units.map(({ name, range }) => ({ name, ...range })),
+ [{ name: "target", startLine: 2, endLine: 5 }],
+ );
+ for (const source of [
+ "def target():\n del 1\n",
+ "value = [x for x in y, z]\n",
+ 'value = u"a" b"b"\n',
+ ]) {
+ assert.equal((await inspect(snapshot(source))).fallback, "syntax", source);
+ }
+});
+
+test("cancelled Python startup and active work recover without losing the next request", async () => {
+ const { runPython } = await import("../../packages/core/src/python.ts");
+ const first = new AbortController();
+ const pending = runPython("inspect", "def first():\n pass\n", first.signal);
+ first.abort();
+ await assert.rejects(pending, { name: "AbortError" });
+ assert.deepEqual(await runPython("inspect", "def recovered():\n pass\n"), [
+ { name: "recovered", startLine: 1, endLine: 2 },
+ ]);
+ const active = new AbortController();
+ const parsing = runPython("inspect", "value = 1\n".repeat(500_000), active.signal);
+ const timer = setTimeout(() => active.abort(), 20);
+ try {
+ await assert.rejects(parsing, { name: "AbortError" });
+ } finally {
+ clearTimeout(timer);
+ }
+ assert.equal(await runPython("inspect", "def broken():\n del 1\n"), null);
+ assert.deepEqual(await runPython("inspect", "def healthy():\n pass\n"), [
+ { name: "healthy", startLine: 1, endLine: 2 },
+ ]);
+});
+
+test("a completed Python helper does not keep the Node process alive", async () => {
+ const { spawn } = await import("node:child_process");
+ const child = spawn(
+ process.execPath,
+ [
+ "--experimental-strip-types",
+ "--input-type=module",
+ "-e",
+ `import { runPython } from ${JSON.stringify(new URL("../../packages/core/src/python.ts", import.meta.url).href)}; console.log(JSON.stringify(await runPython('inspect', 'def done():\\n pass\\n')));`,
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let output = "",
+ errors = "";
+ child.stdout.on("data", (chunk) => {
+ output += chunk;
+ });
+ child.stderr.on("data", (chunk) => {
+ errors += chunk;
+ });
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15_000);
+ try {
+ const code = await new Promise<number | null>((resolve, reject) => {
+ child.on("error", reject);
+ child.on("exit", resolve);
+ });
+ assert.equal(code, 0, errors);
+ assert.deepEqual(JSON.parse(output), [{ name: "done", startLine: 1, endLine: 2 }]);
+ } finally {
+ clearTimeout(timer);
+ child.kill();
+ }
+});
+
+test("bundled Python programs remain byte-identical to the frozen helpers", async () => {
+ const { readFile } = await import("node:fs/promises");
+ for (const [asset, reference] of [
+ ["inspect", "source-method-declarations"],
+ ["preview", "content-handoff-v47"],
+ ["neighborhood", "source-neighborhood"],
+ ]) {
+ assert.deepEqual(
+ await readFile(new URL(`../../packages/core/assets/python/${asset}.py`, import.meta.url)),
+ await readFile(
+ new URL(`../../evals/implementation/swebench/${reference}-spike.py`, import.meta.url),
+ ),
+ );
+ }
+});
+
+test("cancelling one query preserves unrelated concurrent Python work", async () => {
+ const { runPython } = await import("../../packages/core/src/python.ts");
+ const controller = new AbortController();
+ const cancelled = runPython("inspect", "value = 1\n".repeat(100_000), controller.signal);
+ const independent = runPython(
+ "inspect",
+ "def retained():\n pass\n",
+ new AbortController().signal,
+ );
+ controller.abort();
+ await assert.rejects(cancelled, { name: "AbortError" });
+ assert.deepEqual(await independent, [{ name: "retained", startLine: 1, endLine: 2 }]);
+});
+
+test("oversized CR-only declarations retain every source byte in bounded units", async () => {
+ const { sourceForUnit } = await import("../../packages/core/src/source.ts");
+ const source = 'def target():\r return "' + "x".repeat(25_000) + '"\r';
+ const snapshot = { path: "source.py", source, contentHash: "fixture" };
+ const result = await inspect(snapshot);
+ assert.equal(result.units.map((unit) => sourceForUnit(snapshot, unit)).join(""), source);
+ assert.ok(
+ result.units.every((unit) => Buffer.byteLength(sourceForUnit(snapshot, unit)) <= 24_000),
+ );
+});
diff --git a/test/reference/python-cancellation.test.ts b/test/reference/python-cancellation.test.ts
new file mode 100644
index 0000000..0a4db25
--- /dev/null
+++ b/test/reference/python-cancellation.test.ts
@@ -0,0 +1,47 @@
+import { expect } from "bun:test";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { testIfDocker } from "../helpers/docker";
+import { retrieve } from "../../packages/core/src/retrieve";
+
+testIfDocker(
+ "Python cancellation retains acquired selections and the next query recovers",
+ async () => {
+ const root = await mkdtemp(join(tmpdir(), "jg-python-cancel-"));
+ try {
+ await writeFile(
+ join(root, "events.py"),
+ Array.from({ length: 20 }, (_, i) => `def event${i}():\n return ${i}\n`).join(""),
+ );
+ const controller = new AbortController();
+ let groups = 0;
+ const evaluator = {
+ requests: 0,
+ async evaluate(request: Parameters<Parameters<typeof retrieve>[1]["evaluate"]>[0]) {
+ if ((request.state as { declarations?: unknown[] }).declarations && ++groups === 1)
+ controller.abort();
+ return Object.fromEntries(Object.keys(request.questions).map((id) => [id, 0.9]));
+ },
+ };
+ const result = await retrieve({ root, query: "event", signal: controller.signal }, evaluator);
+ expect(result.status).toBe("interrupted");
+ const text = result.files
+ .flatMap((file) => file.excerpts.map((excerpt) => excerpt.source))
+ .join("\n");
+ expect(text).toContain("def event0");
+ expect(text).not.toContain("def event19");
+ const next = await retrieve(
+ { root, query: "event", signal: new AbortController().signal },
+ evaluator,
+ );
+ expect(next.status).toBe("complete");
+ expect(
+ next.files.flatMap((file) => file.excerpts.map((excerpt) => excerpt.source)).join("\n"),
+ ).toContain("def event19");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ 120_000,
+);
diff --git a/test/reference/python-parity.test.ts b/test/reference/python-parity.test.ts
index 027624a..0231514 100644
--- a/test/reference/python-parity.test.ts
+++ b/test/reference/python-parity.test.ts
@@ -5,6 +5,21 @@ import { join, resolve } from "node:path";
import { testIfDocker } from "../helpers/docker";
for (const [name, source] of [
+ [
+ "parenthesized decorator",
+ "@(\n decorator\n)\ndef target():\n return 1\n" + "# padding\n".repeat(2100),
+ ],
+ [
+ "backslash decorator",
+ "@\\\n decorator\ndef target():\n return 1\n" + "# padding\n".repeat(2100),
+ ],
+ ["CR preview helper failure", "x=1\rdef target(): return 1\r#" + "x".repeat(17_000)],
+ ["mixed CR/LF source", "class Target:\r def target(self):\r return 1\n# tail\n"],
+ ["CR-only method selected", "class Target:\r def target(self):\r return 1\r"],
+ ["CR-only source", "class Target:\r def target(self):\r return 1\r"],
+ ["invalid deletion", "def target():\n del 1\n" + "# padding\n".repeat(2100)],
+ ["invalid comprehension", "value = [x for x in y, z]\n" + "# padding\n".repeat(2100)],
+ ["invalid mixed strings", 'value = u"a" b"b"\n' + "# padding\n".repeat(2100)],
["Python 2 fallback", 'def target():\n print "old"\n' + "# padding\n".repeat(2100)],
["Python 3.12 type alias fallback", "type Alias = int\n" + "# padding\n".repeat(2100)],
[
@@ -28,11 +43,24 @@ for (const [name, source] of [
const server = Bun.serve({
port: 0,
async fetch(request) {
- const body = (await request.json()) as { questions: Record<string, unknown> };
+ const body = (await request.json()) as {
+ questions: Record<string, unknown>;
+ state?: { declarations?: { name: string }[] };
+ };
requests[arm]!.push(JSON.stringify(body));
return Response.json({
answers: Object.fromEntries(
- Object.keys(body.questions).map((id) => [id, { type: "boolean", probability: 0.9 }]),
+ Object.keys(body.questions).map((id, index) => [
+ id,
+ {
+ type: "boolean",
+ probability:
+ name === "CR-only method selected" &&
+ body.state?.declarations?.[index]?.name.endsWith(".context")
+ ? 0.1
+ : 0.9,
+ },
+ ]),
),
});
},