Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

14.3 KB
Raw Blame
package diff

import (
	"strings"
	"testing"
)

func TestFromCursorEdits_SingleEdit(t *testing.T) {
	edits := []interface{}{
		map[string]interface{}{
			"old_string": "x = 1",
			"new_string": "x = 2",
		},
	}

	result := FromCursorEdits("/path/to/file.py", edits)

	if result == "" {
		t.Fatal("FromCursorEdits() returned empty string")
	}

	if !strings.Contains(result, "--- a/file.py") {
		t.Error("Missing --- header")
	}
	if !strings.Contains(result, "+++ b/file.py") {
		t.Error("Missing +++ header")
	}
	if !strings.Contains(result, "-x = 1") {
		t.Error("Missing old string in diff")
	}
	if !strings.Contains(result, "+x = 2") {
		t.Error("Missing new string in diff")
	}
}

func TestFromCursorEdits_MultipleEdits(t *testing.T) {
	edits := []interface{}{
		map[string]interface{}{
			"old_string": "x = 1",
			"new_string": "x = 2",
		},
		map[string]interface{}{
			"old_string": "y = 3",
			"new_string": "y = 4",
		},
	}

	result := FromCursorEdits("/path/to/file.py", edits)

	if result == "" {
		t.Fatal("FromCursorEdits() returned empty string")
	}

	// Should contain two diffs separated by double newline
	parts := strings.Split(result, "\n\n")
	if len(parts) < 2 {
		t.Errorf("Expected at least 2 diff sections, got %d", len(parts))
	}

	if !strings.Contains(result, "-x = 1") {
		t.Error("Missing first old string")
	}
	if !strings.Contains(result, "+x = 2") {
		t.Error("Missing first new string")
	}
	if !strings.Contains(result, "-y = 3") {
		t.Error("Missing second old string")
	}
	if !strings.Contains(result, "+y = 4") {
		t.Error("Missing second new string")
	}
}

func TestFromCursorEdits_InvalidEditFormat(t *testing.T) {
	edits := []interface{}{
		"not a map",
		42,
	}

	result := FromCursorEdits("/path/to/file.py", edits)

	if result != "" {
		t.Errorf("FromCursorEdits() with invalid edits = %q, want empty", result)
	}
}

func TestFromCursorEdits_EmptyStrings(t *testing.T) {
	edits := []interface{}{
		map[string]interface{}{
			"old_string": "",
			"new_string": "",
		},
	}

	result := FromCursorEdits("/path/to/file.py", edits)

	// fromEditTool returns "" for empty old and new strings
	if result != "" {
		t.Errorf("FromCursorEdits() with empty strings = %q, want empty", result)
	}
}

// Cline's write tool is spelled write_to_file. Without it in the Write case, FromToolResponse
// returns nothing and a created file reaches the log as raw content with no diff metadata.
func TestFromToolResponse_ClineWriteToFile(t *testing.T) {
	got := FromToolResponse(
		"write_to_file",
		map[string]interface{}{"path": "src/health.ts", "content": "export const health = () => true\n"},
		nil,
	)
	if !strings.Contains(got, "--- a/health.ts") || !strings.Contains(got, "+++ b/health.ts") {
		t.Fatalf("diff header = %q, want the file named in both halves", got)
	}
	if !strings.Contains(got, "@@ -0,0 +1,") {
		t.Errorf("diff = %q, want a new-file hunk header", got)
	}
	if !strings.Contains(got, "+export const health") {
		t.Errorf("diff = %q, want the written content as added lines", got)
	}
}

