Skip to content

feat(patch): resilient fuzzy diff engine with Tree-sitter pre-validation - #62

Merged
developjik merged 2 commits into
mainfrom
feat/patch-fuzzy-diff-engine
Nov 30, 2026
Merged

developjik merged 2 commits into
mainfrom
feat/patch-fuzzy-diff-engine

Conversation

@developjik

@developjik developjik commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

Closes #31.

An agent edits by emitting a patch. The patch fails for reasons that have nothing to do with the edit being wrong — the model read a stale file so every line number drifted, or it retyped a context comment so the context no longer matches — and git apply and naive string replacement both call that a hard failure, so the model burns turns retrying. When a patch does land with broken code on disk, everything downstream inherits it.

src/patch/ applies one file's unified diff through four stages that never touch the disk until all of them pass:

  1. parse (parse.rs) — one file's hunks. A second file's header (diff --git, or a plain diff -u ---/+++ pair followed by @@) is an error rather than a silent stop: applying half a patch and reporting success is the failure this engine exists to prevent.
  2. anchor (anchor.rs) — where each hunk belongs in the file as it is now.
  3. render (render.rs) — the shadow file, byte-preserving outside the edit.
  4. validate (syntax.rs) — Tree-sitter parse of the whole shadow file, when a grammar is known.

Then, and only then, atomic::replace writes: a sibling temp file (random name, O_EXCL), the original's permission bits, fsync, rename over the target. There is no rollback path because there is no partial state to roll back.

Against the acceptance criteria

criterion how
hunks apply when code shifted or context differs only in comments/whitespace, within a configurable similarity threshold token-level alignment with ApplyOptions::similarity_threshold (0.60); whitespace and comments are normalized out of the score
atomic application — any hunk unanchored leaves the file byte-identical every hunk anchors before anything renders; the write is one rename. Tested end to end
every patched text file parsed with Tree-sitter before writing; syntax errors rejected with diagnostics PatchError::Syntax { diagnostics }, line:col: unexpected …, file untouched
grammars resolved per file type, safe fallback (log a warning, apply) rust / python / javascript / typescript / tsx, lazily loaded; anything else → SyntaxCheck::Skipped + tracing::warn!
explicit line-number patches still work and take precedence on exact context pass 1 is the byte-exact block: at the declared line, or a single match in the window
tests: moved code, comment drift, partial-apply rollback, syntax-error rejection tests/patch_engine.rs (27 end-to-end) + unit tests per module

The five design points from the lobby

From 키링's review of #31:

  1. Anchor score: exact first, then normalized token similarity with a distance penalty. A byte-exact block outranks fuzzy, so a patch written against the right file version still lands on its numbered line. Equal similarity resolves to the anchor nearest the declared line, so the same patch always lands the same way instead of depending on scan order. The distance term is a tie-break: similarity always decides first, because a distance cost subtracted from the score could outrank a genuinely better target.
  2. Guard against misapplication with an ambiguity margin, not just one threshold. The best anchor must beat the next non-overlapping anchor by ambiguity_margin (0.05), or the patch fails as PatchError::Ambiguous rather than guessing. The comparison is |gap| < margin, so exactly the margin is still distinguishable and margin: 0.0 opts out (for fuzzy anchors; two byte-exact blocks at equal distance are still two edits and are still refused). The boundary is pinned by the_ambiguity_margin_boundary, with the knob itself covered by a_wider_margin_makes_a_close_call_ambiguous / a_zero_margin_turns_the_ambiguity_refusal_off.
  3. Atomic write by anchoring everything first, not by rolling back. All hunks are anchored and confirmed in memory, the file is rendered in a shadow buffer, and one temp file + rename replaces it. A no-op patch writes nothing; apply_patch_file canonicalizes first, so patching through a symlink updates the target and keeps the link.
  4. Whole-file Tree-sitter parse, grammars lazily loaded, load failure is a warning + apply. Parsing a few thousand lines is milliseconds, and an incremental parse against a stale tree would miss exactly the errors the edit introduced. Grammars are OnceLock-cached per language.
  5. Tests split comment paraphrase from comment deletion, plus CRLF and no-trailing-newline. Separate cases for a paraphrased comment, a comment line the file dropped, and a rewritten code line; a_crlf_file_stays_crlf, the no-trailing-newline pair, and the \ No newline marker.

