* Lightweight forward scan of [0, endOffset) collecting only metadata-entry lines. * Uses raw Buffer chunks and byte-level marker matching — no readline, no per-line * string conversion for the ~99% of lines that are message content. * * Fast path: if a chunk contains zero markers (the common ca
( filePath: string, endOffset: number, )
| 3337 | * are <50 per session), the entire chunk is skipped without line splitting. |
| 3338 | */ |
| 3339 | async function scanPreBoundaryMetadata( |
| 3340 | filePath: string, |
| 3341 | endOffset: number, |
| 3342 | ): Promise<string[]> { |
| 3343 | const { createReadStream } = await import('fs') |
| 3344 | const NEWLINE = 0x0a |
| 3345 | |
| 3346 | const stream = createReadStream(filePath, { end: endOffset - 1 }) |
| 3347 | const metadataLines: string[] = [] |
| 3348 | let carry: Buffer | null = null |
| 3349 | |
| 3350 | for await (const chunk of stream) { |
| 3351 | const chunkBuf = chunk as Buffer |
| 3352 | const buf = resolveMetadataBuf(carry, chunkBuf) |
| 3353 | if (buf === null) { |
| 3354 | carry = null |
| 3355 | continue |
| 3356 | } |
| 3357 | |
| 3358 | // Fast path: most chunks contain zero metadata markers. Skip line splitting. |
| 3359 | let hasAnyMarker = false |
| 3360 | for (const m of METADATA_MARKER_BUFS) { |
| 3361 | if (buf.includes(m)) { |
| 3362 | hasAnyMarker = true |
| 3363 | break |
| 3364 | } |
| 3365 | } |
| 3366 | |
| 3367 | if (hasAnyMarker) { |
| 3368 | let lineStart = 0 |
| 3369 | let nl = buf.indexOf(NEWLINE) |
| 3370 | while (nl !== -1) { |
| 3371 | // Bounded marker check: only look within this line's byte range |
| 3372 | for (const m of METADATA_MARKER_BUFS) { |
| 3373 | const mIdx = buf.indexOf(m, lineStart) |
| 3374 | if (mIdx !== -1 && mIdx < nl) { |
| 3375 | metadataLines.push(buf.toString('utf-8', lineStart, nl)) |
| 3376 | break |
| 3377 | } |
| 3378 | } |
| 3379 | lineStart = nl + 1 |
| 3380 | nl = buf.indexOf(NEWLINE, lineStart) |
| 3381 | } |
| 3382 | carry = buf.subarray(lineStart) |
| 3383 | } else { |
| 3384 | // No markers in this chunk — just preserve the incomplete trailing line |
| 3385 | const lastNl = buf.lastIndexOf(NEWLINE) |
| 3386 | carry = lastNl >= 0 ? buf.subarray(lastNl + 1) : buf |
| 3387 | } |
| 3388 | |
| 3389 | // Guard against quadratic carry growth for pathological huge lines |
| 3390 | // (e.g., a 10 MB tool-output line with no newline). Real metadata entries |
| 3391 | // are <1 KB, so if carry exceeds this we're mid-message-content — drop it. |
| 3392 | if (carry.length > 64 * 1024) carry = null |
| 3393 | } |
| 3394 | |
| 3395 | // Final incomplete line (no trailing newline at endOffset) |
| 3396 | if (carry !== null && carry.length > 0) { |
no test coverage detected