// "replace" is Gemini CLI's -- and so early Qwen Code's -- id for the old_string/new_string edit
// tool. Qwen's mapper recognizes it as a file edit, so the diff builder has to recognize it too:
// otherwise the event records that a file changed and never records how, which is the difference
// between an auditable edit and a bare notification.
func TestFromToolResponseBuildsADiffForTheReplaceTool(t *testing.T) {
	toolInput := map[string]interface{}{
		"file_path":  "/repo/src/server.ts",
		"old_string": "const routes = []",
		"new_string": "const routes = [health]",
	}
	got := FromToolResponse("replace", toolInput, nil)
	if got == "" {
		t.Fatal("FromToolResponse(replace) = \"\", want a diff")
	}
	if !strings.Contains(got, "const routes = []") || !strings.Contains(got, "const routes = [health]") {
		t.Fatalf("diff = %q, want both sides of the replacement", got)
	}
	if want := FromToolResponse("edit", toolInput, nil); got != want {
		t.Fatalf("replace and edit produced different diffs:\n replace: %q\n edit:    %q", got, want)
	}
}

// Gemini CLI's read_file names its target `absolute_path`. The resolver already read the CamelCase
// `AbsolutePath`; without the snake_case sibling the path is empty and FromToolResponse bails out
// before it looks at the tool at all.
func TestFromToolResponseResolvesAbsolutePathParameter(t *testing.T) {
	got := FromToolResponse("write_file", map[string]interface{}{
		"absolute_path": "/repo/src/health.ts",
		"content":       "export const health = () => ({ ok: true })\n",
	}, nil)
	if got == "" {
		t.Fatal("FromToolResponse = \"\", want a diff resolved from absolute_path")
	}
	// The diff header names the file by its base name, so what this asserts is that a path was
	// resolved at all -- an unresolved path returns "" a few lines above.
	if !strings.Contains(got, "health.ts") || !strings.Contains(got, "export const health") {
		t.Fatalf("diff = %q, want the absolute_path target and its content", got)
	}
}

// FromContentChange is the one constructor here that is given the answer rather than asked to
// infer it, so these cases pin the shapes an observation can report: a modification and a
// deletion here, a creation in TestFromEditFragmentsDoesNotReportAnInsertionAsANewFile.
func TestFromContentChangeBuildsAReplacementDiff(t *testing.T) {
	got := FromContentChange("/workspace/main.go", "package main\n\nfunc old() {}\n", "package main\n\nfunc new() {}\n")
	for _, want := range []string{"--- a/main.go", "+++ b/main.go", "-func old() {}", "+func new() {}"} {
		if !strings.Contains(got, want) {
			t.Errorf("FromContentChange missing %q:\n%s", want, got)
		}
	}
}

// diffBodyLines returns the diff's content lines starting with prefix, skipping the ---/+++ file
// headers so that a "+++ b/x" header is not mistaken for an added line.
func diffBodyLines(diff, prefix string) []string {
	var out []string
	for _, line := range strings.Split(diff, "\n") {
		if strings.HasPrefix(line, "---") || strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "@@") {
			continue
		}
		if strings.HasPrefix(line, prefix) {
			out = append(out, line)
		}
	}
	return out
}

func TestFromContentChangeBuildsADeletionDiff(t *testing.T) {
	got := FromContentChange("/workspace/gone.go", "package main\n", "")
	if !strings.Contains(got, "-package main") {
		t.Errorf("FromContentChange = %q, want the removed line", got)
	}
	if added := diffBodyLines(got, "+"); len(added) != 0 {
		t.Errorf("FromContentChange = %q, want no added lines for a deletion, got %v", got, added)
	}
}

// An unchanged file is not an edit. Returning a header with an empty hunk would record that a file
// changed when it did not -- which is the failure this constructor exists to avoid, because a
// runtime that reports before and after can legitimately report them equal (an undo that restores
// identical content, a patch entry whose two sides match).
func TestFromContentChangeReturnsNothingWhenTheContentIsUnchanged(t *testing.T) {
	for _, tc := range []struct{ name, path, oldContent, newContent string }{
		{"identical", "/workspace/main.go", "same\n", "same\n"},
		{"no path", "", "a\n", "b\n"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			if got := FromContentChange(tc.path, tc.oldContent, tc.newContent); got != "" {
				t.Errorf("FromContentChange = %q, want empty", got)
			}
		})
	}
}

