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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 |
Expand Down
1 change: 1 addition & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ agent CLI subprocess (stream-json / NDJSON / HTTP+SSE)
| `src/prompts.rs` | 프롬프트 라이브러리(`<workspace>/.damon/prompts/`, `<data_dir>/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` |
Expand Down
65 changes: 65 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
87 changes: 85 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading