From a34e01b89e1e0856493f489501f97d7656ab09da Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:42:07 +0900 Subject: [PATCH 1/2] feat(patch): resilient fuzzy diff engine with Tree-sitter pre-validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: 정인권 --- AGENTS.md | 3 + ARCHITECTURE.md | 1 + CHANGELOG.md | 65 +++++ Cargo.lock | 83 ++++++ Cargo.toml | 10 + docs/patch-engine.ko.md | 172 ++++++++++++ docs/patch-engine.md | 183 +++++++++++++ src/lib.rs | 1 + src/patch/anchor.rs | 564 ++++++++++++++++++++++++++++++++++++++++ src/patch/atomic.rs | 128 +++++++++ src/patch/mod.rs | 474 +++++++++++++++++++++++++++++++++ src/patch/parse.rs | 348 +++++++++++++++++++++++++ src/patch/render.rs | 172 ++++++++++++ src/patch/score.rs | 250 ++++++++++++++++++ src/patch/syntax.rs | 319 +++++++++++++++++++++++ tests/patch_engine.rs | 378 +++++++++++++++++++++++++++ 16 files changed, 3151 insertions(+) create mode 100644 docs/patch-engine.ko.md create mode 100644 docs/patch-engine.md create mode 100644 src/patch/anchor.rs create mode 100644 src/patch/atomic.rs create mode 100644 src/patch/mod.rs create mode 100644 src/patch/parse.rs create mode 100644 src/patch/render.rs create mode 100644 src/patch/score.rs create mode 100644 src/patch/syntax.rs create mode 100644 tests/patch_engine.rs diff --git a/AGENTS.md b/AGENTS.md index 183d086..07f81b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,6 +33,8 @@ Persistence goes through `src/store.rs` (`Store`, tokio-rusqlite wrapper, sessio **Sandbox (`src/sandbox/`)**: one declarative policy (`sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"`, global / per backend / per session) compiled into the driver's native launcher. `decide()` is the only place the rules live: an explicit request that the backend or host cannot honor is an error naming the cause and choices (never a silent fallback), `auto` may fall back and reports why, and a serve-mode backend (opencode, mimo) resolves to `unsupported` rather than `none` because it has no per-session child to wrap. Spawn-mode backends launch through `ResolvedBackend::spawn_ndjson`, so every one of them inherits the policy; the compiler (`bwrap::compile_args`) is pure and golden-tested, the planner (`compile_policy`) resolves symlinks and refuses `/` or credential paths as writable. +**Patch engine (`src/patch/`)**: applies one file's unified diff from an agent. Four stages — parse, anchor every hunk, render a shadow file, parse it with Tree-sitter — run without touching the disk; only then does `atomic::replace` write (temp file + rename), so any failure leaves the file byte-identical. Anchoring is strongest-evidence-first: a byte-exact block outranks fuzzy, a pure insertion uses its line number, and the rest are scored by token similarity with a distance tie-break and an ambiguity margin (`ambiguous` rather than a guess). Context lines are written back from the *file* (comment wording and untouched lines survive), the file's line endings survive, and a file type without a grammar applies with a logged warning (`SyntaxCheck::Skipped`) instead of failing. Knobs live in `ApplyOptions`; `render_patch` is the same pipeline with no IO. + ## Key Directories | Path | Purpose | @@ -44,6 +46,7 @@ Persistence goes through `src/store.rs` (`Store`, tokio-rusqlite wrapper, sessio | `src/state.rs` | Pure serializable session state (phases, open turn, parked ask, rollups) + the `sessions.state.json` checkpoint shape — no IO, no async, no process types (`tests/state_boundary.rs` enforces it) | | `src/store.rs` | SQLite + FTS5 persistence (`Store::open` / `Store::in_memory`) | | `src/skills_hub/` | Skill package manager: discovery, fetch, install lifecycle, target roots | +| `src/patch/` | Fuzzy patch engine: unified-diff parse → anchor → shadow render → Tree-sitter validation → one atomic write | | `src/channel.rs` + `telegram.rs`/`slack.rs`/`discord.rs` | Chat bridge + per-platform adapters | | `src/relay.rs`, `src/bin/damon-relay.rs` | E2E-encrypted outbound tunnel (X25519 + AES-256-GCM) | | `src/sandbox/` | OS-level isolation: the declarative policy (`SandboxRequest` → `SandboxDecision`), the thin `SandboxDriver` trait, and the bwrap driver (`bwrap.rs`: policy → launcher argv, availability probe). Resolved per session at the spawn point (`ResolvedBackend::spawn_ndjson`); seatbelt/docker are follow-ups to #33 | diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 5620d32..8d804ca 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -111,6 +111,7 @@ agent CLI subprocess (stream-json / NDJSON / HTTP+SSE) | `src/prompts.rs` | 프롬프트 라이브러리(`/.damon/prompts/`, `/prompts/`) | scope별 목록/CRUD | | `src/skills_hub/` | 스킬 패키지 매니저: discovery·fetch·install lifecycle·target roots | `TargetRoot`, `InstalledSkill`, `HubError`, `ScanRoots` | | `src/worktree.rs` | git worktree 워크스페이스 — "PR 하나당 격리 워크스페이스 하나" | `WorktreeInfo`, `CreateArgs`, `CreateOutcome`, `PrPreview` | +| `src/patch/` | 퍼지 패치 엔진: unified diff 파싱 → hunk 앵커링 → 섀도 렌더 → Tree-sitter 검증 → 원자적 1회 쓰기 | `apply_patch_file`, `render_patch`, `ApplyOptions`, `PatchError` | | `src/file_index.rs` | gitignore-aware 워크스페이스 파일 인덱스(`@path` 멘션용) | `ignore` walker 기반 인덱서 | | `src/history_scan.rs` | 네이티브 세션 스캐너 — 발견된 외부 세션에 bookmark row 생성 | rescan 루프 (`session.rescan` 백엔드) | | `src/mcp_inventory.rs` | 각 CLI의 네이티브 MCP 설정 인벤토리 + 연결 probe | `sources_for` | diff --git a/CHANGELOG.md b/CHANGELOG.md index f413553..b5d2c4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,71 @@ ## Unreleased +### Added — resilient fuzzy patch engine with Tree-sitter pre-validation (#31) + +- `src/patch/` applies an agent-emitted unified diff to one file through + four stages that never touch the disk until all of them pass: parse, + anchor every hunk, render a shadow file, parse the shadow file with + Tree-sitter. Only then does one atomic write happen (temp file + rename + in the same directory), so a failure at any point leaves the file + byte-identical to what it was — there is no rollback path because there + is no partial state. +- **Anchoring** survives the two drifts that make `git apply` unusable in + an agent loop. Line numbers that moved are recovered from context; a + hunk whose context differs only in comments or whitespace still applies. + Three passes run strongest-evidence-first: a byte-exact block (at the + 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. +- 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 + `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. +- **Rendering writes context 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, 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). +- **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 + 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, recorded as + `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 + 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 + file) and `validate_syntax` (true). `ApplyReport` returns per-hunk + anchors (line, exact, similarity), the syntax outcome, and warnings for + 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 + 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`). +- Known gaps, left for their own decisions: no RPC method yet (the engine + is a library seam; the daemon's backends still own file writes), no + C/Go/Java grammars, and a hunk still applies whole-or-not-at-all — fuzz + is about *where*, not *what*. + ### Added — pluggable OS sandbox, first cut: the bwrap driver (#33) - `sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"` at the diff --git a/Cargo.lock b/Cargo.lock index 1335dae..ad87384 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -600,6 +600,11 @@ dependencies = [ "tower", "tracing", "tracing-subscriber", + "tree-sitter", + "tree-sitter-javascript", + "tree-sitter-python", + "tree-sitter-rust", + "tree-sitter-typescript", "uuid", "windows-sys 0.61.2", "x25519-dalek", @@ -1742,6 +1747,18 @@ dependencies = [ "thiserror", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -2133,6 +2150,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + [[package]] name = "strsim" version = "0.11.1" @@ -2466,6 +2489,66 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "tree-sitter" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87" +dependencies = [ + "cc", + "regex", + "regex-syntax", + "serde_json", + "streaming-iterator", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-javascript" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-language" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" + +[[package]] +name = "tree-sitter-python" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-rust" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-typescript" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "try-lock" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 0bc86d6..a0dab68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,16 @@ axum-server = { version = "0.8.0", features = ["tls-rustls"] } rustls = { version = "0.23.45", features = ["ring"] } ignore = "0.4" +# Patch engine (#31): Tree-sitter grammars are the shadow-parse +# pre-validation for a patched file. Each grammar is compiled in and +# loaded lazily on the first patch of its file type, so a language a +# session never touches costs nothing at run time. +tree-sitter = "0.25" +tree-sitter-rust = "0.24" +tree-sitter-python = "0.25" +tree-sitter-javascript = "0.25" +tree-sitter-typescript = "0.23" + # Process-group signaling for tree kills on Unix (see transport.rs). [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/docs/patch-engine.ko.md b/docs/patch-engine.ko.md new file mode 100644 index 0000000..b38004b --- /dev/null +++ b/docs/patch-engine.ko.md @@ -0,0 +1,172 @@ +# 퍼지 패치 엔진 (`#31`) + +[English](patch-engine.md) | **한국어** + +`src/patch/`는 에이전트가 내보낸 unified diff를 파일 하나에 적용한다. +에이전트 루프에서 `git apply`를 쓸 수 없게 만드는 두 가지 드리프트 — +코드가 옮겨간 경우, 주석·공백만 달라진 컨텍스트 — 를 견디면서도 절반만 +적용된 파일이나 문법이 깨진 파일은 절대 남기지 않는다. + +배경 이슈: [#31](https://github.com/developjik/damon-agent-core/issues/31). + +## 4단계 + +| 단계 | 모듈 | 결정하는 것 | +|---|---|---| +| 파싱 | `src/patch/parse.rs` | 파일 하나의 hunk (여러 파일 패치는 거부) | +| 앵커링 | `src/patch/anchor.rs` | 지금 파일에서 각 hunk가 들어갈 자리 | +| 렌더링 | `src/patch/render.rs` | 섀도 파일 — 편집 밖은 바이트 그대로 | +| 검증 | `src/patch/syntax.rs` | 문법이 있으면 Tree-sitter로 섀도 파일 파싱 | +| 쓰기 | `src/patch/atomic.rs` | 임시 파일 + `rename`, 위 단계가 모두 끝난 뒤에만 | + +모든 hunk가 앵커링되고 섀도 파일이 파싱되기 전까지 디스크를 건드리지 +않으므로, 어느 단계에서 실패하든 파일은 이전과 바이트 단위로 같다. + +## 앵커링 + +증거가 강한 순서로 세 번 시도한다. + +1. **바이트 일치 블록.** hunk의 패치 전 줄들이 선언된 줄에서, 또는 검색 + 범위 안에서 한 번, 바이트 그대로 나타나면 그것이 앵커다. 정확 일치가 + 퍼지보다 우선하므로, 올바른 파일 버전을 보고 만든 패치는 줄 번호가 + 가리키는 자리에 *비슷한* 블록이 있어도 제 줄에 그대로 붙는다. +2. **줄 번호 앵커링.** 순수 삽입 hunk는 점수로 삼을 컨텍스트가 없다. + 선언된 줄이 곧 앵커다. +3. **퍼지 유사도.** hunk의 패치 전 줄들을 선언된 줄 주변 윈도(기본 + ±250줄, `search_window: None`이면 파일 전체)에 토큰 수준으로 + 정렬한다. + +퍼지 점수는 줄별 유사도를 정렬해 평균한 값이고, 각 줄은 정규화 후 +*토큰*으로 비교한다(`src/patch/score.rs`). 들여쓰기와 연속 공백은 +토큰이 되지 않고, 줄 끝 주석은 코드 토큰에 들어가지 않으며, 주석만 있는 +두 줄은 0.9로 비교된다. 반면 *코드* 토큰이 바뀌면 점수가 실제로 +떨어진다 — 패치가 엉뚱한 함수에 붙지 않게 하는 장치다. 주석 줄이 코드 +줄을 대신할 수는 없다. + +점수를 결정으로 바꾸는 규칙 두 가지: + +- **거리 페널티** — 유사도가 같으면 선언된 줄에 가까운 앵커를 고른다. + 스캔 순서가 아니라 규칙이 결과를 정하므로 재현 가능하다. +- **모호성 마진** — 최적 앵커는 겹치지 않는 차선 앵커를 + `ambiguity_margin`만큼 앞서야 한다. 근소한 차이는 추측하지 않고 + `PatchError::Ambiguous`로 실패한다. 잘못 붙은 편집의 복구 비용이 + 거부된 패치보다 훨씬 크기 때문이다. 비교는 + `best - runner_up < margin`이라 마진과 정확히 같은 차이는 구분되고, + `margin: 0.0`이면 이 규칙을 끈다. + +## 렌더링 + +섀도 파일은 세 종류의 줄로 만들어진다. + +- **유지**되는 파일 줄 — 자기 줄바꿈까지 바이트 그대로. 패치가 언급하지 + 않은 줄, hunk 범위 안에서 드리프트한 줄(누가 덧붙인 주석, 다시 포맷된 + 블록)도 포함된다. 패치가 건드리지 않은 것은 다시 쓰지 않는다. +- **삭제**되는 파일 줄 — 앵커의 정렬 결과로 제거. +- **추가**되는 패치 줄 — 파일의 줄바꿈 문자로 기록. + +그래서 다음이 성립한다. + +- 컨텍스트 줄은 패치가 아니라 **파일**에서 쓴다. 의역된 주석은 파일에 + 있는 그대로 남고, 다른 사람이 지운 주석 줄은 되살아나지 않는다. +- CRLF 파일은 패치가 LF로 와도 CRLF를 유지한다. +- 파일 끝에 개행이 없으면, 중간 편집 뒤에도, 마지막 줄을 고쳐 쓴 뒤에도 + 개행이 없는 채로 남는다(표준 + `\ No newline at end of file` 마커가 있으면 그대로 따른다). + +## 섀도 검증 + +패치 후 파일 전체를 쓰기 전에 Tree-sitter로 파싱한다(현재 `rust`, +`python`, `javascript`, `typescript`, `tsx`). `ERROR`·`MISSING` 노드는 +줄·열·종류·스니펫을 담은 `Diagnostic`이 되고, 패치는 +`PatchError::Syntax`로 실패한다. 호출자는 이 진단을 패치를 쓴 모델에게 +그대로 돌려줄 수 있다. + +문법은 크레이트에 포함되지만 해당 파일 형식의 첫 패치 때 **지연 +로드**된다. 문법이 없는 형식 — 또는 나중에 동적 로더를 붙였을 때 로드에 +실패한 문법 — 은 경고 후 적용이며 `ApplyReport::syntax`에 +`SyntaxCheck::Skipped`로 남는다. 파서가 없다고 그 언어의 패치를 멈추면 +안 된다. + +문법은 C 라이브러리다. 추가하려면 `Cargo.toml`에 한 줄, 그리고 +`syntax.rs`의 `Language::for_path`/`grammar`에 매치 갈래 하나면 된다. + +## 쓰기 + +`atomic::replace`는 대상 옆에 임시 파일을 만들고 권한 비트를 복사한 뒤 +`fsync`하고 대상 위로 `rename`한다(유닉스에서는 디렉터리 sync도 +best-effort). 같은 파일시스템 안에서 rename은 원자적이라, 읽는 쪽은 +옛 바이트나 새 바이트를 볼 뿐 섞인 상태를 보지 않는다. +`apply_patch_file`은 먼저 canonicalize하므로 심볼릭 링크를 거친 패치는 +링크를 일반 파일로 바꾸지 않고 대상 파일을 고친다. + +렌더 결과가 원본과 같으면(무변경 패치) 아무것도 쓰지 않는다. + +## API + +```rust +use damon_core::patch::{apply_patch_file, render_patch, ApplyOptions}; + +// 파일에 적용 — 원자적 쓰기, 섀도 검증 포함. +let report = apply_patch_file(Path::new("src/lib.rs"), patch_text, &ApplyOptions::default())?; + +// 또는 메모리에서만 렌더 (IO 없음). 경로는 문법 선택에만 쓰인다. +let rendered = render_patch(Path::new("src/lib.rs"), &original, patch_text, &ApplyOptions::default())?; +``` + +`ApplyOptions` 기본값: + +| 필드 | 기본값 | 의미 | +|---|---|---| +| `similarity_threshold` | `0.60` | 앵커가 될 수 있는 최저 유사도 | +| `ambiguity_margin` | `0.05` | 차선 앵커와의 최소 격차 | +| `search_window` | `Some(250)` | 선언된 줄 좌우로 탐색할 줄 수, `None`이면 파일 전체 | +| `validate_syntax` | `true` | 섀도 파일을 Tree-sitter로 파싱 | + +`ApplyReport`는 hunk별 `HunkReport`(줄, 정확 일치 여부, 유사도)와 +`syntax` 결과, 그리고 `warnings`(헤더 줄 수 불일치, 퍼지로 옮겨간 앵커, +문법 없음)를 담는다. + +## 오류 + +`PatchError`의 모든 변형은 디스크의 파일이 바뀌지 않았음을 뜻한다. + +| 변형 | 발생 조건 | +|---|---| +| `Parse` | 파일 하나의 unified diff가 아님(hunk 없음, 헤더 깨짐, 본문 쓰레기 줄, 두 번째 파일) | +| `NotAnchored` | 임계값을 넘는 후보 없음(최고 점수·줄·거리 보고) | +| `Ambiguous` | 최적 두 앵커가 마진 이내 | +| `OutOfOrder` | hunk가 파일 순서가 아님 | +| `Syntax` | 섀도 파일 파싱 실패(`diagnostics()`로 진단 반환) | +| `NotText` | UTF-8이 아님 | +| `Io` | 읽기·쓰기 실패 | + +## 테스트 + +- `src/patch/*` 단위 테스트: 토크나이저·유사도(주석 의역, 주석 꼬리, + 어트리뷰트와 주석 구분, 문자열, 한글 텍스트), 파서 경계(CRLF, 공백 + 없는 빈 컨텍스트 줄, EOF 마커, 여러 파일), 앵커링(정확 일치, 옮겨간 + 블록, 삽입, 둘 중 가까운 쪽, 등거리 모호성, 마진 경계, 순서 위반), + 마지막 줄 개행 규칙, 원자적 쓰기(임시 파일 잔여 없음, 권한 유지). +- `tests/patch_engine.rs`(실제 파일, 끝-끝): 줄 번호 드리프트, 주석 + 의역, 파일에서 지워진 주석 줄, 코드 변경은 거부, hunk 하나 실패 시 + 원자성, 문법 오류 거부, CRLF, 끝 개행 없음, 마커, 삽입, 다중 hunk, + 순서 위반, 모호성, `render_patch`는 쓰지 않음, 두 번 적용 거부, + 심볼릭 링크, 여러 파일 패치, 비 UTF-8, Python 검증. + +```bash +cargo test --lib patch +cargo test --test patch_engine +``` + +## 의도적으로 넣지 않은 것 + +- **RPC 메서드 없음.** 이 엔진은 라이브러리 이음새다. 오늘 파일 쓰기는 + 데몬의 백엔드가 쥐고 있고, 같은 규칙을 두 곳에 두는 것보다 한 곳에 + 두는 편이 낫다. RPC 표면은 프로토콜·클라이언트 작업이 따르는 별도 + 결정이다. +- **롤백 없음.** 되돌릴 것이 없다. 모든 실패는 쓰기 전에 일어나고, + 쓰기는 rename 한 번이다. +- **hunk 부분 적용 없음.** hunk는 전부 적용되거나 전부 적용되지 않는다. + 퍼지는 *어디에* 붙일지의 문제이지 *무엇을* 적용할지의 문제가 아니다. +- **C/Go/Java 문법은 아직 없음.** 지원하지 않는 형식도 경고 로그와 함께 + 패치된다. diff --git a/docs/patch-engine.md b/docs/patch-engine.md new file mode 100644 index 0000000..723a519 --- /dev/null +++ b/docs/patch-engine.md @@ -0,0 +1,183 @@ +# Fuzzy patch engine (`#31`) + +**English** | [한국어](patch-engine.ko.md) + +`src/patch/` applies an agent-emitted unified diff to one file, tolerating +the two drifts that make `git apply` useless in an agent loop — moved +code and trivia-only context changes — while never leaving a half-applied +or syntactically broken file behind. + +The issue that asked for it: [#31](https://github.com/developjik/damon-agent-core/issues/31). + +## The four stages + +| stage | module | what it decides | +|---|---|---| +| parse | `src/patch/parse.rs` | one file's hunks (multi-file patches are refused) | +| anchor | `src/patch/anchor.rs` | where each hunk belongs in the file as it is now | +| render | `src/patch/render.rs` | the shadow file, byte-preserving outside the edit | +| validate | `src/patch/syntax.rs` | Tree-sitter parse of the shadow file, if a grammar is known | +| write | `src/patch/atomic.rs` | one temp file + `rename`, only after all of the above | + +No stage touches the disk until every hunk has anchored and the shadow +file has parsed, so a failure at any point leaves the file +byte-identical to what it was. + +## Anchoring + +Three passes, strongest evidence first: + +1. **Byte-exact block.** If the hunk's pre-patch lines appear + byte-for-byte — at the declared line, or once within the search window + — that is the anchor. Exact beats fuzzy, so a patch written against the + right file version still lands on its numbered line even when a + *similar* block sits nearer to where the numbers now point. +2. **Line-number anchoring.** A pure insertion has no context to score; + its declared line is its anchor. +3. **Fuzzy similarity.** A token-level alignment of the hunk's pre-patch + lines against a window around the declared line (default ±250 lines, + `search_window: None` for the whole file). + +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. + +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. +- **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 + more than a rejected one. The comparison is `best - runner_up < margin`, + so a gap exactly equal to the margin is still distinguishable and + `margin: 0.0` switches the rule off. + +## Rendering + +The shadow file is built from three kinds of line: + +- **kept** file lines, byte-for-byte with their own ending — including + lines the patch never mentioned and lines that drifted inside a hunk's + span (an extra comment, a re-formatted block). Nothing the patch did not + address is rewritten; +- **removed** file lines, dropped through the anchor's alignment; +- **added** patch lines, written with the file's own line ending. + +Consequences worth knowing: + +- Context lines are written 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. +- 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). + +## Shadow validation + +The whole post-patch file is parsed with Tree-sitter before writing +(`rust`, `python`, `javascript`, `typescript`, `tsx` today). `ERROR` and +`MISSING` nodes become `Diagnostic`s — line, column, kind, snippet — and +the patch fails with `PatchError::Syntax`, so a caller can hand the +diagnostics straight back to the model that wrote the patch. + +Grammars are compiled in but **loaded lazily**, on the first patch of a +given file type. A file type with no grammar — or, in a future dynamic +loader, a grammar that fails to load — is a warning and an apply, recorded +in `ApplyReport::syntax` as `SyntaxCheck::Skipped`: the engine must never +stop patching a language it happens to lack a parser for. + +A grammar is a C library; adding one is a `Cargo.toml` line plus a match +arm in `syntax.rs::Language::for_path` / `grammar`. + +## Writing + +`atomic::replace` writes a sibling temp file, copies the target's +permission bits, `fsync`s it, and `rename`s it over the target (plus a +best-effort directory sync on Unix). A rename is atomic within a +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. + +If the rendered text equals the original (a no-op patch), nothing is +written at all. + +## API + +```rust +use damon_core::patch::{apply_patch_file, render_patch, ApplyOptions}; + +// Apply to a file — atomic write, shadow validated. +let report = apply_patch_file(Path::new("src/lib.rs"), patch_text, &ApplyOptions::default())?; + +// Or render in memory only (no IO); the path is used just for the grammar. +let rendered = render_patch(Path::new("src/lib.rs"), &original, patch_text, &ApplyOptions::default())?; +``` + +`ApplyOptions`: + +| field | default | meaning | +|---|---|---| +| `similarity_threshold` | `0.60` | lowest hunk-to-file similarity that may anchor | +| `ambiguity_margin` | `0.05` | minimum gap to the runner-up anchor | +| `search_window` | `Some(250)` | lines searched each side of the declared line; `None` = whole file | +| `validate_syntax` | `true` | parse the shadow file with Tree-sitter | + +`ApplyReport` carries one `HunkReport` per hunk (line, exact, similarity), +the `syntax` outcome, and `warnings` (miscounted hunk header, a fuzzy +anchor that moved, a missing grammar). + +## Error surface + +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) | +| `NotAnchored` | no candidate reached the threshold (reports best score, line, distance) | +| `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) | +| `NotText` | the file is not UTF-8 | +| `Io` | read or write failed | + +## Tests + +- `src/patch/*` unit tests: tokenizer and similarity (comment paraphrase, + comment tail, attribute vs comment, strings, Korean text), parser edge + cases (CRLF, bare empty context line, EOF marker, multi-file), anchoring + (exact, moved block, insertion, nearest-of-two, equidistant ambiguity, + margin boundary, out-of-order), the final-line ending rules, atomic + write (no temp left, permissions kept). +- `tests/patch_engine.rs` (end to end, real files): drifted line numbers, + paraphrased comment, deleted comment line, rewritten code line refused, + one-bad-hunk atomicity, syntax rejection, CRLF, missing trailing + newline, marker, insertion, multi-hunk, out-of-order, ambiguity, + `render_patch` writes nothing, double-apply refused, symlink, + multi-file patch, non-UTF-8 file, Python checked too. + +Run them with: + +```bash +cargo test --lib patch +cargo test --test patch_engine +``` + +## Deliberately left out + +- **No RPC method.** The engine is a library seam; the daemon's backends + own file writes today, and one implementation of the rule beat a second + copy on the wire. An RPC surface is a separate decision with its own + protocol and client work. +- **No rollback.** There is nothing to roll back: every failure happens + before the write, and the write is a rename. +- **No partial-hunk application.** A hunk is applied whole or not at all; + fuzz is about *where*, not *what*. +- **No C/Go/Java grammars yet.** Unsupported types still patch, with a + logged warning. diff --git a/src/lib.rs b/src/lib.rs index 316523c..8509bd2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,6 +14,7 @@ pub mod logs; pub mod mcp_inventory; pub mod memory; pub mod mission; +pub mod patch; pub mod prompts; pub mod ratelimit; pub mod relay; diff --git a/src/patch/anchor.rs b/src/patch/anchor.rs new file mode 100644 index 0000000..a122d5d --- /dev/null +++ b/src/patch/anchor.rs @@ -0,0 +1,564 @@ +//! Hunk anchoring: deciding where in the *current* file each hunk +//! actually belongs. +//! +//! Three passes, strongest evidence first: +//! +//! 1. **Exact block match** — the hunk's pre-patch lines appear +//! byte-for-byte, at the declared line or, failing that, once under +//! the same search bounds. A byte-identical block outranks any +//! similarity score, so a patch written against the right file +//! version still lands on its numbered line even when a *similar* +//! block sits nearer to where the numbers now point. +//! 2. **Line-number anchoring** — a pure insertion has no context to +//! score, so its declared line *is* its anchor. +//! 3. **Fuzzy similarity** — a token-level alignment of the hunk's +//! pre-patch lines against a window around the declared line. +//! +//! Fuzzy ranking applies a small **distance penalty**: equal-scoring +//! anchors resolve to the one nearest the declared line, which makes the +//! outcome reproducible instead of dependent on scan order. And a single +//! threshold is not enough to prevent a wrong-but-plausible anchor, so +//! the best anchor must also beat the runner-up by `ambiguity_margin`. +//! When two anchors are too close to call, the patch fails as +//! [`PatchError::Ambiguous`] instead of guessing: a misplaced edit costs +//! far more than a rejected one. +//! +//! Anchors are computed for *every* hunk before anything is rendered, and +//! each one is constrained to start after the previous hunk ended. The +//! engine therefore never discovers a failure halfway through a file. + +use std::collections::BTreeMap; + +use super::ApplyOptions; +use super::PatchError; +use super::parse::Hunk; +use super::score::{self, LineTokens}; + +/// Cost of one skipped line in the alignment. Small enough that a +/// handful of inserted lines does not sink an otherwise perfect hunk; +/// large enough that skipping the whole hunk body does not score. +const GAP_PENALTY: f64 = 0.30; + +/// Reward for a line that is too different to count as a match. Negative +/// so an alignment prefers skipping a changed line to pairing with it. +const MISMATCH_PENALTY: f64 = -0.50; + +/// At or above this line similarity, an aligned pair counts as evidence. +const MATCH_FLOOR: f64 = 0.50; + +/// How much of the score one line of distance from the declared position +/// can cost, and the cap. The penalty only breaks ties between +/// equal-similarity anchors; it never overrides a real similarity gap. +const DISTANCE_PENALTY_PER_LINE: f64 = 0.0005; +const MAX_DISTANCE_PENALTY: f64 = 0.05; + +/// Float slack for "these two scores are the same". +const TIE_EPSILON: f64 = 1e-9; + +/// Where one hunk landed. +#[derive(Debug, Clone)] +pub(crate) struct Anchor { + /// 0-based first pre-patch line the hunk covers. + pub start: usize, + /// 0-based one past the last pre-patch line the hunk covers. + pub end: usize, + /// `(hunk old index, file line index)` pairs the alignment found, in + /// order. Context lines are written back from the file through these; + /// removals are dropped through these. + pub pairs: Vec<(usize, usize)>, + /// The block matched byte-for-byte (or the hunk is a pure insertion + /// at its declared line). + pub exact: bool, + /// Hunk-to-file similarity the anchor was chosen on. + pub similarity: f64, +} + +/// Anchor every hunk, in file order, or fail the whole patch. +pub(crate) fn anchor_all( + original: &[&str], + hunks: &[Hunk], + opts: &ApplyOptions, +) -> Result, PatchError> { + let tokens: Vec = original.iter().map(|l| score::tokenize(l)).collect(); + let total = hunks.len(); + let mut anchors: Vec = Vec::with_capacity(total); + // Every hunk must land after the previous one ended: a patch's hunks + // in file order are a promise about the result, and honoring it is + // what keeps two hunks from editing the same lines twice. + let mut floor = 0usize; + let mut previous_start = 0usize; + + for (index, hunk) in hunks.iter().enumerate() { + let old: Vec<&str> = hunk.old_lines().collect(); + let nominal = if old.is_empty() { + hunk.old_start.min(original.len()) + } else { + hunk.old_start.saturating_sub(1) + }; + if index > 0 && nominal < previous_start { + return Err(PatchError::OutOfOrder { + hunk: index + 1, + total, + line: nominal + 1, + previous_hunk: index, + previous: previous_start + 1, + }); + } + previous_start = nominal; + let anchor = anchor_one(index, total, &old, original, &tokens, nominal, floor, opts)?; + floor = anchor.end.max(floor); + anchors.push(anchor); + } + Ok(anchors) +} + +#[allow(clippy::too_many_arguments)] +fn anchor_one( + index: usize, + total: usize, + old: &[&str], + original: &[&str], + tokens: &[LineTokens], + nominal: usize, + floor: usize, + opts: &ApplyOptions, +) -> Result { + // A pure insertion has nothing to recognize: its declared line is the + // anchor, clamped into the file. + if old.is_empty() { + let at = nominal.min(original.len()).max(floor); + return Ok(Anchor { + start: at, + end: at, + pairs: Vec::new(), + exact: true, + similarity: 1.0, + }); + } + + let (lo, hi) = search_bounds( + nominal, + old.len(), + original.len(), + floor, + opts.search_window, + ); + + // Pass 1: byte-exact block. + let mut exact_matches: Vec = Vec::new(); + for start in lo..=hi { + if start + old.len() <= original.len() + && original[start..start + old.len()] + .iter() + .zip(old) + .all(|(a, b)| a == b) + { + exact_matches.push(start); + } + } + if !exact_matches.is_empty() { + let chosen = choose_exact(&exact_matches, nominal, index, total, opts)?; + return Ok(Anchor { + start: chosen, + end: chosen + old.len(), + pairs: (0..old.len()).map(|i| (i, chosen + i)).collect(), + exact: true, + similarity: 1.0, + }); + } + + // Pass 2: fuzzy alignment over a window around the declared line. + let old_tokens: Vec = old.iter().map(|l| score::tokenize(l)).collect(); + let slack = (old.len() / 4).clamp(4, 32); + let mut by_start: BTreeMap = 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; + }; + if pairs.is_empty() { + continue; + } + // `align` reports window-relative indices; the rest of the engine + // speaks file lines. + for pair in &mut pairs { + pair.1 += start; + } + let first = pairs.first().map(|p| p.1).unwrap_or(start); + let last = pairs.last().map(|p| p.1 + 1).unwrap_or(start); + let candidate = Candidate { + start: first, + end: last, + similarity, + pairs, + }; + match by_start.get(&first) { + Some(existing) if existing.similarity >= similarity => {} + _ => { + by_start.insert(first, candidate); + } + } + } + let mut candidates: Vec = by_start.into_values().collect(); + rank(&mut candidates, nominal); + + let Some(best) = candidates.first() else { + return Err(PatchError::NotAnchored { + hunk: index + 1, + total, + best: 0.0, + line: nominal.min(original.len()) + 1, + distance: 0, + nominal: nominal + 1, + threshold: opts.similarity_threshold, + }); + }; + if best.similarity < opts.similarity_threshold { + return Err(PatchError::NotAnchored { + hunk: index + 1, + total, + best: best.similarity, + line: best.start + 1, + distance: best.start.abs_diff(nominal), + nominal: nominal + 1, + threshold: opts.similarity_threshold, + }); + } + + // The runner-up only counts if it is a *different* edit: two alignments + // that overlap describe the same lines and are not a choice. + if let Some(runner) = candidates + .iter() + .skip(1) + .find(|c| c.end <= best.start || c.start >= best.end) + { + 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) + { + return Err(PatchError::Ambiguous { + hunk: index + 1, + total, + best: best.similarity, + best_line: best.start + 1, + runner_up: runner.similarity, + runner_line: runner.start + 1, + margin: opts.ambiguity_margin, + }); + } + } + + Ok(Anchor { + start: best.start, + end: best.end, + pairs: best.pairs.clone(), + exact: false, + similarity: best.similarity, + }) +} + +#[derive(Debug, Clone)] +struct Candidate { + start: usize, + end: usize, + similarity: f64, + pairs: Vec<(usize, usize)>, +} + +/// Order candidates best-first: similarity, then the distance penalty +/// (nearer the declared line wins an equal-similarity tie), then file +/// order so the result never depends on map iteration order. +fn rank(candidates: &mut [Candidate], nominal: usize) { + candidates.sort_by(|a, b| { + let a_rank = a.similarity - distance_penalty(a.start.abs_diff(nominal)); + let b_rank = b.similarity - distance_penalty(b.start.abs_diff(nominal)); + b_rank + .total_cmp(&a_rank) + .then(a.start.abs_diff(nominal).cmp(&b.start.abs_diff(nominal))) + .then(a.start.cmp(&b.start)) + }); +} + +fn distance_penalty(lines: usize) -> f64 { + (lines as f64 * DISTANCE_PENALTY_PER_LINE).min(MAX_DISTANCE_PENALTY) +} + +/// The margin rule: a runner-up within `margin` of the best anchor makes +/// the patch ambiguous. Exactly the configured gap is still distinguishable; +/// a configured `0.0` switches the rule off, which is how a caller opts +/// into "take the best score even when it is a coin flip". Kept as its own +/// function so the boundary can be pinned by a unit test instead of only +/// showing up as a hand-built file that happens to score a certain way. +fn within_margin(best: f64, runner_up: f64, margin: f64) -> bool { + best - runner_up < margin +} + +/// The inclusive range of candidate start lines to test. +fn search_bounds( + nominal: usize, + len: usize, + file_len: usize, + floor: usize, + window: Option, +) -> (usize, usize) { + let last_start = file_len.saturating_sub(len); + let hi = match window { + Some(w) => (nominal + w).min(last_start), + None => last_start, + }; + let lo = match window { + Some(w) => nominal.saturating_sub(w), + None => 0, + } + .max(floor) + .min(hi); + (lo, hi.max(lo)) +} + +/// Pick between several byte-exact matches: the declared line if it is +/// one of them, else the single nearest, else refuse. +fn choose_exact( + matches: &[usize], + nominal: usize, + index: usize, + total: usize, + opts: &ApplyOptions, +) -> Result { + if matches.contains(&nominal) { + return Ok(nominal); + } + let nearest = matches + .iter() + .map(|m| m.abs_diff(nominal)) + .min() + .unwrap_or(0); + 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, + }); + } + Ok(first) +} + +/// Align the *whole* hunk against a window: every pre-patch line is +/// paired or skipped (at [`GAP_PENALTY`]), and leading window lines count +/// as skips, so a window that opens before the block is not free. +/// +/// Aligning the whole hunk rather than the best local fragment is what +/// makes alternates visible: a window near one candidate block scores +/// that block best, so a second, similar block elsewhere turns into a +/// separate candidate instead of being reported as the same answer. That +/// distinction is what the ambiguity margin is checking. +/// +/// Returns the similarity and the matched `(old line index, window line +/// index)` pairs; the caller offsets the window indices into file lines. +fn align(old: &[LineTokens], window: &[LineTokens]) -> Option<(f64, Vec<(usize, usize)>)> { + let n = old.len(); + let m = window.len(); + if n == 0 || m == 0 { + return None; + } + let width = m + 1; + let mut table = vec![0f64; (n + 1) * width]; + // 0 = nothing, 1 = pair, 2 = skip an old line, 3 = skip a file line. + let mut from = vec![0u8; (n + 1) * width]; + + for (j, cell) in table.iter_mut().enumerate().take(m + 1) { + *cell = -(j as f64) * GAP_PENALTY; + } + for i in 1..=n { + table[i * width] = -(i as f64) * GAP_PENALTY; + for j in 1..=m { + let sim = score::similarity(&old[i - 1], &window[j - 1]); + let pair = table[(i - 1) * width + (j - 1)] + + if sim >= MATCH_FLOOR { + sim + } else { + MISMATCH_PENALTY + }; + let skip_old = table[(i - 1) * width + j] - GAP_PENALTY; + let skip_file = table[i * width + (j - 1)] - GAP_PENALTY; + 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; + } + } + + // The hunk may end anywhere in the window: trailing window lines are + // not part of it. + let mut best = f64::NEG_INFINITY; + let mut end_column = 0usize; + for j in 0..=m { + let value = table[n * width + j]; + if value > best { + best = value; + end_column = j; + } + } + + let mut pairs: Vec<(usize, usize)> = Vec::new(); + let (mut i, mut j) = (n, end_column); + while i > 0 || j > 0 { + let dir = if i == 0 { + 3 + } else if j == 0 { + 2 + } else { + from[i * width + j] + }; + match dir { + 1 => { + pairs.push((i - 1, j - 1)); + i -= 1; + j -= 1; + } + 2 => i -= 1, + 3 => j -= 1, + _ => break, + } + } + pairs.reverse(); + if pairs.is_empty() { + return None; + } + Some((best / n as f64, pairs)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::parse::parse; + + fn anchor(original: &str, patch: &str) -> Result, PatchError> { + let lines: Vec<&str> = original.split('\n').collect(); + let hunks = parse(patch).unwrap(); + anchor_all(&lines, &hunks, &ApplyOptions::default()) + } + + #[test] + fn exact_block_at_the_declared_line_is_used_as_is() { + let original = "one\ntwo\nthree\n"; + let patch = "@@ -2,1 +2,1 @@\n-two\n+TWO\n"; + let anchors = anchor(original, patch).unwrap(); + assert_eq!((anchors[0].start, anchors[0].end), (1, 2)); + assert!(anchors[0].exact); + } + + #[test] + fn a_moved_block_is_found_by_exact_match() { + let original = "new top\nnew top 2\nfn moved() {\n body();\n}\n"; + let patch = "@@ -9,2 +9,2 @@\n fn moved() {\n- body();\n+ other();\n"; + let anchors = anchor(original, patch).unwrap(); + assert!(anchors[0].exact); + assert_eq!(anchors[0].start, 2); + } + + #[test] + fn a_pure_insertion_anchors_on_its_declared_line() { + let original = "a\nb\nc\n"; + let patch = "@@ -2,0 +3,1 @@\n+inserted\n"; + let anchors = anchor(original, patch).unwrap(); + assert_eq!(anchors[0].start, 2); + } + + #[test] + fn equal_similarity_resolves_to_the_nearer_block() { + // The same block twice. The hunk's removal line differs slightly, so + // neither copy is byte-exact and the two alignments score the same; + // the copy beside the declared line must win, every run. + let original = "fn b() {\n one();\n}\n\nfn a() {\n one();\n}\n"; + let patch = "@@ -5,2 +5,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + let anchors = anchor(original, patch).unwrap(); + assert!(!anchors[0].exact); + assert_eq!(anchors[0].start, 4); + } + + #[test] + fn two_equidistant_blocks_with_equal_scores_are_ambiguous() { + // Blocks at 0-1 and 4-5, declared line exactly between them. + let original = "fn a() {\n one();\n\n\nfn a() {\n one();\n}\n"; + let patch = "@@ -3,2 +3,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + let err = anchor(original, patch).unwrap_err(); + assert!(matches!(err, PatchError::Ambiguous { .. }), "{err}"); + } + + #[test] + fn out_of_order_hunks_are_rejected() { + let original = "a\nb\nc\nd\n"; + let patch = "@@ -4,1 +4,1 @@\n-d\n+D\n@@ -2,1 +2,1 @@\n-b\n+B\n"; + let err = anchor(original, patch).unwrap_err(); + assert!(matches!(err, PatchError::OutOfOrder { .. }), "{err}"); + } + + #[test] + fn the_ambiguity_margin_boundary() { + // A gap exactly equal to the configured margin is enough. + assert!(!within_margin(0.90, 0.85, 0.05)); + // A hair less is not. + assert!(within_margin(0.90, 0.850_001, 0.05)); + // Identical scores are always inside the margin. + assert!(within_margin(0.90, 0.90, 0.05)); + // Margin 0.0 switches the rule off (callers can opt into best-score-wins). + assert!(!within_margin(0.90, 0.85, 0.0)); + } + + #[test] + fn a_zero_margin_turns_the_ambiguity_refusal_off() { + // Same equidistant pair as above: margin 0 means "always take the best". + let original = "fn a() {\n one();\n\n\nfn a() {\n one();\n}\n"; + let patch = "@@ -3,2 +3,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + let lines: Vec<&str> = original.split('\n').collect(); + let hunks = parse(patch).unwrap(); + let opts = ApplyOptions { + ambiguity_margin: 0.0, + ..ApplyOptions::default() + }; + assert!(anchor_all(&lines, &hunks, &opts).is_ok()); + } + + #[test] + fn a_wider_margin_makes_a_close_call_ambiguous() { + // Two near-identical blocks whose scores differ by ~0.10. The default + // margin (0.05) can tell them apart; a wider one refuses to choose. + let original = "fn b() {\n one();\n}\n\nfn a() {\n one();\n}\n"; + let patch = "@@ -5,2 +5,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + let lines: Vec<&str> = original.split('\n').collect(); + let hunks = parse(patch).unwrap(); + let anchors = anchor_all(&lines, &hunks, &ApplyOptions::default()).unwrap(); + assert_eq!(anchors[0].start, 4); + + let wide = ApplyOptions { + ambiguity_margin: 0.2, + ..ApplyOptions::default() + }; + let err = anchor_all(&lines, &hunks, &wide).unwrap_err(); + assert!(matches!(err, PatchError::Ambiguous { .. }), "{err}"); + } + + #[test] + fn search_bounds_stay_inside_the_file() { + assert_eq!(search_bounds(0, 3, 10, 0, Some(5)), (0, 5)); + assert_eq!(search_bounds(9, 3, 10, 0, Some(5)), (4, 7)); + assert_eq!(search_bounds(2, 3, 10, 5, Some(5)), (5, 7)); + assert_eq!(search_bounds(2, 3, 10, 0, None), (0, 7)); + } +} diff --git a/src/patch/atomic.rs b/src/patch/atomic.rs new file mode 100644 index 0000000..701d2ba --- /dev/null +++ b/src/patch/atomic.rs @@ -0,0 +1,128 @@ +//! The one write a patch is allowed to make. +//! +//! Rollback is not the goal — never entering a half-applied state is. +//! By the time this runs, every hunk has anchored and the shadow file +//! has parsed, so the only remaining failure mode is the write itself. +//! Writing a sibling temp file and renaming it over the target keeps +//! that failure mode to "the original is untouched": a rename is atomic +//! within a filesystem, so a reader sees the old bytes or the new bytes, +//! never a mixture, and a crash mid-write leaves the original intact +//! (the orphaned temp file is cleaned up best-effort). +//! +//! The target's permission bits and symlink resolution are preserved: +//! the temp file inherits the original's mode, and the rename happens at +//! the real path, so patching through a symlink updates its target +//! instead of replacing the link with a regular file. + +use std::io::{self, Write}; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Atomically replace `path` with `contents`. +pub(crate) fn replace(path: &Path, contents: &[u8]) -> io::Result<()> { + let directory = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "patch".to_string()); + 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)?; + if let Some(metadata) = &metadata { + // Keep exec bits and group/other access. File::create would + // otherwise hand the file the default 0666 & !umask. + let _ = file.set_permissions(metadata.permissions()); + } + file.write_all(contents)?; + file.sync_all()?; + drop(file); + std::fs::rename(&temp, path) + })(); + + if result.is_err() { + let _ = std::fs::remove_file(&temp); + return result; + } + + // Make the rename itself durable on Unix. Best effort: the data is + // already on disk and the rename has landed; a directory that cannot + // be opened for a sync (or a platform without the notion) is not a + // reason to report a failed patch. + #[cfg(unix)] + { + if let Ok(directory) = std::fs::File::open(directory) { + let _ = directory.sync_all(); + } + } + Ok(()) +} + +/// Unique enough for concurrent writers in one directory: process id plus +/// a counter that never repeats within the process. +fn unique_suffix() -> String { + static COUNTER: AtomicU64 = AtomicU64::new(0); + format!( + "{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "damon-patch-atomic-{tag}-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn replaces_the_file_and_leaves_no_temp_behind() { + let dir = temp_dir("replace"); + let path = dir.join("file.txt"); + std::fs::write(&path, "old").unwrap(); + replace(&path, b"new").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "new"); + let leftovers: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .filter_map(Result::ok) + .filter(|e| e.file_name().to_string_lossy().contains("damon-patch")) + .collect(); + assert!(leftovers.is_empty(), "left {leftovers:?}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn keeps_the_original_permission_bits() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("mode"); + let path = dir.join("script.sh"); + std::fs::write(&path, "old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o750)).unwrap(); + replace(&path, b"new").unwrap(); + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o750); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_missing_parent_fails_without_creating_anything() { + let dir = temp_dir("missing"); + let path = dir.join("nope").join("file.txt"); + assert!(replace(&path, b"new").is_err()); + assert!(!path.exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src/patch/mod.rs b/src/patch/mod.rs new file mode 100644 index 0000000..0599dfb --- /dev/null +++ b/src/patch/mod.rs @@ -0,0 +1,474 @@ +//! Resilient patch application — the engine `#31` asks for. +//! +//! A coding agent edits by emitting a patch, and patches fail 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 and now the context does not match. `git apply` and +//! naive string replacement both call that a hard failure, the model +//! burns turns retrying, and when a patch *does* land but leaves broken +//! code on disk, everything downstream inherits it. +//! +//! This engine applies a patch in four stages, and no stage touches the +//! disk until all of them have passed: +//! +//! 1. **Parse** ([`parse`]) one file's unified diff into hunks. +//! 2. **Anchor every hunk** ([`anchor`]) against the file as it is now: +//! byte-exact blocks first, then token-level similarity around the +//! declared line, with a distance tie-break and an ambiguity margin +//! that refuses near-ties instead of guessing. +//! 3. **Render** the result in a shadow buffer ([`render`]), writing +//! context lines from the *file* so comment wording and indentation +//! the patch never intended to change survive, and the file's line +//! endings (CRLF, missing final newline) survive too. +//! 4. **Validate** the shadow file with Tree-sitter ([`syntax`]) when a +//! grammar is known; syntax errors come back as diagnostics and +//! nothing is written. +//! +//! Only then does [`atomic`] write: one temp file beside the target and +//! a rename over it. There is no rollback path because there is no +//! partial state to roll back — a failure at any stage leaves the file +//! byte-identical to what it was. +//! +//! ```no_run +//! use damon_core::patch::{apply_patch_file, ApplyOptions}; +//! use std::path::Path; +//! +//! # fn demo() -> Result<(), damon_core::patch::PatchError> { +//! let report = apply_patch_file( +//! Path::new("src/lib.rs"), +//! "@@ -2,1 +2,1 @@\n-let a = 1;\n+let a = 2;\n", +//! &ApplyOptions::default(), +//! )?; +//! # std::fs::remove_file("src/lib.rs").ok(); +//! println!("{} hunk(s)", report.hunks.len()); +//! # Ok(()) +//! # } +//! ``` +//! +//! The engine is deliberately a library seam, not an RPC method: the +//! daemon's backends own the file writes today, and giving a caller the +//! same function keeps one implementation of the rule instead of two. + +mod anchor; +mod atomic; +mod parse; +mod render; +mod score; +mod syntax; + +use std::path::{Path, PathBuf}; + +pub use parse::ParseError; +pub use syntax::Diagnostic; + +/// Tuning for one patch. +#[derive(Debug, Clone)] +pub struct ApplyOptions { + /// Lowest hunk-to-file similarity that may anchor. The default (0.60) + /// still accepts a hunk whose context has one rewritten line in + /// three, and rejects a hunk that mostly does not exist in the file. + pub similarity_threshold: f64, + /// How far the best anchor must beat the next *non-overlapping* + /// anchor. Near-ties fail as ambiguous rather than guessing: a patch + /// applied to the wrong place is far more expensive than one + /// rejected. + pub ambiguity_margin: f64, + /// Lines of search on each side of the declared line. `None` scans + /// the whole file. + pub search_window: Option, + /// Parse the shadow file with Tree-sitter before writing. + pub validate_syntax: bool, +} + +impl Default for ApplyOptions { + fn default() -> Self { + Self { + similarity_threshold: 0.60, + ambiguity_margin: 0.05, + search_window: Some(250), + validate_syntax: true, + } + } +} + +/// What happened to the shadow file's Tree-sitter check. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SyntaxCheck { + /// Parsed cleanly with the named grammar. + Clean(&'static str), + /// No grammar for this file type, or the grammar failed to load; the + /// patch was applied and the reason is recorded here and in the log. + Skipped(String), + /// `validate_syntax = false`. + Disabled, +} + +/// Where one hunk landed. +#[derive(Debug, Clone, PartialEq)] +pub struct HunkReport { + /// 1-based hunk number within the patch. + pub index: usize, + /// 1-based file line the hunk anchored on. + pub line: usize, + /// The block matched byte-for-byte, or the hunk is a pure insertion + /// at its declared line. + pub exact: bool, + /// Hunk-to-file similarity the anchor was chosen on (`1.0` for an + /// exact match). + pub similarity: f64, +} + +/// The result of an applied (or rendered) patch. +#[derive(Debug, Clone, PartialEq)] +pub struct ApplyReport { + pub hunks: Vec, + pub syntax: SyntaxCheck, + /// Things the caller should know but that did not stop the patch: + /// a miscounted hunk header, a fuzzy anchor that moved a long way, a + /// missing grammar. + pub warnings: Vec, +} + +/// A patched file rendered in memory, not yet written. +#[derive(Debug, Clone, PartialEq)] +pub struct Rendered { + pub text: String, + pub report: ApplyReport, +} + +/// Why a patch was not applied. In every case the file on disk is +/// unchanged. +#[derive(Debug, thiserror::Error)] +pub enum PatchError { + /// The patch text is not one file's unified diff. + #[error("{0}")] + Parse(#[from] ParseError), + /// No candidate anchor reached the similarity threshold. + #[error( + "hunk {hunk}/{total}: no anchor reached similarity {threshold:.2} (best {best:.2} at line {line}, {distance} line(s) from the declared line {nominal})" + )] + NotAnchored { + hunk: usize, + total: usize, + best: f64, + line: usize, + distance: usize, + nominal: usize, + threshold: f64, + }, + /// Two non-overlapping anchors scored within the margin. + #[error( + "hunk {hunk}/{total}: ambiguous — {best:.2} at line {best_line} vs {runner_up:.2} at line {runner_line} (margin {margin:.2}); narrow it with more context instead of guessing" + )] + Ambiguous { + hunk: usize, + total: usize, + best: f64, + best_line: usize, + runner_up: f64, + runner_line: usize, + margin: f64, + }, + /// A hunk's declared position is earlier than the hunk before it. + #[error( + "hunk {hunk}/{total} targets line {line}, before hunk {previous_hunk} at line {previous}; hunks must be in file order" + )] + OutOfOrder { + hunk: usize, + total: usize, + line: usize, + previous_hunk: usize, + previous: usize, + }, + /// The file is not UTF-8 text. + #[error("{path}: not UTF-8 text — this engine patches text files only")] + NotText { path: PathBuf }, + /// The shadow file did not parse; the diagnostics are the model's next input. + #[error( + "shadow file failed {language} parse: {first} ({count} diagnostic(s)); nothing was written" + )] + Syntax { + language: &'static str, + count: usize, + first: String, + diagnostics: Vec, + }, + /// Reading or writing the file failed. + #[error("{path}: {source}")] + Io { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +impl PatchError { + /// Parse diagnostics, when this failure carried any — the text a + /// caller can feed straight back to the model that wrote the patch. + pub fn diagnostics(&self) -> &[Diagnostic] { + match self { + PatchError::Syntax { diagnostics, .. } => diagnostics, + _ => &[], + } + } +} + +/// Apply `patch` to the file at `path`, or leave it untouched. +/// +/// One file per call: a patch spanning several files is a parse error, +/// because a caller that only reads "ok" would otherwise never learn that +/// half its intent was dropped. +pub fn apply_patch_file( + path: &Path, + patch: &str, + opts: &ApplyOptions, +) -> Result { + // Write through symlinks instead of replacing them with a regular file. + let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let bytes = std::fs::read(&target).map_err(|source| PatchError::Io { + path: path.to_path_buf(), + source, + })?; + let original = String::from_utf8(bytes).map_err(|_| PatchError::NotText { + path: path.to_path_buf(), + })?; + let rendered = render_patch(&target, &original, patch, opts)?; + if rendered.text != original { + atomic::replace(&target, rendered.text.as_bytes()).map_err(|source| PatchError::Io { + path: path.to_path_buf(), + source, + })?; + } + Ok(rendered.report) +} + +/// Render the patched text in memory: anchor, apply, validate — no IO. +/// +/// `path` is used only to resolve the Tree-sitter grammar for the file +/// type; nothing is read from or written to it. +pub fn render_patch( + path: &Path, + original: &str, + patch: &str, + opts: &ApplyOptions, +) -> Result { + let hunks = parse::parse(patch)?; + let lines = render::split(original); + let contents: Vec<&str> = lines.iter().map(|(content, _)| *content).collect(); + let anchors = anchor::anchor_all(&contents, &hunks, opts)?; + let text = render::render(&lines, &hunks, &anchors); + + let total = hunks.len(); + let mut warnings = Vec::new(); + let mut reports = Vec::with_capacity(total); + for (index, (hunk, anchor)) in hunks.iter().zip(&anchors).enumerate() { + if hunk.old_count() != hunk.declared_old || hunk.new_count() != hunk.declared_new { + warnings.push(format!( + "hunk {}/{}: header declares {} old / {} new line(s) but the body carries {} / {}; anchored on the body", + index + 1, + total, + hunk.declared_old, + hunk.declared_new, + hunk.old_count(), + hunk.new_count() + )); + } + let insertion = hunk.old_count() == 0; + let declared = if insertion { + hunk.old_start + } else { + hunk.old_start.saturating_sub(1) + }; + if anchor.exact && anchor.start != declared { + warnings.push(format!( + "hunk {}/{}: exact context matched at line {}, not the declared line {}", + index + 1, + total, + anchor.start + 1, + declared + 1 + )); + } else if !anchor.exact { + warnings.push(format!( + "hunk {}/{}: anchored by similarity {:.2} at line {}, {} line(s) from the declared line", + index + 1, + total, + anchor.similarity, + anchor.start + 1, + anchor.start.abs_diff(declared) + )); + } + reports.push(HunkReport { + index: index + 1, + line: anchor.start + 1, + exact: anchor.exact, + similarity: anchor.similarity, + }); + } + + let syntax = check_syntax(path, &text, opts, &mut warnings)?; + + Ok(Rendered { + text, + report: ApplyReport { + hunks: reports, + syntax, + warnings, + }, + }) +} + +fn check_syntax( + path: &Path, + text: &str, + opts: &ApplyOptions, + warnings: &mut Vec, +) -> Result { + if !opts.validate_syntax { + return Ok(SyntaxCheck::Disabled); + } + let Some(language) = syntax::Language::for_path(path) else { + let reason = format!( + "no tree-sitter grammar for `{}` — patched without a syntax check", + path.display() + ); + tracing::warn!(path = %path.display(), "patch: {reason}"); + warnings.push(reason.clone()); + return Ok(SyntaxCheck::Skipped(reason)); + }; + match syntax::validate(text, language) { + syntax::Validation::Clean => Ok(SyntaxCheck::Clean(language.name())), + syntax::Validation::Unavailable(reason) => { + tracing::warn!(path = %path.display(), language = language.name(), "patch: {reason}"); + let reason = format!( + "{} grammar unavailable ({reason}) — patched without a syntax check", + language.name() + ); + warnings.push(reason.clone()); + Ok(SyntaxCheck::Skipped(reason)) + } + syntax::Validation::Syntax(diagnostics) => { + let count = diagnostics.len(); + let first = diagnostics + .first() + .map(|d| d.to_string()) + .unwrap_or_else(|| "unlocated parse error".to_string()); + Err(PatchError::Syntax { + language: language.name(), + count, + first, + diagnostics, + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn render(original: &str, patch: &str) -> Result { + render_patch( + Path::new("src/demo.rs"), + original, + patch, + &ApplyOptions::default(), + ) + } + + #[test] + fn default_options_are_the_documented_ones() { + let opts = ApplyOptions::default(); + assert_eq!(opts.similarity_threshold, 0.60); + assert_eq!(opts.ambiguity_margin, 0.05); + assert_eq!(opts.search_window, Some(250)); + assert!(opts.validate_syntax); + } + + #[test] + fn a_direct_patch_renders_and_reports() { + let out = render( + "fn main() {\n let a = 1;\n}\n", + "@@ -2,1 +2,1 @@\n- let a = 1;\n+ let a = 2;\n", + ) + .unwrap(); + assert_eq!(out.text, "fn main() {\n let a = 2;\n}\n"); + assert_eq!(out.report.hunks.len(), 1); + assert!(out.report.hunks[0].exact); + assert_eq!(out.report.syntax, SyntaxCheck::Clean("rust")); + assert!(out.report.warnings.is_empty(), "{:?}", out.report.warnings); + } + + #[test] + fn a_miscounted_header_warns_but_applies() { + // A `.txt` path: the body is not Rust, so no grammar gets in the way + // of what this test is about. + let out = render_patch( + Path::new("notes.txt"), + "a\nb\nc\n", + "@@ -2,9 +2,9 @@\n-b\n+B\n", + &ApplyOptions::default(), + ) + .unwrap(); + assert_eq!(out.text, "a\nB\nc\n"); + assert!( + out.report.warnings.iter().any(|w| w.contains("declares")), + "{:?}", + out.report.warnings + ); + } + + #[test] + fn a_fuzzy_anchor_is_reported_and_warned() { + let original = "// top\nfn main() {\n let a = 1;\n}\n"; + let patch = "@@ -9,2 +9,2 @@\n fn main() {\n- let a = 2;\n+ let a = 3;\n"; + let out = render(original, patch).unwrap(); + assert!(!out.report.hunks[0].exact); + assert!( + out.report.warnings.iter().any(|w| w.contains("similarity")), + "{:?}", + out.report.warnings + ); + assert!(out.text.contains("let a = 3;")); + } + + #[test] + fn syntax_errors_are_returned_as_diagnostics() { + let err = render( + "fn main() {\n let a = 1;\n}\n", + "@@ -2,1 +2,1 @@\n- let a = 1;\n+ let = ;\n", + ) + .unwrap_err(); + assert!(matches!(err, PatchError::Syntax { .. }), "{err}"); + assert!(!err.diagnostics().is_empty()); + } + + #[test] + fn validation_can_be_turned_off() { + let opts = ApplyOptions { + validate_syntax: false, + ..ApplyOptions::default() + }; + let out = render_patch( + Path::new("src/demo.rs"), + "fn main() {\n let a = 1;\n}\n", + "@@ -2,1 +2,1 @@\n- let a = 1;\n+ let = ;\n", + &opts, + ) + .unwrap(); + assert_eq!(out.report.syntax, SyntaxCheck::Disabled); + } + + #[test] + fn an_unknown_file_type_applies_with_a_warning() { + let out = render_patch( + Path::new("notes.txt"), + "one\ntwo\nthree\n", + "@@ -2,1 +2,1 @@\n-two\n+TWO\n", + &ApplyOptions::default(), + ) + .unwrap(); + assert_eq!(out.text, "one\nTWO\nthree\n"); + assert!(matches!(out.report.syntax, SyntaxCheck::Skipped(_))); + assert!(!out.report.warnings.is_empty()); + } +} diff --git a/src/patch/parse.rs b/src/patch/parse.rs new file mode 100644 index 0000000..7c06bdb --- /dev/null +++ b/src/patch/parse.rs @@ -0,0 +1,348 @@ +//! Unified-diff parsing for the fuzzy patch engine. +//! +//! Scope is one file's patch, as `git diff` or a model emits it. File +//! headers (`diff --git`, `index`, `--- a/x`, `+++ b/x`, mode lines, +//! binary notices) are skipped; everything from the first `@@` on is +//! hunk body. A second file header after hunks began is an error rather +//! than a silent stop: applying only the first file of a multi-file +//! patch and reporting success is the half-done edit this engine exists +//! to prevent. +//! +//! The line counts in the `@@` header are advisory. Agent-emitted +//! patches routinely miscount them (that miscount is part of why they +//! fail under `git apply`), so the hunk **body** is what gets anchored, +//! and a disagreement is surfaced as a warning by the caller instead of +//! a parse failure. +//! +//! Line endings: a `\r` before the newline is stripped while parsing. +//! Hunks therefore compare against the file's content lines regardless +//! of which side of the newline convention the patch was produced on; +//! [`crate::patch::render`] puts the file's own endings back. + +use std::fmt; + +/// The role of one hunk body line. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HunkLineKind { + /// Present on both sides (leading space). + Context, + /// Present only before the patch (leading `-`). + Remove, + /// Present only after the patch (leading `+`). + Add, +} + +/// One line of a hunk body, without its leading marker. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HunkLine { + pub kind: HunkLineKind, + pub text: String, +} + +/// One `@@` block: where it nominally starts on the pre-patch side and +/// the body lines that carry the edit. +#[derive(Debug, Clone)] +pub(crate) struct Hunk { + /// 1-based first line of the hunk on the pre-patch side. `0` for a + /// hunk that only inserts before the first line (`@@ -0,0 +1,2 @@`). + pub old_start: usize, + /// Old-side line count claimed by the header — advisory only. + pub declared_old: usize, + /// New-side line count claimed by the header — advisory only. + pub declared_new: usize, + pub lines: Vec, + /// The hunk ended with `\ No newline at end of file`. + pub eof_no_newline: bool, +} + +impl Hunk { + /// Content of the pre-patch side, in patch order (context + removals). + pub fn old_lines(&self) -> impl Iterator { + self.lines + .iter() + .filter(|l| l.kind != HunkLineKind::Add) + .map(|l| l.text.as_str()) + } + + /// How many pre-patch lines the body actually carries. + pub fn old_count(&self) -> usize { + self.lines + .iter() + .filter(|l| l.kind != HunkLineKind::Add) + .count() + } + + /// How many post-patch lines the body actually carries. + pub fn new_count(&self) -> usize { + self.lines + .iter() + .filter(|l| l.kind != HunkLineKind::Remove) + .count() + } +} + +/// Why a patch could not be read as one file's hunks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ParseError { + /// The text carries no `@@` hunk at all. + NoHunks, + /// A `@@` line whose ranges could not be read. + BadHeader { line: usize, text: String }, + /// Text inside a hunk body that starts with none of ` `, `+`, `-`, `\`. + Garbage { line: usize, text: String }, + /// A second file's header after hunks began. + MultiFile { line: usize }, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParseError::NoHunks => write!(f, "no @@ hunk found in the patch"), + ParseError::BadHeader { line, text } => { + write!(f, "line {line}: cannot read hunk header `{text}`") + } + ParseError::Garbage { line, text } => write!( + f, + "line {line}: unexpected line inside a hunk body (must start with ' ', '+', '-' or '\\'): `{text}`" + ), + ParseError::MultiFile { line } => write!( + f, + "line {line}: a second file's header — this engine applies one file per patch" + ), + } + } +} + +impl std::error::Error for ParseError {} + +/// Parse one file's unified diff into hunks. +pub(crate) fn parse(text: &str) -> Result, ParseError> { + let raw: Vec<&str> = text.split('\n').collect(); + let mut hunks: Vec = Vec::new(); + let mut current: Option = None; + + for (index, raw_line) in raw.iter().enumerate() { + let line_no = index + 1; + let line = raw_line.strip_suffix('\r').unwrap_or(raw_line); + + if line.starts_with("@@") { + if let Some(done) = current.take() { + hunks.push(done); + } + let header = parse_header(line).ok_or_else(|| ParseError::BadHeader { + line: line_no, + text: line.to_string(), + })?; + current = Some(Hunk { + old_start: header.old_start, + declared_old: header.old_len, + declared_new: header.new_len, + lines: Vec::new(), + eof_no_newline: false, + }); + continue; + } + + let Some(hunk) = current.as_mut() else { + // Preamble before the first hunk: `diff --git`, `index`, + // `---`/`+++`, mode and rename lines, binary notices. None + // of it says where the edit goes; the hunks do. + continue; + }; + + if line.starts_with("diff --git ") || line.starts_with("diff --cc ") { + return Err(ParseError::MultiFile { line: line_no }); + } + + if line.is_empty() && index + 1 == raw.len() { + // The artifact of the patch text's own final newline, not a + // body line. + continue; + } + // A body line replaces any `\ No newline` marker that preceded it. + hunk.eof_no_newline = false; + match line.chars().next() { + None => { + // A bare empty line: git writes " " for an empty context + // line, but hand-written patches drop the space. + hunk.lines.push(HunkLine { + kind: HunkLineKind::Context, + text: String::new(), + }); + } + Some(' ') => hunk.lines.push(HunkLine { + kind: HunkLineKind::Context, + text: line[1..].to_string(), + }), + Some('+') => hunk.lines.push(HunkLine { + kind: HunkLineKind::Add, + text: line[1..].to_string(), + }), + Some('-') => hunk.lines.push(HunkLine { + kind: HunkLineKind::Remove, + text: line[1..].to_string(), + }), + Some('\\') => { + // "\ No newline at end of file" describes the line above. + // It only means something when it closes the hunk; a + // later body line clears it again. + hunk.eof_no_newline = true; + } + Some(_) => { + return Err(ParseError::Garbage { + line: line_no, + text: line.to_string(), + }); + } + } + } + + if let Some(done) = current.take() { + hunks.push(done); + } + if hunks.is_empty() { + return Err(ParseError::NoHunks); + } + Ok(hunks) +} + +struct Header { + old_start: usize, + old_len: usize, + new_len: usize, +} + +/// `@@ -15,7 +15,8 @@ optional section heading` +fn parse_header(line: &str) -> Option
{ + let rest = line.strip_prefix("@@")?.trim_start(); + let end = rest.find("@@")?; + let mut parts = rest[..end].split_whitespace(); + let old = parts.next()?.strip_prefix('-')?; + let new = parts.next()?.strip_prefix('+')?; + let (old_start, old_len) = parse_range(old)?; + let (_, new_len) = parse_range(new)?; + Some(Header { + old_start, + old_len, + new_len, + }) +} + +/// `15,7` → (15, 7); `15` → (15, 1); `0,0` → (0, 0). +fn parse_range(text: &str) -> Option<(usize, usize)> { + let (start, len) = match text.split_once(',') { + Some((start, len)) => (start, len), + None => (text, "1"), + }; + Some((start.parse().ok()?, len.parse().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_a_git_style_patch_with_preamble() { + let patch = "\ +diff --git a/src/lib.rs b/src/lib.rs +index 1111111..2222222 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -10,3 +10,3 @@ fn main() { + let a = 1; +-let b = 2; ++let b = 3; + ctx +"; + let hunks = parse(patch).unwrap(); + assert_eq!(hunks.len(), 1); + let hunk = &hunks[0]; + assert_eq!(hunk.old_start, 10); + assert_eq!(hunk.declared_old, 3); + assert_eq!(hunk.old_count(), 3); + assert_eq!(hunk.new_count(), 3); + let kinds: Vec<_> = hunk.lines.iter().map(|l| l.kind).collect(); + assert_eq!( + kinds, + vec![ + HunkLineKind::Context, + HunkLineKind::Remove, + HunkLineKind::Add, + HunkLineKind::Context + ] + ); + } + + #[test] + fn parses_multiple_hunks_and_bare_empty_context_lines() { + let patch = "@@ -1,2 +1,2 @@\n a\n\n@@ -9,1 +9,1 @@\n-b\n+c\n"; + let hunks = parse(patch).unwrap(); + assert_eq!(hunks.len(), 2); + assert_eq!(hunks[0].lines.len(), 2); + assert_eq!(hunks[0].lines[1].text, ""); + assert_eq!(hunks[1].old_start, 9); + } + + #[test] + fn parses_insertion_only_hunk() { + let hunks = parse("@@ -3,0 +4,2 @@\n+one\n+two\n").unwrap(); + assert_eq!(hunks[0].old_count(), 0); + assert_eq!(hunks[0].new_count(), 2); + assert_eq!(hunks[0].old_start, 3); + } + + #[test] + fn range_without_a_count_is_one_line() { + assert_eq!(parse_range("7"), Some((7, 1))); + assert_eq!(parse_range("7,0"), Some((7, 0))); + assert_eq!(parse_range("x"), None); + } + + #[test] + fn strips_crlf_from_body_lines() { + let hunks = parse("@@ -1,2 +1,2 @@\r\n a\r\n-b\r\n+c\r\n").unwrap(); + assert_eq!(hunks[0].lines[0].text, " a".trim_start()); + assert_eq!(hunks[0].lines[2].text, "c"); + } + + #[test] + fn eof_no_newline_marker_is_captured() { + let hunks = parse("@@ -1,1 +1,1 @@\n-a\n+b\n\\ No newline at end of file\n").unwrap(); + assert!(hunks[0].eof_no_newline); + } + + #[test] + fn a_marker_followed_by_another_line_is_not_the_eof_marker() { + let hunks = parse("@@ -1,2 +1,2 @@\n-a\n\\ No newline at end of file\n+b\n c\n").unwrap(); + assert!(!hunks[0].eof_no_newline); + } + + #[test] + fn rejects_text_without_hunks() { + assert_eq!(parse("just a sentence\n").unwrap_err(), ParseError::NoHunks); + } + + #[test] + fn rejects_a_second_file_header() { + let err = parse("@@ -1,1 +1,1 @@\n-a\n+b\ndiff --git a/x b/x\n").unwrap_err(); + assert!(matches!(err, ParseError::MultiFile { .. }), "{err}"); + } + + #[test] + fn rejects_garbage_inside_a_hunk() { + let err = parse("@@ -1,1 +1,1 @@\n???\n").unwrap_err(); + assert!(matches!(err, ParseError::Garbage { .. }), "{err}"); + } + + #[test] + fn rejects_a_broken_header() { + let err = parse("@@ nonsense @@\n-a\n").unwrap_err(); + assert!(matches!(err, ParseError::BadHeader { .. }), "{err}"); + } + + #[test] + fn a_minus_line_that_looks_like_a_file_header_is_body() { + let hunks = parse("@@ -1,1 +1,1 @@\n--- not a header\n").unwrap(); + assert_eq!(hunks[0].lines[0].text, "-- not a header"); + } +} diff --git a/src/patch/render.rs b/src/patch/render.rs new file mode 100644 index 0000000..a500c59 --- /dev/null +++ b/src/patch/render.rs @@ -0,0 +1,172 @@ +//! Rendering the patched file in memory. +//! +//! The output is built from three kinds of line: +//! +//! - **kept** file lines, written back byte-for-byte with their own line +//! ending — including lines the patch never mentioned and lines that +//! drifted inside a hunk's span (an extra comment, a re-formatted +//! block). Nothing the patch did not address gets rewritten; +//! - **removed** file lines, dropped through the anchor's alignment; +//! - **added** patch lines, written with the file's own line ending, so a +//! CRLF file stays CRLF even when the patch text arrived LF-only. +//! +//! The tail is handled separately: a file that ends without a newline +//! keeps ending without one through a middle edit, and a patch that +//! rewrites the final line either carries the standard +//! `\ No newline at end of file` marker or, if the file already ended +//! without one, keeps that ending. + +use super::anchor::Anchor; +use super::parse::{Hunk, HunkLineKind}; + +/// One line of the original file: content without the ending, and the +/// ending exactly as it was (`"\n"`, `"\r\n"`, or `""` for a final line +/// with no newline). +pub(crate) type FileLine<'a> = (&'a str, &'a str); + +/// Split text into lines, keeping each line's own ending. +pub(crate) fn split(text: &str) -> Vec> { + let mut lines = Vec::new(); + let mut start = 0usize; + for (index, ch) in text.char_indices() { + if ch != '\n' { + continue; + } + let raw = &text[start..index]; + let (content, ending) = match raw.strip_suffix('\r') { + Some(content) => (content, "\r\n"), + None => (raw, "\n"), + }; + lines.push((content, ending)); + start = index + 1; + } + if start < text.len() { + lines.push((&text[start..], "")); + } + lines +} + +/// Render the post-patch text. +pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Anchor]) -> String { + let newline = if original.iter().any(|(_, ending)| *ending == "\r\n") { + "\r\n" + } else { + "\n" + }; + let eof_marker = hunks.last().map(|h| h.eof_no_newline).unwrap_or(false); + let file_ends_with_newline = original.last().map(|(_, e)| !e.is_empty()).unwrap_or(false); + + let mut out: Vec<(&str, &str)> = Vec::new(); + let mut last_is_added = false; + let mut cursor = 0usize; + + for (hunk, anchor) in hunks.iter().zip(anchors) { + while cursor < anchor.start && cursor < original.len() { + out.push(original[cursor]); + last_is_added = false; + cursor += 1; + } + let mut mapped = std::collections::BTreeMap::new(); + for &(old_index, file_index) in &anchor.pairs { + mapped.insert(old_index, file_index); + } + let mut old_index = 0usize; + for line in &hunk.lines { + match line.kind { + HunkLineKind::Context => { + if let Some(&file_index) = mapped.get(&old_index) { + while cursor < file_index { + out.push(original[cursor]); + cursor += 1; + } + if cursor == file_index { + out.push(original[file_index]); + last_is_added = false; + cursor = file_index + 1; + } + } + // Unmapped: the file no longer carries this line. Keeping + // it absent is the point of fuzzy anchoring. + old_index += 1; + } + HunkLineKind::Remove => { + if let Some(&file_index) = mapped.get(&old_index) + && file_index >= cursor + { + while cursor < file_index { + out.push(original[cursor]); + cursor += 1; + } + cursor = file_index + 1; + } + old_index += 1; + } + HunkLineKind::Add => { + out.push((line.text.as_str(), newline)); + last_is_added = true; + } + } + } + } + while cursor < original.len() { + out.push(original[cursor]); + last_is_added = false; + cursor += 1; + } + + // The final line's ending. A kept file line keeps its own ending + // (including none); an added final line takes one unless the patch + // marked it or the file it replaced had no trailing newline. + let reaches_eof = anchors + .last() + .map(|a| a.end >= original.len()) + .unwrap_or(false); + let drop_final_newline = + eof_marker || (last_is_added && reaches_eof && !file_ends_with_newline); + + let mut text = String::new(); + for (index, (content, ending)) in out.iter().enumerate() { + text.push_str(content); + if index + 1 == out.len() { + if last_is_added { + if !drop_final_newline { + text.push_str(newline); + } + } else { + text.push_str(ending); + } + } else if ending.is_empty() { + text.push_str(newline); + } else { + text.push_str(ending); + } + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines(text: &str) -> Vec<(&str, &str)> { + split(text) + } + + #[test] + fn split_keeps_each_line_ending() { + assert_eq!( + lines("a\r\nb\nc"), + vec![("a", "\r\n"), ("b", "\n"), ("c", "")] + ); + } + + #[test] + fn split_of_an_empty_file_is_empty() { + assert!(split("").is_empty()); + } + + #[test] + fn split_of_a_single_newline_is_one_empty_line() { + assert_eq!(split("\n"), vec![("", "\n")]); + } +} diff --git a/src/patch/score.rs b/src/patch/score.rs new file mode 100644 index 0000000..6a24494 --- /dev/null +++ b/src/patch/score.rs @@ -0,0 +1,250 @@ +//! Line normalization and similarity for fuzzy anchoring. +//! +//! A hunk anchors on *content*, not on line arithmetic, so the +//! comparison has to survive the two drifts that break `git apply`: +//! whitespace/indentation churn and comment rewording. Both are +//! normalized away before the code tokens are compared: +//! +//! - indentation and runs of whitespace never become tokens, so re-indented +//! or re-wrapped lines compare equal; +//! - a line's comment tail is not part of its code tokens, so a +//! paraphrased or deleted comment costs nothing on a code line; +//! - two comment-only lines compare at [`COMMENT_DRIFT_SIM`] — high enough +//! to keep their place in a hunk, low enough that code evidence still +//! dominates the hunk score; +//! - a comment-only line never matches a code line, so a comment cannot +//! stand in for the statement it describes. +//! +//! The cost of that tolerance: a *code* token change does move the score, +//! which is what keeps a patch from anchoring onto the wrong function. +//! +//! Comment detection is deliberately lexical and language-agnostic +//! (`//`, `/* */`, and `#` at the start of the line's code), which also +//! catches C preprocessor lines as "comments". They are treated as +//! prose-like, which is acceptable: preprocessor lines never carry the +//! edit an agent is trying to place. + +use std::hash::{Hash, Hasher}; + +/// Similarity two comment-only lines score against each other. High +/// enough that a hunk still anchors across comment rewording; below 1.0 +/// so an exact code match still outranks it. +pub(crate) const COMMENT_DRIFT_SIM: f64 = 0.9; + +/// A line reduced to comparable tokens. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct LineTokens { + /// Sorted token hashes of everything outside comments. Sorted so a + /// multiset intersection is a linear merge, and hashed so a token + /// comparison is an integer compare. + code: Vec, + /// The line carries a comment (and therefore some prose). + has_comment: bool, + /// The line is empty or whitespace only. + blank: bool, +} + +impl LineTokens { + /// Nothing but a comment on this line. + pub(crate) fn comment_only(&self) -> bool { + self.has_comment && self.code.is_empty() && !self.blank + } +} + +/// Reduce one line to its comparable tokens. +pub(crate) fn tokenize(line: &str) -> LineTokens { + let mut code: Vec = Vec::new(); + let mut has_comment = false; + let mut i = 0usize; + let bytes = line.as_bytes(); + + while i < line.len() { + let rest = &line[i..]; + let ch = rest.chars().next().expect("i is inside the line"); + match ch { + c if c.is_whitespace() => i += c.len_utf8(), + '/' if bytes.get(i + 1) == Some(&b'/') => { + has_comment = true; + break; + } + '/' if bytes.get(i + 1) == Some(&b'*') => { + has_comment = true; + match line[i + 2..].find("*/") { + Some(end) => i = i + 2 + end + 2, + None => break, + } + } + // `#` 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; + } + quote @ ('"' | '\'' | '`') => { + let end = skip_quoted(bytes, i, quote); + code.push(hash(&rest[..end - i])); + i = end; + } + c if c.is_alphanumeric() || c == '_' => { + let start = i; + while i < line.len() { + let c = line[i..].chars().next().expect("i is inside the line"); + if c.is_alphanumeric() || c == '_' { + i += c.len_utf8(); + } else { + break; + } + } + code.push(hash(&line[start..i])); + } + other => { + code.push(hash(&rest[..other.len_utf8()])); + i += other.len_utf8(); + } + } + } + + code.sort_unstable(); + LineTokens { + code, + has_comment, + blank: line.trim().is_empty(), + } +} + +/// Token-level Dice coefficient between two lines, 0.0–1.0. +pub(crate) fn similarity(a: &LineTokens, b: &LineTokens) -> f64 { + if a.blank || b.blank { + return if a.blank && b.blank { 1.0 } else { 0.0 }; + } + let a_comment = a.comment_only(); + let b_comment = b.comment_only(); + if a_comment || b_comment { + return if a_comment && b_comment { + COMMENT_DRIFT_SIM + } else { + 0.0 + }; + } + if a.code.is_empty() || b.code.is_empty() { + // Two lines with no comparable token (e.g. pure punctuation that + // tokenized away) are only as similar as their text. + return if a.code.is_empty() && b.code.is_empty() { + 1.0 + } else { + 0.0 + }; + } + let (mut i, mut j, mut common) = (0usize, 0usize, 0usize); + while i < a.code.len() && j < b.code.len() { + match a.code[i].cmp(&b.code[j]) { + std::cmp::Ordering::Less => i += 1, + std::cmp::Ordering::Greater => j += 1, + std::cmp::Ordering::Equal => { + common += 1; + i += 1; + j += 1; + } + } + } + (2.0 * common as f64) / ((a.code.len() + b.code.len()) as f64) +} + +fn hash(token: &str) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + token.hash(&mut hasher); + hasher.finish() +} + +/// End byte index of the quoted run starting at `start` (inclusive of +/// the closing quote when there is one, or the line end when the literal +/// is unterminated — a half-typed string still compares as one token). +fn skip_quoted(bytes: &[u8], start: usize, quote: char) -> usize { + let mut i = start + quote.len_utf8(); + while i < bytes.len() { + match bytes[i] { + b'\\' => i += 2, + b if b == quote as u8 => return i + 1, + _ => i += 1, + } + } + bytes.len() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sim(a: &str, b: &str) -> f64 { + similarity(&tokenize(a), &tokenize(b)) + } + + #[test] + fn identical_lines_are_a_perfect_match() { + assert_eq!(sim("let x = 1;", "let x = 1;"), 1.0); + } + + #[test] + fn indentation_and_whitespace_runs_do_not_count() { + assert_eq!(sim(" let x = 1;", " let x=1;"), 1.0); + } + + #[test] + fn a_changed_identifier_lowers_the_score() { + let s = sim("let total = items.len();", "let count = items.len();"); + assert!(s > 0.5 && s < 1.0, "{s}"); + } + + #[test] + fn a_paraphrased_comment_stays_high() { + let s = sim("// load the config", "// read the configuration file"); + assert!(s >= COMMENT_DRIFT_SIM, "{s}"); + } + + #[test] + fn a_comment_tail_does_not_move_a_code_line() { + assert_eq!(sim("let x = 1; // set the value", "let x = 1;"), 1.0); + } + + #[test] + fn a_comment_never_stands_in_for_code() { + assert_eq!(sim("// let x = 1;", "let x = 1;"), 0.0); + } + + #[test] + fn blank_lines_match_only_blank_lines() { + assert_eq!(sim(" ", ""), 1.0); + assert_eq!(sim("", "let x = 1;"), 0.0); + } + + #[test] + fn rust_attributes_are_not_comments() { + let tokens = tokenize("#[derive(Debug)]"); + assert!(!tokens.comment_only()); + assert!(sim("#[derive(Debug)]", "#[derive(Clone)]") < 1.0); + } + + #[test] + fn string_literals_are_one_token() { + // A changed literal is one changed token, not a dozen. + let s = sim( + r#"println!("hello {}", name);"#, + r#"println!("bye {}", name);"#, + ); + assert!(s > 0.7 && s < 1.0, "{s}"); + } + + #[test] + fn korean_text_in_a_comment_is_ignored() { + assert_eq!(sim("let x = 1; // 값 설정", "let x = 1;"), 1.0); + } + + #[test] + fn block_comments_are_comment_only() { + assert!(tokenize("/* note */").comment_only()); + assert_eq!(sim("/* one */", "/* two */"), COMMENT_DRIFT_SIM); + } +} diff --git a/src/patch/syntax.rs b/src/patch/syntax.rs new file mode 100644 index 0000000..2e3ce24 --- /dev/null +++ b/src/patch/syntax.rs @@ -0,0 +1,319 @@ +//! Tree-sitter shadow validation: parse the patched text before it is +//! written, so a syntactically broken result never reaches the disk. +//! +//! A bad patch used to be discovered by the build — or worse, by the +//! next model turn reading a poisoned file. Here the whole post-patch +//! file is parsed in memory and `ERROR`/`MISSING` nodes become +//! diagnostics the caller can hand straight back to the model. +//! +//! Grammars are compiled in but loaded **lazily**, on the first patch of +//! a given file type: a daemon that only ever patches Rust pays nothing +//! for the TypeScript grammar. A file type with no grammar — or, in a +//! future dynamic loader, a grammar that fails to load — is a warning +//! and an apply, never a block: refusing to patch the languages this +//! build happens not to ship a parser for would make the engine useless +//! exactly where it is needed (`#31`'s acceptance criteria). +//! +//! The check is whole-file on purpose. Parsing a few thousand lines is +//! milliseconds, and an incremental parse against a stale tree would +//! miss the errors that matter: the ones the edit introduced. + +use std::fmt; +use std::path::Path; +use std::sync::OnceLock; + +/// A file type the engine can parse. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Language { + Rust, + Python, + JavaScript, + TypeScript, + Tsx, +} + +impl Language { + /// Resolve a file type from its extension. + pub(crate) fn for_path(path: &Path) -> Option { + let extension = path.extension()?.to_str()?.to_ascii_lowercase(); + Some(match extension.as_str() { + "rs" => Language::Rust, + "py" | "pyi" => Language::Python, + "js" | "mjs" | "cjs" | "jsx" => Language::JavaScript, + "ts" | "mts" | "cts" => Language::TypeScript, + "tsx" => Language::Tsx, + _ => return None, + }) + } + + pub(crate) fn name(self) -> &'static str { + match self { + Language::Rust => "rust", + Language::Python => "python", + Language::JavaScript => "javascript", + Language::TypeScript => "typescript", + Language::Tsx => "tsx", + } + } + + /// The grammar, loaded on first use. Today every grammar is compiled + /// in, so this cannot fail; the seam exists because a load failure + /// must be a warning and an apply, and a dynamically loaded grammar + /// will fail here. + fn grammar(self) -> Result { + static RUST: OnceLock> = OnceLock::new(); + static PYTHON: OnceLock> = OnceLock::new(); + static JAVASCRIPT: OnceLock> = OnceLock::new(); + static TYPESCRIPT: OnceLock> = OnceLock::new(); + static TSX: OnceLock> = OnceLock::new(); + + let slot = match self { + Language::Rust => &RUST, + Language::Python => &PYTHON, + Language::JavaScript => &JAVASCRIPT, + Language::TypeScript => &TYPESCRIPT, + Language::Tsx => &TSX, + }; + slot.get_or_init(|| match self { + Language::Rust => Ok(tree_sitter_rust::LANGUAGE.into()), + Language::Python => Ok(tree_sitter_python::LANGUAGE.into()), + Language::JavaScript => Ok(tree_sitter_javascript::LANGUAGE.into()), + Language::TypeScript => Ok(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()), + Language::Tsx => Ok(tree_sitter_typescript::LANGUAGE_TSX.into()), + }) + .clone() + } +} + +/// One parse problem, positioned for a caller (a model, a human) to act on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Diagnostic { + /// 1-based line in the shadow file. + pub line: usize, + /// 1-based column. + pub column: usize, + /// What Tree-sitter expected (`MISSING`) or the node kind it failed on. + pub kind: String, + /// Set for `MISSING` nodes — the parse wanted a token that is absent. + pub missing: bool, + /// Nearby text, single-line and truncated. + pub snippet: String, +} + +impl fmt::Display for Diagnostic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.missing { + write!(f, "{}:{}: missing `{}`", self.line, self.column, self.kind) + } else { + write!( + f, + "{}:{}: unexpected `{}`", + self.line, self.column, self.snippet + ) + } + } +} + +/// Why a shadow file was not validated. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Validation { + /// Parsed; no `ERROR`/`MISSING` node. + Clean, + /// No grammar for this file type (or the grammar could not be loaded). + Unavailable(String), + /// The parse found syntax errors. + Syntax(Vec), +} + +/// Longest snippet kept per diagnostic. +const SNIPPET_CHARS: usize = 60; + +/// Most diagnostics reported in one failure — the first few carry the +/// information; a cascade of hundreds only makes the message unreadable. +const MAX_DIAGNOSTICS: usize = 16; + +pub(crate) fn validate(source: &str, language: Language) -> Validation { + let grammar = match language.grammar() { + Ok(grammar) => grammar, + Err(error) => return Validation::Unavailable(error), + }; + let mut parser = tree_sitter::Parser::new(); + if let Err(error) = parser.set_language(&grammar) { + return Validation::Unavailable(format!("{} grammar rejected: {error}", language.name())); + } + let Some(tree) = parser.parse(source, None) else { + return Validation::Unavailable("tree-sitter cancelled the parse".to_string()); + }; + let root = tree.root_node(); + if !root.has_error() { + return Validation::Clean; + } + let mut diagnostics = Vec::new(); + collect(root, source, &mut diagnostics); + if diagnostics.is_empty() { + // `has_error` was true but no node carried the flag in the walk we + // understand — still a broken parse; say so rather than pass it. + diagnostics.push(Diagnostic { + line: root.start_position().row + 1, + column: root.start_position().column + 1, + kind: root.kind().to_string(), + missing: false, + snippet: "".to_string(), + }); + } + Validation::Syntax(diagnostics) +} + +fn collect(node: tree_sitter::Node<'_>, source: &str, out: &mut Vec) { + let mut stack = vec![node]; + while let Some(node) = stack.pop() { + if out.len() >= MAX_DIAGNOSTICS { + return; + } + if node.is_error() || node.is_missing() { + out.push(diagnostic(node, source)); + continue; + } + if node.has_error() { + // Push in reverse so the walk visits children in source order. + for index in (0..node.child_count()).rev() { + if let Some(child) = node.child(index) { + stack.push(child); + } + } + } + } +} + +fn diagnostic(node: tree_sitter::Node<'_>, source: &str) -> Diagnostic { + let position = node.start_position(); + let snippet = match source.get(node.byte_range()) { + Some(text) if !text.is_empty() => summarize(text), + _ => source + .lines() + .nth(position.row) + .map(summarize) + .unwrap_or_default(), + }; + Diagnostic { + line: position.row + 1, + column: position.column + 1, + kind: node.kind().to_string(), + missing: node.is_missing(), + snippet, + } +} + +fn summarize(text: &str) -> String { + let collapsed = text.split_whitespace().collect::>().join(" "); + let mut snippet: String = collapsed.chars().take(SNIPPET_CHARS).collect(); + if collapsed.chars().count() > SNIPPET_CHARS { + snippet.push('…'); + } + snippet +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_languages_from_extensions() { + assert_eq!( + Language::for_path(Path::new("a/b.rs")), + Some(Language::Rust) + ); + assert_eq!( + Language::for_path(Path::new("x.py")), + Some(Language::Python) + ); + assert_eq!( + Language::for_path(Path::new("x.mjs")), + Some(Language::JavaScript) + ); + assert_eq!(Language::for_path(Path::new("x.tsx")), Some(Language::Tsx)); + assert_eq!( + Language::for_path(Path::new("x.TS")), + Some(Language::TypeScript) + ); + assert_eq!(Language::for_path(Path::new("notes.txt")), None); + assert_eq!(Language::for_path(Path::new("Makefile")), None); + } + + #[test] + fn valid_rust_parses_clean() { + assert_eq!( + validate("fn main() { let x = 1; }\n", Language::Rust), + Validation::Clean + ); + } + + #[test] + fn broken_rust_reports_positioned_diagnostics() { + let Validation::Syntax(diagnostics) = + validate("fn main() {\n let x = ;\n}\n", Language::Rust) + else { + panic!("expected syntax diagnostics"); + }; + assert!(!diagnostics.is_empty()); + assert_eq!(diagnostics[0].line, 2); + assert!(diagnostics[0].column > 1); + } + + #[test] + fn a_missing_token_is_reported_as_missing() { + let Validation::Syntax(diagnostics) = validate("fn f( {}\n", Language::Rust) else { + panic!("expected syntax diagnostics"); + }; + assert!(diagnostics.iter().any(|d| d.missing), "{diagnostics:?}"); + } + + #[test] + fn valid_python_parses_clean() { + assert_eq!( + validate("def f():\n return 1\n", Language::Python), + Validation::Clean + ); + } + + #[test] + fn broken_python_is_rejected() { + assert!(matches!( + validate("def f(:\n pass\n", Language::Python), + Validation::Syntax(_) + )); + } + + #[test] + fn valid_typescript_parses_clean() { + assert_eq!( + validate("const x: number = 1;\n", Language::TypeScript), + Validation::Clean + ); + assert_eq!( + validate("const C = () =>
;\n", Language::Tsx), + Validation::Clean + ); + } + + #[test] + fn diagnostics_are_capped() { + let source = "fn f() {\n".to_string() + &" let = ;\n".repeat(400) + "}\n"; + let Validation::Syntax(diagnostics) = validate(&source, Language::Rust) else { + panic!("expected syntax diagnostics"); + }; + assert!(diagnostics.len() <= MAX_DIAGNOSTICS); + } + + #[test] + fn diagnostic_display_names_the_position() { + let d = Diagnostic { + line: 3, + column: 7, + kind: ")".to_string(), + missing: true, + snippet: String::new(), + }; + assert_eq!(d.to_string(), "3:7: missing `)`"); + } +} diff --git a/tests/patch_engine.rs b/tests/patch_engine.rs new file mode 100644 index 0000000..e7dbb53 --- /dev/null +++ b/tests/patch_engine.rs @@ -0,0 +1,378 @@ +//! End-to-end tests for the fuzzy patch engine (`#31`): real files, real +//! writes, and the failure modes that matter — a hunk that cannot anchor +//! or a shadow file that does not parse must leave the file byte-identical. + +use damon_core::patch::{ApplyOptions, PatchError, SyntaxCheck, apply_patch_file, render_patch}; +use std::path::{Path, PathBuf}; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "damon-patch-engine-{tag}-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn write(dir: &Path, name: &str, body: &str) -> PathBuf { + let path = dir.join(name); + std::fs::write(&path, body).unwrap(); + path +} + +fn apply(path: &Path, patch: &str) -> Result { + apply_patch_file(path, patch, &ApplyOptions::default()) +} + +fn contents(path: &Path) -> String { + std::fs::read_to_string(path).unwrap() +} + +/// No temp files may survive a patch, successful or not. +fn assert_no_temp_files(dir: &Path) { + let leftovers: Vec = std::fs::read_dir(dir) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|name| name.contains("damon-patch")) + .collect(); + assert!( + leftovers.is_empty(), + "temp files left behind: {leftovers:?}" + ); +} + +#[test] +fn a_patch_whose_line_numbers_drifted_still_lands() { + // The model read an older file: three lines were added above the target. + let dir = temp_dir("drift"); + let path = write( + &dir, + "main.rs", + "// header one\n// header two\n// header three\nfn main() {\n let a = 1;\n println!(\"{}\", a);\n}\n", + ); + let patch = "\ +@@ -2,3 +2,3 @@ + fn main() { +- let a = 1; ++ let a = 2; + println!(\"{}\", a); +"; + let report = apply(&path, patch).unwrap(); + assert!(report.hunks[0].exact); + assert_eq!(report.hunks[0].line, 4); + assert!(contents(&path).contains("let a = 2;")); + assert!(contents(&path).starts_with("// header one\n")); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_paraphrased_comment_in_the_context_still_anchors() { + // Context comments drift; the edit is about the code line. + let dir = temp_dir("comment-para"); + let path = write( + &dir, + "main.rs", + "fn main() {\n // read the configuration\n let a = load();\n}\n", + ); + let patch = "\ +@@ -1,3 +1,3 @@ + fn main() { + // load the config +- let a = load(); ++ let a = reload(); + } +"; + let report = apply(&path, patch).unwrap(); + assert!(!report.hunks[0].exact); + let text = contents(&path); + assert!(text.contains("let a = reload();")); + // The file's own comment wording survives: the patch never asked to change it. + assert!(text.contains("// read the configuration"), "{text}"); + assert!(!text.contains("// load the config"), "{text}"); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_comment_line_dropped_from_the_file_is_neither_required_nor_resurrected() { + // The hunk's context never saw this comment line; it must be kept once. + let dir = temp_dir("comment-gone"); + let path = write( + &dir, + "main.rs", + "fn main() {\n // added by someone else after the model read the file\n let a = 1;\n println!(\"{}\", a);\n}\n", + ); + let patch = "\ +@@ -1,3 +1,3 @@ + fn main() { +- let a = 1; ++ let a = 3; + println!(\"{}\", a); +"; + apply(&path, patch).unwrap(); + let text = contents(&path); + assert_eq!(text.matches("added by someone else").count(), 1, "{text}"); + assert!(text.contains("let a = 3;"), "{text}"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_rewritten_code_line_is_not_mistaken_for_comment_drift() { + // Same shape as the comment test, but the drift is in code: refuse. + let dir = temp_dir("code-drift"); + let body = "fn main() {\n let total = items.len();\n}\n"; + let path = write(&dir, "main.rs", body); + let patch = "\ +@@ -2,1 +2,1 @@ +- let count = compute(&users); ++ let count = compute(&users, 2); +"; + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::NotAnchored { .. }), "{err}"); + assert_eq!(contents(&path), body); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn one_unanchorable_hunk_leaves_the_file_byte_identical() { + // Hunk 1 is fine, hunk 2 refers to text that is not there. + let dir = temp_dir("all-or-nothing"); + let body = "alpha\nbeta\ngamma\ndelta\n"; + let path = write(&dir, "notes.txt", body); + let patch = "\ +@@ -1,1 +1,1 @@ +-alpha ++ALPHA +@@ -3,2 +3,2 @@ +-nope ++still nope +"; + let err = apply(&path, patch).unwrap_err(); + assert!( + matches!(err, PatchError::NotAnchored { hunk: 2, .. }), + "{err}" + ); + assert_eq!(std::fs::read(&path).unwrap(), body.as_bytes()); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_syntax_error_in_the_shadow_file_is_rejected_with_diagnostics() { + let dir = temp_dir("syntax"); + let body = "fn main() {\n let a = 1;\n}\n"; + let path = write(&dir, "main.rs", body); + let patch = "\ +@@ -2,1 +2,1 @@ +- let a = 1; ++ let = ; +"; + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::Syntax { .. }), "{err}"); + assert!(!err.diagnostics().is_empty()); + assert!(err.to_string().contains("nothing was written"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), body.as_bytes()); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_file_type_without_a_grammar_applies_with_a_warning() { + let dir = temp_dir("no-grammar"); + let path = write(&dir, "notes.txt", "one\ntwo\nthree\n"); + let report = apply(&path, "@@ -2,1 +2,1 @@\n-two\n+TWO\n").unwrap(); + assert!( + matches!(report.syntax, SyntaxCheck::Skipped(_)), + "{:?}", + report.syntax + ); + assert!(!report.warnings.is_empty()); + assert_eq!(contents(&path), "one\nTWO\nthree\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_crlf_file_stays_crlf() { + let dir = temp_dir("crlf"); + let path = write(&dir, "main.rs", "fn main() {\r\n let a = 1;\r\n}\r\n"); + // The patch is LF-only, as a model would emit it. + apply(&path, "@@ -2,1 +2,1 @@\n- let a = 1;\n+ let a = 5;\n").unwrap(); + assert_eq!(contents(&path), "fn main() {\r\n let a = 5;\r\n}\r\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_file_without_a_trailing_newline_keeps_that_shape_on_a_middle_edit() { + let dir = temp_dir("no-eof-newline"); + let path = write(&dir, "notes.txt", "a\nb\nc"); + apply(&path, "@@ -2,1 +2,1 @@\n-b\n+B\n").unwrap(); + assert_eq!(contents(&path), "a\nB\nc"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn rewriting_the_final_line_honours_the_no_newline_marker() { + let dir = temp_dir("no-eof-marker"); + let path = write(&dir, "notes.txt", "a\nb"); + let patch = + "@@ -2,1 +2,1 @@\n-b\n\\ No newline at end of file\n+c\n\\ No newline at end of file\n"; + apply(&path, patch).unwrap(); + assert_eq!(contents(&path), "a\nc"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn rewriting_the_final_line_of_a_file_that_ends_with_a_newline_keeps_it() { + let dir = temp_dir("eof-newline"); + let path = write(&dir, "notes.txt", "a\nb\n"); + apply(&path, "@@ -2,1 +2,1 @@\n-b\n+c\n").unwrap(); + assert_eq!(contents(&path), "a\nc\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_pure_insertion_is_placed_by_its_line_number() { + let dir = temp_dir("insert"); + let path = write(&dir, "notes.txt", "a\nb\nc\n"); + apply(&path, "@@ -1,0 +2,1 @@\n+INSERTED\n").unwrap(); + assert_eq!(contents(&path), "a\nINSERTED\nb\nc\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn several_hunks_apply_in_file_order() { + let dir = temp_dir("multi-hunk"); + let path = write(&dir, "notes.txt", "one\ntwo\nthree\nfour\nfive\n"); + let patch = "\ +@@ -1,1 +1,1 @@ +-one ++ONE +@@ -5,1 +5,1 @@ +-five ++FIVE +"; + let report = apply(&path, patch).unwrap(); + assert_eq!(report.hunks.len(), 2); + assert_eq!(contents(&path), "ONE\ntwo\nthree\nfour\nFIVE\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn out_of_order_hunks_are_refused() { + let dir = temp_dir("out-of-order"); + let body = "a\nb\nc\nd\n"; + let path = write(&dir, "notes.txt", body); + let err = apply(&path, "@@ -4,1 +4,1 @@\n-d\n+D\n@@ -2,1 +2,1 @@\n-b\n+B\n").unwrap_err(); + assert!(matches!(err, PatchError::OutOfOrder { .. }), "{err}"); + assert_eq!(contents(&path), body); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn two_plausible_anchors_are_refused_instead_of_guessed() { + let dir = temp_dir("ambiguous"); + let body = "fn a() {\n one();\n}\n\nfn a() {\n one();\n}\n"; + let path = write(&dir, "main.rs", body); + // Declared line 3 sits exactly between the two identical functions, and + // no byte-exact block exists (the removal line differs slightly). + let patch = "@@ -3,2 +3,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::Ambiguous { .. }), "{err}"); + assert_eq!(contents(&path), body); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn render_patch_writes_nothing() { + let dir = temp_dir("render-only"); + let path = write(&dir, "notes.txt", "a\nb\nc\n"); + let rendered = render_patch( + &path, + &contents(&path), + "@@ -2,1 +2,1 @@\n-b\n+B\n", + &ApplyOptions::default(), + ) + .unwrap(); + assert_eq!(rendered.text, "a\nB\nc\n"); + assert_eq!(contents(&path), "a\nb\nc\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn applying_the_same_patch_twice_does_not_double_apply() { + let dir = temp_dir("twice"); + let path = write(&dir, "notes.txt", "a\nb\nc\n"); + let patch = "@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n"; + apply(&path, patch).unwrap(); + assert_eq!(contents(&path), "a\nB\nc\n"); + // The pre-patch line is gone, so the retry cannot anchor — it is refused, + // and the applied file stays exactly as it is. + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::NotAnchored { .. }), "{err}"); + assert_eq!(contents(&path), "a\nB\nc\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn patching_through_a_symlink_updates_the_target() { + let dir = temp_dir("symlink"); + let target = write(&dir, "real.rs", "fn main() {\n let a = 1;\n}\n"); + let link = dir.join("link.rs"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + apply(&link, "@@ -2,1 +2,1 @@\n- let a = 1;\n+ let a = 9;\n").unwrap(); + assert!( + std::fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_symlink() + ); + assert!(contents(&target).contains("let a = 9;")); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_multi_file_patch_is_refused() { + let dir = temp_dir("multi-file"); + let body = "a\nb\n"; + let path = write(&dir, "notes.txt", body); + let patch = "\ +@@ -1,1 +1,1 @@ +-a ++A +diff --git a/other.txt b/other.txt +@@ -1,1 +1,1 @@ +-x ++y +"; + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::Parse(_)), "{err}"); + assert_eq!(contents(&path), body); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_non_utf8_file_is_reported_not_mangled() { + let dir = temp_dir("binary"); + let path = dir.join("data.txt"); + std::fs::write(&path, [0xff, 0xfe, 0x00, 0x01]).unwrap(); + let err = apply(&path, "@@ -1,1 +1,1 @@\n-a\n+b\n").unwrap_err(); + assert!(matches!(err, PatchError::NotText { .. }), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), vec![0xff, 0xfe, 0x00, 0x01]); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_python_patch_is_syntax_checked_too() { + let dir = temp_dir("python"); + let path = write(&dir, "tool.py", "def f():\n return 1\n"); + let report = apply(&path, "@@ -2,1 +2,1 @@\n- return 1\n+ return 2\n").unwrap(); + assert_eq!(report.syntax, SyntaxCheck::Clean("python")); + assert_eq!(contents(&path), "def f():\n return 2\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} From cdab99be33fa76e472d8a53045cf24fdf4d9db2d Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:01:50 +0900 Subject: [PATCH 2/2] fix(deps): curve25519-dalek 5.1.0 for RUSTSEC-2026-0620 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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: 정인권 --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ad87384..ff350a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -539,9 +539,9 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" dependencies = [ "cfg-if", "cpufeatures 0.3.1",