From 4bdcfd7e42eeaf5fec84954f7fa083ad82c4b256 Mon Sep 17 00:00:00 2001 From: Robert DeRienzo Date: Fri, 27 Nov 2026 15:22:05 +0000 Subject: [PATCH] fix: drop PDF page markers and stop chunks from splitting words pdf-parse 2.x inserts "-- N of M --" between pages by default; pass an empty pageJoiner so pages are joined by a blank line only. Oversized paragraphs now split at the last whitespace within the limit, overlap prefixes start at a word boundary (keeping CJK text, which has no spaces), and the streaming chunker for content over 1 MB snaps window starts and ends to whitespace and only treats a period followed by whitespace as a sentence end. --- src/core/indexing.ts | 47 +++++++++----- src/core/parsers/pdf.ts | 2 +- tests/unit/indexing.test.ts | 122 ++++++++++++++++++++++++++++++++++++ tests/unit/parsers.test.ts | 39 ++++++++++++ 4 files changed, 192 insertions(+), 18 deletions(-) diff --git a/src/core/indexing.ts b/src/core/indexing.ts index 68170b50..66d8a517 100644 --- a/src/core/indexing.ts +++ b/src/core/indexing.ts @@ -140,20 +140,19 @@ export function chunkContent( /** * Split oversized text at paragraph boundaries (double-newline). - * Falls back to hard character split when a paragraph exceeds maxSize. + * When a paragraph exceeds maxSize, falls back to splitting at whitespace, + * and to a hard character split only when a word exceeds maxSize. */ function splitAtParagraphs(text: string, maxSize: number, out: string[]): void { const emit = (buf: string): void => { - const trimmed = buf.trim(); - if (trimmed.length === 0) return; - if (trimmed.length <= maxSize) { - out.push(trimmed); - } else { - for (let i = 0; i < trimmed.length; i += maxSize) { - const slice = trimmed.slice(i, i + maxSize).trim(); - if (slice.length > 0) out.push(slice); - } + let rest = buf.trim(); + while (rest.length > maxSize) { + const lastWhitespace = rest.slice(0, maxSize + 1).search(/\s\S*$/); + const splitAt = lastWhitespace > 0 ? lastWhitespace : maxSize; + out.push(rest.slice(0, splitAt).trimEnd()); + rest = rest.slice(splitAt).trimStart(); } + if (rest.length > 0) out.push(rest); }; const paragraphs = text.split(/\n\n+/); @@ -185,10 +184,13 @@ function addChunkOverlap(chunks: string[], fraction: number): string[] { if (overlapChars > 0) { // Take trailing portion of previous chunk, preferring line boundaries - let overlapText = prev.slice(-overlapChars); + const overlapStart = prev.length - overlapChars; + let overlapText = prev.slice(overlapStart); const newlineIdx = overlapText.indexOf("\n"); if (newlineIdx > 0) { overlapText = overlapText.slice(newlineIdx + 1); + } else if (/\S/.test(prev.charAt(overlapStart - 1))) { + overlapText = overlapText.replace(/^[^\s\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}]+/u, ""); } overlapText = overlapText.trim(); if (overlapText.length > 0) { @@ -207,18 +209,26 @@ function addChunkOverlap(chunks: string[], fraction: number): string[] { /** Size threshold above which streaming chunking is used (1MB). */ export const STREAMING_THRESHOLD = 1024 * 1024; -/** Find the best sentence/line boundary near the window end to avoid mid-sentence cuts. */ +/** + * Find the best sentence/line boundary within 200 characters after the window end to + * avoid mid-sentence cuts. Falls back to the next whitespace in that range, or the end + * of the text, to avoid mid-word cuts. + */ function findWindowBoundary(text: string, end: number): number { if (end >= text.length) return end; - const sentenceEnd = text.indexOf(".", end); - const newlineEnd = text.indexOf("\n", end); + const lookahead = text.slice(end, end + 200); + const sentenceEnd = lookahead.search(/\.\s/); + const newlineEnd = lookahead.indexOf("\n"); let boundary = -1; - if (sentenceEnd !== -1 && sentenceEnd - end < 200) boundary = sentenceEnd + 1; - if (newlineEnd !== -1 && newlineEnd - end < 200 && (boundary === -1 || newlineEnd < boundary)) { + if (sentenceEnd !== -1) boundary = sentenceEnd + 1; + if (newlineEnd !== -1 && (boundary === -1 || newlineEnd < boundary)) { boundary = newlineEnd + 1; } - return boundary !== -1 ? boundary : end; + if (boundary === -1) boundary = lookahead.search(/\s/); + if (boundary !== -1) return end + boundary; + + return end + lookahead.length === text.length ? text.length : end; } /** Add chunks from a window to the output, deduplicating by content hash. */ @@ -280,6 +290,9 @@ export function chunkContentStreaming( offset = windowEnd - overlap; if (offset <= 0 || windowEnd >= content.length) { offset = windowEnd; + } else { + const whitespaceIdx = content.slice(offset, windowEnd).search(/\s/); + offset = whitespaceIdx === -1 ? windowEnd : offset + whitespaceIdx; } } diff --git a/src/core/parsers/pdf.ts b/src/core/parsers/pdf.ts index 105d2d22..65fa0913 100644 --- a/src/core/parsers/pdf.ts +++ b/src/core/parsers/pdf.ts @@ -19,7 +19,7 @@ export class PdfParser implements DocumentParser { try { const parser = new PDFParse({ data: new Uint8Array(content) }); - const result = await parser.getText(); + const result = await parser.getText({ pageJoiner: "" }); return result.text; } catch (err) { throw new ValidationError( diff --git a/tests/unit/indexing.test.ts b/tests/unit/indexing.test.ts index c7119991..50139904 100644 --- a/tests/unit/indexing.test.ts +++ b/tests/unit/indexing.test.ts @@ -142,6 +142,52 @@ More content here.`; expect(joined).toContain("Line 1999"); }); + it("should not cut words at window edges", () => { + const words = Array.from({ length: 6000 }, (_, i) => `w${i}${"x".repeat(i % 5)}e`); + const lines: string[] = []; + for (let i = 0; i < words.length; i += 40) { + lines.push(words.slice(i, i + 40).join(" ")); + } + + const chunks = chunkContentStreaming(lines.join("\n"), { windowSize: 4096 }); + + const tokens = new Set(chunks.flatMap((chunk) => chunk.split(/\s+/))); + expect(tokens).toEqual(new Set(words)); + }); + + it("should not cut dotted tokens at window edges", () => { + const words = Array.from({ length: 2000 }, (_, i) => `v${i}.10.${i}`); + + const chunks = chunkContentStreaming(words.join(" "), { windowSize: 1024 }); + + const tokens = new Set(chunks.flatMap((chunk) => chunk.split(/\s+/))); + expect(tokens).toEqual(new Set(words)); + }); + + it("should not cut the last word of the content", () => { + const content = `${"word ".repeat(20)}finalword`; + + const chunks = chunkContentStreaming(content, { windowSize: 104 }); + + const tokens = new Set(chunks.flatMap((chunk) => chunk.split(/\s+/))); + expect(tokens).toEqual(new Set(["word", "finalword"])); + }); + + it("should not start a window in the middle of a word", () => { + const words = Array.from({ length: 40 }, (_, i) => `interoperability${i}`); + + const chunks = chunkContentStreaming(words.join(" "), { windowSize: 104 }); + + const tokens = new Set(chunks.flatMap((chunk) => chunk.split(/\s+/))); + expect(tokens).toEqual(new Set(words)); + }); + + it("should advance past consecutive whitespace", () => { + const chunks = chunkContentStreaming("a b", { windowSize: 1 }); + + expect(chunks).toEqual(["a", "b"]); + }); + it("should respect maxDocumentSize", () => { const content = "A".repeat(200); expect(() => chunkContentStreaming(content, { maxDocumentSize: 100 })).toThrow( @@ -284,6 +330,52 @@ More content here.`; expect(chunksNeg.length).toBeGreaterThan(0); expect(chunksHigh.length).toBeGreaterThan(0); }); + + it("should not start the overlap in the middle of a word", () => { + const content = `# First\n${"alpha ".repeat(30)}interoperability checks\n\n## Second\nBody.`; + + const chunks = chunkContent(content, { maxChunkSize: 1500, overlapFraction: 0.1 }); + + expect(chunks[1]).toBe("checks\n\nContext: First\n## Second\nBody."); + }); + + it("should keep the first word when the overlap starts at a word start", () => { + const content = `# First\n${"alpha ".repeat(34)}interoperability checks\n\n## Second\nBody.`; + + const chunks = chunkContent(content, { maxChunkSize: 1500, overlapFraction: 0.1 }); + + expect(chunks[1]).toBe("interoperability checks\n\nContext: First\n## Second\nBody."); + }); + + it("should add no overlap when it would only be part of a word", () => { + const content = "# Install\nnpm install libscope\n\n## Usage\nRun it."; + + const chunks = chunkContent(content); + + expect(chunks[1]).toBe("Context: Install\n## Usage\nRun it."); + }); + + it("should keep the overlap of text without whitespace", () => { + const content = "漢字".repeat(200); + + const chunks = chunkContent(content, { maxChunkSize: 300, overlapFraction: 0.1 }); + + expect(chunks).toEqual(["漢字".repeat(150), `${"漢字".repeat(15)}\n\n${"漢字".repeat(50)}`]); + }); + + it("should keep the overlap of CJK text under a heading", () => { + const content = `# 見出し\n${"漢字".repeat(50)}\n\n## Second\nBody.`; + + const chunks = chunkContent(content, { maxChunkSize: 1500, overlapFraction: 0.1 }); + + expect(chunks[1]).toBe(`${"漢字".repeat(5)}\n\nContext: 見出し\n## Second\nBody.`); + }); + + it("should add no overlap from a previous chunk of one word", () => { + const chunks = chunkContent("Introduction\n# Next\nBody"); + + expect(chunks[1]).toBe("# Next\nBody"); + }); }); describe("chunkContent paragraph-boundary splitting", () => { @@ -303,6 +395,36 @@ describe("chunkContent paragraph-boundary splitting", () => { expect(chunk.length).toBeLessThanOrEqual(300 + 50); // small tolerance for overlap } }); + + it("should split a paragraph without blank lines at whitespace", () => { + const words = Array.from({ length: 400 }, (_, i) => `word${i}`); + const lines: string[] = []; + for (let i = 0; i < words.length; i += 12) { + lines.push(words.slice(i, i + 12).join(" ")); + } + + const chunks = chunkContent(lines.join("\n"), { maxChunkSize: 300, overlapFraction: 0 }); + + expect(chunks.length).toBeGreaterThan(1); + expect(chunks.join(" ").split(/\s+/)).toEqual(words); + for (const chunk of chunks) { + expect(chunk.length).toBeLessThanOrEqual(300); + } + }); + + it("should keep a word that ends exactly at the max size", () => { + const content = `aaa ${"b".repeat(296)} c`; + + const chunks = chunkContent(content, { maxChunkSize: 300, overlapFraction: 0 }); + + expect(chunks.map((chunk) => chunk.length)).toEqual([300, 1]); + }); + + it("should hard split a word that is longer than the max size", () => { + const chunks = chunkContent("A".repeat(700), { maxChunkSize: 300, overlapFraction: 0 }); + + expect(chunks.map((chunk) => chunk.length)).toEqual([300, 300, 100]); + }); }); describe("plain-text breadcrumbs", () => { diff --git a/tests/unit/parsers.test.ts b/tests/unit/parsers.test.ts index c6495c4f..bdf97794 100644 --- a/tests/unit/parsers.test.ts +++ b/tests/unit/parsers.test.ts @@ -8,6 +8,38 @@ import { CsvParser } from "../../src/core/parsers/csv.js"; import { HtmlParser } from "../../src/core/parsers/html.js"; import { ValidationError } from "../../src/errors.js"; +/** Builds a PDF with one page per entry of pageTexts. */ +function buildPdf(pageTexts: string[]): Buffer { + const fontId = 3 + pageTexts.length * 2; + const pageIds = pageTexts.map((_, i) => 3 + i * 2); + const objects = [ + "<< /Type /Catalog /Pages 2 0 R >>", + `<< /Type /Pages /Kids [${pageIds.map((id) => `${id} 0 R`).join(" ")}] /Count ${pageTexts.length} >>`, + ]; + for (const [i, text] of pageTexts.entries()) { + const stream = `BT /F1 12 Tf 20 100 Td (${text}) Tj ET`; + objects.push( + `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents ${pageIds[i]! + 1} 0 R /Resources << /Font << /F1 ${fontId} 0 R >> >> >>`, + `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`, + ); + } + objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); + + let pdf = "%PDF-1.4\n"; + const offsets: number[] = []; + for (const [i, body] of objects.entries()) { + offsets.push(pdf.length); + pdf += `${i + 1} 0 obj\n${body}\nendobj\n`; + } + const xrefOffset = pdf.length; + pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`; + for (const offset of offsets) { + pdf += `${String(offset).padStart(10, "0")} 00000 n \n`; + } + pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`; + return Buffer.from(pdf, "latin1"); +} + describe("getParserForFile", () => { it("returns parser for .md files", () => { expect(getParserForFile("docs/guide.md")).not.toBeNull(); @@ -209,6 +241,13 @@ describe("PdfParser", () => { it("throws ValidationError for invalid PDF content", async () => { await expect(parser.parse(Buffer.from("not a pdf"))).rejects.toThrow(ValidationError); }); + + it("does not add page separators to the text", async () => { + const result = await parser.parse(buildPdf(["First page", "Second page"])); + + expect(result).toMatch(/First page\s+Second page/); + expect(result).not.toMatch(/-- \d+ of \d+ --/); + }); }); describe("WordParser", () => {