use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use parking_lot::Mutex;
use serde_json::{Value, json};
use symforge::live_index::LiveIndex;
use symforge::protocol::SymForgeServer;
use symforge::watcher::WatcherInfo;
use tempfile::TempDir;
const EDIT_TOOLS: &[&str] = &[
"edit_within_symbol",
"replace_symbol_body",
"insert_symbol",
"delete_symbol",
"batch_edit",
"batch_insert",
"batch_rename",
];
const HELLO_RS: &str =
"fn hello() {\n println!(\"hello\");\n}\n\nfn world() {\n println!(\"world\");\n}\n";
fn enable_feature_flag() {
unsafe { std::env::set_var("SYMFORGE_WORKTREE_AWARE", "1") };
}
fn run_git(cwd: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(cwd)
.args(args)
.output()
.unwrap_or_else(|e| panic!("git spawn failed for {args:?}: {e}"));
if !out.status.success() {
panic!(
"git {args:?} in {cwd:?} failed:\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
}
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn git_init_with_initial_commit(root: &Path) {
run_git(root, &["init", "-b", "main"]);
run_git(root, &["config", "user.email", "test@example.com"]);
run_git(root, &["config", "user.name", "wtaware-test"]);
run_git(root, &["add", "-A"]);
run_git(root, &["commit", "-m", "initial"]);
}
fn git_worktree_add(indexed_root: &Path, worktree_root: &Path, branch: &str) {
if let Some(parent) = worktree_root.parent() {
fs::create_dir_all(parent).expect("worktree parent dir");
}
run_git(
indexed_root,
&[
"worktree",
"add",
"-b",
branch,
worktree_root.to_str().expect("utf-8 worktree path"),
],
);
}
struct IndexedOnlyFixture {
_dir: TempDir,
root: PathBuf,
server: SymForgeServer,
}
impl IndexedOnlyFixture {
fn new(files: &[(&str, &str)]) -> Self {
let dir = tempfile::tempdir().expect("tempdir");
let container = dir.path().to_path_buf();
let root = container.join("main");
fs::create_dir_all(&root).expect("create main dir");
for (rel, content) in files {
let path = root.join(rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("create parent dir");
}
fs::write(&path, content).expect("write fixture file");
}
git_init_with_initial_commit(&root);
let shared = LiveIndex::load(&root).expect("LiveIndex::load");
let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
let server = SymForgeServer::new(
shared,
"worktree_awareness_indexed_only".to_string(),
watcher_info,
Some(root.clone()),
None,
);
Self { _dir: dir, root, server }
}
fn read(&self, rel: &str) -> String {
fs::read_to_string(self.root.join(rel)).expect("read file")
}
}
struct WorktreeFixture {
_dir: TempDir,
root: PathBuf,
worktree_root: PathBuf,
server: SymForgeServer,
}
impl WorktreeFixture {
fn new(files: &[(&str, &str)]) -> Self {
let dir = tempfile::tempdir().expect("tempdir");
let container = dir.path().to_path_buf();
let root = container.join("main");
fs::create_dir_all(&root).expect("create main dir");
for (rel, content) in files {
let path = root.join(rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("create parent dir");
}
fs::write(&path, content).expect("write fixture file");
}
git_init_with_initial_commit(&root);
let worktree_root = container.join("wt_one");
git_worktree_add(&root, &worktree_root, "tentacle/test");
let shared = LiveIndex::load(&root).expect("LiveIndex::load");
let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
let server = SymForgeServer::new(
shared,
"worktree_awareness_test".to_string(),
watcher_info,
Some(root.clone()),
None,
);
Self {
_dir: dir,
root,
worktree_root,
server,
}
}
fn container(&self) -> PathBuf {
self.root.parent().expect("container").to_path_buf()
}
fn read_indexed(&self, rel: &str) -> String {
fs::read_to_string(self.root.join(rel)).expect("read indexed file")
}
fn read_worktree(&self, rel: &str) -> String {
fs::read_to_string(self.worktree_root.join(rel)).expect("read worktree file")
}
}
async fn call(server: &SymForgeServer, tool: &str, params: Value) -> String {
server.dispatch_tool_for_tests(tool, params).await
}
fn assert_contains(result: &str, needle: &str) {
assert!(
result.contains(needle),
"expected result to contain `{needle}`; result was:\n{result}"
);
}
fn assert_not_contains(result: &str, needle: &str) {
assert!(
!result.contains(needle),
"expected result NOT to contain `{needle}`; result was:\n{result}"
);
}
#[tokio::test]
async fn ac1_all_seven_edit_tools_accept_working_directory_param() {
enable_feature_flag();
assert_eq!(EDIT_TOOLS.len(), 7, "spec §2.1 lists exactly 7 write tools");
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let wt_arg = fx.worktree_root.to_str().unwrap().to_string();
let payloads: Vec<(&str, Value)> = vec![
(
"edit_within_symbol",
json!({
"path": "src/lib.rs",
"name": "hello",
"old_text": "hello",
"new_text": "HELLO",
"working_directory": wt_arg.clone(),
}),
),
(
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": wt_arg.clone(),
}),
),
(
"insert_symbol",
json!({
"path": "src/lib.rs",
"name": "hello",
"content": "fn added() {}",
"working_directory": wt_arg.clone(),
}),
),
(
"delete_symbol",
json!({
"path": "src/lib.rs",
"name": "hello",
"working_directory": wt_arg.clone(),
}),
),
(
"batch_edit",
json!({
"edits": [],
"working_directory": wt_arg.clone(),
}),
),
(
"batch_insert",
json!({
"content": "fn x() {}",
"position": "after",
"targets": [],
"working_directory": wt_arg.clone(),
}),
),
(
"batch_rename",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_name": "greet",
"working_directory": wt_arg.clone(),
}),
),
];
assert_eq!(
payloads.len(),
EDIT_TOOLS.len(),
"AC1 payload table must cover every tool in EDIT_TOOLS"
);
for (tool, params) in payloads {
let result = call(&fx.server, tool, params).await;
assert!(
!result.contains("invalid tool parameters"),
"tool `{tool}` rejected the `working_directory` param; \
response was:\n{result}"
);
assert!(
!result.starts_with("dispatch_tool_for_tests: unknown tool"),
"tool `{tool}` is not wired into dispatch_tool_for_tests: {result}"
);
}
}
#[tokio::test]
async fn ac2_omitted_working_directory_is_byte_identical() {
enable_feature_flag();
let fx = IndexedOnlyFixture::new(&[("src/lib.rs", HELLO_RS)]);
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {\n println!(\"HELLO\");\n}",
}),
)
.await;
assert_contains(&result, "Edit safety: structural-edit-safe");
assert_contains(&result, "Path authority: repository-bound");
assert_contains(&result, "Write semantics: atomic write + reindex");
assert_not_contains(&result, "rerouted: true");
let on_disk = fx.read("src/lib.rs");
assert!(
on_disk.contains("HELLO"),
"indexed copy must be written when working_directory is omitted: {on_disk}",
);
}
#[tokio::test]
async fn ac3_working_directory_at_known_worktree_writes_to_worktree() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let wt_arg = fx.worktree_root.to_str().unwrap().to_string();
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {\n println!(\"HELLO_WT\");\n}",
"working_directory": wt_arg,
}),
)
.await;
assert_contains(&result, "rerouted: true");
assert_contains(&result, "wrote_to");
assert_contains(&result, "indexed_path");
let wt_after = fx.read_worktree("src/lib.rs");
assert!(
wt_after.contains("HELLO_WT"),
"worktree copy must receive the write: {wt_after}",
);
let indexed_after = fx.read_indexed("src/lib.rs");
assert!(
!indexed_after.contains("HELLO_WT"),
"indexed copy must NOT be touched when rerouting: {indexed_after}",
);
}
#[tokio::test]
async fn ac4_working_directory_at_unknown_path_errors_and_writes_nothing() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let bogus = tempfile::tempdir().expect("bogus tempdir");
let indexed_before = fx.read_indexed("src/lib.rs");
let wt_before = fx.read_worktree("src/lib.rs");
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {\n println!(\"SHOULD_NOT_LAND\");\n}",
"working_directory": bogus.path().to_str().unwrap(),
}),
)
.await;
assert_contains(&result, "WorkingDirectoryNotARecognizedWorktree");
assert_contains(&result, "git worktree list");
assert_eq!(
fx.read_indexed("src/lib.rs"),
indexed_before,
"indexed copy modified despite unknown working_directory",
);
assert_eq!(
fx.read_worktree("src/lib.rs"),
wt_before,
"worktree copy modified despite unknown working_directory",
);
}
#[tokio::test]
async fn ac5_response_surfaces_wrote_to_and_indexed_path_and_rerouted() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let wt_arg = fx.worktree_root.to_str().unwrap().to_string();
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() { }",
"working_directory": wt_arg,
}),
)
.await;
assert_contains(&result, "wrote_to");
assert_contains(&result, "indexed_path");
assert_contains(&result, "rerouted: true");
assert_contains(&result, fx.worktree_root.to_str().unwrap());
}
#[tokio::test]
async fn ac6_matrix_covers_indexed_root_and_missing_file_cases() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let result_a = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": fx.root.to_str().unwrap(),
}),
)
.await;
assert_contains(&result_a, "rerouted: false");
fs::remove_file(fx.worktree_root.join("src/lib.rs")).expect("remove worktree file");
let result_b = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": fx.worktree_root.to_str().unwrap(),
}),
)
.await;
assert_contains(&result_b, "TargetFileMissing");
assert_contains(&result_b, "git ls-tree");
}
#[test]
fn ac7_readme_documents_working_directory_parameter() {
let readme_path = format!("{}/README.md", env!("CARGO_MANIFEST_DIR"));
let readme = fs::read_to_string(&readme_path)
.unwrap_or_else(|e| panic!("README.md unreadable at {readme_path}: {e}"));
assert!(
readme.contains("working_directory"),
"README.md must document the `working_directory` parameter",
);
assert!(
readme.to_lowercase().contains("worktree"),
"README.md must reference git worktrees",
);
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn matrix_windows_forward_and_back_slash_canonicalize_equal() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let back = fx.worktree_root.to_str().unwrap().to_string();
let forward = back.replace('\\', "/");
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": forward,
}),
)
.await;
assert_contains(&result, "rerouted: true");
assert_not_contains(&result, "WorkingDirectoryNotARecognizedWorktree");
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn matrix_mixed_case_windows_canonicalize_equal() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let original = fx.worktree_root.to_str().unwrap().to_string();
let mixed: String = original
.chars()
.enumerate()
.map(|(i, c)| {
if i % 3 == 0 {
c.to_ascii_uppercase()
} else {
c.to_ascii_lowercase()
}
})
.collect();
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": mixed,
}),
)
.await;
assert_contains(&result, "rerouted: true");
}
#[tokio::test]
async fn matrix_trailing_slash_canonicalize_equal() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let base = fx.worktree_root.to_str().unwrap().to_string();
let sep = std::path::MAIN_SEPARATOR;
let with_trailing = if base.ends_with(sep) {
base.clone()
} else {
format!("{base}{sep}")
};
let result = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": with_trailing,
}),
)
.await;
assert_contains(&result, "rerouted: true");
assert_not_contains(&result, "WorkingDirectoryNotARecognizedWorktree");
}
#[tokio::test]
async fn matrix_two_worktrees_concurrent_calls_have_no_crosstalk() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let wt2 = fx.container().join("wt_two");
git_worktree_add(&fx.root, &wt2, "tentacle/test-two");
let wt1_arg = fx.worktree_root.to_str().unwrap().to_string();
let wt2_arg = wt2.to_str().unwrap().to_string();
let r1 = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() { /* wt1 */ }",
"working_directory": wt1_arg,
}),
)
.await;
let r2 = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() { /* wt2 */ }",
"working_directory": wt2_arg,
}),
)
.await;
assert_contains(&r1, "rerouted: true");
assert_contains(&r2, "rerouted: true");
let c1 = fs::read_to_string(fx.worktree_root.join("src/lib.rs")).unwrap();
let c2 = fs::read_to_string(wt2.join("src/lib.rs")).unwrap();
assert!(
c1.contains("wt1") && !c1.contains("wt2"),
"wt1 cross-written:\n{c1}",
);
assert!(
c2.contains("wt2") && !c2.contains("wt1"),
"wt2 cross-written:\n{c2}",
);
let indexed = fx.read_indexed("src/lib.rs");
assert!(
!indexed.contains("wt1") && !indexed.contains("wt2"),
"indexed root polluted:\n{indexed}",
);
}
#[tokio::test]
async fn matrix_cache_refresh_newly_created_worktree_accepted() {
enable_feature_flag();
let fx = IndexedOnlyFixture::new(&[("src/lib.rs", HELLO_RS)]);
let container = fx.root.parent().expect("container").to_path_buf();
let lateborn = container.join("wt_lateborn");
let pre = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": lateborn.to_str().unwrap(),
}),
)
.await;
assert_contains(&pre, "WorkingDirectoryNotARecognizedWorktree");
git_worktree_add(&fx.root, &lateborn, "tentacle/lateborn");
let post = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {}",
"working_directory": lateborn.to_str().unwrap(),
}),
)
.await;
assert_contains(&post, "rerouted: true");
}
#[tokio::test]
async fn health_surfaces_worktree_misuse_counter() {
enable_feature_flag();
let fx = IndexedOnlyFixture::new(&[("src/lib.rs", HELLO_RS)]);
let baseline = call(&fx.server, "health", json!({})).await;
assert_contains(&baseline, "Worktree-awareness misuse");
assert_contains(
&baseline,
"edit tool calls without working_directory (last hour): 0",
);
let _ = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() {\n println!(\"bump\");\n}",
}),
)
.await;
let after_one = call(&fx.server, "health", json!({})).await;
assert_contains(
&after_one,
"edit tool calls without working_directory (last hour): 1",
);
let _ = call(
&fx.server,
"edit_within_symbol",
json!({
"path": "src/lib.rs",
"name": "hello",
"old_text": "bump",
"new_text": "bumped",
}),
)
.await;
let after_two = call(&fx.server, "health", json!({})).await;
assert_contains(
&after_two,
"edit tool calls without working_directory (last hour): 2",
);
}
#[tokio::test]
async fn health_misuse_counter_does_not_increment_when_working_directory_supplied() {
enable_feature_flag();
let fx = WorktreeFixture::new(&[("src/lib.rs", HELLO_RS)]);
let wt_arg = fx.worktree_root.to_str().unwrap().to_string();
let _ = call(
&fx.server,
"replace_symbol_body",
json!({
"path": "src/lib.rs",
"name": "hello",
"new_body": "fn hello() { }",
"working_directory": wt_arg,
}),
)
.await;
let after = call(&fx.server, "health", json!({})).await;
assert_contains(
&after,
"edit tool calls without working_directory (last hour): 0",
);
}
#[tokio::test]
async fn conventions_surfaces_worktree_awareness_guidance() {
let fx = IndexedOnlyFixture::new(&[("src/lib.rs", HELLO_RS)]);
let output = call(&fx.server, "conventions", json!({})).await;
assert_contains(&output, "Worktree awareness");
assert_contains(&output, "working_directory");
assert_contains(&output, "SYMFORGE_WORKTREE_AWARE");
assert_contains(&output, "README");
}