Behaviour a reviewer should check

Rendering writes context lines from the file, not from the patch. A paraphrased comment stays as the file has it; a comment line someone else deleted is not resurrected; nothing the patch did not address is rewritten. That is what makes comment-level fuzz safe in both directions.

Two rules keep that from becoming "it applied, but it means something else":

  • A - line must be in the file. The context may drift; the line being deleted may not. A removal with no trustworthy pair fails as RemovalMissing instead of deleting the nearest line.
  • Added lines follow their block. When the matched context moved into a deeper block, the indentation shift (taken from the first indented matched line) is applied to the added lines, so a Python statement that moved into an if stays inside it.

Review pass (commit fc25c52)

Devin Review's findings were reproduced as tests and fixed:

finding fix
fuzzy patch deletes an unrelated line removals verified against their pair; RemovalMissing
two hunks edit the same lines empty search range is now None → NotAnchored
plain diff -u multi-file patch mixes files ---/+++ + @@ inside a hunk is MultiFile
distance cost inverts the ranking similarity-first, distance as tie-break
token order ignored (a - b vs b - a) similarity blends bag-of-tokens with adjacent token pairs (0.6/0.4)
Python statement written at the old indentation indentation rebased onto the matched line
empty file / newline-marker edge cases \ No newline read per side; empty file gets the implied newline
Python # trailing comment scored as code # after whitespace is a comment
temp file could be redirected by a planted symlink random UUID + create_new (O_EXCL)

Left as documented behaviour rather than "fixed": ambiguity_margin: 0.0 disables the rule for fuzzy anchors only (above), and the alignment is O(hunk × window) per candidate — a 500-line hunk over the default ±250 window repeats comparisons (~10⁸ line comparisons in the pathological case). Worth a benchmark before tuning for very large hunks; not addressed here.

Verified locally

  • cargo test --lib — 353 passed (67 new)
  • cargo test --test patch_engine — 27 passed
  • cargo fmt --check, cargo clippy --lib --tests -- -D warnings

CI on the previous head was green on all 7 checks (test × 3 OSes, coverage, deny, audit, Devin Review); this head is running through the same.

An agent edits by emitting a patch, and the patch fails for reasons that
have nothing to do with the edit: the model read a stale file so every
line number drifted, or it retyped a context comment so the context no
longer matches. `git apply` and naive replacement both call that a hard
failure, the model burns turns retrying, and when a patch does land with
broken code, the broken file poisons everything downstream. This is #31.

`src/patch/` runs four stages and touches the disk only after all of them
pass: parse one file's unified diff, anchor every hunk against the file as
it is now, render a shadow file, parse the shadow file with Tree-sitter.
Then one atomic write (temp file + rename in the same directory) replaces
the file. There is no rollback path because there is no partial state to
roll back — any failure leaves the file byte-identical.

Anchoring, strongest evidence first:
- a byte-exact block (at the declared line, or a single match within the
  search window) outranks fuzzy matching, so a patch written against the
  right file version still lands on its numbered line;
- a pure insertion anchors on its own line number — it has no context to
  score;
- everything else is a token-level alignment around the declared line.
  Indentation, whitespace runs and comment tails do not count, two
  comment-only lines compare at 0.9, but a changed code token lowers the
  score and a comment never stands in for a code line. That is the line
  between "a comment was paraphrased" (apply) and "the code moved on"
  (refuse).

