Skip to content
Open
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
2 changes: 1 addition & 1 deletion skills/retriv/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export default {
- **TypeScript 7 breaks code chunking.** `pnpm add typescript` installs 7.x, outside the peer range, and both code chunkers throw `Cannot read properties of undefined (reading 'TS')`. Install `typescript@^6`. Without TypeScript, `autoChunker` throws on the first code document.
- **Node floor.** Below the Node versions in the table, SQLite drivers fail with `no such module: fts5` (22.14, 22.15) or `node:sqlite not available` (before 22.13).
- **Scores are not similarities.** `sqlite`, composed drivers, `categories`, and multi-token `sqlite-fts` queries return RRF scores, about 0.005 to 0.05; `search()` makes `getUserName` multi-token. A single-token `sqlite-fts` hit scores near 1; a reranker sets 0 to 1. A driver with vectors returns up to `limit` rows even for a nonsense query. Never threshold on score.
- **`codeChunker` skips text.** At each chunk boundary it drops the next declaration's comments and JSDoc, and a variable's `export const`. It also drops statements after the last declaration. A declaration over `maxChunkSize` stays one chunk, and code chunks get no `range`, `scope`, or `context`. To index every line, chunk code with `markdownChunker()`.
- **`codeChunker` chunks are coarse.** A declaration over `maxChunkSize` stays one chunk, and code chunks get no `range`, `scope`, or `context`.
- **Filters differ by driver.** SQL drivers drop documents that lack the field on `$ne` and `$nin`, and throw on a field name outside letters, digits, `_`, and `.`. The SQLite and libsql drivers read `a.b` as nested JSON. pgvector reads `a.b` as one literal key and never matches a boolean; flatten nested fields and store booleans as strings.
- **Upstash and Cloudflare filter in memory** over the `limit * 4` nearest vectors, so a selective filter can return few rows or none; raise `limit`. There, `$ne` keeps a document without the field but drops one without metadata, `a.b` never matches, and a bad field name returns `[]`.
- **One model per index.** The vector table takes its dimensions from the first open; another model on the same file throws `Dimension mismatch`. `cachedEmbeddings` hashes only the text, so give each model its own storage. Never pass `dimensions` to `transformersJs()` for a known model; a wrong value gives silent garbage vectors.
Expand Down
100 changes: 37 additions & 63 deletions src/chunkers/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,36 @@ interface ChunkRange {
entities: ParsedDeclaration[]
}

/** Where the chunk for `node` may start, JSDoc included, never before `after`. */
function chunkBoundary(node: TS.Node, sourceFile: TS.SourceFile, after: number): number {
const chain: TS.Node[] = []
for (let current: TS.Node = node; current !== sourceFile; current = current.parent)
chain.unshift(current)
for (const ancestor of chain) {
const comments = ts.getLeadingCommentRanges(sourceFile.text, ancestor.pos)
const start = comments?.[0]?.pos ?? ancestor.getStart(sourceFile)
if (start >= after)
return start
}
return node.getStart(sourceFile)
}

/** Lines are counted on the trimmed text, so `lineRange` matches `chunk.text`. */
function toChunkRange(
sourceFile: TS.SourceFile,
start: number,
end: number,
entities: ParsedDeclaration[],
): ChunkRange {
const slice = sourceFile.text.slice(start, end)
const textStart = start + slice.length - slice.trimStart().length
const textEnd = start + slice.trimEnd().length
const { line: lineStart } = sourceFile.getLineAndCharacterOfPosition(textStart)
const { line: lineEnd } = sourceFile.getLineAndCharacterOfPosition(Math.max(textStart, textEnd))
return { start, end, lineStart: lineStart + 1, lineEnd: lineEnd + 1, entities }
}

/** Chunks touch end to end, so no comment or statement falls between them. */
function splitIntoChunks(
content: string,
declarations: ParsedDeclaration[],
Expand Down Expand Up @@ -320,75 +350,19 @@ function splitIntoChunks(
let currentStart = filterImports ? importEnd : 0
let currentEntities: ParsedDeclaration[] = []

// Group declarations into chunks
for (const decl of declarations) {
const declSize = decl.end - decl.start
const currentSize = decl.end - currentStart

if (currentSize > maxChunkSize && currentEntities.length > 0) {
// Flush current chunk
const lastEntity = currentEntities.at(-1)!
const { line: lineStart } = sourceFile.getLineAndCharacterOfPosition(currentStart)
const { line: lineEnd } = sourceFile.getLineAndCharacterOfPosition(lastEntity.end)

chunks.push({
start: currentStart,
end: lastEntity.end,
lineStart: lineStart + 1,
lineEnd: lineEnd + 1,
entities: currentEntities,
})
const boundary = chunkBoundary(decl.node, sourceFile, currentEntities.at(-1)?.end ?? currentStart)

currentStart = decl.start
currentEntities = [decl]
}
else if (declSize > maxChunkSize) {
// Single large declaration - split it
if (currentEntities.length > 0) {
const lastEntity = currentEntities.at(-1)!
const { line: lineStart } = sourceFile.getLineAndCharacterOfPosition(currentStart)
const { line: lineEnd } = sourceFile.getLineAndCharacterOfPosition(lastEntity.end)
chunks.push({
start: currentStart,
end: lastEntity.end,
lineStart: lineStart + 1,
lineEnd: lineEnd + 1,
entities: currentEntities,
})
}

// Add the large declaration as its own chunk(s)
const { line: declLineStart } = sourceFile.getLineAndCharacterOfPosition(decl.start)
const { line: declLineEnd } = sourceFile.getLineAndCharacterOfPosition(decl.end)
chunks.push({
start: decl.start,
end: decl.end,
lineStart: declLineStart + 1,
lineEnd: declLineEnd + 1,
entities: [decl],
})

currentStart = decl.end
if (decl.end - currentStart > maxChunkSize && currentEntities.length > 0 && boundary > currentStart) {
chunks.push(toChunkRange(sourceFile, currentStart, boundary, currentEntities))
currentStart = boundary
currentEntities = []
}
else {
currentEntities.push(decl)
}
currentEntities.push(decl)
}

// Flush remaining
if (currentEntities.length > 0) {
const lastEntity = currentEntities.at(-1)!
const { line: lineStart } = sourceFile.getLineAndCharacterOfPosition(currentStart)
const { line: lineEnd } = sourceFile.getLineAndCharacterOfPosition(lastEntity.end)
chunks.push({
start: currentStart,
end: lastEntity.end,
lineStart: lineStart + 1,
lineEnd: lineEnd + 1,
entities: currentEntities,
})
}
if (currentEntities.length > 0)
chunks.push(toChunkRange(sourceFile, currentStart, content.length, currentEntities))

// If no chunks created, return entire content
if (chunks.length === 0) {
Expand Down
33 changes: 33 additions & 0 deletions test/chunkers-typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,37 @@ export function longFunction() {
// Should produce multiple chunks due to small maxChunkSize
expect(chunks.length).toBeGreaterThanOrEqual(1)
})

it('keeps comments, keywords and trailing statements at chunk boundaries', async () => {
const code = `export function alpha() {
return 1
}

/** Beta doc comment */
export function beta() {
return 2
}

export const GAMMA = 3

registerPlugin('trailing statement')
`
const chunks = await codeChunker({ maxChunkSize: 40 })(code, { id: 'src/a.ts' })

expect(chunks.map(c => c.text)).toEqual([
'export function alpha() {\n return 1\n}',
'/** Beta doc comment */\nexport function beta() {\n return 2\n}',
'export const GAMMA = 3\n\nregisterPlugin(\'trailing statement\')',
])
expect(chunks.map(c => c.lineRange)).toEqual([[1, 3], [5, 8], [10, 12]])
})

it('covers every line when declarations share one statement', async () => {
const methods = Array.from({ length: 30 }, (_, i) => ` /** doc ${i} */\n method${i}(raw) { return raw + '${i}' },`)
const code = `module.exports = {\n${methods.join('\n')}\n}\nconsole.log('tail')\n`
const chunks = await codeChunker({ maxChunkSize: 200 })(code, { id: 'bundle.js' })

expect(chunks.length).toBeGreaterThan(1)
expect(chunks.map(c => c.text).join('').replace(/\s/g, '')).toBe(code.replace(/\s/g, ''))
})
})