Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 58.9 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- If `braid verify` reverted a changeset of yours, fix it and land a new
726 changeset.
727- **On a hub:** when `braid hub status` names a hub (the repository was
728 published on [BraidHub](https://braidhub.elffuss.com) or cloned from it;
729 elsewhere it says the repository is not linked), `land` and `update` go
730 through the hub, where agents on other machines land too, and answer as
731 they do here. When it names a mirror of `{branch}` on GitHub, the hub
732 sends what lands there itself: skip the `git sync` below, and the user's
733 checkout gets it with `git pull --ff-only`. Without the network,
734 `land --local` and `update --local` work in this repository only. New
735 projects you start for the user go on BraidHub only as
736 <https://braidhub.elffuss.com/agents.md> says.
737- **When you finish**, tell the user that what you landed is on braid's
738 `{branch}` only: their checkout and the git remote get it once someone
739 runs this from the project root.
740
741 ```bash
742 braid --agent agent-1 git sync \"$(git remote get-url origin)\" --branch {branch}
743 git pull --ff-only
744 ```
745
746 Offer to run it: when to sync is the user's call. If the sync exits
747 with 2 (`conflicts`), braid and the remote changed the same lines, and
748 nothing moved: tell the user, since the merge is made with git, in their
749 checkout, as <https://braid.elffuss.com/agents.md> shows under
750 \"Keeping the git remote up to date\". With `remote_moved` (exit status
751 1), sync again; with `rejected`, ask the user. If `git pull --ff-only`
752 refuses, their checkout has commits of its own, and what to do is their
753 call: `git pull --rebase`, `git push` and a new sync bring them into
754 braid. Where `git remote get-url origin` fails, the project has no
755 remote of that name: if `git remote` lists others, ask the user which to
756 sync with, and write its name in place of `origin`; if it lists none,
757 say so, and offer to make one next to the project first, from the
758 project root:
759
760 ```bash
761 git init --bare -b {branch} \"$PWD.git\"
762 git remote add origin \"$PWD.git\"
763 git push -u origin {branch}
764 ```
765
766 Once everything has landed, `braid workspace remove agent-1`, from the
767 project root, removes your workspace.
768- Changesets are signed by `BRAID_AUTHOR` (`\"Name <email>\"`), or else by the
769 `name` and `email` in `.braid/config`. With neither, `commit`, `land` and
770 `update` fail with \"no author\", and `status` lists it first among what
771 stops a commit: ask the user who signs, and write the answer into
772 `.braid/config` in the project root, the one file there you may edit, as
773 `name = <name>` and `email = <email>` lines. The merges that `git sync`
774 makes are signed by its `--agent`, with that email.
775- New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
776 than 1 MiB wait for `braid track <path>`. Never track a secret: move it
777 out of the workspace.
778- `braid --agent agent-1 undo` reverts the newest operation in the
779 repository, whoever made it: read `braid op log` first.
780{END}
781"
782 )
783}
784
785/// Whether `line` is `marker`: alone on its line, indented by three spaces
786/// at most, as Markdown lets an HTML comment be.
787fn is_marker(line: &str, marker: &str) -> bool {
788 let line = line.trim_end();
789 let text = line.trim_start_matches(' ');
790 line.len() - text.len() <= 3 && text == marker
791}
792
793/// The fence a line opens or closes, as CommonMark reads one: indented by
794/// three spaces at most, then three or more backticks or tildes, with no
795/// backtick after backticks. Gives the character, how many of it there
796/// are, and the rest of the line.
797fn fence(line: &str) -> Option<(u8, usize, &str)> {
798 let line = line.trim_end_matches(['\n', '\r']);
799 let text = line.trim_start_matches(' ');
800 if line.len() - text.len() > 3 {
801 return None;
802 }
803 let mark = *text.as_bytes().first()?;
804 if mark != b'`' && mark != b'~' {
805 return None;
806 }
807 let count = text.bytes().take_while(|byte| *byte == mark).count();
808 let rest = &text[count..];
809 (count >= 3 && !(mark == b'`' && rest.contains('`'))).then_some((mark, count, rest))
810}
811
812/// Follows the fenced code blocks of a Markdown text, a line at a time.
813#[derive(Debug, Default)]
814struct Fences {
815 /// The block open after the last line: its fence's character and
816 /// length, and the line it opened on.
817 open: Option<(u8, usize, usize)>,
818}
819
820impl Fences {
821 /// Whether line number `number` is code: a fence, or inside a block.
822 fn code(&mut self, line: &str, number: usize) -> bool {
823 match (self.open, fence(line)) {
824 (Some((mark, count, _)), Some((found, length, rest)))
825 if found == mark && length >= count && rest.trim().is_empty() =>
826 {
827 self.open = None;
828 true
829 }
830 (Some(_), _) => true,
831 (None, Some((mark, count, _))) => {
832 self.open = Some((mark, count, number));
833 true
834 }
835 (None, None) => false,
836 }
837 }
838}
839
840/// `line`, the first of a text, without the byte order mark an editor may
841/// have put before it.
842fn without_bom(line: &str) -> &str {
843 line.strip_prefix('\u{feff}').unwrap_or(line)
844}
845
846/// The line a fenced code block that `text` never closes opens on.
847fn open_fence(text: &str) -> Option<usize> {
848 let mut fences = Fences::default();
849 for (index, line) in text.lines().enumerate() {
850 let line = if index == 0 { without_bom(line) } else { line };
851 fences.code(line, index + 1);
852 }
853 fences.open.map(|(_, _, line)| line)
854}
855
856/// What a Markdown text holds of the braid section.
857#[derive(Debug, Default, PartialEq, Eq)]
858pub(crate) struct Scanned {
859 /// The section: from the start of its start marker's line to the end of
860 /// its end marker's line.
861 pub(crate) section: Option<Range<usize>>,
862 /// The line a fenced code block that the text never closes opens on.
863 pub(crate) open_fence: Option<usize>,
864}
865
866/// Where the braid section is in `text`, with the markers inside fenced
867/// code blocks left out, as examples rather than markers. An error that
868/// says where they are when they do not pair up.
869pub(crate) fn scan_section(text: &str) -> Result<Scanned, String> {
870 let mut starts = Vec::new();
871 let mut ends = Vec::new();
872 let mut fences = Fences::default();
873 let mut offset = 0;
874 for (index, line) in text.split_inclusive('\n').enumerate() {
875 // A byte order mark is not part of the first line: the section
876 // starts after it, so that it stays.
877 let skip = if index == 0 {
878 line.len() - without_bom(line).len()
879 } else {
880 0
881 };
882 let body = &line[skip..];
883 if !fences.code(body, index + 1) {
884 if is_marker(body, START) {
885 starts.push((index + 1, offset + skip));
886 } else if is_marker(body, END) {
887 ends.push((index + 1, offset + line.len()));
888 }
889 }
890 offset += line.len();
891 }
892 let section = match (starts.as_slice(), ends.as_slice()) {
893 ([], []) => None,
894 ([(first, from)], [(last, to)]) if first < last => Some(*from..*to),
895 _ => {
896 return Err(format!(
897 "`{START}` is on {}, `{END}` on {}, and there must be one of each, the start first",
898 line_list(&starts),
899 line_list(&ends)
900 ));
901 }
902 };
903 Ok(Scanned {
904 section,
905 open_fence: fences.open.map(|(_, _, line)| line),
906 })
907}
908
909/// `no line`, `line 3`, `lines 3 and 9`, `lines 3, 9 and 12`.
910fn line_list(found: &[(usize, usize)]) -> String {
911 let numbers: Vec<String> = found.iter().map(|(line, _)| line.to_string()).collect();
912 match numbers.as_slice() {
913 [] => "no line".to_owned(),
914 [one] => format!("line {one}"),
915 [rest @ .., last] => format!("lines {} and {last}", rest.join(", ")),
916 }
917}
918
919/// The line end `text` uses: `\r\n` if it has any, otherwise `\n`.
920fn line_end(text: &str) -> &'static str {
921 if text.contains("\r\n") { "\r\n" } else { "\n" }
922}
923
924/// `section`, written with the line ends of `text`.
925fn in_line_ends_of(text: &str, section: &str) -> String {
926 match line_end(text) {
927 "\n" => section.to_owned(),
928 end => section.replace('\n', end),
929 }
930}
931
932/// `text` with the section at `range` replaced by `section`.
933pub(crate) fn replace_section(text: &str, range: Range<usize>, section: &str) -> String {
934 let section = in_line_ends_of(text, section);
935 let mut out = String::with_capacity(text.len() - range.len() + section.len());
936 out.push_str(&text[..range.start]);
937 out.push_str(&section);
938 out.push_str(&text[range.end..]);
939 out
940}
941
942/// `text` with `section` at its end, after a blank line.
943pub(crate) fn append_section(text: &str, section: &str) -> String {
944 let end = line_end(text);
945 let section = in_line_ends_of(text, section);
946 let mut out = String::with_capacity(text.len() + section.len() + 2 * end.len());
947 out.push_str(text);
948 if !without_bom(text).is_empty() {
949 if !out.ends_with('\n') {
950 out.push_str(end);
951 }
952 if !without_bom(&out).trim_end_matches(['\n', '\r']).is_empty()
953 && !ends_with_blank_line(&out)
954 {
955 out.push_str(end);
956 }
957 }
958 out.push_str(&section);
959 out
960}
961
962/// Whether the last line of `text`, which ends in a line end, is blank.
963fn ends_with_blank_line(text: &str) -> bool {
964 let body = text
965 .strip_suffix('\n')
966 .map(|body| body.strip_suffix('\r').unwrap_or(body))
967 .unwrap_or(text);
968 body.is_empty() || body.ends_with('\n')
969}
970
971/// The branch a section was written for, as its first comment says, if
972/// the section can name it.
973pub(crate) fn named_branch(section: &str) -> Option<String> {
974 let line = section.lines().find(|line| line.contains(BRANCH_NOTE))?;
975 let (_, rest) = line.split_once(BRANCH_NOTE)?;
976 let (name, _) = rest.split_once(')')?;
977 is_section_branch(name).then(|| name.to_owned())
978}
979
980/// `line` without its code spans: the text between two runs of the same
981/// number of backticks. A run that nothing closes stays, as text.
982fn without_code_spans(line: &str) -> String {
983 let mut out = String::with_capacity(line.len());
984 let mut rest = line;
985 while let Some(at) = rest.find('`') {
986 out.push_str(&rest[..at]);
987 let run = rest[at..].bytes().take_while(|byte| *byte == b'`').count();
988 let after = &rest[at + run..];
989 match closing_run(after, run) {
990 Some(end) => {
991 out.push(' ');
992 rest = &after[end..];
993 }
994 None => {
995 out.push_str(&rest[at..at + run]);
996 rest = after;
997 }
998 }
999 }
1000 out.push_str(rest);
1001 out
1002}
1003
1004/// Where the first run of exactly `run` backticks in `text` ends.
1005fn closing_run(text: &str, run: usize) -> Option<usize> {
1006 let mut from = 0;
1007 while let Some(at) = text[from..].find('`') {
1008 let start = from + at;
1009 let length = text[start..]
1010 .bytes()
1011 .take_while(|byte| *byte == b'`')
1012 .count();
1013 if length == run {
1014 return Some(start + length);
1015 }
1016 from = start + length;
1017 }
1018 None
1019}
1020
1021/// Whether a `CLAUDE.md` or `GEMINI.md` includes `AGENTS.md`: a word
1022/// `@AGENTS.md` or `@./AGENTS.md` outside code, as Claude Code reads its
1023/// imports. Neither a code span nor a fenced code block imports anything.
1024pub(crate) fn includes_agents(text: &str) -> bool {
1025 let mut fences = Fences::default();
1026 text.lines().enumerate().any(|(index, line)| {
1027 let line = if index == 0 { without_bom(line) } else { line };
1028 !fences.code(line, index + 1)
1029 && without_code_spans(line).split_whitespace().any(|word| {
1030 let word = word
1031 .trim_start_matches('(')
1032 .trim_end_matches([',', ';', ':', ')']);
1033 word == INCLUDE || word == "@./AGENTS.md"
1034 })
1035 })
1036}
1037
1038/// `text` with `@AGENTS.md` as its last line.
1039pub(crate) fn add_include(text: &str) -> String {
1040 let end = line_end(text);
1041 let mut out = text.to_owned();
1042 if !out.is_empty() && !out.ends_with('\n') {
1043 out.push_str(end);
1044 }
1045 out.push_str(INCLUDE);
1046 out.push_str(end);
1047 out
1048}
1049
1050/// What tells two names of one file apart from two files: the device and
1051/// the inode where there are hard links, the canonical path elsewhere.
1052#[cfg(unix)]
1053type FileId = (u64, u64);
1054#[cfg(not(unix))]
1055type FileId = PathBuf;
1056
1057#[cfg(unix)]
1058fn file_id(meta: &fs::Metadata, _path: &Path) -> FileId {
1059 use std::os::unix::fs::MetadataExt;
1060 (meta.dev(), meta.ino())
1061}
1062
1063#[cfg(not(unix))]
1064fn file_id(_meta: &fs::Metadata, path: &Path) -> FileId {
1065 fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1066}
1067
1068/// How many names the file has.
1069#[cfg(unix)]
1070fn names_of(meta: &fs::Metadata) -> u64 {
1071 use std::os::unix::fs::MetadataExt;
1072 meta.nlink()
1073}
1074
1075#[cfg(not(unix))]
1076fn names_of(_meta: &fs::Metadata) -> u64 {
1077 1
1078}
1079
1080/// The guides of `dir` that are regular files, not symbolic links, with
1081/// what tells them apart: the names a file with hard links may have here.
1082fn guide_files(dir: &Path) -> Vec<(PathBuf, FileId)> {
1083 [AGENTS_FILE, CLAUDE_FILE, GEMINI_FILE]
1084 .iter()
1085 .filter_map(|name| {
1086 let path = dir.join(name);
1087 let meta = fs::symlink_metadata(&path).ok()?;
1088 meta.is_file().then(|| {
1089 let id = file_id(&meta, &path);
1090 (path, id)
1091 })
1092 })
1093 .collect()
1094}
1095
1096/// The file a guide is, once checked: what is read and written.
1097#[derive(Clone, Debug)]
1098struct Target {
1099 /// Where the text is: the name itself, or the file its link points to.
1100 path: PathBuf,
1101 /// That file as the output names it: its path from the project's
1102 /// directory, or the whole path when it is elsewhere in the repository.
1103 shown: String,
1104 /// Whether the file exists.
1105 exists: bool,
1106 /// Whether it is written in place rather than replaced, since it has
1107 /// hard links, all of them guides of the project.
1108 in_place: bool,
1109 /// What tells it from other files, when it exists.
1110 id: Option<FileId>,
1111}
1112
1113impl Target {
1114 /// A file that does not exist yet: `name` in `dir`.
1115 fn new_file(dir: &Path, name: &str) -> Target {
1116 Target {
1117 path: dir.join(name),
1118 shown: name.to_owned(),
1119 exists: false,
1120 in_place: false,
1121 id: None,
1122 }
1123 }
1124
1125 /// How the output names the file known as `name`: by that name, and by
1126 /// the file its link points to when that is another.
1127 fn called(&self, name: &str) -> String {
1128 if self.shown == name {
1129 name.to_owned()
1130 } else {
1131 format!("{name} ({}, which it links to)", self.shown)
1132 }
1133 }
1134
1135 /// The file's text, or `None` when it does not exist.
1136 fn read(&self) -> Result<Option<String>> {
1137 if !self.exists {
1138 return Ok(None);
1139 }
1140 let bytes =
1141 fs::read(&self.path).with_context(|| format!("cannot read {}", self.path.display()))?;
1142 String::from_utf8(bytes)
1143 .map(Some)
1144 .map_err(|_| anyhow!("{} is not UTF-8 text: {NOTHING}", self.shown))
1145 }
1146}
1147
1148/// What a guide's name leads to.
1149enum Located {
1150 /// Nothing has the name.
1151 Missing,
1152 /// A symbolic link to a file that does not exist; where it points.
1153 Dangling(PathBuf),
1154 /// A file braid may write.
1155 File(Target),
1156}
1157
1158/// Finds the file `name` of `dir` is, and checks that braid may write it:
1159/// a regular file, or a symbolic link to one inside `roots`, the project's
1160/// directory and the repository's root; not read-only; and with no hard
1161/// link but the guides of `dir`. Every check runs before anything is read,
1162/// with or without `--dry-run`, so that a dry run fails as the real run
1163/// would, and a FIFO is never opened.
1164fn locate_file(
1165 dir: &Path,
1166 name: &'static str,
1167 roots: &[PathBuf],
1168 guides: &[(PathBuf, FileId)],
1169) -> Result<Located> {
1170 let path = dir.join(name);
1171 let own = match fs::symlink_metadata(&path) {
1172 Ok(meta) => meta,
1173 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Located::Missing),
1174 Err(err) => return Err(err).with_context(|| format!("cannot read {}", path.display())),
1175 };
1176 let linked = own.file_type().is_symlink();
1177 let (path, meta) = if linked {
1178 let target = match fs::canonicalize(&path) {
1179 Ok(target) => target,
1180 Err(err) if err.kind() == io::ErrorKind::NotFound => {
1181 return Ok(Located::Dangling(fs::read_link(&path).unwrap_or_default()));
1182 }
1183 Err(err) => {
1184 return Err(err).with_context(|| format!("cannot follow {}", path.display()));
1185 }
1186 };
1187 let meta =
1188 fs::metadata(&target).with_context(|| format!("cannot read {}", target.display()))?;
1189 (target, meta)
1190 } else {
1191 (path, own)
1192 };
1193 let shown = if linked {
1194 match path.strip_prefix(&roots[0]) {
1195 Ok(inside) => inside.to_string_lossy().into_owned(),
1196 Err(_) => path.to_string_lossy().into_owned(),
1197 }
1198 } else {
1199 name.to_owned()
1200 };
1201 if !meta.is_file() {
1202 let what = if linked {
1203 format!("{name}, a link to {shown},")
1204 } else {
1205 name.to_owned()
1206 };
1207 bail!("{what} is not a regular file: {NOTHING}");
1208 }
1209 if linked && !roots.iter().any(|root| path.starts_with(root)) {
1210 bail!(
1211 "{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}",
1212 path.display()
1213 );
1214 }
1215 if meta.permissions().readonly() {
1216 bail!("{shown} is read-only: make it writable, then run the command again: {NOTHING}");
1217 }
1218 let id = file_id(&meta, &path);
1219 let mut known = vec![path.clone()];
1220 for (other, other_id) in guides {
1221 if *other_id == id && !known.contains(other) {
1222 known.push(other.clone());
1223 }
1224 }
1225 let names = names_of(&meta);
1226 if names > known.len() as u64 {
1227 bail!(
1228 "{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}"
1229 );
1230 }
1231 Ok(Located::File(Target {
1232 path,
1233 shown,
1234 exists: true,
1235 in_place: names > 1,
1236 id: Some(id),
1237 }))
1238}
1239
1240/// Writes every planned file that changes. Each is first written whole to
1241/// a temporary file next to it, so that a failure there leaves every file
1242/// as it was; then each replaces its file with a rename, so that no file
1243/// is ever seen half written. A file with hard links is written in place,
1244/// last. A failure after the first file is replaced says which were.
1245fn write_all(planned: &[Planned]) -> Result<()> {
1246 let changing: Vec<(&Planned, &str)> = planned
1247 .iter()
1248 .filter_map(|file| file.contents.as_deref().map(|contents| (file, contents)))
1249 .collect();
1250 let mut staged: Vec<(&Planned, PathBuf)> = Vec::new();
1251 for (file, contents) in changing.iter().filter(|(file, _)| !file.target.in_place) {
1252 match stage(&file.target.path, contents) {
1253 Ok(temp) => staged.push((file, temp)),
1254 Err(err) => {
1255 for (_, temp) in &staged {
1256 let _ = fs::remove_file(temp);
1257 }
1258 return Err(failed(file, &err, &[]));
1259 }
1260 }
1261 }
1262 let mut written: Vec<&str> = Vec::new();
1263 let mut renames = staged.into_iter();
1264 while let Some((file, temp)) = renames.next() {
1265 if let Err(err) = fs::rename(&temp, &file.target.path) {
1266 let _ = fs::remove_file(&temp);
1267 for (_, rest) in renames {
1268 let _ = fs::remove_file(rest);
1269 }
1270 return Err(failed(file, &err, &written));
1271 }
1272 written.push(&file.target.shown);
1273 }
1274 for (file, contents) in changing.iter().filter(|(file, _)| file.target.in_place) {
1275 if let Err(err) = write_in_place(&file.target.path, contents) {
1276 return Err(failed(file, &err, &written));
1277 }
1278 written.push(&file.target.shown);
1279 }
1280 Ok(())
1281}
1282
1283/// The error for `file`, which could not be written, saying which files
1284/// were.
1285fn failed(file: &Planned, err: &io::Error, written: &[&str]) -> anyhow::Error {
1286 let shown = &file.target.shown;
1287 let done = match written {
1288 [] => NOTHING.to_owned(),
1289 [one] => format!("{one} was written, {shown} was not"),
1290 several => format!("{} were written, {shown} was not", listed(several)),
1291 };
1292 anyhow!("cannot write {shown}: {err}; {done}")
1293}
1294
1295/// Writes `contents` to a new temporary file next to `path`, with the
1296/// permissions `path` has, and returns its path once it is on disk.
1297fn stage(path: &Path, contents: &str) -> io::Result<PathBuf> {
1298 let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
1299 return Err(io::Error::other("it has no directory"));
1300 };
1301 let name = name.to_string_lossy();
1302 let mut attempt = 0u32;
1303 let (temp, mut file) = loop {
1304 let temp = parent.join(format!(".{name}.braid-{}-{attempt}", std::process::id()));
1305 match OpenOptions::new().write(true).create_new(true).open(&temp) {
1306 Ok(file) => break (temp, file),
1307 Err(err) if err.kind() == io::ErrorKind::AlreadyExists && attempt < 64 => {
1308 attempt += 1;
1309 }
1310 Err(err) => return Err(err),
1311 }
1312 };
1313 let mut written = || -> io::Result<()> {
1314 if let Ok(meta) = fs::metadata(path) {
1315 fs::set_permissions(&temp, meta.permissions())?;
1316 }
1317 file.write_all(contents.as_bytes())?;
1318 file.sync_all()
1319 };
1320 match written() {
1321 Ok(()) => Ok(temp),
1322 Err(err) => {
1323 let _ = fs::remove_file(&temp);
1324 Err(err)
1325 }
1326 }
1327}
1328
1329/// Writes `contents` over the file at `path`, keeping the file and so
1330/// every name it has.
1331fn write_in_place(path: &Path, contents: &str) -> io::Result<()> {
1332 let mut file = OpenOptions::new().write(true).truncate(true).open(path)?;
1333 file.write_all(contents.as_bytes())?;
1334 file.sync_all()
1335}
1336
1337#[cfg(test)]
1338mod tests {
1339 use super::*;
1340
1341 const ABOVE: &str = "# Project\n\nRules of our own.\n\n";
1342 const BELOW: &str = "\n## More rules\n\nKept as they are.\n";
1343
1344 fn find(text: &str) -> Result<Option<Range<usize>>, String> {
1345 scan_section(text).map(|scanned| scanned.section)
1346 }
1347
1348 #[test]
1349 fn the_section_names_the_branch_and_holds_no_marker_inside() {
1350 let text = section("trunk");
1351 assert!(text.starts_with(&format!("{START}\n")));
1352 assert!(text.ends_with(&format!("\n{END}\n")));
1353 assert!(text.contains("--track trunk\n"));
1354 assert!(text.contains("land their changes on `trunk`"));
1355 assert!(text.contains("--branch trunk\n"));
1356 assert!(
1357 !text.contains("`main`") && !text.contains(" main"),
1358 "{text}"
1359 );
1360 assert_eq!(named_branch(&text).as_deref(), Some("trunk"));
1361 // The markers appear once each, on their own lines, and the
1362 // section's own code blocks are closed.
1363 assert_eq!(
1364 scan_section(&text),
1365 Ok(Scanned {
1366 section: Some(0..text.len()),
1367 open_fence: None
1368 })
1369 );
1370 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
1371 }
1372
1373 #[test]
1374 fn branches_the_section_can_name_read_back_exactly() {
1375 for good in [
1376 "main",
1377 "master",
1378 "trunk",
1379 "release-1.2",
1380 "feature/x.y_z-1",
1381 "v1.x/beta",
1382 "UPPER_case",
1383 ] {
1384 assert!(is_section_branch(good), "{good}");
1385 assert_eq!(named_branch(&section(good)).as_deref(), Some(good));
1386 }
1387 for bad in [
1388 "",
1389 "feat(x)",
1390 "a;b",
1391 "a;touch${IFS}pwned",
1392 "q$(id)",
1393 "x`id`",
1394 "it's",
1395 "a|b",
1396 "a>b",
1397 "a b",
1398 "-x",
1399 "--no-claude",
1400 "a..b",
1401 "x.lock",
1402 "tags/v1",
1403 "braid/git-map",
1404 "rama-ñ",
1405 ] {
1406 assert!(!is_section_branch(bad), "{bad}");
1407 }
1408 // A section an older braid wrote for a name it cannot hold names
1409 // nothing, rather than a part of it.
1410 let old =
1411 format!("{START}\n<!-- Written by `braid agents init` (branch: feat(x)). -->\n{END}\n");
1412 assert_eq!(named_branch(&old), None);
1413 }
1414
1415 #[test]
1416 fn a_section_is_appended_after_a_blank_line() {
1417 let new = section("main");
1418 assert_eq!(append_section("", &new), new);
1419 assert_eq!(append_section("# Rules", &new), format!("# Rules\n\n{new}"));
1420 assert_eq!(
1421 append_section("# Rules\n", &new),
1422 format!("# Rules\n\n{new}")
1423 );
1424 assert_eq!(
1425 append_section("# Rules\n\n", &new),
1426 format!("# Rules\n\n{new}")
1427 );
1428 // Line ends follow the file's.
1429 let crlf = append_section("# Rules\r\n", &new);
1430 assert_eq!(
1431 crlf,
1432 format!("# Rules\r\n\r\n{}", new.replace('\n', "\r\n"))
1433 );
1434 let range = find(&crlf).unwrap().unwrap();
1435 assert_eq!(replace_section(&crlf, range, &new), crlf);
1436 }
1437
1438 #[test]
1439 fn only_the_text_between_the_markers_changes() {
1440 let old = format!("{START}\nan older section\n{END}\n");
1441 let text = format!("{ABOVE}{old}{BELOW}");
1442 let range = find(&text).unwrap().unwrap();
1443 assert_eq!(&text[range.clone()], old);
1444 let new = replace_section(&text, range, &section("main"));
1445 assert_eq!(new, format!("{ABOVE}{}{BELOW}", section("main")));
1446 // Again: nothing changes.
1447 let range = find(&new).unwrap().unwrap();
1448 assert_eq!(replace_section(&new, range, &section("main")), new);
1449 // The older section named no branch.
1450 assert_eq!(named_branch(&old), None);
1451 }
1452
1453 #[test]
1454 fn markers_may_be_indented_a_little_but_must_be_alone() {
1455 let text = format!(" {START} \nx\n{END}\n");
1456 assert_eq!(find(&text), Ok(Some(0..text.len())));
1457 for not_markers in [
1458 format!(" {START}\n{END}\n"),
1459 format!("see `{START}`\n{END}\n"),
1460 format!("{START} and more\n{END}\n"),
1461 ] {
1462 assert!(find(&not_markers).is_err(), "{not_markers:?}");
1463 }
1464 assert_eq!(find("no markers at all\n"), Ok(None));
1465 }
1466
1467 #[test]
1468 fn markers_in_fenced_code_blocks_are_examples() {
1469 let example = format!("```markdown\n{START}\n(the rules braid writes)\n{END}\n```\n");
1470 let text = format!("# Rules\n\n{example}");
1471 assert_eq!(
1472 scan_section(&text),
1473 Ok(Scanned {
1474 section: None,
1475 open_fence: None
1476 })
1477 );
1478 // Next to a real section, the example is left alone.
1479 let real = section("main");
1480 let both = format!("{text}\n{real}");
1481 let range = find(&both).unwrap().unwrap();
1482 assert_eq!(&both[range], real);
1483 // Tildes, longer fences, and a fence that only a fence as long
1484 // closes.
1485 for fenced in [
1486 format!("~~~\n{START}\n~~~\n"),
1487 format!("````text\n```\n{END}\n````\n"),
1488 format!(" ```\n{START}\n{END}\n ```\n"),
1489 ] {
1490 assert_eq!(find(&fenced), Ok(None), "{fenced:?}");
1491 }
1492 // Four spaces make no fence, and backticks in a backtick fence's
1493 // info string make none either.
1494 assert!(find(&format!(" ```\n{START}\n")).is_err());
1495 assert!(find(&format!("``` a`b\n{START}\n")).is_err());
1496 // A block that is never closed hides what follows it, and says
1497 // where it opens.
1498 let open = format!("# Rules\n\n```bash\nmake test\n{START}\n{END}\n");
1499 assert_eq!(
1500 scan_section(&open),
1501 Ok(Scanned {
1502 section: None,
1503 open_fence: Some(3)
1504 })
1505 );
1506 assert_eq!(open_fence(&open), Some(3));
1507 assert_eq!(open_fence(&text), None);
1508 }
1509
1510 #[test]
1511 fn a_byte_order_mark_before_the_start_marker_stays() {
1512 let section = section("main");
1513 let text = format!("\u{feff}{section}");
1514 let range = find(&text).unwrap().unwrap();
1515 assert_eq!(range, '\u{feff}'.len_utf8()..text.len());
1516 assert_eq!(replace_section(&text, range, &section), text);
1517 assert!(includes_agents("\u{feff}@AGENTS.md\n"));
1518 assert_eq!(
1519 append_section("\u{feff}", &section),
1520 format!("\u{feff}{section}")
1521 );
1522 assert_eq!(
1523 append_section("\u{feff}# Rules\n", &section),
1524 format!("\u{feff}# Rules\n\n{section}")
1525 );
1526 }
1527
1528 #[test]
1529 fn unbalanced_markers_are_refused_with_their_lines() {
1530 let cases = [
1531 (
1532 format!("a\n{START}\nb\n"),
1533 "on line 2, `<!-- braid:end -->` on no line",
1534 ),
1535 (
1536 format!("{END}\n"),
1537 "on no line, `<!-- braid:end -->` on line 1",
1538 ),
1539 (
1540 format!("{END}\n{START}\n"),
1541 "on line 2, `<!-- braid:end -->` on line 1",
1542 ),
1543 (
1544 format!("{START}\n{START}\n{END}\n"),
1545 "on lines 1 and 2, `<!-- braid:end -->` on line 3",
1546 ),
1547 (
1548 format!("{START}\n{END}\n{START}\n{END}\n{END}\n"),
1549 "on lines 1 and 3, `<!-- braid:end -->` on lines 2, 4 and 5",
1550 ),
1551 ];
1552 for (text, said) in cases {
1553 let err = find(&text).unwrap_err();
1554 assert!(err.contains(said), "{text:?}: {err}");
1555 }
1556 }
1557
1558 #[test]
1559 fn claude_md_includes() {
1560 for yes in [
1561 "@AGENTS.md\n",
1562 "# Notes\nSee @AGENTS.md for the rules.\n",
1563 "(@./AGENTS.md)\n",
1564 " @AGENTS.md ",
1565 "```text\nan example\n```\n@AGENTS.md\n",
1566 "Read `this` and @AGENTS.md\n",
1567 ] {
1568 assert!(includes_agents(yes), "{yes:?}");
1569 }
1570 for no in [
1571 "",
1572 "Read AGENTS.md\n",
1573 "`@AGENTS.md`\n",
1574 "@AGENTS.md.bak\n",
1575 "@docs/AGENTS.md\n",
1576 "``see @AGENTS.md here``\n",
1577 "# Claude notes\n\n```text\n@AGENTS.md\n```\n",
1578 "~~~\n@AGENTS.md\n",
1579 ] {
1580 assert!(!includes_agents(no), "{no:?}");
1581 }
1582 assert_eq!(add_include(""), "@AGENTS.md\n");
1583 assert_eq!(add_include("# Claude"), "# Claude\n@AGENTS.md\n");
1584 assert_eq!(add_include("# Claude\n"), "# Claude\n@AGENTS.md\n");
1585 assert_eq!(add_include("# Claude\r\n"), "# Claude\r\n@AGENTS.md\r\n");
1586 assert!(includes_agents(&add_include("# Claude\n")));
1587 }
1588
1589 #[test]
1590 fn code_spans_are_left_out() {
1591 assert_eq!(without_code_spans("a `b` c"), "a c");
1592 assert_eq!(without_code_spans("a ``b ` c`` d"), "a d");
1593 assert_eq!(without_code_spans("a ` b"), "a ` b");
1594 assert_eq!(without_code_spans("é `x` ü"), "é ü");
1595 assert_eq!(without_code_spans("``a` b"), "``a` b");
1596 }
1597}