Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ Example output:
node /path/to/codebase-context/dist/index.js patterns
```

Use `patterns --category di --json` to find example files for dependency injection.
When examples are available, `results` lists up to three project-relative files
with their category and detected pattern. Run a full `reindex` to refresh examples
in an older index.

Example output (truncated):

```text
Expand Down
117 changes: 82 additions & 35 deletions src/core/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ import { type IndexMeta, readIndexMeta, validateIndexArtifacts } from './index-m
import { hashFileContent, readReferenceManifest, type FileManifest } from './manifest.js';
import { isPathWithin } from '../utils/project-discovery.js';
import { isSourceBodyWithinInterval } from '../utils/source-interval.js';
import {
findLexicalIdentifierOccurrences,
hasIdentifierCandidate,
maskComments
} from '../utils/tree-sitter.js';
import {
InternalSourceResolver,
loadTsconfigCompilerOptions
Expand Down Expand Up @@ -237,6 +242,7 @@ export class CodebaseSearcher {

private importCentrality: Map<string, number> | null = null;
private indexedImports = new Map<string, Map<string, string[]>>();
private rescueDeclaredNames: Set<string> | undefined;

constructor(rootPath: string) {
this.rootPath = rootPath;
Expand Down Expand Up @@ -265,6 +271,7 @@ export class CodebaseSearcher {
this.patternIntelligence = null;
this.importCentrality = null;
this.indexedImports.clear();
this.rescueDeclaredNames = undefined;
}
if (
this.initialized &&
Expand Down Expand Up @@ -783,6 +790,23 @@ export class CodebaseSearcher {
.flatMap((name) => name.split('+'));
}

private indexedSymbolNames(chunk: CodeChunk): string[] {
return [...this.indexedDeclarationNames(chunk), ...(chunk.exports ?? [])];
}

private lexicalRescueDeclaredNames(): Set<string> {
if (this.rescueDeclaredNames) return this.rescueDeclaredNames;

const names = new Set<string>();
for (const chunk of this.chunks) {
for (const name of this.indexedSymbolNames(chunk)) {
if (typeof name === 'string') names.add(name.toLowerCase());
}
}
this.rescueDeclaredNames = names;
return names;
}

private hasExactQueryDeclaration(chunk: Pick<CodeChunk, 'metadata'>, query: string): boolean {
const identifiers = new Set(
(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(query.trim())
Expand Down Expand Up @@ -828,11 +852,35 @@ export class CodebaseSearcher {

const queryTerms = this.lexicalQueryTerms(query);
const terms = [...queryTerms.keys()];
if (terms.length < 2) return [];
const symbolAnchors = new Set(
(query.match(/[a-zA-Z_][a-zA-Z0-9_]*/g) ?? [])
.filter(
(term) =>
term.length >= 8 &&
(/[a-z][A-Z]/.test(term) || (term.includes('_') && term.replace(/_/g, '').length >= 4))
)
.map((term) => term.toLowerCase())
);
if (terms.length + symbolAnchors.size < 2) return [];

const symbolAnchors = (query.match(/[a-zA-Z_][a-zA-Z0-9_]*/g) ?? [])
.filter((term) => /[a-z][A-Z]/.test(term) && term.length >= 8)
.map((term) => term.toLowerCase());
// Declarations still require an indexed edge for corroboration. A name with
// no declaration can instead count as a literal clue in the file that uses it.
const literalAnchors = [...symbolAnchors].filter(
(anchor) => !this.lexicalRescueDeclaredNames().has(anchor)
);
const possibleClues = terms.length + literalAnchors.length;
if (possibleClues < 2) return [];

const literalMatches = (item: CodeChunk, nominationText: string): string[] => {
if (!literalAnchors.some((anchor) => nominationText.includes(anchor))) return [];
const code = maskComments(item.content).toLowerCase();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve comment context across chunk boundaries

When a multiline comment crosses a chunk boundary, masking item.content starts with no knowledge of the opening delimiter. The line-based chunker in src/utils/chunking.ts slices files every 50 lines without preserving comment boundaries, so an identifier appearing only inside a comment after that boundary remains unmasked. Combined with one natural clue elsewhere in the file, it becomes sufficient rescue evidence and returns a comment-only identifier match, contrary to the new admission contract. Mask the complete source before selecting chunk intervals, or retain the lexical state at each chunk's start.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Split comments count as evidence

maskComments starts fresh for each chunk, but chunks can begin inside a block comment. The line-based splitter cuts files every 50 lines without carrying comment state. In a CSS file with a long opening comment, a chunk starting at line 51 can contain WIDGET_RETRY_LIMIT without the earlier /*; the mask keeps it, and another matching word admits the file. Build the comment mask from the full source before selecting the chunk's range, or preserve the comment state across chunk boundaries.

const filename = path.basename(item.relativePath).toLowerCase();
return literalAnchors.filter(
(anchor) =>
findLexicalIdentifierOccurrences(code, anchor).length > 0 ||
findLexicalIdentifierOccurrences(filename, anchor).length > 0
);
};

const candidateLimit = Math.min(MAX_CANDIDATE_WORK, Math.max(256, limit * 80));
const budget = sourceBudget ?? { limit: candidateLimit, inspected: new Set<string>() };
Expand All @@ -841,9 +889,12 @@ export class CodebaseSearcher {
// "polic", and archive/archiving share "archiv". These fragments only nominate;
// the unchanged exact lexical evidence below still decides admission.
const fragments = [...new Set(aliases.map((alias) => alias.replace(/[ey]$/, '')))];
const lookupTerms = fragments.filter(
(fragment) => !fragments.some((other) => other !== fragment && fragment.includes(other))
);
const lookupTerms = [
...fragments.filter(
(fragment) => !fragments.some((other) => other !== fragment && fragment.includes(other))
),
...symbolAnchors
];
// Keep original chunk ordinals, including ties, and nominate across every
// exact evidence zone. Filters apply before the bounded evidence window.
const rawCandidates =
Expand All @@ -853,15 +904,11 @@ export class CodebaseSearcher {
const fields = [
item.content,
path.basename(item.relativePath),
...this.indexedDeclarationNames(item),
...(item.exports ?? [])
...this.indexedSymbolNames(item)
];
const matches = fields.some((field) => {
const text = field.toLowerCase();
return (
lookupTerms.some((term) => text.includes(term)) ||
symbolAnchors.some((anchor) => text.includes(anchor))
);
return lookupTerms.some((term) => text.includes(term));
});
return matches ? [{ item, refIndex, score: 0 }] : [];
});
Expand All @@ -879,27 +926,27 @@ export class CodebaseSearcher {
const text = [
result.item.content,
path.basename(result.item.relativePath),
...this.indexedDeclarationNames(result.item),
...(result.item.exports ?? [])
...this.indexedSymbolNames(result.item)
]
.join(' ')
.toLowerCase();
const clues = [...queryTerms.values()].filter((aliases) =>
aliases.some((alias) => text.includes(alias))
).length;
return { result, clues };
const identifiers = literalMatches(result.item, text);
const clues =
[...queryTerms.values()].filter((aliases) =>
aliases.some((alias) => text.includes(alias))
).length + identifiers.length;
return { result, identifiers, clues };
})
.sort((a, b) => b.clues - a.clues || a.result.refIndex - b.result.refIndex)
.slice(0, candidateLimit)
.map(({ result }) => result);
.slice(0, candidateLimit);
const unavailableBefore = [...checkedSources.values()].filter(
(source) => source === null
).length;

const queryAliases = new Map(
terms.map((term) => [term, new Set(queryTerms.get(term)!)] as const)
);
const evidence = candidates.map((result) => {
const evidence = candidates.map(({ result, identifiers }) => {
const { item } = result;
const bodyWords = this.lexicalWords(item.content);
const bodyLexemes = new Set<string>();
Expand Down Expand Up @@ -929,18 +976,15 @@ export class CodebaseSearcher {
Math.sqrt(Math.max(1, bodyWords.length));
// Export names remain useful lexical/graph clues, but can be re-exports;
// exact definition priority below requires own declaration metadata.
const indexedSymbols = [...this.indexedDeclarationNames(item), ...(item.exports ?? [])];
const exactAnchor = symbolAnchors.some((symbol) =>
indexedSymbols.some(
(indexedSymbol) =>
typeof indexedSymbol === 'string' && indexedSymbol.toLowerCase() === symbol
)
const indexedSymbols = this.indexedSymbolNames(item);
const exactAnchor = indexedSymbols.some(
(name) => typeof name === 'string' && symbolAnchors.has(name.toLowerCase())
);
const declarationLexemes = this.lexicalEvidence(indexedSymbols.filter(Boolean).join(' '));
const declarationMatching = new Set(
terms.filter((term) => queryTerms.get(term)!.some((alias) => declarationLexemes.has(alias)))
);
return { result, matching, declarationMatching, exactAnchor, density };
return { result, matching, identifiers, declarationMatching, exactAnchor, density };
});

const supportedCompanions = new Map(
Expand Down Expand Up @@ -1015,10 +1059,11 @@ export class CodebaseSearcher {
}

const fileEvidence = new Map<string, Set<string>>();
for (const { result, matching } of evidence) {
for (const { result, matching, identifiers } of evidence) {
const key = this.indexedFileKey(result.item.filePath);
const termsForFile = fileEvidence.get(key) ?? new Set<string>();
for (const term of matching) termsForFile.add(term);
for (const identifier of identifiers) termsForFile.add(identifier);
fileEvidence.set(key, termsForFile);
}

Expand All @@ -1036,6 +1081,7 @@ export class CodebaseSearcher {
const score = (entry: typeof a, key: string) =>
((fileEvidence.get(key)?.size ?? 0) + entry.declarationMatching.size) * 8 +
entry.matching.size * 3 +
entry.identifiers.length * 8 +
(entry.exactAnchor ? 8 : 0) -
(this.isTestFile(entry.result.item.filePath) ? 2 : 0) -
(entry.result.score ?? 0);
Expand All @@ -1049,16 +1095,17 @@ export class CodebaseSearcher {
seenFiles.add(key);
return true;
})
.map(({ result, declarationMatching }) => ({
.map(({ result, declarationMatching, identifiers }) => ({
...result,
// Equal document zones: distinct source clues nominate the file;
// indexed declaration clues distinguish its own work from mentions in
// imports or configuration. This remains bounded to [0, 1].
// declaration and literal clues in the selected chunk distinguish where
// the named evidence appears. This remains bounded to [0, 1].
score:
1 -
((fileEvidence.get(this.indexedFileKey(result.item.filePath))?.size ?? 0) +
declarationMatching.size) /
(terms.length * 2)
declarationMatching.size +
identifiers.length) /
(possibleClues * 2)
}));
const current = await this.selectCurrentCandidates(
nominated,
Expand Down
66 changes: 66 additions & 0 deletions src/utils/tree-sitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,72 @@ export interface IdentifierOccurrence {
nodeType: string;
}

/** Mask common source comments while preserving quoted text and source offsets. */
export function maskComments(source: string): string {
const chars = source.split('');
let quote: string | undefined;
let escaped = false;

for (let index = 0; index < chars.length; index += 1) {
const char = chars[index];
const next = chars[index + 1];

if (quote) {
if (escaped) escaped = false;
else if (char === '\\') escaped = true;
else if (char === quote) quote = undefined;
continue;
}

if (char === '"' || char === "'" || char === '`') {
quote = char;
continue;
Comment on lines +539 to +548

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Template comments count as evidence

maskComments leaves comments inside template expressions untouched. For example, const text = ${/* WIDGET_RETRY_LIMIT */ 3}; keeps WIDGET_RETRY_LIMIT because the opening backtick puts the entire template into quoted mode. Another clue such as throttling in the same file then makes this comment-only mention count toward admission. Track template expressions separately so their comments are removed while literal template text stays searchable.

}

if (source.startsWith('<!--', index)) {
while (index < chars.length && !source.startsWith('-->', index)) {
if (chars[index] !== '\n' && chars[index] !== '\r') chars[index] = ' ';
index += 1;
}
if (index < chars.length) {
chars[index] = ' ';
chars[index + 1] = ' ';
chars[index + 2] = ' ';
index += 2;
}
continue;
}

const lineComment =
(char === '/' && next === '/') || char === '#' || (char === '-' && next === '-');
Comment on lines +565 to +566

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make comment delimiters conditional on the source language

For JavaScript/TypeScript, # can introduce a private field and -- is a decrement operator, but this treats both as line comments. For example, #limit = process.env.WIDGET_RETRY_LIMIT; loses the entire identifier during masking. Consequently, a query combining that identifier with one natural-language clue cannot rescue the file, even when both clues are present. Use language-aware comment recognition rather than applying every supported language's delimiters simultaneously; this also preserves the repository's language-agnostic search contract.

AGENTS.md reference: AGENTS.md:L108-L108

Useful? React with 👍 / 👎.

Comment on lines +565 to +566

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Private fields lose search evidence

maskComments treats # and -- as comments in every language. In valid TypeScript such as class Settings { #limit = process.env.WIDGET_RETRY_LIMIT; }, it erases the environment variable along with the private field. A question about WIDGET_RETRY_LIMIT and one other clue then misses this file because only the other clue survives. Use the chunk's language to decide which comment markers apply.

if (lineComment) {
while (index < chars.length && chars[index] !== '\n' && chars[index] !== '\r') {
chars[index] = ' ';
index += 1;
}
index -= 1;
continue;
}

if (char === '/' && next === '*') {
chars[index] = ' ';
chars[index + 1] = ' ';
index += 2;
while (index < chars.length && !(chars[index] === '*' && chars[index + 1] === '/')) {
if (chars[index] !== '\n' && chars[index] !== '\r') chars[index] = ' ';
index += 1;
}
if (index < chars.length) {
chars[index] = ' ';
chars[index + 1] = ' ';
index += 1;
}
}
}

return chars.join('');
}

const LEXICAL_IDENTIFIER_CONTINUE = /(?:\p{ID_Continue}|[$]|\u200c|\u200d)/u;
const ASCII_IDENTIFIER_CONTINUE = /[A-Za-z0-9_$]/;
const ASCII_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
Expand Down
70 changes: 70 additions & 0 deletions tests/cli-entrypoint-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,76 @@ describe('CLI entrypoint runtime', () => {
expect(parsed.hint).toContain('refresh_index');
}, 120_000);

it('ranks indexed convention files by pattern and filters to the requested category', async () => {
const projectRoot = await mkdtemp(join(tmpdir(), 'cbc-cli-pattern-examples-'));
const directory = 'apps/web/src/app';
const primary = `${directory}/core/session.service.ts`;
const alternative = `${directory}/features/profile.service.ts`;
const anotherPrimary = `${directory}/features/account.service.ts`;
const state = 'apps/dashboard/src/features/session.state.tsx';
try {
await writeFile(
join(projectRoot, 'package.json'),
JSON.stringify({ dependencies: { '@angular/core': '^17.0.0', react: '^19.0.0' } })
);
await mkdir(join(projectRoot, directory, 'core'), { recursive: true });
await mkdir(join(projectRoot, directory, 'features'), { recursive: true });
await mkdir(join(projectRoot, 'apps/dashboard/src/features'), { recursive: true });
for (const [file, name, injection] of [
[primary, 'SessionService', 'private readonly http = inject(HttpClient);'],
[anotherPrimary, 'AccountService', 'private readonly http = inject(HttpClient);'],
[alternative, 'ProfileService', 'constructor(private http: HttpClient) {}']
]) {
await writeFile(
join(projectRoot, file),
[
"import { Injectable, inject } from '@angular/core';",
"import { HttpClient } from '@angular/common/http';",
"@Injectable({ providedIn: 'root' })",
`export class ${name} { ${injection} }`
].join('\n')
);
}
await writeFile(
join(projectRoot, state),
"import { createContext } from 'react';\nexport const SessionContext = createContext(null);\n"
);

const indexed = runCli(['reindex', '--no-embeddings', '--json'], projectRoot);
expect(indexed.status, indexed.stderr).toBe(0);

const di = runCli(['patterns', '--category', 'di', '--json'], projectRoot);
expect(di.status, di.stderr).toBe(0);
const diOutput = JSON.parse(di.stdout);
expect(diOutput).toMatchObject({
patterns: { dependencyInjection: { primary: { name: 'inject() function' } } },
goldenFiles: []
});
expect(diOutput.results).toEqual([
{ file: primary, category: 'dependencyInjection', pattern: 'inject() function' },
{ file: alternative, category: 'dependencyInjection', pattern: 'Constructor injection' },
{ file: anotherPrimary, category: 'dependencyInjection', pattern: 'inject() function' }
]);

const stateResult = runCli(['patterns', '--category', 'state', '--json'], projectRoot);
expect(stateResult.status, stateResult.stderr).toBe(0);
expect(JSON.parse(stateResult.stdout).results).toEqual([
{ file: state, category: 'stateManagement', pattern: 'React Context' }
]);

const human = runCli(['patterns', '--category', 'di'], projectRoot);
expect(human.status, human.stderr).toBe(0);
expect(human.stdout).toContain(primary);
expect(human.stdout).not.toContain(state);

const testing = runCli(['patterns', '--category', 'testing', '--json'], projectRoot);
expect(testing.status, testing.stderr).toBe(0);
expect(JSON.parse(testing.stdout)).not.toHaveProperty('results');
} finally {
await rm(projectRoot, { recursive: true, force: true });
}
}, 120_000);

it('prints usage for help from a project containing a directory named help', async () => {
const projectRoot = await mkdtemp(join(tmpdir(), 'cbc-cli-help-'));
const helpDirectory = join(projectRoot, 'help');
Expand Down
Loading
Loading