Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 33 additions & 14 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,23 @@
declared line, or a single match within the search window) outranks
everything, a pure insertion anchors on its line number, and the rest
are scored by token-level similarity — indentation, whitespace runs and
comment tails do not count, two comment-only lines compare at 0.9, but a
changed *code* token does lower the score, and a comment never stands in
for a code line.
comment tails (Python `#` included) do not count, two comment-only lines
compare at 0.9, but a changed *code* token does lower the score, and a
comment never stands in for a code line. Token order counts too: a
bag-of-tokens Dice score blended with adjacent token pairs keeps
`end - start` from passing as `start - end`.
- A hunk's `-` lines are held to a stricter rule than its context: the
context may drift, but the line being **removed must still carry that
code in the file**. Comments and indentation may differ; the tokens may
not. A removal whose pair carries different code (or has no pair) fails
as `RemovalMissing` instead of deleting the nearest line — and a second
application of an applied patch therefore fails instead of removing its
replacement.
- Two rules turn a score into a decision. An **equal-similarity tie
resolves to the anchor nearest the declared line** (a distance penalty),
so the same patch always lands the same way instead of depending on scan
order. And the best anchor must beat the next non-overlapping one by
resolves to the anchor nearest the declared line** (a distance tie-break
— similarity always decides first, so the tie-break cannot outrank a
better-scoring target), so the same patch always lands the same way
instead of depending on scan order. And the best anchor must beat the next non-overlapping one by
`ambiguity_margin`, or the patch fails as `ambiguous` — a patch applied
to the wrong place costs far more than one rejected. Exactly the
configured margin is still distinguishable, and `margin: 0.0` opts out.
Expand All @@ -33,8 +43,14 @@
else deleted is not resurrected, and nothing the patch did not address is
rewritten. The file's own line endings survive (a CRLF file stays CRLF
with an LF-only patch), and a file that ends without a newline keeps
ending that way through a middle edit and through a final-line rewrite
(`\ No newline at end of file` is honored).
ending that way through a middle edit and through a final-line rewrite —
with `\ No newline at end of file` read per side, so a marker on the
removed line means the patch is *adding* the newline back. An empty file
gets the newline a normal patch implies, and an added line follows its
block when the block moved deeper (the indentation shift comes from the
matched code lines, all of which must agree), so a Python statement that
moved into an `if` stays inside it — while a moved *comment* does not drag
code with it and the inside of a triple-quoted string is left alone.
- **Shadow validation** parses the whole post-patch file and returns
`ERROR`/`MISSING` nodes as positioned diagnostics (`line:col: unexpected
…`) with the patch rejected, so broken code never reaches the disk and
Expand All @@ -45,7 +61,9 @@
`SyntaxCheck::Skipped`, never a block.
- `apply_patch_file` canonicalizes first (patching through a symlink
updates its target, keeping the link) and preserves the target's
permission bits. A no-op patch writes nothing. `render_patch` offers the
permission bits. The temp file name carries a random UUID and is opened
with `O_EXCL` (`create_new`), so a planted symlink in a shared directory
cannot redirect the write. A no-op patch writes nothing. `render_patch` offers the
same pipeline in memory with no IO.
- `ApplyOptions` carries the knobs: `similarity_threshold` (0.60),
`ambiguity_margin` (0.05), `search_window` (±250 lines, `None` = whole
Expand All @@ -54,11 +72,12 @@
a miscounted hunk header, a fuzzy anchor that moved, or a missing
grammar.
- Tests: unit coverage for the tokenizer/similarity boundaries (comment
paraphrase vs code change, attributes, strings, Korean text), the parser
(CRLF, bare empty context line, EOF marker, multi-file refusal), the
anchoring rules (exact precedence, moved block, nearest of two,
equidistant ambiguity, margin boundary, out-of-order hunks) and the
atomic write; `tests/patch_engine.rs` covers the issue's acceptance
paraphrase vs code change, token order, attributes, strings, Korean
text), the parser (CRLF, bare empty context line, per-side EOF markers,
`diff --git` and plain `diff -u` multi-file refusal), the anchoring rules
(exact precedence, moved block, nearest of two, equidistant ambiguity,
margin boundary, out-of-order hunks, no hunk reusing another's lines, a
missing removal line) and the atomic write; `tests/patch_engine.rs` covers the issue's acceptance
criteria end to end on real files, including `one bad hunk leaves the
file byte-identical` and `a syntax error writes nothing`. Docs:
`docs/patch-engine.md` (+ `.ko.md`).
Expand Down
42 changes: 34 additions & 8 deletions docs/patch-engine.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,27 @@

퍼지 점수는 줄별 유사도를 정렬해 평균한 값이고, 각 줄은 정규화 후
*토큰*으로 비교한다(`src/patch/score.rs`). 들여쓰기와 연속 공백은
토큰이 되지 않고, 줄 끝 주석은 코드 토큰에 들어가지 않으며, 주석만 있는
두 줄은 0.9로 비교된다. 반면 *코드* 토큰이 바뀌면 점수가 실제로
떨어진다 — 패치가 엉뚱한 함수에 붙지 않게 하는 장치다. 주석 줄이 코드
줄을 대신할 수는 없다.
토큰이 되지 않고, 줄 끝 주석(파이썬 `#` 주석 포함)은 코드 토큰에 들어가지
않으며, 주석만 있는 두 줄은 0.9로 비교된다. 반면 *코드* 토큰이 바뀌면
점수가 실제로 떨어진다 — 패치가 엉뚱한 함수에 붙지 않게 하는 장치다.
주석 줄이 코드 줄을 대신할 수는 없다. 토큰 **순서**도 반영한다. 단어
가방(bag-of-tokens) Dice 점수와 인접 토큰 쌍에 대한 같은 점수를 섞어,
`end - start`와 `start - end`는 비슷하지만 같지는 않다.

hunk의 `-` 줄은 컨텍스트와 다르게 다룬다. 컨텍스트는 드리프트를
견디지만 **삭제 대상 줄은 그 코드가 파일에 그대로 있어야 한다**. 주석과
들여쓰기는 달라도 되지만 토큰은 달라서는 안 된다. 코드가 다른 짝, 또는
짝이 아예 없는 삭제 줄은 가장 가까운 줄을 지우는 대신
`PatchError::RemovalMissing`으로 실패한다. 패치가 보지 못한 내용을
지우는 조용한 손상은 거부된 패치보다 나쁘다(이미 적용된 패치를 다시
적용하면 교체 결과를 지우는 대신 실패한다).

점수를 결정으로 바꾸는 규칙 두 가지:

- **거리 페널티** — 유사도가 같으면 선언된 줄에 가까운 앵커를 고른다.
스캔 순서가 아니라 규칙이 결과를 정하므로 재현 가능하다.
스캔 순서가 아니라 규칙이 결과를 정하므로 재현 가능하다. 점수를 깎는
방식이 아니라 동점 처리 규칙이다. 거리 비용을 점수에서 빼면 실제로
더 잘 맞는 대상을 앞지를 수 있기 때문에, 유사도가 항상 먼저다.
- **모호성 마진** — 최적 앵커는 겹치지 않는 차선 앵커를
`ambiguity_margin`만큼 앞서야 한다. 근소한 차이는 추측하지 않고
`PatchError::Ambiguous`로 실패한다. 잘못 붙은 편집의 복구 비용이
Expand All @@ -70,8 +82,16 @@
있는 그대로 남고, 다른 사람이 지운 주석 줄은 되살아나지 않는다.
- CRLF 파일은 패치가 LF로 와도 CRLF를 유지한다.
- 파일 끝에 개행이 없으면, 중간 편집 뒤에도, 마지막 줄을 고쳐 쓴 뒤에도
개행이 없는 채로 남는다(표준
`\ No newline at end of file` 마커가 있으면 그대로 따른다).
개행이 없는 채로 남는다. 표준 `\ No newline at end of file` 마커는 양쪽
모두에서 존중한다. 결과 쪽에 붙으면 개행 없음, 삭제 쪽에 붙으면 패치가
빠진 개행을 **되살리는** 중이다.
- 블록이 더 깊은 곳으로 옮겨졌으면 추가 줄도 따라간다. 들여쓰기 차이는
매칭된 **코드** 줄에서만 계산하고(옮겨진 주석은 블록의 이동을 말해주지
않는다), 모든 코드 줄이 같은 차이를 가리켜야 하며, 패치 자체의 접두사가
교체 줄의 접두사일 때만 적용한다. 열린 삼중 따옴표 문자열 안의 줄은
건드리지 않는다. 그 공백은 들여쓰기가 아니라 데이터다.
- 빈 파일에는 일반 패치가 뜻하는 개행이 들어간다(`+hello`는 `hello\n`).
애초에 없던 '끝 개행 없음' 모양을 물려받지 않는다.

## 섀도 검증

Expand Down Expand Up @@ -99,6 +119,11 @@ best-effort). 같은 파일시스템 안에서 rename은 원자적이라, 읽는
`apply_patch_file`은 먼저 canonicalize하므로 심볼릭 링크를 거친 패치는
링크를 일반 파일로 바꾸지 않고 대상 파일을 고친다.

임시 경로에는 무작위 UUID가 들어가고 `create_new`(`O_EXCL`)로 연다.
다른 로컬 사용자가 쓸 수 있는 디렉터리에서 예측 가능한 이름은 공격
지점이다. 그 자리에 심볼릭 링크를 심으면 패치 프로세스 권한으로 링크가
가리키는 곳에 쓰이기 때문이다.

렌더 결과가 원본과 같으면(무변경 패치) 아무것도 쓰지 않는다.

