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.

Add packaged source parsers and frozen Python conformance fixtures

David Zhanga82a62c5e839
diff --git a/bun.lock b/bun.lock
index f6db5b2..736f4cd 100644
--- a/bun.lock
+++ b/bun.lock
@@ -33,12 +33,12 @@
"dependencies": {
"ai": "7.0.107",
"ignore": "7.0.5",
+ "typescript": "5.9.3",
+ "web-tree-sitter": "0.25.10",
},
"devDependencies": {
"@repo/typescript-config": "workspace:*",
- "@types/bun": "catalog:",
"@types/node": "22",
- "typescript": "catalog:",
},
},
"packages/typescript-config": {
@@ -197,6 +197,8 @@
"undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+ "web-tree-sitter": ["[email protected]", "", { "peerDependencies": { "@types/emscripten": "^1.40.0" }, "optionalPeers": ["@types/emscripten"] }, "sha512-Y09sF44/13XvgVKgO2cNDw5rGk6s26MgoZPXLESvMXeefBf7i6/73eFurre0IsTW6E14Y0ArIzhUMmjoc7xyzA=="],
+
"zod": ["[email protected]", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],
"bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-X1P21scMv4zGKLYqjdGjaKa7COa0RKVYYZZN/NfvLQ1JegxFhdhpZG/Lyn8AXx6CDUavKAd11v6BvfpkDByK8g=="],
diff --git a/packages/core/assets/README.md b/packages/core/assets/README.md
new file mode 100644
index 0000000..d36fe7a
--- /dev/null
+++ b/packages/core/assets/README.md
@@ -0,0 +1,12 @@
+# Packaged Python parser
+
+The grammar is the unmodified `tree-sitter-python.wasm` from the official
+[`[email protected]` npm tarball](https://registry.npmjs.org/tree-sitter-python/-/tree-sitter-python-0.25.0.tgz).
+Its SHA-256 is `16108b50df4ee9a30168794252ab55e7c93bfc5765d7fa0aa3e335752c515f47`.
+The adjacent MIT license comes from that same archive.
+
+Keep this directory beside the compiled source module's parent. The parser resolves
+its grammar from the module location, so installing or running from another working
+directory does not change asset lookup. The Web Tree-sitter runtime is an exact npm
+dependency with its own WASM and MIT license; it must remain available in the packed
+installation. Neither grammar nor runtime is downloaded while inspecting source.
diff --git a/packages/core/assets/tree-sitter-python.LICENSE b/packages/core/assets/tree-sitter-python.LICENSE
new file mode 100644
index 0000000..ff8ed93
--- /dev/null
+++ b/packages/core/assets/tree-sitter-python.LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Max Brunsfeld
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/core/assets/tree-sitter-python.wasm b/packages/core/assets/tree-sitter-python.wasm
new file mode 100644
index 0000000..dc9de36
Binary files /dev/null and b/packages/core/assets/tree-sitter-python.wasm differ
diff --git a/packages/core/package.json b/packages/core/package.json
index c8e6d4f..ebbb8b3 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -4,7 +4,8 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./source": "./src/source.ts"
},
"scripts": {
"check-types": "tsc --noEmit",
@@ -12,12 +13,12 @@
},
"dependencies": {
"ai": "7.0.107",
- "ignore": "7.0.5"
+ "ignore": "7.0.5",
+ "typescript": "5.9.3",
+ "web-tree-sitter": "0.25.10"
},
"devDependencies": {
"@repo/typescript-config": "workspace:*",
- "@types/bun": "catalog:",
- "@types/node": "22",
- "typescript": "catalog:"
+ "@types/node": "22"
}
}
diff --git a/packages/core/src/source.ts b/packages/core/src/source.ts
new file mode 100644
index 0000000..a7d00ec
--- /dev/null
+++ b/packages/core/src/source.ts
@@ -0,0 +1,658 @@
+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";
+
+export type Range = { startLine: number; endLine: number };
+export type Snapshot = { path: string; contentHash: string; source: string };
+export type SourceUnit = {
+ id: string;
+ name: string;
+ range: Range;
+ sourceByteStart: number;
+ sourceByteEnd: number;
+ partial?: boolean;
+};
+export type Inspection = {
+ units: SourceUnit[];
+ comments: Range[];
+ mode: "python" | "typescript" | "text";
+ 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;
+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);
+ if (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"),
+ offsets = [0];
+ for (const line of lines) offsets.push(offsets.at(-1)! + Buffer.byteLength(line) + 1);
+ return { bytes: Buffer.from(source), offsets, lineCount: lines.length };
+}
+function textUnits(
+ text: SourceText,
+ range: Range,
+ name: string,
+ maxBytes: number,
+ partial: boolean,
+): 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]!);
+ let start = first,
+ line = range.startLine;
+ while (start < end) {
+ let finish = Math.min(end, start + maxBytes);
+ if (finish < end) {
+ while (finish > start && (raw[finish]! & 0xc0) === 0x80) finish--;
+ const newline = raw.subarray(start, finish).lastIndexOf(10);
+ if (newline >= 0) finish = start + newline + 1;
+ }
+ const part = raw.subarray(start, finish).toString("utf8");
+ const newlines = part.split("\n").length - 1;
+ const endLine = line + newlines - (part.endsWith("\n") ? 1 : 0);
+ units.push({
+ id: `${name}:${start}:${finish}`,
+ name,
+ range: { startLine: line, endLine },
+ sourceByteStart: start,
+ sourceByteEnd: finish,
+ ...(partial || first !== start || finish !== end ? { partial: true } : {}),
+ });
+ line += newlines;
+ start = finish;
+ }
+ // The final empty line has no bytes but still belongs to the snapshot coordinates.
+ if (raw.at(-1) === 10 && range.endLine === lineCount && units.length)
+ units.at(-1)!.range.endLine = lineCount;
+ return units;
+}
+
+export async function inspect(
+ snapshot: Snapshot,
+ options: { maxUnitBytes?: number; maxParseBytes?: number } = {},
+): Promise<Inspection> {
+ const maxUnitBytes = options.maxUnitBytes ?? 24_000;
+ const maxParseBytes = options.maxParseBytes ?? 1_000_000;
+ if (
+ !Number.isSafeInteger(maxUnitBytes) ||
+ maxUnitBytes < 4 ||
+ !Number.isSafeInteger(maxParseBytes) ||
+ maxParseBytes < 1
+ )
+ throw new Error(
+ "Source bounds must be integers; unit bytes at least 4 and parse bytes positive",
+ );
+ const { source, path } = snapshot;
+ const text = sourceText(source);
+ const fallback = (reason: Inspection["fallback"]): Inspection => ({
+ mode: "text",
+ fallback: reason,
+ comments: [],
+ units: source
+ ? textUnits(text, { startLine: 1, endLine: text.lineCount }, "source", maxUnitBytes, true)
+ : [],
+ });
+ if (Buffer.byteLength(source) > maxParseBytes) return fallback("size");
+ let units: { name: string; range: Range }[] = [],
+ comments: Range[] = [],
+ mode: Inspection["mode"];
+ 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);
+ const stack = [tree.rootNode];
+ while (stack.length) {
+ const node = stack.pop()!;
+ if (node.type === "comment") comments.push(nodeRange(node));
+ else stack.push(...children(node));
+ }
+ mode = "python";
+ } finally {
+ tree.delete();
+ }
+ } else if (/\.(?:[cm]?[jt]s|[jt]sx)$/.test(path)) {
+ const kind = path.endsWith(".tsx")
+ ? ts.ScriptKind.TSX
+ : path.endsWith(".jsx")
+ ? ts.ScriptKind.JSX
+ : /\.[cm]?js$/.test(path)
+ ? ts.ScriptKind.JS
+ : ts.ScriptKind.TS;
+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, kind);
+ if ((file as ts.SourceFile & { parseDiagnostics?: unknown[] }).parseDiagnostics?.length)
+ return fallback("syntax");
+ const line = (position: number) => file.getLineAndCharacterOfPosition(position).line + 1;
+ const add = (node: ts.Node, prefix = "") => {
+ const named = node as ts.Node & { name?: ts.Node };
+ const name =
+ prefix +
+ (named.name?.getText(file) ||
+ (ts.isVariableStatement(node)
+ ? node.declarationList.declarations.map((d) => d.name.getText(file)).join(", ")
+ : "source"));
+ if (ts.isClassDeclaration(node) && node.members.length) {
+ const start = line(node.getStart(file)),
+ first = line(node.members[0]!.getStart(file));
+ if (first > start)
+ units.push({ name: name + ".context", range: { startLine: start, endLine: first - 1 } });
+ for (const member of node.members) add(member, name + ".");
+ } else
+ units.push({
+ name,
+ range: {
+ startLine: line(node.getStart(file)),
+ endLine: line(Math.max(node.getStart(file), node.end - 1)),
+ },
+ });
+ };
+ for (const statement of file.statements) add(statement);
+ const visit = (node: ts.Node) => {
+ for (const comment of [
+ ...(ts.getLeadingCommentRanges(source, node.getFullStart()) ?? []),
+ ...(ts.getTrailingCommentRanges(source, node.end) ?? []),
+ ])
+ comments.push({ startLine: line(comment.pos), endLine: line(comment.end - 1) });
+ for (const child of node.getChildren(file)) visit(child);
+ };
+ visit(file);
+ mode = "typescript";
+ } else return fallback("unsupported");
+ comments = [...new Map(comments.map((r) => [`${r.startLine}:${r.endLine}`, r])).values()].sort(
+ (a, b) => a.startLine - b.startLine,
+ );
+ if (!units.length && source)
+ return {
+ units: textUnits(
+ text,
+ { startLine: 1, endLine: text.lineCount },
+ "source",
+ maxUnitBytes,
+ true,
+ ),
+ comments,
+ mode,
+ };
+ return {
+ 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);
+ }),
+ };
+}
+
+/** Additive policy only: callers retain selected ranges separately. */
+export async function pythonNeighborhood(snapshot: Snapshot, selected: Range[]): 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();
+ }
+}
+
+export type PreviewSpan = Range & {
+ text: string;
+ basis: string;
+ sourceByteStart: number;
+ sourceByteEnd: number;
+ partialLine?: boolean;
+ columnStartByte?: number;
+ columnEndByte?: number;
+};
+export type SourcePreview = {
+ text: string;
+ spans: PreviewSpan[];
+ truncated: boolean;
+ sourceBytes: number;
+ previewBytes: number;
+ method: string;
+ matchedDeclarations: number;
+ unrepresentedMatches: number;
+ 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. */
+export async function pythonPreview(
+ snapshot: Snapshot,
+ query: string,
+ budget = 16_384,
+): Promise<SourcePreview> {
+ 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 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",
+ );
+ } else
+ represented = add(
+ body.startLine,
+ match.range.endLine,
+ remaining,
+ "query-named implementation",
+ );
+ if (!represented) unrepresented++;
+ }
+ }
+ 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.",
+ };
+}
+
+/** Byte spans include original line endings; never widen a partial unit to whole lines. */
+export function sourceForUnit(snapshot: Snapshot, unit: SourceUnit): string {
+ return Buffer.from(snapshot.source)
+ .subarray(unit.sourceByteStart, unit.sourceByteEnd)
+ .toString("utf8");
+}
diff --git a/test/parser/README.md b/test/parser/README.md
new file mode 100644
index 0000000..555cd62
--- /dev/null
+++ b/test/parser/README.md
@@ -0,0 +1,29 @@
+# Parser conformance
+
+The synthetic corpus in `fixtures/python-reference.json` records unmodified frozen
+Python helper results, with helper hashes. Expectations are captured in a Python
+container; application tests run the production TypeScript implementation in Node.
+`capture-reference.py` reads that corpus on stdin and writes refreshed expectations
+on stdout when the original helpers are mounted read-only at `/reference`. Capture
+output is deliberately separate from assertion: a failing port never rewrites its
+own expected result.
+
+The parser keeps class context separate from methods, includes decorators in their
+declarations, and treats function-local functions as part of the outer unit. Query
+preview windows and additive neighboring-method ranges preserve the recorded Python
+policy. Comments stay independently available for later context expansion.
+
+Intentional grammar differences are visible: Tree-sitter accepts Python-2
+`print` syntax that the Python-3 reference rejects, and actual comment tokens include
+inline comments while avoiding hashes inside strings. TypeScript comment collection
+also retains comments between tokens and before closing braces. The packaged grammar is a
+syntax inspector, not a Python interpreter or semantic validator. Syntax errors
+reported by either language parser use text chunks. Asset loading errors are setup
+failures, because silently changing behavior would hide a broken installation.
+
+Units carry byte spans into the same immutable snapshot as their one-based line
+ranges. Consumers use `sourceForUnit` for request text: widening a partial unit back
+to whole lines would defeat the bound. UTF-8 boundaries and original line endings
+survive splitting, including a single oversized line. The parser-size ceiling uses
+bounded chunks rather than discarding source. These mechanism tests do not replace
+the packed Node-only CLI conformance gate.
diff --git a/test/parser/capture-reference.py b/test/parser/capture-reference.py
new file mode 100644
index 0000000..9039d9b
--- /dev/null
+++ b/test/parser/capture-reference.py
@@ -0,0 +1,18 @@
+"""Regenerate synthetic expectations in a Python container with /reference read-only."""
+import io,json,sys,contextlib,hashlib
+from pathlib import Path
+corpus=json.load(sys.stdin)
+cases=corpus["cases"] if isinstance(corpus,dict) else corpus
+helpers=['source-method-declarations-spike.py','content-handoff-v47-spike.py','source-neighborhood-spike.py']
+for case in cases:
+ results={}
+ for helper in helpers:
+ request=case['source'] if helper==helpers[0] else json.dumps({'source':case['source'],'ranges':case['selected'],'text':case['source'],'query':case['query'],'path':case['path'],'budget':case['budget']})
+ sys.stdin=io.StringIO(request)
+ captured=io.StringIO()
+ try:
+ with contextlib.redirect_stdout(captured):exec(compile(Path('/reference',helper).read_text(),helper,'exec'),{'__name__':'__main__'})
+ results[helper]=json.loads(captured.getvalue())
+ except (SyntaxError,ValueError,RecursionError) as error:results[helper]={'error':type(error).__name__}
+ case['reference']=results
+print(json.dumps({'helpers':{name:hashlib.sha256(Path('/reference',name).read_bytes()).hexdigest() for name in helpers},'cases':cases},indent=2,ensure_ascii=False))
diff --git a/test/parser/fixtures/python-reference.json b/test/parser/fixtures/python-reference.json
new file mode 100644
index 0000000..f13fb8d
--- /dev/null
+++ b/test/parser/fixtures/python-reference.json
@@ -0,0 +1,464 @@
+{
+ "helpers": {
+ "source-method-declarations-spike.py": "05542d042d649d5af58981c8a30e263e8f6ae72a410db888b2e4a51216cf84d4",
+ "content-handoff-v47-spike.py": "05db2e67c04a5132f3abb20320c8fba45993cb2ced18f380dc902c84c186d58d",
+ "source-neighborhood-spike.py": "9971e0012f78128de5334b8238155689d838e18925a1c727838eb401cbd12673"
+ },
+ "cases": [
+ {
+ "name": "nested-decorated",
+ "source": "# module\n@decorator\nclass Café:\n \"\"\"docs\"\"\"\n value = 1\n @property\n def first(self):\n def nested():\n return \"é\"\n return nested()\n\n class Inner:\n def method(self):\n pass\n tail = 2\n",
+ "path": "sample.py",
+ "query": "first",
+ "selected": [
+ {
+ "startLine": 7,
+ "endLine": 7
+ }
+ ],
+ "budget": 512,
+ "reference": {
+ "source-method-declarations-spike.py": [
+ {
+ "name": "Café.context",
+ "startLine": 2,
+ "endLine": 5
+ },
+ {
+ "name": "Café.first",
+ "startLine": 6,
+ "endLine": 10
+ },
+ {
+ "name": "Café.context",
+ "startLine": 11,
+ "endLine": 11
+ },
+ {
+ "name": "Café.Inner.context",
+ "startLine": 12,
+ "endLine": 12
+ },
+ {
+ "name": "Café.Inner.method",
+ "startLine": 13,
+ "endLine": 14
+ },
+ {
+ "name": "Café.context",
+ "startLine": 15,
+ "endLine": 15
+ }
+ ],
+ "content-handoff-v47-spike.py": {
+ "text": "# module\n@decorator\nclass Café:\n \"\"\"docs\"\"\"\n value = 1\n @property\n def first(self):\n def nested():\n return \"é\"\n return nested()\n\n class Inner:\n def method(self):\n pass\n tail = 2\n",
+ "spans": [
+ {
+ "startLine": 1,
+ "endLine": 16,
+ "text": "# module\n@decorator\nclass Café:\n \"\"\"docs\"\"\"\n value = 1\n @property\n def first(self):\n def nested():\n return \"é\"\n return nested()\n\n class Inner:\n def method(self):\n pass\n tail = 2\n",
+ "basis": "complete source",
+ "sourceByteStart": 0,
+ "sourceByteEnd": 241
+ }
+ ],
+ "truncated": false,
+ "sourceBytes": 241,
+ "previewBytes": 241,
+ "method": "complete source",
+ "matchedDeclarations": 0,
+ "unrepresentedMatches": 0
+ },
+ "source-neighborhood-spike.py": [
+ {
+ "startLine": 2,
+ "endLine": 5
+ },
+ {
+ "startLine": 12,
+ "endLine": 14
+ }
+ ]
+ }
+ },
+ {
+ "name": "query-preview",
+ "source": "class Café:\n \"\"\"documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation documentation \"\"\"\n @staticmethod\n def target():\n \"\"\"method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs method docs \"\"\"\n return \"é漢🙂\"\n\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n",
+ "path": "sample.py",
+ "query": "Café target",
+ "selected": [
+ {
+ "startLine": 6,
+ "endLine": 6
+ }
+ ],
+ "budget": 512,
+ "reference": {
+ "source-method-declarations-spike.py": [
+ {
+ "name": "Café.context",
+ "startLine": 1,
+ "endLine": 2
+ },
+ {
+ "name": "Café.target",
+ "startLine": 3,
+ "endLine": 6
+ }
+ ],
+ "content-handoff-v47-spike.py": {
+ "text": "--- source lines 1-1; opening context ---\nclass Café:\n--- source lines 4-4; query-named implementation ---\n def target():\n--- source lines 6-6; query-named implementation ---\n return \"é漢🙂\"\n--- source lines 23-25; distributed context ---\n# padding\n# padding\n# padding\n--- source lines 37-41; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n--- source lines 62-68; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n\n",
+ "spans": [
+ {
+ "sourceByteStart": 0,
+ "sourceByteEnd": 12,
+ "startLine": 1,
+ "endLine": 1,
+ "text": "class Café:",
+ "basis": "opening context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 1022,
+ "sourceByteEnd": 1039,
+ "startLine": 4,
+ "endLine": 4,
+ "text": " def target():",
+ "basis": "query-named implementation",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 1895,
+ "sourceByteEnd": 1921,
+ "startLine": 6,
+ "endLine": 6,
+ "text": " return \"é漢🙂\"",
+ "basis": "query-named implementation",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 2073,
+ "sourceByteEnd": 2102,
+ "startLine": 23,
+ "endLine": 25,
+ "text": "# padding\n# padding\n# padding",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 2213,
+ "sourceByteEnd": 2262,
+ "startLine": 37,
+ "endLine": 41,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 2463,
+ "sourceByteEnd": 2523,
+ "startLine": 62,
+ "endLine": 68,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n",
+ "basis": "distributed context",
+ "partialLine": false
+ }
+ ],
+ "truncated": true,
+ "sourceBytes": 2523,
+ "previewBytes": 491,
+ "method": "query-assisted source windows",
+ "matchedDeclarations": 2,
+ "unrepresentedMatches": 0,
+ "parseUnavailable": false,
+ "scope": "Sampled content only; missing terms or unseen ranges do not establish irrelevance. No additional source files read."
+ },
+ "source-neighborhood-spike.py": [
+ {
+ "startLine": 1,
+ "endLine": 2
+ }
+ ]
+ }
+ },
+ {
+ "name": "inline-docstring",
+ "source": "class A:\r\n def target(self): \"docs\"; return \"漢🙂\"\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n",
+ "path": "sample.py",
+ "query": "target",
+ "selected": [
+ {
+ "startLine": 2,
+ "endLine": 2
+ }
+ ],
+ "budget": 512,
+ "reference": {
+ "source-method-declarations-spike.py": [
+ {
+ "name": "A.context",
+ "startLine": 1,
+ "endLine": 1
+ },
+ {
+ "name": "A.target",
+ "startLine": 2,
+ "endLine": 2
+ }
+ ],
+ "content-handoff-v47-spike.py": {
+ "text": "--- source lines 1-3; opening context ---\nclass A:\r\n def target(self): \"docs\"; return \"漢🙂\"\r\n# padding\r\n--- source lines 1-1; enclosing class context ---\nclass A:\r\n--- source line 2, bytes 30-47; query-named implementation; partial line ---\nreturn \"漢🙂\"\r\n--- source lines 25-25; distributed context ---\n# padding\r\n--- source lines 42-43; distributed context ---\n# padding\r\n# padding\r\n--- source lines 69-73; distributed context ---\n# padding\r\n# padding\r\n# padding\r\n# padding\r\n\n",
+ "spans": [
+ {
+ "sourceByteStart": 0,
+ "sourceByteEnd": 68,
+ "startLine": 1,
+ "endLine": 3,
+ "text": "class A:\r\n def target(self): \"docs\"; return \"漢🙂\"\r\n# padding\r",
+ "basis": "opening context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 0,
+ "sourceByteEnd": 9,
+ "startLine": 1,
+ "endLine": 1,
+ "text": "class A:\r",
+ "basis": "enclosing class context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 40,
+ "sourceByteEnd": 57,
+ "startLine": 2,
+ "endLine": 2,
+ "columnStartByte": 30,
+ "columnEndByte": 47,
+ "text": "return \"漢🙂\"\r",
+ "basis": "query-named implementation",
+ "partialLine": true
+ },
+ {
+ "sourceByteStart": 300,
+ "sourceByteEnd": 310,
+ "startLine": 25,
+ "endLine": 25,
+ "text": "# padding\r",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 487,
+ "sourceByteEnd": 508,
+ "startLine": 42,
+ "endLine": 43,
+ "text": "# padding\r\n# padding\r",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 784,
+ "sourceByteEnd": 828,
+ "startLine": 69,
+ "endLine": 73,
+ "text": "# padding\r\n# padding\r\n# padding\r\n# padding\r\n",
+ "basis": "distributed context",
+ "partialLine": false
+ }
+ ],
+ "truncated": true,
+ "sourceBytes": 828,
+ "previewBytes": 488,
+ "method": "query-assisted source windows",
+ "matchedDeclarations": 1,
+ "unrepresentedMatches": 0,
+ "parseUnavailable": false,
+ "scope": "Sampled content only; missing terms or unseen ranges do not establish irrelevance. No additional source files read."
+ },
+ "source-neighborhood-spike.py": [
+ {
+ "startLine": 1,
+ "endLine": 1
+ }
+ ]
+ }
+ },
+ {
+ "name": "conditional-declarations",
+ "source": "if True:\n def hidden():\n pass\nclass A:\n if True:\n def conditional(self):\n pass\n def visible(self):\n pass\n",
+ "path": "sample.py",
+ "query": "target",
+ "selected": [
+ {
+ "startLine": 6,
+ "endLine": 7
+ }
+ ],
+ "budget": 512,
+ "reference": {
+ "source-method-declarations-spike.py": [
+ {
+ "name": "A.context",
+ "startLine": 4,
+ "endLine": 7
+ },
+ {
+ "name": "A.visible",
+ "startLine": 8,
+ "endLine": 9
+ }
+ ],
+ "content-handoff-v47-spike.py": {
+ "text": "if True:\n def hidden():\n pass\nclass A:\n if True:\n def conditional(self):\n pass\n def visible(self):\n pass\n",
+ "spans": [
+ {
+ "startLine": 1,
+ "endLine": 10,
+ "text": "if True:\n def hidden():\n pass\nclass A:\n if True:\n def conditional(self):\n pass\n def visible(self):\n pass\n",
+ "basis": "complete source",
+ "sourceByteStart": 0,
+ "sourceByteEnd": 146
+ }
+ ],
+ "truncated": false,
+ "sourceBytes": 146,
+ "previewBytes": 146,
+ "method": "complete source",
+ "matchedDeclarations": 0,
+ "unrepresentedMatches": 0
+ },
+ "source-neighborhood-spike.py": []
+ }
+ },
+ {
+ "name": "python2",
+ "source": "def target():\n print \"old\"\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n",
+ "path": "sample.py",
+ "query": "target",
+ "selected": [],
+ "budget": 512,
+ "reference": {
+ "source-method-declarations-spike.py": {
+ "error": "SyntaxError"
+ },
+ "content-handoff-v47-spike.py": {
+ "text": "--- source lines 1-5; opening context ---\ndef target():\n print \"old\"\n# padding\n# padding\n# padding\n--- source lines 22-28; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n--- source lines 32-39; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n--- source lines 54-63; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n\n",
+ "spans": [
+ {
+ "sourceByteStart": 0,
+ "sourceByteEnd": 59,
+ "startLine": 1,
+ "endLine": 5,
+ "text": "def target():\n print \"old\"\n# padding\n# padding\n# padding",
+ "basis": "opening context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 220,
+ "sourceByteEnd": 289,
+ "startLine": 22,
+ "endLine": 28,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 320,
+ "sourceByteEnd": 399,
+ "startLine": 32,
+ "endLine": 39,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 540,
+ "sourceByteEnd": 630,
+ "startLine": 54,
+ "endLine": 63,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n",
+ "basis": "distributed context",
+ "partialLine": false
+ }
+ ],
+ "truncated": true,
+ "sourceBytes": 630,
+ "previewBytes": 487,
+ "method": "query-assisted source windows",
+ "matchedDeclarations": 0,
+ "unrepresentedMatches": 0,
+ "parseUnavailable": true,
+ "scope": "Sampled content only; missing terms or unseen ranges do not establish irrelevance. No additional source files read."
+ },
+ "source-neighborhood-spike.py": {
+ "error": "SyntaxError"
+ }
+ }
+ },
+ {
+ "name": "invalid",
+ "source": "def broken(:\n return 2\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n",
+ "path": "sample.py",
+ "query": "target",
+ "selected": [],
+ "budget": 512,
+ "reference": {
+ "source-method-declarations-spike.py": {
+ "error": "SyntaxError"
+ },
+ "content-handoff-v47-spike.py": {
+ "text": "--- source lines 1-6; opening context ---\ndef broken(:\n return 2\n# padding\n# padding\n# padding\n# padding\n--- source lines 22-28; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n--- source lines 32-39; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n--- source lines 54-63; distributed context ---\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n\n",
+ "spans": [
+ {
+ "sourceByteStart": 0,
+ "sourceByteEnd": 63,
+ "startLine": 1,
+ "endLine": 6,
+ "text": "def broken(:\n return 2\n# padding\n# padding\n# padding\n# padding",
+ "basis": "opening context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 214,
+ "sourceByteEnd": 283,
+ "startLine": 22,
+ "endLine": 28,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 314,
+ "sourceByteEnd": 393,
+ "startLine": 32,
+ "endLine": 39,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding",
+ "basis": "distributed context",
+ "partialLine": false
+ },
+ {
+ "sourceByteStart": 534,
+ "sourceByteEnd": 624,
+ "startLine": 54,
+ "endLine": 63,
+ "text": "# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n# padding\n",
+ "basis": "distributed context",
+ "partialLine": false
+ }
+ ],
+ "truncated": true,
+ "sourceBytes": 624,
+ "previewBytes": 491,
+ "method": "query-assisted source windows",
+ "matchedDeclarations": 0,
+ "unrepresentedMatches": 0,
+ "parseUnavailable": true,
+ "scope": "Sampled content only; missing terms or unseen ranges do not establish irrelevance. No additional source files read."
+ },
+ "source-neighborhood-spike.py": {
+ "error": "SyntaxError"
+ }
+ }
+ }
+ ]
+}
diff --git a/test/parser/source.test.ts b/test/parser/source.test.ts
new file mode 100644
index 0000000..a48c725
--- /dev/null
+++ b/test/parser/source.test.ts
@@ -0,0 +1,237 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { inspect } from "../../packages/core/src/source.ts";
+
+test("Python preserves decorators, class context and nested declarations", async () => {
+ const source =
+ '# module\n@decorator\nclass Café:\n """docs"""\n value = 1\n @property\n def first(self):\n def nested():\n return "é"\n return nested()\n\n class Inner:\n def method(self):\n pass\n tail = 2\n';
+ const result = await inspect({ path: "sample.py", contentHash: "fixture", source });
+ assert.equal(result.mode, "python");
+ assert.deepEqual(
+ result.units.map(({ name, range }) => ({ name, ...range })),
+ [
+ { name: "Café.context", startLine: 2, endLine: 5 },
+ { name: "Café.first", startLine: 6, endLine: 10 },
+ { name: "Café.context", startLine: 11, endLine: 11 },
+ { name: "Café.Inner.context", startLine: 12, endLine: 12 },
+ { name: "Café.Inner.method", startLine: 13, endLine: 14 },
+ { name: "Café.context", startLine: 15, endLine: 15 },
+ ],
+ );
+ assert.deepEqual(result.comments, [{ startLine: 1, endLine: 1 }]);
+});
+
+test("syntax errors and unsupported source fall back without losing source lines", async () => {
+ for (const [path, source, reason] of [
+ ["bad.py", "def broken(:\n return 2\n", "syntax"],
+ ["bad.ts", "const = ;", "syntax"],
+ ["readme.md", "éé\r\nnext\r\nlast", "unsupported"],
+ ]) {
+ const result = await inspect(
+ { path: path!, source: source!, contentHash: "fixture" },
+ { maxUnitBytes: 8 },
+ );
+ assert.equal(result.mode, "text");
+ assert.equal(result.fallback, reason);
+ assert.equal(result.units[0]!.range.startLine, 1);
+ assert.equal(result.units.at(-1)!.range.endLine, source!.split("\n").length);
+ }
+});
+
+test("oversized Unicode lines are losslessly split into bounded byte spans", async () => {
+ const source = "é漢🙂".repeat(10) + "\r\nend";
+ const result = await inspect(
+ { path: "large.txt", source, contentHash: "fixture" },
+ { maxUnitBytes: 16 },
+ );
+ const bytes = Buffer.from(source);
+ const pieces = result.units.map((unit) =>
+ bytes.subarray(unit.sourceByteStart, unit.sourceByteEnd),
+ );
+ assert.ok(pieces.every((piece) => piece.length <= 16));
+ assert.equal(
+ pieces.map((piece) => new TextDecoder("utf-8", { fatal: true }).decode(piece)).join(""),
+ source,
+ );
+ assert.ok(result.units.every((unit) => unit.partial));
+});
+
+test("selected methods add only their class header and small immediate neighbors", async () => {
+ const { pythonNeighborhood } = await import("../../packages/core/src/source.ts");
+ const source =
+ 'class Example:\n """context"""\n def first(self):\n pass\n @decorator\n def middle(self):\n pass\n def last(self):\n pass\n';
+ assert.deepEqual(
+ await pythonNeighborhood({ path: "example.py", source, contentHash: "fixture" }, [
+ { startLine: 6, endLine: 7 },
+ ]),
+ [
+ { startLine: 1, endLine: 2 },
+ { startLine: 3, endLine: 4 },
+ { startLine: 8, endLine: 9 },
+ ],
+ );
+});
+
+test("query previews preserve frozen Python source windows and bytes", async () => {
+ const { readFile } = await import("node:fs/promises");
+ const { pythonPreview } = await import("../../packages/core/src/source.ts");
+ const corpus = JSON.parse(
+ await readFile(new URL("./fixtures/python-reference.json", import.meta.url), "utf8"),
+ );
+ for (const fixture of corpus.cases.filter((f) => f.name !== "python2")) {
+ const preview = await pythonPreview(
+ { path: fixture.path, source: fixture.source, contentHash: "fixture" },
+ fixture.query,
+ fixture.budget,
+ );
+ assert.deepEqual(preview, fixture.reference["content-handoff-v47-spike.py"], fixture.name);
+ }
+});
+
+test("Python declaration and neighbor ranges agree with frozen helper corpus", async () => {
+ const { readFile } = await import("node:fs/promises");
+ const { pythonNeighborhood } = await import("../../packages/core/src/source.ts");
+ const corpus = JSON.parse(
+ await readFile(new URL("./fixtures/python-reference.json", import.meta.url), "utf8"),
+ );
+ for (const fixture of corpus.cases.filter((f) => !["python2", "invalid"].includes(f.name))) {
+ const snapshot = { path: fixture.path, source: fixture.source, contentHash: "fixture" };
+ const result = await inspect(snapshot);
+ assert.deepEqual(
+ result.units.map(({ name, range }) => ({ name, ...range })),
+ fixture.reference["source-method-declarations-spike.py"],
+ fixture.name,
+ );
+ assert.deepEqual(
+ await pythonNeighborhood(snapshot, fixture.selected),
+ fixture.reference["source-neighborhood-spike.py"],
+ fixture.name,
+ );
+ }
+});
+
+test("TS/JS uses original source coordinates, comments, and decorator-bearing members", async () => {
+ const source =
+ '/** header */\r\nexport class Box {\r\n // getter\r\n @trace\r\n get value() { return "🙂"; }\r\n}\r\n';
+ const result = await inspect({ path: "box.ts", source, contentHash: "fixture" });
+ assert.equal(result.mode, "typescript");
+ assert.deepEqual(
+ result.units.map(({ name, range }) => ({ name, ...range })),
+ [
+ { name: "Box.context", startLine: 2, endLine: 3 },
+ { name: "Box.value", startLine: 4, endLine: 5 },
+ ],
+ );
+ assert.deepEqual(result.comments, [
+ { startLine: 1, endLine: 1 },
+ { startLine: 3, endLine: 3 },
+ ]);
+});
+
+test("Python 2 syntax accepted by the packaged grammar is an explicit parser difference", async () => {
+ const source = 'def target():\n print "old"\n';
+ const result = await inspect({ path: "old.py", source, contentHash: "fixture" });
+ assert.equal(result.mode, "python");
+ assert.deepEqual(
+ result.units.map(({ name, range }) => ({ name, ...range })),
+ [{ name: "target", startLine: 1, endLine: 2 }],
+ );
+});
+
+test("trailing Python comments stay separate from AST declaration ends", async () => {
+ const source = "class A:\n def x(self):\n pass\n # tail\n";
+ const result = await inspect({ path: "a.py", source, contentHash: "fixture" });
+ assert.deepEqual(
+ result.units.map(({ name, range }) => ({ name, ...range })),
+ [
+ { name: "A.context", startLine: 1, endLine: 1 },
+ { name: "A.x", startLine: 2, endLine: 3 },
+ ],
+ );
+ assert.deepEqual(result.comments, [{ startLine: 4, endLine: 4 }]);
+});
+
+test("an f-string expression is implementation, not a Python docstring", async () => {
+ const { pythonPreview } = await import("../../packages/core/src/source.ts");
+ const source = 'def target():\n f"compute {value}"\n return 2\n' + "# filler\n".repeat(120);
+ const preview = await pythonPreview(
+ { path: "a.py", source, contentHash: "fixture" },
+ "target",
+ 600,
+ );
+ assert.ok(
+ preview.spans.some(
+ (span) => span.basis === "query-named implementation" && span.startLine === 2,
+ ),
+ );
+});
+
+test("parse ceiling still returns complete bounded text without losing CRLF", async () => {
+ const { sourceForUnit } = await import("../../packages/core/src/source.ts");
+ const source = 'def example():\r\n return "🙂"\r\n';
+ const snapshot = { path: "big.py", source, contentHash: "fixture" };
+ const result = await inspect(snapshot, { maxParseBytes: 12, maxUnitBytes: 8 });
+ assert.equal(result.fallback, "size");
+ assert.equal(result.mode, "text");
+ assert.equal(result.units.map((unit) => sourceForUnit(snapshot, unit)).join(""), source);
+ assert.ok(result.units.every((unit) => Buffer.byteLength(sourceForUnit(snapshot, unit)) <= 8));
+});
+
+test("query previews skip parenthesized Python docstrings", async () => {
+ const { pythonPreview } = await import("../../packages/core/src/source.ts");
+ const source =
+ 'def target():\n ("""' +
+ "docs ".repeat(250) +
+ '""")\n return "IMPORTANT"\n' +
+ "# filler\n".repeat(400);
+ const result = await pythonPreview(
+ { path: "a.py", source, contentHash: "fixture" },
+ "target",
+ 600,
+ );
+ assert.ok(
+ result.spans.some(
+ (span) =>
+ span.basis === "query-named implementation" &&
+ span.startLine === 3 &&
+ span.text.includes("IMPORTANT"),
+ ),
+ );
+});
+
+test("Python identifiers match normalized query names without changing source", async () => {
+ const { pythonPreview } = await import("../../packages/core/src/source.ts");
+ const source =
+ "# opening\n".repeat(40) + 'def K():\n return "important"\n' + "# filler\n".repeat(100);
+ const snapshot = { path: "a.py", source, contentHash: "fixture" };
+ assert.equal((await inspect(snapshot)).units[0]!.name, "K");
+ for (const query of ["K", "K"]) {
+ const result = await pythonPreview(snapshot, query, 600);
+ assert.equal(result.matchedDeclarations, 1);
+ assert.ok(
+ result.spans.some(
+ (span) => span.basis === "query-named implementation" && span.text.includes("important"),
+ ),
+ );
+ }
+});
+
+test("empty Python suites fall back instead of crashing query previews", async () => {
+ const { pythonPreview } = await import("../../packages/core/src/source.ts");
+ const source = "def f():\n" + "\n".repeat(700),
+ snapshot = { path: "a.py", source, contentHash: "fixture" };
+ const result = await pythonPreview(snapshot, "f", 600);
+ assert.equal(result.parseUnavailable, true);
+ assert.equal(result.matchedDeclarations, 0);
+ assert.equal((await inspect(snapshot)).mode, "text");
+});
+
+test("TS comments survive token positions without treating string contents as comments", async () => {
+ const source =
+ 'function x() {\n // end\n}\nconst x = /*important*/ 1;\nconst url="https://example.test";\nconst regexp=/https?:\\/\\//;\n';
+ const result = await inspect({ path: "comments.ts", source, contentHash: "fixture" });
+ assert.deepEqual(result.comments, [
+ { startLine: 2, endLine: 2 },
+ { startLine: 4, endLine: 4 },
+ ]);
+});