opencode-codebase-index 0.16.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1708,7 +1708,12 @@ function sameReclaimOwner(left, right) {
1708
1708
  }
1709
1709
  function publishJsonDirectory(finalPath, value) {
1710
1710
  const candidatePath = `${finalPath}.candidate.${process.pid}.${randomUUID()}`;
1711
- mkdirSync2(candidatePath, { mode: 448 });
1711
+ try {
1712
+ mkdirSync2(candidatePath, { mode: 448 });
1713
+ } catch (error) {
1714
+ if (getErrorCode(error) === "ENOENT") return false;
1715
+ throw error;
1716
+ }
1712
1717
  try {
1713
1718
  writeFileSync2(path7.join(candidatePath, OWNER_FILE_NAME), JSON.stringify(value), {
1714
1719
  encoding: "utf-8",
@@ -1721,8 +1726,12 @@ function publishJsonDirectory(finalPath, value) {
1721
1726
  return true;
1722
1727
  } catch (error) {
1723
1728
  if (existsSync5(finalPath)) return false;
1729
+ if (getErrorCode(error) === "ENOENT") return false;
1724
1730
  throw error;
1725
1731
  }
1732
+ } catch (error) {
1733
+ if (getErrorCode(error) === "ENOENT") return false;
1734
+ throw error;
1726
1735
  } finally {
1727
1736
  if (existsSync5(candidatePath)) rmSync(candidatePath, { recursive: true, force: true });
1728
1737
  }
@@ -6578,6 +6587,27 @@ function mergeTieredResults(symbolLane, hybridLane, limit) {
6578
6587
  }
6579
6588
  return out;
6580
6589
  }
6590
+ function selectChunksWithFileCoverage(chunks, limit) {
6591
+ if (limit <= 0 || chunks.length === 0) {
6592
+ return [];
6593
+ }
6594
+ if (chunks.length <= limit) {
6595
+ return chunks;
6596
+ }
6597
+ if (limit === 1) {
6598
+ return [chunks[Math.floor((chunks.length - 1) / 2)]];
6599
+ }
6600
+ const selected = [];
6601
+ for (let index = 0; index < limit; index++) {
6602
+ const sourceIndex = Math.round(index * (chunks.length - 1) / (limit - 1));
6603
+ selected.push(chunks[sourceIndex]);
6604
+ }
6605
+ return selected;
6606
+ }
6607
+ function selectIndexableChunks(chunks, limit, semanticOnly) {
6608
+ const indexableChunks = semanticOnly ? chunks.filter((chunk) => chunk.chunkType !== "other") : chunks;
6609
+ return selectChunksWithFileCoverage(indexableChunks, limit);
6610
+ }
6581
6611
  function matchesSearchFilters(candidate, options, minScore) {
6582
6612
  if (candidate.score < minScore) return false;
6583
6613
  if (options?.fileType) {
@@ -8316,7 +8346,6 @@ var Indexer = class {
8316
8346
  const relativePath = path13.relative(this.projectRoot, parsed.path);
8317
8347
  stats.parseFailures.push(relativePath);
8318
8348
  }
8319
- let fileChunkCount = 0;
8320
8349
  let chunksToProcess = parsed.chunks;
8321
8350
  if (this.config.indexing.fallbackToTextOnMaxChunks && chunksToProcess.length > this.config.indexing.maxChunksPerFile) {
8322
8351
  const changedFile = changedFiles.find((f) => f.path === parsed.path);
@@ -8325,13 +8354,12 @@ var Indexer = class {
8325
8354
  chunksToProcess = textChunks;
8326
8355
  }
8327
8356
  }
8357
+ chunksToProcess = selectIndexableChunks(
8358
+ chunksToProcess,
8359
+ this.config.indexing.maxChunksPerFile,
8360
+ this.config.indexing.semanticOnly
8361
+ );
8328
8362
  for (const chunk of chunksToProcess) {
8329
- if (fileChunkCount >= this.config.indexing.maxChunksPerFile) {
8330
- break;
8331
- }
8332
- if (this.config.indexing.semanticOnly && chunk.chunkType === "other") {
8333
- continue;
8334
- }
8335
8363
  const id = generateChunkId(parsed.path, chunk);
8336
8364
  const contentHash = generateChunkHash(chunk);
8337
8365
  const existingContentHash = existingChunks.get(id);
@@ -8355,7 +8383,6 @@ var Indexer = class {
8355
8383
  blameSummary: blameMetadata.blameSummary
8356
8384
  });
8357
8385
  if (existingContentHash === contentHash) {
8358
- fileChunkCount++;
8359
8386
  continue;
8360
8387
  }
8361
8388
  const texts = createEmbeddingTexts(chunk, parsed.path, getSafeEmbeddingChunkTokenLimit(configuredProviderInfo)).map((text) => ({
@@ -8380,7 +8407,6 @@ var Indexer = class {
8380
8407
  contentHash,
8381
8408
  metadata
8382
8409
  });
8383
- fileChunkCount++;
8384
8410
  }
8385
8411
  }
8386
8412
  const retryableFailedChunks = this.collectRetryableFailedChunks(
@@ -9971,6 +9997,159 @@ function findKnowledgeBasePathIndex(knowledgeBases, inputPath, projectRoot) {
9971
9997
  }
9972
9998
 
9973
9999
  // src/tools/utils.ts
10000
+ import { get_encoding } from "tiktoken";
10001
+ var MIN_CONTEXT_PACK_TOKEN_BUDGET = 128;
10002
+ var MAX_CONTEXT_PACK_TOKEN_BUDGET = 4e3;
10003
+ var DEFAULT_CONTEXT_PACK_TOKEN_BUDGET = 1200;
10004
+ var CONTEXT_TOKENIZER = get_encoding("cl100k_base");
10005
+ function clampContextPackTokenBudget(tokenBudget) {
10006
+ if (tokenBudget === void 0 || !Number.isFinite(tokenBudget)) {
10007
+ return DEFAULT_CONTEXT_PACK_TOKEN_BUDGET;
10008
+ }
10009
+ return Math.min(
10010
+ MAX_CONTEXT_PACK_TOKEN_BUDGET,
10011
+ Math.max(MIN_CONTEXT_PACK_TOKEN_BUDGET, Math.floor(tokenBudget))
10012
+ );
10013
+ }
10014
+ function countContextTokens(text) {
10015
+ return CONTEXT_TOKENIZER.encode(text).length;
10016
+ }
10017
+ function fitTextToContextBudget(text, tokenBudget) {
10018
+ const normalizedBudget = clampContextPackTokenBudget(tokenBudget);
10019
+ const tokenEstimate = countContextTokens(text);
10020
+ if (tokenEstimate <= normalizedBudget) {
10021
+ return {
10022
+ text,
10023
+ tokenBudget: normalizedBudget,
10024
+ tokenEstimate,
10025
+ truncated: false
10026
+ };
10027
+ }
10028
+ const suffix = "\n...[truncated to context token budget]";
10029
+ const codePoints = Array.from(text);
10030
+ let low = 0;
10031
+ let high = codePoints.length;
10032
+ while (low < high) {
10033
+ const middle = Math.ceil((low + high) / 2);
10034
+ const candidate = `${codePoints.slice(0, middle).join("").trimEnd()}${suffix}`;
10035
+ if (countContextTokens(candidate) <= normalizedBudget) low = middle;
10036
+ else high = middle - 1;
10037
+ }
10038
+ const fitted = `${codePoints.slice(0, low).join("").trimEnd()}${suffix}`;
10039
+ return {
10040
+ text: fitted,
10041
+ tokenBudget: normalizedBudget,
10042
+ tokenEstimate: countContextTokens(fitted),
10043
+ truncated: true
10044
+ };
10045
+ }
10046
+ function normalizedLineRange(result) {
10047
+ return result.startLine <= result.endLine ? { start: result.startLine, end: result.endLine } : { start: result.endLine, end: result.startLine };
10048
+ }
10049
+ function rankContextCandidates(results) {
10050
+ return results.map((result, originalIndex) => ({ result, originalIndex })).sort((left, right) => right.result.score - left.result.score || left.originalIndex - right.originalIndex);
10051
+ }
10052
+ function deduplicateContextCandidates(candidates) {
10053
+ const acceptedByFile = /* @__PURE__ */ new Map();
10054
+ const deduplicated = [];
10055
+ for (const { result } of candidates) {
10056
+ const range = normalizedLineRange(result);
10057
+ const accepted = acceptedByFile.get(result.filePath) ?? [];
10058
+ if (accepted.some((item) => item.start <= range.end && range.start <= item.end)) {
10059
+ continue;
10060
+ }
10061
+ accepted.push(range);
10062
+ acceptedByFile.set(result.filePath, accepted);
10063
+ deduplicated.push(result);
10064
+ }
10065
+ return deduplicated;
10066
+ }
10067
+ function diversifyContextCandidates(results) {
10068
+ const byFile = /* @__PURE__ */ new Map();
10069
+ for (const result of results) {
10070
+ const bucket = byFile.get(result.filePath) ?? [];
10071
+ bucket.push(result);
10072
+ byFile.set(result.filePath, bucket);
10073
+ }
10074
+ const files = [...byFile.keys()];
10075
+ const diversified = [];
10076
+ for (let depth = 0; diversified.length < results.length; depth += 1) {
10077
+ for (const file of files) {
10078
+ const result = byFile.get(file)?.[depth];
10079
+ if (result) diversified.push(result);
10080
+ }
10081
+ }
10082
+ return diversified;
10083
+ }
10084
+ function compactEvidenceValue(value, maxChars) {
10085
+ const characters = [...value];
10086
+ if (characters.length <= maxChars) return value;
10087
+ return `\u2026${characters.slice(-(maxChars - 1)).join("")}`;
10088
+ }
10089
+ function formatContextEvidence(result, index) {
10090
+ const symbol = result.name ? ` ${JSON.stringify(compactEvidenceValue(result.name, 80))}` : "";
10091
+ const path24 = compactEvidenceValue(result.filePath, 120);
10092
+ return `[${index}] ${result.chunkType}${symbol} in ${path24}:${result.startLine}-${result.endLine} (score ${result.score.toFixed(2)})`;
10093
+ }
10094
+ function formatContextPack(heading, selected, candidateCount, duplicateCount, limitOmittedCount, budgetOmittedCount) {
10095
+ const lines = selected.map((result, index) => formatContextEvidence(result, index + 1));
10096
+ const notes = [];
10097
+ if (duplicateCount > 0) notes.push(`${duplicateCount} overlapping duplicate${duplicateCount === 1 ? "" : "s"} removed`);
10098
+ if (limitOmittedCount > 0) notes.push(`${limitOmittedCount} additional result${limitOmittedCount === 1 ? "" : "s"} excluded by result limit`);
10099
+ if (budgetOmittedCount > 0) notes.push(`${budgetOmittedCount} additional result${budgetOmittedCount === 1 ? "" : "s"} omitted by token budget`);
10100
+ const footer = notes.length > 0 ? `Selected ${selected.length} of ${candidateCount} candidates; ${notes.join("; ")}.` : `Selected ${selected.length} of ${candidateCount} candidates.`;
10101
+ return `${heading}
10102
+
10103
+ ${lines.join("\n")}
10104
+
10105
+ ${footer}`;
10106
+ }
10107
+ function buildContextPack(results, options = {}) {
10108
+ const requestedTokenBudget = options.tokenBudget ?? DEFAULT_CONTEXT_PACK_TOKEN_BUDGET;
10109
+ const tokenBudget = clampContextPackTokenBudget(options.tokenBudget);
10110
+ const heading = compactEvidenceValue(options.heading?.trim() || "Codebase evidence", 160);
10111
+ const maxResults = Math.max(0, Math.floor(options.maxResults ?? results.length));
10112
+ const candidateCount = results.length;
10113
+ const deduplicated = deduplicateContextCandidates(rankContextCandidates(results));
10114
+ const diversified = diversifyContextCandidates(deduplicated);
10115
+ const duplicateCount = candidateCount - deduplicated.length;
10116
+ const selectable = diversified.slice(0, maxResults);
10117
+ const limitOmittedCount = deduplicated.length - selectable.length;
10118
+ let selected = [];
10119
+ let text = formatContextPack(heading, selected, candidateCount, duplicateCount, limitOmittedCount, selectable.length);
10120
+ for (let count = 1; count <= selectable.length; count += 1) {
10121
+ const candidateSelection = selectable.slice(0, count);
10122
+ const budgetOmittedCount2 = selectable.length - candidateSelection.length;
10123
+ const candidateText = formatContextPack(
10124
+ heading,
10125
+ candidateSelection,
10126
+ candidateCount,
10127
+ duplicateCount,
10128
+ limitOmittedCount,
10129
+ budgetOmittedCount2
10130
+ );
10131
+ if (countContextTokens(candidateText) > tokenBudget) break;
10132
+ selected = candidateSelection;
10133
+ text = candidateText;
10134
+ }
10135
+ const fitted = fitTextToContextBudget(text, tokenBudget);
10136
+ const budgetOmittedCount = selectable.length - selected.length;
10137
+ const omittedCount = candidateCount - selected.length;
10138
+ return {
10139
+ requestedTokenBudget,
10140
+ tokenBudget,
10141
+ text: fitted.text,
10142
+ tokenEstimate: fitted.tokenEstimate,
10143
+ results: selected,
10144
+ candidateCount,
10145
+ deduplicatedCount: deduplicated.length,
10146
+ selectedCount: selected.length,
10147
+ omittedCount,
10148
+ duplicateCount,
10149
+ limitOmittedCount,
10150
+ budgetOmittedCount
10151
+ };
10152
+ }
9974
10153
  var MAX_CONTENT_LINES = 30;
9975
10154
  function truncateContent(content) {
9976
10155
  const lines = content.split("\n");
@@ -12800,6 +12979,253 @@ var pr_impact = tool({
12800
12979
  }
12801
12980
  });
12802
12981
 
12982
+ // src/tools/symbol-inference.ts
12983
+ var IDENTIFIER_RE = /[A-Za-z_$][A-Za-z0-9_$]*/g;
12984
+ var QUOTED_BACKTICK_RE = /`([^`]+)`/g;
12985
+ var QUOTED_SINGLE_RE = /'([^'\\]+)'/g;
12986
+ var QUOTED_DOUBLE_RE = /"([^"]+)"/g;
12987
+ var SYMBOL_LIKE_RE = /^(?:[A-Za-z_$][A-Za-z0-9_$]*)$/;
12988
+ var CAMEL_CASE_RE = /^[a-z_][A-Za-z0-9_$]*[A-Z][A-Za-z0-9_$]*$/;
12989
+ var PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9_$]*$/;
12990
+ var SNAKE_CASE_RE = /^[a-z][a-z0-9_]*_[a-z0-9_]+$/;
12991
+ var DEFINITION_INTENT_RE = /\b(where|defined|definition|define|declaration|symbol|function|method|class|interface|type)\b/i;
12992
+ var STOP_WORDS = /* @__PURE__ */ new Set([
12993
+ "a",
12994
+ "an",
12995
+ "and",
12996
+ "are",
12997
+ "at",
12998
+ "for",
12999
+ "find",
13000
+ "how",
13001
+ "i",
13002
+ "in",
13003
+ "is",
13004
+ "it",
13005
+ "of",
13006
+ "on",
13007
+ "that",
13008
+ "the",
13009
+ "definition",
13010
+ "show",
13011
+ "to",
13012
+ "where",
13013
+ "which",
13014
+ "what",
13015
+ "you",
13016
+ "your",
13017
+ "with"
13018
+ ]);
13019
+ function stripCallSuffix(token) {
13020
+ return token.replace(/\(\s*\)$/, "");
13021
+ }
13022
+ function isLikelySymbolName(token) {
13023
+ if (!SYMBOL_LIKE_RE.test(token)) {
13024
+ return false;
13025
+ }
13026
+ if (STOP_WORDS.has(token.toLowerCase())) {
13027
+ return false;
13028
+ }
13029
+ return CAMEL_CASE_RE.test(token) || PASCAL_CASE_RE.test(token) || SNAKE_CASE_RE.test(token);
13030
+ }
13031
+ function extractQuotedIdentifiers(query) {
13032
+ const identifiers = /* @__PURE__ */ new Set();
13033
+ for (const match of query.matchAll(QUOTED_BACKTICK_RE)) {
13034
+ const candidate = stripCallSuffix(match[1].trim());
13035
+ if (candidate && isLikelySymbolName(candidate)) {
13036
+ identifiers.add(candidate);
13037
+ }
13038
+ }
13039
+ for (const match of query.matchAll(QUOTED_SINGLE_RE)) {
13040
+ const candidate = stripCallSuffix(match[1].trim());
13041
+ if (candidate && isLikelySymbolName(candidate)) {
13042
+ identifiers.add(candidate);
13043
+ }
13044
+ }
13045
+ for (const match of query.matchAll(QUOTED_DOUBLE_RE)) {
13046
+ const candidate = stripCallSuffix(match[1].trim());
13047
+ if (candidate && isLikelySymbolName(candidate)) {
13048
+ identifiers.add(candidate);
13049
+ }
13050
+ }
13051
+ return [...identifiers];
13052
+ }
13053
+ function extractBareIdentifiers(query) {
13054
+ const unquoted = query.replace(QUOTED_BACKTICK_RE, " ").replace(QUOTED_SINGLE_RE, " ").replace(QUOTED_DOUBLE_RE, " ");
13055
+ const identifiers = /* @__PURE__ */ new Set();
13056
+ for (const match of unquoted.matchAll(IDENTIFIER_RE)) {
13057
+ const candidate = stripCallSuffix(match[0]);
13058
+ if (isLikelySymbolName(candidate)) {
13059
+ identifiers.add(candidate);
13060
+ }
13061
+ }
13062
+ return [...identifiers];
13063
+ }
13064
+ function isSingleMeaningfulToken(query, symbol) {
13065
+ const tokens = query.replace(/[`'"()]/g, " ").split(/[^A-Za-z0-9_$]+/).map((token) => token.trim().toLowerCase()).filter((token) => token.length > 0).filter((token) => !STOP_WORDS.has(token));
13066
+ return tokens.length === 1 && tokens[0] === symbol.toLowerCase();
13067
+ }
13068
+ function inferExactSymbolFromQuery(query) {
13069
+ const quoted = extractQuotedIdentifiers(query);
13070
+ if (quoted.length === 1) {
13071
+ return quoted[0];
13072
+ }
13073
+ if (quoted.length > 1) {
13074
+ return void 0;
13075
+ }
13076
+ const candidates = extractBareIdentifiers(query);
13077
+ if (candidates.length !== 1) {
13078
+ return void 0;
13079
+ }
13080
+ const candidate = candidates[0];
13081
+ if (DEFINITION_INTENT_RE.test(query)) {
13082
+ return candidate;
13083
+ }
13084
+ if (isSingleMeaningfulToken(query, candidate)) {
13085
+ return candidate;
13086
+ }
13087
+ return void 0;
13088
+ }
13089
+
13090
+ // src/tools/context.ts
13091
+ var MIN_CONTEXT_RESULT_LIMIT = 1;
13092
+ var MAX_CONTEXT_RESULT_LIMIT = 100;
13093
+ var MIN_CONTEXT_PATH_DEPTH = 1;
13094
+ var MAX_CONTEXT_PATH_DEPTH = 100;
13095
+ function locations(results) {
13096
+ return results.map((result) => ({
13097
+ filePath: result.filePath,
13098
+ startLine: result.startLine,
13099
+ endLine: result.endLine,
13100
+ score: result.score,
13101
+ chunkType: result.chunkType,
13102
+ name: result.name
13103
+ }));
13104
+ }
13105
+ function packedResult(route, routedQuery, pack) {
13106
+ return {
13107
+ text: pack.text,
13108
+ details: {
13109
+ route,
13110
+ routedQuery,
13111
+ tokenBudget: pack.tokenBudget,
13112
+ tokenEstimate: pack.tokenEstimate,
13113
+ candidateCount: pack.candidateCount,
13114
+ deduplicatedCount: pack.deduplicatedCount,
13115
+ selectedCount: pack.selectedCount,
13116
+ omittedCount: pack.omittedCount,
13117
+ duplicateCount: pack.duplicateCount,
13118
+ limitOmittedCount: pack.limitOmittedCount,
13119
+ budgetOmittedCount: pack.budgetOmittedCount,
13120
+ results: locations(pack.results)
13121
+ }
13122
+ };
13123
+ }
13124
+ async function resolveSearchContext(input, operations) {
13125
+ const explicitSymbol = input.symbol ?? void 0;
13126
+ const limit = input.limit ?? 10;
13127
+ const tokenBudget = input.tokenBudget ?? void 0;
13128
+ const lookupSymbol = explicitSymbol ?? inferExactSymbolFromQuery(input.query);
13129
+ if (lookupSymbol) {
13130
+ const definitions = await operations.lookup(lookupSymbol, MAX_CONTEXT_RESULT_LIMIT);
13131
+ if (definitions.length > 0) {
13132
+ return packedResult("definition", lookupSymbol, buildContextPack(definitions, {
13133
+ tokenBudget,
13134
+ maxResults: limit,
13135
+ heading: `Definition evidence for ${JSON.stringify(lookupSymbol)}`
13136
+ }));
13137
+ }
13138
+ if (explicitSymbol) {
13139
+ const fitted = fitTextToContextBudget(
13140
+ formatDefinitionLookup(definitions, lookupSymbol),
13141
+ tokenBudget
13142
+ );
13143
+ return { text: fitted.text };
13144
+ }
13145
+ }
13146
+ const results = await operations.search(input.query, MAX_CONTEXT_RESULT_LIMIT);
13147
+ if (results.length === 0) {
13148
+ const fitted = fitTextToContextBudget(
13149
+ "No matching code found. Try a different query or run index_codebase first.",
13150
+ tokenBudget
13151
+ );
13152
+ return { text: fitted.text };
13153
+ }
13154
+ return packedResult("conceptual", input.query, buildContextPack(results, {
13155
+ tokenBudget,
13156
+ maxResults: limit,
13157
+ heading: `Codebase evidence for ${JSON.stringify(input.query)}`
13158
+ }));
13159
+ }
13160
+ function fittedDetails(route, fitted) {
13161
+ return {
13162
+ route,
13163
+ tokenBudget: fitted.tokenBudget,
13164
+ tokenEstimate: fitted.tokenEstimate,
13165
+ truncated: fitted.truncated
13166
+ };
13167
+ }
13168
+ async function resolveCodebaseContext(projectRoot, host, input) {
13169
+ const from = input.from ?? void 0;
13170
+ const to = input.to ?? void 0;
13171
+ const symbol = input.symbol ?? void 0;
13172
+ const limit = input.limit ?? 10;
13173
+ const maxDepth = input.maxDepth ?? 10;
13174
+ const fileType = input.fileType ?? void 0;
13175
+ const directory = input.directory ?? void 0;
13176
+ const tokenBudget = input.tokenBudget ?? void 0;
13177
+ if (from && to) {
13178
+ const path24 = await getCallGraphPath(projectRoot, host, from, to, maxDepth);
13179
+ if (path24.length > 0) {
13180
+ const fitted2 = fitTextToContextBudget(
13181
+ formatCallGraphPath(from, to, path24),
13182
+ tokenBudget
13183
+ );
13184
+ return {
13185
+ text: fitted2.text,
13186
+ details: fittedDetails("path", fitted2)
13187
+ };
13188
+ }
13189
+ const { callers } = await getCallGraphData(projectRoot, host, {
13190
+ name: to,
13191
+ direction: "callers"
13192
+ });
13193
+ const directEdge = callers.find((edge) => edge.fromSymbolName === from);
13194
+ if (directEdge) {
13195
+ const location = directEdge.fromSymbolFilePath ? ` at ${directEdge.fromSymbolFilePath}:${directEdge.line}` : "";
13196
+ const fitted2 = fitTextToContextBudget(
13197
+ `Direct path: ${from} --${directEdge.callType}--> ${to}${location} (edge is ${directEdge.isResolved ? "resolved" : "unresolved"}).`,
13198
+ tokenBudget
13199
+ );
13200
+ return {
13201
+ text: fitted2.text,
13202
+ details: fittedDetails("direct-edge", fitted2)
13203
+ };
13204
+ }
13205
+ const fitted = fitTextToContextBudget(
13206
+ formatCallGraphPath(from, to, path24),
13207
+ tokenBudget
13208
+ );
13209
+ return {
13210
+ text: fitted.text,
13211
+ details: fittedDetails("path", fitted)
13212
+ };
13213
+ }
13214
+ return resolveSearchContext({ query: input.query, symbol, limit, tokenBudget }, {
13215
+ lookup: (lookupSymbol, retrievalLimit) => implementationLookup(projectRoot, host, lookupSymbol, {
13216
+ limit: retrievalLimit,
13217
+ fileType,
13218
+ directory
13219
+ }),
13220
+ search: (query, retrievalLimit) => searchCodebase(projectRoot, host, query, {
13221
+ limit: retrievalLimit,
13222
+ fileType,
13223
+ directory,
13224
+ metadataOnly: true
13225
+ })
13226
+ });
13227
+ }
13228
+
12803
13229
  // src/tools/index.ts
12804
13230
  import { writeFileSync as writeFileSync5 } from "fs";
12805
13231
  import * as os5 from "os";
@@ -13531,6 +13957,23 @@ function initializeTools2(projectRoot, config) {
13531
13957
  function getIndexerForProject2(directory) {
13532
13958
  return getIndexerForProject(directory, DEFAULT_HOST);
13533
13959
  }
13960
+ var codebase_context = tool2({
13961
+ description: "PREFERRED FIRST TOOL for repository questions. Returns a deduplicated, file-diverse evidence pack within tokenBudget. Provide from and to for dependency paths, symbol for definitions, or only query for conceptual discovery.",
13962
+ args: {
13963
+ query: z2.string().describe("The repository question or behavior to locate"),
13964
+ from: z2.string().nullable().optional().describe("Source symbol for a dependency path"),
13965
+ to: z2.string().nullable().optional().describe("Target symbol for a dependency path"),
13966
+ symbol: z2.string().nullable().optional().describe("Exact symbol for authoritative definition lookup"),
13967
+ limit: z2.number().int().min(MIN_CONTEXT_RESULT_LIMIT).max(MAX_CONTEXT_RESULT_LIMIT).nullable().optional().default(10).describe(`Maximum number of results (${MIN_CONTEXT_RESULT_LIMIT}-${MAX_CONTEXT_RESULT_LIMIT})`),
13968
+ maxDepth: z2.number().int().min(MIN_CONTEXT_PATH_DEPTH).max(MAX_CONTEXT_PATH_DEPTH).nullable().optional().default(10).describe(`Maximum call-path traversal depth (${MIN_CONTEXT_PATH_DEPTH}-${MAX_CONTEXT_PATH_DEPTH})`),
13969
+ fileType: z2.string().nullable().optional().describe("Filter by file extension"),
13970
+ directory: z2.string().nullable().optional().describe("Filter by directory path"),
13971
+ tokenBudget: z2.number().int().min(MIN_CONTEXT_PACK_TOKEN_BUDGET).max(MAX_CONTEXT_PACK_TOKEN_BUDGET).nullable().optional().default(DEFAULT_CONTEXT_PACK_TOKEN_BUDGET).describe(`Maximum response tokens (${MIN_CONTEXT_PACK_TOKEN_BUDGET}-${MAX_CONTEXT_PACK_TOKEN_BUDGET})`)
13972
+ },
13973
+ async execute(args, context) {
13974
+ return (await resolveCodebaseContext(context?.worktree, DEFAULT_HOST, args)).text;
13975
+ }
13976
+ });
13534
13977
  var codebase_peek = tool2({
13535
13978
  description: "Quick lookup of code locations by meaning. Returns only metadata (file, line, name, type) WITHOUT code content. Use this first to find WHERE code is, then use Read tool to examine specific files. Saves tokens by not returning full code blocks. Best for: discovery, navigation, finding multiple related locations.",
13536
13979
  args: {
@@ -14213,6 +14656,7 @@ var plugin = async ({ directory, worktree }) => {
14213
14656
  }
14214
14657
  return {
14215
14658
  tool: {
14659
+ codebase_context,
14216
14660
  codebase_search,
14217
14661
  codebase_peek,
14218
14662
  index_codebase,