diff --git a/README.md b/README.md
index 71435bf..3917f4b 100644
--- a/README.md
+++ b/README.md
@@ -586,8 +586,10 @@ claude`.
project's allowlist for the next session.
- **Timeline**: if the session has snapshots, a slider picks a point in time
and the file list shows only what changed after it (read-only).
-- **Conflicts**: files you changed yourself since the session started are
- flagged in the list and above the diff, and are never overwritten.
+- **Conflicts and merges**: files you changed yourself since the session
+ started are flagged in the list and above the diff, and are never
+ overwritten. When your changes and the agent's are in different lines of a
+ text file, the file is marked as a merge instead and applying keeps both.
- **Apply Selected** (⌘↩), **Apply All** (⇧⌘↩), **Undo** (⌥⌘Z) and
**Discard** (⌘⌫). Each apply can be undone in one step. Space toggles the
selected file.
@@ -1276,9 +1278,30 @@ point Mudroom at a file outside the session.
### How apply stays safe
For each path, Mudroom checks that the real project still has exactly what the
-session started from. If you edited `README.md` while the agent was working,
-`apply` reports a conflict for that file and leaves it alone; the rest still
-applies. Other rules:
+session started from. If you edited `README.md` while the agent was working
+(or another session's apply changed it), Mudroom tries a three-way merge of
+the session's base, your current file and the agent's copy:
+
+- If the two sets of changes are in different lines, the merged file is
+ applied like any other change. `apply` prints it as `merged`, the review
+ marks it before you apply, and `undo` puts back your file exactly as it was
+ before the apply. A later apply of the same session merges again instead of
+ writing the agent's copy over it.
+- If they change the same lines, or lines right next to each other, it's a
+ conflict: nothing is written to that file and the rest still applies. The
+ same goes for permissions changed on both sides.
+- Only regular text files are merged. A binary file, a symlink, a mode-only
+ change, a change of type, a file one side deleted and the other edited, a
+ file both sides added, files over 4 MB and anything inside `.git` stay
+ conflicts.
+- Line endings are part of each line, so CRLF files stay CRLF and a missing
+ final newline stays missing. Converting a whole file between CRLF and LF on
+ one side touches every line, so it conflicts with any edit on the other.
+- Selected hunks merge the same way: the base plus the hunks you picked is
+ merged into your current file, so a hunk still goes in when you changed a
+ different part of the file.
+
+Other rules:
- Files are written to a temp name and renamed into place.
- Directories are removed with `rmdir`, so a directory that gained a file on
@@ -1589,8 +1612,10 @@ safe](#how-apply-stays-safe).
Apply checks each file in your project against the session's starting copy.
-A file you changed is reported as a conflict and left alone; the rest still
-applies.
+If you changed a text file in different lines from the agent, apply merges
+the two and keeps both. If you changed the same or neighbouring lines, the file is reported
+as a conflict and left alone; the rest still applies. The same happens when
+two sessions on one project edit the same file and you apply both.
diff --git a/Sources/MudroomApp/DiffView.swift b/Sources/MudroomApp/DiffView.swift
index b3d9002..abd9bba 100644
--- a/Sources/MudroomApp/DiffView.swift
+++ b/Sources/MudroomApp/DiffView.swift
@@ -21,10 +21,19 @@ struct FileDetailView: View {
.padding(.vertical, 10)
Divider()
}
+ if entry.merges && !entry.isApplied && !entry.readOnly {
+ Banner(style: .info, title: "This file also changed in your project",
+ detail: "The changes are in different lines, so applying merges them: your version keeps its changes and gets the agent's. Undo puts your version back.")
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ Divider()
+ }
if let conflict = entry.conflict {
Banner(style: .warning,
title: FileEntry.conflictTitle(conflict),
- detail: "Mudroom won't overwrite your version, so this change can't be applied. Copy the parts you want by hand.")
+ detail: conflict.contains("overlap the agent's")
+ ? "Your version and the agent's change the same or neighbouring lines, so Mudroom can't merge them. Copy the parts you want by hand."
+ : "Mudroom won't overwrite your version, so this change can't be applied. Copy the parts you want by hand.")
.help(conflict)
.padding(.horizontal, 14)
.padding(.vertical, 10)
diff --git a/Sources/MudroomApp/ReviewModel.swift b/Sources/MudroomApp/ReviewModel.swift
index 9d301d4..9b6b3b1 100644
--- a/Sources/MudroomApp/ReviewModel.swift
+++ b/Sources/MudroomApp/ReviewModel.swift
@@ -389,13 +389,15 @@ final class ReviewModel {
// contents aren't rows.
let rows = Set(baseFiles.map(\.path))
let n = report.applied.filter { rows.contains($0) }.count
+ let m = report.merged.count
let c = report.conflicts.count
if n == 0 && c == 0 {
lastResult = .init(style: .info, title: "Nothing to apply", detail: nil, offerUndo: false)
} else {
let files = n == 1 ? "1 file" : "\(n) files"
- let detail = c == 0 ? "Undo puts the previous versions back."
- : "\(c) \(c == 1 ? "path was" : "paths were") left alone because of conflicts."
+ let merged = m == 0 ? "" : "\(m == 1 ? "1 file was" : "\(m) files were") merged with changes in your project. "
+ let detail = merged + (c == 0 ? "Undo puts the previous versions back."
+ : "\(c) \(c == 1 ? "path was" : "paths were") left alone because of conflicts.")
lastResult = .init(style: c == 0 ? .success : .warning, title: "\(verb) \(files)",
detail: detail, offerUndo: n > 0)
}
diff --git a/Sources/MudroomApp/ReviewView.swift b/Sources/MudroomApp/ReviewView.swift
index b7922bf..0877d62 100644
--- a/Sources/MudroomApp/ReviewView.swift
+++ b/Sources/MudroomApp/ReviewView.swift
@@ -262,6 +262,10 @@ struct FileRow: View {
.help(entry.conflict ?? "")
} else if entry.isApplied {
Image(systemName: "checkmark.circle.fill").foregroundStyle(.green).help("Applied")
+ } else if entry.merges {
+ Image(systemName: "arrow.triangle.merge")
+ .foregroundStyle(.blue)
+ .help("Also changed in your project, in other lines. Applying merges both.")
} else if !entry.appliedHunks.isEmpty {
Text("\(entry.appliedHunks.count)/\(entry.hunks.count)")
.font(.system(size: 10, weight: .semibold)).foregroundStyle(.green)
diff --git a/Sources/MudroomCore/Applier.swift b/Sources/MudroomCore/Applier.swift
index 6cb168e..f538e86 100644
--- a/Sources/MudroomCore/Applier.swift
+++ b/Sources/MudroomCore/Applier.swift
@@ -26,6 +26,10 @@ public struct RollbackEntry: Codable, Sendable, Equatable {
public var pending: Bool?
/// This entry has been rolled back.
public var undone: Bool?
+ /// The file was written as a three-way merge of base/, the project's
+ /// copy and work/, so it also holds changes that aren't this session's.
+ /// A later apply merges again instead of writing work/ over it.
+ public var merged: Bool?
public init(path: String, prior: FileNode, applied: FileNode, backup: String? = nil, hunks: [Int]? = nil) {
self.path = path
@@ -51,7 +55,7 @@ public struct RollbackManifest: Codable, Sendable {
public struct PathIssue: Sendable, Equatable, CustomStringConvertible {
public let path: String
public let reason: String
- public var description: String { "\(TextLines.visible(path)): \(reason)" }
+ public var description: String { "\(TextLines.visible(path)): \(TextLines.visible(reason))" }
public init(path: String, reason: String) {
self.path = path
@@ -61,6 +65,9 @@ public struct PathIssue: Sendable, Equatable, CustomStringConvertible {
public struct ApplyReport: Sendable {
public var applied: [String] = []
+ /// Paths in `applied` that had changed in the project too, written as a
+ /// three-way merge: the project's changes kept, the agent's added.
+ public var merged: [String] = []
/// The project already matched the agent's version.
public var alreadyApplied: [String] = []
/// Refused because the real project (or the agent's copy) changed.
@@ -325,8 +332,8 @@ public struct Applier {
}
}
- // Per-hunk paths are planned separately (below).
- var hunkPlans: [HunkPlan] = []
+ // Per-hunk paths are planned separately (below), and so are merges.
+ var textPlans: [TextPlan] = []
for (path, selected) in hunkSel.sorted(by: { $0.key < $1.key }) {
guard let change = changes.first(where: { $0.path == path }) else {
if !report.skipped.contains(where: { $0.path == path }) && !report.conflicts.contains(where: { $0.path == path }) {
@@ -334,7 +341,7 @@ public struct Applier {
}
continue
}
- if let plan = try planHunks(change, selected: selected, written: written, report: &report) { hunkPlans.append(plan) }
+ if let plan = try planHunks(change, selected: selected, written: written, report: &report) { textPlans.append(plan) }
}
changes.removeAll { hunkSel[$0.path] != nil }
@@ -385,7 +392,7 @@ public struct Applier {
for (change, real) in zip(candidates, reals) {
if renamedAway.contains(change.path) {
// Checked along with its rename partner.
- if real != change.before && written[change.path]?.applied != real {
+ if real != change.before && !Self.ownWrite(written[change.path], real) {
report.conflicts.append(PathIssue(path: change.path, reason: conflictReason(change, real)))
renames = renames.filter { $0.value.path != change.path }
renamedAway.remove(change.path)
@@ -409,10 +416,25 @@ public struct Applier {
}
if real == want {
report.alreadyApplied.append(change.path)
- } else if !(real == change.before || written[change.path]?.applied == real) {
- report.conflicts.append(PathIssue(path: change.path, reason: conflictReason(change, real)))
- } else {
+ } else if real == change.before || Self.ownWrite(written[change.path], real) {
planned.append((change, real))
+ } else {
+ // Changed in the project too (by you, or by another session's
+ // apply). A text file can still go in if the changes don't overlap.
+ do {
+ switch try mergeWhole(change, real: real) {
+ case nil:
+ report.conflicts.append(PathIssue(path: change.path, reason: conflictReason(change, real)))
+ case .unchanged?:
+ report.alreadyApplied.append(change.path)
+ case .overlap(let why)?:
+ report.conflicts.append(PathIssue(path: change.path, reason: why))
+ case .merged(let content, let mode)?:
+ textPlans.append(TextPlan(change: change, real: real, content: content, mode: mode, hunks: nil, merged: true))
+ }
+ } catch {
+ report.conflicts.append(PathIssue(path: change.path, reason: "\(error)"))
+ }
}
}
// A repository's .git goes in whole or not at all. Half of one (the
@@ -430,14 +452,15 @@ public struct Applier {
renamedAway.remove(renames[added]!.path)
renames[added] = nil
}
- for (change, _) in planned {
+ for change in planned.map(\.change) + textPlans.filter(\.merged).map(\.change) {
if let risk = Differ.hostRisk(change.path) { report.warnings.append(PathIssue(path: change.path, reason: risk)) }
}
if dryRun {
- report.applied = planned.map(\.change.path) + Array(renamedAway).sorted() + hunkPlans.map(\.change.path)
+ report.applied = planned.map(\.change.path) + Array(renamedAway).sorted() + textPlans.map(\.change.path)
+ report.merged = textPlans.filter(\.merged).map(\.change.path).sorted()
return report
}
- guard !planned.isEmpty || !hunkPlans.isEmpty else { return report }
+ guard !planned.isEmpty || !textPlans.isEmpty else { return report }
let bundle = try makeBundleDirectory()
report.bundle = bundle
@@ -549,8 +572,9 @@ public struct Applier {
}
}
- // 2b. Partial files: write the base with the chosen hunks applied.
- for plan in hunkPlans {
+ // 2b. Files built in memory: the base with the chosen hunks applied,
+ // or a three-way merge with the project's copy.
+ for plan in textPlans {
run(plan.change.path) {
var cache: [String: String?] = [:]
if let bad = unsafeAncestor(of: plan.change.path, cache: &cache) {
@@ -560,10 +584,25 @@ public struct Applier {
stagedCount += 1
let staged = staging.appendingPathComponent(String(stagedCount))
try plan.content.write(to: staged)
- let i = try record(try backup(plan.change.path, prior: plan.real, applied: .absent, bundle: bundle))
- try placeFile(from: staged, to: target, mode: plan.mode & ~0o6000, consume: true)
- entries[i].hunks = plan.hunks
+ // The content was built from the project's copy as read
+ // above, and undo restores the backup: both must be that copy.
+ let changedHere = MudroomError.invalid("changed in the project while applying; nothing written, try again")
+ guard try FileNode.read(at: target) == plan.real else { throw changedHere }
+ // setuid/setgid stay only when the file keeps the project's own mode.
+ let mode = plan.mode == plan.real.mode ? plan.mode : plan.mode & ~0o6000
+ // What the write will leave, so undo after a crash right
+ // after it still knows the file.
+ let expected = FileNode.file(mode: mode, size: Int64(plan.content.count), sha256: SafeFS.sha256(plan.content))
+ var entry = try backup(plan.change.path, prior: plan.real, applied: expected, bundle: bundle)
+ if let rel = entry.backup, try FileNode.read(at: bundle.appendingPathComponent(rel)).sha256 != plan.real.sha256 {
+ throw changedHere
+ }
+ entry.hunks = plan.hunks
+ entry.merged = plan.merged ? true : nil
+ let i = try record(entry)
+ try placeFile(from: staged, to: target, mode: mode, consume: true)
done(i, applied: try FileNode.read(at: target))
+ if plan.merged { report.merged.append(plan.change.path) }
}
}
@@ -573,6 +612,7 @@ public struct Applier {
}
try? fm.removeItem(at: staging)
report.applied.sort()
+ report.merged.sort()
return report
}
@@ -620,26 +660,41 @@ public struct Applier {
// MARK: - Hunks
- struct HunkPlan {
+ /// A file built in memory: the base with some hunks applied, or a
+ /// three-way merge with the project's copy.
+ struct TextPlan {
let change: Change
+ /// The project's copy the content was built from.
let real: FileNode
let content: Data
let mode: UInt16
/// Hunk ids present after the write; nil when that is all of them.
let hunks: [Int]?
+ /// Built by merging with a project copy that changed since the base.
+ let merged: Bool
+ }
+
+ /// True when `real` is what this session last wrote at a path, and that
+ /// was the session's own content (base or work, or base plus hunks), not
+ /// a merge holding someone else's changes.
+ static func ownWrite(_ last: RollbackEntry?, _ real: FileNode) -> Bool {
+ guard let last, last.applied == real else { return false }
+ return last.merged != true
}
/// Base and work bytes of a modified text file, read without following
- /// symlinks; the work bytes are checked against the diff's hash.
- func texts(for change: Change) throws -> (Data, Data)? {
+ /// symlinks; the work bytes are checked against the diff's hash. Reads
+ /// at most `limit` bytes of each, so a file that grew past it since the
+ /// diff fails the hash check instead of being read whole.
+ func texts(for change: Change, limit: Int = .max) throws -> (Data, Data)? {
guard change.kind == .modified, case .file = change.before, case .file(_, _, let sha) = change.after else { return nil }
- let b = try SafeFS.readBeneath(handle.base, change.path)
+ let b = try SafeFS.readBeneath(handle.base, change.path, limit: limit)
#if os(Windows)
- let w = try SafeFS.readBeneath(handle.work, change.path)
+ let w = try SafeFS.readBeneath(handle.work, change.path, limit: limit)
#else
let fd = try SafeFS.openBeneath(handle.work, change.path)
defer { close(fd) }
- let w = try SafeFS.readAll(fd, limit: .max)
+ let w = try SafeFS.readAll(fd, limit: limit)
#endif
guard SafeFS.sha256(w) == sha else {
throw MudroomError.invalid("\(change.path) changed in the agent's copy since the diff was taken; review again")
@@ -659,18 +714,84 @@ public struct Applier {
/// partial apply. Empty when the project still has the base version.
public func appliedHunks(for change: Change, hunks known: [Hunk]? = nil) throws -> Set {
let real = try FileNode.read(at: project.appendingPathComponent(change.path))
- if real == Self.sanitized(change.after) {
- guard let hunks = try known ?? hunks(for: change) else { return [] }
- return Set(hunks.map(\.id))
- }
if real == change.before { return [] }
- guard let last = lastWritten(change.path), last.applied == real, let ids = last.hunks else { return [] }
- return Set(ids)
+ guard let hunks = try known ?? hunks(for: change) else { return [] }
+ return Self.hunksPresent(change, hunks: hunks, real: real, last: lastWritten(change.path))
+ }
+
+ /// Which of `hunks` the project copy `real` has, going by what this
+ /// session wrote last (`last`).
+ static func hunksPresent(_ change: Change, hunks: [Hunk], real: FileNode, last: RollbackEntry?) -> Set {
+ if real == sanitized(change.after) { return Set(hunks.map(\.id)) }
+ guard real != change.before, let last, last.applied == real else { return [] }
+ if let ids = last.hunks { return Set(ids) }
+ // A whole-file merge has every hunk in it.
+ return last.merged == true ? Set(hunks.map(\.id)) : []
+ }
+
+ // MARK: - Merge
+
+ /// What merging one file came to.
+ enum MergeOutcome {
+ /// Clean: write this content with this mode.
+ case merged(Data, mode: UInt16)
+ /// The merge is what the project already has.
+ case unchanged
+ /// Both sides changed the same lines (or the permissions) differently.
+ case overlap(String)
+ }
+
+ /// Whether `change` can be merged with the project copy `real` at all:
+ /// a modified regular file on all three sides, outside .git, no larger
+ /// than the review shows as text. Anything else stays a conflict.
+ static func mergeable(_ change: Change, real: FileNode) -> Bool {
+ guard change.kind == .modified, gitDirectory(of: change.path) == nil,
+ case .file(_, let b, _) = change.before, case .file(_, let w, _) = change.after,
+ case .file(_, let p, _) = real else { return false }
+ return max(b, w, p) <= ReviewSnapshot.maxTextBytes
+ }
+
+ /// The whole of work/ merged into the project's copy of a file that
+ /// changed there too. Nil when it can't be merged (see `mergeable`).
+ func mergeWhole(_ change: Change, real: FileNode) throws -> MergeOutcome? {
+ guard Self.mergeable(change, real: real),
+ let (b, w) = try texts(for: change, limit: Int(ReviewSnapshot.maxTextBytes) + 1) else { return nil }
+ return try merge(change, real: real, base: TextLines(b), theirs: TextLines(w), theirsMode: change.after.mode ?? 0o644)
+ }
+
+ /// Three-way merge of base, the project's copy (`real`, read here and
+ /// checked against its hash) and `theirs`, what this session would write.
+ /// Nil when the project's copy isn't text.
+ func merge(_ change: Change, real: FileNode, base: TextLines, theirs: TextLines, theirsMode: UInt16) throws -> MergeOutcome? {
+ guard case .file(let realMode, _, let realSHA) = real, let baseMode = change.before.mode else { return nil }
+ let ours = try SafeFS.readBeneath(project, change.path, limit: Int(ReviewSnapshot.maxTextBytes) + 1)
+ guard SafeFS.sha256(ours) == realSHA else {
+ throw MudroomError.invalid("changed in the project while applying; nothing written, try again")
+ }
+ if DiffRenderer.looksBinary(ours) { return nil }
+ // Permissions merge the same way: whichever side changed them wins.
+ let mode: UInt16
+ if theirsMode & 0o7777 == baseMode & 0o7777 {
+ mode = realMode
+ } else if realMode & 0o7777 == baseMode & 0o7777 || realMode & 0o7777 == theirsMode & 0o7777 {
+ mode = theirsMode
+ } else {
+ return .overlap("project changed since the session started, and both the project and the agent changed its permissions; apply it by hand")
+ }
+ switch LineDiff.merge(base: base, ours: TextLines(ours), theirs: theirs) {
+ case .clean(let lines):
+ let content = lines.data
+ if content == ours && mode & 0o7777 == realMode & 0o7777 { return .unchanged }
+ return .merged(content, mode: mode)
+ case .conflict(let ranges):
+ let more = ranges.count > 1 ? " (and \(ranges.count - 1) more place\(ranges.count > 2 ? "s" : ""))" : ""
+ return .overlap("project changed since the session started, and its changes overlap the agent's near line \(ranges[0].lowerBound + 1)\(more); merge it by hand")
+ }
}
/// Checks one per-hunk selection and computes the file to write. Returns
/// nil (after noting why in `report`) when there is nothing to write.
- func planHunks(_ change: Change, selected: Set, written: [String: RollbackEntry], report: inout ApplyReport) throws -> HunkPlan? {
+ func planHunks(_ change: Change, selected: Set, written: [String: RollbackEntry], report: inout ApplyReport) throws -> TextPlan? {
let path = change.path
guard let (baseData, workData) = try texts(for: change) else {
report.skipped.append(PathIssue(path: path, reason: "not a modified text file; apply the whole path instead"))
@@ -694,10 +815,38 @@ public struct Applier {
} else if real == Self.sanitized(change.after) {
report.alreadyApplied.append(path)
return nil
- } else if let last = written[path], last.applied == real {
- previous = Set(last.hunks ?? [])
+ } else if Self.ownWrite(written[path], real) {
+ previous = Set(written[path]?.hunks ?? [])
} else {
- report.conflicts.append(PathIssue(path: path, reason: conflictReason(change, real)))
+ // Changed in the project too: merge base plus the wanted hunks
+ // into the project's copy, if the changes don't overlap.
+ guard Self.mergeable(change, real: real) else {
+ report.conflicts.append(PathIssue(path: path, reason: conflictReason(change, real)))
+ return nil
+ }
+ let earlier = Self.hunksPresent(change, hunks: hunks, real: real, last: written[path])
+ let wanted = earlier.union(selected)
+ let partial = LineDiff.apply(hunks, selected: wanted, base: baseLines, work: workLines)
+ let complete = partial.data == workData
+ let theirsMode = (complete ? change.after.mode : change.before.mode) ?? 0o644
+ let outcome: MergeOutcome?
+ do {
+ outcome = try merge(change, real: real, base: baseLines, theirs: partial, theirsMode: theirsMode)
+ } catch {
+ report.conflicts.append(PathIssue(path: path, reason: "\(error)"))
+ return nil
+ }
+ switch outcome {
+ case nil:
+ report.conflicts.append(PathIssue(path: path, reason: conflictReason(change, real)))
+ case .unchanged?:
+ report.alreadyApplied.append(path)
+ case .overlap(let why)?:
+ report.conflicts.append(PathIssue(path: path, reason: why))
+ case .merged(let content, let mode)?:
+ return TextPlan(change: change, real: real, content: content, mode: mode,
+ hunks: complete ? nil : wanted.sorted(), merged: true)
+ }
return nil
}
let wanted = previous.union(selected)
@@ -707,9 +856,9 @@ public struct Applier {
}
let content = LineDiff.apply(hunks, selected: wanted, base: baseLines, work: workLines).data
let complete = content == workData
- return HunkPlan(change: change, real: real, content: content,
+ return TextPlan(change: change, real: real, content: content,
mode: (complete ? change.after.mode : change.before.mode) ?? 0o644,
- hunks: complete ? nil : wanted.sorted())
+ hunks: complete ? nil : wanted.sorted(), merged: false)
}
/// Applies some hunks of one modified text file. Shorthand for
diff --git a/Sources/MudroomCore/LineDiff.swift b/Sources/MudroomCore/LineDiff.swift
index c05b378..2e79a99 100644
--- a/Sources/MudroomCore/LineDiff.swift
+++ b/Sources/MudroomCore/LineDiff.swift
@@ -110,6 +110,15 @@ public struct Hunk: Sendable, Equatable, Identifiable {
}
}
+/// What a three-way merge (`LineDiff.merge`) came to.
+public enum MergeResult: Sendable, Equatable {
+ /// Both sides' changes in one file.
+ case clean(TextLines)
+ /// Base line ranges (0-based, half-open) that both sides changed in
+ /// different ways. Nothing is merged.
+ case conflict([Range])
+}
+
public enum LineDiff {
/// Past this many edits Myers gives up and reports the rest of the
/// differing region as one replaced block. Keeps worst-case time bounded
@@ -305,6 +314,51 @@ public enum LineDiff {
return apply(hunks(base: b, work: w, context: context), selected: selected, base: b, work: w).data
}
+ /// Three-way merge of two edits of `base`, the way diff3 does it. A
+ /// block changed on one side only takes that side's lines; a block both
+ /// sides changed in the same way is taken once. Blocks both sides
+ /// changed differently are a conflict, and so are blocks that touch (no
+ /// unchanged line between them), since their order would be a guess.
+ /// Line terminators are part of a line, so switching CRLF to LF or
+ /// adding a final newline is a change like any other.
+ public static func merge(base: TextLines, ours: TextLines, theirs: TextLines) -> MergeResult {
+ let a = changes(base.lines, ours.lines), b = changes(base.lines, theirs.lines)
+ var out: [Data] = []
+ var conflicts: [Range] = []
+ var i = 0, j = 0, pos = 0
+ while i < a.count || j < b.count {
+ // A group starts at the first block left on either side and takes
+ // in every block, from either side, that overlaps or touches it.
+ let lo = min(i < a.count ? a[i].old.lowerBound : .max, j < b.count ? b[j].old.lowerBound : .max)
+ var hi = lo, ea = i, eb = j
+ while true {
+ if ea < a.count, a[ea].old.lowerBound <= hi { hi = max(hi, a[ea].old.upperBound); ea += 1; continue }
+ if eb < b.count, b[eb].old.lowerBound <= hi { hi = max(hi, b[eb].old.upperBound); eb += 1; continue }
+ break
+ }
+ // One side's lines for base lines lo.., new: Range)>, _ text: TextLines) -> ArraySlice {
+ guard let f = blocks.first, let l = blocks.last else { return base.lines[lo.. String {
var out: [String] = []
diff --git a/Sources/MudroomCore/ReviewData.swift b/Sources/MudroomCore/ReviewData.swift
index fdfe13a..64d3d22 100644
--- a/Sources/MudroomCore/ReviewData.swift
+++ b/Sources/MudroomCore/ReviewData.swift
@@ -48,6 +48,9 @@ public struct FileEntry: Identifiable, Sendable {
public var isApplied: Bool
/// Hunks already in the project from an earlier partial apply.
public var appliedHunks: Set
+ /// The project changed this file too, in other lines: applying merges
+ /// both (see `Applier`). Never set together with `conflict`.
+ public var merges = false
/// Shown for a timeline comparison (snapshot to work): look, don't apply.
public var readOnly = false
public let added: Int
@@ -259,6 +262,7 @@ public struct ReviewSnapshot: Sendable {
let preflight = try applier.preflight(diff: diff)
let conflicts = Dictionary(preflight.conflicts.map { ($0.path, $0.reason) }, uniquingKeysWith: { a, _ in a })
let applied = Set(preflight.alreadyApplied)
+ let merges = Set(preflight.merged)
let written = applier.lastWrittenIndex()
let all = visibleRows(diff.changes)
@@ -274,16 +278,15 @@ public struct ReviewSnapshot: Sendable {
guard case .text(let hunks, true) = content else { return (content, []) }
// Hunks already in the project from an earlier partial apply.
let real = (try? FileNode.read(at: handle.project.appendingPathComponent(change.path))) ?? .absent
- if real == Applier.sanitized(change.after) { return (content, Set(hunks.map(\.id))) }
- if real == change.before { return (content, []) }
- if let last = written[change.path], last.applied == real { return (content, Set(last.hunks ?? [])) }
- return (content, [])
+ return (content, Applier.hunksPresent(change, hunks: hunks, real: real, last: written[change.path]))
}
var files: [FileEntry] = []
files.reserveCapacity(rows.count)
for (change, (content, appliedHunks)) in zip(rows, loaded) {
- files.append(FileEntry(change: change, content: content, conflict: conflicts[change.path],
- isApplied: applied.contains(change.path), appliedHunks: appliedHunks))
+ var entry = FileEntry(change: change, content: content, conflict: conflicts[change.path],
+ isApplied: applied.contains(change.path), appliedHunks: appliedHunks)
+ entry.merges = merges.contains(change.path)
+ files.append(entry)
}
files.sort { ($0.group, $0.path) < ($1.group, $1.path) }
var snap = ReviewSnapshot(files: files, hiddenDeletedDirectories: hiddenDeleted,
diff --git a/Sources/MudroomCore/TerminalReview.swift b/Sources/MudroomCore/TerminalReview.swift
index 33341d5..f1c897c 100644
--- a/Sources/MudroomCore/TerminalReview.swift
+++ b/Sources/MudroomCore/TerminalReview.swift
@@ -10,6 +10,9 @@ public struct TerminalReview: Sendable {
public var selected: Bool
/// Set when a dry run reports a conflict; such paths start unselected.
public var conflict: String?
+ /// The project changed this file too, in other lines: an apply
+ /// merges both (from a dry run, like `conflict`).
+ public var merge = false
public var applied = false
/// Set once the file is opened in the hunk view (see `showHunks`).
/// From then on `selectedHunks` decides what goes in.
@@ -71,11 +74,11 @@ public struct TerminalReview: Sendable {
/// One line of feedback under the list ("applied 3 paths").
public var message: String?
- public init(changes: [Change], conflicts: [String: String] = [:]) {
+ public init(changes: [Change], conflicts: [String: String] = [:], merges: Set = []) {
// Conflicts, unreadable entries and files the host acts on start unselected.
items = changes.map {
Item(change: $0, selected: conflicts[$0.path] == nil && $0.kind != .unreadable && Differ.reviewNote($0.path) == nil,
- conflict: conflicts[$0.path])
+ conflict: conflicts[$0.path], merge: merges.contains($0.path))
}
}
@@ -143,6 +146,7 @@ public struct TerminalReview: Sendable {
}
if let c = conflicts[items[i].path] {
items[i].conflict = c
+ items[i].merge = false
items[i].selected = false
items[i].selectedHunks = []
}
@@ -309,6 +313,7 @@ public struct TerminalReview: Sendable {
if !it.appliedHunks.isEmpty { line += " (\(it.appliedHunks.count) of \(hunks.count) hunks applied)" }
}
if let c = it.conflict, !it.applied { line += " CONFLICT: \(c)" }
+ else if it.merge && !it.applied { line += " MERGE: changed in the project too, in other lines; apply keeps both" }
var s = Self.clip(line, width)
if i == cursor { s = style(s.padding(toLength: max(s.count, width), withPad: " ", startingAt: 0), .cursor) }
else if it.conflict != nil && !it.applied { s = style(s, .deleted) }
diff --git a/Sources/mudroom/Mudroom.swift b/Sources/mudroom/Mudroom.swift
index 02d5269..84781eb 100644
--- a/Sources/mudroom/Mudroom.swift
+++ b/Sources/mudroom/Mudroom.swift
@@ -320,11 +320,17 @@ struct Hunks: ParsableCommand {
throw MudroomError.invalid("\(path) is not a modified text file; it can only be applied as a whole")
}
let applied = try applier.appliedHunks(for: change)
+ let dry = try applier.preflight(paths: [path], diff: diff)
print("--- a/\(TextLines.visible(path))\n+++ b/\(TextLines.visible(path))")
print(LineDiff.numberedText(hunks))
if !applied.isEmpty {
print("\nalready applied: \(applied.sorted().map(String.init).joined(separator: ", "))")
}
+ if dry.merged.contains(path) {
+ print("\nthe project changed this file too, in other lines; apply merges the hunks into your version")
+ } else if let c = dry.conflicts.first(where: { $0.path == path }) {
+ print("\nconflict: \(TextLines.visible(c.reason))")
+ }
} catch { fail(error) }
}
}
@@ -379,8 +385,10 @@ struct Apply: ParsableCommand {
abstract: "Copy approved changes into the real project.",
discussion: """
A path is written only if the real project still matches the state the \
- agent started from; otherwise it is reported as a conflict and left alone. \
- Overwritten files are saved in a rollback bundle for `mudroom undo`.
+ agent started from. A text file that changed in the project too is merged \
+ when the two sets of changes touch different lines; anything else is \
+ reported as a conflict and left alone. Overwritten files are saved in a \
+ rollback bundle for `mudroom undo`.
""")
@Argument(help: "Session id, unique prefix, or 'last'.")
@@ -432,14 +440,22 @@ struct Apply: ParsableCommand {
}
} catch { fail(error) }
- for p in report.applied { print("applied \(TextLines.visible(p))") }
+ let merged = Set(report.merged)
+ for p in report.applied {
+ if merged.contains(p) {
+ print("merged \(TextLines.visible(p)) (changed in the project too; both sets of changes kept)")
+ } else {
+ print("applied \(TextLines.visible(p))")
+ }
+ }
for w in report.warnings { print("note \(TextLines.visible(w.path)): check it; it \(w.reason)") }
for p in report.alreadyApplied { print("unchanged \(TextLines.visible(p)) (project already matches)") }
for i in report.skipped { print("skipped \(i)") }
for i in report.conflicts { print("CONFLICT \(i)") }
if !report.applied.isEmpty {
try handle.setStatus(.applied)
- print("\n\(report.applied.count) applied. Undo with: mudroom undo \(handle.session.id)")
+ let note = merged.isEmpty ? "" : " (\(merged.count) merged)"
+ print("\n\(report.applied.count) applied\(note). Undo with: mudroom undo \(handle.session.id)")
} else if report.conflicts.isEmpty {
print("nothing to apply")
}
diff --git a/Sources/mudroom/Review.swift b/Sources/mudroom/Review.swift
index 5b922b1..1a6e8a7 100644
--- a/Sources/mudroom/Review.swift
+++ b/Sources/mudroom/Review.swift
@@ -19,7 +19,8 @@ struct Review: ParsableCommand {
discussion: """
Keys: up/down (or j/k) move, space toggles, a toggles all, enter shows the diff, \
x applies the selected paths (after a y/N prompt), q quits. Conflicting paths \
- start unselected. For a modified text file the diff is split into hunks: j/k \
+ start unselected. A file that changed in the project too, in other lines, \
+ is marked MERGE: applying it keeps both sets of changes. For a modified text file the diff is split into hunks: j/k \
move between them, space toggles one, a/n select all or none, q goes back. A \
file with only some hunks selected shows [~] and is applied hunk by hunk. \
`mudroom hunks` and `apply --hunks` do the same from scripts.
@@ -45,7 +46,8 @@ struct Review: ParsableCommand {
let dry = try applier.preflight(diff: diff)
reviewed = ReviewedChanges(diff.changes + diff.gitMetadataChanges)
try? reviewed.save(handle)
- state = TerminalReview(changes: diff.changes, conflicts: Dictionary(dry.conflicts.map { ($0.path, $0.reason) }) { a, _ in a })
+ state = TerminalReview(changes: diff.changes, conflicts: Dictionary(dry.conflicts.map { ($0.path, $0.reason) }) { a, _ in a },
+ merges: Set(dry.merged))
let excluded = diff.excludedNames.map(TextLines.visible)
if !excluded.isEmpty {
state.message = "not applied, on the exclude list: " + excluded.prefix(6).joined(separator: ", ")
@@ -107,6 +109,7 @@ struct Review: ParsableCommand {
state.markApplied(report.applied + report.alreadyApplied, conflicts: conflicts, hunks: nowApplied)
if !report.applied.isEmpty { try handle.setStatus(.applied) }
var parts = ["applied \(report.applied.count)"]
+ if !report.merged.isEmpty { parts.append("\(report.merged.count) merged with project changes") }
if !report.conflicts.isEmpty { parts.append("\(report.conflicts.count) conflict(s)") }
if !report.skipped.isEmpty { parts.append("\(report.skipped.count) skipped") }
state.message = parts.joined(separator: ", ") + ". Undo with: mudroom undo \(handle.session.id)"
diff --git a/Tests/MudroomCoreTests/HunkApplyTests.swift b/Tests/MudroomCoreTests/HunkApplyTests.swift
index 28cee6e..90d0054 100644
--- a/Tests/MudroomCoreTests/HunkApplyTests.swift
+++ b/Tests/MudroomCoreTests/HunkApplyTests.swift
@@ -89,13 +89,14 @@ struct HunkApplyTests {
#expect(try Applier(handle: f.handle).apply(paths: ["src/file.txt"]).alreadyApplied == ["src/file.txt"])
}
- @Test("a human edit to the file is a conflict and nothing is written")
+ @Test("a human edit to the hunk's lines is a conflict and nothing is written")
func conflict() throws {
let f = try fixture()
- try write(Self.base + "mine\n", to: target(f))
+ let mine = Self.base.replacingOccurrences(of: "line 3\n", with: "mine\n")
+ try write(mine, to: target(f))
let report = try Applier(handle: f.handle).applyHunks(path: "src/file.txt", hunks: [1])
#expect(report.conflicts.map(\.path) == ["src/file.txt"])
- #expect(try read(target(f)) == Self.base + "mine\n")
+ #expect(try read(target(f)) == mine)
#expect(report.bundle == nil)
}
diff --git a/Tests/MudroomCoreTests/MergeTests.swift b/Tests/MudroomCoreTests/MergeTests.swift
new file mode 100644
index 0000000..c33509c
--- /dev/null
+++ b/Tests/MudroomCoreTests/MergeTests.swift
@@ -0,0 +1,387 @@
+#if canImport(Darwin)
+import Darwin
+#elseif canImport(Glibc)
+import Glibc
+#elseif canImport(Musl)
+import Musl
+#elseif canImport(WinSDK)
+import WinSDK
+#endif
+import Foundation
+import Testing
+@testable import MudroomCore
+
+@Suite("Three-way merge (LineDiff.merge)")
+struct LineMergeTests {
+ func merge(_ base: String, _ ours: String, _ theirs: String) -> MergeResult {
+ LineDiff.merge(base: TextLines(Data(base.utf8)), ours: TextLines(Data(ours.utf8)), theirs: TextLines(Data(theirs.utf8)))
+ }
+
+ func clean(_ r: MergeResult) -> String? {
+ if case .clean(let lines) = r { return String(decoding: lines.data, as: UTF8.self) }
+ return nil
+ }
+
+ static let base = (1...20).map { "line \($0)\n" }.joined()
+
+ @Test("changes in different places merge, both kept")
+ func separate() {
+ let ours = Self.base.replacingOccurrences(of: "line 2\n", with: "line two\n")
+ let theirs = Self.base.replacingOccurrences(of: "line 15\n", with: "line fifteen\nmore\n")
+ let want = ours.replacingOccurrences(of: "line 15\n", with: "line fifteen\nmore\n")
+ #expect(clean(merge(Self.base, ours, theirs)) == want)
+ // Which side is which doesn't change the result.
+ #expect(clean(merge(Self.base, theirs, ours)) == want)
+ }
+
+ @Test("the same line changed two ways is a conflict at that line")
+ func overlap() {
+ let ours = Self.base.replacingOccurrences(of: "line 7\n", with: "mine\n")
+ let theirs = Self.base.replacingOccurrences(of: "line 7\n", with: "agent\n")
+ #expect(merge(Self.base, ours, theirs) == .conflict([6..<7]))
+ }
+
+ @Test("changes on neighbouring lines touch and are a conflict")
+ func touching() {
+ let ours = Self.base.replacingOccurrences(of: "line 7\n", with: "mine\n")
+ let theirs = Self.base.replacingOccurrences(of: "line 8\n", with: "agent\n")
+ #expect(merge(Self.base, ours, theirs) == .conflict([6..<8]))
+ // One unchanged line between them is enough.
+ let apart = Self.base.replacingOccurrences(of: "line 9\n", with: "agent\n")
+ #expect(clean(merge(Self.base, ours, apart)) != nil)
+ }
+
+ @Test("both sides making the same change is taken once")
+ func same() {
+ let both = Self.base.replacingOccurrences(of: "line 4\n", with: "fixed\n")
+ #expect(clean(merge(Self.base, both, both)) == both)
+ let ours = both.replacingOccurrences(of: "line 18\n", with: "ours\n")
+ let theirs = both.replacingOccurrences(of: "line 1\n", with: "theirs\n")
+ #expect(clean(merge(Self.base, ours, theirs)) == ours.replacingOccurrences(of: "line 1\n", with: "theirs\n"))
+ }
+
+ @Test("CRLF lines stay CRLF; a line-ending switch is a change like any other")
+ func crlf() {
+ let base = (1...12).map { "row \($0)\r\n" }.joined()
+ let ours = base.replacingOccurrences(of: "row 2\r\n", with: "row 2b\r\n")
+ let theirs = base.replacingOccurrences(of: "row 11\r\n", with: "row 11b\r\n")
+ #expect(clean(merge(base, ours, theirs)) == ours.replacingOccurrences(of: "row 11\r\n", with: "row 11b\r\n"))
+ // The whole file converted to LF on one side, an edit on the other: overlap.
+ let lf = base.replacingOccurrences(of: "\r\n", with: "\n")
+ if case .clean = merge(base, lf, theirs) { Issue.record("a line-ending switch merged with an edit") }
+ }
+
+ @Test("a missing final newline is kept, and adding one is a change")
+ func finalNewline() {
+ let base = "a\nb\nc\nd\ne"
+ #expect(clean(merge(base, "A\nb\nc\nd\ne", "a\nb\nc\nd\nE")) == "A\nb\nc\nd\nE")
+ #expect(clean(merge(base, "A\nb\nc\nd\ne", "a\nb\nc\nd\ne\n")) == "A\nb\nc\nd\ne\n")
+ if case .clean = merge(base, "a\nb\nc\nd\ne\n", "a\nb\nc\nd\nE") { Issue.record("two changes to the last line merged") }
+ }
+
+ @Test("empty files: two different additions conflict, identical ones merge")
+ func empty() {
+ #expect(merge("", "x\n", "y\n") == .conflict([0..<0]))
+ #expect(clean(merge("", "x\n", "x\n")) == "x\n")
+ #expect(clean(merge("a\n", "", "a\n")) == "")
+ #expect(clean(merge("", "", "")) == "")
+ }
+
+ @Test("the result is deterministic")
+ func deterministic() {
+ let ours = Self.base.replacingOccurrences(of: "line 3\n", with: "")
+ let theirs = Self.base + "tail\n"
+ #expect(merge(Self.base, ours, theirs) == merge(Self.base, ours, theirs))
+ }
+}
+
+@Suite("Apply merges files that changed in the project too")
+struct MergeApplyTests {
+ static let base = (1...40).map { "line \($0)\n" }.joined()
+ /// The agent: line 30 rewritten.
+ static let agent = base.replacingOccurrences(of: "line 30\n", with: "line thirty\n")
+ /// The project, meanwhile: line 3 rewritten.
+ static let mine = base.replacingOccurrences(of: "line 3\n", with: "line three\n")
+ static let both = mine.replacingOccurrences(of: "line 30\n", with: "line thirty\n")
+
+ func fixture(base: String = Self.base, agent: String = Self.agent, mine: String = Self.mine) throws -> Fixture {
+ let f = try Fixture { root in
+ try write(base, to: root.appendingPathComponent("src/file.txt"))
+ try write("x\n", to: root.appendingPathComponent("other.txt"))
+ }
+ try write(agent, to: f.work.appendingPathComponent("src/file.txt"))
+ try write(mine, to: f.project.appendingPathComponent("src/file.txt"))
+ return f
+ }
+
+ func target(_ f: Fixture) -> URL { f.project.appendingPathComponent("src/file.txt") }
+
+ @Test("a clean merge is applied, reported as merged, and undo restores the project's bytes")
+ func cleanMerge() throws {
+ let f = try fixture()
+ let applier = Applier(handle: f.handle)
+ let dry = try applier.preflight()
+ #expect(dry.merged == ["src/file.txt"] && dry.applied == ["src/file.txt"] && dry.conflicts.isEmpty)
+ #expect(try read(target(f)) == Self.mine)
+
+ let report = try applier.apply(paths: nil)
+ #expect(report.applied == ["src/file.txt"])
+ #expect(report.merged == ["src/file.txt"])
+ #expect(report.conflicts.isEmpty)
+ #expect(try read(target(f)) == Self.both)
+
+ // Nothing left to do, and nothing is written over the merge.
+ let again = try applier.apply(paths: nil)
+ #expect(again.alreadyApplied == ["src/file.txt"] && again.applied.isEmpty)
+ #expect(try read(target(f)) == Self.both)
+
+ let undo = try applier.undo()
+ #expect(undo.restored == ["src/file.txt"])
+ #expect(try read(target(f)) == Self.mine)
+ }
+
+ @Test("two sessions on one project editing one file: the second apply merges")
+ func twoSessions() throws {
+ let f = try fixture(mine: Self.base)
+ let second = try f.store.create(project: f.project, command: ["true"], image: "test")
+ try write(Self.mine, to: second.work.appendingPathComponent("src/file.txt"))
+ #expect(try Applier(handle: second).apply(paths: nil).applied == ["src/file.txt"])
+ let report = try Applier(handle: f.handle).apply(paths: nil)
+ #expect(report.merged == ["src/file.txt"])
+ #expect(try read(target(f)) == Self.both)
+ // The first session can't undo over the merge; the second one can.
+ #expect(try Applier(handle: second).undo().conflicts.map(\.path) == ["src/file.txt"])
+ _ = try Applier(handle: f.handle).undo()
+ #expect(try read(target(f)) == Self.mine)
+ _ = try Applier(handle: second).undo()
+ #expect(try read(target(f)) == Self.base)
+ }
+
+ @Test("overlapping changes are a conflict and nothing is written")
+ func overlap() throws {
+ let mine = Self.base.replacingOccurrences(of: "line 30\n", with: "my thirty\n")
+ let f = try fixture(mine: mine)
+ let report = try Applier(handle: f.handle).apply(paths: ["src/file.txt"])
+ #expect(report.applied.isEmpty && report.merged.isEmpty)
+ let c = try #require(report.conflicts.first)
+ #expect(c.path == "src/file.txt")
+ #expect(c.reason.hasPrefix("project changed since the session started"))
+ #expect(c.reason.contains("near line 30"))
+ #expect(report.bundle == nil)
+ #expect(try read(target(f)) == mine)
+ }
+
+ @Test("CRLF files merge and stay CRLF")
+ func crlf() throws {
+ let crlf = (1...30).map { "row \($0)\r\n" }.joined()
+ let f = try fixture(base: crlf,
+ agent: crlf.replacingOccurrences(of: "row 25\r\n", with: "row 25b\r\n"),
+ mine: crlf.replacingOccurrences(of: "row 2\r\n", with: "row 2b\r\n"))
+ #expect(try Applier(handle: f.handle).apply(paths: nil).merged == ["src/file.txt"])
+ #expect(try read(target(f)) == crlf.replacingOccurrences(of: "row 2\r\n", with: "row 2b\r\n")
+ .replacingOccurrences(of: "row 25\r\n", with: "row 25b\r\n"))
+ }
+
+ @Test("a file without a final newline merges and keeps it missing")
+ func missingNewline() throws {
+ let base = (1...20).map { "l\($0)" }.joined(separator: "\n")
+ let f = try fixture(base: base,
+ agent: base.replacingOccurrences(of: "l20", with: "last"),
+ mine: base.replacingOccurrences(of: "l1\n", with: "first\n"))
+ #expect(try Applier(handle: f.handle).apply(paths: nil).merged == ["src/file.txt"])
+ let out = try read(target(f))
+ #expect(out.hasPrefix("first\n") && out.hasSuffix("\nlast"))
+ }
+
+ @Test("the same change on both sides plus one elsewhere is kept once")
+ func sameChange() throws {
+ let fix = Self.base.replacingOccurrences(of: "line 10\n", with: "fixed\n")
+ let f = try fixture(agent: fix.replacingOccurrences(of: "line 30\n", with: "line thirty\n"),
+ mine: fix.replacingOccurrences(of: "line 3\n", with: "line three\n"))
+ #expect(try Applier(handle: f.handle).apply(paths: nil).merged == ["src/file.txt"])
+ #expect(try read(target(f)) == Self.both.replacingOccurrences(of: "line 10\n", with: "fixed\n"))
+ }
+
+ @Test("delete against edit, edit against delete and add against add stay conflicts")
+ func notMergeable() throws {
+ // The agent deleted it, the project edited it.
+ var f = try fixture()
+ unlink(f.work.appendingPathComponent("src/file.txt").path)
+ var r = try Applier(handle: f.handle).apply(paths: nil)
+ #expect(r.conflicts.map(\.path) == ["src/file.txt"] && r.merged.isEmpty)
+ #expect(try read(target(f)) == Self.mine)
+
+ // The agent edited it, the project deleted it.
+ f = try fixture()
+ unlink(target(f).path)
+ r = try Applier(handle: f.handle).apply(paths: nil)
+ #expect(r.conflicts.map(\.path) == ["src/file.txt"] && !exists(target(f)))
+
+ // Both added a file at the same path.
+ f = try fixture(mine: Self.base)
+ try write("agent\nnew\n", to: f.work.appendingPathComponent("added.txt"))
+ try write("my\nnew\n", to: f.project.appendingPathComponent("added.txt"))
+ r = try Applier(handle: f.handle).apply(paths: ["added.txt"])
+ #expect(r.conflicts.map(\.path) == ["added.txt"] && r.merged.isEmpty)
+ #expect(try read(f.project.appendingPathComponent("added.txt")) == "my\nnew\n")
+ }
+
+ @Test("binary files are not merged")
+ func binary() throws {
+ let base = Self.base + "\u{0}bin\n"
+ let f = try fixture(base: base,
+ agent: base.replacingOccurrences(of: "line 30\n", with: "x\n"),
+ mine: base.replacingOccurrences(of: "line 3\n", with: "y\n"))
+ let r = try Applier(handle: f.handle).apply(paths: nil)
+ #expect(r.conflicts.map(\.path) == ["src/file.txt"] && r.merged.isEmpty)
+ #expect(r.conflicts[0].reason.hasPrefix("project changed since the session started (expected"))
+ }
+
+ @Test("a symlink in the project, or a mode-only change, is not merged",
+ .disabled(if: isWindows, "symlinks and modes"))
+ func symlinkAndMode() throws {
+ var f = try fixture()
+ unlink(target(f).path)
+ symlink("../other.txt", target(f).path)
+ var r = try Applier(handle: f.handle).apply(paths: nil)
+ #expect(r.conflicts.map(\.path) == ["src/file.txt"] && r.merged.isEmpty)
+
+ // The agent only changed the mode; the project edited the text.
+ f = try fixture(agent: Self.base)
+ chmod(f.work.appendingPathComponent("src/file.txt").path, 0o755)
+ r = try Applier(handle: f.handle).apply(paths: nil)
+ #expect(r.conflicts.map(\.path) == ["src/file.txt"] && r.merged.isEmpty)
+ #expect(try modeOf(target(f)) == 0o644)
+ }
+
+ @Test("permissions merge too: the side that changed them wins", .disabled(if: isWindows, "no mode bits on Windows"))
+ func modes() throws {
+ let f = try fixture()
+ chmod(f.work.appendingPathComponent("src/file.txt").path, 0o755)
+ #expect(try Applier(handle: f.handle).apply(paths: nil).merged == ["src/file.txt"])
+ #expect(try modeOf(target(f)) == 0o755)
+ _ = try Applier(handle: f.handle).undo()
+ #expect(try modeOf(target(f)) == 0o644)
+ #expect(try read(target(f)) == Self.mine)
+
+ // Both changed them, differently: conflict.
+ let g = try fixture()
+ chmod(g.work.appendingPathComponent("src/file.txt").path, 0o755)
+ chmod(target(g).path, 0o600)
+ let r = try Applier(handle: g.handle).apply(paths: nil)
+ #expect(r.conflicts.first?.reason.contains("permissions") == true)
+ }
+
+ @Test("a merge keeps the project's own setuid bit but never takes one from work/",
+ .disabled(if: isWindows, "no mode bits on Windows"))
+ func setuid() throws {
+ let f = try fixture()
+ chmod(target(f).path, 0o4755)
+ #expect(try Applier(handle: f.handle).apply(paths: nil).merged == ["src/file.txt"])
+ #expect(try modeOf(target(f)) == 0o4755)
+
+ let g = try fixture()
+ chmod(g.work.appendingPathComponent("src/file.txt").path, 0o4755)
+ #expect(try Applier(handle: g.handle).apply(paths: nil).merged == ["src/file.txt"])
+ #expect(try modeOf(target(g)) == 0o755)
+ }
+
+ @Test("undo of a merged file refuses after a later edit, unless forced")
+ func undoAfterEdit() throws {
+ let f = try fixture()
+ let applier = Applier(handle: f.handle)
+ _ = try applier.apply(paths: nil)
+ try write(Self.both + "later\n", to: target(f))
+ let undo = try applier.undo()
+ #expect(undo.conflicts.map(\.path) == ["src/file.txt"] && undo.restored.isEmpty)
+ #expect(try read(target(f)) == Self.both + "later\n")
+ let forced = try applier.undo(force: true)
+ #expect(forced.restored == ["src/file.txt"])
+ #expect(try read(target(f)) == Self.mine)
+ }
+
+ @Test("files inside .git are never merged")
+ func gitInternal() throws {
+ let f = try Fixture { root in try write(Self.base, to: root.appendingPathComponent(".git/description")) }
+ try write(Self.agent, to: f.work.appendingPathComponent(".git/description"))
+ try write(Self.mine, to: f.project.appendingPathComponent(".git/description"))
+ let r = try Applier(handle: f.handle).apply(paths: nil, includeGit: true)
+ #expect(r.conflicts.map(\.path) == [".git/description"] && r.merged.isEmpty)
+ }
+
+ @Test("hunks merge into a project copy changed elsewhere, one at a time, and undo step by step")
+ func hunks() throws {
+ // Agent: three hunks (lines 10, 25, 38). Project: line 3.
+ let agent = Self.base.replacingOccurrences(of: "line 10\n", with: "ten\n")
+ .replacingOccurrences(of: "line 25\n", with: "twenty-five\n")
+ .replacingOccurrences(of: "line 38\n", with: "")
+ let f = try fixture(agent: agent)
+ let applier = Applier(handle: f.handle)
+ let change = try #require(try f.diff().changes.first { $0.path == "src/file.txt" })
+ #expect(try applier.hunks(for: change)?.map(\.id) == [1, 2, 3])
+
+ let first = try applier.applyHunks(path: "src/file.txt", hunks: [2])
+ #expect(first.merged == ["src/file.txt"] && first.conflicts.isEmpty)
+ let afterFirst = Self.mine.replacingOccurrences(of: "line 25\n", with: "twenty-five\n")
+ #expect(try read(target(f)) == afterFirst)
+ #expect(try applier.appliedHunks(for: change) == [2])
+
+ let second = try applier.applyHunks(path: "src/file.txt", hunks: [1, 3])
+ #expect(second.merged == ["src/file.txt"])
+ let all = Self.mine.replacingOccurrences(of: "line 10\n", with: "ten\n")
+ .replacingOccurrences(of: "line 25\n", with: "twenty-five\n")
+ .replacingOccurrences(of: "line 38\n", with: "")
+ #expect(try read(target(f)) == all)
+ #expect(try applier.appliedHunks(for: change) == [1, 2, 3])
+ #expect(try applier.apply(paths: nil).alreadyApplied == ["src/file.txt"])
+
+ _ = try applier.undo()
+ #expect(try read(target(f)) == afterFirst)
+ _ = try applier.undo()
+ #expect(try read(target(f)) == Self.mine)
+ #expect(!applier.canUndo)
+ }
+
+ @Test("a hunk overlapping the project's change is a conflict; another one still merges")
+ func hunkOverlap() throws {
+ let agent = Self.base.replacingOccurrences(of: "line 3\n", with: "agent three\n")
+ .replacingOccurrences(of: "line 30\n", with: "line thirty\n")
+ let f = try fixture(agent: agent)
+ let applier = Applier(handle: f.handle)
+ let bad = try applier.applyHunks(path: "src/file.txt", hunks: [1])
+ #expect(bad.conflicts.map(\.path) == ["src/file.txt"] && bad.bundle == nil)
+ #expect(try read(target(f)) == Self.mine)
+ let good = try applier.applyHunks(path: "src/file.txt", hunks: [2])
+ #expect(good.merged == ["src/file.txt"])
+ #expect(try read(target(f)) == Self.both)
+ }
+
+ @Test("a rollback entry for a merge is marked in the journal before the write")
+ func journal() throws {
+ let f = try fixture()
+ let report = try Applier(handle: f.handle).apply(paths: nil)
+ let bundle = try #require(report.bundle)
+ let manifest = try #require(try Applier.readManifest(bundle))
+ let entry = try #require(manifest.entries.first { $0.path == "src/file.txt" })
+ #expect(entry.merged == true && entry.pending == nil)
+ let journal = try read(bundle.appendingPathComponent(Journal.name))
+ #expect(journal.contains("\"merged\":true"))
+ #expect(try read(bundle.appendingPathComponent(try #require(entry.backup))) == Self.mine)
+ }
+
+ @Test("the review marks a mergeable file and starts it selected")
+ func review() throws {
+ let f = try fixture()
+ try write("y\n", to: f.work.appendingPathComponent("other.txt"))
+ let snap = try ReviewSnapshot.load(f.handle)
+ let entry = try #require(snap.entry("src/file.txt"))
+ #expect(entry.merges && entry.conflict == nil && entry.selectedByDefault)
+ #expect(snap.entry("other.txt")?.merges == false)
+
+ let dry = try Applier(handle: f.handle).preflight()
+ let term = TerminalReview(changes: try f.diff().changes, merges: Set(dry.merged))
+ let lines = term.body(width: 200, height: 10)
+ #expect(lines.contains { $0.contains("src/file.txt") && $0.contains("MERGE") })
+ #expect(!lines.contains { $0.contains("other.txt") && $0.contains("MERGE") })
+ }
+}
diff --git a/scripts/windows-smoke.ps1 b/scripts/windows-smoke.ps1
index ed1eefd..3bd15d4 100644
--- a/scripts/windows-smoke.ps1
+++ b/scripts/windows-smoke.ps1
@@ -59,6 +59,23 @@ try {
expect (-not (Test-Path (Join-Path $project 'new.txt'))) 'undo removes the added file'
expect (Test-Path (Join-Path $project 'old.txt')) 'undo brings back the deleted file'
+ # Two sessions edit one file in different lines: the second apply merges.
+ $appTxt = Join-Path $project 'src\app.txt'
+ $a = (mr @('new', $project, '--agent', 'smoke', '--', 'cmd', '/c', 'exit')).Trim()
+ $b = (mr @('new', $project, '--agent', 'smoke', '--', 'cmd', '/c', 'exit')).Trim()
+ [IO.File]::WriteAllText((Join-Path $env:MUDROOM_HOME "sessions\$a\work\src\app.txt"), "ONE`r`ntwo`r`nthree`r`n")
+ [IO.File]::WriteAllText((Join-Path $env:MUDROOM_HOME "sessions\$b\work\src\app.txt"), "one`r`ntwo`r`nTHREE`r`n")
+ mr @('apply', $a, '--all') | Out-Null
+ $merge = mr @('apply', $b, '--all')
+ expect ($merge -match 'merged\s+src/app.txt') 'the second apply reports a merge'
+ expect ([IO.File]::ReadAllText($appTxt) -eq "ONE`r`ntwo`r`nTHREE`r`n") 'both edits are in the file, CRLF intact'
+ mr @('undo', $b) | Out-Null
+ expect ([IO.File]::ReadAllText($appTxt) -eq "ONE`r`ntwo`r`nthree`r`n") 'undo of the merge puts back the first apply'
+ mr @('undo', $a) | Out-Null
+ expect ([IO.File]::ReadAllText($appTxt) -eq "one`r`ntwo`r`nthree`r`n") 'undo of the first apply restores the original'
+ mr @('discard', $a) | Out-Null
+ mr @('discard', $b) | Out-Null
+
$list = mr @('list')
expect ($list -match $id) 'list shows the session'
mr @('discard', $id) | Out-Null