Two rules turn the score into a decision. Equal similarity resolves to
the anchor nearest the declared line (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
`ambiguity_margin` or the patch fails as `ambiguous`: a misplaced edit
costs far more than a rejected one. A gap exactly equal to the margin is
still distinguishable; `margin: 0.0` opts out.

Rendering writes context from the *file*, not from the patch: a
paraphrased comment stays as the file has it, a comment someone else
deleted is not resurrected, and nothing the patch did not address is
rewritten. File line endings survive (a CRLF file stays CRLF with an
LF-only patch), and a file without a trailing newline keeps that shape
through a middle edit and through a final-line rewrite (`\ No newline at
end of file` is honored).

Shadow validation returns Tree-sitter `ERROR`/`MISSING` nodes as
positioned diagnostics and refuses the write, so broken code never reaches
the disk and the model gets something actionable in the same turn.
Grammars (rust, python, javascript, typescript, tsx) are compiled in but
loaded lazily per file type; a file type without one — or a grammar that
fails to load — is a logged warning and an apply (`SyntaxCheck::Skipped`),
never a block.

`apply_patch_file` canonicalizes first (patching through a symlink updates
its target and keeps the link) and preserves permission bits; a no-op
patch writes nothing. `render_patch` is the same pipeline with no IO.

Knobs: `ApplyOptions { similarity_threshold, ambiguity_margin,
search_window, validate_syntax }`. `ApplyReport` returns per-hunk anchors,
the syntax outcome, and warnings (miscounted hunk header, fuzzy anchor
that moved, missing grammar).

Tests: unit coverage of the tokenizer/similarity boundary, the parser
edge cases, every anchoring rule (including the margin boundary and
equidistant ambiguity), the final-line ending rules and the atomic write;
`tests/patch_engine.rs` covers the issue's acceptance criteria end to end
on real files. Docs in `docs/patch-engine.md` (+ `.ko.md`).

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-30T03:43:28.811831Z
We couldn’t complete this review. Comment @codex review to try again.
a34e01b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 11 potential issues.

Devin Review

Comment thread src/patch/anchor.rs
Comment on lines +394 to +402
let (value, dir) = if pair >= skip_old && pair >= skip_file {
(pair, 1u8)
} else if skip_old >= skip_file {
(skip_old, 2u8)
} else {
(skip_file, 3u8)
};
table[i * width + j] = value;
from[i * width + j] = dir;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 퍼지 패치가 무관한 줄을 삭제함

삭제 대상이 바뀌었어도 주변 문맥이 맞으면 패치가 통과합니다. 정렬이 무관한 줄을 삭제 대상으로 넘겨 새 내용을 덮어씁니다.

Learn more

align은 전혀 다른 두 줄을 짝짓는 비용을 0.50으로, 두 줄을 각각 건너뛰는 비용을 합계 0.60으로 계산합니다. 역추적은 짝짓기 결과에 줄별 유사도와 무관하게 이 짝을 포함합니다. 앵커 승인은 평균 점수만 검사하며, 렌더러의 삭제 분기는 이 짝을 그대로 삭제합니다. 반대로 삭제 대상이 완전히 사라졌다면 매핑 없이도 같은 평균 검사에 통과해 추가만 적용될 수 있습니다.

Example: 패치의 삭제 줄 obsolete가 현재 파일에 new-setting으로 바뀌고 주변 세 줄이 같다면, 헝크 점수는 (3 − 0.50) / 4 = 0.625입니다. 기본 임계값 0.60을 넘어 new-setting이 삭제됩니다.

Recommended fix: 정렬에 행 종류를 전달하고, 모든 삭제 줄에 신뢰할 만한 짝이 있는 후보만 승인하세요. 문맥 줄은 건너뛸 수 있게 유지하되, 삭제 줄을 건너뛰거나 최소 증거 미달인 줄과 짝지으면 해당 후보를 거부하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/anchor.rs
Comment on lines +314 to +320
let lo = match window {
Some(w) => nominal.saturating_sub(w),
None => 0,
}
.max(floor)
.min(hi);
(lo, hi.max(lo))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 두 헝크가 같은 원본 줄을 편집함

앞 헝크 뒤에 후보가 없으면 검색이 앞 헝크 안으로 되돌아갑니다. 두 헝크가 같은 줄에 붙으면 뒤 헝크의 삭제만 건너뜁니다.

Learn more

anchor_all은 다음 헝크가 앞 헝크 끝보다 먼저 시작하지 않도록 하한을 넘깁니다. 하한이 탐색 상한보다 높을 때 현재 계산은 빈 범위 대신 상한 한 점을 반환합니다. 이로 인해 정확 일치 검색이 이미 사용한 줄을 다시 선택할 수 있습니다. 렌더러는 그 줄의 삭제는 건너뛰지만 추가 줄은 출력합니다. 같은 범위 계산은 선언 위치 주변 윈도가 파일과 전혀 겹치지 않을 때도 창 밖의 마지막 후보 하나를 검색합니다.

Example: 이전 파일의 1행과 5행에 둘 다 alpha가 있고 두 헝크가 이를 각각 A, B로 바꾼다고 가정합니다. 현재 파일에는 첫 alpha만 남아 있습니다. 첫 헝크가 유일한 줄을 소비한 뒤에도 두 번째 헝크가 같은 줄을 찾아 결과가 A\nB\n이 됩니다.

Recommended fix: 윈도, 파일 범위, 앞 헝크 하한의 교집합이 비면 빈 범위를 반환하고 NotAnchored로 끝내세요. search_window 상한을 더할 때는 포화 덧셈을 사용하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/parse.rs
Comment on lines +153 to +155
if line.starts_with("diff --git ") || line.starts_with("diff --cc ") {
return Err(ParseError::MultiFile { line: line_no });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 다중 파일 패치가 한 파일에 섞여 적용됨

diff -u로 만든 두 번째 파일 헤더가 첫 헝크의 편집 줄로 처리됩니다. 두 헝크가 맞으면 두 파일의 변경과 헤더 일부가 한 파일에 기록됩니다.

Learn more

파서는 diff --git과 diff --cc만 후속 파일 경계로 감지합니다. 일반 unified diff가 사용하는 연속 --- / +++ 헤더는 본문 분기로 들어갑니다. anchor_one은 다른 본문 줄이 충분히 맞으면 첫 헝크를 승인하고, 뒤 헝크도 동일한 대상 파일에서 찾습니다. render는 두 번째 파일의 +++ 헤더까지 추가 줄로 출력합니다.

Example: 내용이 같은 여섯 줄짜리 텍스트 파일 두 개에 대해 diff -U2 결과를 이어 붙입니다. 첫 diff는 1행을, 둘째 diff는 6행을 수정합니다. 첫 헝크는 문맥 포함 세 줄이 일치해 잘못 포함된 삭제 헤더에도 점수 0.675로 통과합니다. 둘째 헝크도 정확히 맞아 두 편집이 첫 파일에 들어갑니다.

Recommended fix: 후속 --- / +++ 쌍과 이어지는 헝크를 파일 경계로 인식하고 MultiFile을 반환하세요. 헤더처럼 보이는 합법적인 본문 줄도 있으므로 헤더 쌍의 위치와 주변 구조를 함께 확인하고 양쪽 사례를 테스트하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/anchor.rs
Comment on lines +238 to +242
let same_score = best.similarity - runner.similarity <= TIE_EPSILON;
let distance_decides =
same_score && best.start.abs_diff(nominal) < runner.start.abs_diff(nominal);
if !distance_decides
&& within_margin(best.similarity, runner.similarity, opts.ambiguity_margin)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 더 잘 맞는 위치를 두고 다른 줄에 패치가 붙음

거리 차감이 유사도 순위를 뒤집으면 실제 점수 차이를 동점으로 봅니다. 모호성 검사도 건너뛰어 덜 닮은 줄을 수정합니다.

Learn more

rank는 실제 유사도에서 거리에 따라 최대 0.05를 빼고 정렬합니다. 그 결과 실제 유사도가 더 낮은 후보가 1위가 되면 best.similarity - runner.similarity는 음수가 됩니다. 현재 분기는 이 값을 동점으로 처리해 더 가까운 1위 후보를 모호성 검사 없이 승인합니다.

Example: 선언 위치에는 상수 하나가 바뀐 줄이 있어 0.96점이고, 100줄 떨어진 진짜 대상에는 끝 주석만 추가되어 1.00점이라고 가정합니다. 정확 일치는 없고, 거리 차감 후 순위는 0.96 대 0.95입니다. 원점수는 동점이 아니고 격차도 기본 마진보다 작지만 가까운 줄에 패치가 적용됩니다.

Recommended fix: 실제 유사도를 첫 정렬 기준으로 사용하고 동일한 점수에서만 거리로 순위를 정하세요. 동점 판정도 유사도 차이의 절댓값으로 하여 음수 차이가 예외를 통과하지 못하게 하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/score.rs
Comment on lines +110 to +115
code.sort_unstable();
LineTokens {
code,
has_comment,
blank: line.trim().is_empty(),
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 연산 순서가 다른 줄에 퍼지 패치가 붙음

토큰 순서를 버려 뺄셈의 피연산자가 뒤바뀐 줄도 같은 코드로 평가합니다. 그 줄이 더 가까우면 실제 대상 대신 수정됩니다.

Learn more

similarity는 정렬된 토큰 배열의 교집합을 계산합니다. 동일한 토큰이 동일한 횟수만 나타나면 순서가 바뀌어도 1.0입니다. 실제 대상에도 끝 주석이 추가됐다면 정확 일치가 없고, 퍼지 순위가 동일한 점수의 두 후보 중 가까운 쪽을 선택합니다.

Example: let elapsed = end - start;를 대상으로 하는 패치에서 실제 줄 뒤에는 주석이 추가됐고, 선언 위치에는 let elapsed = start - end;가 있습니다. 둘 다 1.0점이어서 반대 방향으로 차이를 계산하는 줄이 바뀝니다.

Recommended fix: 정규화에서 공백과 주석만 제거하고 토큰 순서는 유지하세요. 순서가 다른 후보는 완전 일치에서 제외하고, 올바른 후보를 선택하거나 모호한 패치로 거부하는 회귀 테스트를 추가하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/render.rs
Comment on lines +124 to +125
let drop_final_newline =
eof_marker || (last_is_added && reaches_eof && !file_ends_with_newline);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 표준 패치의 마지막 개행이 누락됨

빈 파일에 첫 줄을 추가하거나 마지막 개행을 복구하는 패치에 기존 개행 상태를 강제합니다. 성공을 반환하지만 요청한 개행은 쓰지 않습니다.

Learn more

초기 개행 판정은 줄이 없는 파일과 마지막 줄에 개행이 없는 파일을 구분하지 않습니다. 파서는 No newline at end of file이 삭제 줄에 붙었더라도 다음 추가 줄을 읽을 때 그 정보를 지웁니다. 따라서 결과 쪽에 개행이 있는 표준 패치도 기존 상태 보존 분기로 들어갑니다.

Example: 빈 파일에 +hello 한 줄을 넣는 표준 diff는 hello\n을 뜻하지만 결과는 hello입니다. 또 원본이 b이고 -b에만 개행 없음 마커가 붙은 뒤 +b가 오면, 개행만 추가해야 할 패치가 무변경으로 끝납니다.

Recommended fix: 개행 없음 마커를 그 앞 본문 줄의 원본·결과 쪽 정보로 보존하세요. 빈 입력에 대한 기본 추가에는 개행을 쓰고, 원본 쪽에만 마커가 있으면 결과 쪽에는 개행을 복구하세요. 어느 쪽에도 명시적 마커가 없는 비어 있지 않은 입력에는 기존 보존 정책을 유지할 수 있습니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/score.rs
Comment on lines +77 to +85
// `#` starts a comment when nothing but indentation precedes it
// and it is not a Rust attribute (`#[…]`) or inner attribute
// (`#![…]`).
'#' if line[..i].trim().is_empty()
&& !matches!(bytes.get(i + 1), Some(b'[') | Some(b'!')) =>
{
has_comment = true;
break;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 파이썬 줄 끝 주석이 바뀌면 패치가 거부됨

파이썬 줄 끝의 # 주석을 코드로 채점합니다. 주석 문구만 달라져도 짧은 코드 줄의 유사도가 임계값 아래로 떨어집니다.

Learn more

anchor_all은 파일 종류를 토크나이저에 전달하지 않습니다. 토크나이저는 # 앞에 코드가 있으면 뒤의 설명을 일반 토큰으로 처리합니다. anchor_one은 주석 때문에 떨어진 점수에도 일반 임계값을 적용합니다.

Example: 패치가 return result # read existing configuration from the workspace를 교체하려는데 현재 줄이 return result # use cached settings when possible이면, 같은 코드를 담고 있어도 유사도는 약 0.35입니다. 주변 문맥이 없는 한 줄 헝크는 기본 임계값 0.60을 통과하지 못합니다.

Recommended fix: 파일 종류를 정렬과 토크나이저까지 전달하고, 파이썬 모드에서는 인용부 밖의 #을 줄 끝 주석으로 처리하세요. 주석 문구가 달라진 한 줄 파이썬 교체 테스트를 추가하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/anchor.rs
Comment on lines +170 to +181
// Pass 2: fuzzy alignment over a window around the declared line.
let old_tokens: Vec<LineTokens> = old.iter().map(|l| score::tokenize(l)).collect();
let slack = (old.len() / 4).clamp(4, 32);
let mut by_start: BTreeMap<usize, Candidate> = BTreeMap::new();
for start in lo..=hi {
let end = (start + old.len() + slack).min(original.len());
if end <= start {
continue;
}
let Some((similarity, mut pairs)) = align(&old_tokens, &tokens[start..end]) else {
continue;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 큰 헝크의 퍼지 탐색은 같은 비교를 반복함

기본 검색 범위에서 500줄 헝크는 주석 한 줄만 달라져도 줄 유사도를 약 1억 3천만 번 계산합니다. align이 겹치는 검색 창마다 비교를 반복하므로, 대형 편집의 지연을 벤치마크할 필요가 있습니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/anchor.rs
Comment on lines +340 to +351
let mut tied = matches.iter().filter(|m| m.abs_diff(nominal) == nearest);
let first = *tied.next().expect("matches is not empty");
if let Some(second) = tied.next() {
return Err(PatchError::Ambiguous {
hunk: index + 1,
total,
best: 1.0,
best_line: first + 1,
runner_up: 1.0,
runner_line: second + 1,
margin: opts.ambiguity_margin,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 마진을 0으로 바꿔도 등거리 정확 일치는 거부됨

퍼지 후보와 달리 정확 일치 후보는 선언 위치에서 같은 거리에 있으면 ambiguity_margin: 0.0이어도 거부됩니다. 마진 비활성화가 퍼지 후보에만 적용되는지 API 문서에서 명시할 필요가 있습니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/atomic.rs
Comment on lines +31 to +35
let temp = directory.join(format!(".{name}.damon-patch-{}.tmp", unique_suffix()));

let metadata = std::fs::metadata(path).ok();
let result = (|| -> io::Result<()> {
let mut file = std::fs::File::create(&temp)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟥 패치 임시 파일을 통해 다른 파일을 덮어쓸 수 있음

공유 작업 디렉터리에 쓸 수 있는 로컬 사용자가 임시 경로를 제어할 수 있습니다. 패치 엔진은 기존 링크를 따라가 패치 프로세스 권한으로 다른 파일을 덮어씁니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

`cargo audit` fails on every PR since 2026-11-29 — the advisory landed
after main's last green run — on a crate this branch does not touch:

    Crate:    curve25519-dalek
    Version:  5.0.0
    Title:    Scalar Multiplication Arithmetic Bug in AVX-512 Backend
    ID:       RUSTSEC-2026-0620
    Solution: Upgrade to >=5.1.0 (patched)

Pick up the patched release. `x25519-dalek 3` requires `^5`, so this is a
lockfile-only patch bump within the range it already declares, and the
E2E relay stack (x25519-dalek 3 + aes-gcm 0.11 on rand_core 0.10) still
resolves as one.

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

Devin Review

Comment thread Cargo.lock
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
version = "5.1.0"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 Info: 패치 엔진이 아닌 릴레이 키 교환에 적용되는 의존성 변경

이 의존성은 릴레이 키 교환에서 x25519-dalek을 통해 사용됩니다. 배포된 소스에서 몽고메리 연산 코드는 그대로이고, 64비트 필드 제곱도 기존 수식을 유지합니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@developjik
developjik merged commit 56fc5c9 into main Nov 30, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(patch): resilient fuzzy diff engine with AST syntax pre-validation

1 participant