Elffuss BraidHub

utopia-ia/elffuss-braid public

Agents: cover no remote, no git identity and build output

What a fresh agent ran into when it followed agents.md in a scratch
project, then ran two sessions with a conflict.

- No remote: the setup lists the project's remotes and offers to make
  one where there is none, and the section's finish step says what to do
  when `git remote get-url origin` fails, with the lines that make a bare
  remote next to the project. It is named after the project and made
  with a main branch (git init --bare -b main), so a clone checks it out
  and git prints no hint.
- No identity: a check after the .braid/config line fails while the file
  has no name or email, and the guide says how to set them for the
  checkout and write the file again; the setup's git commit needs them
  too.
- Build output and uncommitted files: files .gitignore does not list are
  changes like any other, .braidignore keeps them out once it lists
  itself too, land refuses while anything is left uncommitted, and
  commit takes paths.
- After a conflict, commit keeps the change's message unless -m gives
  another. The *.sample hooks do not count, untracked files do not
  matter, `git rev-parse --abbrev-ref '@{u}'` tells whether there is an
  upstream, braid refs lists braid's own refs too, and CLAUDE.md is made
  only once the user says yes.
- braid status lists a missing or invalid author first in blocking, in
  text and JSON, exactly when commit would refuse for it: it reads
  --author, BRAID_AUTHOR and .braid/config as commit does, and takes
  --author too.
- workspace list says there are none in text; JSON stays an empty list.
- workspace remove no longer says to commit the files the secrets guard
  holds back: it says to move a secret out, or to track and commit a file
  that is not one. Uncommitted changes count "1 path".
- README, site and llms.txt say the setup offers a remote, and that
  blocking lists a missing author.

Tests: the setup runs as written with and without a git identity; a
session without a remote makes one that sync and a clone use, keeps
build output out, and is held back by what it left uncommitted; status
and commit agree on the author for ten ways of giving one; remove with
held-back files, in the library and the CLI; list with no workspaces;
and every braid command in the guides' code spans exists with its flags,
as in their code blocks.
Changeset4b3dd661f2e57f2168893f9ca2f438fce83576c3da0839e75b557ff7b9ff3de5
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 12:42 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 12:42 +02:00
Parents48132bc26e68

Browse the files at this changeset

14 files changed