// FromEditorCommandWrite is the one diff builder written against a tool whose arguments the vendor does not
// publish, so its safety property is worth stating as a test rather than as a comment: an
// unrecognized shape must produce no diff, never a wrong one. Every case below is a shape Kiro
// could plausibly send, and each either resolves exactly or returns "".
func TestFromEditorCommandWriteReadsBothArgumentSpellings(t *testing.T) {
	for _, tc := range []struct {
		name      string
		operation string
		toolName  string
		input     map[string]interface{}
		wantLines []string
	}{
		{
			name:      "create with the Amazon Q spelling",
			operation: "create",
			toolName:  "fs_write",
			input:     map[string]interface{}{"path": "/repo/a.go", "file_text": "package main\n"},
			wantLines: []string{"+++ b/a.go", "+package main"},
		},
		{
			name:      "create with the ecosystem spelling",
			operation: "",
			toolName:  "write",
			input:     map[string]interface{}{"path": "/repo/a.go", "content": "package main\n"},
			wantLines: []string{"+++ b/a.go", "+package main"},
		},
		{
			name:      "replacement with the Amazon Q spelling",
			operation: "str_replace",
			toolName:  "fs_write",
			input:     map[string]interface{}{"path": "/repo/a.go", "old_str": "one", "new_str": "two"},
			wantLines: []string{"-one", "+two"},
		},
		{
			name:      "replacement with the ecosystem spelling",
			operation: "",
			toolName:  "str_replace",
			input:     map[string]interface{}{"path": "/repo/a.go", "old_string": "one", "new_string": "two"},
			wantLines: []string{"-one", "+two"},
		},
		{
			name:      "append adds and removes nothing",
			operation: "",
			toolName:  "fs_append",
			input:     map[string]interface{}{"path": "/repo/a.go", "new_str": "// tail\n"},
			wantLines: []string{"+// tail"},
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			got := FromEditorCommandWrite(tc.operation, tc.toolName, tc.input, nil)
			for _, want := range tc.wantLines {
				if !hasExactLine(got, want) {
					t.Fatalf("diff missing %q:\n%s", want, got)
				}
			}
		})
	}
}

// The safety property itself. A shape this build cannot read yields nothing, which records the
// file event without a diff -- rather than a diff built from a value that was not the content.
func TestFromEditorCommandWriteReturnsNothingRatherThanGuessing(t *testing.T) {
	for _, tc := range []struct {
		name      string
		operation string
		toolName  string
		input     map[string]interface{}
	}{
		{"no path", "create", "fs_write", map[string]interface{}{"file_text": "x"}},
		{"no content", "create", "fs_write", map[string]interface{}{"path": "/repo/a.go"}},
		{"unreadable arguments", "", "fs_write", map[string]interface{}{"path": "/repo/a.go", "payload": "?"}},
		{"a delete has no content on either side", "delete", "delete_file", map[string]interface{}{"path": "/repo/a.go"}},
		{"an unknown tool", "", "some_future_tool", map[string]interface{}{"path": "/repo/a.go", "content": "x"}},
	} {
		t.Run(tc.name, func(t *testing.T) {
			if got := FromEditorCommandWrite(tc.operation, tc.toolName, tc.input, nil); got != "" {
				t.Fatalf("FromEditorCommandWrite = %q, want empty", got)
			}
		})
	}
}

// A create that reports the file's previous contents is an overwrite, and rendering it as a new
// file would hide what was replaced.
func TestFromEditorCommandWriteRendersAnOverwriteAsAReplacement(t *testing.T) {
	got := FromEditorCommandWrite("create", "fs_write", map[string]interface{}{
		"path":          "/repo/a.go",
		"file_text":     "new\n",
		"original_file": "old\n",
	}, nil)
	if !hasExactLine(got, "-old") || !hasExactLine(got, "+new") {
		t.Fatalf("overwrite was not rendered as a replacement:\n%s", got)
	}
}

