* 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, )
| 3156 | * are <50 per session), the entire chunk is skipped without line splitting. |
| 3157 | */ |
| 3158 | async function scanPreBoundaryMetadata( |
| 3159 | filePath: string, |
| 3160 | endOffset: number, |
| 3161 | ): Promise<string[]> { |
| 3162 | const { createReadStream } = await import('fs') |
| 3163 | const NEWLINE = 0x0a |
| 3164 | |
| 3165 | const stream = createReadStream(filePath, { end: endOffset - 1 }) |
| 3166 | const metadataLines: string[] = [] |
| 3167 | let carry: Buffer | null = null |
| 3168 | |
| 3169 | for await (const chunk of stream) { |
| 3170 | const chunkBuf = chunk as Buffer |
| 3171 | const buf = resolveMetadataBuf(carry, chunkBuf) |
| 3172 | if (buf === null) { |
| 3173 | carry = null |
| 3174 | continue |
| 3175 | } |
| 3176 | |
| 3177 | // Fast path: most chunks contain zero metadata markers. Skip line splitting. |
| 3178 | let hasAnyMarker = false |
| 3179 | for (const m of METADATA_MARKER_BUFS) { |
| 3180 | if (buf.includes(m)) { |
| 3181 | hasAnyMarker = true |
| 3182 | break |
| 3183 | } |
| 3184 | } |
| 3185 | |
| 3186 | if (hasAnyMarker) { |
| 3187 | let lineStart = 0 |
| 3188 | let nl = buf.indexOf(NEWLINE) |
| 3189 | while (nl !== -1) { |
| 3190 | // Bounded marker check: only look within this line's byte range |
| 3191 | for (const m of METADATA_MARKER_BUFS) { |
| 3192 | const mIdx = buf.indexOf(m, lineStart) |
| 3193 | if (mIdx !== -1 && mIdx < nl) { |
| 3194 | metadataLines.push(buf.toString('utf-8', lineStart, nl)) |
| 3195 | break |
| 3196 | } |
| 3197 | } |
| 3198 | lineStart = nl + 1 |
| 3199 | nl = buf.indexOf(NEWLINE, lineStart) |
| 3200 | } |
| 3201 | carry = buf.subarray(lineStart) |
| 3202 | } else { |
| 3203 | // No markers in this chunk — just preserve the incomplete trailing line |
| 3204 | const lastNl = buf.lastIndexOf(NEWLINE) |
| 3205 | carry = lastNl >= 0 ? buf.subarray(lastNl + 1) : buf |
| 3206 | } |
| 3207 | |
| 3208 | // Guard against quadratic carry growth for pathological huge lines |
| 3209 | // (e.g., a 10 MB tool-output line with no newline). Real metadata entries |
| 3210 | // are <1 KB, so if carry exceeds this we're mid-message-content — drop it. |
| 3211 | if (carry.length > 64 * 1024) carry = null |
| 3212 | } |
| 3213 | |
| 3214 | // Final incomplete line (no trailing newline at endOffset) |
| 3215 | if (carry !== null && carry.length > 0) { |
no test coverage detected