## API
Expand Down Expand Up @@ -132,8 +157,9 @@ let rendered = render_patch(Path::new("src/lib.rs"), &original, patch_text, &App

| 변형 | 발생 조건 |
|---|---|
| `Parse` | 파일 하나의 unified diff가 아님(hunk 없음, 헤더 깨짐, 본문 쓰레기 줄, 두 번째 파일) |
| `Parse` | 파일 하나의 unified diff가 아님(hunk 없음, 헤더 깨짐, 본문 쓰레기 줄, 두 번째 파일 — `diff --git` 또는 `---`/`+++` 쌍 뒤에 `@@`) |
| `NotAnchored` | 임계값을 넘는 후보 없음(최고 점수·줄·거리 보고) |
| `RemovalMissing` | `-` 줄이 파일에 없음 — 패치가 본 적 없는 내용을 지우게 됨 |
| `Ambiguous` | 최적 두 앵커가 마진 이내 |
| `OutOfOrder` | hunk가 파일 순서가 아님 |
| `Syntax` | 섀도 파일 파싱 실패(`diagnostics()`로 진단 반환) |
Expand Down
49 changes: 40 additions & 9 deletions docs/patch-engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,31 @@ Three passes, strongest evidence first:

The fuzzy score is the aligned average of per-line similarities, each
compared on *tokens* after normalization (`src/patch/score.rs`):
indentation and whitespace runs vanish, a line's comment tail is not part
of its code tokens, and two comment-only lines compare at 0.9. A changed
*code* token does move the score — that is what keeps a patch from
anchoring onto the wrong function — and a comment line never stands in
for a code line.
indentation and whitespace runs vanish, a line's comment tail (including
a Python `#` comment) is not part of its code tokens, and two comment-only
lines compare at 0.9. A changed *code* token does move the score — that is
what keeps a patch from anchoring onto the wrong function — and a comment
line never stands in for a code line. Token *order* also counts: the
similarity blends a bag-of-tokens Dice score with the same measure over
adjacent token pairs, so `end - start` and `start - end` are similar but
not identical.

A hunk's `-` lines are treated differently from its context: the context
may drift, but the line being **removed must still carry that code in the
file**. Comments and indentation may differ; the tokens may not. A
removal whose pair has different code, or no pair at all, fails as
`PatchError::RemovalMissing` instead of deleting the nearest line — that
silent corruption is the one outcome worse than a rejected patch (and it
makes re-applying an applied patch fail instead of removing its
replacement).

Two rules turn scores into a decision:

- **Distance penalty** — an equal-similarity tie resolves to the anchor
nearest the declared line, so the outcome is reproducible instead of
depending on scan order.
depending on scan order. It is a tie-break, not a score adjustment: a
distance cost subtracted from the score could outrank a genuinely
better target, so similarity always decides first.
- **Ambiguity margin** — the best anchor must beat the next
non-overlapping one by `ambiguity_margin`. A near-tie fails as
`PatchError::Ambiguous` rather than guessing: a misplaced edit costs far
Expand All @@ -76,8 +90,19 @@ Consequences worth knowing:
else deleted is not resurrected.
- A CRLF file stays CRLF even when the patch arrived LF-only.
- A file that ends without a newline keeps ending without one through a
middle edit, and through a rewrite of its final line (the standard
`\ No newline at end of file` marker is honored when present).
middle edit, and through a rewrite of its final line. The standard
`\ No newline at end of file` marker is honored on both sides: on the
result side it means "no newline", on the removed side it means the
patch is *adding* the missing newline back.
- An added line follows its block when the block moved deeper: the
indentation shift is taken from the matched *code* lines only (a comment
that moved says nothing about the block), must be the same for every one
of them, and is applied only when the patch's own prefix is a prefix of
the replacement line. Lines inside an open triple-quoted string are left
alone — that whitespace is data, not indentation.
- An empty file gets the newline a normal patch implies (`+hello` means
`hello\n`), rather than inheriting a "no trailing newline" shape it
never had.

## Shadow validation

Expand Down Expand Up @@ -105,6 +130,11 @@ filesystem, so a reader sees the old bytes or the new ones, never a
mixture. `apply_patch_file` canonicalizes first, so patching through a
symlink updates the target instead of replacing the link.

The temp path carries a random UUID and is opened with `create_new`
(`O_EXCL`): a predictable name in a directory another local user can write
to is an attack — plant a symlink there and the write lands wherever it
points, with the patching process's privileges.

If the rendered text equals the original (a no-op patch), nothing is
written at all.

Expand Down Expand Up @@ -139,8 +169,9 @@ All variants of `PatchError` mean the file on disk is unchanged.

| variant | when |
|---|---|
| `Parse` | not one file's unified diff (no hunk, broken header, garbage body line, second file) |
| `Parse` | not one file's unified diff (no hunk, broken header, garbage body line, second file — `diff --git` or a `---`/`+++` pair followed by `@@`) |
| `NotAnchored` | no candidate reached the threshold (reports best score, line, distance) |
| `RemovalMissing` | a `-` line's code is not in the file — the patch would delete content it never saw |
| `Ambiguous` | the best two anchors are within the margin |
| `OutOfOrder` | hunks are not in file order |
| `Syntax` | the shadow file did not parse (`diagnostics()` returns them) |
Expand Down
Loading
Loading