| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The guides for coding agents: part 1 of AGENTS.md, which the site also |
| 5 | //! serves as agents.md, and the section `braid agents init` writes. They say |
| 6 | //! the same things in several places, they install the braid they describe, |
| 7 | //! and every braid command they give must exist, with every flag it is |
| 8 | //! given. |
| 9 | |
| 10 | use std::fs; |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | use std::process::{Command, Output}; |
| 13 | |
| 14 | use serde_json::Value; |
| 15 | |
| 16 | const START: &str = "<!-- braid:start -->"; |
| 17 | const END: &str = "<!-- braid:end -->"; |
| 18 | |
| 19 | /// The prompt that sends an agent to the guide. It asks for the page whole, |
| 20 | /// since some harnesses fetch a summary of a page rather than its text. |
| 21 | const PROMPT: &str = "Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md (read it whole, with curl -fsSL)"; |
| 22 | |
| 23 | /// The same prompt, as the Spanish page and the README's Spanish part give |
| 24 | /// it. |
| 25 | const PROMPT_ES: &str = "Instala braid en este proyecto y configúralo para agentes siguiendo https://braid.elffuss.com/agents.md (léelo entero, con curl -fsSL)"; |
| 26 | |
| 27 | fn repository_file(path: &str) -> String { |
| 28 | let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); |
| 29 | std::fs::read_to_string(root.join(path)).unwrap_or_else(|err| panic!("{path}: {err}")) |
| 30 | } |
| 31 | |
| 32 | /// Runs braid, expecting success, and returns what it printed. |
| 33 | fn braid(dir: &Path, args: &[&str]) -> String { |
| 34 | let out = Command::new(env!("CARGO_BIN_EXE_braid")) |
| 35 | .current_dir(dir) |
| 36 | .args(args) |
| 37 | .output() |
| 38 | .unwrap(); |
| 39 | assert!( |
| 40 | out.status.success(), |
| 41 | "braid {args:?}: {}", |
| 42 | String::from_utf8_lossy(&out.stderr) |
| 43 | ); |
| 44 | String::from_utf8(out.stdout).unwrap() |
| 45 | } |
| 46 | |
| 47 | /// The text of a Markdown file from `from` to `until` or the end, with every |
| 48 | /// heading one level higher when `promote` is set. |
| 49 | fn part(text: &str, from: &str, until: Option<&str>, promote: bool) -> String { |
| 50 | let start = text |
| 51 | .find(from) |
| 52 | .unwrap_or_else(|| panic!("no {from:?} in the file")); |
| 53 | let rest = &text[start..]; |
| 54 | let end = until |
| 55 | .and_then(|until| rest.find(until)) |
| 56 | .unwrap_or(rest.len()); |
| 57 | rest[..end] |
| 58 | .lines() |
| 59 | .map(|line| match line.strip_prefix('#') { |
| 60 | Some(heading) if promote && heading.starts_with('#') => heading.to_owned(), |
| 61 | _ => line.to_owned(), |
| 62 | }) |
| 63 | .collect::<Vec<_>>() |
| 64 | .join("\n") |
| 65 | } |
| 66 | |
| 67 | /// Part 1 of AGENTS.md. |
| 68 | fn part_one() -> String { |
| 69 | part( |
| 70 | &repository_file("AGENTS.md"), |
| 71 | "## 1.", |
| 72 | Some("\n## 2."), |
| 73 | false, |
| 74 | ) |
| 75 | } |
| 76 | |
| 77 | /// The section `braid agents init` writes, as its dry run prints it. |
| 78 | fn section() -> String { |
| 79 | let temp = tempfile::tempdir().unwrap(); |
| 80 | let said = braid( |
| 81 | temp.path(), |
| 82 | &["agents", "init", "--dry-run", "--branch", "main"], |
| 83 | ); |
| 84 | let start = said.find(START).expect("the dry run prints the section"); |
| 85 | said[start..].to_owned() |
| 86 | } |
| 87 | |
| 88 | /// The lines of the ```bash blocks of a Markdown text, without their |
| 89 | /// indentation. |
| 90 | fn bash_lines(text: &str) -> Vec<String> { |
| 91 | bash_blocks(text).concat() |
| 92 | } |
| 93 | |
| 94 | /// The ```bash blocks of a Markdown text, each as its lines without their |
| 95 | /// indentation. |
| 96 | fn bash_blocks(text: &str) -> Vec<Vec<String>> { |
| 97 | let mut blocks = Vec::new(); |
| 98 | let mut inside = false; |
| 99 | for line in text.lines() { |
| 100 | let line = line.trim(); |
| 101 | if line.starts_with("```") { |
| 102 | inside = !inside && line == "```bash"; |
| 103 | if inside { |
| 104 | blocks.push(Vec::new()); |
| 105 | } |
| 106 | continue; |
| 107 | } |
| 108 | if inside && let Some(block) = blocks.last_mut() { |
| 109 | block.push(line.to_owned()); |
| 110 | } |
| 111 | } |
| 112 | blocks |
| 113 | } |
| 114 | |
| 115 | /// The ```bash block of `text` with a line that starts with `first`. |
| 116 | fn block_with(text: &str, first: &str) -> Vec<String> { |
| 117 | bash_blocks(text) |
| 118 | .into_iter() |
| 119 | .find(|block| block.iter().any(|line| line.starts_with(first))) |
| 120 | .unwrap_or_else(|| panic!("no block with {first:?}")) |
| 121 | } |
| 122 | |
| 123 | /// The text of `line` without its command substitutions, such as |
| 124 | /// `"$(git branch --show-current)"`, which leaves `""`. |
| 125 | fn without_substitutions(line: &str) -> String { |
| 126 | let mut kept = String::new(); |
| 127 | let mut rest = line; |
| 128 | while let Some(start) = rest.find("$(") { |
| 129 | kept.push_str(&rest[..start]); |
| 130 | // From the opening parenthesis to the one that closes it. |
| 131 | let mut depth = 0; |
| 132 | let mut end = rest.len(); |
| 133 | for (offset, c) in rest[start + 1..].char_indices() { |
| 134 | match c { |
| 135 | '(' => depth += 1, |
| 136 | ')' => { |
| 137 | depth -= 1; |
| 138 | if depth == 0 { |
| 139 | end = start + 1 + offset + 1; |
| 140 | break; |
| 141 | } |
| 142 | } |
| 143 | _ => {} |
| 144 | } |
| 145 | } |
| 146 | rest = &rest[end..]; |
| 147 | } |
| 148 | kept.push_str(rest); |
| 149 | kept |
| 150 | } |
| 151 | |
| 152 | /// The braid commands a shell line runs, without its comment and its |
| 153 | /// command substitutions. A line may run braid after another command, |
| 154 | /// `test -d .braid || braid init`, pipe it into one, |
| 155 | /// `braid cat-object <base>:<path> | diff`, or run it inside an `if`, |
| 156 | /// `if ...; then braid git import . && braid agents init; else ...; fi`. |
| 157 | fn braid_commands(line: &str) -> Vec<String> { |
| 158 | let line = without_substitutions(line.split(" #").next().unwrap()); |
| 159 | line.split(['|', '&', ';']) |
| 160 | .map(|command| { |
| 161 | let mut command = command.trim(); |
| 162 | for keyword in ["if ", "then ", "else ", "! "] { |
| 163 | command = command.strip_prefix(keyword).unwrap_or(command).trim(); |
| 164 | } |
| 165 | command |
| 166 | }) |
| 167 | .filter(|command| command.starts_with("braid ")) |
| 168 | .map(str::to_owned) |
| 169 | .collect() |
| 170 | } |
| 171 | |
| 172 | /// Runs `line` in a new POSIX shell in `dir`, as a harness that keeps |
| 173 | /// nothing between commands runs it: with this build's braid first on |
| 174 | /// `PATH`, no braid variables, and git reading only `config` (no system |
| 175 | /// configuration) and no identity from the environment. |
| 176 | fn shell(dir: &Path, config: &Path, line: &str) -> Output { |
| 177 | let bin = Path::new(env!("CARGO_BIN_EXE_braid")).parent().unwrap(); |
| 178 | let path = std::env::join_paths(std::iter::once(bin.to_path_buf()).chain( |
| 179 | std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()), |
| 180 | )) |
| 181 | .unwrap(); |
| 182 | let mut command = Command::new("sh"); |
| 183 | command |
| 184 | .arg("-c") |
| 185 | .arg(line) |
| 186 | .current_dir(dir) |
| 187 | .env("PATH", path) |
| 188 | .env("GIT_CONFIG_GLOBAL", config) |
| 189 | .env("GIT_CONFIG_NOSYSTEM", "1") |
| 190 | // The shell sets it from the directory it starts in. |
| 191 | .env_remove("PWD"); |
| 192 | for variable in [ |
| 193 | "BRAID_AUTHOR", |
| 194 | "BRAID_AGENT", |
| 195 | "EMAIL", |
| 196 | "GIT_AUTHOR_NAME", |
| 197 | "GIT_AUTHOR_EMAIL", |
| 198 | "GIT_COMMITTER_NAME", |
| 199 | "GIT_COMMITTER_EMAIL", |
| 200 | ] { |
| 201 | command.env_remove(variable); |
| 202 | } |
| 203 | command.output().unwrap() |
| 204 | } |
| 205 | |
| 206 | /// Runs `line` as [`shell`] does, expecting success. |
| 207 | fn shell_ok(dir: &Path, config: &Path, line: &str) -> String { |
| 208 | let out = shell(dir, config, line); |
| 209 | assert!( |
| 210 | out.status.success(), |
| 211 | "{line}: {}{}", |
| 212 | String::from_utf8_lossy(&out.stdout), |
| 213 | String::from_utf8_lossy(&out.stderr) |
| 214 | ); |
| 215 | String::from_utf8(out.stdout).unwrap() |
| 216 | } |
| 217 | |
| 218 | /// A git project in `dir`, on `branch`, with one commit of `notes.txt`, and |
| 219 | /// a git configuration of its own that gives `identity` as git's user, or |
| 220 | /// none. |
| 221 | fn git_project(dir: &Path, branch: &str, identity: Option<(&str, &str)>) -> PathBuf { |
| 222 | git_project_from(dir, &format!("git init -q -b {branch}"), identity) |
| 223 | } |
| 224 | |
| 225 | /// A git project as [`git_project`] makes it, created by `init`. |
| 226 | fn git_project_from(dir: &Path, init: &str, identity: Option<(&str, &str)>) -> PathBuf { |
| 227 | fs::create_dir_all(dir).unwrap(); |
| 228 | let config = dir.with_extension("gitconfig"); |
| 229 | let user = identity.map_or_else(String::new, |(name, email)| { |
| 230 | format!("[user]\n\tname = {name}\n\temail = {email}\n") |
| 231 | }); |
| 232 | fs::write(&config, user).unwrap(); |
| 233 | fs::write(dir.join("notes.txt"), "one\ntwo\n").unwrap(); |
| 234 | for line in [ |
| 235 | init, |
| 236 | "git add notes.txt", |
| 237 | "git -c user.name=Ada -c user.email=ada@example.org commit -q -m First", |
| 238 | ] { |
| 239 | shell_ok(dir, &config, line); |
| 240 | } |
| 241 | config |
| 242 | } |
| 243 | |
| 244 | /// The line of the guide that says whether braid is set up in a project: |
| 245 | /// the guide gives it to check before anything else, and ends the setup |
| 246 | /// with it. |
| 247 | fn set_up_check(guide: &str) -> String { |
| 248 | let check = block_with(guide, "braid --version") |
| 249 | .into_iter() |
| 250 | .find(|line| line.starts_with("braid cat-object ")) |
| 251 | .expect("the guide checks whether braid is set up"); |
| 252 | let commit = block_with(guide, "git add AGENTS.md"); |
| 253 | assert_eq!(commit.last(), Some(&check), "the setup ends with the check"); |
| 254 | check |
| 255 | } |
| 256 | |
| 257 | /// What the check prints once braid is set up. |
| 258 | const SET_UP: &str = "braid is set up here\n"; |
| 259 | |
| 260 | /// The text of the file at `path` in `dir`. |
| 261 | fn read(dir: &Path, path: &str) -> String { |
| 262 | fs::read_to_string(dir.join(path)).unwrap_or_else(|err| panic!("{path}: {err}")) |
| 263 | } |
| 264 | |
| 265 | /// What `braid status --json` says in the workspace at `dir`, with no |
| 266 | /// author from the environment. |
| 267 | fn status(dir: &Path) -> Value { |
| 268 | let out = Command::new(env!("CARGO_BIN_EXE_braid")) |
| 269 | .current_dir(dir) |
| 270 | .args(["status", "--json"]) |
| 271 | .env_remove("BRAID_AUTHOR") |
| 272 | .output() |
| 273 | .unwrap(); |
| 274 | assert!( |
| 275 | out.status.success(), |
| 276 | "{}", |
| 277 | String::from_utf8_lossy(&out.stderr) |
| 278 | ); |
| 279 | serde_json::from_slice(&out.stdout).unwrap() |
| 280 | } |
| 281 | |
| 282 | #[test] |
| 283 | fn the_guide_for_agents_is_the_same_in_agents_md_and_on_the_site() { |
| 284 | let agents = repository_file("AGENTS.md"); |
| 285 | let site = repository_file("site/agents.md"); |
| 286 | let first = "### Install"; |
| 287 | let ours = part(&agents, first, Some("\n## 2."), true); |
| 288 | let theirs = part(&site, &first[1..], None, false); |
| 289 | assert_eq!(ours.trim_end(), theirs.trim_end()); |
| 290 | for text in [&agents, &site] { |
| 291 | assert!( |
| 292 | !text |
| 293 | .lines() |
| 294 | .any(|line| line.trim() == START || line.trim() == END) |
| 295 | ); |
| 296 | } |
| 297 | assert_eq!(repository_file("CLAUDE.md"), "@AGENTS.md\n"); |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn the_prompt_for_agents_is_the_same_everywhere() { |
| 302 | for path in [ |
| 303 | "README.md", |
| 304 | "site/index.html", |
| 305 | "site/scion.html", |
| 306 | "site/llms.txt", |
| 307 | ] { |
| 308 | assert!(repository_file(path).contains(PROMPT), "{path}"); |
| 309 | } |
| 310 | for path in ["README.md", "site/index.html", "site/scion.html"] { |
| 311 | assert!(repository_file(path).contains(PROMPT_ES), "{path}"); |
| 312 | } |
| 313 | assert!(PROMPT.contains(" https://braid.elffuss.com/agents.md ")); |
| 314 | assert!(repository_file("site/llms.txt").contains("(https://braid.elffuss.com/agents.md)")); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn the_site_names_the_version_of_the_code() { |
| 319 | // The home page's structured data says which braid it describes. |
| 320 | let version = env!("CARGO_PKG_VERSION"); |
| 321 | let page = repository_file("site/index.html"); |
| 322 | for field in ["version", "softwareVersion"] { |
| 323 | let pair = format!("\"{field}\": \"{version}\""); |
| 324 | assert!(page.contains(&pair), "site/index.html: {pair}"); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn the_sitemap_lists_every_page_of_the_site() { |
| 330 | let sitemap = repository_file("site/sitemap.xml"); |
| 331 | let site = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../site"); |
| 332 | for entry in fs::read_dir(&site).unwrap() { |
| 333 | let name = entry.unwrap().file_name().into_string().unwrap(); |
| 334 | if !name.ends_with(".html") { |
| 335 | continue; |
| 336 | } |
| 337 | let url = match name.as_str() { |
| 338 | "index.html" => "https://braid.elffuss.com/".to_owned(), |
| 339 | other => format!("https://braid.elffuss.com/{other}"), |
| 340 | }; |
| 341 | assert!(sitemap.contains(&format!("<loc>{url}</loc>")), "{url}"); |
| 342 | } |
| 343 | assert!( |
| 344 | repository_file("site/robots.txt") |
| 345 | .contains("Sitemap: https://braid.elffuss.com/sitemap.xml") |
| 346 | ); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn every_text_that_names_scion_says_braid_is_independent() { |
| 351 | for path in [ |
| 352 | "README.md", |
| 353 | "site/index.html", |
| 354 | "site/scion.html", |
| 355 | "site/llms.txt", |
| 356 | ] { |
| 357 | let text = repository_file(path); |
| 358 | let flat = text.split_whitespace().collect::<Vec<_>>().join(" "); |
| 359 | if flat.contains("Scion") { |
| 360 | assert!( |
| 361 | flat.contains("not affiliated with or endorsed by Anthropic"), |
| 362 | "{path}" |
| 363 | ); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | #[test] |
| 369 | fn the_guide_installs_the_braid_it_describes() { |
| 370 | // The guide is served apart from the code: it installs a tag, so that |
| 371 | // the braid an agent builds is the one the guide was written for, and |
| 372 | // the version check names that version. |
| 373 | let version = env!("CARGO_PKG_VERSION"); |
| 374 | let guide = part_one(); |
| 375 | let install = format!( |
| 376 | "cargo install --locked --git https://github.com/utopia-ia/elffuss-braid --tag v{version} elffuss-braid-cli\n" |
| 377 | ); |
| 378 | assert!(guide.contains(&install), "{install}"); |
| 379 | assert!(guide.contains(&format!("\"braid {version}\", or newer"))); |
| 380 | let printed = braid(Path::new("."), &["--version"]); |
| 381 | assert_eq!(printed, format!("braid {version}\n")); |
| 382 | // The guide's version has `agents init`: an older one is what the check |
| 383 | // sends back to the install. |
| 384 | braid(Path::new("."), &["agents", "init", "--help"]); |
| 385 | } |
| 386 | |
| 387 | /// The code spans of a Markdown text outside its fenced blocks, such as |
| 388 | /// `braid status`, wherever their lines break. |
| 389 | fn code_spans(text: &str) -> Vec<String> { |
| 390 | let mut prose = Vec::new(); |
| 391 | let mut fenced = false; |
| 392 | for line in text.lines() { |
| 393 | if line.trim().starts_with("```") { |
| 394 | fenced = !fenced; |
| 395 | } else if !fenced { |
| 396 | prose.push(line.trim()); |
| 397 | } |
| 398 | } |
| 399 | let prose = prose.join(" "); |
| 400 | assert!( |
| 401 | !prose.contains("``"), |
| 402 | "a code span of more than one backtick" |
| 403 | ); |
| 404 | prose |
| 405 | .split('`') |
| 406 | .skip(1) |
| 407 | .step_by(2) |
| 408 | .map(str::to_owned) |
| 409 | .collect() |
| 410 | } |
| 411 | |
| 412 | #[test] |
| 413 | fn every_braid_command_in_the_guides_exists_with_its_flags() { |
| 414 | let mut lines: Vec<String> = Vec::new(); |
| 415 | for text in [part_one(), section()] { |
| 416 | lines.extend(bash_lines(&text)); |
| 417 | lines.extend(code_spans(&text)); |
| 418 | } |
| 419 | let commands: Vec<String> = lines.iter().flat_map(|line| braid_commands(line)).collect(); |
| 420 | assert!(commands.len() >= 40, "{commands:?}"); |
| 421 | for (line, expected) in [ |
| 422 | ( |
| 423 | "test -d .braid || braid init # .braid/: the store", |
| 424 | vec!["braid init"], |
| 425 | ), |
| 426 | ( |
| 427 | "if grep -q x f; then braid git import . && braid agents init; else echo no >&2; false; fi", |
| 428 | vec!["braid git import .", "braid agents init"], |
| 429 | ), |
| 430 | ( |
| 431 | "braid cat-object \"$(git branch --show-current):AGENTS.md\" | grep -q x", |
| 432 | vec!["braid cat-object \":AGENTS.md\""], |
| 433 | ), |
| 434 | ] { |
| 435 | assert_eq!(braid_commands(line), expected); |
| 436 | } |
| 437 | let groups = ["agents", "change", "git", "op", "ref", "workspace"]; |
| 438 | for command in &commands { |
| 439 | let words: Vec<&str> = command.split_whitespace().skip(1).collect(); |
| 440 | let mut rest = words.as_slice(); |
| 441 | while let [flag, _, tail @ ..] = rest { |
| 442 | if matches!(*flag, "--agent" | "--workspace" | "--repo") { |
| 443 | rest = tail; |
| 444 | } else { |
| 445 | break; |
| 446 | } |
| 447 | } |
| 448 | if rest[0] == "--version" { |
| 449 | let version = braid(Path::new("."), &["--version"]); |
| 450 | assert!(version.starts_with("braid "), "{version}"); |
| 451 | continue; |
| 452 | } |
| 453 | let mut path = vec![rest[0]]; |
| 454 | if groups.contains(&rest[0]) { |
| 455 | path.push(rest[1]); |
| 456 | } |
| 457 | let mut help_args = path.clone(); |
| 458 | help_args.push("--help"); |
| 459 | let help = braid(Path::new("."), &help_args); |
| 460 | for word in &words { |
| 461 | let flag = word.split('=').next().unwrap(); |
| 462 | if flag.starts_with("--") { |
| 463 | assert!( |
| 464 | help.contains(flag), |
| 465 | "{command}: no {flag} in braid {path:?}" |
| 466 | ); |
| 467 | } else if flag.len() == 2 && flag.starts_with('-') { |
| 468 | assert!( |
| 469 | help.contains(&format!("{flag},")), |
| 470 | "{command}: no {flag} in braid {path:?}" |
| 471 | ); |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | #[test] |
| 478 | fn the_setup_stops_at_its_check_until_braid_has_a_name_and_an_email() { |
| 479 | let guide = part_one(); |
| 480 | let setup = block_with(&guide, "test -d .braid || braid init"); |
| 481 | let commit = block_with(&guide, "git add AGENTS.md"); |
| 482 | let check = set_up_check(&guide); |
| 483 | // The import and AGENTS.md wait on the name and the email, in the line |
| 484 | // that checks them, so that the setup stops there however it is run. |
| 485 | let gate = setup.len() - 1; |
| 486 | assert!( |
| 487 | setup[gate].starts_with("if grep -q '^name = .' .braid/config"), |
| 488 | "{setup:?}" |
| 489 | ); |
| 490 | for identity in [Some(("Ada Lovelace", "ada@example.org")), None] { |
| 491 | let temp = tempfile::tempdir().unwrap(); |
| 492 | let dir = fs::canonicalize(temp.path()).unwrap().join("project"); |
| 493 | let config = git_project(&dir, "main", identity); |
| 494 | assert!(!shell(&dir, &config, &check).status.success()); |
| 495 | // Each line in a shell of its own, as written: only the check fails |
| 496 | // where git has no identity. |
| 497 | let run = || -> Vec<Option<i32>> { |
| 498 | setup |
| 499 | .iter() |
| 500 | .map(|line| shell(&dir, &config, line).status.code()) |
| 501 | .collect() |
| 502 | }; |
| 503 | let failing = |index: usize| Some(i32::from(identity.is_none() && index == gate)); |
| 504 | assert_eq!(run(), (0..setup.len()).map(failing).collect::<Vec<_>>()); |
| 505 | let written = read(&dir, ".braid/config"); |
| 506 | let Some((name, email)) = identity else { |
| 507 | assert_eq!(written, "name = \nemail = \n"); |
| 508 | // The setup says why it stopped, and has imported nothing and |
| 509 | // written no AGENTS.md, whether its lines run one at a time or |
| 510 | // as one script, as a harness may run a block. |
| 511 | let stopped = shell(&dir, &config, &setup[gate]); |
| 512 | assert_eq!(stopped.status.code(), Some(1)); |
| 513 | let said = String::from_utf8_lossy(&stopped.stderr); |
| 514 | assert!(said.contains("ask the user who signs"), "{said}"); |
| 515 | let script = shell(&dir, &config, &setup.join("\n")); |
| 516 | assert_eq!(script.status.code(), Some(1)); |
| 517 | assert_eq!(shell_ok(&dir, &config, "braid refs"), ""); |
| 518 | assert!(!dir.join("AGENTS.md").exists()); |
| 519 | // The commit block, run all the same, commits nothing: git |
| 520 | // refuses to make up who signs, and the check still fails. |
| 521 | fs::write(dir.join("AGENTS.md"), "# Rules\n").unwrap(); |
| 522 | let script = shell(&dir, &config, &commit.join("\n")); |
| 523 | assert_eq!(script.status.code(), Some(1)); |
| 524 | assert_eq!(shell_ok(&dir, &config, "git log --format=%s"), "First\n"); |
| 525 | shell_ok(&dir, &config, "git reset -q && rm AGENTS.md"); |
| 526 | // Fixed as the guide says, the setup runs again from its first |
| 527 | // line without a failure, and git's commit is signed as braid's |
| 528 | // changesets are. |
| 529 | for line in block_with(&guide, "git config user.name") { |
| 530 | let line = line |
| 531 | .replace("<name>", "Grace Hopper") |
| 532 | .replace("<email>", "grace@example.org"); |
| 533 | shell_ok(&dir, &config, &line); |
| 534 | } |
| 535 | assert!(run().iter().all(|code| *code == Some(0))); |
| 536 | assert_eq!( |
| 537 | read(&dir, ".braid/config"), |
| 538 | "name = Grace Hopper\nemail = grace@example.org\n" |
| 539 | ); |
| 540 | for line in &commit { |
| 541 | shell_ok(&dir, &config, line); |
| 542 | } |
| 543 | assert_eq!( |
| 544 | shell_ok(&dir, &config, "git log -1 --format='%an <%ae>'"), |
| 545 | "Grace Hopper <grace@example.org>\n" |
| 546 | ); |
| 547 | assert_eq!(shell_ok(&dir, &config, &check), SET_UP); |
| 548 | continue; |
| 549 | }; |
| 550 | assert_eq!(written, format!("name = {name}\nemail = {email}\n")); |
| 551 | assert!(read(&dir, "AGENTS.md").contains(START)); |
| 552 | // Written but not committed, the section is not on braid's branch |
| 553 | // yet: braid is not set up. |
| 554 | assert!(!shell(&dir, &config, &check).status.success()); |
| 555 | let said: Vec<String> = commit |
| 556 | .iter() |
| 557 | .map(|line| shell_ok(&dir, &config, line)) |
| 558 | .collect(); |
| 559 | assert_eq!(said.last().map(String::as_str), Some(SET_UP)); |
| 560 | // Running the setup again changes nothing. |
| 561 | assert!(run().iter().all(|code| *code == Some(0))); |
| 562 | assert_eq!(read(&dir, ".braid/config"), written); |
| 563 | // Without anyone to sign, braid is not set up either, and the setup |
| 564 | // run again puts that right. |
| 565 | fs::remove_file(dir.join(".braid/config")).unwrap(); |
| 566 | assert!(!shell(&dir, &config, &check).status.success()); |
| 567 | assert!(run().iter().all(|code| *code == Some(0))); |
| 568 | assert_eq!(shell_ok(&dir, &config, &check), SET_UP); |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | #[test] |
| 573 | fn a_session_names_who_signs_in_the_config_of_the_project_root() { |
| 574 | let temp = tempfile::tempdir().unwrap(); |
| 575 | let dir = fs::canonicalize(temp.path()).unwrap().join("project"); |
| 576 | let config = git_project(&dir, "main", Some(("Ada Lovelace", "ada@example.org"))); |
| 577 | for line in block_with(&part_one(), "test -d .braid || braid init") { |
| 578 | shell_ok(&dir, &config, &line); |
| 579 | } |
| 580 | // Nobody signs: the session's status says so first. |
| 581 | fs::write(dir.join(".braid/config"), "name = \nemail = \n").unwrap(); |
| 582 | shell_ok(&dir, &config, "braid workspace add agent-1 --track main"); |
| 583 | let workspace = dir.join(".braid/work/agent-1"); |
| 584 | assert_eq!(status(&workspace)["blocking"][0]["reason"], "author"); |
| 585 | // In the workspace, `.braid` is a file: the config the section means |
| 586 | // is the project root's, where the lines it gives, added after the |
| 587 | // empty ones, name who signs. |
| 588 | assert!(workspace.join(".braid").is_file()); |
| 589 | let section = section().split_whitespace().collect::<Vec<_>>().join(" "); |
| 590 | assert!( |
| 591 | section.contains( |
| 592 | "write the answer into `.braid/config` in the project root, the one file there you may edit, as `name = <name>` and `email = <email>` lines" |
| 593 | ), |
| 594 | "{section}" |
| 595 | ); |
| 596 | let mut file = fs::OpenOptions::new() |
| 597 | .append(true) |
| 598 | .open(dir.join(".braid/config")) |
| 599 | .unwrap(); |
| 600 | std::io::Write::write_all( |
| 601 | &mut file, |
| 602 | b"name = Grace Hopper\nemail = grace@example.org\n", |
| 603 | ) |
| 604 | .unwrap(); |
| 605 | assert_eq!(status(&workspace)["blocking"], serde_json::json!([])); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn the_setup_runs_as_written_where_the_branch_is_master() { |
| 610 | let temp = tempfile::tempdir().unwrap(); |
| 611 | let parent = fs::canonicalize(temp.path()).unwrap(); |
| 612 | let dir = parent.join("project"); |
| 613 | let config = git_project(&dir, "master", Some(("Ada Lovelace", "ada@example.org"))); |
| 614 | let guide = part_one(); |
| 615 | let check = set_up_check(&guide); |
| 616 | // The setup, its commit, and a remote made where there is none, each |
| 617 | // line as written. |
| 618 | for first in [ |
| 619 | "test -d .braid || braid init", |
| 620 | "git add AGENTS.md", |
| 621 | "git init --bare -b", |
| 622 | ] { |
| 623 | for line in block_with(&guide, first) { |
| 624 | shell_ok(&dir, &config, &line); |
| 625 | } |
| 626 | } |
| 627 | assert_eq!(shell_ok(&dir, &config, &check), SET_UP); |
| 628 | let rules = read(&dir, "AGENTS.md"); |
| 629 | assert!(rules.contains("--track master\n"), "{rules}"); |
| 630 | // The new remote's HEAD names the branch, so that a clone checks it |
| 631 | // out, with the setup's commit. |
| 632 | let bare = parent.join("project.git"); |
| 633 | assert_eq!( |
| 634 | shell_ok(&bare, &config, "git symbolic-ref HEAD"), |
| 635 | "refs/heads/master\n" |
| 636 | ); |
| 637 | shell_ok(&parent, &config, "git clone -q project.git clone"); |
| 638 | assert_eq!(read(&parent.join("clone"), "AGENTS.md"), rules); |
| 639 | } |
| 640 | |
| 641 | #[test] |
| 642 | fn the_setup_keeps_braid_out_of_git_without_an_info_directory() { |
| 643 | // A template that holds only hooks, as hook managers set one up, gives |
| 644 | // repositories with no `.git/info`. |
| 645 | let temp = tempfile::tempdir().unwrap(); |
| 646 | let root = fs::canonicalize(temp.path()).unwrap(); |
| 647 | let template = root.join("template"); |
| 648 | fs::create_dir_all(template.join("hooks")).unwrap(); |
| 649 | let dir = root.join("project"); |
| 650 | let init = format!("git init -q -b main --template='{}'", template.display()); |
| 651 | let config = git_project_from(&dir, &init, Some(("Ada Lovelace", "ada@example.org"))); |
| 652 | assert!(!dir.join(".git/info").exists()); |
| 653 | for line in block_with(&part_one(), "test -d .braid || braid init") { |
| 654 | shell_ok(&dir, &config, &line); |
| 655 | } |
| 656 | assert_eq!(read(&dir, ".git/info/exclude"), ".braid\n"); |
| 657 | assert_eq!( |
| 658 | shell_ok( |
| 659 | &dir, |
| 660 | &config, |
| 661 | "git status --porcelain --untracked-files=all" |
| 662 | ), |
| 663 | "?? AGENTS.md\n" |
| 664 | ); |
| 665 | } |
| 666 | |
| 667 | /// The line the guides give to keep Python's build output out of a |
| 668 | /// workspace, `.braidignore` included. |
| 669 | const BRAIDIGNORE: &str = "printf '%s\\n' .braidignore __pycache__/ >> .braidignore"; |
| 670 | |
| 671 | #[test] |
| 672 | fn a_session_without_a_remote_makes_one_that_sync_and_clones_use() { |
| 673 | let temp = tempfile::tempdir().unwrap(); |
| 674 | let parent = fs::canonicalize(temp.path()).unwrap(); |
| 675 | let dir = parent.join("project"); |
| 676 | let config = git_project(&dir, "main", Some(("Ada Lovelace", "ada@example.org"))); |
| 677 | for line in block_with(&part_one(), "test -d .braid || braid init") { |
| 678 | shell_ok(&dir, &config, &line); |
| 679 | } |
| 680 | let section = section(); |
| 681 | let sync = block_with(§ion, "braid --agent agent-1 git sync"); |
| 682 | let recipe = block_with(§ion, "git init --bare"); |
| 683 | // The guide gives the same lines for a project with no remote, with the |
| 684 | // branch the shared checkout is on, which the setup has be the main |
| 685 | // one, where the section names its branch. |
| 686 | let guide: Vec<String> = block_with(&part_one(), "git init --bare -b") |
| 687 | .iter() |
| 688 | .map(|line| line.replace("\"$(git branch --show-current)\"", "main")) |
| 689 | .collect(); |
| 690 | assert_eq!(guide, recipe); |
| 691 | for text in [part_one(), section.clone()] { |
| 692 | assert!(code_spans(&text).iter().any(|span| span == BRAIDIGNORE)); |
| 693 | } |
| 694 | |
| 695 | // A session lands a change, with build output kept out of it, and |
| 696 | // what is left uncommitted holding the landing back. |
| 697 | shell_ok(&dir, &config, "braid workspace add agent-1 --track main"); |
| 698 | let workspace = dir.join(".braid/work/agent-1"); |
| 699 | fs::write(workspace.join("app.py"), "print('hi')\n").unwrap(); |
| 700 | fs::create_dir(workspace.join("__pycache__")).unwrap(); |
| 701 | fs::write(workspace.join("__pycache__/app.cpython.pyc"), [0u8, 1]).unwrap(); |
| 702 | let before = status(&workspace)["added"].clone(); |
| 703 | assert_eq!( |
| 704 | before, |
| 705 | serde_json::json!(["__pycache__/app.cpython.pyc", "app.py"]) |
| 706 | ); |
| 707 | shell_ok(&workspace, &config, BRAIDIGNORE); |
| 708 | assert_eq!(status(&workspace)["added"], serde_json::json!(["app.py"])); |
| 709 | fs::write(workspace.join("notes.txt"), "one\ntwo, the agent's\n").unwrap(); |
| 710 | let session = "braid --agent agent-1"; |
| 711 | shell_ok( |
| 712 | &workspace, |
| 713 | &config, |
| 714 | &format!("{session} commit -m 'Add app.py' app.py"), |
| 715 | ); |
| 716 | let held = shell(&workspace, &config, &format!("{session} land")); |
| 717 | assert_eq!(held.status.code(), Some(1)); |
| 718 | let said = String::from_utf8_lossy(&held.stderr); |
| 719 | assert!( |
| 720 | said.contains("uncommitted changes (1 path, \"notes.txt\")"), |
| 721 | "{said}" |
| 722 | ); |
| 723 | shell_ok( |
| 724 | &workspace, |
| 725 | &config, |
| 726 | &format!("{session} commit -m 'Edit notes'"), |
| 727 | ); |
| 728 | shell_ok(&workspace, &config, &format!("{session} land")); |
| 729 | |
| 730 | // The sync fails without a remote, as the section says; the recipe makes |
| 731 | // one next to the project, and the sync then reaches it and the shared |
| 732 | // checkout. |
| 733 | assert!(!shell(&dir, &config, &sync[0]).status.success()); |
| 734 | for line in &recipe { |
| 735 | let out = shell(&dir, &config, line); |
| 736 | assert!(out.status.success(), "{line}: {:?}", out); |
| 737 | let said = String::from_utf8_lossy(&out.stderr); |
| 738 | assert!(!said.contains("hint:"), "{line}: {said}"); |
| 739 | } |
| 740 | let bare = parent.join("project.git"); |
| 741 | assert_eq!( |
| 742 | shell_ok(&dir, &config, "git remote get-url origin"), |
| 743 | format!("{}\n", bare.display()) |
| 744 | ); |
| 745 | assert_eq!( |
| 746 | shell_ok(&bare, &config, "git symbolic-ref HEAD"), |
| 747 | "refs/heads/main\n" |
| 748 | ); |
| 749 | for line in &sync { |
| 750 | shell_ok(&dir, &config, line); |
| 751 | } |
| 752 | assert_eq!(read(&dir, "app.py"), "print('hi')\n"); |
| 753 | assert_eq!(read(&dir, "notes.txt"), "one\ntwo, the agent's\n"); |
| 754 | // A clone of the new remote checks out its main. |
| 755 | shell_ok(&parent, &config, "git clone -q project.git clone"); |
| 756 | assert_eq!(read(&parent.join("clone"), "app.py"), "print('hi')\n"); |
| 757 | for kept_out in ["__pycache__", ".braidignore", ".braid"] { |
| 758 | assert!(!parent.join("clone").join(kept_out).exists(), "{kept_out}"); |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /// The heading of the guide that says how to keep the git remote in step, |
| 763 | /// and what to do when a sync fails. |
| 764 | const SYNC_HEADING: &str = "Keeping the git remote up to date"; |
| 765 | |
| 766 | #[test] |
| 767 | fn the_section_sends_a_failed_sync_to_the_guide() { |
| 768 | assert!(part_one().contains(&format!("\n### {SYNC_HEADING}\n"))); |
| 769 | let section = section().split_whitespace().collect::<Vec<_>>().join(" "); |
| 770 | for said in [ |
| 771 | "If the sync exits with 2 (`conflicts`)", |
| 772 | &format!("as <https://braid.elffuss.com/agents.md> shows under \"{SYNC_HEADING}\""), |
| 773 | "With `remote_moved` (exit status 1), sync again; with `rejected`, ask the user.", |
| 774 | "If `git pull --ff-only` refuses,", |
| 775 | ] { |
| 776 | assert!(section.contains(said), "{said}: {section}"); |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn a_sync_conflict_is_merged_in_git_as_the_guide_says() { |
| 782 | let temp = tempfile::tempdir().unwrap(); |
| 783 | let parent = fs::canonicalize(temp.path()).unwrap(); |
| 784 | let dir = parent.join("project"); |
| 785 | let config = git_project(&dir, "main", Some(("Ada Lovelace", "ada@example.org"))); |
| 786 | let guide = part_one(); |
| 787 | // A remote, the setup and its commit, each line as written, and a sync |
| 788 | // that takes the commit to the remote. |
| 789 | for first in [ |
| 790 | "git init --bare -b", |
| 791 | "test -d .braid || braid init", |
| 792 | "git add AGENTS.md", |
| 793 | "braid --agent agent-1 git sync", |
| 794 | ] { |
| 795 | for line in block_with(&guide, first) { |
| 796 | shell_ok(&dir, &config, &line); |
| 797 | } |
| 798 | } |
| 799 | let sync = block_with(&guide, "braid --agent agent-1 git sync") |
| 800 | .into_iter() |
| 801 | .find(|line| !line.contains("--dry-run") && line.starts_with("braid ")) |
| 802 | .unwrap(); |
| 803 | |
| 804 | // A session lands an edit of a line that someone else edits and pushes. |
| 805 | shell_ok(&dir, &config, "braid workspace add agent-1 --track main"); |
| 806 | let workspace = dir.join(".braid/work/agent-1"); |
| 807 | fs::write(workspace.join("notes.txt"), "one\ntwo, the agent's\n").unwrap(); |
| 808 | for line in [ |
| 809 | "braid --agent agent-1 commit -m 'The agent edits notes'", |
| 810 | "braid --agent agent-1 land", |
| 811 | ] { |
| 812 | shell_ok(&workspace, &config, line); |
| 813 | } |
| 814 | shell_ok(&parent, &config, "git clone -q project.git person"); |
| 815 | let person = parent.join("person"); |
| 816 | fs::write(person.join("notes.txt"), "one\ntwo, the person's\n").unwrap(); |
| 817 | shell_ok( |
| 818 | &person, |
| 819 | &config, |
| 820 | "git commit -q -am 'The person edits notes'", |
| 821 | ); |
| 822 | shell_ok(&person, &config, "git push -q"); |
| 823 | |
| 824 | // The sync stops, and says where the steps are. |
| 825 | let stopped = shell(&dir, &config, &sync); |
| 826 | assert_eq!(stopped.status.code(), Some(2)); |
| 827 | let said = String::from_utf8_lossy(&stopped.stdout); |
| 828 | assert!(said.contains("CONTENT notes.txt"), "{said}"); |
| 829 | assert!( |
| 830 | said.contains(&format!( |
| 831 | "https://braid.elffuss.com/agents.md shows how, under \"{SYNC_HEADING}\"" |
| 832 | )), |
| 833 | "{said}" |
| 834 | ); |
| 835 | |
| 836 | // The guide's steps, with the conflict fixed where git stops. |
| 837 | let recipe = block_with(&guide, "git init --bare .braid/export.git"); |
| 838 | let merge = recipe |
| 839 | .iter() |
| 840 | .position(|line| line.starts_with("git merge --no-edit origin/main")) |
| 841 | .expect("the remote's branch is merged into braid's"); |
| 842 | assert_eq!( |
| 843 | recipe[merge + 1], |
| 844 | "# if it stopped: fix those files and git add them, then git commit --no-edit --cleanup=strip" |
| 845 | ); |
| 846 | for (index, line) in recipe.iter().enumerate() { |
| 847 | let out = shell(&dir, &config, line); |
| 848 | if index == merge { |
| 849 | assert_eq!(out.status.code(), Some(1), "git stops at the conflict"); |
| 850 | fs::write(dir.join("notes.txt"), "one\ntwo, both\n").unwrap(); |
| 851 | shell_ok(&dir, &config, "git add notes.txt"); |
| 852 | shell_ok(&dir, &config, "git commit -q --no-edit --cleanup=strip"); |
| 853 | continue; |
| 854 | } |
| 855 | assert!( |
| 856 | out.status.success(), |
| 857 | "{line}: {}", |
| 858 | String::from_utf8_lossy(&out.stderr) |
| 859 | ); |
| 860 | } |
| 861 | // The merge's message names the branch, not the remote's address, and |
| 862 | // braid's branch is its first parent; braid's main and the remote's are |
| 863 | // the merge. |
| 864 | let merged = shell_ok(&dir, &config, "git log -1 --format=%B"); |
| 865 | assert_eq!( |
| 866 | merged.trim_end(), |
| 867 | "Merge remote-tracking branch 'origin/main'" |
| 868 | ); |
| 869 | assert_eq!( |
| 870 | shell_ok(&dir, &config, "git log -1 --format=%s HEAD^1"), |
| 871 | "The agent edits notes\n" |
| 872 | ); |
| 873 | let head = shell_ok(&dir, &config, "git rev-parse HEAD"); |
| 874 | assert_eq!( |
| 875 | shell_ok(&parent.join("project.git"), &config, "git rev-parse main"), |
| 876 | head |
| 877 | ); |
| 878 | assert!( |
| 879 | shell_ok(&dir, &config, "braid log main -n 1") |
| 880 | .contains("Merge remote-tracking branch 'origin/main'") |
| 881 | ); |
| 882 | // The session carries on from the merge, and the next sync has nothing |
| 883 | // to do. |
| 884 | shell_ok(&workspace, &config, "braid --agent agent-1 update"); |
| 885 | assert_eq!(status(&workspace)["behind_by"], 0); |
| 886 | assert_eq!(read(&workspace, "notes.txt"), "one\ntwo, both\n"); |
| 887 | assert!(shell_ok(&dir, &config, &sync).contains("up to date")); |
| 888 | assert!(!dir.join(".braid/export.git").exists()); |
| 889 | } |