MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / scanForContext

Function scanForContext

source code/utils/readEditContext.ts:62–115  ·  view source on GitHub ↗
(
  handle: FileHandle,
  needle: string,
  contextLines: number,
)

Source from the content-addressed store, hash-verified

60 * Handle-accepting core of readEditContext. Caller owns open/close.
61 */
62export async function scanForContext(
63 handle: FileHandle,
64 needle: string,
65 contextLines: number,
66): Promise<EditContext> {
67 if (needle === '') return { content: '', lineOffset: 1, truncated: false }
68 const needleLF = Buffer.from(needle, 'utf8')
69 // Model sends LF; files may be CRLF. Count newlines to size the overlap for
70 // the longer CRLF form; defer encoding the CRLF buffer until LF scan misses.
71 let nlCount = 0
72 for (let i = 0; i < needleLF.length; i++) if (needleLF[i] === NL) nlCount++
73 let needleCRLF: Buffer | undefined
74 const overlap = needleLF.length + nlCount - 1
75
76 const buf = Buffer.allocUnsafe(CHUNK_SIZE + overlap)
77 let pos = 0
78 let linesBeforePos = 0
79 let prevTail = 0
80
81 while (pos < MAX_SCAN_BYTES) {
82 const { bytesRead } = await handle.read(buf, prevTail, CHUNK_SIZE, pos)
83 if (bytesRead === 0) break
84 const viewLen = prevTail + bytesRead
85
86 let matchAt = indexOfWithin(buf, needleLF, viewLen)
87 let matchLen = needleLF.length
88 if (matchAt === -1 && nlCount > 0) {
89 needleCRLF ??= Buffer.from(needle.replaceAll('\n', '\r\n'), 'utf8')
90 matchAt = indexOfWithin(buf, needleCRLF, viewLen)
91 matchLen = needleCRLF.length
92 }
93 if (matchAt !== -1) {
94 const absMatch = pos - prevTail + matchAt
95 return await sliceContext(
96 handle,
97 buf,
98 absMatch,
99 matchLen,
100 contextLines,
101 linesBeforePos + countNewlines(buf, 0, matchAt),
102 )
103 }
104 pos += bytesRead
105 // Shift the tail to the front for straddle. linesBeforePos tracks
106 // newlines in bytes we've DISCARDED (not in buf) — count only the
107 // non-overlap portion we're about to copyWithin over.
108 const nextTail = Math.min(overlap, viewLen)
109 linesBeforePos += countNewlines(buf, 0, viewLen - nextTail)
110 prevTail = nextTail
111 buf.copyWithin(0, viewLen - prevTail, viewLen)
112 }
113
114 return { content: '', lineOffset: 1, truncated: pos >= MAX_SCAN_BYTES }
115}
116
117/**
118 * Reads the entire file via `handle` up to MAX_SCAN_BYTES. Returns null if the

Callers 2

loadDiffDataFunction · 0.85
readEditContextFunction · 0.85

Calls 4

indexOfWithinFunction · 0.85
sliceContextFunction · 0.85
countNewlinesFunction · 0.85
readMethod · 0.45

Tested by

no test coverage detected