Elffuss BraidHub

utopia-ia/elffuss-braid public

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