func hasExactLine(diff, want string) bool {
	for _, line := range strings.Split(diff, "\n") {
		if line == want {
			return true
		}
	}
	return false
}

// FromEditFragments and FromContentChange take the same two arguments and mean different things by
// them, so the case that separates them is worth pinning: a replacement whose "before" side is
// empty.
//
// FromContentChange is told the file's whole contents, so an empty old side means the file did not
// exist and `@@ -0,0` is right. FromEditFragments is told one replaced span, so an empty before
// side means an insertion into a file that does exist, and `@@ -0,0` would claim the whole file was
// created by an edit that added one line.
func TestFromEditFragmentsDoesNotReportAnInsertionAsANewFile(t *testing.T) {
	inserted := FromEditFragments("/repo/main.go", "", "\tdefer cancel()")
	if strings.Contains(inserted, "@@ -0,0") {
		t.Fatalf("FromEditFragments reported an insertion as a new file: %q", inserted)
	}
	if !strings.Contains(inserted, "+\tdefer cancel()") {
		t.Fatalf("FromEditFragments did not record the inserted line: %q", inserted)
	}

	created := FromContentChange("/repo/main.go", "", "package main\n")
	if !strings.Contains(created, "@@ -0,0") {
		t.Fatalf("FromContentChange must still report a created file as new: %q", created)
	}
}

// A replacement that substitutes a fragment for an identical one changed nothing, and a hunk for it
// would record that a file changed when it did not.
func TestFromEditFragmentsReturnsNothingForAnUnchangedSpan(t *testing.T) {
	if got := FromEditFragments("/repo/main.go", "timeout := 5", "timeout := 5"); got != "" {
		t.Fatalf("FromEditFragments = %q, want empty for an unchanged span", got)
	}
	if got := FromEditFragments("", "before", "after"); got != "" {
		t.Fatalf("FromEditFragments = %q, want empty without a path", got)
	}
}

// A whole-file Write diff carries the file's exact line boundaries: a terminating newline is not
// an extra blank line, real trailing blank lines stay, and unterminated content gets the unified
// diff EOF marker.
func TestWholeFileWriteDiffPreservesFinalLineBoundaries(t *testing.T) {
	const header = "--- a/result.txt\n+++ b/result.txt\n"
	const eof = "\\ No newline at end of file"
	for _, tc := range []struct{ name, before, after, want string }{
		{"create terminated", "", "new\n", "@@ -0,0 +1,1 @@\n+new"},
		{"create with trailing blank line", "", "new\n\n", "@@ -0,0 +1,2 @@\n+new\n+"},
		{"create a lone newline", "", "\n", "@@ -0,0 +1,1 @@\n+"},
		{"create unterminated", "", "new", "@@ -0,0 +1,1 @@\n+new\n" + eof},
		{"replace both unterminated", "old", "new", "@@ -1,1 +1,1 @@\n-old\n" + eof + "\n+new\n" + eof},
		{"remove final newline", "same\n", "same", "@@ -1,1 +1,1 @@\n-same\n+same\n" + eof},
		{"add final newline", "same", "same\n", "@@ -1,1 +1,1 @@\n-same\n" + eof + "\n+same"},
		{"replace trailing blank line", "old\n\n", "new", "@@ -1,2 +1,1 @@\n-old\n-\n+new\n" + eof},
	} {
		t.Run(tc.name, func(t *testing.T) {
			got := FromToolResponse("Write", map[string]interface{}{"file_path": "/repo/result.txt", "content": tc.after}, map[string]interface{}{"originalFile": tc.before})
			if want := header + tc.want; got != want {
				t.Fatalf("diff:\n%s\nwant:\n%s", got, want)
			}
		})
	}
}

func TestEditFragmentsDoNotClaimEndOfFile(t *testing.T) {
	if got := FromEditFragments("/repo/result.txt", "old", "new"); strings.Contains(got, "\\ No newline at end of file") {
		t.Fatalf("partial edit claims EOF: %s", got)
	}
}