Elffuss BraidHub

utopia-ia/elffuss-braid public

2dd40509e7e2 · 56.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid agents init`: the rules for coding agents, written into the
5//! project's `AGENTS.md` between two marker lines, so that every agent
6//! session, whatever runs it, knows to work in a braid workspace of its own
7//! and to land through braid. A `CLAUDE.md` or a `GEMINI.md` that does not
8//! include `AGENTS.md` gets the line that does.
9//!
10//! Text outside the markers is never touched, and running the command again
11//! rewrites the section in place, so it is idempotent. Marker lines inside
12//! fenced code blocks are not markers. Every file is checked before any is
13//! written, and all of them are prepared before any is replaced.
14
15use std::fs::{self, OpenOptions};
16use std::io::{self, Write};
17use std::ops::Range;
18use std::path::{Path, PathBuf};
19use std::process::ExitCode;
20
21use anyhow::{Context, Result, anyhow, bail};
22use braid_repo::{Location, Repo};
23use braid_wc::Workspace;
24use clap::{Args, Subcommand};
25use serde_json::{Map, Value, json};
26
27use crate::work::{branches, listed};
28use crate::{Cli, open_repo, print_json};
29
30/// The line that opens the braid section of `AGENTS.md`.
31pub(crate) const START: &str = "<!-- braid:start -->";
32
33/// The line that closes it.
34pub(crate) const END: &str = "<!-- braid:end -->";
35
36/// The file the section goes in.
37const AGENTS_FILE: &str = "AGENTS.md";
38
39/// The file Claude Code reads, which should include `AGENTS.md`.
40const CLAUDE_FILE: &str = "CLAUDE.md";
41
42/// The file Gemini CLI reads, which should include `AGENTS.md`.
43const GEMINI_FILE: &str = "GEMINI.md";
44
45/// The line that makes `CLAUDE.md` or `GEMINI.md` include `AGENTS.md`.
46const INCLUDE: &str = "@AGENTS.md";
47
48/// What the section's first comment says just before the branch it names.
49const BRANCH_NOTE: &str = "(branch: ";
50
51/// The end of every refusal: nothing is written when any check fails.
52const NOTHING: &str = "nothing was written";
53
54/// The long help of `agents init`.
55pub(crate) const INIT_HELP: &str =
56 "Write the rules for coding agents into the project's AGENTS.md, so that
57every agent session, whatever runs it, works in a braid workspace of its
58own and lands through braid.
59
60The rules go in a section between two lines, <!-- braid:start --> and
61<!-- braid:end -->: at the end of AGENTS.md, which is created if there is
62none, and in place on later runs. Text outside the markers is never
63touched, and running the command twice changes nothing. Marker lines
64inside fenced code blocks are not markers. Markers that do not pair up (one
65without the other, the end first, or either of them twice) are refused
66before anything is written, and so is a file that ends inside a fenced
67code block, where the section would be read as code.
68
69The project's directory is the root of the repository or of the workspace
70the current directory is in, or the current directory; --workspace names a
71workspace to write in, --repo a repository whose root to write in, and
72--dir any directory.
73
74The section names the branch agents land on: --branch, which must be a
75branch the repository has; else the one the section names already, if the
76repository has it; else, inside a workspace, the one it tracks; else main,
77master, or the repository's only branch. Without a braid repository, or
78with one that has no branch yet, there is no branch to name: set braid up
79first, or pass --branch. The section writes the name into shell commands,
80so it takes ASCII letters, digits, '.', '_', '/' and '-' only, and does not
81start with '-'.
82
83Claude Code reads CLAUDE.md, and Gemini CLI reads GEMINI.md, instead of
84AGENTS.md: each of them that exists and does not include AGENTS.md gets the
85line @AGENTS.md at its end. --no-claude and --no-gemini leave them alone.
86Neither is ever created.
87
88Any of the three may be a symbolic link to a file inside the project, and
89the file it points to is the one written. A link that leads outside the
90project, a name that is not a regular file, a read-only file, and a file
91with hard links other than these three names are refused. Files are
92written through a temporary file and a rename, every one of them prepared
93before any is replaced; a file with hard links is written in place, so
94that its names stay one file.
95
96With --dry-run nothing is written: the command makes the same checks, says
97what it would do, and prints the section when AGENTS.md would change. With
98--json it prints one object:
99
100 dir the project's directory
101 branch the branch the section names
102 previous_branch the branch it named before, when that was another;
103 otherwise null
104 repository the root of the braid repository, or null when there is
105 none
106 dry_run whether nothing was written
107 created the files created (or, with --dry-run, that would be)
108 updated the files changed
109 unchanged the files already as they should be
110 paths for each file in those lists, the file written: its own
111 path from dir, or the file its link points to
112
113A CLAUDE.md or a GEMINI.md that does not exist, or that --no-claude or
114--no-gemini leaves alone, is in none of the lists.";
115
116#[derive(Debug, Subcommand)]
117pub(crate) enum AgentsAction {
118 /// Write the braid section of the project's AGENTS.md, and make its
119 /// CLAUDE.md and GEMINI.md include AGENTS.md.
120 #[command(long_about = INIT_HELP)]
121 Init(InitArgs),
122}
123
124#[derive(Debug, Args)]
125pub(crate) struct InitArgs {
126 /// The project's root directory (default: the root of the repository or
127 /// the workspace the current directory is in, or else the current
128 /// directory).
129 #[arg(long, value_name = "DIR")]
130 dir: Option<PathBuf>,
131 /// The branch agents land on, one the repository has (default: the one
132 /// the section names already, if the repository has it; inside a
133 /// workspace, the one it tracks; otherwise main, master, or the
134 /// repository's only branch).
135 #[arg(long, value_name = "BRANCH")]
136 branch: Option<String>,
137 /// Say what would change, and write nothing.
138 #[arg(long)]
139 dry_run: bool,
140 /// Leave CLAUDE.md alone.
141 #[arg(long)]
142 no_claude: bool,
143 /// Leave GEMINI.md alone.
144 #[arg(long)]
145 no_gemini: bool,
146}
147
148pub(crate) fn agents(cli: &Cli, action: &AgentsAction) -> Result<ExitCode> {
149 let AgentsAction::Init(args) = action;
150 init(cli, args)
151}
152
153/// What a file needs.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155enum Action {
156 Create,
157 Update,
158 Unchanged,
159}
160
161/// One file the command looked at, and what it does to it.
162struct Planned {
163 /// The name the project knows it by: `AGENTS.md`, `CLAUDE.md` or
164 /// `GEMINI.md`.
165 name: &'static str,
166 target: Target,
167 action: Action,
168 /// The new contents, unless unchanged.
169 contents: Option<String>,
170 /// What the text output says about it, once done.
171 done: String,
172 /// What it says with `--dry-run`.
173 would: String,
174}
175
176fn init(cli: &Cli, args: &InitArgs) -> Result<ExitCode> {
177 let place = Place::find(cli, args.dir.as_deref())?;
178 let dir = &place.dir;
179 let mut roots = vec![fs::canonicalize(dir).unwrap_or_else(|_| dir.clone())];
180 if let Some(repo) = &place.repo
181 && let Ok(root) = fs::canonicalize(repo.root())
182 {
183 roots.push(root);
184 }
185 let guides = guide_files(dir);
186
187 let agents_target = match locate_file(dir, AGENTS_FILE, &roots, &guides)? {
188 Located::Missing => Target::new_file(dir, AGENTS_FILE),
189 Located::Dangling(to) => bail!(
190 "{AGENTS_FILE} is a symbolic link to {}, which does not exist: {NOTHING}",
191 to.display()
192 ),
193 Located::File(target) => target,
194 };
195 let current = agents_target.read()?;
196 let scanned = match &current {
197 Some(text) => scan_section(text).map_err(|why| {
198 anyhow!(
199 "{} has unbalanced braid markers: {why}. Fix them by hand: {NOTHING}",
200 agents_target.shown
201 )
202 })?,
203 None => Scanned::default(),
204 };
205 let named = match (&current, &scanned.section) {
206 (Some(text), Some(range)) => named_branch(&text[range.clone()]),
207 _ => None,
208 };
209 let choice = choose_branch(args.branch.as_deref(), named, &place)?;
210 let mut planned = vec![plan_agents(
211 agents_target,
212 current.as_deref(),
213 &scanned,
214 &choice.branch,
215 )?];
216 for (name, skipped) in [(CLAUDE_FILE, args.no_claude), (GEMINI_FILE, args.no_gemini)] {
217 if !skipped && let Some(file) = plan_include(dir, name, &roots, &guides, &planned)? {
218 planned.push(file);
219 }
220 }
221
222 if !args.dry_run {
223 write_all(&planned)?;
224 }
225
226 if cli.json {
227 let names = |action: Action| -> Vec<&str> {
228 planned
229 .iter()
230 .filter(|file| file.action == action)
231 .map(|file| file.name)
232 .collect()
233 };
234 let paths: Map<String, Value> = planned
235 .iter()
236 .map(|file| (file.name.to_owned(), Value::from(file.target.shown.clone())))
237 .collect();
238 print_json(&json!({
239 "dir": dir.to_string_lossy(),
240 "branch": choice.branch,
241 "previous_branch": choice.previous,
242 "repository": place.repo.as_ref().map(|repo| repo.root().to_string_lossy()),
243 "dry_run": args.dry_run,
244 "created": names(Action::Create),
245 "updated": names(Action::Update),
246 "unchanged": names(Action::Unchanged),
247 "paths": paths,
248 }))?;
249 return Ok(ExitCode::SUCCESS);
250 }
251
252 let mut out = io::stdout().lock();
253 if let (Some(previous), true) = (&choice.previous, choice.missing) {
254 let names = if args.dry_run { "would name" } else { "names" };
255 writeln!(
256 out,
257 "The section named {previous}, which the repository does not have: it {names} {} now.",
258 choice.branch
259 )?;
260 }
261 for file in &planned {
262 let said = if args.dry_run {
263 &file.would
264 } else {
265 &file.done
266 };
267 writeln!(out, "{said}")?;
268 }
269 if place.repo.is_none() {
270 writeln!(
271 out,
272 "There is no braid repository here yet: set braid up in the project root (`braid init`, then `braid git import .`) before agents start."
273 )?;
274 }
275 if args.dry_run {
276 writeln!(out, "Nothing was written.")?;
277 if planned[0].action != Action::Unchanged {
278 writeln!(out, "\nThe section {AGENTS_FILE} would hold:\n")?;
279 write!(out, "{}", section(&choice.branch))?;
280 }
281 }
282 Ok(ExitCode::SUCCESS)
283}
284
285/// Where the command writes, and the repository and workspace that tells
286/// it which branch to name.
287struct Place {
288 repo: Option<Repo>,
289 /// The project's directory: where `AGENTS.md` is.
290 dir: PathBuf,
291 /// The branch of the workspace `dir` is, when it is one.
292 workspace_branch: Option<String>,
293}
294
295impl Place {
296 /// The directory to write in: the workspace `--workspace` names; else
297 /// `--dir`; else the root of the repository or the workspace the
298 /// current directory is in, if it belongs to the repository `--repo`
299 /// names, if any; else the root of that repository; else the current
300 /// directory.
301 fn find(cli: &Cli, given: Option<&Path>) -> Result<Place> {
302 if let Some(name) = &cli.workspace {
303 if given.is_some() {
304 bail!("--dir and --workspace both say where to write: give one of them");
305 }
306 let repo = open_repo(cli)?;
307 let (dir, branch) = {
308 let workspace = Workspace::open(&repo, name)?;
309 (workspace.dir().to_path_buf(), workspace.state()?.branch)
310 };
311 if !dir.is_dir() {
312 bail!(
313 "the directory of workspace {name}, {}, is gone",
314 dir.display()
315 );
316 }
317 return Ok(Place {
318 repo: Some(repo),
319 dir,
320 workspace_branch: Some(branch),
321 });
322 }
323 let start = match given {
324 Some(dir) => std::path::absolute(dir)?,
325 None => std::env::current_dir()?,
326 };
327 if !start.is_dir() {
328 bail!("{} is not a directory", start.display());
329 }
330 let location = match braid_repo::locate(&start) {
331 Ok(location) => Some(location),
332 Err(braid_repo::Error::NotFound) => None,
333 Err(err) => return Err(err.into()),
334 };
335 let repo = match (&cli.repo, &location) {
336 (Some(root), _) => Some(Repo::open(root)?),
337 (None, Some(Location::Root(dir))) => Some(Repo::open(dir)?),
338 (None, Some(Location::Workspace { link, .. })) => Some(Repo::open(&link.repository)?),
339 (None, None) => None,
340 };
341 // What the current directory is in counts only when it belongs to
342 // the repository: --repo may name another.
343 let belongs = |root: &Path| {
344 cli.repo.is_none()
345 || repo
346 .as_ref()
347 .is_some_and(|repo| same_dir(root, repo.root()))
348 };
349 let (top, workspace_branch) = match &location {
350 Some(Location::Root(root)) if belongs(root) => (Some(root.clone()), None),
351 Some(Location::Workspace { dir, link }) if belongs(&link.repository) => {
352 // A workspace whose state is gone names no branch.
353 let branch = repo.as_ref().and_then(|repo| {
354 Workspace::open(repo, &link.name)
355 .and_then(|workspace| workspace.state())
356 .ok()
357 .map(|state| state.branch)
358 });
359 (Some(dir.clone()), branch)
360 }
361 _ => (repo.as_ref().map(|repo| repo.root().to_path_buf()), None),
362 };
363 let dir = match (given, top) {
364 (None, Some(top)) => top,
365 _ => start,
366 };
367 Ok(Place {
368 repo,
369 dir,
370 workspace_branch,
371 })
372 }
373}
374
375/// Whether two paths name the same directory.
376fn same_dir(a: &Path, b: &Path) -> bool {
377 match (fs::canonicalize(a), fs::canonicalize(b)) {
378 (Ok(a), Ok(b)) => a == b,
379 _ => a == b,
380 }
381}
382
383/// The branch the section names, and what it named before.
384#[derive(Debug)]
385struct Choice {
386 branch: String,
387 /// The branch the section named before, when that was another.
388 previous: Option<String>,
389 /// Whether it changes because the repository does not have the branch
390 /// the section named.
391 missing: bool,
392}
393
394/// The branch the section names: the one asked for, which the repository
395/// must have; the one the section names already, if the repository has
396/// it; the workspace's; or the repository's main one. A branch the section
397/// names but the repository does not have was written before the
398/// project's history came in, or names a branch since removed: it is
399/// chosen again rather than kept.
400fn choose_branch(given: Option<&str>, named: Option<String>, place: &Place) -> Result<Choice> {
401 let refs = place
402 .repo
403 .as_ref()
404 .map(|repo| repo.store().refs())
405 .transpose()?;
406 let names: Option<Vec<&str>> = refs.as_ref().map(branches);
407 // Whether the repository could have the branch: it has it, it has no
408 // branch yet, or there is no repository to ask.
409 let possible = |branch: &str| {
410 names
411 .as_ref()
412 .is_none_or(|names| names.is_empty() || names.contains(&branch))
413 };
414 if let Some(given) = given {
415 check_branch(given)?;
416 if !possible(given) {
417 bail!(
418 "the repository has no branch {given:?}; it has {}. Pass --branch the branch agents land on",
419 listed(names.as_deref().unwrap_or_default())
420 );
421 }
422 return Ok(Choice {
423 branch: given.to_owned(),
424 previous: named.filter(|named| named != given),
425 missing: false,
426 });
427 }
428 if let Some(named) = named {
429 if possible(&named) {
430 return Ok(Choice {
431 branch: named,
432 previous: None,
433 missing: false,
434 });
435 }
436 let branch = main_branch(names.as_deref().unwrap_or_default())?;
437 return Ok(Choice {
438 branch,
439 previous: Some(named),
440 missing: true,
441 });
442 }
443 let branch = match (&place.workspace_branch, names.as_deref()) {
444 (Some(tracked), _) => {
445 check_branch(tracked)?;
446 tracked.clone()
447 }
448 (None, None) => bail!(
449 "there is no braid repository here, so there is no branch to name yet: set braid up first (`braid init`, then `braid git import .`), or pass --branch"
450 ),
451 (None, Some([])) => bail!(
452 "the braid repository has no branch yet: import the project's history first (`braid git import .`), or pass --branch"
453 ),
454 (None, Some(names)) => main_branch(names)?,
455 };
456 Ok(Choice {
457 branch,
458 previous: None,
459 missing: false,
460 })
461}
462
463/// The repository's main branch among its branches `names`: `main`,
464/// `master`, or its only branch.
465fn main_branch(names: &[&str]) -> Result<String> {
466 if let Some(preferred) = ["main", "master"]
467 .into_iter()
468 .find(|preferred| names.contains(preferred))
469 {
470 return Ok(preferred.to_owned());
471 }
472 match names {
473 [only] => {
474 check_branch(only)?;
475 Ok((*only).to_owned())
476 }
477 [] => bail!("the repository has no branch yet: pass --branch"),
478 several => bail!(
479 "cannot tell which branch agents land on: the repository has {}; pass --branch",
480 listed(several)
481 ),
482 }
483}
484
485/// Whether the section can name `branch`. The section writes it into shell
486/// commands and reads it back from its first comment, so it takes only a
487/// set of characters that needs no quoting and holds no `)`: ASCII letters,
488/// digits, `.`, `_`, `/` and `-`, not first. It must be a git branch name
489/// outside braid's own namespaces, too.
490pub(crate) fn is_section_branch(branch: &str) -> bool {
491 !branch.is_empty()
492 && !branch.starts_with('-')
493 && branch
494 .bytes()
495 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'/' | b'-'))
496 && braid_git::is_branch_name(branch)
497 && braid_repo::is_branch(branch)
498}
499
500fn check_branch(branch: &str) -> Result<()> {
501 if is_section_branch(branch) {
502 Ok(())
503 } else {
504 bail!(
505 "{branch:?} cannot name the branch agents land on: the section writes it into shell commands, so it takes a git branch name of ASCII letters, digits, '.', '_', '/' and '-', not starting with '-' and outside braid's own refs (braid/, git/, remote/, tags/)"
506 )
507 }
508}
509
510/// What `AGENTS.md` needs: to be created, to get the section, or to have
511/// it rewritten in place.
512fn plan_agents(
513 target: Target,
514 current: Option<&str>,
515 scanned: &Scanned,
516 branch: &str,
517) -> Result<Planned> {
518 let landing = format!("agents land on {branch}");
519 let called = target.called(AGENTS_FILE);
520 let (action, contents, done, would) = match (current, &scanned.section) {
521 (None, _) => (
522 Action::Create,
523 Some(section(branch)),
524 format!("Created {called} with the braid section: {landing}."),
525 format!("Would create {called} with the braid section: {landing}."),
526 ),
527 (Some(text), Some(range)) => {
528 let new = replace_section(text, range.clone(), &section(branch));
529 if new == text {
530 let said = format!("{called} has this braid section already: {landing}.");
531 (Action::Unchanged, None, said.clone(), said)
532 } else {
533 (
534 Action::Update,
535 Some(new),
536 format!("Updated the braid section of {called}: {landing}."),
537 format!("Would update the braid section of {called}: {landing}."),
538 )
539 }
540 }
541 (Some(_), None) if scanned.open_fence.is_some() => bail!(
542 "{} ends inside a fenced code block, which opens on line {} and is never closed: the section would be read as code there. Close the block, then run the command again: {NOTHING}",
543 target.shown,
544 scanned.open_fence.unwrap_or_default()
545 ),
546 (Some(text), None) => (
547 Action::Update,
548 Some(append_section(text, &section(branch))),
549 format!("Added the braid section to {called}: {landing}."),
550 format!("Would add the braid section to {called}: {landing}."),
551 ),
552 };
553 Ok(Planned {
554 name: AGENTS_FILE,
555 target,
556 action,
557 contents,
558 done,
559 would,
560 })
561}
562
563/// What `name`, `CLAUDE.md` or `GEMINI.md`, needs, or `None` when there is
564/// no such file. `earlier` are the files planned before it, `AGENTS.md`
565/// first: a file that is one of them under another name needs nothing.
566fn plan_include(
567 dir: &Path,
568 name: &'static str,
569 roots: &[PathBuf],
570 guides: &[(PathBuf, FileId)],
571 earlier: &[Planned],
572) -> Result<Option<Planned>> {
573 let planned = |target, action, contents, said: String, would: String| Planned {
574 name,
575 target,
576 action,
577 contents,
578 done: said,
579 would,
580 };
581 let same = |other: &str| {
582 let said = if other == AGENTS_FILE {
583 format!("{name} is {AGENTS_FILE} under another name: it holds the section itself.")
584 } else {
585 format!("{name} is {other} under another name.")
586 };
587 (said.clone(), said)
588 };
589 let target = match locate_file(dir, name, roots, guides)? {
590 Located::Missing => return Ok(None),
591 Located::Dangling(to) => {
592 // A link to the AGENTS.md this run creates holds the section;
593 // a link to anything else that is missing has nothing to add
594 // the line to.
595 let agents = &earlier[0];
596 let to_agents = to == Path::new(AGENTS_FILE)
597 || to == Path::new("./AGENTS.md")
598 || dir.join(&to) == agents.target.path;
599 if !to_agents || agents.action != Action::Create {
600 return Ok(None);
601 }
602 let (said, would) = same(AGENTS_FILE);
603 let target = Target {
604 shown: agents.target.shown.clone(),
605 ..Target::new_file(dir, name)
606 };
607 return Ok(Some(planned(target, Action::Unchanged, None, said, would)));
608 }
609 Located::File(target) => target,
610 };
611 if let Some(other) = earlier
612 .iter()
613 .find(|file| file.target.id.is_some() && file.target.id == target.id)
614 {
615 let (said, would) = same(other.name);
616 return Ok(Some(planned(target, Action::Unchanged, None, said, would)));
617 }
618 let text = target.read()?.unwrap_or_default();
619 if includes_agents(&text) {
620 let said = format!("{} includes {AGENTS_FILE} already.", target.called(name));
621 return Ok(Some(planned(
622 target,
623 Action::Unchanged,
624 None,
625 said.clone(),
626 said,
627 )));
628 }
629 if let Some(line) = open_fence(&text) {
630 bail!(
631 "{} ends inside a fenced code block, which opens on line {line} and is never closed: the line {INCLUDE} would be read as code there. Close the block, then run the command again: {NOTHING}",
632 target.shown
633 );
634 }
635 let called = target.called(name);
636 Ok(Some(planned(
637 target,
638 Action::Update,
639 Some(add_include(&text)),
640 format!("Added {INCLUDE} to {called}."),
641 format!("Would add {INCLUDE} to {called}."),
642 )))
643}
644
645/// The braid section for agents that land on `branch`, from its start
646/// marker to its end marker, each line ending in `\n`.
647pub(crate) fn section(branch: &str) -> String {
648 format!(
649 "{START}
650<!-- Written by `braid agents init` {BRANCH_NOTE}{branch}). Running it
651 again rewrites everything between the braid markers. -->
652## Version control with braid
653
654Agents land their changes on `{branch}` through [braid](https://braid.elffuss.com),
655each in a braid workspace of its own. Braid is pre-alpha: git stays the
656source of truth, and `braid git sync` keeps the git remote in step.
657
658- **Only where braid is set up:** in a checkout whose root has a `.braid`
659 directory. Without one (a fresh clone, CI, another machine), skip this
660 section and work with git, as the project's other rules say; set braid
661 up only if the user asks for it (<https://braid.elffuss.com/agents.md>
662 says how). With `.braid` but no `braid` command, braid is not on `PATH`:
663 try `\"$HOME/.cargo/bin/braid\"`, or ask the user to install it.
664- **Never edit files, `git add`, `git commit` or `git push` in the project
665 root.** It is the shared checkout, where the user works: work only in
666 your workspace.
667- **Start** with a workspace named for your session: 1 to 64 ASCII
668 letters, digits, `.`, `_` or `-`, starting with a letter or a digit
669 (`braid workspace list` shows the names taken). The commands here call it
670 `agent-1`: use your own name. From the project root, this creates it in
671 `.braid/work/agent-1`:
672
673 ```bash
674 braid workspace add agent-1 --track {branch}
675 cd .braid/work/agent-1
676 ```
677
678- **Work** in `.braid/work/agent-1`: edit, build and test there. Record and
679 land from the workspace, naming your session with `--agent` every time:
680
681 ```bash
682 braid --agent agent-1 status --json
683 braid --agent agent-1 commit -m \"Say what changed and why\"
684 braid --agent agent-1 land --json
685 ```
686
687 If your shell does not stay in the workspace between commands, add
688 `--workspace agent-1` and run them from the project root.
689- **No git in the workspace.** Its `.git` file points nowhere, so `git`
690 fails there. Never get around that (`git -C`, `GIT_DIR`): `git stash`,
691 `reset`, `checkout`, `restore`, `clean`, `add` or `commit` would act on
692 the user's checkout. A build or test script that finds the project with
693 git fails in the workspace too: run its steps yourself. To review an
694 edit, from the workspace's root, compare the file with the workspace's
695 `base`, which `status --json` gives:
696 `braid cat-object <base>:<path> | diff -u - <path>`. To undo it, write
697 the base's version back with `braid cat-object <base>:<path> > <path>`,
698 or delete a file you added.
699- **Before each commit**, read `braid status`. There is no staging area:
700 `commit` records every change in the workspace, and only `.gitignore` and
701 `.braidignore` apply there, not `.git/info/exclude` or a global excludes
702 file, so list files that must stay local in `.braidignore`. Braid runs no
703 git hooks: run the project's checks yourself before you land.
704- **Conflicts:** `land` and `update` exit with status 2, the `outcome` in
705 their JSON is `conflicts`, and `{branch}` does not move. After `land`, run
706 `braid --agent agent-1 update`, which writes conflict markers into the
707 files; fix them (`braid resolve <path>` settles conflicts that are not
708 about content), then `commit` (the message is kept) and `land` again. In
709 the JSON, `next` says what to run. Never `commit --force` during a
710 rebase: it would commit the markers. Any other failure exits with status
711 1, and braid prints it as text on standard error, even with `--json`.
712- **Before a new task**, `braid --agent agent-1 update` brings your
713 workspace onto `{branch}`.
714- **When you finish**, tell the user that what you landed is on braid's
715 `{branch}` only: their checkout and the git remote get it once someone
716 runs this from the project root.
717
718 ```bash
719 braid --agent agent-1 git sync \"$(git remote get-url origin)\" --branch {branch}
720 git pull --ff-only
721 ```
722
723 Offer to run it: when to sync is the user's call. Once everything has
724 landed, `braid workspace remove agent-1`, from the project root, removes
725 your workspace.
726- Changesets are signed by `BRAID_AUTHOR` (`\"Name <email>\"`), or else by the
727 `name` and `email` in `.braid/config`.
728- New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
729 than 1 MiB wait for `braid track <path>`. Never track a secret: move it
730 out of the workspace.
731- `braid --agent agent-1 undo` reverts the newest operation in the
732 repository, whoever made it: read `braid op log` first.
733{END}
734"
735 )
736}
737
738/// Whether `line` is `marker`: alone on its line, indented by three spaces
739/// at most, as Markdown lets an HTML comment be.
740fn is_marker(line: &str, marker: &str) -> bool {
741 let line = line.trim_end();
742 let text = line.trim_start_matches(' ');
743 line.len() - text.len() <= 3 && text == marker
744}
745
746/// The fence a line opens or closes, as CommonMark reads one: indented by
747/// three spaces at most, then three or more backticks or tildes, with no
748/// backtick after backticks. Gives the character, how many of it there
749/// are, and the rest of the line.
750fn fence(line: &str) -> Option<(u8, usize, &str)> {
751 let line = line.trim_end_matches(['\n', '\r']);
752 let text = line.trim_start_matches(' ');
753 if line.len() - text.len() > 3 {
754 return None;
755 }
756 let mark = *text.as_bytes().first()?;
757 if mark != b'`' && mark != b'~' {
758 return None;
759 }
760 let count = text.bytes().take_while(|byte| *byte == mark).count();
761 let rest = &text[count..];
762 (count >= 3 && !(mark == b'`' && rest.contains('`'))).then_some((mark, count, rest))
763}
764
765/// Follows the fenced code blocks of a Markdown text, a line at a time.
766#[derive(Debug, Default)]
767struct Fences {
768 /// The block open after the last line: its fence's character and
769 /// length, and the line it opened on.
770 open: Option<(u8, usize, usize)>,
771}
772
773impl Fences {
774 /// Whether line number `number` is code: a fence, or inside a block.
775 fn code(&mut self, line: &str, number: usize) -> bool {
776 match (self.open, fence(line)) {
777 (Some((mark, count, _)), Some((found, length, rest)))
778 if found == mark && length >= count && rest.trim().is_empty() =>
779 {
780 self.open = None;
781 true
782 }
783 (Some(_), _) => true,
784 (None, Some((mark, count, _))) => {
785 self.open = Some((mark, count, number));
786 true
787 }
788 (None, None) => false,
789 }
790 }
791}
792
793/// `line`, the first of a text, without the byte order mark an editor may
794/// have put before it.
795fn without_bom(line: &str) -> &str {
796 line.strip_prefix('\u{feff}').unwrap_or(line)
797}
798
799/// The line a fenced code block that `text` never closes opens on.
800fn open_fence(text: &str) -> Option<usize> {
801 let mut fences = Fences::default();
802 for (index, line) in text.lines().enumerate() {
803 let line = if index == 0 { without_bom(line) } else { line };
804 fences.code(line, index + 1);
805 }
806 fences.open.map(|(_, _, line)| line)
807}
808
809/// What a Markdown text holds of the braid section.
810#[derive(Debug, Default, PartialEq, Eq)]
811pub(crate) struct Scanned {
812 /// The section: from the start of its start marker's line to the end of
813 /// its end marker's line.
814 pub(crate) section: Option<Range<usize>>,
815 /// The line a fenced code block that the text never closes opens on.
816 pub(crate) open_fence: Option<usize>,
817}
818
819/// Where the braid section is in `text`, with the markers inside fenced
820/// code blocks left out, as examples rather than markers. An error that
821/// says where they are when they do not pair up.
822pub(crate) fn scan_section(text: &str) -> Result<Scanned, String> {
823 let mut starts = Vec::new();
824 let mut ends = Vec::new();
825 let mut fences = Fences::default();
826 let mut offset = 0;
827 for (index, line) in text.split_inclusive('\n').enumerate() {
828 // A byte order mark is not part of the first line: the section
829 // starts after it, so that it stays.
830 let skip = if index == 0 {
831 line.len() - without_bom(line).len()
832 } else {
833 0
834 };
835 let body = &line[skip..];
836 if !fences.code(body, index + 1) {
837 if is_marker(body, START) {
838 starts.push((index + 1, offset + skip));
839 } else if is_marker(body, END) {
840 ends.push((index + 1, offset + line.len()));
841 }
842 }
843 offset += line.len();
844 }
845 let section = match (starts.as_slice(), ends.as_slice()) {
846 ([], []) => None,
847 ([(first, from)], [(last, to)]) if first < last => Some(*from..*to),
848 _ => {
849 return Err(format!(
850 "`{START}` is on {}, `{END}` on {}, and there must be one of each, the start first",
851 line_list(&starts),
852 line_list(&ends)
853 ));
854 }
855 };
856 Ok(Scanned {
857 section,
858 open_fence: fences.open.map(|(_, _, line)| line),
859 })
860}
861
862/// `no line`, `line 3`, `lines 3 and 9`, `lines 3, 9 and 12`.
863fn line_list(found: &[(usize, usize)]) -> String {
864 let numbers: Vec<String> = found.iter().map(|(line, _)| line.to_string()).collect();
865 match numbers.as_slice() {
866 [] => "no line".to_owned(),
867 [one] => format!("line {one}"),
868 [rest @ .., last] => format!("lines {} and {last}", rest.join(", ")),
869 }
870}
871
872/// The line end `text` uses: `\r\n` if it has any, otherwise `\n`.
873fn line_end(text: &str) -> &'static str {
874 if text.contains("\r\n") { "\r\n" } else { "\n" }
875}
876
877/// `section`, written with the line ends of `text`.
878fn in_line_ends_of(text: &str, section: &str) -> String {
879 match line_end(text) {
880 "\n" => section.to_owned(),
881 end => section.replace('\n', end),
882 }
883}
884
885/// `text` with the section at `range` replaced by `section`.
886pub(crate) fn replace_section(text: &str, range: Range<usize>, section: &str) -> String {
887 let section = in_line_ends_of(text, section);
888 let mut out = String::with_capacity(text.len() - range.len() + section.len());
889 out.push_str(&text[..range.start]);
890 out.push_str(&section);
891 out.push_str(&text[range.end..]);
892 out
893}
894
895/// `text` with `section` at its end, after a blank line.
896pub(crate) fn append_section(text: &str, section: &str) -> String {
897 let end = line_end(text);
898 let section = in_line_ends_of(text, section);
899 let mut out = String::with_capacity(text.len() + section.len() + 2 * end.len());
900 out.push_str(text);
901 if !without_bom(text).is_empty() {
902 if !out.ends_with('\n') {
903 out.push_str(end);
904 }
905 if !without_bom(&out).trim_end_matches(['\n', '\r']).is_empty()
906 && !ends_with_blank_line(&out)
907 {
908 out.push_str(end);
909 }
910 }
911 out.push_str(&section);
912 out
913}
914
915/// Whether the last line of `text`, which ends in a line end, is blank.
916fn ends_with_blank_line(text: &str) -> bool {
917 let body = text
918 .strip_suffix('\n')
919 .map(|body| body.strip_suffix('\r').unwrap_or(body))
920 .unwrap_or(text);
921 body.is_empty() || body.ends_with('\n')
922}
923
924/// The branch a section was written for, as its first comment says, if
925/// the section can name it.
926pub(crate) fn named_branch(section: &str) -> Option<String> {
927 let line = section.lines().find(|line| line.contains(BRANCH_NOTE))?;
928 let (_, rest) = line.split_once(BRANCH_NOTE)?;
929 let (name, _) = rest.split_once(')')?;
930 is_section_branch(name).then(|| name.to_owned())
931}
932
933/// `line` without its code spans: the text between two runs of the same
934/// number of backticks. A run that nothing closes stays, as text.
935fn without_code_spans(line: &str) -> String {
936 let mut out = String::with_capacity(line.len());
937 let mut rest = line;
938 while let Some(at) = rest.find('`') {
939 out.push_str(&rest[..at]);
940 let run = rest[at..].bytes().take_while(|byte| *byte == b'`').count();
941 let after = &rest[at + run..];
942 match closing_run(after, run) {
943 Some(end) => {
944 out.push(' ');
945 rest = &after[end..];
946 }
947 None => {
948 out.push_str(&rest[at..at + run]);
949 rest = after;
950 }
951 }
952 }
953 out.push_str(rest);
954 out
955}
956
957/// Where the first run of exactly `run` backticks in `text` ends.
958fn closing_run(text: &str, run: usize) -> Option<usize> {
959 let mut from = 0;
960 while let Some(at) = text[from..].find('`') {
961 let start = from + at;
962 let length = text[start..]
963 .bytes()
964 .take_while(|byte| *byte == b'`')
965 .count();
966 if length == run {
967 return Some(start + length);
968 }
969 from = start + length;
970 }
971 None
972}
973
974/// Whether a `CLAUDE.md` or `GEMINI.md` includes `AGENTS.md`: a word
975/// `@AGENTS.md` or `@./AGENTS.md` outside code, as Claude Code reads its
976/// imports. Neither a code span nor a fenced code block imports anything.
977pub(crate) fn includes_agents(text: &str) -> bool {
978 let mut fences = Fences::default();
979 text.lines().enumerate().any(|(index, line)| {
980 let line = if index == 0 { without_bom(line) } else { line };
981 !fences.code(line, index + 1)
982 && without_code_spans(line).split_whitespace().any(|word| {
983 let word = word
984 .trim_start_matches('(')
985 .trim_end_matches([',', ';', ':', ')']);
986 word == INCLUDE || word == "@./AGENTS.md"
987 })
988 })
989}
990
991/// `text` with `@AGENTS.md` as its last line.
992pub(crate) fn add_include(text: &str) -> String {
993 let end = line_end(text);
994 let mut out = text.to_owned();
995 if !out.is_empty() && !out.ends_with('\n') {
996 out.push_str(end);
997 }
998 out.push_str(INCLUDE);
999 out.push_str(end);
1000 out
1001}
1002
1003/// What tells two names of one file apart from two files: the device and
1004/// the inode where there are hard links, the canonical path elsewhere.
1005#[cfg(unix)]
1006type FileId = (u64, u64);
1007#[cfg(not(unix))]
1008type FileId = PathBuf;
1009
1010#[cfg(unix)]
1011fn file_id(meta: &fs::Metadata, _path: &Path) -> FileId {
1012 use std::os::unix::fs::MetadataExt;
1013 (meta.dev(), meta.ino())
1014}
1015
1016#[cfg(not(unix))]
1017fn file_id(_meta: &fs::Metadata, path: &Path) -> FileId {
1018 fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1019}
1020
1021/// How many names the file has.
1022#[cfg(unix)]
1023fn names_of(meta: &fs::Metadata) -> u64 {
1024 use std::os::unix::fs::MetadataExt;
1025 meta.nlink()
1026}
1027
1028#[cfg(not(unix))]
1029fn names_of(_meta: &fs::Metadata) -> u64 {
1030 1
1031}
1032
1033/// The guides of `dir` that are regular files, not symbolic links, with
1034/// what tells them apart: the names a file with hard links may have here.
1035fn guide_files(dir: &Path) -> Vec<(PathBuf, FileId)> {
1036 [AGENTS_FILE, CLAUDE_FILE, GEMINI_FILE]
1037 .iter()
1038 .filter_map(|name| {
1039 let path = dir.join(name);
1040 let meta = fs::symlink_metadata(&path).ok()?;
1041 meta.is_file().then(|| {
1042 let id = file_id(&meta, &path);
1043 (path, id)
1044 })
1045 })
1046 .collect()
1047}
1048
1049/// The file a guide is, once checked: what is read and written.
1050#[derive(Clone, Debug)]
1051struct Target {
1052 /// Where the text is: the name itself, or the file its link points to.
1053 path: PathBuf,
1054 /// That file as the output names it: its path from the project's
1055 /// directory, or the whole path when it is elsewhere in the repository.
1056 shown: String,
1057 /// Whether the file exists.
1058 exists: bool,
1059 /// Whether it is written in place rather than replaced, since it has
1060 /// hard links, all of them guides of the project.
1061 in_place: bool,
1062 /// What tells it from other files, when it exists.
1063 id: Option<FileId>,
1064}
1065
1066impl Target {
1067 /// A file that does not exist yet: `name` in `dir`.
1068 fn new_file(dir: &Path, name: &str) -> Target {
1069 Target {
1070 path: dir.join(name),
1071 shown: name.to_owned(),
1072 exists: false,
1073 in_place: false,
1074 id: None,
1075 }
1076 }
1077
1078 /// How the output names the file known as `name`: by that name, and by
1079 /// the file its link points to when that is another.
1080 fn called(&self, name: &str) -> String {
1081 if self.shown == name {
1082 name.to_owned()
1083 } else {
1084 format!("{name} ({}, which it links to)", self.shown)
1085 }
1086 }
1087
1088 /// The file's text, or `None` when it does not exist.
1089 fn read(&self) -> Result<Option<String>> {
1090 if !self.exists {
1091 return Ok(None);
1092 }
1093 let bytes =
1094 fs::read(&self.path).with_context(|| format!("cannot read {}", self.path.display()))?;
1095 String::from_utf8(bytes)
1096 .map(Some)
1097 .map_err(|_| anyhow!("{} is not UTF-8 text: {NOTHING}", self.shown))
1098 }
1099}
1100
1101/// What a guide's name leads to.
1102enum Located {
1103 /// Nothing has the name.
1104 Missing,
1105 /// A symbolic link to a file that does not exist; where it points.
1106 Dangling(PathBuf),
1107 /// A file braid may write.
1108 File(Target),
1109}
1110
1111/// Finds the file `name` of `dir` is, and checks that braid may write it:
1112/// a regular file, or a symbolic link to one inside `roots`, the project's
1113/// directory and the repository's root; not read-only; and with no hard
1114/// link but the guides of `dir`. Every check runs before anything is read,
1115/// with or without `--dry-run`, so that a dry run fails as the real run
1116/// would, and a FIFO is never opened.
1117fn locate_file(
1118 dir: &Path,
1119 name: &'static str,
1120 roots: &[PathBuf],
1121 guides: &[(PathBuf, FileId)],
1122) -> Result<Located> {
1123 let path = dir.join(name);
1124 let own = match fs::symlink_metadata(&path) {
1125 Ok(meta) => meta,
1126 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Located::Missing),
1127 Err(err) => return Err(err).with_context(|| format!("cannot read {}", path.display())),
1128 };
1129 let linked = own.file_type().is_symlink();
1130 let (path, meta) = if linked {
1131 let target = match fs::canonicalize(&path) {
1132 Ok(target) => target,
1133 Err(err) if err.kind() == io::ErrorKind::NotFound => {
1134 return Ok(Located::Dangling(fs::read_link(&path).unwrap_or_default()));
1135 }
1136 Err(err) => {
1137 return Err(err).with_context(|| format!("cannot follow {}", path.display()));
1138 }
1139 };
1140 let meta =
1141 fs::metadata(&target).with_context(|| format!("cannot read {}", target.display()))?;
1142 (target, meta)
1143 } else {
1144 (path, own)
1145 };
1146 let shown = if linked {
1147 match path.strip_prefix(&roots[0]) {
1148 Ok(inside) => inside.to_string_lossy().into_owned(),
1149 Err(_) => path.to_string_lossy().into_owned(),
1150 }
1151 } else {
1152 name.to_owned()
1153 };
1154 if !meta.is_file() {
1155 let what = if linked {
1156 format!("{name}, a link to {shown},")
1157 } else {
1158 name.to_owned()
1159 };
1160 bail!("{what} is not a regular file: {NOTHING}");
1161 }
1162 if linked && !roots.iter().any(|root| path.starts_with(root)) {
1163 bail!(
1164 "{name} is a link to {}, outside the project: other projects may read that file too. Replace the link with a copy of the file, or point it inside the project: {NOTHING}",
1165 path.display()
1166 );
1167 }
1168 if meta.permissions().readonly() {
1169 bail!("{shown} is read-only: make it writable, then run the command again: {NOTHING}");
1170 }
1171 let id = file_id(&meta, &path);
1172 let mut known = vec![path.clone()];
1173 for (other, other_id) in guides {
1174 if *other_id == id && !known.contains(other) {
1175 known.push(other.clone());
1176 }
1177 }
1178 let names = names_of(&meta);
1179 if names > known.len() as u64 {
1180 bail!(
1181 "{shown} has hard links besides the {AGENTS_FILE}, {CLAUDE_FILE} and {GEMINI_FILE} here: writing it would change the file under those names too. Replace it with a copy, then run the command again: {NOTHING}"
1182 );
1183 }
1184 Ok(Located::File(Target {
1185 path,
1186 shown,
1187 exists: true,
1188 in_place: names > 1,
1189 id: Some(id),
1190 }))
1191}
1192
1193/// Writes every planned file that changes. Each is first written whole to
1194/// a temporary file next to it, so that a failure there leaves every file
1195/// as it was; then each replaces its file with a rename, so that no file
1196/// is ever seen half written. A file with hard links is written in place,
1197/// last. A failure after the first file is replaced says which were.
1198fn write_all(planned: &[Planned]) -> Result<()> {
1199 let changing: Vec<(&Planned, &str)> = planned
1200 .iter()
1201 .filter_map(|file| file.contents.as_deref().map(|contents| (file, contents)))
1202 .collect();
1203 let mut staged: Vec<(&Planned, PathBuf)> = Vec::new();
1204 for (file, contents) in changing.iter().filter(|(file, _)| !file.target.in_place) {
1205 match stage(&file.target.path, contents) {
1206 Ok(temp) => staged.push((file, temp)),
1207 Err(err) => {
1208 for (_, temp) in &staged {
1209 let _ = fs::remove_file(temp);
1210 }
1211 return Err(failed(file, &err, &[]));
1212 }
1213 }
1214 }
1215 let mut written: Vec<&str> = Vec::new();
1216 let mut renames = staged.into_iter();
1217 while let Some((file, temp)) = renames.next() {
1218 if let Err(err) = fs::rename(&temp, &file.target.path) {
1219 let _ = fs::remove_file(&temp);
1220 for (_, rest) in renames {
1221 let _ = fs::remove_file(rest);
1222 }
1223 return Err(failed(file, &err, &written));
1224 }
1225 written.push(&file.target.shown);
1226 }
1227 for (file, contents) in changing.iter().filter(|(file, _)| file.target.in_place) {
1228 if let Err(err) = write_in_place(&file.target.path, contents) {
1229 return Err(failed(file, &err, &written));
1230 }
1231 written.push(&file.target.shown);
1232 }
1233 Ok(())
1234}
1235
1236/// The error for `file`, which could not be written, saying which files
1237/// were.
1238fn failed(file: &Planned, err: &io::Error, written: &[&str]) -> anyhow::Error {
1239 let shown = &file.target.shown;
1240 let done = match written {
1241 [] => NOTHING.to_owned(),
1242 [one] => format!("{one} was written, {shown} was not"),
1243 several => format!("{} were written, {shown} was not", listed(several)),
1244 };
1245 anyhow!("cannot write {shown}: {err}; {done}")
1246}
1247
1248/// Writes `contents` to a new temporary file next to `path`, with the
1249/// permissions `path` has, and returns its path once it is on disk.
1250fn stage(path: &Path, contents: &str) -> io::Result<PathBuf> {
1251 let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
1252 return Err(io::Error::other("it has no directory"));
1253 };
1254 let name = name.to_string_lossy();
1255 let mut attempt = 0u32;
1256 let (temp, mut file) = loop {
1257 let temp = parent.join(format!(".{name}.braid-{}-{attempt}", std::process::id()));
1258 match OpenOptions::new().write(true).create_new(true).open(&temp) {
1259 Ok(file) => break (temp, file),
1260 Err(err) if err.kind() == io::ErrorKind::AlreadyExists && attempt < 64 => {
1261 attempt += 1;
1262 }
1263 Err(err) => return Err(err),
1264 }
1265 };
1266 let mut written = || -> io::Result<()> {
1267 if let Ok(meta) = fs::metadata(path) {
1268 fs::set_permissions(&temp, meta.permissions())?;
1269 }
1270 file.write_all(contents.as_bytes())?;
1271 file.sync_all()
1272 };
1273 match written() {
1274 Ok(()) => Ok(temp),
1275 Err(err) => {
1276 let _ = fs::remove_file(&temp);
1277 Err(err)
1278 }
1279 }
1280}
1281
1282/// Writes `contents` over the file at `path`, keeping the file and so
1283/// every name it has.
1284fn write_in_place(path: &Path, contents: &str) -> io::Result<()> {
1285 let mut file = OpenOptions::new().write(true).truncate(true).open(path)?;
1286 file.write_all(contents.as_bytes())?;
1287 file.sync_all()
1288}
1289
1290#[cfg(test)]
1291mod tests {
1292 use super::*;
1293
1294 const ABOVE: &str = "# Project\n\nRules of our own.\n\n";
1295 const BELOW: &str = "\n## More rules\n\nKept as they are.\n";
1296
1297 fn find(text: &str) -> Result<Option<Range<usize>>, String> {
1298 scan_section(text).map(|scanned| scanned.section)
1299 }
1300
1301 #[test]
1302 fn the_section_names_the_branch_and_holds_no_marker_inside() {
1303 let text = section("trunk");
1304 assert!(text.starts_with(&format!("{START}\n")));
1305 assert!(text.ends_with(&format!("\n{END}\n")));
1306 assert!(text.contains("--track trunk\n"));
1307 assert!(text.contains("land their changes on `trunk`"));
1308 assert!(text.contains("--branch trunk\n"));
1309 assert!(
1310 !text.contains("`main`") && !text.contains(" main"),
1311 "{text}"
1312 );
1313 assert_eq!(named_branch(&text).as_deref(), Some("trunk"));
1314 // The markers appear once each, on their own lines, and the
1315 // section's own code blocks are closed.
1316 assert_eq!(
1317 scan_section(&text),
1318 Ok(Scanned {
1319 section: Some(0..text.len()),
1320 open_fence: None
1321 })
1322 );
1323 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
1324 }
1325
1326 #[test]
1327 fn branches_the_section_can_name_read_back_exactly() {
1328 for good in [
1329 "main",
1330 "master",
1331 "trunk",
1332 "release-1.2",
1333 "feature/x.y_z-1",
1334 "v1.x/beta",
1335 "UPPER_case",
1336 ] {
1337 assert!(is_section_branch(good), "{good}");
1338 assert_eq!(named_branch(&section(good)).as_deref(), Some(good));
1339 }
1340 for bad in [
1341 "",
1342 "feat(x)",
1343 "a;b",
1344 "a;touch${IFS}pwned",
1345 "q$(id)",
1346 "x`id`",
1347 "it's",
1348 "a|b",
1349 "a>b",
1350 "a b",
1351 "-x",
1352 "--no-claude",
1353 "a..b",
1354 "x.lock",
1355 "tags/v1",
1356 "braid/git-map",
1357 "rama-ñ",
1358 ] {
1359 assert!(!is_section_branch(bad), "{bad}");
1360 }
1361 // A section an older braid wrote for a name it cannot hold names
1362 // nothing, rather than a part of it.
1363 let old =
1364 format!("{START}\n<!-- Written by `braid agents init` (branch: feat(x)). -->\n{END}\n");
1365 assert_eq!(named_branch(&old), None);
1366 }
1367
1368 #[test]
1369 fn a_section_is_appended_after_a_blank_line() {
1370 let new = section("main");
1371 assert_eq!(append_section("", &new), new);
1372 assert_eq!(append_section("# Rules", &new), format!("# Rules\n\n{new}"));
1373 assert_eq!(
1374 append_section("# Rules\n", &new),
1375 format!("# Rules\n\n{new}")
1376 );
1377 assert_eq!(
1378 append_section("# Rules\n\n", &new),
1379 format!("# Rules\n\n{new}")
1380 );
1381 // Line ends follow the file's.
1382 let crlf = append_section("# Rules\r\n", &new);
1383 assert_eq!(
1384 crlf,
1385 format!("# Rules\r\n\r\n{}", new.replace('\n', "\r\n"))
1386 );
1387 let range = find(&crlf).unwrap().unwrap();
1388 assert_eq!(replace_section(&crlf, range, &new), crlf);
1389 }
1390
1391 #[test]
1392 fn only_the_text_between_the_markers_changes() {
1393 let old = format!("{START}\nan older section\n{END}\n");
1394 let text = format!("{ABOVE}{old}{BELOW}");
1395 let range = find(&text).unwrap().unwrap();
1396 assert_eq!(&text[range.clone()], old);
1397 let new = replace_section(&text, range, &section("main"));
1398 assert_eq!(new, format!("{ABOVE}{}{BELOW}", section("main")));
1399 // Again: nothing changes.
1400 let range = find(&new).unwrap().unwrap();
1401 assert_eq!(replace_section(&new, range, &section("main")), new);
1402 // The older section named no branch.
1403 assert_eq!(named_branch(&old), None);
1404 }
1405
1406 #[test]
1407 fn markers_may_be_indented_a_little_but_must_be_alone() {
1408 let text = format!(" {START} \nx\n{END}\n");
1409 assert_eq!(find(&text), Ok(Some(0..text.len())));
1410 for not_markers in [
1411 format!(" {START}\n{END}\n"),
1412 format!("see `{START}`\n{END}\n"),
1413 format!("{START} and more\n{END}\n"),
1414 ] {
1415 assert!(find(&not_markers).is_err(), "{not_markers:?}");
1416 }
1417 assert_eq!(find("no markers at all\n"), Ok(None));
1418 }
1419
1420 #[test]
1421 fn markers_in_fenced_code_blocks_are_examples() {
1422 let example = format!("```markdown\n{START}\n(the rules braid writes)\n{END}\n```\n");
1423 let text = format!("# Rules\n\n{example}");
1424 assert_eq!(
1425 scan_section(&text),
1426 Ok(Scanned {
1427 section: None,
1428 open_fence: None
1429 })
1430 );
1431 // Next to a real section, the example is left alone.
1432 let real = section("main");
1433 let both = format!("{text}\n{real}");
1434 let range = find(&both).unwrap().unwrap();
1435 assert_eq!(&both[range], real);
1436 // Tildes, longer fences, and a fence that only a fence as long
1437 // closes.
1438 for fenced in [
1439 format!("~~~\n{START}\n~~~\n"),
1440 format!("````text\n```\n{END}\n````\n"),
1441 format!(" ```\n{START}\n{END}\n ```\n"),
1442 ] {
1443 assert_eq!(find(&fenced), Ok(None), "{fenced:?}");
1444 }
1445 // Four spaces make no fence, and backticks in a backtick fence's
1446 // info string make none either.
1447 assert!(find(&format!(" ```\n{START}\n")).is_err());
1448 assert!(find(&format!("``` a`b\n{START}\n")).is_err());
1449 // A block that is never closed hides what follows it, and says
1450 // where it opens.
1451 let open = format!("# Rules\n\n```bash\nmake test\n{START}\n{END}\n");
1452 assert_eq!(
1453 scan_section(&open),
1454 Ok(Scanned {
1455 section: None,
1456 open_fence: Some(3)
1457 })
1458 );
1459 assert_eq!(open_fence(&open), Some(3));
1460 assert_eq!(open_fence(&text), None);
1461 }
1462
1463 #[test]
1464 fn a_byte_order_mark_before_the_start_marker_stays() {
1465 let section = section("main");
1466 let text = format!("\u{feff}{section}");
1467 let range = find(&text).unwrap().unwrap();
1468 assert_eq!(range, '\u{feff}'.len_utf8()..text.len());
1469 assert_eq!(replace_section(&text, range, &section), text);
1470 assert!(includes_agents("\u{feff}@AGENTS.md\n"));
1471 assert_eq!(
1472 append_section("\u{feff}", &section),
1473 format!("\u{feff}{section}")
1474 );
1475 assert_eq!(
1476 append_section("\u{feff}# Rules\n", &section),
1477 format!("\u{feff}# Rules\n\n{section}")
1478 );
1479 }
1480
1481 #[test]
1482 fn unbalanced_markers_are_refused_with_their_lines() {
1483 let cases = [
1484 (
1485 format!("a\n{START}\nb\n"),
1486 "on line 2, `<!-- braid:end -->` on no line",
1487 ),
1488 (
1489 format!("{END}\n"),
1490 "on no line, `<!-- braid:end -->` on line 1",
1491 ),
1492 (
1493 format!("{END}\n{START}\n"),
1494 "on line 2, `<!-- braid:end -->` on line 1",
1495 ),
1496 (
1497 format!("{START}\n{START}\n{END}\n"),
1498 "on lines 1 and 2, `<!-- braid:end -->` on line 3",
1499 ),
1500 (
1501 format!("{START}\n{END}\n{START}\n{END}\n{END}\n"),
1502 "on lines 1 and 3, `<!-- braid:end -->` on lines 2, 4 and 5",
1503 ),
1504 ];
1505 for (text, said) in cases {
1506 let err = find(&text).unwrap_err();
1507 assert!(err.contains(said), "{text:?}: {err}");
1508 }
1509 }
1510
1511 #[test]
1512 fn claude_md_includes() {
1513 for yes in [
1514 "@AGENTS.md\n",
1515 "# Notes\nSee @AGENTS.md for the rules.\n",
1516 "(@./AGENTS.md)\n",
1517 " @AGENTS.md ",
1518 "```text\nan example\n```\n@AGENTS.md\n",
1519 "Read `this` and @AGENTS.md\n",
1520 ] {
1521 assert!(includes_agents(yes), "{yes:?}");
1522 }
1523 for no in [
1524 "",
1525 "Read AGENTS.md\n",
1526 "`@AGENTS.md`\n",
1527 "@AGENTS.md.bak\n",
1528 "@docs/AGENTS.md\n",
1529 "``see @AGENTS.md here``\n",
1530 "# Claude notes\n\n```text\n@AGENTS.md\n```\n",
1531 "~~~\n@AGENTS.md\n",
1532 ] {
1533 assert!(!includes_agents(no), "{no:?}");
1534 }
1535 assert_eq!(add_include(""), "@AGENTS.md\n");
1536 assert_eq!(add_include("# Claude"), "# Claude\n@AGENTS.md\n");
1537 assert_eq!(add_include("# Claude\n"), "# Claude\n@AGENTS.md\n");
1538 assert_eq!(add_include("# Claude\r\n"), "# Claude\r\n@AGENTS.md\r\n");
1539 assert!(includes_agents(&add_include("# Claude\n")));
1540 }
1541
1542 #[test]
1543 fn code_spans_are_left_out() {
1544 assert_eq!(without_code_spans("a `b` c"), "a c");
1545 assert_eq!(without_code_spans("a ``b ` c`` d"), "a d");
1546 assert_eq!(without_code_spans("a ` b"), "a ` b");
1547 assert_eq!(without_code_spans("é `x` ü"), "é ü");
1548 assert_eq!(without_code_spans("``a` b"), "``a` b");
1549 }
1550}