| 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 ["README.md", "site/index.html", "site/llms.txt"] { |
| 303 | assert!(repository_file(path).contains(PROMPT), "{path}"); |
| 304 | } |
| 305 | for path in ["README.md", "site/index.html"] { |
| 306 | assert!(repository_file(path).contains(PROMPT_ES), "{path}"); |
| 307 | } |
| 308 | assert!(PROMPT.contains(" https://braid.elffuss.com/agents.md ")); |
| 309 | assert!(repository_file("site/llms.txt").contains("(https://braid.elffuss.com/agents.md)")); |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn the_guide_installs_the_braid_it_describes() { |
| 314 | // The guide is served apart from the code: it installs a tag, so that |
| 315 | // the braid an agent builds is the one the guide was written for, and |
| 316 | // the version check names that version. |
| 317 | let version = env!("CARGO_PKG_VERSION"); |
| 318 | let guide = part_one(); |
| 319 | let install = format!( |
| 320 | "cargo install --locked --git https://github.com/KikoCis/elffuss-braid --tag v{version} elffuss-braid-cli\n" |
| 321 | ); |
| 322 | assert!(guide.contains(&install), "{install}"); |
| 323 | assert!(guide.contains(&format!("\"braid {version}\", or newer"))); |
| 324 | let printed = braid(Path::new("."), &["--version"]); |
| 325 | assert_eq!(printed, format!("braid {version}\n")); |
| 326 | // The guide's version has `agents init`: an older one is what the check |
| 327 | // sends back to the install. |
| 328 | braid(Path::new("."), &["agents", "init", "--help"]); |
| 329 | } |
| 330 | |
| 331 | /// The code spans of a Markdown text outside its fenced blocks, such as |
| 332 | /// `braid status`, wherever their lines break. |
| 333 | fn code_spans(text: &str) -> Vec<String> { |
| 334 | let mut prose = Vec::new(); |
| 335 | let mut fenced = false; |
| 336 | for line in text.lines() { |
| 337 | if line.trim().starts_with("```") { |
| 338 | fenced = !fenced; |
| 339 | } else if !fenced { |
| 340 | prose.push(line.trim()); |
| 341 | } |
| 342 | } |
| 343 | let prose = prose.join(" "); |
| 344 | assert!( |
| 345 | !prose.contains("``"), |
| 346 | "a code span of more than one backtick" |
| 347 | ); |
| 348 | prose |
| 349 | .split('`') |
| 350 | .skip(1) |
| 351 | .step_by(2) |
| 352 | .map(str::to_owned) |
| 353 | .collect() |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn every_braid_command_in_the_guides_exists_with_its_flags() { |
| 358 | let mut lines: Vec<String> = Vec::new(); |
| 359 | for text in [part_one(), section()] { |
| 360 | lines.extend(bash_lines(&text)); |
| 361 | lines.extend(code_spans(&text)); |
| 362 | } |
| 363 | let commands: Vec<String> = lines.iter().flat_map(|line| braid_commands(line)).collect(); |
| 364 | assert!(commands.len() >= 40, "{commands:?}"); |
| 365 | for (line, expected) in [ |
| 366 | ( |
| 367 | "test -d .braid || braid init # .braid/: the store", |
| 368 | vec!["braid init"], |
| 369 | ), |
| 370 | ( |
| 371 | "if grep -q x f; then braid git import . && braid agents init; else echo no >&2; false; fi", |
| 372 | vec!["braid git import .", "braid agents init"], |
| 373 | ), |
| 374 | ( |
| 375 | "braid cat-object \"$(git branch --show-current):AGENTS.md\" | grep -q x", |
| 376 | vec!["braid cat-object \":AGENTS.md\""], |
| 377 | ), |
| 378 | ] { |
| 379 | assert_eq!(braid_commands(line), expected); |
| 380 | } |
| 381 | let groups = ["agents", "change", "git", "op", "ref", "workspace"]; |
| 382 | for command in &commands { |
| 383 | let words: Vec<&str> = command.split_whitespace().skip(1).collect(); |
| 384 | let mut rest = words.as_slice(); |
| 385 | while let [flag, _, tail @ ..] = rest { |
| 386 | if matches!(*flag, "--agent" | "--workspace" | "--repo") { |
| 387 | rest = tail; |
| 388 | } else { |
| 389 | break; |
| 390 | } |
| 391 | } |
| 392 | if rest[0] == "--version" { |
| 393 | let version = braid(Path::new("."), &["--version"]); |
| 394 | assert!(version.starts_with("braid "), "{version}"); |
| 395 | continue; |
| 396 | } |
| 397 | let mut path = vec![rest[0]]; |
| 398 | if groups.contains(&rest[0]) { |
| 399 | path.push(rest[1]); |
| 400 | } |
| 401 | let mut help_args = path.clone(); |
| 402 | help_args.push("--help"); |
| 403 | let help = braid(Path::new("."), &help_args); |
| 404 | for word in &words { |
| 405 | let flag = word.split('=').next().unwrap(); |
| 406 | if flag.starts_with("--") { |
| 407 | assert!( |
| 408 | help.contains(flag), |
| 409 | "{command}: no {flag} in braid {path:?}" |
| 410 | ); |
| 411 | } else if flag.len() == 2 && flag.starts_with('-') { |
| 412 | assert!( |
| 413 | help.contains(&format!("{flag},")), |
| 414 | "{command}: no {flag} in braid {path:?}" |
| 415 | ); |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn the_setup_stops_at_its_check_until_braid_has_a_name_and_an_email() { |
| 423 | let guide = part_one(); |
| 424 | let setup = block_with(&guide, "test -d .braid || braid init"); |
| 425 | let commit = block_with(&guide, "git add AGENTS.md"); |
| 426 | let check = set_up_check(&guide); |
| 427 | // The import and AGENTS.md wait on the name and the email, in the line |
| 428 | // that checks them, so that the setup stops there however it is run. |
| 429 | let gate = setup.len() - 1; |
| 430 | assert!( |
| 431 | setup[gate].starts_with("if grep -q '^name = .' .braid/config"), |
| 432 | "{setup:?}" |
| 433 | ); |
| 434 | for identity in [Some(("Ada Lovelace", "ada@example.org")), None] { |
| 435 | let temp = tempfile::tempdir().unwrap(); |
| 436 | let dir = fs::canonicalize(temp.path()).unwrap().join("project"); |
| 437 | let config = git_project(&dir, "main", identity); |
| 438 | assert!(!shell(&dir, &config, &check).status.success()); |
| 439 | // Each line in a shell of its own, as written: only the check fails |
| 440 | // where git has no identity. |
| 441 | let run = || -> Vec<Option<i32>> { |
| 442 | setup |
| 443 | .iter() |
| 444 | .map(|line| shell(&dir, &config, line).status.code()) |
| 445 | .collect() |
| 446 | }; |
| 447 | let failing = |index: usize| Some(i32::from(identity.is_none() && index == gate)); |
| 448 | assert_eq!(run(), (0..setup.len()).map(failing).collect::<Vec<_>>()); |
| 449 | let written = read(&dir, ".braid/config"); |
| 450 | let Some((name, email)) = identity else { |
| 451 | assert_eq!(written, "name = \nemail = \n"); |
| 452 | // The setup says why it stopped, and has imported nothing and |
| 453 | // written no AGENTS.md, whether its lines run one at a time or |
| 454 | // as one script, as a harness may run a block. |
| 455 | let stopped = shell(&dir, &config, &setup[gate]); |
| 456 | assert_eq!(stopped.status.code(), Some(1)); |
| 457 | let said = String::from_utf8_lossy(&stopped.stderr); |
| 458 | assert!(said.contains("ask the user who signs"), "{said}"); |
| 459 | let script = shell(&dir, &config, &setup.join("\n")); |
| 460 | assert_eq!(script.status.code(), Some(1)); |
| 461 | assert_eq!(shell_ok(&dir, &config, "braid refs"), ""); |
| 462 | assert!(!dir.join("AGENTS.md").exists()); |
| 463 | // The commit block, run all the same, commits nothing: git |
| 464 | // refuses to make up who signs, and the check still fails. |
| 465 | fs::write(dir.join("AGENTS.md"), "# Rules\n").unwrap(); |
| 466 | let script = shell(&dir, &config, &commit.join("\n")); |
| 467 | assert_eq!(script.status.code(), Some(1)); |
| 468 | assert_eq!(shell_ok(&dir, &config, "git log --format=%s"), "First\n"); |
| 469 | shell_ok(&dir, &config, "git reset -q && rm AGENTS.md"); |
| 470 | // Fixed as the guide says, the setup runs again from its first |
| 471 | // line without a failure, and git's commit is signed as braid's |
| 472 | // changesets are. |
| 473 | for line in block_with(&guide, "git config user.name") { |
| 474 | let line = line |
| 475 | .replace("<name>", "Grace Hopper") |
| 476 | .replace("<email>", "grace@example.org"); |
| 477 | shell_ok(&dir, &config, &line); |
| 478 | } |
| 479 | assert!(run().iter().all(|code| *code == Some(0))); |
| 480 | assert_eq!( |
| 481 | read(&dir, ".braid/config"), |
| 482 | "name = Grace Hopper\nemail = grace@example.org\n" |
| 483 | ); |
| 484 | for line in &commit { |
| 485 | shell_ok(&dir, &config, line); |
| 486 | } |
| 487 | assert_eq!( |
| 488 | shell_ok(&dir, &config, "git log -1 --format='%an <%ae>'"), |
| 489 | "Grace Hopper <grace@example.org>\n" |
| 490 | ); |
| 491 | assert_eq!(shell_ok(&dir, &config, &check), SET_UP); |
| 492 | continue; |
| 493 | }; |
| 494 | assert_eq!(written, format!("name = {name}\nemail = {email}\n")); |
| 495 | assert!(read(&dir, "AGENTS.md").contains(START)); |
| 496 | // Written but not committed, the section is not on braid's branch |
| 497 | // yet: braid is not set up. |
| 498 | assert!(!shell(&dir, &config, &check).status.success()); |
| 499 | let said: Vec<String> = commit |
| 500 | .iter() |
| 501 | .map(|line| shell_ok(&dir, &config, line)) |
| 502 | .collect(); |
| 503 | assert_eq!(said.last().map(String::as_str), Some(SET_UP)); |
| 504 | // Running the setup again changes nothing. |
| 505 | assert!(run().iter().all(|code| *code == Some(0))); |
| 506 | assert_eq!(read(&dir, ".braid/config"), written); |
| 507 | // Without anyone to sign, braid is not set up either, and the setup |
| 508 | // run again puts that right. |
| 509 | fs::remove_file(dir.join(".braid/config")).unwrap(); |
| 510 | assert!(!shell(&dir, &config, &check).status.success()); |
| 511 | assert!(run().iter().all(|code| *code == Some(0))); |
| 512 | assert_eq!(shell_ok(&dir, &config, &check), SET_UP); |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn a_session_names_who_signs_in_the_config_of_the_project_root() { |
| 518 | let temp = tempfile::tempdir().unwrap(); |
| 519 | let dir = fs::canonicalize(temp.path()).unwrap().join("project"); |
| 520 | let config = git_project(&dir, "main", Some(("Ada Lovelace", "ada@example.org"))); |
| 521 | for line in block_with(&part_one(), "test -d .braid || braid init") { |
| 522 | shell_ok(&dir, &config, &line); |
| 523 | } |
| 524 | // Nobody signs: the session's status says so first. |
| 525 | fs::write(dir.join(".braid/config"), "name = \nemail = \n").unwrap(); |
| 526 | shell_ok(&dir, &config, "braid workspace add agent-1 --track main"); |
| 527 | let workspace = dir.join(".braid/work/agent-1"); |
| 528 | assert_eq!(status(&workspace)["blocking"][0]["reason"], "author"); |
| 529 | // In the workspace, `.braid` is a file: the config the section means |
| 530 | // is the project root's, where the lines it gives, added after the |
| 531 | // empty ones, name who signs. |
| 532 | assert!(workspace.join(".braid").is_file()); |
| 533 | let section = section().split_whitespace().collect::<Vec<_>>().join(" "); |
| 534 | assert!( |
| 535 | section.contains( |
| 536 | "write the answer into `.braid/config` in the project root, the one file there you may edit, as `name = <name>` and `email = <email>` lines" |
| 537 | ), |
| 538 | "{section}" |
| 539 | ); |
| 540 | let mut file = fs::OpenOptions::new() |
| 541 | .append(true) |
| 542 | .open(dir.join(".braid/config")) |
| 543 | .unwrap(); |
| 544 | std::io::Write::write_all( |
| 545 | &mut file, |
| 546 | b"name = Grace Hopper\nemail = grace@example.org\n", |
| 547 | ) |
| 548 | .unwrap(); |
| 549 | assert_eq!(status(&workspace)["blocking"], serde_json::json!([])); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn the_setup_runs_as_written_where_the_branch_is_master() { |
| 554 | let temp = tempfile::tempdir().unwrap(); |
| 555 | let parent = fs::canonicalize(temp.path()).unwrap(); |
| 556 | let dir = parent.join("project"); |
| 557 | let config = git_project(&dir, "master", Some(("Ada Lovelace", "ada@example.org"))); |
| 558 | let guide = part_one(); |
| 559 | let check = set_up_check(&guide); |
| 560 | // The setup, its commit, and a remote made where there is none, each |
| 561 | // line as written. |
| 562 | for first in [ |
| 563 | "test -d .braid || braid init", |
| 564 | "git add AGENTS.md", |
| 565 | "git init --bare -b", |
| 566 | ] { |
| 567 | for line in block_with(&guide, first) { |
| 568 | shell_ok(&dir, &config, &line); |
| 569 | } |
| 570 | } |
| 571 | assert_eq!(shell_ok(&dir, &config, &check), SET_UP); |
| 572 | let rules = read(&dir, "AGENTS.md"); |
| 573 | assert!(rules.contains("--track master\n"), "{rules}"); |
| 574 | // The new remote's HEAD names the branch, so that a clone checks it |
| 575 | // out, with the setup's commit. |
| 576 | let bare = parent.join("project.git"); |
| 577 | assert_eq!( |
| 578 | shell_ok(&bare, &config, "git symbolic-ref HEAD"), |
| 579 | "refs/heads/master\n" |
| 580 | ); |
| 581 | shell_ok(&parent, &config, "git clone -q project.git clone"); |
| 582 | assert_eq!(read(&parent.join("clone"), "AGENTS.md"), rules); |
| 583 | } |
| 584 | |
| 585 | #[test] |
| 586 | fn the_setup_keeps_braid_out_of_git_without_an_info_directory() { |
| 587 | // A template that holds only hooks, as hook managers set one up, gives |
| 588 | // repositories with no `.git/info`. |
| 589 | let temp = tempfile::tempdir().unwrap(); |
| 590 | let root = fs::canonicalize(temp.path()).unwrap(); |
| 591 | let template = root.join("template"); |
| 592 | fs::create_dir_all(template.join("hooks")).unwrap(); |
| 593 | let dir = root.join("project"); |
| 594 | let init = format!("git init -q -b main --template='{}'", template.display()); |
| 595 | let config = git_project_from(&dir, &init, Some(("Ada Lovelace", "ada@example.org"))); |
| 596 | assert!(!dir.join(".git/info").exists()); |
| 597 | for line in block_with(&part_one(), "test -d .braid || braid init") { |
| 598 | shell_ok(&dir, &config, &line); |
| 599 | } |
| 600 | assert_eq!(read(&dir, ".git/info/exclude"), ".braid\n"); |
| 601 | assert_eq!( |
| 602 | shell_ok( |
| 603 | &dir, |
| 604 | &config, |
| 605 | "git status --porcelain --untracked-files=all" |
| 606 | ), |
| 607 | "?? AGENTS.md\n" |
| 608 | ); |
| 609 | } |
| 610 | |
| 611 | /// The line the guides give to keep Python's build output out of a |
| 612 | /// workspace, `.braidignore` included. |
| 613 | const BRAIDIGNORE: &str = "printf '%s\\n' .braidignore __pycache__/ >> .braidignore"; |
| 614 | |
| 615 | #[test] |
| 616 | fn a_session_without_a_remote_makes_one_that_sync_and_clones_use() { |
| 617 | let temp = tempfile::tempdir().unwrap(); |
| 618 | let parent = fs::canonicalize(temp.path()).unwrap(); |
| 619 | let dir = parent.join("project"); |
| 620 | let config = git_project(&dir, "main", Some(("Ada Lovelace", "ada@example.org"))); |
| 621 | for line in block_with(&part_one(), "test -d .braid || braid init") { |
| 622 | shell_ok(&dir, &config, &line); |
| 623 | } |
| 624 | let section = section(); |
| 625 | let sync = block_with(§ion, "braid --agent agent-1 git sync"); |
| 626 | let recipe = block_with(§ion, "git init --bare"); |
| 627 | // The guide gives the same lines for a project with no remote, with the |
| 628 | // branch the shared checkout is on, which the setup has be the main |
| 629 | // one, where the section names its branch. |
| 630 | let guide: Vec<String> = block_with(&part_one(), "git init --bare -b") |
| 631 | .iter() |
| 632 | .map(|line| line.replace("\"$(git branch --show-current)\"", "main")) |
| 633 | .collect(); |
| 634 | assert_eq!(guide, recipe); |
| 635 | for text in [part_one(), section.clone()] { |
| 636 | assert!(code_spans(&text).iter().any(|span| span == BRAIDIGNORE)); |
| 637 | } |
| 638 | |
| 639 | // A session lands a change, with build output kept out of it, and |
| 640 | // what is left uncommitted holding the landing back. |
| 641 | shell_ok(&dir, &config, "braid workspace add agent-1 --track main"); |
| 642 | let workspace = dir.join(".braid/work/agent-1"); |
| 643 | fs::write(workspace.join("app.py"), "print('hi')\n").unwrap(); |
| 644 | fs::create_dir(workspace.join("__pycache__")).unwrap(); |
| 645 | fs::write(workspace.join("__pycache__/app.cpython.pyc"), [0u8, 1]).unwrap(); |
| 646 | let before = status(&workspace)["added"].clone(); |
| 647 | assert_eq!( |
| 648 | before, |
| 649 | serde_json::json!(["__pycache__/app.cpython.pyc", "app.py"]) |
| 650 | ); |
| 651 | shell_ok(&workspace, &config, BRAIDIGNORE); |
| 652 | assert_eq!(status(&workspace)["added"], serde_json::json!(["app.py"])); |
| 653 | fs::write(workspace.join("notes.txt"), "one\ntwo, the agent's\n").unwrap(); |
| 654 | let session = "braid --agent agent-1"; |
| 655 | shell_ok( |
| 656 | &workspace, |
| 657 | &config, |
| 658 | &format!("{session} commit -m 'Add app.py' app.py"), |
| 659 | ); |
| 660 | let held = shell(&workspace, &config, &format!("{session} land")); |
| 661 | assert_eq!(held.status.code(), Some(1)); |
| 662 | let said = String::from_utf8_lossy(&held.stderr); |
| 663 | assert!( |
| 664 | said.contains("uncommitted changes (1 path, \"notes.txt\")"), |
| 665 | "{said}" |
| 666 | ); |
| 667 | shell_ok( |
| 668 | &workspace, |
| 669 | &config, |
| 670 | &format!("{session} commit -m 'Edit notes'"), |
| 671 | ); |
| 672 | shell_ok(&workspace, &config, &format!("{session} land")); |
| 673 | |
| 674 | // The sync fails without a remote, as the section says; the recipe makes |
| 675 | // one next to the project, and the sync then reaches it and the shared |
| 676 | // checkout. |
| 677 | assert!(!shell(&dir, &config, &sync[0]).status.success()); |
| 678 | for line in &recipe { |
| 679 | let out = shell(&dir, &config, line); |
| 680 | assert!(out.status.success(), "{line}: {:?}", out); |
| 681 | let said = String::from_utf8_lossy(&out.stderr); |
| 682 | assert!(!said.contains("hint:"), "{line}: {said}"); |
| 683 | } |
| 684 | let bare = parent.join("project.git"); |
| 685 | assert_eq!( |
| 686 | shell_ok(&dir, &config, "git remote get-url origin"), |
| 687 | format!("{}\n", bare.display()) |
| 688 | ); |
| 689 | assert_eq!( |
| 690 | shell_ok(&bare, &config, "git symbolic-ref HEAD"), |
| 691 | "refs/heads/main\n" |
| 692 | ); |
| 693 | for line in &sync { |
| 694 | shell_ok(&dir, &config, line); |
| 695 | } |
| 696 | assert_eq!(read(&dir, "app.py"), "print('hi')\n"); |
| 697 | assert_eq!(read(&dir, "notes.txt"), "one\ntwo, the agent's\n"); |
| 698 | // A clone of the new remote checks out its main. |
| 699 | shell_ok(&parent, &config, "git clone -q project.git clone"); |
| 700 | assert_eq!(read(&parent.join("clone"), "app.py"), "print('hi')\n"); |
| 701 | for kept_out in ["__pycache__", ".braidignore", ".braid"] { |
| 702 | assert!(!parent.join("clone").join(kept_out).exists(), "{kept_out}"); |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | /// The heading of the guide that says how to keep the git remote in step, |
| 707 | /// and what to do when a sync fails. |
| 708 | const SYNC_HEADING: &str = "Keeping the git remote up to date"; |
| 709 | |
| 710 | #[test] |
| 711 | fn the_section_sends_a_failed_sync_to_the_guide() { |
| 712 | assert!(part_one().contains(&format!("\n### {SYNC_HEADING}\n"))); |
| 713 | let section = section().split_whitespace().collect::<Vec<_>>().join(" "); |
| 714 | for said in [ |
| 715 | "If the sync exits with 2 (`conflicts`)", |
| 716 | &format!("as <https://braid.elffuss.com/agents.md> shows under \"{SYNC_HEADING}\""), |
| 717 | "With `remote_moved` (exit status 1), sync again; with `rejected`, ask the user.", |
| 718 | "If `git pull --ff-only` refuses,", |
| 719 | ] { |
| 720 | assert!(section.contains(said), "{said}: {section}"); |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | #[test] |
| 725 | fn a_sync_conflict_is_merged_in_git_as_the_guide_says() { |
| 726 | let temp = tempfile::tempdir().unwrap(); |
| 727 | let parent = fs::canonicalize(temp.path()).unwrap(); |
| 728 | let dir = parent.join("project"); |
| 729 | let config = git_project(&dir, "main", Some(("Ada Lovelace", "ada@example.org"))); |
| 730 | let guide = part_one(); |
| 731 | // A remote, the setup and its commit, each line as written, and a sync |
| 732 | // that takes the commit to the remote. |
| 733 | for first in [ |
| 734 | "git init --bare -b", |
| 735 | "test -d .braid || braid init", |
| 736 | "git add AGENTS.md", |
| 737 | "braid --agent agent-1 git sync", |
| 738 | ] { |
| 739 | for line in block_with(&guide, first) { |
| 740 | shell_ok(&dir, &config, &line); |
| 741 | } |
| 742 | } |
| 743 | let sync = block_with(&guide, "braid --agent agent-1 git sync") |
| 744 | .into_iter() |
| 745 | .find(|line| !line.contains("--dry-run") && line.starts_with("braid ")) |
| 746 | .unwrap(); |
| 747 | |
| 748 | // A session lands an edit of a line that someone else edits and pushes. |
| 749 | shell_ok(&dir, &config, "braid workspace add agent-1 --track main"); |
| 750 | let workspace = dir.join(".braid/work/agent-1"); |
| 751 | fs::write(workspace.join("notes.txt"), "one\ntwo, the agent's\n").unwrap(); |
| 752 | for line in [ |
| 753 | "braid --agent agent-1 commit -m 'The agent edits notes'", |
| 754 | "braid --agent agent-1 land", |
| 755 | ] { |
| 756 | shell_ok(&workspace, &config, line); |
| 757 | } |
| 758 | shell_ok(&parent, &config, "git clone -q project.git person"); |
| 759 | let person = parent.join("person"); |
| 760 | fs::write(person.join("notes.txt"), "one\ntwo, the person's\n").unwrap(); |
| 761 | shell_ok( |
| 762 | &person, |
| 763 | &config, |
| 764 | "git commit -q -am 'The person edits notes'", |
| 765 | ); |
| 766 | shell_ok(&person, &config, "git push -q"); |
| 767 | |
| 768 | // The sync stops, and says where the steps are. |
| 769 | let stopped = shell(&dir, &config, &sync); |
| 770 | assert_eq!(stopped.status.code(), Some(2)); |
| 771 | let said = String::from_utf8_lossy(&stopped.stdout); |
| 772 | assert!(said.contains("CONTENT notes.txt"), "{said}"); |
| 773 | assert!( |
| 774 | said.contains(&format!( |
| 775 | "https://braid.elffuss.com/agents.md shows how, under \"{SYNC_HEADING}\"" |
| 776 | )), |
| 777 | "{said}" |
| 778 | ); |
| 779 | |
| 780 | // The guide's steps, with the conflict fixed where git stops. |
| 781 | let recipe = block_with(&guide, "git init --bare .braid/export.git"); |
| 782 | let merge = recipe |
| 783 | .iter() |
| 784 | .position(|line| line.starts_with("git merge --no-edit origin/main")) |
| 785 | .expect("the remote's branch is merged into braid's"); |
| 786 | assert_eq!( |
| 787 | recipe[merge + 1], |
| 788 | "# if it stopped: fix those files and git add them, then git commit --no-edit --cleanup=strip" |
| 789 | ); |
| 790 | for (index, line) in recipe.iter().enumerate() { |
| 791 | let out = shell(&dir, &config, line); |
| 792 | if index == merge { |
| 793 | assert_eq!(out.status.code(), Some(1), "git stops at the conflict"); |
| 794 | fs::write(dir.join("notes.txt"), "one\ntwo, both\n").unwrap(); |
| 795 | shell_ok(&dir, &config, "git add notes.txt"); |
| 796 | shell_ok(&dir, &config, "git commit -q --no-edit --cleanup=strip"); |
| 797 | continue; |
| 798 | } |
| 799 | assert!( |
| 800 | out.status.success(), |
| 801 | "{line}: {}", |
| 802 | String::from_utf8_lossy(&out.stderr) |
| 803 | ); |
| 804 | } |
| 805 | // The merge's message names the branch, not the remote's address, and |
| 806 | // braid's branch is its first parent; braid's main and the remote's are |
| 807 | // the merge. |
| 808 | let merged = shell_ok(&dir, &config, "git log -1 --format=%B"); |
| 809 | assert_eq!( |
| 810 | merged.trim_end(), |
| 811 | "Merge remote-tracking branch 'origin/main'" |
| 812 | ); |
| 813 | assert_eq!( |
| 814 | shell_ok(&dir, &config, "git log -1 --format=%s HEAD^1"), |
| 815 | "The agent edits notes\n" |
| 816 | ); |
| 817 | let head = shell_ok(&dir, &config, "git rev-parse HEAD"); |
| 818 | assert_eq!( |
| 819 | shell_ok(&parent.join("project.git"), &config, "git rev-parse main"), |
| 820 | head |
| 821 | ); |
| 822 | assert!( |
| 823 | shell_ok(&dir, &config, "braid log main -n 1") |
| 824 | .contains("Merge remote-tracking branch 'origin/main'") |
| 825 | ); |
| 826 | // The session carries on from the merge, and the next sync has nothing |
| 827 | // to do. |
| 828 | shell_ok(&workspace, &config, "braid --agent agent-1 update"); |
| 829 | assert_eq!(status(&workspace)["behind_by"], 0); |
| 830 | assert_eq!(read(&workspace, "notes.txt"), "one\ntwo, both\n"); |
| 831 | assert!(shell_ok(&dir, &config, &sync).contains("up to date")); |
| 832 | assert!(!dir.join(".braid/export.git").exists()); |
| 833 | } |