@@ -131,19 +131,30 @@ export const apply_diff = (params: {
131131 let replace_chunks = [ ]
132132
133133 let inside_replace_block = false
134+ let has_context_lines = false
135+
134136 for ( let i = 0 ; i < patch_lines_normalized . length ; i ++ ) {
135137 const line = patch_lines_normalized [ i ]
136138 const line_original = patch_lines_original [ i ]
137139
138140 if ( line . startsWith ( '@@' ) ) {
139141 if ( search_chunks . length > 0 || replace_chunks . length > 0 ) {
142+ // Validate that the hunk has context before adding it
143+ if ( ! has_context_lines && search_chunks . length === 0 && replace_chunks . length > 0 ) {
144+ throw new Error (
145+ 'Zero-context hunk detected: hunks with only additions and no context lines cannot be reliably applied. ' +
146+ 'The diff must include surrounding unchanged lines for proper placement.'
147+ )
148+ }
149+
140150 search_replace_blocks . push (
141151 new SearchBlock ( search_chunks , replace_chunks , - 1 )
142152 )
143153 }
144154 search_chunks = [ ]
145155 replace_chunks = [ ]
146156 inside_replace_block = false
157+ has_context_lines = false
147158 }
148159
149160 if ( line . startsWith ( '-' ) || line . startsWith ( '~' ) ) {
@@ -158,6 +169,7 @@ export const apply_diff = (params: {
158169
159170 search_chunks = [ ]
160171 replace_chunks = [ ]
172+ has_context_lines = false
161173 }
162174
163175 if ( line . startsWith ( '--' ) ) {
@@ -173,8 +185,10 @@ export const apply_diff = (params: {
173185 // Also replace unchanged lines
174186 if ( line . startsWith ( '~nnn' ) ) {
175187 replace_chunks . push ( line_original . replace ( / ^ ~ n n n / , '' ) + '\n' )
188+ has_context_lines = true
176189 } else if ( line . startsWith ( '~' ) ) {
177190 replace_chunks . push ( line_original . replace ( / ^ ~ / , '' ) + '\n' )
191+ has_context_lines = true
178192 }
179193
180194 continue
@@ -202,6 +216,14 @@ export const apply_diff = (params: {
202216 }
203217
204218 if ( search_chunks . length != 0 || replace_chunks . length != 0 ) {
219+ // Final validation for zero-context hunks
220+ if ( ! has_context_lines && search_chunks . length === 0 && replace_chunks . length > 0 ) {
221+ throw new Error (
222+ 'Zero-context hunk detected: hunks with only additions and no context lines cannot be reliably applied. ' +
223+ 'The diff must include surrounding unchanged lines for proper placement.'
224+ )
225+ }
226+
205227 // This is crucial for diffs that only have deletions
206228 search_replace_blocks . push (
207229 new SearchBlock ( search_chunks , replace_chunks , - 1 )
@@ -296,4 +318,4 @@ export const apply_diff = (params: {
296318 } )
297319 throw error
298320 }
299- }
321+ }
0 commit comments