modified AGENTS.md +79 −33
@@ -59,32 +59,45 @@
5959 - In a project where braid is not set up, `braid refs` fails with "not
6060 inside a braid repository". Where it lists the project's branches and
6161 `AGENTS.md` has a braid section (a `<!-- braid:start -->` line), braid is
62- set up: skip to "Every agent session, from then on".
62+ set up: skip to "Every agent session, from then on". It lists braid's own
63+ refs too: `braid/git-map`, the project's tags as `tags/<name>`, and once
64+ a sync has run, `remote/<label>/<branch>`.
6365
6466 ### Set up a project
6567
6668 First read the project's `AGENTS.md`, `CLAUDE.md` and the like for rules
6769 about git: branches, pull requests, how to commit. Look too for what braid
6870 does not run: git hooks (in `.git/hooks`, or where
69-`git config core.hooksPath` says), Git LFS (`filter=lfs` in
71+`git config core.hooksPath` says; the `*.sample` files git puts in
72+`.git/hooks` never run, and do not count), Git LFS (`filter=lfs` in
7073 `.gitattributes`: braid sees the pointer files, not the content) and a main
71-branch that takes changes only through pull requests. Tell the user what
72-you found, and if any of it clashes with agents landing on the main
73-branch, ask how to go on before you set anything up.
74+branch that takes changes only through pull requests. Then list the
75+project's git remotes (`git remote -v`): what agents land reaches the
76+user's checkout through one, which the commands here call `origin`; if it
77+has another name, write that instead. Tell the user what you found, and
78+if any of it clashes with agents landing on the main branch, ask how to
79+go on before you set anything up. With no remote at all, what agents land
80+stays in braid: offer to make one (see "No remote?" below). And if the
81+project has no `CLAUDE.md`, ask whether to add one, since Claude Code
82+reads `CLAUDE.md` rather than `AGENTS.md`: with a yes, run
83+`touch CLAUDE.md` before the commands below, and `braid agents init` makes
84+it include `AGENTS.md`.
7485
7586 Then work in the root of the project's git checkout, on its main branch,
76-with nothing to commit (`git status`) and nothing new to pull
77-(`git pull --ff-only`; skip it when the branch has no upstream). In a
78-shallow clone, run `git fetch --unshallow` first: braid imports the whole
79-history. The commands say `main`; if the project's main branch has another
80-name, such as `master`, write that instead. Every line is safe to run
81-again, so after a failure, start again from the top.
87+with nothing to commit (`git status` shows no staged or modified files;
88+untracked files do not matter) and nothing new to pull
89+(`git pull --ff-only`; skip it when the branch has no upstream, which is
90+when `git rev-parse --abbrev-ref '@{u}'` fails). In a shallow clone, run
91+`git fetch --unshallow` first: braid imports the whole history. The
92+commands say `main`; if the project's main branch has another name, such
93+as `master`, write that instead. Every line is safe to run again, so after
94+a failure, start again from the top.
8295
8396 ```bash
8497 test -d .braid || braid init # .braid/: the store and the agents' workspaces
8598 grep -qsxF .braid "$(git rev-parse --git-path info/exclude)" || echo .braid >> "$(git rev-parse --git-path info/exclude)"
8699 test -f .braid/config || printf 'name = %s\nemail = %s\n' "$(git config user.name)" "$(git config user.email)" > .braid/config
87-touch CLAUDE.md # for Claude Code, which reads CLAUDE.md, not AGENTS.md
100+grep -q '^name = .' .braid/config && grep -q '^email = .' .braid/config # fails without a name and an email
88101 braid git import . # the project's whole history: every local branch and tag
89102 braid agents init # the rules for agents, in AGENTS.md
90103 ```
@@ -93,16 +106,27 @@
93106 only in this one: braid's directory, and the `.braid` file that marks
94107 each workspace, so that nothing of braid's is ever committed with git.
95108 - `.braid/config` names who signs the changesets agents make, here the
96- same person as git's commits. If git has no `user.name` or `user.email`,
97- write them into it by hand; otherwise every session has to set
98- `BRAID_AUTHOR`.
109+ same person as git's commits. The line after it fails, with exit status
110+ 1 and nothing printed, while the file lacks a name or an email, as it
111+ does when git has no `user.name` or `user.email`: every commit and
112+ landing would then fail with "no author", and the `git commit` below
113+ would fail too, or sign with a name and an address that git guesses
114+ from the machine. Ask the user for the name and the e-mail address to
115+ use. With their answer, set them for this checkout, and let the setup
116+ write the file anew:
117+
118+ ```bash
119+ git config user.name "<name>"
120+ git config user.email "<email>"
121+ rm .braid/config # then start again from the top
122+ ```
123+
99124 - Most harnesses read `AGENTS.md`. Claude Code reads `CLAUDE.md` instead,
100125 and Gemini CLI `GEMINI.md`: `braid agents init` adds the line
101126 `@AGENTS.md` to each of them that exists, so that they read the section
102- too. A `CLAUDE.md` that holds only that line is harmless; leave out the
103- `touch` line if the user does not want one. In Claude Code, each braid
104- command asks for permission unless the project allows it: offer to add
105- `"Bash(braid:*)"` to `permissions.allow` in `.claude/settings.json`.
127+ too. In Claude Code, each braid command asks for permission unless the
128+ project allows it: offer to add `"Bash(braid:*)"` to `permissions.allow`
129+ in `.claude/settings.json`.
106130 - `braid agents init` writes a section into `AGENTS.md`, creating the file
107131 if there is none, between a `<!-- braid:start -->` line and a
108132 `<!-- braid:end -->` line. The section tells every agent session to work
@@ -188,12 +212,21 @@
188212 ```
189213
190214 There is no staging area: `commit` records every change in the
191- workspace, so read `braid status` before each commit. Only `.gitignore`
192- and `.braidignore` apply in a workspace, not `.git/info/exclude` or a
193- global excludes file: list files that must stay local in `.braidignore`.
194- Braid runs no git hooks, so run the project's checks yourself before you
195- land. `land` puts the workspace's changesets on `main`, as a
196- fast-forward or rebased onto whatever landed first.
215+ workspace, or only the paths it is given
216+ (`braid --agent agent-1 commit -m "..." <path>...`), so read
217+ `braid status` before each commit. `land` refuses while anything is left
218+ uncommitted ("the workspace has uncommitted changes ...; commit them
219+ first"). Building or running the project writes files too: those that
220+ `.gitignore` does not list are new files like any other. Delete them, or
221+ list them in `.braidignore`, which must then list itself too, or it is a
222+ new file to commit: for Python's `__pycache__/`, run
223+ `printf '%s\n' .braidignore __pycache__/ >> .braidignore` in the
224+ workspace's root. Only `.gitignore` and `.braidignore` apply in a
225+ workspace, not `.git/info/exclude` or a global excludes file: anything
226+ else that must stay local goes in `.braidignore` too. Braid runs no git
227+ hooks, so run the project's checks yourself before you land. `land` puts
228+ the workspace's changesets on `main`, as a fast-forward or rebased onto
229+ whatever landed first.
197230 - **Before a new task**, `braid --agent agent-1 update` brings the
198231 workspace onto `main`. `status --json` says how far behind it is
199232 (`behind_by`).
@@ -201,7 +234,10 @@
201234 The user's checkout and the git remote get it with `braid git sync`, then
202235 `git pull --ff-only`, both from the project root (see "Keeping the git
203236 remote up to date"). The session tells the user so, and offers to run
204- them: when to sync is the user's call.
237+ them: when to sync is the user's call. Where `git remote get-url origin`
238+ fails, the project has no remote of that name: the session asks the
239+ user which of those `git remote` lists to sync with, or, where it lists
240+ none, says so and offers to make one first (see "No remote?").
205241 - **Done**: once everything has landed, `braid workspace remove agent-1`
206242 from the project root. It refuses while the workspace holds work that
207243 has not landed.
@@ -210,7 +246,11 @@
210246 standard output, even with `--json`; only `git sync` and `fsck` print
211247 their report as well when they exit with 1.
212248 - Changesets are signed by `BRAID_AUTHOR` (`"Name <email>"`), or else by
213- the `name` and `email` in `.braid/config`.
249+ the `name` and `email` in `.braid/config`. With neither, `commit`,
250+ `land` and `update` fail with "no author", and `braid status` lists it
251+ first among what stops a commit: the session asks the user who signs,
252+ and writes the answer into `.braid/config` as `name = <name>` and
253+ `email = <email>` lines.
214254 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
215255 than 1 MiB are held back until `braid track <path>`: `commit` refuses,
216256 naming them, and `--force` leaves them out. Never `braid track` a secret:
@@ -229,7 +269,7 @@
229269 ```bash
230270 braid --agent agent-1 update # exit status 2: conflict markers in the files
231271 # edit the files until no marker is left; `braid status` lists what still blocks
232-braid --agent agent-1 commit # keeps the change's message
272+braid --agent agent-1 commit # keeps the change's message; -m gives another
233273 braid --agent agent-1 land --json
234274 ```
235275
@@ -292,11 +332,17 @@
292332 parents to tell what a workspace has landed, so the workspaces carry on
293333 from the merge.
294334
295-No remote? Any bare repository will do. In the shared checkout,
296-`git init --bare ../project.git`, then
297-`git remote add origin "$(cd .. && pwd)/project.git"` (an absolute path,
298-which braid reads the same from any directory) and
299-`git push -u origin main`.
335+No remote? Any bare repository will do. With the user's yes, these lines,
336+run in the shared checkout, make one next to the project, named after it
337+(`../<project>.git`, by an absolute path, which braid reads the same from
338+any directory), and push the main branch to it. If something has that
339+name already, choose another.
340+
341+```bash
342+git init --bare -b main "$PWD.git"
343+git remote add origin "$PWD.git"
344+git push -u origin main
345+```
300346
301347 ### Undoing
302348
modified README.md +5 −3
@@ -113,8 +113,9 @@
113113 ```
114114
115115 It installs braid with cargo, tells you what in the project braid does not
116-run, such as git hooks, imports the project's git history, and writes the
117-rules for agents into the project's `AGENTS.md` with `braid agents init`.
116+run, such as git hooks, offers to make a git remote if the project has
117+none, imports the project's git history, and writes the rules for agents
118+into the project's `AGENTS.md` with `braid agents init`.
118119 From then on, every agent session works in a braid workspace of its own,
119120 where git refuses to run, lands through braid, and tells you when what it
120121 landed is waiting for a sync to the git remote. Git stays the source of
@@ -203,7 +204,8 @@
203204 - `braid status --json` says how far the branch is ahead (`behind_by`), which
204205 changesets have not landed, including one whose rebase is in progress, and
205206 whether a commit would go through (`ready_to_commit`), with every reason
206- it would not (`blocking`), which `braid commit` refuses with too.
207+ it would not (`blocking`), a missing author among them, which
208+ `braid commit` refuses with too.
207209 - Every changeset names the agent that made it, and keeps it when it is
208210 rebased; `braid log`, `braid show` and `braid op log` show who did what,
209211 and the op log says what each landing did. Signatures use the local time
modified crates/cli/src/agents.rs +35 −13
@@ -696,19 +696,27 @@
696696 `braid cat-object <base>:<path> | diff -u - <path>`. To undo it, write
697697 the base's version back with `braid cat-object <base>:<path> > <path>`,
698698 or delete a file you added.
699-- **Before each commit**, read `braid status`. There is no staging area:
700- `commit` records every change in the workspace, and only `.gitignore` and
701- `.braidignore` apply there, not `.git/info/exclude` or a global excludes
702- file, so list files that must stay local in `.braidignore`. Braid runs no
703- git hooks: run the project's checks yourself before you land.
699+- **Before each commit**, read `braid status`: it lists what `commit` would
700+ record, and what would stop it. There is no staging area: `commit`
701+ records every change in the workspace, or only the paths it is given
702+ (`commit -m \"...\" <path>...`), and `land` refuses while anything is left
703+ uncommitted. Building or running the project writes files too: those
704+ `.gitignore` does not list are new files like any other. Delete them, or
705+ list them in `.braidignore`, which must then list itself too, or it is a
706+ new file to commit: for Python's `__pycache__/`, run
707+ `printf '%s\\n' .braidignore __pycache__/ >> .braidignore` in the
708+ workspace's root. Only `.gitignore` and `.braidignore` apply in a
709+ workspace, not `.git/info/exclude` or a global excludes file. Braid runs
710+ no git hooks: run the project's checks yourself before you land.
704711 - **Conflicts:** `land` and `update` exit with status 2, the `outcome` in
705712 their JSON is `conflicts`, and `{branch}` does not move. After `land`, run
706713 `braid --agent agent-1 update`, which writes conflict markers into the
707714 files; fix them (`braid resolve <path>` settles conflicts that are not
708- about content), then `commit` (the message is kept) and `land` again. In
709- the JSON, `next` says what to run. Never `commit --force` during a
710- rebase: it would commit the markers. Any other failure exits with status
711- 1, and braid prints it as text on standard error, even with `--json`.
715+ about content), then `commit`, which keeps the change's message unless
716+ `-m` gives another, and `land` again. In the JSON, `next` says what to
717+ run. Never `commit --force` during a rebase: it would commit the markers.
718+ Any other failure exits with status 1, and braid prints it as text on
719+ standard error, even with `--json`.
712720 - **Before a new task**, `braid --agent agent-1 update` brings your
713721 workspace onto `{branch}`.
714722 - **When you finish**, tell the user that what you landed is on braid's
@@ -720,11 +728,25 @@
720728 git pull --ff-only
721729 ```
722730
723- Offer to run it: when to sync is the user's call. Once everything has
724- landed, `braid workspace remove agent-1`, from the project root, removes
725- your workspace.
731+ Offer to run it: when to sync is the user's call. Where
732+ `git remote get-url origin` fails, the project has no remote of that
733+ name: if `git remote` lists others, ask the user which to sync with, and
734+ write its name in place of `origin`; if it lists none, say so, and offer
735+ to make one next to the project first, from the project root:
736+
737+ ```bash
738+ git init --bare -b {branch} \"$PWD.git\"
739+ git remote add origin \"$PWD.git\"
740+ git push -u origin {branch}
741+ ```
742+
743+ Once everything has landed, `braid workspace remove agent-1`, from the
744+ project root, removes your workspace.
726745 - Changesets are signed by `BRAID_AUTHOR` (`\"Name <email>\"`), or else by the
727- `name` and `email` in `.braid/config`.
746+ `name` and `email` in `.braid/config`. With neither, `commit`, `land` and
747+ `update` fail with \"no author\", and `status` lists it first among what
748+ stops a commit: ask the user who signs, and write the answer into
749+ `.braid/config` as `name = <name>` and `email = <email>` lines.
728750 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
729751 than 1 MiB wait for `braid track <path>`. Never track a secret: move it
730752 out of the workspace.
modified crates/cli/src/main.rs +2 −2
@@ -240,7 +240,7 @@
240240 },
241241 /// Show how the workspace differs from its base and its branch.
242242 #[command(long_about = work::STATUS_HELP)]
243- Status,
243+ Status(work::IdentityArgs),
244244 /// Record the workspace's changes as a changeset on its base.
245245 Commit(work::CommitArgs),
246246 /// Land the workspace's changesets on its branch (exit status 2 on
@@ -390,7 +390,7 @@
390390 Command::Fsck => fsck(cli),
391391 Command::Stats => stats(cli),
392392 Command::Workspace { action } => work::workspace(cli, action),
393- Command::Status => work::status(cli),
393+ Command::Status(args) => work::status(cli, args),
394394 Command::Commit(args) => work::commit(cli, args),
395395 Command::Land(args) => work::land(cli, args),
396396 Command::Update(args) => work::update(cli, args),
modified crates/cli/src/work.rs +35 −12
@@ -100,11 +100,14 @@
100100 there are changes, or a rebase to finish, and nothing
101101 blocks it
102102 blocking why `braid commit` would refuse, each {reason, path,
103- message}: markers (conflict markers remain in the file),
104- unresolved (a conflict that is not about content, not
105- marked resolved with `braid resolve`), both with the
106- conflict's kind, or needs_track; commit refuses with the
107- same list, unless --force
103+ message}: author (no one valid to sign changesets, from
104+ --author, BRAID_AUTHOR or .braid/config, which status
105+ reads as commit does; path is null), markers (conflict
106+ markers remain in the file), unresolved (a conflict that
107+ is not about content, not marked resolved with `braid
108+ resolve`), both with the conflict's kind, or needs_track.
109+ Commit refuses for author first, on its own, and for the
110+ others with the same list, unless --force
108111 rebase null, or the rebase in progress: change (the changeset
109112 being rebased), onto, pending (those waiting after it),
110113 and conflicts, each {path, kind, markers, markers_remain,
@@ -194,8 +197,8 @@
194197 Remove {
195198 /// The workspace's name.
196199 name: String,
197- /// Remove it even with uncommitted changes, unlanded changesets or
198- /// a rebase in progress.
200+ /// Remove it even with uncommitted changes, new files the secrets
201+ /// guard holds back, unlanded changesets or a rebase in progress.
199202 #[arg(long)]
200203 force: bool,
201204 },
@@ -453,6 +456,11 @@
453456 })
454457 .collect();
455458 print_json(&Value::Array(items))?;
459+ } else if all.is_empty() {
460+ println!(
461+ "No workspaces yet: `{}` makes one in .braid/work/<name>.",
462+ cli.hint("workspace add <name>")
463+ );
456464 } else {
457465 for (name, state) in &all {
458466 println!(
@@ -482,12 +490,20 @@
482490 Ok(ExitCode::SUCCESS)
483491 }
484492
485-pub(crate) fn status(cli: &Cli) -> Result<ExitCode> {
493+pub(crate) fn status(cli: &Cli, args: &IdentityArgs) -> Result<ExitCode> {
486494 let target = Target::find(cli)?;
487495 let workspace = target.open()?;
488496 let report = workspace.status()?;
489497 let state = &report.state;
490498 let status = &report.status;
499+ // Commit reads who signs before anything else, and refuses without
500+ // someone valid; land and update need them too. Status reads them the
501+ // same way, from the same flag, environment and config, so that it
502+ // lists that refusal exactly when commit would make it.
503+ let author = identity(args, &target.repo)
504+ .err()
505+ .map(|err| format!("{err:#}"));
506+ let ready_to_commit = author.is_none() && report.ready_to_commit();
491507 if cli.json {
492508 let by_kind = |kind: braid_wc::ChangeKind| -> Vec<String> {
493509 status
@@ -534,8 +550,12 @@
534550 "deleted": by_kind(braid_wc::ChangeKind::Deleted),
535551 "typechanged": by_kind(braid_wc::ChangeKind::TypeChanged),
536552 "needs_track": status.needs_track.iter().map(|p| show(p)).collect::<Vec<_>>(),
537- "ready_to_commit": report.ready_to_commit(),
538- "blocking": report.blocking.iter().map(blocker_json).collect::<Vec<_>>(),
553+ "ready_to_commit": ready_to_commit,
554+ "blocking": author
555+ .iter()
556+ .map(|message| json!({ "reason": "author", "path": null, "message": message }))
557+ .chain(report.blocking.iter().map(blocker_json))
558+ .collect::<Vec<_>>(),
539559 "rebase": rebase,
540560 }))?;
541561 return Ok(ExitCode::SUCCESS);
@@ -612,12 +632,15 @@
612632 writeln!(out, " {}", show(path))?;
613633 }
614634 }
615- if !report.blocking.is_empty() {
635+ if author.is_some() || !report.blocking.is_empty() {
616636 writeln!(out, "Not ready to commit:")?;
637+ if let Some(message) = &author {
638+ writeln!(out, " - {message}")?;
639+ }
617640 for blocker in &report.blocking {
618641 writeln!(out, " - {blocker}")?;
619642 }
620- } else if report.ready_to_commit() {
643+ } else if ready_to_commit {
621644 writeln!(out, "Ready to commit.")?;
622645 }
623646 Ok(ExitCode::SUCCESS)
modified crates/cli/tests/guides.rs +297 −12
@@ -7,8 +7,11 @@
77 //! and every braid command they give must exist, with every flag it is
88 //! given.
99
10-use std::path::Path;
11-use std::process::Command;
10+use std::fs;
11+use std::path::{Path, PathBuf};
12+use std::process::{Command, Output};
13+
14+use serde_json::Value;
1215
1316 const START: &str = "<!-- braid:start -->";
1417 const END: &str = "<!-- braid:end -->";
@@ -85,19 +88,116 @@
8588 /// The lines of the ```bash blocks of a Markdown text, without their
8689 /// indentation.
8790 fn bash_lines(text: &str) -> Vec<String> {
88- let mut lines = Vec::new();
91+ bash_blocks(text).concat()
92+}
93+
94+/// The ```bash blocks of a Markdown text, each as its lines without their
95+/// indentation.
96+fn bash_blocks(text: &str) -> Vec<Vec<String>> {
97+ let mut blocks = Vec::new();
8998 let mut inside = false;
9099 for line in text.lines() {
91100 let line = line.trim();
92101 if line.starts_with("```") {
93102 inside = !inside && line == "```bash";
103+ if inside {
104+ blocks.push(Vec::new());
105+ }
94106 continue;
95107 }
96- if inside {
97- lines.push(line.to_owned());
108+ if inside && let Some(block) = blocks.last_mut() {
109+ block.push(line.to_owned());
98110 }
99111 }
100- lines
112+ blocks
113+}
114+
115+/// The ```bash block of `text` with a line that starts with `first`.
116+fn block_with(text: &str, first: &str) -> Vec<String> {
117+ bash_blocks(text)
118+ .into_iter()
119+ .find(|block| block.iter().any(|line| line.starts_with(first)))
120+ .unwrap_or_else(|| panic!("no block with {first:?}"))
121+}
122+
123+/// Runs `line` in a new POSIX shell in `dir`, as a harness that keeps
124+/// nothing between commands runs it: with this build's braid first on
125+/// `PATH`, no braid variables, and git reading only `config` (no system
126+/// configuration).
127+fn shell(dir: &Path, config: &Path, line: &str) -> Output {
128+ let bin = Path::new(env!("CARGO_BIN_EXE_braid")).parent().unwrap();
129+ let path = std::env::join_paths(std::iter::once(bin.to_path_buf()).chain(
130+ std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()),
131+ ))
132+ .unwrap();
133+ Command::new("sh")
134+ .arg("-c")
135+ .arg(line)
136+ .current_dir(dir)
137+ .env("PATH", path)
138+ .env("GIT_CONFIG_GLOBAL", config)
139+ .env("GIT_CONFIG_NOSYSTEM", "1")
140+ .env_remove("BRAID_AUTHOR")
141+ .env_remove("BRAID_AGENT")
142+ // The shell sets it from the directory it starts in.
143+ .env_remove("PWD")
144+ .output()
145+ .unwrap()
146+}
147+
148+/// Runs `line` as [`shell`] does, expecting success.
149+fn shell_ok(dir: &Path, config: &Path, line: &str) -> String {
150+ let out = shell(dir, config, line);
151+ assert!(
152+ out.status.success(),
153+ "{line}: {}{}",
154+ String::from_utf8_lossy(&out.stdout),
155+ String::from_utf8_lossy(&out.stderr)
156+ );
157+ String::from_utf8(out.stdout).unwrap()
158+}
159+
160+/// A git project in `dir`, on `main`, with one commit of `notes.txt`, and
161+/// a git configuration of its own that gives `identity` as git's user, or
162+/// none.
163+fn git_project(dir: &Path, identity: Option<(&str, &str)>) -> PathBuf {
164+ fs::create_dir_all(dir).unwrap();
165+ let config = dir.with_extension("gitconfig");
166+ let user = identity.map_or_else(String::new, |(name, email)| {
167+ format!("[user]\n\tname = {name}\n\temail = {email}\n")
168+ });
169+ fs::write(&config, user).unwrap();
170+ fs::write(dir.join("notes.txt"), "one\ntwo\n").unwrap();
171+ for line in [
172+ "git init -q -b main",
173+ "git add notes.txt",
174+ "git -c user.name=Ada -c user.email=ada@example.org commit -q -m First",
175+ ] {
176+ shell_ok(dir, &config, line);
177+ }
178+ config
179+}
180+
181+/// The text of the file at `path` in `dir`.
182+fn read(dir: &Path, path: &str) -> String {
183+ fs::read_to_string(dir.join(path)).unwrap_or_else(|err| panic!("{path}: {err}"))
184+}
185+
186+/// What `braid status --json` says in the workspace at `dir`, with no
187+/// author from the environment.
188+fn status(dir: &Path) -> Value {
189+ let out = Command::new(env!("CARGO_BIN_EXE_braid"))
190+ .current_dir(dir)
191+ .args(["status", "--json"])
192+ .env_remove("BRAID_AUTHOR")
193+ .output()
194+ .unwrap();
195+ assert!(
196+ out.status.success(),
197+ "{}",
198+ String::from_utf8_lossy(&out.stderr)
199+ );
200+ serde_json::from_slice(&out.stdout).unwrap()
101201 }
102202
103203 #[test]
@@ -149,20 +249,48 @@
149249 braid(Path::new("."), &["agents", "init", "--help"]);
150250 }
151251
252+/// The code spans of a Markdown text outside its fenced blocks, such as
253+/// `braid status`, wherever their lines break.
254+fn code_spans(text: &str) -> Vec<String> {
255+ let mut prose = Vec::new();
256+ let mut fenced = false;
257+ for line in text.lines() {
258+ if line.trim().starts_with("```") {
259+ fenced = !fenced;
260+ } else if !fenced {
261+ prose.push(line.trim());
262+ }
263+ }
264+ let prose = prose.join(" ");
265+ assert!(
266+ !prose.contains("``"),
267+ "a code span of more than one backtick"
268+ );
269+ prose
270+ .split('`')
271+ .skip(1)
272+ .step_by(2)
273+ .map(str::to_owned)
274+ .collect()
275+}
276+
152277 #[test]
153278 fn every_braid_command_in_the_guides_exists_with_its_flags() {
154- let mut lines: Vec<String> = bash_lines(&part_one());
155- lines.extend(bash_lines(&section()));
156- // A line may run braid after another command: `test -d .braid || braid
157- // init`.
279+ let mut lines: Vec<String> = Vec::new();
280+ for text in [part_one(), section()] {
281+ lines.extend(bash_lines(&text));
282+ lines.extend(code_spans(&text));
283+ }
284+ // A line may run braid after another command, `test -d .braid || braid
285+ // init`, or pipe it into one, `braid cat-object <base>:<path> | diff`.
158286 let commands: Vec<String> = lines
159287 .iter()
160- .flat_map(|line| line.split("||").flat_map(|part| part.split("&&")))
288+ .flat_map(|line| line.split('|').flat_map(|part| part.split("&&")))
161289 .map(str::trim)
162290 .filter(|command| command.starts_with("braid "))
163291 .map(str::to_owned)
164292 .collect();
165- assert!(commands.len() >= 15, "{commands:?}");
293+ assert!(commands.len() >= 40, "{commands:?}");
166294 let groups = ["agents", "change", "git", "op", "ref", "workspace"];
167295 for command in &commands {
168296 let words: Vec<&str> = command
@@ -208,3 +336,160 @@
208336 }
209337 }
210338 }
339+
340+#[test]
341+fn the_setup_stops_at_its_check_until_braid_has_a_name_and_an_email() {
342+ let setup = block_with(&part_one(), "test -d .braid || braid init");
343+ let check = setup
344+ .iter()
345+ .position(|line| line.starts_with("grep -q '^name = .' .braid/config"))
346+ .expect("the setup checks the name and the email it wrote");
347+ for identity in [Some(("Ada Lovelace", "ada@example.org")), None] {
348+ let temp = tempfile::tempdir().unwrap();
349+ let dir = fs::canonicalize(temp.path()).unwrap().join("project");
350+ let config = git_project(&dir, identity);
351+ // Each line in a shell of its own, as written: only the check fails
352+ // where git has no identity, and nothing says why but the guide.
353+ let run = || -> Vec<Option<i32>> {
354+ setup
355+ .iter()
356+ .map(|line| shell(&dir, &config, line).status.code())
357+ .collect()
358+ };
359+ let failing = |index: usize| Some(i32::from(identity.is_none() && index == check));
360+ assert_eq!(run(), (0..setup.len()).map(failing).collect::<Vec<_>>());
361+ assert!(read(&dir, "AGENTS.md").contains(START));
362+ let commit = block_with(&part_one(), "git add AGENTS.md");
363+ let written = read(&dir, ".braid/config");
364+ let Some((name, email)) = identity else {
365+ assert_eq!(written, "name = \nemail = \n");
366+ // Every commit and landing would fail: a session's status says
367+ // so first.
368+ shell_ok(&dir, &config, "braid workspace add agent-1 --track main");
369+ let workspace = dir.join(".braid/work/agent-1");
370+ assert_eq!(status(&workspace)["blocking"][0]["reason"], "author");
371+ // Fixed as the guide says, the setup runs again from the top
372+ // without a failure, and git's commit is signed as braid's
373+ // changesets are, not as git would guess.
374+ for line in block_with(&part_one(), "git config user.name") {
375+ let line = line
376+ .replace("<name>", "Grace Hopper")
377+ .replace("<email>", "grace@example.org");
378+ shell_ok(&dir, &config, &line);
379+ }
380+ assert!(run().iter().all(|code| *code == Some(0)));
381+ assert_eq!(
382+ read(&dir, ".braid/config"),
383+ "name = Grace Hopper\nemail = grace@example.org\n"
384+ );
385+ assert_eq!(status(&workspace)["blocking"], serde_json::json!([]));
386+ for line in &commit {
387+ shell_ok(&dir, &config, line);
388+ }
389+ assert_eq!(
390+ shell_ok(&dir, &config, "git log -1 --format='%an <%ae>'"),
391+ "Grace Hopper <grace@example.org>\n"
392+ );
393+ continue;
394+ };
395+ assert_eq!(written, format!("name = {name}\nemail = {email}\n"));
396+ for line in &commit {
397+ shell_ok(&dir, &config, line);
398+ }
399+ // Running it again changes nothing.
400+ assert!(run().iter().all(|code| *code == Some(0)));
401+ assert_eq!(read(&dir, ".braid/config"), written);
402+ }
403+}
404+
405+/// The line the guides give to keep Python's build output out of a
406+/// workspace, `.braidignore` included.
407+const BRAIDIGNORE: &str = "printf '%s\\n' .braidignore __pycache__/ >> .braidignore";
408+
409+#[test]
410+fn a_session_without_a_remote_makes_one_that_sync_and_clones_use() {
411+ let temp = tempfile::tempdir().unwrap();
412+ let parent = fs::canonicalize(temp.path()).unwrap();
413+ let dir = parent.join("project");
414+ let config = git_project(&dir, Some(("Ada Lovelace", "ada@example.org")));
415+ for line in block_with(&part_one(), "test -d .braid || braid init") {
416+ shell_ok(&dir, &config, &line);
417+ }
418+ let section = section();
419+ let sync = block_with(&section, "braid --agent agent-1 git sync");
420+ let recipe = block_with(&section, "git init --bare");
421+ // The guide gives the same lines for a project with no remote.
422+ let guide = bash_lines(&part_one());
423+ for line in &recipe {
424+ assert!(guide.contains(line), "the guide has no {line:?}");
425+ }
426+ for text in [part_one(), section.clone()] {
427+ assert!(code_spans(&text).iter().any(|span| span == BRAIDIGNORE));
428+ }
429+
430+ // A session lands a change, with build output kept out of it, and
431+ // what is left uncommitted holding the landing back.
432+ shell_ok(&dir, &config, "braid workspace add agent-1 --track main");
433+ let workspace = dir.join(".braid/work/agent-1");
434+ fs::write(workspace.join("app.py"), "print('hi')\n").unwrap();
435+ fs::create_dir(workspace.join("__pycache__")).unwrap();
436+ fs::write(workspace.join("__pycache__/app.cpython.pyc"), [0u8, 1]).unwrap();
437+ let before = status(&workspace)["added"].clone();
438+ assert_eq!(
439+ before,
440+ serde_json::json!(["__pycache__/app.cpython.pyc", "app.py"])
441+ );
442+ shell_ok(&workspace, &config, BRAIDIGNORE);
443+ assert_eq!(status(&workspace)["added"], serde_json::json!(["app.py"]));
444+ fs::write(workspace.join("notes.txt"), "one\ntwo, the agent's\n").unwrap();
445+ let session = "braid --agent agent-1";
446+ shell_ok(
447+ &workspace,
448+ &config,
449+ &format!("{session} commit -m 'Add app.py' app.py"),
450+ );
451+ let held = shell(&workspace, &config, &format!("{session} land"));
452+ assert_eq!(held.status.code(), Some(1));
453+ let said = String::from_utf8_lossy(&held.stderr);
454+ assert!(
455+ said.contains("uncommitted changes (1 path, \"notes.txt\")"),
456+ "{said}"
457+ );
458+ shell_ok(
459+ &workspace,
460+ &config,
461+ &format!("{session} commit -m 'Edit notes'"),
462+ );
463+ shell_ok(&workspace, &config, &format!("{session} land"));
464+
465+ // The sync fails without a remote, as the section says; the recipe makes
466+ // one next to the project, and the sync then reaches it and the shared
467+ // checkout.
468+ assert!(!shell(&dir, &config, &sync[0]).status.success());
469+ for line in &recipe {
470+ let out = shell(&dir, &config, line);
471+ assert!(out.status.success(), "{line}: {:?}", out);
472+ let said = String::from_utf8_lossy(&out.stderr);
473+ assert!(!said.contains("hint:"), "{line}: {said}");
474+ }
475+ let bare = parent.join("project.git");
476+ assert_eq!(
477+ shell_ok(&dir, &config, "git remote get-url origin"),
478+ format!("{}\n", bare.display())
479+ );
480+ assert_eq!(
481+ shell_ok(&bare, &config, "git symbolic-ref HEAD"),
482+ "refs/heads/main\n"
483+ );
484+ for line in &sync {
485+ shell_ok(&dir, &config, line);
486+ }
487+ assert_eq!(read(&dir, "app.py"), "print('hi')\n");
488+ assert_eq!(read(&dir, "notes.txt"), "one\ntwo, the agent's\n");
489+ // A clone of the new remote checks out its main.
490+ shell_ok(&parent, &config, "git clone -q project.git clone");
491+ assert_eq!(read(&parent.join("clone"), "app.py"), "print('hi')\n");
492+ for kept_out in ["__pycache__", ".braidignore", ".braid"] {
493+ assert!(!parent.join("clone").join(kept_out).exists(), "{kept_out}");
494+ }
495+}
modified crates/cli/tests/workspaces.rs +164 −0
@@ -818,6 +818,170 @@
818818 write(&other, "scratch.txt", "x\n");
819819 json(&repo.root, &["workspace", "remove", "other", "--force"]);
820820 assert!(!other.exists());
821+
822+ // With none left, the list says so in text, and is empty in JSON.
823+ let out = braid(&repo.root, &["workspace", "list"]);
824+ assert!(out.status.success(), "{}", stderr(&out));
825+ let text = String::from_utf8(out.stdout).unwrap();
826+ assert!(text.starts_with("No workspaces yet: "), "{text}");
827+ assert!(text.contains("`braid workspace add <name>`"), "{text}");
828+ assert_eq!(
829+ json(&repo.root, &["workspace", "list"]),
830+ serde_json::json!([])
831+ );
832+ repo.workspace("again");
833+ let out = braid(&repo.root, &["workspace", "list"]);
834+ let text = String::from_utf8(out.stdout).unwrap();
835+ assert!(text.starts_with("again main "), "{text}");
836+}
837+
838+#[test]
839+fn removing_a_workspace_never_says_to_commit_a_secret() {
840+ let repo = Repo::new();
841+ seed(&repo, &[("README.md", "hello\n")]);
842+ let ws = repo.workspace("ws");
843+ write(&ws, ".env", "TOKEN=secret\n");
844+ let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
845+ assert!(
846+ refused.contains("a new file the secrets guard holds back, \".env\""),
847+ "{refused}"
848+ );
849+ assert!(
850+ refused.contains("move it out of the workspace"),
851+ "{refused}"
852+ );
853+ assert!(!refused.contains("commit them first"), "{refused}");
854+ // Changes to commit come first, counted on their own.
855+ write(&ws, "notes.txt", "notes\n");
856+ let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
857+ assert!(
858+ refused.contains("uncommitted changes (1 path, \"notes.txt\"); commit them first"),
859+ "{refused}"
860+ );
861+ std::fs::remove_file(ws.join("notes.txt")).unwrap();
862+ // Moved out, the secret no longer holds the workspace.
863+ std::fs::rename(ws.join(".env"), repo.root.parent().unwrap().join(".env")).unwrap();
864+ json(&repo.root, &["workspace", "remove", "ws"]);
865+ assert!(!ws.exists());
866+}
867+
868+/// Runs braid in `dir` with no author from the environment unless
869+/// `author` gives one, and returns its exit status, standard output and
870+/// standard error.
871+fn signed(dir: &Path, author: Option<&str>, args: &[&str]) -> (i32, String, String) {
872+ let mut command = Command::new(env!("CARGO_BIN_EXE_braid"));
873+ command
874+ .current_dir(dir)
875+ .args(args)
876+ .env_remove("BRAID_AUTHOR")
877+ .env("BRAID_AGENT", "tester");
878+ if let Some(author) = author {
879+ command.env("BRAID_AUTHOR", author);
880+ }
881+ let out = command.output().unwrap();
882+ (
883+ out.status.code().unwrap_or(-1),
884+ String::from_utf8(out.stdout).unwrap(),
885+ String::from_utf8(out.stderr).unwrap(),
886+ )
887+}
888+
889+#[test]
890+fn status_lists_a_missing_author_exactly_when_commit_refuses_for_it() {
891+ const ADA: &str = "Ada <ada@example.org>";
892+ const GRACE: &str = "name = Grace\nemail = grace@example.org\n";
893+ // What the setup in agents.md writes where git has no identity.
894+ const EMPTY: &str = "name = \nemail = \n";
895+ // Where the author comes from (BRAID_AUTHOR, --author and
896+ // .braid/config), and whether commit has one it can use.
897+ let cases = [
898+ (None, None, None, false),
899+ (Some(ADA), None, None, true),
900+ (None, Some(ADA), None, true),
901+ (Some("Ada"), None, None, false),
902+ (None, Some("Ada <a> b"), None, false),
903+ (None, None, Some(GRACE), true),
904+ (None, None, Some(EMPTY), false),
905+ (None, None, Some("name = Grace\n"), false),
906+ (Some("Ada"), None, Some(GRACE), false),
907+ (Some(ADA), None, Some(EMPTY), true),
908+ ];
909+ for (env, flag, config, can_sign) in cases {
910+ let case = format!("BRAID_AUTHOR {env:?}, --author {flag:?}, config {config:?}");
911+ let repo = Repo::new();
912+ seed(&repo, &[("README.md", "hello\n")]);
913+ let ws = repo.workspace("ws");
914+ if let Some(config) = config {
915+ std::fs::write(repo.root.join(".braid/config"), config).unwrap();
916+ }
917+ let with_flag = |args: &[&str]| -> Vec<String> {
918+ let mut all: Vec<String> = args.iter().map(|arg| arg.to_string()).collect();
919+ if let Some(flag) = flag {
920+ all.extend(["--author".to_owned(), flag.to_owned()]);
921+ }
922+ all
923+ };
924+ let run = |args: &[&str]| {
925+ let all = with_flag(args);
926+ let all: Vec<&str> = all.iter().map(String::as_str).collect();
927+ signed(&ws, env, &all)
928+ };
929+
930+ // Clean, then with a change: the author blocks a commit either way.
931+ for dirty in [false, true] {
932+ if dirty {
933+ write(&ws, "notes.txt", "notes\n");
934+ }
935+ let (code, out, err) = run(&["status", "--json"]);
936+ assert_eq!(code, 0, "{case}: {err}");
937+ let now: Value = serde_json::from_str(&out).unwrap();
938+ let author: Vec<&Value> = now["blocking"]
939+ .as_array()
940+ .unwrap()
941+ .iter()
942+ .filter(|blocker| blocker["reason"] == "author")
943+ .collect();
944+ assert_eq!(author.len(), usize::from(!can_sign), "{case}: {out}");
945+ assert_eq!(now["ready_to_commit"], dirty && can_sign, "{case}: {out}");
946+ let (code, text, _) = run(&["status"]);
947+ assert_eq!(code, 0, "{case}");
948+ assert_eq!(
949+ text.contains("Ready to commit."),
950+ dirty && can_sign,
951+ "{case}: {text}"
952+ );
953+ assert_eq!(
954+ text.contains("Not ready to commit:"),
955+ !can_sign,
956+ "{case}: {text}"
957+ );
958+
959+ let (code, _, err) = run(&["commit", "-m", "notes"]);
960+ if can_sign {
961+ assert!(author.is_empty());
962+ if dirty {
963+ assert_eq!(code, 0, "{case}: {err}");
964+ } else {
965+ assert_eq!(code, 1, "{case}");
966+ assert_eq!(err, "braid: error: nothing to commit\n", "{case}");
967+ }
968+ } else {
969+ // Commit refuses with the very reason status gave, before
970+ // looking for anything to commit.
971+ assert_eq!(code, 1, "{case}");
972+ let reason = author[0]["message"].as_str().unwrap();
973+ assert_eq!(author[0]["path"], Value::Null, "{case}");
974+ assert_eq!(err, format!("braid: error: {reason}\n"), "{case}");
975+ assert!(text.contains(&format!(" - {reason}\n")), "{case}: {text}");
976+ // Landing and updating need someone to sign as too.
977+ for command in ["land", "update"] {
978+ let (code, _, refused) = run(&[command]);
979+ assert_eq!(code, 1, "{case}: {command}");
980+ assert_eq!(refused, err, "{case}: {command}");
981+ }
982+ }
983+ }
984+ }
821985 }
822986
823987 #[test]
modified crates/wc/src/error.rs +36 −1
@@ -103,7 +103,7 @@
103103 },
104104
105105 /// The workspace has changes that are not committed.
106- #[error("the workspace has uncommitted changes ({count} paths, starting with {:?}); commit them first", show(.first))]
106+ #[error("the workspace has uncommitted changes ({}); commit them first", some_paths(*.count, .first))]
107107 Uncommitted {
108108 /// How many paths changed.
109109 count: usize,
@@ -111,6 +111,17 @@
111111 first: Vec<u8>,
112112 },
113113
114+ /// The workspace holds new files that the secrets guard holds back,
115+ /// which removing it would delete. They are not uncommitted changes to
116+ /// commit: any of them may be a secret.
117+ #[error("{}", held_back(*.count, .first))]
118+ HeldBack {
119+ /// How many there are.
120+ count: usize,
121+ /// The first of them.
122+ first: Vec<u8>,
123+ },
124+
114125 /// The command needs the rebase in progress to be finished first.
115126 #[error("a rebase is in progress: resolve the conflicts and run `braid commit` first")]
116127 RebaseInProgress,
@@ -225,6 +236,30 @@
225236 }
226237 }
227238
239+/// `1 path, "a"`, or `3 paths, starting with "a"`.
240+fn some_paths(count: usize, first: &[u8]) -> String {
241+ match count {
242+ 1 => format!("1 path, {:?}", show(first)),
243+ n => format!("{n} paths, starting with {:?}", show(first)),
244+ }
245+}
246+
247+/// Why a workspace that holds files the secrets guard holds back is not
248+/// removed, and what to do: never to commit them as they are, since any of
249+/// them may be a secret.
250+fn held_back(count: usize, first: &[u8]) -> String {
251+ let first = show(first);
252+ if count == 1 {
253+ format!(
254+ "the workspace holds a new file the secrets guard holds back, {first:?}, which removing the workspace would delete: move it out of the workspace if it is a secret, or `braid track` and commit it if it is not; --force removes the workspace with it"
255+ )
256+ } else {
257+ format!(
258+ "the workspace holds {count} new files the secrets guard holds back, starting with {first:?}, which removing the workspace would delete: move the secrets among them out of the workspace, and `braid track` and commit the files that are not secrets; --force removes the workspace with them"
259+ )
260+ }
261+}
262+
228263 /// How many reasons a refusal lists, at most.
229264 const REASONS_SHOWN: usize = 20;
230265
modified crates/wc/src/workspace.rs +16 −13
@@ -516,10 +516,11 @@
516516 }
517517
518518 /// Removes the workspace named `name`: its directory and its state.
519- /// Refused while it has uncommitted changes, files waiting for `braid
520- /// track`, changesets the branch does not have, or a rebase in progress,
521- /// unless `force`. The directory is removed only if its `.braid` file
522- /// still names this workspace of this repository.
519+ /// Refused while it has uncommitted changes ([`Error::Uncommitted`]),
520+ /// new files the secrets guard holds back ([`Error::HeldBack`]),
521+ /// changesets the branch does not have, or a rebase in progress, unless
522+ /// `force`. The directory is removed only if its `.braid` file still
523+ /// names this workspace of this repository.
523524 pub fn remove(repo: &Repo, name: &str, force: bool) -> Result<(), Error> {
524525 let workspace = Workspace::open(repo, name)?;
525526 let lock = Lock::acquire(&workspace.state_dir)?;
@@ -532,16 +533,18 @@
532533 if owned {
533534 let root = Root::open(&state.path)?;
534535 let status = workspace.scan_status(&root, &state)?;
535- let dirty: Vec<&Vec<u8>> = status
536- .changes
537- .iter()
538- .map(|change| &change.path)
539- .chain(&status.needs_track)
540- .collect();
541- if let Some(first) = dirty.first() {
536+ if let Some(first) = status.changes.first() {
542537 return Err(Error::Uncommitted {
543- count: dirty.len(),
544- first: first.to_vec(),
538+ count: status.changes.len(),
539+ first: first.path.clone(),
540+ });
541+ }
542+ // Files the guard holds back are not changes to commit:
543+ // any of them may be a secret.
544+ if let Some(first) = status.needs_track.first() {
545+ return Err(Error::HeldBack {
546+ count: status.needs_track.len(),
547+ first: first.clone(),
545548 });
546549 }
547550 }
modified crates/wc/tests/workspaces.rs +50 −0
@@ -478,6 +478,56 @@
478478 assert_eq!(ws.land(None, "t", &ada()).unwrap().landed, Landed::Nothing);
479479 }
480480
481+#[test]
482+fn removal_never_says_to_commit_what_the_guard_holds_back() {
483+ let f = Fixture::new();
484+ let first = f.commit(&[], vec![("README.md", f.file("hello\n"))]);
485+ f.set_branch("main", first);
486+ let dir = f.path("ws");
487+ Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap();
488+ fs::write(dir.join(".env"), "TOKEN=secret\n").unwrap();
489+
490+ // A file the guard holds back is not a change to commit: it may be a
491+ // secret, which removing the workspace would delete.
492+ let refused = Workspace::remove(&f.repo, "ws", false).unwrap_err();
493+ assert!(
494+ matches!(&refused, Error::HeldBack { count: 1, first } if first == b".env"),
495+ "{refused:?}"
496+ );
497+ let said = refused.to_string();
498+ assert!(
499+ said.contains("secrets guard holds back, \".env\""),
500+ "{said}"
501+ );
502+ assert!(said.contains("move it out of the workspace"), "{said}");
503+ assert!(!said.contains("commit them"), "{said}");
504+ fs::write(dir.join("id_rsa"), "private\n").unwrap();
505+ let said = Workspace::remove(&f.repo, "ws", false)
506+ .unwrap_err()
507+ .to_string();
508+ assert!(said.contains("2 new files"), "{said}");
509+ assert!(!said.contains("commit them"), "{said}");
510+
511+ // Changes come first, and only they count as uncommitted.
512+ fs::write(dir.join("notes.txt"), "notes\n").unwrap();
513+ let refused = Workspace::remove(&f.repo, "ws", false).unwrap_err();
514+ assert!(
515+ matches!(&refused, Error::Uncommitted { count: 1, first } if first == b"notes.txt"),
516+ "{refused:?}"
517+ );
518+ assert!(
519+ refused
520+ .to_string()
521+ .contains("uncommitted changes (1 path, \"notes.txt\")"),
522+ "{refused}"
523+ );
524+ assert!(dir.join(".env").exists());
525+
526+ // --force removes the workspace with them.
527+ Workspace::remove(&f.repo, "ws", true).unwrap();
528+ assert!(!dir.exists());
529+}
530+
481531 #[cfg(unix)]
482532 #[test]
483533 fn a_commit_of_some_paths_reads_only_those() {
modified docs/design.md +10 −6
@@ -289,11 +289,14 @@
289289 - `braid commit` records the working copy as a changeset on the base. It
290290 refuses while something blocks it, listing every reason at once: conflict
291291 markers left in a file, a conflict that is not about content and not marked
292- resolved, a new file waiting for `braid track`. `braid status` lists the
293- same reasons as `blocking`, with `ready_to_commit`; it also counts how far
294- the branch's head is ahead of the workspace along first parents, stopping
295- after 5000 changesets, and lists the changesets that have not landed,
296- including those of a rebase in progress.
292+ resolved, a new file waiting for `braid track`. Before any of them it needs
293+ someone to sign as, from `--author`, `BRAID_AUTHOR` or `.braid/config`, as
294+ `land` and `update` do. `braid status` lists the same reasons as
295+ `blocking`, with `ready_to_commit`, and a missing or invalid author first,
296+ read the same way; it also counts how far the branch's head is ahead of
297+ the workspace along first parents, stopping after 5000 changesets, and
298+ lists the changesets that have not landed, including those of a rebase in
299+ progress.
297300 - `braid land` puts the workspace's changesets on its branch in one op log
298301 transaction: the engine fast-forwards or rebases them onto the head, and the
299302 branch moves with a compare-and-swap. The working copy then follows, writing
@@ -387,7 +390,8 @@
387390 shared checkout and the git remote get it from `braid git sync` and
388391 `git pull --ff-only`. The section has a session that finishes say so to
389392 the user, and offer to run them, rather than leave the user looking at
390- files that did not change.
393+ files that did not change; where the project has no git remote, it says
394+ so, and offers to make a bare one next to the project first.
391395
392396 ## Git bridge
393397
modified site/agents.md +79 −33
@@ -59,32 +59,45 @@
5959 - In a project where braid is not set up, `braid refs` fails with "not
6060 inside a braid repository". Where it lists the project's branches and
6161 `AGENTS.md` has a braid section (a `<!-- braid:start -->` line), braid is
62- set up: skip to "Every agent session, from then on".
62+ set up: skip to "Every agent session, from then on". It lists braid's own
63+ refs too: `braid/git-map`, the project's tags as `tags/<name>`, and once
64+ a sync has run, `remote/<label>/<branch>`.
6365
6466 ## Set up a project
6567
6668 First read the project's `AGENTS.md`, `CLAUDE.md` and the like for rules
6769 about git: branches, pull requests, how to commit. Look too for what braid
6870 does not run: git hooks (in `.git/hooks`, or where
69-`git config core.hooksPath` says), Git LFS (`filter=lfs` in
71+`git config core.hooksPath` says; the `*.sample` files git puts in
72+`.git/hooks` never run, and do not count), Git LFS (`filter=lfs` in
7073 `.gitattributes`: braid sees the pointer files, not the content) and a main
71-branch that takes changes only through pull requests. Tell the user what
72-you found, and if any of it clashes with agents landing on the main
73-branch, ask how to go on before you set anything up.
74+branch that takes changes only through pull requests. Then list the
75+project's git remotes (`git remote -v`): what agents land reaches the
76+user's checkout through one, which the commands here call `origin`; if it
77+has another name, write that instead. Tell the user what you found, and
78+if any of it clashes with agents landing on the main branch, ask how to
79+go on before you set anything up. With no remote at all, what agents land
80+stays in braid: offer to make one (see "No remote?" below). And if the
81+project has no `CLAUDE.md`, ask whether to add one, since Claude Code
82+reads `CLAUDE.md` rather than `AGENTS.md`: with a yes, run
83+`touch CLAUDE.md` before the commands below, and `braid agents init` makes
84+it include `AGENTS.md`.
7485
7586 Then work in the root of the project's git checkout, on its main branch,
76-with nothing to commit (`git status`) and nothing new to pull
77-(`git pull --ff-only`; skip it when the branch has no upstream). In a
78-shallow clone, run `git fetch --unshallow` first: braid imports the whole
79-history. The commands say `main`; if the project's main branch has another
80-name, such as `master`, write that instead. Every line is safe to run
81-again, so after a failure, start again from the top.
87+with nothing to commit (`git status` shows no staged or modified files;
88+untracked files do not matter) and nothing new to pull
89+(`git pull --ff-only`; skip it when the branch has no upstream, which is
90+when `git rev-parse --abbrev-ref '@{u}'` fails). In a shallow clone, run
91+`git fetch --unshallow` first: braid imports the whole history. The
92+commands say `main`; if the project's main branch has another name, such
93+as `master`, write that instead. Every line is safe to run again, so after
94+a failure, start again from the top.
8295
8396 ```bash
8497 test -d .braid || braid init # .braid/: the store and the agents' workspaces
8598 grep -qsxF .braid "$(git rev-parse --git-path info/exclude)" || echo .braid >> "$(git rev-parse --git-path info/exclude)"
8699 test -f .braid/config || printf 'name = %s\nemail = %s\n' "$(git config user.name)" "$(git config user.email)" > .braid/config
87-touch CLAUDE.md # for Claude Code, which reads CLAUDE.md, not AGENTS.md
100+grep -q '^name = .' .braid/config && grep -q '^email = .' .braid/config # fails without a name and an email
88101 braid git import . # the project's whole history: every local branch and tag
89102 braid agents init # the rules for agents, in AGENTS.md
90103 ```
@@ -93,16 +106,27 @@
93106 only in this one: braid's directory, and the `.braid` file that marks
94107 each workspace, so that nothing of braid's is ever committed with git.
95108 - `.braid/config` names who signs the changesets agents make, here the
96- same person as git's commits. If git has no `user.name` or `user.email`,
97- write them into it by hand; otherwise every session has to set
98- `BRAID_AUTHOR`.
109+ same person as git's commits. The line after it fails, with exit status
110+ 1 and nothing printed, while the file lacks a name or an email, as it
111+ does when git has no `user.name` or `user.email`: every commit and
112+ landing would then fail with "no author", and the `git commit` below
113+ would fail too, or sign with a name and an address that git guesses
114+ from the machine. Ask the user for the name and the e-mail address to
115+ use. With their answer, set them for this checkout, and let the setup
116+ write the file anew:
117+
118+ ```bash
119+ git config user.name "<name>"
120+ git config user.email "<email>"
121+ rm .braid/config # then start again from the top
122+ ```
123+
99124 - Most harnesses read `AGENTS.md`. Claude Code reads `CLAUDE.md` instead,
100125 and Gemini CLI `GEMINI.md`: `braid agents init` adds the line
101126 `@AGENTS.md` to each of them that exists, so that they read the section
102- too. A `CLAUDE.md` that holds only that line is harmless; leave out the
103- `touch` line if the user does not want one. In Claude Code, each braid
104- command asks for permission unless the project allows it: offer to add
105- `"Bash(braid:*)"` to `permissions.allow` in `.claude/settings.json`.
127+ too. In Claude Code, each braid command asks for permission unless the
128+ project allows it: offer to add `"Bash(braid:*)"` to `permissions.allow`
129+ in `.claude/settings.json`.
106130 - `braid agents init` writes a section into `AGENTS.md`, creating the file
107131 if there is none, between a `<!-- braid:start -->` line and a
108132 `<!-- braid:end -->` line. The section tells every agent session to work
@@ -188,12 +212,21 @@
188212 ```
189213
190214 There is no staging area: `commit` records every change in the
191- workspace, so read `braid status` before each commit. Only `.gitignore`
192- and `.braidignore` apply in a workspace, not `.git/info/exclude` or a
193- global excludes file: list files that must stay local in `.braidignore`.
194- Braid runs no git hooks, so run the project's checks yourself before you
195- land. `land` puts the workspace's changesets on `main`, as a
196- fast-forward or rebased onto whatever landed first.
215+ workspace, or only the paths it is given
216+ (`braid --agent agent-1 commit -m "..." <path>...`), so read
217+ `braid status` before each commit. `land` refuses while anything is left
218+ uncommitted ("the workspace has uncommitted changes ...; commit them
219+ first"). Building or running the project writes files too: those that
220+ `.gitignore` does not list are new files like any other. Delete them, or
221+ list them in `.braidignore`, which must then list itself too, or it is a
222+ new file to commit: for Python's `__pycache__/`, run
223+ `printf '%s\n' .braidignore __pycache__/ >> .braidignore` in the
224+ workspace's root. Only `.gitignore` and `.braidignore` apply in a
225+ workspace, not `.git/info/exclude` or a global excludes file: anything
226+ else that must stay local goes in `.braidignore` too. Braid runs no git
227+ hooks, so run the project's checks yourself before you land. `land` puts
228+ the workspace's changesets on `main`, as a fast-forward or rebased onto
229+ whatever landed first.
197230 - **Before a new task**, `braid --agent agent-1 update` brings the
198231 workspace onto `main`. `status --json` says how far behind it is
199232 (`behind_by`).
@@ -201,7 +234,10 @@
201234 The user's checkout and the git remote get it with `braid git sync`, then
202235 `git pull --ff-only`, both from the project root (see "Keeping the git
203236 remote up to date"). The session tells the user so, and offers to run
204- them: when to sync is the user's call.
237+ them: when to sync is the user's call. Where `git remote get-url origin`
238+ fails, the project has no remote of that name: the session asks the
239+ user which of those `git remote` lists to sync with, or, where it lists
240+ none, says so and offers to make one first (see "No remote?").
205241 - **Done**: once everything has landed, `braid workspace remove agent-1`
206242 from the project root. It refuses while the workspace holds work that
207243 has not landed.
@@ -210,7 +246,11 @@
210246 standard output, even with `--json`; only `git sync` and `fsck` print
211247 their report as well when they exit with 1.
212248 - Changesets are signed by `BRAID_AUTHOR` (`"Name <email>"`), or else by
213- the `name` and `email` in `.braid/config`.
249+ the `name` and `email` in `.braid/config`. With neither, `commit`,
250+ `land` and `update` fail with "no author", and `braid status` lists it
251+ first among what stops a commit: the session asks the user who signs,
252+ and writes the answer into `.braid/config` as `name = <name>` and
253+ `email = <email>` lines.
214254 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
215255 than 1 MiB are held back until `braid track <path>`: `commit` refuses,
216256 naming them, and `--force` leaves them out. Never `braid track` a secret:
@@ -229,7 +269,7 @@
229269 ```bash
230270 braid --agent agent-1 update # exit status 2: conflict markers in the files
231271 # edit the files until no marker is left; `braid status` lists what still blocks
232-braid --agent agent-1 commit # keeps the change's message
272+braid --agent agent-1 commit # keeps the change's message; -m gives another
233273 braid --agent agent-1 land --json
234274 ```
235275
@@ -292,11 +332,17 @@
292332 parents to tell what a workspace has landed, so the workspaces carry on
293333 from the merge.
294334
295-No remote? Any bare repository will do. In the shared checkout,
296-`git init --bare ../project.git`, then
297-`git remote add origin "$(cd .. && pwd)/project.git"` (an absolute path,
298-which braid reads the same from any directory) and
299-`git push -u origin main`.
335+No remote? Any bare repository will do. With the user's yes, these lines,
336+run in the shared checkout, make one next to the project, named after it
337+(`../<project>.git`, by an absolute path, which braid reads the same from
338+any directory), and push the main branch to it. If something has that
339+name already, choose another.
340+
341+```bash
342+git init --bare -b main "$PWD.git"
343+git remote add origin "$PWD.git"
344+git push -u origin main
345+```
300346
301347 ## Undoing
302348
modified site/index.html +4 −4
@@ -414,8 +414,8 @@
414414 <div class="code-bar"><span>petición</span><button class="copy" type="button" aria-label="Copiar la petición" data-aria-en="Copy the prompt" data-aria-es="Copiar la petición" hidden><span class="c-idle" data-l="en" lang="en">Copy</span><span class="c-idle" data-l="es" lang="es">Copiar</span><span class="c-done" data-l="en" lang="en">Copied</span><span class="c-done" data-l="es" lang="es">Copiado</span></button></div>
415415 <pre tabindex="0" role="region" aria-label="La petición para tu agente" data-aria-en="The prompt for your agent" data-aria-es="La petición para tu agente"><code>Instala braid en este proyecto y configúralo para agentes siguiendo https://braid.elffuss.com/agents.md (léelo entero, con curl -fsSL)</code></pre>
416416 </div>
417-<p data-l="en" lang="en">Your agent installs braid with cargo, tells you what in the project braid does not run, such as git hooks, imports the project's git history, and writes the rules for agents into its <code>AGENTS.md</code> with <code>braid agents init</code>. From then on, every agent session works in a braid workspace of its own, where git refuses to run, lands through braid, and tells you when what it landed is waiting for a sync to the git remote. Git stays the source of truth, and in a clone where braid is not set up, agents work with git as before.</p>
418-<p data-l="es" lang="es">Tu agente instala braid con cargo, te avisa de lo que braid no ejecuta en el proyecto, como los hooks de git, importa su historia de git y, con <code>braid agents init</code>, escribe en su <code>AGENTS.md</code> las reglas para los agentes. A partir de ahí, cada sesión trabaja en su propio espacio de trabajo, donde git se niega a funcionar, aterriza sus cambios con braid y te avisa cuando lo que ha aterrizado está pendiente de sincronizar con el remoto de git. Git sigue siendo la fuente de verdad, y en un clon donde braid no está configurado los agentes trabajan con git, como siempre.</p>
417+<p data-l="en" lang="en">Your agent installs braid with cargo, tells you what in the project braid does not run, such as git hooks, offers to make a git remote if the project has none, imports the project's git history, and writes the rules for agents into its <code>AGENTS.md</code> with <code>braid agents init</code>. From then on, every agent session works in a braid workspace of its own, where git refuses to run, lands through braid, and tells you when what it landed is waiting for a sync to the git remote. Git stays the source of truth, and in a clone where braid is not set up, agents work with git as before.</p>
418+<p data-l="es" lang="es">Tu agente instala braid con cargo, te avisa de lo que braid no ejecuta en el proyecto, como los hooks de git, se ofrece a crearle un remoto de git si no tiene ninguno, importa su historia de git y, con <code>braid agents init</code>, escribe en su <code>AGENTS.md</code> las reglas para los agentes. A partir de ahí, cada sesión trabaja en su propio espacio de trabajo, donde git se niega a funcionar, aterriza sus cambios con braid y te avisa cuando lo que ha aterrizado está pendiente de sincronizar con el remoto de git. Git sigue siendo la fuente de verdad, y en un clon donde braid no está configurado los agentes trabajan con git, como siempre.</p>
419419 <p class="note" data-l="en" lang="en">The instructions are <a href="agents.md">agents.md</a>, part 1 of the repository's <a href="https://github.com/KikoCis/elffuss-braid/blob/main/AGENTS.md"><code>AGENTS.md</code></a>; there is an <a href="llms.txt">llms.txt</a> too. To do it by hand, follow the same steps in <a href="agents.md">agents.md</a>; the quick start below tries braid on its own repository.</p>
420420 <p class="note" data-l="es" lang="es">Las instrucciones son <a href="agents.md">agents.md</a>, la primera parte del <a href="https://github.com/KikoCis/elffuss-braid/blob/main/AGENTS.md"><code>AGENTS.md</code></a> del repositorio, en inglés; también hay un <a href="llms.txt">llms.txt</a>. Para hacerlo a mano, sigue los mismos pasos de <a href="agents.md">agents.md</a>; los primeros pasos, justo debajo, prueban braid con su propio repositorio.</p>
421421 </div>
@@ -506,8 +506,8 @@
506506 <p data-l="en" lang="en"><code>0</code> done, <code>1</code> failed, <code>2</code> conflicts (the branch did not move), or a command line braid could not parse; with <code class="nw">--json</code>, the <code>outcome</code> is <code>conflicts</code> only for a conflict. A failure is printed as text on standard error.</p>
507507 <p data-l="es" lang="es"><code>0</code> hecho, <code>1</code> fallo, <code>2</code> conflictos (la rama no se movió) o un comando que braid no sabe interpretar; con <code class="nw">--json</code>, solo en un conflicto el <code>outcome</code> vale <code>conflicts</code>. Un fallo se imprime como texto en la salida de error.</p></li>
508508 <li><h4><span data-l="en" lang="en">Status</span><span data-l="es" lang="es">Estado</span></h4>
509-<p data-l="en" lang="en"><code>braid status <span class="nw">--json</span></code> gives <code>behind_by</code>, <code>unlanded</code>, <code>ready_to_commit</code> and <code>blocking</code>, which lists the same reasons <code>braid commit</code> refuses with.</p>
510-<p data-l="es" lang="es"><code>braid status <span class="nw">--json</span></code> da <code>behind_by</code>, <code>unlanded</code>, <code>ready_to_commit</code> y <code>blocking</code>, que lista los mismos motivos por los que <code>braid commit</code> se niega.</p></li>
509+<p data-l="en" lang="en"><code>braid status <span class="nw">--json</span></code> gives <code>behind_by</code>, <code>unlanded</code>, <code>ready_to_commit</code> and <code>blocking</code>, which lists the same reasons <code>braid commit</code> refuses with, a missing author among them.</p>
510+<p data-l="es" lang="es"><code>braid status <span class="nw">--json</span></code> da <code>behind_by</code>, <code>unlanded</code>, <code>ready_to_commit</code> y <code>blocking</code>, que lista los mismos motivos por los que <code>braid commit</code> se niega, entre ellos que no haya autor.</p></li>
511511 <li><h4><span data-l="en" lang="en">Secrets guard</span><span data-l="es" lang="es">Guarda de secretos</span></h4>
512512 <p data-l="en" lang="en">New <code>.env*</code>, <code>*.pem</code> and <code>id_*</code> files, and files over 1&nbsp;MiB, wait for <code>braid track</code>. <code class="nw">--force</code> leaves them out.</p>
513513 <p data-l="es" lang="es">Los ficheros nuevos <code>.env*</code>, <code>*.pem</code> e <code>id_*</code>, y los de más de 1&nbsp;MiB, esperan a <code>braid track</code>. <code class="nw">--force</code> los deja fuera.</p></li>
modified site/llms.txt +1 −1
@@ -8,7 +8,7 @@
88
99 ## Docs
1010
11-- [Install braid and set it up for agents](https://braid.elffuss.com/agents.md): for coding agents, to read whole. Installing with cargo, setting up a git project with `braid agents init`, each session's workspace (where git does not run), conflicts, keeping the git remote in step, undoing, and what not to do.
11+- [Install braid and set it up for agents](https://braid.elffuss.com/agents.md): for coding agents, to read whole. Installing with cargo, setting up a git project with `braid agents init`, each session's workspace (where git does not run), conflicts, keeping the git remote in step, or making one where there is none, undoing, and what not to do.
1212 - [README](https://raw.githubusercontent.com/KikoCis/elffuss-braid/main/README.md): what braid is, the quick start, working with git, status and roadmap, and ratios against git.
1313 - [Design](https://raw.githubusercontent.com/KikoCis/elffuss-braid/main/docs/design.md): the store, landing, history, workspaces, the git bridge and sync, and how it is tested.
1414 - [Format v1](https://raw.githubusercontent.com/KikoCis/elffuss-braid/main/docs/spec/format-v1.md): the exact bytes of ids, trees and changesets, with golden vectors.