Find code by asking what it does. A CLI for coding agents that uses Jev to discover relevant files and source context.
TypeScript ai-sdkclaude-codeclicode-searchcodexcoding-agentscontext-retrievaldeveloper-toolsjevsemantic-searchtypescriptvercel-ai-gateway
Overlap declaration groups within a file
taeskim5e0dc9ec6d91
diff --git a/packages/core/src/selection.ts b/packages/core/src/selection.tsindex c153321..d0424e7 100644--- a/packages/core/src/selection.ts+++ b/packages/core/src/selection.ts@@ -16,6 +16,9 @@ const sourceUnitBytes = 24_000;export const wholeFileContextBytes = 16_000;export const sourceBatchSize = 128;export const sourceConfidenceBoundary = 0.7;+// Declaration groups of one file are independent requests. Overlap up to this many instead of+// paying one provider round trip per group; the evaluator still bounds total concurrency.+const groupWindow = 16;export type SelectionResult = {file: FileEvidence;declarations: Array<Pick<SourceUnit, "name" | "range">>;@@ -162,106 +165,164 @@ export async function selectFile(pending.push(unit);}if (pending.length) groups.push(pending);+ type Prepared = { evidence?: Evidence[] };+ function requestFor(group: SourceUnit[], prepared: Prepared) {+ const first = Math.max(1, group[0]!.range.startLine - 8),+ last = Math.min(lines.length, group.at(-1)!.range.endLine + 8);+ const oversizedContext = [...lines.slice(0, 20), ...lines.slice(first - 1, last)].some(+ (line) => Buffer.byteLength(line) > sourceUnitBytes,+ );+ // Line-only windows cannot describe a partial giant line; send only the parser's bounded byte spans.+ const context =+ group.some(partialLine) || oversizedContext+ ? group+ .map(+ (unit) =>+ `Source lines ${unit.range.startLine}-${unit.range.endLine}; source bytes ${unit.sourceByteStart}-${unit.sourceByteEnd}:\n${sourceForUnit(snapshot, unit)}`,+ )+ .join("\n")+ : bytes.length <= 16000+ ? snapshot.source+ : `Opening context:\n${lines.slice(0, 20).join("\n")}\nSource lines ${first}-${last}:\n${lines.slice(first - 1, last).join("\n")}`;+ return evidenceRequest(+ query,+ snapshot.path,+ context,+ group.map((unit) => ({ name: unit.name, ...unit.range })),+ prepared.evidence,+ );+ }+ type Outcome =+ | { status: "invalidated" }+ | { status: "failed"; error: unknown }+ | {+ status: "answered";+ group: SourceUnit[];+ prepared: Prepared;+ answers: Record<string, number>;+ };let invalidated = false;- for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {- const group = groups[groupIndex]!;- try {- const prepared = prepare ? await prepare() : {};+ let stopped = false;+ // Requests within a window overlap. Preparation (freshness and follow-up evidence) still runs+ // before every attempt in source order, including attempts that split an oversized group, and+ // answers are applied in source order, so a healthy pass sends and records exactly what a+ // sequential pass would. After a terminal failure no further group is dispatched once the+ // failure is observed, and answers already in flight in that window are discarded.+ let next = 0;+ while (next < groups.length && !stopped) {+ const outcomes: Array<Promise<Outcome>> = [];+ let halted = false;+ while (outcomes.length < groupWindow && next < groups.length && !halted) {+ const group = groups[next]!;+ let prepared: Prepared | null;+ try {+ prepared = prepare ? await prepare() : {};+ } catch (error) {+ outcomes.push(Promise.resolve({ status: "failed", error }));+ next++;+ break;+ }if (prepared === null) {- invalidated = true;- selected.length = 0;- selectedCoordinates.length = 0;- contextSpans.length = 0;- leads.clear();+ outcomes.push(Promise.resolve({ status: "invalidated" }));+ next++;break;}- const first = Math.max(1, group[0]!.range.startLine - 8),- last = Math.min(lines.length, group.at(-1)!.range.endLine + 8);- const oversizedContext = [...lines.slice(0, 20), ...lines.slice(first - 1, last)].some(- (line) => Buffer.byteLength(line) > sourceUnitBytes,- );- // Line-only windows cannot describe a partial giant line; send only the parser's bounded byte spans.- const context =- group.some(partialLine) || oversizedContext- ? group- .map(- (unit) =>- `Source lines ${unit.range.startLine}-${unit.range.endLine}; source bytes ${unit.sourceByteStart}-${unit.sourceByteEnd}:\n${sourceForUnit(snapshot, unit)}`,- )- .join("\n")- : bytes.length <= wholeFileContextBytes- ? snapshot.source- : `Opening context:\n${lines.slice(0, 20).join("\n")}\nSource lines ${first}-${last}:\n${lines.slice(first - 1, last).join("\n")}`;- const request = evidenceRequest(- query,- snapshot.path,- context,- group.map((unit) => ({ name: unit.name, ...unit.range })),- prepared.evidence,- );+ const request = requestFor(group, prepared);// Shared evidence contributes to the state limit as well as local source.if (group.length > 1 && Buffer.byteLength(JSON.stringify(request.state)) > 80_000) {const middle = Math.ceil(group.length / 2);- groups.splice(groupIndex, 1, group.slice(0, middle), group.slice(middle));- groupIndex--;+ groups.splice(next, 1, group.slice(0, middle), group.slice(middle));continue;}- const answers = await evaluator.evaluate(request);- const values = group.map((unit, index) => {- const values = [- answers[`q${index}`],- answers[`scope${index}`],- ...(prepared.evidence !== undefined ? [answers[`ref${index}`]] : []),- ];- if (- values.some(- (value) =>- typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1,+ // A terminal failure can be observed while this group was being prepared.+ if (halted) break;+ const current = prepared;+ outcomes.push(+ (async (): Promise<Outcome> => {+ try {+ const answers = await evaluator.evaluate(request);+ return { status: "answered", group, prepared: current, answers };+ } catch (error) {+ if (!(error instanceof EvaluationFailure && error.kind === "provider")) halted = true;+ return { status: "failed", error };+ }+ })(),+ );+ next++;+ }+ // Every dispatched request settles before its window is applied or the file is returned.+ for (const outcome of await Promise.all(outcomes)) {+ if (outcome.status === "invalidated") {+ invalidated = true;+ stopped = true;+ selected.length = 0;+ selectedCoordinates.length = 0;+ contextSpans.length = 0;+ leads.clear();+ break;+ }+ try {+ if (outcome.status === "failed") throw outcome.error;+ const { group, prepared, answers } = outcome;+ const values = group.map((unit, index) => {+ const values = [+ answers[`q${index}`],+ answers[`scope${index}`],+ ...(prepared.evidence !== undefined ? [answers[`ref${index}`]] : []),+ ];+ if (+ values.some(+ (value) =>+ typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1,+ ))- )- throw new EvaluationFailure("provider");- return { unit, value: Math.max(Math.min(values[0]!, values[1]!), values[2] ?? 0) };- });- for (const { unit, value } of values) {- const decisionSpan = { start: unit.sourceByteStart, end: unit.sourceByteEnd };- sourceDecisions.set(`${decisionSpan.start}:${decisionSpan.end}`, {- range: rangeForSpan(decisionSpan),- score: value,+ throw new EvaluationFailure("provider");+ return { unit, value: Math.max(Math.min(values[0]!, values[1]!), values[2] ?? 0) };});- // Only a valid contextual rejection retracts an earlier selection.- // Failed or unprocessed groups retain their previous source spans.- if (prepared.evidence !== undefined && value <= 0.5) {- const start = unit.sourceByteStart,- end = unit.sourceByteEnd;- const retained = selected.flatMap((span) => {- if (span.end <= start || span.start >= end) return [span];- return [- ...(span.start < start ? [{ start: span.start, end: start }] : []),- ...(span.end > end ? [{ start: end, end: span.end }] : []),- ];+ for (const { unit, value } of values) {+ const decisionSpan = { start: unit.sourceByteStart, end: unit.sourceByteEnd };+ sourceDecisions.set(`${decisionSpan.start}:${decisionSpan.end}`, {+ range: rangeForSpan(decisionSpan),+ score: value,});- selected.splice(0, selected.length, ...retained);+ // Only a valid contextual rejection retracts an earlier selection.+ // Failed or unprocessed groups retain their previous source spans.+ if (prepared.evidence !== undefined && value <= 0.5) {+ const start = unit.sourceByteStart,+ end = unit.sourceByteEnd;+ const retained = selected.flatMap((span) => {+ if (span.end <= start || span.start >= end) return [span];+ return [+ ...(span.start < start ? [{ start: span.start, end: start }] : []),+ ...(span.end > end ? [{ start: end, end: span.end }] : []),+ ];+ });+ selected.splice(0, selected.length, ...retained);+ }+ if (value > 0.5) {+ 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: partialLine(unit)+ ? rangeForSpan({ start: unit.sourceByteStart, end: unit.sourceByteEnd })+ : unit.range,+ score: value,+ });}- if (value > 0.5) {- const span = { start: unit.sourceByteStart, end: unit.sourceByteEnd };- selected.push(span);- contextSpans.push(span);- if (!partialLine(unit)) selectedCoordinates.push(unit.range);+ } catch (error) {+ if (!(error instanceof EvaluationFailure)) throw error;+ warn(error.kind);+ if (error.kind === "provider") providerFailure ??= error.message;+ if (error.kind !== "provider") {+ stopped = true;+ break;}- if (value > 0.25 && !unit.name.endsWith(".context"))- addLead({- name: unit.name,- range: partialLine(unit)- ? rangeForSpan({ start: unit.sourceByteStart, end: unit.sourceByteEnd })- : unit.range,- score: value,- });}- } catch (error) {- if (!(error instanceof EvaluationFailure)) throw error;- warn(error.kind);- if (error.kind === "provider") providerFailure ??= error.message;- if (error.kind !== "provider") break;}}const chosen = mergeSpans(selected),diff --git a/packages/core/test/selection.test.ts b/packages/core/test/selection.test.tsindex 88b6ef7..b1e5e94 100644--- a/packages/core/test/selection.test.ts+++ b/packages/core/test/selection.test.ts@@ -107,7 +107,7 @@ test("valid contextual rejection retracts selection without promoting surroundinexpect(second.file.roles).toEqual(["implementation"]);});-test("provider failures retain successful groups and fatal failures stop subsequent groups", async () => {+test("provider failures retain successful groups and fatal failures discard subsequent groups", async () => {const source = Array.from({ length: 400 }, (_, i) => `function f${i}() { return ${i}; }\n`).join("",);@@ -133,7 +133,8 @@ test("provider failures retain successful groups and fatal failures stop subsequ);expect(result.issues).toEqual([{ kind, count: 1 }]);if (kind === "provider") expect(calls).toBeGreaterThan(2);- else expect(calls).toBe(2);+ // All four groups share one window and are sent before the failure is observed.+ else expect(calls).toBe(4);expect(result.file.selected[0]?.startLine).toBe(1);expect(result.file.selected.some((range) => range.endLine === 400)).toBe(kind === "provider");expect(rejected.length).toBeGreaterThan(0);@@ -274,3 +275,97 @@ test("scope excludes analogous code while a concrete reference can recover it",expect(second.file.selected).toEqual([{ startLine: 1, endLine: 1 }]);expect(second.file.presentationExcerpts?.[0]?.source).toContain("export function helper()");});++test("a file's groups overlap while preparation and applied answers keep source order", async () => {+ // 600 declarations make five groups of at most 128.+ const source = Array.from({ length: 600 }, (_, i) => `function f${i}() { return ${i}; }\n`).join(+ "",+ );+ let preparing = false;+ let prepares = 0;+ let active = 0;+ let maxActive = 0;+ const fake: Evaluator = {+ requests: 0,+ async evaluate(request) {+ active++;+ maxActive = Math.max(maxActive, active);+ const first = (request.state as { declarations: Declaration[] }).declarations[0]!;+ // Later groups answer first, so applying answers in completion order would reorder leads.+ const group = Math.floor(Number(first.name.slice(1)) / 128);+ await new Promise((resolve) => setTimeout(resolve, 50 - group * 10));+ active--;+ return Object.fromEntries(Object.keys(request.questions).map((id) => [id, 0.9]));+ },+ };+ const result = await selectFile(+ { path: "ordered.ts", contentHash: "ordered", source },+ "q",+ 0.9,+ fake,+ async () => {+ expect(preparing).toBe(false);+ preparing = true;+ prepares++;+ await new Promise((resolve) => setTimeout(resolve, 1));+ preparing = false;+ return {};+ },+ );+ expect(prepares).toBe(5);+ expect(maxActive).toBe(5);+ expect(result.issues).toEqual([]);+ expect(result.file.leads.map((lead) => lead.name)).toEqual(+ Array.from({ length: 600 }, (_, i) => `f${i}`),+ );+ expect(result.file.selected).toEqual([{ startLine: 1, endLine: 600 }]);+});++test("a failure or invalidation observed during preparation stops later dispatch", async () => {+ const snapshot = {+ path: "stop.ts",+ contentHash: "stop",+ source: Array.from({ length: 600 }, (_, i) => `function f${i}() { return ${i}; }\n`).join(""),+ };+ let calls = 0;+ const failed = await selectFile(+ snapshot,+ "q",+ 0.9,+ {+ requests: 0,+ async evaluate() {+ calls++;+ throw new EvaluationFailure("authentication");+ },+ },+ async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ return {};+ },+ );+ expect(calls).toBe(1);+ expect(failed.issues).toEqual([{ kind: "authentication", count: 1 }]);+ expect(failed.file.selected).toEqual([]);++ let prepares = 0;+ let requests = 0;+ const invalidated = await selectFile(+ snapshot,+ "q",+ 0.9,+ {+ requests: 0,+ async evaluate(request) {+ requests++;+ return Object.fromEntries(Object.keys(request.questions).map((id) => [id, 0.9]));+ },+ },+ async () => (++prepares === 3 ? null : {}),+ );+ expect(prepares).toBe(3);+ expect(requests).toBe(2);+ expect(invalidated.file.sourceOmitted).toBe(true);+ expect(invalidated.file.selected).toEqual([]);+ expect(invalidated.file.leads).toEqual([]);+});