use std::path::{Path, PathBuf};
use std::process::Command;
use chrono::{DateTime, TimeZone, Utc};
use second_brain_adapters::encode_project_dir;
use second_brain_adapters::git::{
COMMIT_SOURCE, Checkout, Commit, GitHubRepo, PR_SOURCE, PullRequest, commit_result,
parse_github_url, pull_request_result,
};
use second_brain_core::schema::MemoryType;
use uuid::Uuid;
fn git(dir: &Path, args: &[&str]) -> String {
git_at(dir, args, None)
}
fn git_at(dir: &Path, args: &[&str], date: Option<&str>) -> String {
let mut cmd = Command::new("git");
cmd.arg("-C")
.arg(dir)
.args([
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"-c",
"commit.gpgsign=false",
"-c",
"init.defaultBranch=main",
])
.args(args)
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", "/dev/null");
if let Some(date) = date {
cmd.env("GIT_COMMITTER_DATE", date)
.env("GIT_AUTHOR_DATE", date);
}
let out = cmd.output().expect("git runs");
assert!(
out.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn init(dir: &Path) {
git(dir, &["init", "-q"]);
}
fn commit(dir: &Path, message: &str) -> String {
git(dir, &["commit", "-q", "--allow-empty", "-m", message]);
git(dir, &["rev-parse", "HEAD"])
}
fn repo() -> (tempfile::TempDir, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("widgets");
std::fs::create_dir(&root).unwrap();
init(&root);
let root = root.canonicalize().unwrap();
(tmp, root)
}
fn shas(commits: &[Commit]) -> Vec<String> {
commits.iter().map(|c| c.sha.clone()).collect()
}
#[test]
fn parse_github_url_accepts_github_forms_only() {
let ok = |owner: &str, name: &str| {
Some(GitHubRepo {
owner: owner.to_string(),
name: name.to_string(),
})
};
let cases: &[(&str, Option<GitHubRepo>)] = &[
(
"https://github.com/example/widgets",
ok("example", "widgets"),
),
(
"https://github.com/example/widgets.git",
ok("example", "widgets"),
),
(
"https://github.com/example/widgets/",
ok("example", "widgets"),
),
(
"https://github.com/example/widgets.git/",
ok("example", "widgets"),
),
(
"http://github.com/example/widgets",
ok("example", "widgets"),
),
(
"HTTPS://GitHub.COM/Example/Widgets",
ok("Example", "Widgets"),
),
(
"https://someone@github.com/example/widgets.git",
ok("example", "widgets"),
),
(
"https://github.com:443/example/widgets",
ok("example", "widgets"),
),
(
"git@github.com:example/widgets.git",
ok("example", "widgets"),
),
("git@github.com:example/widgets", ok("example", "widgets")),
(
"ssh://git@github.com/example/widgets.git",
ok("example", "widgets"),
),
(
"ssh://git@github.com:22/example/widgets.git",
ok("example", "widgets"),
),
(
" https://github.com/example/my.widgets_v2-x.git\n",
ok("example", "my.widgets_v2-x"),
),
("https://gitlab.com/example/widgets.git", None),
("git@gitlab.com:example/widgets.git", None),
("https://github.com.evil.example/example/widgets", None),
("git@github.com.evil.example:example/widgets", None),
("https://evilgithub.com/example/widgets", None),
("https://github.com@evil.example/example/widgets", None),
("https://evil.example/github.com/example/widgets", None),
("https://www.github.com/example/widgets", None),
("ssh://git@github.com:notaport/example/widgets", None),
("https://github.com/example", None),
("https://github.com/example/widgets/tree/main", None),
("https://github.com/example/widgets?tab=readme", None),
("https://github.com//widgets", None),
("https://github.com/example/.git", None),
("https://github.com/example/..", None),
("git://github.com/example/widgets.git", None),
("file:///srv/github.com/example/widgets", None),
("/srv/git/widgets.git", None),
("", None),
];
for (url, want) in cases {
assert_eq!(&parse_github_url(url), want, "url {url:?}");
}
}
#[test]
fn encode_project_dir_replaces_every_non_alphanumeric_character() {
assert_eq!(
encode_project_dir(Path::new("/srv/data/my.repo_x")),
"-srv-data-my-repo-x"
);
assert_eq!(
encode_project_dir(Path::new("/srv/u/.claude/w 1")),
"-srv-u--claude-w-1"
);
assert_eq!(encode_project_dir(Path::new("/srv/caf\u{e9}")), "-srv-caf-");
assert_eq!(
encode_project_dir(Path::new("/srv/a\u{1F600}b")),
"-srv-a--b"
);
}
#[test]
fn containing_is_none_outside_a_work_tree() {
let tmp = tempfile::tempdir().unwrap();
assert_eq!(Checkout::containing(tmp.path()), None);
assert_eq!(Checkout::containing(&tmp.path().join("missing")), None);
let bare = tmp.path().join("bare.git");
std::fs::create_dir(&bare).unwrap();
git(&bare, &["init", "-q", "--bare"]);
assert_eq!(Checkout::containing(&bare), None);
}
#[test]
fn containing_maps_subdirectories_and_worktrees_to_the_main_checkout() {
let (tmp, root) = repo();
commit(&root, "first");
let sub = root.join("src/deep");
std::fs::create_dir_all(&sub).unwrap();
let checkout = Checkout::containing(&root).unwrap();
assert_eq!(checkout.root(), root.as_path());
assert_eq!(Checkout::containing(&sub).unwrap(), checkout);
assert_eq!(checkout.project_slug(), encode_project_dir(&root));
let wt = tmp.path().join("wt-side");
git(
&root,
&["worktree", "add", "-q", "-b", "side", wt.to_str().unwrap()],
);
assert_eq!(Checkout::containing(&wt).unwrap(), checkout);
assert_eq!(Checkout::containing(&root.join(".git")), None);
}
#[test]
fn empty_repo_has_no_head_and_no_commits() {
let (_tmp, root) = repo();
let checkout = Checkout::containing(&root).unwrap();
assert_eq!(checkout.head().unwrap(), None);
assert!(checkout.commits_since(None, 10).unwrap().is_empty());
}
#[test]
fn commits_since_reads_full_commits_newest_first() {
let (_tmp, root) = repo();
git_at(
&root,
&[
"commit",
"-q",
"--allow-empty",
"-m",
"Add the parser\n\nIt handles nested lists.\nSecond body line.",
],
Some("2026-03-04T05:06:07+02:00"),
);
let first = git(&root, &["rev-parse", "HEAD"]);
let second = commit(&root, "Fix the parser");
let checkout = Checkout::containing(&root).unwrap();
assert_eq!(checkout.head().unwrap(), Some(second.clone()));
let commits = checkout.commits_since(None, 10).unwrap();
assert_eq!(shas(&commits), vec![second.clone(), first.clone()]);
let oldest = &commits[1];
assert_eq!(oldest.author, "Test");
assert_eq!(
oldest.committed_at,
Utc.with_ymd_and_hms(2026, 3, 4, 3, 6, 7).unwrap()
);
assert_eq!(
oldest.message.trim(),
"Add the parser\n\nIt handles nested lists.\nSecond body line."
);
assert_eq!(commits[0].message.trim(), "Fix the parser");
}
#[test]
fn commits_since_stops_at_since_and_honours_the_limit() {
let (_tmp, root) = repo();
let a = commit(&root, "a");
let b = commit(&root, "b");
let c = commit(&root, "c");
let d = commit(&root, "d");
let checkout = Checkout::containing(&root).unwrap();
assert_eq!(
shas(&checkout.commits_since(Some(&b), 10).unwrap()),
vec![d.clone(), c.clone()]
);
assert!(checkout.commits_since(Some(&d), 10).unwrap().is_empty());
assert_eq!(
shas(&checkout.commits_since(None, 2).unwrap()),
vec![d.clone(), c.clone()]
);
assert_eq!(
shas(&checkout.commits_since(Some(&a[..12]), 10).unwrap()),
vec![d, c, b]
);
assert!(checkout.commits_since(None, 0).unwrap().is_empty());
}
#[test]
fn commits_since_treats_unknown_or_rewritten_since_as_none() {
let (_tmp, root) = repo();
let a = commit(&root, "a");
let b = commit(&root, "b");
git(&root, &["reset", "-q", "--hard", &a]);
let b2 = commit(&root, "b rewritten");
let checkout = Checkout::containing(&root).unwrap();
let all = vec![b2.clone(), a.clone()];
assert_eq!(shas(&checkout.commits_since(Some(&b), 10).unwrap()), all);
assert_eq!(
shas(
&checkout
.commits_since(Some("0123456789abcdef0123456789abcdef01234567"), 10)
.unwrap()
),
all
);
assert_eq!(
shas(&checkout.commits_since(Some("--all"), 10).unwrap()),
all
);
assert_eq!(shas(&checkout.commits_since(Some(""), 10).unwrap()), all);
}
#[test]
fn commits_since_skips_merge_commits() {
let (_tmp, root) = repo();
let base = commit(&root, "base");
git(&root, &["checkout", "-q", "-b", "topic"]);
let topic = commit(&root, "topic work");
git(&root, &["checkout", "-q", "main"]);
let mainline = commit(&root, "main work");
git(
&root,
&[
"merge",
"-q",
"--no-ff",
"-m",
"Merge branch topic",
"topic",
],
);
let checkout = Checkout::containing(&root).unwrap();
let commits = checkout.commits_since(None, 10).unwrap();
let mut got = shas(&commits);
got.sort();
let mut want = vec![base, topic, mainline];
want.sort();
assert_eq!(got, want);
assert!(commits.iter().all(|c| !c.message.contains("Merge branch")));
}
#[test]
fn github_remote_prefers_origin_then_the_first_github_remote() {
let (_tmp, root) = repo();
let checkout = Checkout::containing(&root).unwrap();
assert_eq!(checkout.github_remote(), None);
git(
&root,
&[
"remote",
"add",
"mirror",
"https://gitlab.com/example/widgets.git",
],
);
assert_eq!(checkout.github_remote(), None);
git(
&root,
&[
"remote",
"add",
"fork",
"git@github.com:someone/widgets.git",
],
);
assert_eq!(
checkout.github_remote(),
Some(GitHubRepo {
owner: "someone".into(),
name: "widgets".into()
})
);
git(
&root,
&[
"remote",
"add",
"origin",
"https://github.com/example/widgets.git",
],
);
assert_eq!(
checkout.github_remote(),
Some(GitHubRepo {
owner: "example".into(),
name: "widgets".into()
})
);
}
#[test]
fn commit_result_builds_one_deterministic_memory() {
let (_tmp, root) = repo();
commit(&root, "x");
let checkout = Checkout::containing(&root).unwrap();
let sha = "0123456789abcdef0123456789abcdef01234567".to_string();
let at: DateTime<Utc> = Utc.with_ymd_and_hms(2026, 5, 6, 7, 8, 9).unwrap();
let c = Commit {
sha: sha.clone(),
author: "Test".into(),
committed_at: at,
message: " Add the parser\n\nIt handles nested lists.\n\n".into(),
};
let result = commit_result(&checkout, &c, "machine-1");
assert_eq!(result.memories.len(), 1);
assert!(result.entities.is_empty());
let m = &result.memories[0];
assert_eq!(
m.content,
"Add the parser\n\nIt handles nested lists.\n\nCommit 0123456789ab by Test"
);
assert_eq!(m.source, COMMIT_SOURCE);
assert_eq!(m.source_id, format!("{}@{sha}", root.display()));
assert_eq!(
m.id,
Uuid::new_v5(&Uuid::NAMESPACE_OID, format!("git-commit:{sha}").as_bytes())
);
assert_eq!(m.memory_type, MemoryType::Episodic);
assert_eq!(
m.project_path.as_deref(),
Some(checkout.project_slug().as_str())
);
assert_eq!(m.session_at, Some(at));
assert_eq!(m.machine_id, "machine-1");
let conv = &result.conversation;
assert_eq!(
conv.id,
Uuid::new_v5(
&Uuid::NAMESPACE_OID,
format!("git-commit-repo:{}", root.display()).as_bytes()
)
);
assert_eq!(conv.source, COMMIT_SOURCE);
assert_eq!(conv.started_at, at);
assert_eq!(conv.machine_id, "machine-1");
assert_eq!(conv.project_path, m.project_path);
assert_eq!(m.conversation_id, Some(conv.id));
let again = commit_result(&checkout, &c, "machine-1");
assert_eq!(again.memories[0].id, m.id);
assert_eq!(again.conversation.id, conv.id);
}
#[test]
fn pull_request_result_ids_follow_title_and_body() {
let (_tmp, root) = repo();
commit(&root, "x");
let checkout = Checkout::containing(&root).unwrap();
let repo = GitHubRepo {
owner: "example".into(),
name: "widgets".into(),
};
let at = Utc.with_ymd_and_hms(2026, 6, 7, 8, 9, 10).unwrap();
let pr = PullRequest {
number: 42,
title: "Speed up the parser".into(),
body: "\nUses a single pass.\n".into(),
url: "https://github.com/example/widgets/pull/42".into(),
updated_at: at,
};
let result = pull_request_result(&checkout, &repo, &pr, "machine-1", None);
assert_eq!(result.memories.len(), 1);
assert!(result.entities.is_empty());
let m = &result.memories[0];
assert_eq!(
m.content,
"PR #42: Speed up the parser\n\nUses a single pass.\n\nhttps://github.com/example/widgets/pull/42"
);
assert_eq!(m.source, PR_SOURCE);
assert_eq!(m.source_id, pr.url);
assert_eq!(m.memory_type, MemoryType::Episodic);
assert_eq!(m.session_at, Some(at));
assert_eq!(m.machine_id, "machine-1");
assert_eq!(
m.project_path.as_deref(),
Some(checkout.project_slug().as_str())
);
let conv = &result.conversation;
assert_eq!(
conv.id,
Uuid::new_v5(&Uuid::NAMESPACE_OID, b"git-pr-repo:example/widgets")
);
assert_eq!(conv.source, PR_SOURCE);
assert_eq!(conv.started_at, at);
assert_eq!(m.conversation_id, Some(conv.id));
let same = pull_request_result(&checkout, &repo, &pr, "machine-1", None);
assert_eq!(same.memories[0].id, m.id);
let later = PullRequest {
updated_at: Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
..pr
};
assert_eq!(
pull_request_result(&checkout, &repo, &later, "machine-1", None).memories[0].id,
m.id
);
let edited = PullRequest {
body: "Uses two passes.".into(),
..later
};
assert_ne!(
pull_request_result(&checkout, &repo, &edited, "machine-1", None).memories[0].id,
m.id
);
}