Elffuss BraidHub

utopia-ia/elffuss-braid public

Agents: install the braid the guide describes, keep git out of workspaces

Fixes from the review of braid agents init and the guide for agents.

- Version 0.0.2, and the guide installs the tag v0.0.2, so the version
  check tells an older braid, without agents init, from this one. The
  site's checklist pushes the commits and the tag before agents.md is
  served, and a test ties the tag to the version.
- Every workspace holds a .git file that points nowhere: git run in it
  stops with "not a git repository" instead of stashing, resetting or
  committing in the shared checkout. braid cat-object REV:PATH prints a
  file as a changeset has it, to review or undo an edit.
- workspace add puts a workspace in .braid/work/<name> by default, and
  refuses a branch the repository does not have, unless it has none yet
  or --new-branch asks for one. The error outside a workspace points at
  --workspace and .braid/work.
- agents init names a branch the repository has: one the section named
  before the import is chosen again, --branch must exist, and with no
  repository or branch yet it asks for --branch. Names are limited to
  what a shell reads as written, and read back exactly.
- agents init ignores markers in fenced code blocks, keeps a byte order
  mark, refuses links out of the project and files that are not regular,
  are read-only or have other hard links, in dry runs too; writes every
  file or none; reports the path written; honours --workspace and --repo;
  and bridges GEMINI.md as it does CLAUDE.md.
- Hints and next repeat the --repo, --agent and --workspace typed.
- The section: only where braid is set up; no git in a workspace; read
  status before each commit; run the project's checks; no --force in a
  rebase; tell the user that what landed reaches their checkout and the
  remote with git sync and git pull, from the project root.
- The guide: what installing needs, a setup safe to run again with a
  guarded commit, a look for hooks, LFS and protected branches first,
  CLAUDE.md by default, an absolute path for a local remote, and every
  check of part 2.
- The prompt asks for agents.md whole; README, site and llms.txt follow,
  and the site's Spanish reads as written, not translated.
Changeset2dd40509e7e2946fdf85f47ac0eabbba833e1582dfa9f2ba721f3b0fa4c131ea
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 10:42 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 10:42 +02:00
Parents68c0144475c3

Browse the files at this changeset

22 files changed

modified AGENTS.md +193 −81
@@ -16,101 +16,170 @@
1616
1717 ## 1. Installing braid and setting it up in a project
1818
19+Read this part whole before you run anything, and run its commands exactly
20+as they are written.
21+
1922 ### Install
2023
21-Braid builds from source with cargo. It needs Rust 1.89 or newer (from
22-<https://rustup.rs>) and git.
24+Braid builds from source with cargo. It needs:
25+
26+- Rust 1.89 or newer (`rustc --version` says which; <https://rustup.rs>
27+ installs it), a C compiler (`cc`), git, and a POSIX shell such as bash:
28+ every command here is written for one.
29+- Linux, macOS or another Unix-like system. Windows is not tested yet: use
30+ WSL there.
31+- The network, and permission to write in cargo's directory, `~/.cargo`.
32+ A sandboxed harness blocks both by default: ask the user to allow them,
33+ or to run the command themselves.
2334
2435 ```bash
25-cargo install --locked --git https://github.com/KikoCis/elffuss-braid elffuss-braid-cli
36+cargo install --locked --git https://github.com/KikoCis/elffuss-braid --tag v0.0.2 elffuss-braid-cli
2637 ```
2738
28-This puts a `braid` binary in cargo's bin directory, `~/.cargo/bin` unless
29-`CARGO_HOME` says otherwise, which must be on `PATH`. Running the same
30-command again upgrades it.
39+It compiles braid and its dependencies from source, which takes a while:
40+give the command a long timeout, or run it in the background, since a
41+command cut short starts again from the beginning. It puts a `braid` binary
42+in cargo's bin directory, `~/.cargo/bin` unless `CARGO_HOME` says
43+otherwise. If that directory is not on `PATH`, call braid as
44+`"$HOME/.cargo/bin/braid"` wherever this file says `braid`: a harness may
45+not keep a changed `PATH` from one command to the next. Running the same
46+command again replaces an older braid with this version.
3147
3248 ### Is it installed, and set up here?
3349
3450 ```bash
35-braid --version # prints "braid" and its version once it is installed
51+braid --version # "braid 0.0.2", or newer, once it is installed
3652 braid refs # in the project root: its branches, once it is set up
3753 ```
3854
39-Before it is installed, `braid --version` fails with "command not found"
40-(or cargo's bin directory is not on `PATH`). In a project where braid is
41-not set up, `braid refs` fails with "not inside a braid repository".
55+- Before braid is installed, `braid --version` fails with "command not
56+ found", as it does while cargo's bin directory is not on `PATH`. An older
57+ braid, or one that says `agents` is not a subcommand, needs the install
58+ command again.
59+- In a project where braid is not set up, `braid refs` fails with "not
60+ inside a braid repository". Where it lists the project's branches and
61+ `AGENTS.md` has a braid section (a `<!-- braid:start -->` line), braid is
62+ set up: skip to "Every agent session, from then on".
4263
4364 ### Set up a project
4465
45-Do this once, in the root of the project's git checkout: on its main
46-branch, with nothing to commit (`git status`) and nothing new to pull
47-(`git pull --ff-only`). The commands say `main`; if the project's main
48-branch has another name, such as `master`, write that instead.
66+First read the project's `AGENTS.md`, `CLAUDE.md` and the like for rules
67+about git: branches, pull requests, how to commit. Look too for what braid
68+does not run: git hooks (in `.git/hooks`, or where
69+`git config core.hooksPath` says), Git LFS (`filter=lfs` in
70+`.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+
75+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.
4982
5083 ```bash
51-braid init # creates .braid/, for the store and the agents' workspaces
52-echo '/.braid/' >> "$(git rev-parse --git-path info/exclude)"
53-printf 'name = %s\nemail = %s\n' "$(git config user.name)" "$(git config user.email)" > .braid/config
84+test -d .braid || braid init # .braid/: the store and the agents' workspaces
85+grep -qsxF .braid "$(git rev-parse --git-path info/exclude)" || echo .braid >> "$(git rev-parse --git-path info/exclude)"
86+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
5488 braid git import . # the project's whole history: every local branch and tag
5589 braid agents init # the rules for agents, in AGENTS.md
5690 ```
5791
58-- The second line makes git ignore `.braid/` in this checkout only, so that
59- nothing of braid's is ever committed with git.
92+- The second line makes git ignore every `.braid` in this checkout, and
93+ only in this one: braid's directory, and the `.braid` file that marks
94+ each workspace, so that nothing of braid's is ever committed with git.
6095 - `.braid/config` names who signs the changesets agents make, here the
6196 same person as git's commits. If git has no `user.name` or `user.email`,
62- write them in by hand; otherwise every session has to set `BRAID_AUTHOR`.
97+ write them into it by hand; otherwise every session has to set
98+ `BRAID_AUTHOR`.
99+- Most harnesses read `AGENTS.md`. Claude Code reads `CLAUDE.md` instead,
100+ and Gemini CLI `GEMINI.md`: `braid agents init` adds the line
101+ `@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`.
63106 - `braid agents init` writes a section into `AGENTS.md`, creating the file
64107 if there is none, between a `<!-- braid:start -->` line and a
65108 `<!-- braid:end -->` line. The section tells every agent session to work
66109 in a workspace of its own and to land through braid, and names the branch
67- agents land on: `main`, `master`, or the project's only branch.
68- `--branch <name>` names another, and `--dry-run` shows what it would
69- write. Text outside the markers is never touched, and running it again
70- rewrites the section in place.
71-- If the project has a `CLAUDE.md`, `braid agents init` adds the line
72- `@AGENTS.md` to it, so that Claude Code reads the section too. If agents
73- work on the project with Claude Code and there is no `CLAUDE.md`, run
74- `touch CLAUDE.md` before `braid agents init`.
110+ agents land on: `main`, `master`, or the project's only branch. With
111+ several, it asks for `--branch <name>`, which must name a branch the
112+ project has. `--dry-run` shows what it would write. Text outside the
113+ markers is never touched, and running it again rewrites the section in
114+ place.
75115
76116 Commit what `braid agents init` wrote, so that every workspace and every
77-clone has the rules, then import that commit too:
117+clone has the rules, then import that commit too. From this commit on,
118+agents in every clone of the project read the section: tell the user so
119+before you commit. Where `braid agents init` found the files as they
120+should be already, there is nothing to commit, and the `git commit` line
121+does nothing.
78122
79123 ```bash
80124 git add AGENTS.md
81-test -f CLAUDE.md && git add CLAUDE.md
82-git commit -m "Set up braid for agents"
125+if [ -f CLAUDE.md ]; then git add CLAUDE.md; fi
126+if [ -f GEMINI.md ]; then git add GEMINI.md; fi
127+git diff --cached --quiet || git commit -m "Set up braid for agents"
83128 braid git import . # braid's main takes the commit
84129 braid log main -n 1 # and shows it
85130 ```
86131
87-### Every agent session, from then on
132+If `AGENTS.md`, `CLAUDE.md` or `GEMINI.md` is a symbolic link,
133+`braid agents init` writes the file it points to, and names it: `git add`
134+that file as well.
88135
89-The section in the project's `AGENTS.md` tells each session what to do. In
90-short:
136+### Every agent session, from then on
91137
138+The section in the project's `AGENTS.md` tells each session what to do,
139+with the branch it names where the commands here say `main`. In short:
140+
141+- **Only where braid is set up.** A checkout with no `.braid` directory in
142+ its root (a fresh clone, CI, another machine) does not use braid: agents
143+ there work with git, as the project's other rules say, and set braid up
144+ only when the user asks. With `.braid` but no `braid` command, braid is
145+ not on `PATH`: `"$HOME/.cargo/bin/braid"` may be there, or it needs
146+ installing.
92147 - **Never edit files, `git add`, `git commit` or `git push` in the project
93- root.** It is the shared checkout. Every session works in a workspace of
94- its own, under `.braid/work/`.
95-- **Start** from the project root with a workspace named for the session:
96- 1 to 64 letters, digits, `.`, `_` or `-`. `braid workspace list` shows the
97- names taken, and a name that is taken is refused. Then edit, build and
98- test only in that directory. A workspace is a whole checkout of the
99- branch, so builds in it start from scratch.
148+ root.** It is the shared checkout, where the user works. Every session
149+ works in a workspace of its own, under `.braid/work/`.
150+- **Start** with a workspace named for the session: 1 to 64 ASCII letters,
151+ digits, `.`, `_` or `-`, starting with a letter or a digit.
152+ `braid workspace list` shows the names taken, and a name that is taken is
153+ refused. Wherever it runs in the project, `braid workspace add` puts the
154+ workspace in `.braid/work/<name>` of the project root, and it refuses a
155+ branch the project does not have. Then edit, build and test only in that
156+ directory. A workspace is a whole checkout of the branch, so builds in it
157+ start from scratch.
100158
101159 ```bash
102- braid workspace add agent-1 .braid/work/agent-1 --track main
103- cd .braid/work/agent-1
160+ braid workspace add agent-1 --track main
161+ cd .braid/work/agent-1 # from the project root
104162 ```
105163
106-- **Use braid, not git, in the workspace.** It has no `.git` of its own, so
107- `git` there finds the shared checkout's repository and knows nothing of
108- the session's work. `braid --agent agent-1 status` says what changed.
164+- **No git in the workspace.** A workspace holds a `.git` file that points
165+ nowhere, so `git` fails there with "not a git repository" instead of
166+ acting on the shared checkout around it, where `git stash`, `reset`,
167+ `checkout`, `restore`, `clean`, `add` or `commit` would change the user's
168+ files. Do not get around it with `git -C` or `GIT_DIR`. A build or test
169+ script that finds the project with git (`git rev-parse --show-toplevel`)
170+ fails in a workspace too: run its steps yourself. To see what an edit
171+ changed, compare the file with the workspace's `base`, which
172+ `braid status --json` gives, from the workspace's root:
173+ `braid cat-object <base>:<path> | diff -u - <path>`. To undo an edit,
174+ write the base's version back with
175+ `braid cat-object <base>:<path> > <path>`; a file the workspace added has
176+ none, so delete it.
109177 - **Record and land** from the workspace. `--agent` (or `BRAID_AGENT`)
110178 names the session in the op log and in every changeset it makes; pass it
111179 every time, since a harness may not keep variables between commands. If
112180 the shell does not keep its directory either, add `--workspace agent-1`
113- and run the commands from the project root.
181+ and run the commands from the project root. The hints braid prints, and
182+ `next` in its JSON, repeat the `--agent` and `--workspace` given.
114183
115184 ```bash
116185 braid --agent agent-1 status --json
@@ -119,28 +188,43 @@
119188 ```
120189
121190 There is no staging area: `commit` records every change in the
122- workspace. `land` puts the workspace's changesets on `main`, as a
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
123196 fast-forward or rebased onto whatever landed first.
124197 - **Before a new task**, `braid --agent agent-1 update` brings the
125198 workspace onto `main`. `status --json` says how far behind it is
126199 (`behind_by`).
200+- **When the session finishes**, what it landed is on braid's `main` only.
201+ The user's checkout and the git remote get it with `braid git sync`, then
202+ `git pull --ff-only`, both from the project root (see "Keeping the git
203+ remote up to date"). The session tells the user so, and offers to run
204+ them: when to sync is the user's call.
127205 - **Done**: once everything has landed, `braid workspace remove agent-1`
128206 from the project root. It refuses while the workspace holds work that
129207 has not landed.
130-- Every command takes `--json`. Changesets are signed by `BRAID_AUTHOR`
131- (`"Name <email>"`), or else by the `name` and `email` in `.braid/config`.
208+- Every command takes `--json`. Exit status 2 is a conflict, and 1 a
209+ failure, which braid prints as text on standard error, with nothing on
210+ standard output, even with `--json`; only `git sync` and `fsck` print
211+ their report as well when they exit with 1.
212+- Changesets are signed by `BRAID_AUTHOR` (`"Name <email>"`), or else by
213+ the `name` and `email` in `.braid/config`.
132214 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
133215 than 1 MiB are held back until `braid track <path>`: `commit` refuses,
134- naming them, and `--force` leaves them out.
216+ naming them, and `--force` leaves them out. Never `braid track` a secret:
217+ move it out of the workspace.
135218
136219 ### Conflicts
137220
138221 When another agent landed a change to the same lines first, `land` exits
139-with status 2 and leaves `main` where it was. Exit status 2 also means a
140-command line braid could not parse, so check the JSON: only a conflict
141-prints `"outcome": "conflicts"`. Each conflict names its sides: `base`,
142-`branch` (what `main` holds now) and `workspace` (the session's own
143-change), and `next` says what to run.
222+with status 2 and leaves `main` where it was, and `update` exits with 2 as
223+it writes the conflicts into the files. Exit status 2 also means a command
224+line braid could not parse, which prints only an error, so read the JSON:
225+a conflict's `outcome` is `conflicts`. Each conflict names its sides:
226+`base`, `branch` (what `main` holds now) and `workspace` (the session's
227+own change), and `next` says what to run.
144228
145229 ```bash
146230 braid --agent agent-1 update # exit status 2: conflict markers in the files
@@ -150,7 +234,9 @@
150234 ```
151235
152236 `braid resolve <path>` settles conflicts that are not about content, such
153-as a file deleted on one side and changed on the other.
237+as a file deleted on one side and changed on the other. Never
238+`commit --force` while a rebase is in progress: it would commit the
239+conflict markers as they are.
154240
155241 ### Keeping the git remote up to date
156242
@@ -159,25 +245,31 @@
159245 braid's branch when only the remote moved, pushes braid's branch when only
160246 braid moved, and when both moved, merges them and pushes the merge. The
161247 push is a fast-forward with a lease on what was just fetched, so the
162-remote's history is never rewritten; braid never force-pushes. It runs the
163-`git` binary with your environment, so it needs the network and the
164-credentials `git push` uses. Run it from the project root, when the
165-remote should have what landed: who runs it, and when, is the user's call.
248+remote's history is never rewritten; braid never force-pushes, and runs no
249+git hooks. It runs the `git` binary with your environment, so it needs the
250+network and the credentials `git push` uses. Run it from the project root,
251+when the remote should have what landed: who runs it, and when, is the
252+user's call. Braid pushes to the remote's address, so the shared
253+checkout's own record of the remote (`origin/main`) does not move:
254+`git pull --ff-only` brings the checkout up to date.
166255
167256 ```bash
168-braid git sync "$(git remote get-url origin)" --branch main --dry-run --json
169-braid git sync "$(git remote get-url origin)" --branch main
257+braid --agent agent-1 git sync "$(git remote get-url origin)" --branch main --dry-run --json
258+braid --agent agent-1 git sync "$(git remote get-url origin)" --branch main
170259 git pull --ff-only # the shared checkout follows
171260 ```
172261
173262 - With `--json`, `outcome` is one of `up_to_date`, `created`,
174263 `fast_forwarded`, `pushed`, `merged`, `conflicts`, `remote_moved` or
175- `rejected`. `--dry-run` writes nothing.
264+ `rejected`. `--dry-run` writes nothing. `--agent` names the session in
265+ the op log, and in the merge a sync makes.
176266 - Each changeset reaches git as a commit of its own, with an `agent` header
177267 that names the agent that made it.
178268 - Exit status 1 with `remote_moved`: someone pushed meanwhile; sync again.
179269 With `rejected`, also exit status 1, the remote refused the push, as a
180- protected branch does.
270+ protected branch does: ask the user. They may let braid push there, or
271+ have it push to a branch of its own, with `--remote-branch <name>`, to
272+ open a pull request from.
181273 - Exit status 2 with `conflicts`: braid and the remote changed the same
182274 lines. Nothing moved and nothing was pushed. Merge them in git, in the
183275 shared checkout, and sync again:
@@ -200,32 +292,38 @@
200292 parents to tell what a workspace has landed, so the workspaces carry on
201293 from the merge.
202294
203-No remote? Any bare repository will do: `git init --bare ../project.git`,
204-then `git remote add origin ../project.git` and `git push -u origin main`
205-in the shared checkout.
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`.
206300
207301 ### Undoing
208302
209303 - `braid op log` lists every operation (imports, landings, syncs), newest
210- first, with the agent that made it. `braid undo` reverts the newest one
211- that is not undone yet, whoever made it, so read the log first. A landing
212- undone leaves its changeset in the workspace that made it, ready to land
213- again.
304+ first, with the agent that made it. `braid --agent agent-1 undo` reverts
305+ the newest one that is not undone yet, whoever made it, so read the log
306+ first. A landing undone leaves its changeset in the workspace that made
307+ it, ready to land again.
214308 - A change that landed under other changes cannot be undone that way.
215309 There is no revert command yet: land a change that puts the files back.
216-- To take braid out of a project: land what the workspaces hold and sync
217- it, remove each workspace (`braid workspace remove <name>`, which refuses
218- while work has not landed), delete `.braid/`, the `/.braid/` line of
219- `.git/info/exclude`, the braid section of `AGENTS.md` (its two marker
220- lines and everything between them) and the `@AGENTS.md` line it added to
221- `CLAUDE.md`, and commit that with git. Then
222- `cargo uninstall elffuss-braid-cli` removes the command.
310+- To take braid out of a project: land what the workspaces hold, sync it
311+ and run `git pull --ff-only`; remove each workspace
312+ (`braid workspace remove <name>`, which refuses while work has not
313+ landed); delete `.braid/`, the `.braid` line of the file that
314+ `git rev-parse --git-path info/exclude` names, the braid section of
315+ `AGENTS.md` (its two marker lines and everything between them) and the
316+ `@AGENTS.md` line it added to `CLAUDE.md` and `GEMINI.md`; and commit
317+ that with git. Then `cargo uninstall elffuss-braid-cli` removes the
318+ command.
223319
224320 ### What not to do
225321
226322 - Do not edit files, `git add`, `git commit`, `git push` or `git pull` in
227323 the shared checkout while you work: only setting up, syncing and merging
228324 a sync conflict touch it, as above.
325+- Do not run git in a workspace, or get around the `.git` file that stops
326+ it there.
229327 - Do not share a workspace between sessions, or work in another session's
230328 workspace.
231329 - Do not run `braid undo` without reading `braid op log` first.
@@ -264,9 +362,12 @@
264362 cargo test --workspace
265363 ```
266364
365+The tests and the quick benchmark read this repository's whole history: in
366+a shallow clone, run `git fetch --unshallow` first.
367+
267368 ### Before every commit
268369
269-These are the checks CI runs. All of them must pass:
370+All of these must pass:
270371
271372 ```bash
272373 cargo fmt --all
@@ -275,9 +376,18 @@
275376 cargo test --workspace
276377 cargo deny check
277378 cargo +1.89 check --workspace --all-targets
379+cargo +1.99.0 check -p elffuss-braid-format -p elffuss-braid-engine --target wasm32-unknown-unknown --locked
380+python3 docs/spec/check_vectors.py
381+python3 bench/run.py --quick
278382 scripts/privacy-check.sh
279383 ```
280384
385+CI runs all of them but the unpinned clippy, which catches the lints of
386+newer toolchains early, and it also runs each fuzz target for a minute with
387+cargo-fuzz, on nightly. The WebAssembly check needs its target
388+(`rustup +1.99.0 target add wasm32-unknown-unknown`), and the vector check
389+`b3sum` (`cargo install b3sum --locked`).
390+
281391 ### Rules
282392
283393 From [CONTRIBUTING.md](CONTRIBUTING.md), in short:
@@ -301,4 +411,6 @@
301411 - The repository is public: no absolute paths, user names, real e-mail
302412 addresses (use `example.org`), hardware or timings in anything committed.
303413 - Part 1 of this file and `site/agents.md` say the same thing, and a test
304- checks it: change both together.
414+ checks it: change both together. The install command names the tag of
415+ the version in `Cargo.toml`, and the test checks that too: a release
416+ bumps both.
modified CONTRIBUTING.md +1 −1
@@ -5,7 +5,7 @@
55 [format](docs/spec/format-v1.md), bug reports, and tests.
66
77 Coding agents: part 2 of [AGENTS.md](AGENTS.md) says the same in short,
8-with every check CI runs.
8+with the checks to run before every commit.
99
1010 ## Build and test
1111
modified Cargo.lock +8 −8
@@ -478,7 +478,7 @@
478478
479479 [[package]]
480480 name = "elffuss-braid-cli"
481-version = "0.0.1"
481+version = "0.0.2"
482482 dependencies = [
483483 "anyhow",
484484 "clap",
@@ -494,7 +494,7 @@
494494
495495 [[package]]
496496 name = "elffuss-braid-engine"
497-version = "0.0.1"
497+version = "0.0.2"
498498 dependencies = [
499499 "blake3",
500500 "elffuss-braid-format",
@@ -506,7 +506,7 @@
506506
507507 [[package]]
508508 name = "elffuss-braid-format"
509-version = "0.0.1"
509+version = "0.0.2"
510510 dependencies = [
511511 "blake3",
512512 "proptest",
@@ -515,7 +515,7 @@
515515
516516 [[package]]
517517 name = "elffuss-braid-git"
518-version = "0.0.1"
518+version = "0.0.2"
519519 dependencies = [
520520 "elffuss-braid-format",
521521 "gix",
@@ -525,7 +525,7 @@
525525
526526 [[package]]
527527 name = "elffuss-braid-repo"
528-version = "0.0.1"
528+version = "0.0.2"
529529 dependencies = [
530530 "blake3",
531531 "elffuss-braid-engine",
@@ -539,7 +539,7 @@
539539
540540 [[package]]
541541 name = "elffuss-braid-sim"
542-version = "0.0.1"
542+version = "0.0.2"
543543 dependencies = [
544544 "elffuss-braid-engine",
545545 "elffuss-braid-format",
@@ -550,7 +550,7 @@
550550
551551 [[package]]
552552 name = "elffuss-braid-store"
553-version = "0.0.1"
553+version = "0.0.2"
554554 dependencies = [
555555 "blake3",
556556 "crc32c",
@@ -566,7 +566,7 @@
566566
567567 [[package]]
568568 name = "elffuss-braid-wc"
569-version = "0.0.1"
569+version = "0.0.2"
570570 dependencies = [
571571 "cap-fs-ext",
572572 "cap-std",
modified Cargo.toml +1 −1
@@ -4,7 +4,7 @@
44 exclude = ["fuzz"]
55
66 [workspace.package]
7-version = "0.0.1"
7+version = "0.0.2"
88 edition = "2024"
99 rust-version = "1.89"
1010 license = "Apache-2.0"
modified README.md +41 −20
@@ -95,14 +95,17 @@
9595 is a git repository, ask your agent, whatever harness runs it:
9696
9797 ```text
98-Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md
98+Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md (read it whole, with curl -fsSL)
9999 ```
100100
101-It installs braid with cargo, imports the project's git history, and writes
102-the rules for agents into the project's `AGENTS.md` with
103-`braid agents init`. From then on, every agent session works in a braid
104-workspace of its own and lands through braid, and git stays the source of
105-truth. The instructions are part 1 of [AGENTS.md](AGENTS.md), which the
101+It installs braid with cargo, tells you what in the project braid does not
102+run, such as git hooks, imports the project's git history, and writes the
103+rules for agents into the project's `AGENTS.md` with `braid agents init`.
104+From then on, every agent session works in a braid workspace of its own,
105+where git refuses to run, lands through braid, and tells you when what it
106+landed is waiting for a sync to the git remote. Git stays the source of
107+truth, and in a clone where braid is not set up, agents work with git as
108+before. The instructions are part 1 of [AGENTS.md](AGENTS.md), which the
106109 site serves as
107110 [braid.elffuss.com/agents.md](https://braid.elffuss.com/agents.md), next to
108111 an [llms.txt](https://braid.elffuss.com/llms.txt).
@@ -160,8 +163,8 @@
160163 ```bash
161164 export BRAID_AUTHOR="Ada Lovelace <ada@example.org>"
162165 export BRAID_AGENT=agent-1 # recorded with everything this agent does
163-braid workspace add agent-1 # ./agent-1, tracking main
164-cd agent-1
166+braid workspace add agent-1 # .braid/work/agent-1, tracking main
167+cd .braid/work/agent-1
165168 echo 'fn main() {}' > main.rs
166169 braid status
167170 braid commit -m "Add main.rs"
@@ -200,15 +203,29 @@
200203 store: generation numbers and skip pointers for ancestry, changed-path
201204 filters, and blame records, computed the first time they are needed.
202205 `braid derive --all` computes them ahead of time, after a large import.
206+- A workspace goes in `.braid/work/<name>` unless `workspace add` is given
207+ a directory, and tracks a branch the repository has, unless it has none
208+ yet; `--new-branch` starts one on purpose. It holds a `.git` file that
209+ points nowhere, so that git run inside
210+ it stops with "not a git repository" instead of acting on the checkout
211+ around it. `braid cat-object <rev>:<path>` prints a file as a changeset
212+ has it: `braid cat-object <base>:<path> | diff -u - <path>` shows what an
213+ edit in the workspace changed.
214+- Hints, and `next` in the JSON, repeat the `--agent`, `--workspace` and
215+ `--repo` a command was given, so that an agent that follows them acts as
216+ the same session.
203217 - `braid agents init` writes the rules for agents into a project's
204218 `AGENTS.md`, in a section between a `<!-- braid:start -->` line and a
205219 `<!-- braid:end -->` line: each session works in a workspace of its own
206- under `.braid/work/` and lands on the branch the section names. Running it
207- again rewrites the section in place and touches nothing else; markers that
208- do not pair up are refused. It also adds `@AGENTS.md` to a `CLAUDE.md`
209- that does not include it (`--no-claude` leaves it alone). `--dry-run`
210- shows what it would write, and `--json` lists the files created, updated
211- and unchanged.
220+ under `.braid/work/` and lands on the branch the section names, one the
221+ repository has. Running it again rewrites the section in place and
222+ touches nothing else; markers that do not pair up are refused, and
223+ marker lines in code blocks are not markers. It also adds `@AGENTS.md` to
224+ a `CLAUDE.md` or a `GEMINI.md` that does not include it (`--no-claude` and
225+ `--no-gemini` leave them alone). It writes through a link only inside the
226+ project, never a read-only file, and replaces no file until every one is
227+ ready. `--dry-run` shows what it would write, and `--json` lists the
228+ files created, updated and unchanged, and the file each one is.
212229
213230 `braid status --help`, `braid land --help`, `braid update --help` and
214231 `braid agents init --help` describe every JSON field.
@@ -419,9 +436,13 @@
419436 Las [fases](#status-and-roadmap) dicen qué llega después y qué pruebas tiene que
420437 pasar cada una.
421438
422-Para usarlo en un proyecto, pídeselo a tu agente: «Instala braid en este
423-proyecto y configúralo para agentes siguiendo
424-https://braid.elffuss.com/agents.md». Lo instala con cargo, importa la
425-historia de git del proyecto y, con `braid agents init`, escribe en su
426-`AGENTS.md` las reglas para que cada sesión trabaje en su propio espacio de
427-trabajo y aterrice a través de braid.
439+Para usarlo en un proyecto, pídeselo a tu agente:
440+
441+```text
442+Instala braid en este proyecto y configúralo para agentes siguiendo https://braid.elffuss.com/agents.md (léelo entero, con curl -fsSL)
443+```
444+
445+Lo instala con cargo, te avisa de lo que braid no ejecuta, como los hooks
446+de git, importa la historia de git del proyecto y, con `braid agents init`,
447+escribe en su `AGENTS.md` las reglas para que cada sesión trabaje en su
448+propio espacio de trabajo y aterrice sus cambios con braid.
modified crates/cli/src/agents.rs +1025 −261
@@ -4,11 +4,13 @@
44 //! `braid agents init`: the rules for coding agents, written into the
55 //! project's `AGENTS.md` between two marker lines, so that every agent
66 //! session, whatever runs it, knows to work in a braid workspace of its own
7-//! and to land through braid. A `CLAUDE.md` that does not include
8-//! `AGENTS.md` gets the line that does.
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.
99 //!
1010 //! Text outside the markers is never touched, and running the command again
11-//! rewrites the section in place, so it is idempotent.
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.
1214
1315 use std::fs::{self, OpenOptions};
1416 use std::io::{self, Write};
@@ -20,9 +22,10 @@
2022 use braid_repo::{Location, Repo};
2123 use braid_wc::Workspace;
2224 use clap::{Args, Subcommand};
23-use serde_json::json;
25+use serde_json::{Map, Value, json};
2426
25-use crate::{Cli, print_json};
27+use crate::work::{branches, listed};
28+use crate::{Cli, open_repo, print_json};
2629
2730 /// The line that opens the braid section of `AGENTS.md`.
2831 pub(crate) const START: &str = "<!-- braid:start -->";
@@ -36,12 +39,18 @@
3639 /// The file Claude Code reads, which should include `AGENTS.md`.
3740 const CLAUDE_FILE: &str = "CLAUDE.md";
3841
39-/// The line that makes `CLAUDE.md` include `AGENTS.md`.
42+/// The file Gemini CLI reads, which should include `AGENTS.md`.
43+const GEMINI_FILE: &str = "GEMINI.md";
44+
45+/// The line that makes `CLAUDE.md` or `GEMINI.md` include `AGENTS.md`.
4046 const INCLUDE: &str = "@AGENTS.md";
4147
4248 /// What the section's first comment says just before the branch it names.
4349 const BRANCH_NOTE: &str = "(branch: ";
4450
51+/// The end of every refusal: nothing is written when any check fails.
52+const NOTHING: &str = "nothing was written";
53+
4554 /// The long help of `agents init`.
4655 pub(crate) const INIT_HELP: &str =
4756 "Write the rules for coding agents into the project's AGENTS.md, so that
@@ -51,38 +60,63 @@
5160 The rules go in a section between two lines, <!-- braid:start --> and
5261 <!-- braid:end -->: at the end of AGENTS.md, which is created if there is
5362 none, and in place on later runs. Text outside the markers is never
54-touched, and running the command twice changes nothing. Markers that do not
55-pair up (one without the other, the end first, or either of them twice)
56-are refused before anything is written.
57-
58-The section names the branch agents land on, says that each session works
59-in a workspace of its own under .braid/work/, commits and lands with braid,
60-and reads exit status 2 as conflicts, and that nobody commits with git in
61-the shared checkout.
62-
63-A CLAUDE.md in the directory that does not include AGENTS.md gets the line
64-@AGENTS.md at its end, so that Claude Code reads the section too;
65---no-claude leaves it alone. CLAUDE.md is never created.
66-
67-With --dry-run nothing is written: the command says what it would do, and
68-prints the section when AGENTS.md would change. With --json it prints one
69-object:
70-
71- dir the project's directory
72- branch the branch the section names
73- repository the root of the braid repository, or null when there is none
74- dry_run whether nothing was written
75- created the files created (or, with --dry-run, that would be)
76- updated the files changed
77- unchanged the files already as they should be
78-
79-A CLAUDE.md that does not exist, or that --no-claude leaves alone, is in
80-none of the lists.";
63+touched, and running the command twice changes nothing. Marker lines
64+inside fenced code blocks are not markers. Markers that do not pair up (one
65+without the other, the end first, or either of them twice) are refused
66+before anything is written, and so is a file that ends inside a fenced
67+code block, where the section would be read as code.
68+
69+The project's directory is the root of the repository or of the workspace
70+the current directory is in, or the current directory; --workspace names a
71+workspace to write in, --repo a repository whose root to write in, and
72+--dir any directory.
73+
74+The section names the branch agents land on: --branch, which must be a
75+branch the repository has; else the one the section names already, if the
76+repository has it; else, inside a workspace, the one it tracks; else main,
77+master, or the repository's only branch. Without a braid repository, or
78+with one that has no branch yet, there is no branch to name: set braid up
79+first, or pass --branch. The section writes the name into shell commands,
80+so it takes ASCII letters, digits, '.', '_', '/' and '-' only, and does not
81+start with '-'.
82+
83+Claude Code reads CLAUDE.md, and Gemini CLI reads GEMINI.md, instead of
84+AGENTS.md: each of them that exists and does not include AGENTS.md gets the
85+line @AGENTS.md at its end. --no-claude and --no-gemini leave them alone.
86+Neither is ever created.
87+
88+Any of the three may be a symbolic link to a file inside the project, and
89+the file it points to is the one written. A link that leads outside the
90+project, a name that is not a regular file, a read-only file, and a file
91+with hard links other than these three names are refused. Files are
92+written through a temporary file and a rename, every one of them prepared
93+before any is replaced; a file with hard links is written in place, so
94+that its names stay one file.
95+
96+With --dry-run nothing is written: the command makes the same checks, says
97+what 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+
113+A 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.";
81115
82116 #[derive(Debug, Subcommand)]
83117 pub(crate) enum AgentsAction {
84118 /// Write the braid section of the project's AGENTS.md, and make its
85- /// CLAUDE.md include AGENTS.md.
119+ /// CLAUDE.md and GEMINI.md include AGENTS.md.
86120 #[command(long_about = INIT_HELP)]
87121 Init(InitArgs),
88122 }
@@ -94,9 +128,10 @@
94128 /// directory).
95129 #[arg(long, value_name = "DIR")]
96130 dir: Option<PathBuf>,
97- /// The branch agents land on (default: the one the section names
98- /// already; inside a workspace, the one it tracks; otherwise main,
99- /// master, or the repository's only branch).
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).
100135 #[arg(long, value_name = "BRANCH")]
101136 branch: Option<String>,
102137 /// Say what would change, and write nothing.
@@ -105,6 +140,9 @@
105140 /// Leave CLAUDE.md alone.
106141 #[arg(long)]
107142 no_claude: bool,
143+ /// Leave GEMINI.md alone.
144+ #[arg(long)]
145+ no_gemini: bool,
108146 }
109147
110148 pub(crate) fn agents(cli: &Cli, action: &AgentsAction) -> Result<ExitCode> {
@@ -122,8 +160,10 @@
122160
123161 /// One file the command looked at, and what it does to it.
124162 struct Planned {
163+ /// The name the project knows it by: `AGENTS.md`, `CLAUDE.md` or
164+ /// `GEMINI.md`.
125165 name: &'static str,
126- path: PathBuf,
166+ target: Target,
127167 action: Action,
128168 /// The new contents, unless unchanged.
129169 contents: Option<String>,
@@ -134,46 +174,53 @@
134174 }
135175
136176 fn init(cli: &Cli, args: &InitArgs) -> Result<ExitCode> {
137- let start = match &args.dir {
138- Some(dir) => std::path::absolute(dir)?,
139- None => std::env::current_dir()?,
140- };
141- if !start.is_dir() {
142- bail!("{} is not a directory", start.display());
143- }
144- let place = Place::find(cli, &start)?;
145- let dir = match (&args.dir, &place.top) {
146- (None, Some(top)) => top.clone(),
147- _ => start,
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,
148194 };
149-
150- let agents_path = dir.join(AGENTS_FILE);
151- let current = read_text(&agents_path)?;
152- let found = match &current {
153- Some(text) => find_section(text).map_err(|why| {
154- anyhow!("{AGENTS_FILE} has unbalanced braid markers: {why}. Fix them by hand: nothing was written")
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+ )
155202 })?,
156- None => None,
203+ None => Scanned::default(),
157204 };
158- let named = match (&current, &found) {
205+ let named = match (&current, &scanned.section) {
159206 (Some(text), Some(range)) => named_branch(&text[range.clone()]),
160207 _ => None,
161208 };
162- let branch = choose_branch(args.branch.as_deref(), named, &place)?;
163- let agents = plan_agents(agents_path, current.as_deref(), found, &branch);
164- let claude = if args.no_claude {
165- None
166- } else {
167- plan_claude(&dir)?
168- };
169- let planned: Vec<&Planned> = std::iter::once(&agents).chain(claude.as_ref()).collect();
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+ }
170221
171222 if !args.dry_run {
172- for file in &planned {
173- if let Some(contents) = &file.contents {
174- write_file(&file.path, contents)?;
175- }
176- }
223+ write_all(&planned)?;
177224 }
178225
179226 if cli.json {
@@ -184,19 +231,33 @@
184231 .map(|file| file.name)
185232 .collect()
186233 };
234+ let paths: Map<String, Value> = planned
235+ .iter()
236+ .map(|file| (file.name.to_owned(), Value::from(file.target.shown.clone())))
237+ .collect();
187238 print_json(&json!({
188239 "dir": dir.to_string_lossy(),
189- "branch": branch,
240+ "branch": choice.branch,
241+ "previous_branch": choice.previous,
190242 "repository": place.repo.as_ref().map(|repo| repo.root().to_string_lossy()),
191243 "dry_run": args.dry_run,
192244 "created": names(Action::Create),
193245 "updated": names(Action::Update),
194246 "unchanged": names(Action::Unchanged),
247+ "paths": paths,
195248 }))?;
196249 return Ok(ExitCode::SUCCESS);
197250 }
198251
199252 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+ }
200261 for file in &planned {
201262 let said = if args.dry_run {
202263 &file.would
@@ -208,31 +269,65 @@
208269 if place.repo.is_none() {
209270 writeln!(
210271 out,
211- "There is no braid repository here yet: run `braid init` in the project root."
272+ "There is no braid repository here yet: set braid up in the project root (`braid init`, then `braid git import .`) before agents start."
212273 )?;
213274 }
214275 if args.dry_run {
215276 writeln!(out, "Nothing was written.")?;
216- if agents.action != Action::Unchanged {
277+ if planned[0].action != Action::Unchanged {
217278 writeln!(out, "\nThe section {AGENTS_FILE} would hold:\n")?;
218- write!(out, "{}", section(&branch))?;
279+ write!(out, "{}", section(&choice.branch))?;
219280 }
220281 }
221282 Ok(ExitCode::SUCCESS)
222283 }
223284
224-/// The repository and the workspace the command runs in, if any.
285+/// Where the command writes, and the repository and workspace that tells
286+/// it which branch to name.
225287 struct Place {
226288 repo: Option<Repo>,
227- /// The directory the repository or the workspace starts at.
228- top: Option<PathBuf>,
229- /// The branch of the workspace, inside one.
289+ /// The project's directory: where `AGENTS.md` is.
290+ dir: PathBuf,
291+ /// The branch of the workspace `dir` is, when it is one.
230292 workspace_branch: Option<String>,
231293 }
232294
233295 impl Place {
234- fn find(cli: &Cli, start: &Path) -> Result<Place> {
235- let location = match braid_repo::locate(start) {
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) {
236331 Ok(location) => Some(location),
237332 Err(braid_repo::Error::NotFound) => None,
238333 Err(err) => return Err(err.into()),
@@ -243,9 +338,17 @@
243338 (None, Some(Location::Workspace { link, .. })) => Some(Repo::open(&link.repository)?),
244339 (None, None) => None,
245340 };
341+ // What the current directory is in counts only when it belongs to
342+ // the repository: --repo may name another.
343+ let belongs = |root: &Path| {
344+ cli.repo.is_none()
345+ || repo
346+ .as_ref()
347+ .is_some_and(|repo| same_dir(root, repo.root()))
348+ };
246349 let (top, workspace_branch) = match &location {
247- Some(Location::Root(dir)) => (Some(dir.clone()), None),
248- Some(Location::Workspace { dir, link }) => {
350+ Some(Location::Root(root)) if belongs(root) => (Some(root.clone()), None),
351+ Some(Location::Workspace { dir, link }) if belongs(&link.repository) => {
249352 // A workspace whose state is gone names no branch.
250353 let branch = repo.as_ref().and_then(|repo| {
251354 Workspace::open(repo, &link.name)
@@ -255,149 +358,287 @@
255358 });
256359 (Some(dir.clone()), branch)
257360 }
258- None => (None, None),
361+ _ => (repo.as_ref().map(|repo| repo.root().to_path_buf()), None),
362+ };
363+ let dir = match (given, top) {
364+ (None, Some(top)) => top,
365+ _ => start,
259366 };
260367 Ok(Place {
261368 repo,
262- top,
369+ dir,
263370 workspace_branch,
264371 })
265372 }
266373 }
267374
268-/// The branch the section names: the one asked for, the one the section
269-/// names already, the workspace's, or the repository's main one.
270-fn choose_branch(given: Option<&str>, named: Option<String>, place: &Place) -> Result<String> {
271- let branch = match (given, named, &place.workspace_branch, &place.repo) {
272- (Some(given), ..) => given.to_owned(),
273- (None, Some(named), ..) => named,
274- (None, None, Some(tracked), _) => tracked.clone(),
275- (None, None, None, Some(repo)) => repository_branch(repo)?,
276- (None, None, None, None) => "main".to_owned(),
375+/// Whether two paths name the same directory.
376+fn same_dir(a: &Path, b: &Path) -> bool {
377+ match (fs::canonicalize(a), fs::canonicalize(b)) {
378+ (Ok(a), Ok(b)) => a == b,
379+ _ => a == b,
380+ }
381+}
382+
383+/// The branch the section names, and what it named before.
384+#[derive(Debug)]
385+struct Choice {
386+ branch: String,
387+ /// The branch the section named before, when that was another.
388+ previous: Option<String>,
389+ /// Whether it changes because the repository does not have the branch
390+ /// the section named.
391+ missing: bool,
392+}
393+
394+/// The branch the section names: the one asked for, which the repository
395+/// must have; the one the section names already, if the repository has
396+/// it; the workspace's; or the repository's main one. A branch the section
397+/// names but the repository does not have was written before the
398+/// project's history came in, or names a branch since removed: it is
399+/// chosen again rather than kept.
400+fn choose_branch(given: Option<&str>, named: Option<String>, place: &Place) -> Result<Choice> {
401+ let refs = place
402+ .repo
403+ .as_ref()
404+ .map(|repo| repo.store().refs())
405+ .transpose()?;
406+ let names: Option<Vec<&str>> = refs.as_ref().map(branches);
407+ // Whether the repository could have the branch: it has it, it has no
408+ // branch yet, or there is no repository to ask.
409+ let possible = |branch: &str| {
410+ names
411+ .as_ref()
412+ .is_none_or(|names| names.is_empty() || names.contains(&branch))
277413 };
278- if !braid_git::is_branch_name(&branch) || !braid_repo::is_branch(&branch) {
279- bail!("{branch:?} cannot name the branch agents land on");
414+ if let Some(given) = given {
415+ check_branch(given)?;
416+ if !possible(given) {
417+ bail!(
418+ "the repository has no branch {given:?}; it has {}. Pass --branch the branch agents land on",
419+ listed(names.as_deref().unwrap_or_default())
420+ );
421+ }
422+ return Ok(Choice {
423+ branch: given.to_owned(),
424+ previous: named.filter(|named| named != given),
425+ missing: false,
426+ });
280427 }
281- Ok(branch)
428+ if let Some(named) = named {
429+ if possible(&named) {
430+ return Ok(Choice {
431+ branch: named,
432+ previous: None,
433+ missing: false,
434+ });
435+ }
436+ let branch = main_branch(names.as_deref().unwrap_or_default())?;
437+ return Ok(Choice {
438+ branch,
439+ previous: Some(named),
440+ missing: true,
441+ });
442+ }
443+ let branch = match (&place.workspace_branch, names.as_deref()) {
444+ (Some(tracked), _) => {
445+ check_branch(tracked)?;
446+ tracked.clone()
447+ }
448+ (None, None) => bail!(
449+ "there is no braid repository here, so there is no branch to name yet: set braid up first (`braid init`, then `braid git import .`), or pass --branch"
450+ ),
451+ (None, Some([])) => bail!(
452+ "the braid repository has no branch yet: import the project's history first (`braid git import .`), or pass --branch"
453+ ),
454+ (None, Some(names)) => main_branch(names)?,
455+ };
456+ Ok(Choice {
457+ branch,
458+ previous: None,
459+ missing: false,
460+ })
282461 }
283462
284-/// The repository's main branch: `main`, `master`, or its only branch;
285-/// `main` when it has none yet.
286-fn repository_branch(repo: &Repo) -> Result<String> {
287- let refs = repo.store().refs()?;
288- let branches: Vec<&str> = refs
289- .iter()
290- .map(|(name, _)| name)
291- .filter(|name| braid_repo::is_branch(name))
292- .collect();
463+/// The repository's main branch among its branches `names`: `main`,
464+/// `master`, or its only branch.
465+fn main_branch(names: &[&str]) -> Result<String> {
293466 if let Some(preferred) = ["main", "master"]
294467 .into_iter()
295- .find(|preferred| branches.contains(preferred))
468+ .find(|preferred| names.contains(preferred))
296469 {
297470 return Ok(preferred.to_owned());
298471 }
299- match branches.as_slice() {
300- [] => Ok("main".to_owned()),
301- [only] => Ok((*only).to_owned()),
472+ match names {
473+ [only] => {
474+ check_branch(only)?;
475+ Ok((*only).to_owned())
476+ }
477+ [] => bail!("the repository has no branch yet: pass --branch"),
302478 several => bail!(
303479 "cannot tell which branch agents land on: the repository has {}; pass --branch",
304- several.join(", ")
480+ listed(several)
305481 ),
306482 }
307483 }
308484
485+/// Whether the section can name `branch`. The section writes it into shell
486+/// commands and reads it back from its first comment, so it takes only a
487+/// set of characters that needs no quoting and holds no `)`: ASCII letters,
488+/// digits, `.`, `_`, `/` and `-`, not first. It must be a git branch name
489+/// outside braid's own namespaces, too.
490+pub(crate) fn is_section_branch(branch: &str) -> bool {
491+ !branch.is_empty()
492+ && !branch.starts_with('-')
493+ && branch
494+ .bytes()
495+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'/' | b'-'))
496+ && braid_git::is_branch_name(branch)
497+ && braid_repo::is_branch(branch)
498+}
499+
500+fn check_branch(branch: &str) -> Result<()> {
501+ if is_section_branch(branch) {
502+ Ok(())
503+ } else {
504+ bail!(
505+ "{branch:?} cannot name the branch agents land on: the section writes it into shell commands, so it takes a git branch name of ASCII letters, digits, '.', '_', '/' and '-', not starting with '-' and outside braid's own refs (braid/, git/, remote/, tags/)"
506+ )
507+ }
508+}
509+
309510 /// What `AGENTS.md` needs: to be created, to get the section, or to have
310511 /// it rewritten in place.
311512 fn plan_agents(
312- path: PathBuf,
513+ target: Target,
313514 current: Option<&str>,
314- found: Option<Range<usize>>,
515+ scanned: &Scanned,
315516 branch: &str,
316-) -> Planned {
517+) -> Result<Planned> {
317518 let landing = format!("agents land on {branch}");
318- let (action, contents, done, would) = match (current, found) {
519+ let called = target.called(AGENTS_FILE);
520+ let (action, contents, done, would) = match (current, &scanned.section) {
319521 (None, _) => (
320522 Action::Create,
321523 Some(section(branch)),
322- format!("Created {AGENTS_FILE} with the braid section: {landing}."),
323- format!("Would create {AGENTS_FILE} with the braid section: {landing}."),
524+ format!("Created {called} with the braid section: {landing}."),
525+ format!("Would create {called} with the braid section: {landing}."),
324526 ),
325527 (Some(text), Some(range)) => {
326- let new = replace_section(text, range, &section(branch));
528+ let new = replace_section(text, range.clone(), &section(branch));
327529 if new == text {
328- let said = format!("{AGENTS_FILE} has this braid section already: {landing}.");
530+ let said = format!("{called} has this braid section already: {landing}.");
329531 (Action::Unchanged, None, said.clone(), said)
330532 } else {
331533 (
332534 Action::Update,
333535 Some(new),
334- format!("Updated the braid section of {AGENTS_FILE}: {landing}."),
335- format!("Would update the braid section of {AGENTS_FILE}: {landing}."),
536+ format!("Updated the braid section of {called}: {landing}."),
537+ format!("Would update the braid section of {called}: {landing}."),
336538 )
337539 }
338540 }
541+ (Some(_), None) if scanned.open_fence.is_some() => bail!(
542+ "{} ends inside a fenced code block, which opens on line {} and is never closed: the section would be read as code there. Close the block, then run the command again: {NOTHING}",
543+ target.shown,
544+ scanned.open_fence.unwrap_or_default()
545+ ),
339546 (Some(text), None) => (
340547 Action::Update,
341548 Some(append_section(text, &section(branch))),
342- format!("Added the braid section to {AGENTS_FILE}: {landing}."),
343- format!("Would add the braid section to {AGENTS_FILE}: {landing}."),
549+ format!("Added the braid section to {called}: {landing}."),
550+ format!("Would add the braid section to {called}: {landing}."),
344551 ),
345552 };
346- Planned {
553+ Ok(Planned {
347554 name: AGENTS_FILE,
348- path,
555+ target,
349556 action,
350557 contents,
351558 done,
352559 would,
353- }
560+ })
354561 }
355562
356-/// What `CLAUDE.md` needs, or `None` when there is no such file.
357-fn plan_claude(dir: &Path) -> Result<Option<Planned>> {
358- let path = dir.join(CLAUDE_FILE);
359- let meta = match fs::symlink_metadata(&path) {
360- Ok(meta) => meta,
361- Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
362- Err(err) => return Err(err).with_context(|| format!("cannot read {}", path.display())),
363- };
364- let planned = |action, contents, done: &str, would: &str| Planned {
365- name: CLAUDE_FILE,
366- path: path.clone(),
563+/// What `name`, `CLAUDE.md` or `GEMINI.md`, needs, or `None` when there is
564+/// no such file. `earlier` are the files planned before it, `AGENTS.md`
565+/// first: a file that is one of them under another name needs nothing.
566+fn plan_include(
567+ dir: &Path,
568+ name: &'static str,
569+ roots: &[PathBuf],
570+ guides: &[(PathBuf, FileId)],
571+ earlier: &[Planned],
572+) -> Result<Option<Planned>> {
573+ let planned = |target, action, contents, said: String, would: String| Planned {
574+ name,
575+ target,
367576 action,
368577 contents,
369- done: done.to_owned(),
370- would: would.to_owned(),
578+ done: said,
579+ would,
580+ };
581+ let same = |other: &str| {
582+ let said = if other == AGENTS_FILE {
583+ format!("{name} is {AGENTS_FILE} under another name: it holds the section itself.")
584+ } else {
585+ format!("{name} is {other} under another name.")
586+ };
587+ (said.clone(), said)
371588 };
372- let includes = "CLAUDE.md includes AGENTS.md already.";
373- let already = planned(Action::Unchanged, None, includes, includes);
374- // A CLAUDE.md that is AGENTS.md under another name, through a symbolic
375- // link, holds the section itself.
376- let agents = dir.join(AGENTS_FILE);
377- let is_agents = match (fs::canonicalize(&path), fs::canonicalize(&agents)) {
378- (Ok(claude), Ok(agents)) => claude == agents,
379- _ => false,
589+ let target = match locate_file(dir, name, roots, guides)? {
590+ Located::Missing => return Ok(None),
591+ Located::Dangling(to) => {
592+ // A link to the AGENTS.md this run creates holds the section;
593+ // a link to anything else that is missing has nothing to add
594+ // the line to.
595+ let agents = &earlier[0];
596+ let to_agents = to == Path::new(AGENTS_FILE)
597+ || to == Path::new("./AGENTS.md")
598+ || dir.join(&to) == agents.target.path;
599+ if !to_agents || agents.action != Action::Create {
600+ return Ok(None);
601+ }
602+ let (said, would) = same(AGENTS_FILE);
603+ let target = Target {
604+ shown: agents.target.shown.clone(),
605+ ..Target::new_file(dir, name)
606+ };
607+ return Ok(Some(planned(target, Action::Unchanged, None, said, would)));
608+ }
609+ Located::File(target) => target,
380610 };
381- if is_agents
382- || (meta.file_type().is_symlink()
383- && fs::read_link(&path).is_ok_and(|target| {
384- target == Path::new(AGENTS_FILE) || target == Path::new("./AGENTS.md")
385- }))
611+ if let Some(other) = earlier
612+ .iter()
613+ .find(|file| file.target.id.is_some() && file.target.id == target.id)
386614 {
387- return Ok(Some(already));
388- }
389- let Some(text) = read_text(&path)? else {
390- // A symbolic link to nothing: there is nothing to add the line to.
391- return Ok(None);
392- };
615+ let (said, would) = same(other.name);
616+ return Ok(Some(planned(target, Action::Unchanged, None, said, would)));
617+ }
618+ let text = target.read()?.unwrap_or_default();
393619 if includes_agents(&text) {
394- return Ok(Some(already));
620+ let said = format!("{} includes {AGENTS_FILE} already.", target.called(name));
621+ return Ok(Some(planned(
622+ target,
623+ Action::Unchanged,
624+ None,
625+ said.clone(),
626+ said,
627+ )));
395628 }
629+ if let Some(line) = open_fence(&text) {
630+ bail!(
631+ "{} ends inside a fenced code block, which opens on line {line} and is never closed: the line {INCLUDE} would be read as code there. Close the block, then run the command again: {NOTHING}",
632+ target.shown
633+ );
634+ }
635+ let called = target.called(name);
396636 Ok(Some(planned(
637+ target,
397638 Action::Update,
398639 Some(add_include(&text)),
399- "Added @AGENTS.md to CLAUDE.md.",
400- "Would add @AGENTS.md to CLAUDE.md.",
640+ format!("Added {INCLUDE} to {called}."),
641+ format!("Would add {INCLUDE} to {called}."),
401642 )))
402643 }
403644
@@ -414,21 +655,28 @@
414655 each in a braid workspace of its own. Braid is pre-alpha: git stays the
415656 source of truth, and `braid git sync` keeps the git remote in step.
416657
658+- **Only where braid is set up:** in a checkout whose root has a `.braid`
659+ directory. Without one (a fresh clone, CI, another machine), skip this
660+ section and work with git, as the project's other rules say; set braid
661+ up only if the user asks for it (<https://braid.elffuss.com/agents.md>
662+ says how). With `.braid` but no `braid` command, braid is not on `PATH`:
663+ try `\"$HOME/.cargo/bin/braid\"`, or ask the user to install it.
417664 - **Never edit files, `git add`, `git commit` or `git push` in the project
418- root.** It is the shared checkout: work only in your workspace.
419-- **Start** from the project root, with a workspace named for your session
420- (letters, digits, `.`, `_` or `-`; `braid workspace list` shows the names
421- taken). The commands here call it `agent-1`: use your own name.
665+ root.** It is the shared checkout, where the user works: work only in
666+ your workspace.
667+- **Start** with a workspace named for your session: 1 to 64 ASCII
668+ letters, digits, `.`, `_` or `-`, starting with a letter or a digit
669+ (`braid workspace list` shows the names taken). The commands here call it
670+ `agent-1`: use your own name. From the project root, this creates it in
671+ `.braid/work/agent-1`:
422672
423673 ```bash
424- braid workspace add agent-1 .braid/work/agent-1 --track {branch}
674+ braid workspace add agent-1 --track {branch}
425675 cd .braid/work/agent-1
426676 ```
427677
428-- **Work** in `.braid/work/agent-1`: edit, build and test there. There is
429- no `.git` in it, so `git` there acts on the shared checkout: use braid.
430- Record and land from the workspace, naming your session with `--agent`
431- (or `BRAID_AGENT`) every time:
678+- **Work** in `.braid/work/agent-1`: edit, build and test there. Record and
679+ land from the workspace, naming your session with `--agent` every time:
432680
433681 ```bash
434682 braid --agent agent-1 status --json
@@ -438,28 +686,50 @@
438686
439687 If your shell does not stay in the workspace between commands, add
440688 `--workspace agent-1` and run them from the project root.
441-- **Conflicts:** `land` exits with status 2, prints `\"outcome\": \"conflicts\"`
442- with `--json`, and leaves `{branch}` where it was. Run
689+- **No git in the workspace.** Its `.git` file points nowhere, so `git`
690+ fails there. Never get around that (`git -C`, `GIT_DIR`): `git stash`,
691+ `reset`, `checkout`, `restore`, `clean`, `add` or `commit` would act on
692+ the user's checkout. A build or test script that finds the project with
693+ git fails in the workspace too: run its steps yourself. To review an
694+ edit, from the workspace's root, compare the file with the workspace's
695+ `base`, which `status --json` gives:
696+ `braid cat-object <base>:<path> | diff -u - <path>`. To undo it, write
697+ the base's version back with `braid cat-object <base>:<path> > <path>`,
698+ or delete a file you added.
699+- **Before each commit**, read `braid status`. There is no staging area:
700+ `commit` records every change in the workspace, and only `.gitignore` and
701+ `.braidignore` apply there, not `.git/info/exclude` or a global excludes
702+ file, so list files that must stay local in `.braidignore`. Braid runs no
703+ git hooks: run the project's checks yourself before you land.
704+- **Conflicts:** `land` and `update` exit with status 2, the `outcome` in
705+ their JSON is `conflicts`, and `{branch}` does not move. After `land`, run
443706 `braid --agent agent-1 update`, which writes conflict markers into the
444707 files; fix them (`braid resolve <path>` settles conflicts that are not
445708 about content), then `commit` (the message is kept) and `land` again. In
446- the JSON, `next` says what to run.
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`.
447712 - **Before a new task**, `braid --agent agent-1 update` brings your
448713 workspace onto `{branch}`.
449-- **Done:** once everything has landed, run `braid workspace remove agent-1`
450- from the project root.
714+- **When you finish**, tell the user that what you landed is on braid's
715+ `{branch}` only: their checkout and the git remote get it once someone
716+ runs this from the project root.
717+
718+ ```bash
719+ braid --agent agent-1 git sync \"$(git remote get-url origin)\" --branch {branch}
720+ git pull --ff-only
721+ ```
722+
723+ Offer to run it: when to sync is the user's call. Once everything has
724+ landed, `braid workspace remove agent-1`, from the project root, removes
725+ your workspace.
451726 - Changesets are signed by `BRAID_AUTHOR` (`\"Name <email>\"`), or else by the
452727 `name` and `email` in `.braid/config`.
453728 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
454- than 1 MiB wait for `braid track <path>`. Never track a secret.
455-- `braid undo` reverts the newest operation in the repository, whoever made
456- it: read `braid op log` first.
457-- `braid git sync \"$(git remote get-url origin)\" --branch {branch}` sends what
458- landed to the git remote and brings in what others pushed there. Run it
459- when the user asks for it.
460-- No `.braid` directory in the project root, or no `braid` command? Braid is
461- not set up in this checkout: follow <https://braid.elffuss.com/agents.md>,
462- or ask the user.
729+ than 1 MiB wait for `braid track <path>`. Never track a secret: move it
730+ out of the workspace.
731+- `braid --agent agent-1 undo` reverts the newest operation in the
732+ repository, whoever made it: read `braid op log` first.
463733 {END}
464734 "
465735 )
@@ -473,30 +743,120 @@
473743 line.len() - text.len() <= 3 && text == marker
474744 }
475745
476-/// Where the braid section is in `text`: from the start of its start
477-/// marker's line to the end of its end marker's line. `None` when there are
478-/// no markers; an error that says where they are when they do not pair up.
479-pub(crate) fn find_section(text: &str) -> Result<Option<Range<usize>>, String> {
746+/// The fence a line opens or closes, as CommonMark reads one: indented by
747+/// three spaces at most, then three or more backticks or tildes, with no
748+/// backtick after backticks. Gives the character, how many of it there
749+/// are, and the rest of the line.
750+fn fence(line: &str) -> Option<(u8, usize, &str)> {
751+ let line = line.trim_end_matches(['\n', '\r']);
752+ let text = line.trim_start_matches(' ');
753+ if line.len() - text.len() > 3 {
754+ return None;
755+ }
756+ let mark = *text.as_bytes().first()?;
757+ if mark != b'`' && mark != b'~' {
758+ return None;
759+ }
760+ let count = text.bytes().take_while(|byte| *byte == mark).count();
761+ let rest = &text[count..];
762+ (count >= 3 && !(mark == b'`' && rest.contains('`'))).then_some((mark, count, rest))
763+}
764+
765+/// Follows the fenced code blocks of a Markdown text, a line at a time.
766+#[derive(Debug, Default)]
767+struct Fences {
768+ /// The block open after the last line: its fence's character and
769+ /// length, and the line it opened on.
770+ open: Option<(u8, usize, usize)>,
771+}
772+
773+impl Fences {
774+ /// Whether line number `number` is code: a fence, or inside a block.
775+ fn code(&mut self, line: &str, number: usize) -> bool {
776+ match (self.open, fence(line)) {
777+ (Some((mark, count, _)), Some((found, length, rest)))
778+ if found == mark && length >= count && rest.trim().is_empty() =>
779+ {
780+ self.open = None;
781+ true
782+ }
783+ (Some(_), _) => true,
784+ (None, Some((mark, count, _))) => {
785+ self.open = Some((mark, count, number));
786+ true
787+ }
788+ (None, None) => false,
789+ }
790+ }
791+}
792+
793+/// `line`, the first of a text, without the byte order mark an editor may
794+/// have put before it.
795+fn without_bom(line: &str) -> &str {
796+ line.strip_prefix('\u{feff}').unwrap_or(line)
797+}
798+
799+/// The line a fenced code block that `text` never closes opens on.
800+fn open_fence(text: &str) -> Option<usize> {
801+ let mut fences = Fences::default();
802+ for (index, line) in text.lines().enumerate() {
803+ let line = if index == 0 { without_bom(line) } else { line };
804+ fences.code(line, index + 1);
805+ }
806+ fences.open.map(|(_, _, line)| line)
807+}
808+
809+/// What a Markdown text holds of the braid section.
810+#[derive(Debug, Default, PartialEq, Eq)]
811+pub(crate) struct Scanned {
812+ /// The section: from the start of its start marker's line to the end of
813+ /// its end marker's line.
814+ pub(crate) section: Option<Range<usize>>,
815+ /// The line a fenced code block that the text never closes opens on.
816+ pub(crate) open_fence: Option<usize>,
817+}
818+
819+/// Where the braid section is in `text`, with the markers inside fenced
820+/// code blocks left out, as examples rather than markers. An error that
821+/// says where they are when they do not pair up.
822+pub(crate) fn scan_section(text: &str) -> Result<Scanned, String> {
480823 let mut starts = Vec::new();
481824 let mut ends = Vec::new();
825+ let mut fences = Fences::default();
482826 let mut offset = 0;
483827 for (index, line) in text.split_inclusive('\n').enumerate() {
484- if is_marker(line, START) {
485- starts.push((index + 1, offset));
486- } else if is_marker(line, END) {
487- ends.push((index + 1, offset + line.len()));
828+ // A byte order mark is not part of the first line: the section
829+ // starts after it, so that it stays.
830+ let skip = if index == 0 {
831+ line.len() - without_bom(line).len()
832+ } else {
833+ 0
834+ };
835+ let body = &line[skip..];
836+ if !fences.code(body, index + 1) {
837+ if is_marker(body, START) {
838+ starts.push((index + 1, offset + skip));
839+ } else if is_marker(body, END) {
840+ ends.push((index + 1, offset + line.len()));
841+ }
488842 }
489843 offset += line.len();
490844 }
491- match (starts.as_slice(), ends.as_slice()) {
492- ([], []) => Ok(None),
493- ([(first, from)], [(last, to)]) if first < last => Ok(Some(*from..*to)),
494- _ => Err(format!(
495- "`{START}` is on {}, `{END}` on {}, and there must be one of each, the start first",
496- line_list(&starts),
497- line_list(&ends)
498- )),
499- }
845+ let section = match (starts.as_slice(), ends.as_slice()) {
846+ ([], []) => None,
847+ ([(first, from)], [(last, to)]) if first < last => Some(*from..*to),
848+ _ => {
849+ return Err(format!(
850+ "`{START}` is on {}, `{END}` on {}, and there must be one of each, the start first",
851+ line_list(&starts),
852+ line_list(&ends)
853+ ));
854+ }
855+ };
856+ Ok(Scanned {
857+ section,
858+ open_fence: fences.open.map(|(_, _, line)| line),
859+ })
500860 }
501861
502862 /// `no line`, `line 3`, `lines 3 and 9`, `lines 3, 9 and 12`.
@@ -538,11 +898,13 @@
538898 let section = in_line_ends_of(text, section);
539899 let mut out = String::with_capacity(text.len() + section.len() + 2 * end.len());
540900 out.push_str(text);
541- if !out.is_empty() {
901+ if !without_bom(text).is_empty() {
542902 if !out.ends_with('\n') {
543903 out.push_str(end);
544904 }
545- if !out.trim_end_matches(['\n', '\r']).is_empty() && !ends_with_blank_line(&out) {
905+ if !without_bom(&out).trim_end_matches(['\n', '\r']).is_empty()
906+ && !ends_with_blank_line(&out)
907+ {
546908 out.push_str(end);
547909 }
548910 }
@@ -559,23 +921,70 @@
559921 body.is_empty() || body.ends_with('\n')
560922 }
561923
562-/// The branch a section was written for, as its first comment says.
563-fn named_branch(section: &str) -> Option<String> {
564- let (_, rest) = section.split_once(BRANCH_NOTE)?;
924+/// The branch a section was written for, as its first comment says, if
925+/// the section can name it.
926+pub(crate) fn named_branch(section: &str) -> Option<String> {
927+ let line = section.lines().find(|line| line.contains(BRANCH_NOTE))?;
928+ let (_, rest) = line.split_once(BRANCH_NOTE)?;
565929 let (name, _) = rest.split_once(')')?;
566- braid_git::is_branch_name(name).then(|| name.to_owned())
930+ is_section_branch(name).then(|| name.to_owned())
931+}
932+
933+/// `line` without its code spans: the text between two runs of the same
934+/// number of backticks. A run that nothing closes stays, as text.
935+fn without_code_spans(line: &str) -> String {
936+ let mut out = String::with_capacity(line.len());
937+ let mut rest = line;
938+ while let Some(at) = rest.find('`') {
939+ out.push_str(&rest[..at]);
940+ let run = rest[at..].bytes().take_while(|byte| *byte == b'`').count();
941+ let after = &rest[at + run..];
942+ match closing_run(after, run) {
943+ Some(end) => {
944+ out.push(' ');
945+ rest = &after[end..];
946+ }
947+ None => {
948+ out.push_str(&rest[at..at + run]);
949+ rest = after;
950+ }
951+ }
952+ }
953+ out.push_str(rest);
954+ out
955+}
956+
957+/// Where the first run of exactly `run` backticks in `text` ends.
958+fn closing_run(text: &str, run: usize) -> Option<usize> {
959+ let mut from = 0;
960+ while let Some(at) = text[from..].find('`') {
961+ let start = from + at;
962+ let length = text[start..]
963+ .bytes()
964+ .take_while(|byte| *byte == b'`')
965+ .count();
966+ if length == run {
967+ return Some(start + length);
968+ }
969+ from = start + length;
970+ }
971+ None
567972 }
568973
569-/// Whether a `CLAUDE.md` includes `AGENTS.md`: a word `@AGENTS.md` or
570-/// `@./AGENTS.md`, as Claude Code reads its imports.
974+/// Whether a `CLAUDE.md` or `GEMINI.md` includes `AGENTS.md`: a word
975+/// `@AGENTS.md` or `@./AGENTS.md` outside code, as Claude Code reads its
976+/// imports. Neither a code span nor a fenced code block imports anything.
571977 pub(crate) fn includes_agents(text: &str) -> bool {
572- text.lines().any(|line| {
573- line.split_whitespace().any(|word| {
574- let word = word
575- .trim_start_matches('(')
576- .trim_end_matches([',', ';', ':', ')']);
577- word == INCLUDE || word == "@./AGENTS.md"
578- })
978+ let mut fences = Fences::default();
979+ text.lines().enumerate().any(|(index, line)| {
980+ let line = if index == 0 { without_bom(line) } else { line };
981+ !fences.code(line, index + 1)
982+ && without_code_spans(line).split_whitespace().any(|word| {
983+ let word = word
984+ .trim_start_matches('(')
985+ .trim_end_matches([',', ';', ':', ')']);
986+ word == INCLUDE || word == "@./AGENTS.md"
987+ })
579988 })
580989 }
581990
@@ -591,36 +1000,256 @@
5911000 out
5921001 }
5931002
594-/// A file's text, or `None` when there is no such file.
595-fn read_text(path: &Path) -> Result<Option<String>> {
596- match fs::read(path) {
597- Ok(bytes) => String::from_utf8(bytes)
1003+/// What tells two names of one file apart from two files: the device and
1004+/// the inode where there are hard links, the canonical path elsewhere.
1005+#[cfg(unix)]
1006+type FileId = (u64, u64);
1007+#[cfg(not(unix))]
1008+type FileId = PathBuf;
1009+
1010+#[cfg(unix)]
1011+fn file_id(meta: &fs::Metadata, _path: &Path) -> FileId {
1012+ use std::os::unix::fs::MetadataExt;
1013+ (meta.dev(), meta.ino())
1014+}
1015+
1016+#[cfg(not(unix))]
1017+fn file_id(_meta: &fs::Metadata, path: &Path) -> FileId {
1018+ fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1019+}
1020+
1021+/// How many names the file has.
1022+#[cfg(unix)]
1023+fn names_of(meta: &fs::Metadata) -> u64 {
1024+ use std::os::unix::fs::MetadataExt;
1025+ meta.nlink()
1026+}
1027+
1028+#[cfg(not(unix))]
1029+fn names_of(_meta: &fs::Metadata) -> u64 {
1030+ 1
1031+}
1032+
1033+/// The guides of `dir` that are regular files, not symbolic links, with
1034+/// what tells them apart: the names a file with hard links may have here.
1035+fn guide_files(dir: &Path) -> Vec<(PathBuf, FileId)> {
1036+ [AGENTS_FILE, CLAUDE_FILE, GEMINI_FILE]
1037+ .iter()
1038+ .filter_map(|name| {
1039+ let path = dir.join(name);
1040+ let meta = fs::symlink_metadata(&path).ok()?;
1041+ meta.is_file().then(|| {
1042+ let id = file_id(&meta, &path);
1043+ (path, id)
1044+ })
1045+ })
1046+ .collect()
1047+}
1048+
1049+/// The file a guide is, once checked: what is read and written.
1050+#[derive(Clone, Debug)]
1051+struct Target {
1052+ /// Where the text is: the name itself, or the file its link points to.
1053+ path: PathBuf,
1054+ /// That file as the output names it: its path from the project's
1055+ /// directory, or the whole path when it is elsewhere in the repository.
1056+ shown: String,
1057+ /// Whether the file exists.
1058+ exists: bool,
1059+ /// Whether it is written in place rather than replaced, since it has
1060+ /// hard links, all of them guides of the project.
1061+ in_place: bool,
1062+ /// What tells it from other files, when it exists.
1063+ id: Option<FileId>,
1064+}
1065+
1066+impl Target {
1067+ /// A file that does not exist yet: `name` in `dir`.
1068+ fn new_file(dir: &Path, name: &str) -> Target {
1069+ Target {
1070+ path: dir.join(name),
1071+ shown: name.to_owned(),
1072+ exists: false,
1073+ in_place: false,
1074+ id: None,
1075+ }
1076+ }
1077+
1078+ /// How the output names the file known as `name`: by that name, and by
1079+ /// the file its link points to when that is another.
1080+ fn called(&self, name: &str) -> String {
1081+ if self.shown == name {
1082+ name.to_owned()
1083+ } else {
1084+ format!("{name} ({}, which it links to)", self.shown)
1085+ }
1086+ }
1087+
1088+ /// The file's text, or `None` when it does not exist.
1089+ fn read(&self) -> Result<Option<String>> {
1090+ if !self.exists {
1091+ return Ok(None);
1092+ }
1093+ let bytes =
1094+ fs::read(&self.path).with_context(|| format!("cannot read {}", self.path.display()))?;
1095+ String::from_utf8(bytes)
5981096 .map(Some)
599- .map_err(|_| anyhow!("{} is not UTF-8 text: nothing was written", path.display())),
600- Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
601- Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())),
602- }
603-}
604-
605-/// Writes `contents` to `path` through a temporary file and a rename, so
606-/// that the file is never seen half written. A symbolic link stays one: the
607-/// file it points to is the one replaced, and keeps its permissions.
608-fn write_file(path: &Path, contents: &str) -> Result<()> {
609- let target = match fs::canonicalize(path) {
610- Ok(target) => target,
611- Err(err) if err.kind() == io::ErrorKind::NotFound => {
612- if fs::symlink_metadata(path).is_ok() {
613- bail!(
614- "{} is a symbolic link to a file that does not exist",
615- path.display()
616- );
1097+ .map_err(|_| anyhow!("{} is not UTF-8 text: {NOTHING}", self.shown))
1098+ }
1099+}
1100+
1101+/// What a guide's name leads to.
1102+enum Located {
1103+ /// Nothing has the name.
1104+ Missing,
1105+ /// A symbolic link to a file that does not exist; where it points.
1106+ Dangling(PathBuf),
1107+ /// A file braid may write.
1108+ File(Target),
1109+}
1110+
1111+/// Finds the file `name` of `dir` is, and checks that braid may write it:
1112+/// a regular file, or a symbolic link to one inside `roots`, the project's
1113+/// directory and the repository's root; not read-only; and with no hard
1114+/// link but the guides of `dir`. Every check runs before anything is read,
1115+/// with or without `--dry-run`, so that a dry run fails as the real run
1116+/// would, and a FIFO is never opened.
1117+fn locate_file(
1118+ dir: &Path,
1119+ name: &'static str,
1120+ roots: &[PathBuf],
1121+ guides: &[(PathBuf, FileId)],
1122+) -> Result<Located> {
1123+ let path = dir.join(name);
1124+ let own = match fs::symlink_metadata(&path) {
1125+ Ok(meta) => meta,
1126+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Located::Missing),
1127+ Err(err) => return Err(err).with_context(|| format!("cannot read {}", path.display())),
1128+ };
1129+ let linked = own.file_type().is_symlink();
1130+ let (path, meta) = if linked {
1131+ let target = match fs::canonicalize(&path) {
1132+ Ok(target) => target,
1133+ Err(err) if err.kind() == io::ErrorKind::NotFound => {
1134+ return Ok(Located::Dangling(fs::read_link(&path).unwrap_or_default()));
1135+ }
1136+ Err(err) => {
1137+ return Err(err).with_context(|| format!("cannot follow {}", path.display()));
1138+ }
1139+ };
1140+ let meta =
1141+ fs::metadata(&target).with_context(|| format!("cannot read {}", target.display()))?;
1142+ (target, meta)
1143+ } else {
1144+ (path, own)
1145+ };
1146+ let shown = if linked {
1147+ match path.strip_prefix(&roots[0]) {
1148+ Ok(inside) => inside.to_string_lossy().into_owned(),
1149+ Err(_) => path.to_string_lossy().into_owned(),
1150+ }
1151+ } else {
1152+ name.to_owned()
1153+ };
1154+ if !meta.is_file() {
1155+ let what = if linked {
1156+ format!("{name}, a link to {shown},")
1157+ } else {
1158+ name.to_owned()
1159+ };
1160+ bail!("{what} is not a regular file: {NOTHING}");
1161+ }
1162+ if linked && !roots.iter().any(|root| path.starts_with(root)) {
1163+ bail!(
1164+ "{name} is a link to {}, outside the project: other projects may read that file too. Replace the link with a copy of the file, or point it inside the project: {NOTHING}",
1165+ path.display()
1166+ );
1167+ }
1168+ if meta.permissions().readonly() {
1169+ bail!("{shown} is read-only: make it writable, then run the command again: {NOTHING}");
1170+ }
1171+ let id = file_id(&meta, &path);
1172+ let mut known = vec![path.clone()];
1173+ for (other, other_id) in guides {
1174+ if *other_id == id && !known.contains(other) {
1175+ known.push(other.clone());
1176+ }
1177+ }
1178+ let names = names_of(&meta);
1179+ if names > known.len() as u64 {
1180+ bail!(
1181+ "{shown} has hard links besides the {AGENTS_FILE}, {CLAUDE_FILE} and {GEMINI_FILE} here: writing it would change the file under those names too. Replace it with a copy, then run the command again: {NOTHING}"
1182+ );
1183+ }
1184+ Ok(Located::File(Target {
1185+ path,
1186+ shown,
1187+ exists: true,
1188+ in_place: names > 1,
1189+ id: Some(id),
1190+ }))
1191+}
1192+
1193+/// Writes every planned file that changes. Each is first written whole to
1194+/// a temporary file next to it, so that a failure there leaves every file
1195+/// as it was; then each replaces its file with a rename, so that no file
1196+/// is ever seen half written. A file with hard links is written in place,
1197+/// last. A failure after the first file is replaced says which were.
1198+fn write_all(planned: &[Planned]) -> Result<()> {
1199+ let changing: Vec<(&Planned, &str)> = planned
1200+ .iter()
1201+ .filter_map(|file| file.contents.as_deref().map(|contents| (file, contents)))
1202+ .collect();
1203+ let mut staged: Vec<(&Planned, PathBuf)> = Vec::new();
1204+ for (file, contents) in changing.iter().filter(|(file, _)| !file.target.in_place) {
1205+ match stage(&file.target.path, contents) {
1206+ Ok(temp) => staged.push((file, temp)),
1207+ Err(err) => {
1208+ for (_, temp) in &staged {
1209+ let _ = fs::remove_file(temp);
1210+ }
1211+ return Err(failed(file, &err, &[]));
6171212 }
618- path.to_path_buf()
6191213 }
620- Err(err) => return Err(err).with_context(|| format!("cannot open {}", path.display())),
1214+ }
1215+ let mut written: Vec<&str> = Vec::new();
1216+ let mut renames = staged.into_iter();
1217+ while let Some((file, temp)) = renames.next() {
1218+ if let Err(err) = fs::rename(&temp, &file.target.path) {
1219+ let _ = fs::remove_file(&temp);
1220+ for (_, rest) in renames {
1221+ let _ = fs::remove_file(rest);
1222+ }
1223+ return Err(failed(file, &err, &written));
1224+ }
1225+ written.push(&file.target.shown);
1226+ }
1227+ for (file, contents) in changing.iter().filter(|(file, _)| file.target.in_place) {
1228+ if let Err(err) = write_in_place(&file.target.path, contents) {
1229+ return Err(failed(file, &err, &written));
1230+ }
1231+ written.push(&file.target.shown);
1232+ }
1233+ Ok(())
1234+}
1235+
1236+/// The error for `file`, which could not be written, saying which files
1237+/// were.
1238+fn failed(file: &Planned, err: &io::Error, written: &[&str]) -> anyhow::Error {
1239+ let shown = &file.target.shown;
1240+ let done = match written {
1241+ [] => NOTHING.to_owned(),
1242+ [one] => format!("{one} was written, {shown} was not"),
1243+ several => format!("{} were written, {shown} was not", listed(several)),
6211244 };
622- let (Some(parent), Some(name)) = (target.parent(), target.file_name()) else {
623- bail!("cannot write {}", target.display());
1245+ anyhow!("cannot write {shown}: {err}; {done}")
1246+}
1247+
1248+/// Writes `contents` to a new temporary file next to `path`, with the
1249+/// permissions `path` has, and returns its path once it is on disk.
1250+fn stage(path: &Path, contents: &str) -> io::Result<PathBuf> {
1251+ let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
1252+ return Err(io::Error::other("it has no directory"));
6241253 };
6251254 let name = name.to_string_lossy();
6261255 let mut attempt = 0u32;
@@ -631,24 +1260,31 @@
6311260 Err(err) if err.kind() == io::ErrorKind::AlreadyExists && attempt < 64 => {
6321261 attempt += 1;
6331262 }
634- Err(err) => {
635- return Err(err).with_context(|| format!("cannot write in {}", parent.display()));
636- }
1263+ Err(err) => return Err(err),
6371264 }
6381265 };
6391266 let mut written = || -> io::Result<()> {
640- if let Ok(meta) = fs::metadata(&target) {
1267+ if let Ok(meta) = fs::metadata(path) {
6411268 fs::set_permissions(&temp, meta.permissions())?;
6421269 }
6431270 file.write_all(contents.as_bytes())?;
644- file.sync_all()?;
645- fs::rename(&temp, &target)
1271+ file.sync_all()
6461272 };
647- if let Err(err) = written() {
648- let _ = fs::remove_file(&temp);
649- return Err(err).with_context(|| format!("cannot write {}", target.display()));
1273+ match written() {
1274+ Ok(()) => Ok(temp),
1275+ Err(err) => {
1276+ let _ = fs::remove_file(&temp);
1277+ Err(err)
1278+ }
6501279 }
651- Ok(())
1280+}
1281+
1282+/// Writes `contents` over the file at `path`, keeping the file and so
1283+/// every name it has.
1284+fn write_in_place(path: &Path, contents: &str) -> io::Result<()> {
1285+ let mut file = OpenOptions::new().write(true).truncate(true).open(path)?;
1286+ file.write_all(contents.as_bytes())?;
1287+ file.sync_all()
6521288 }
6531289
6541290 #[cfg(test)]
@@ -658,6 +1294,10 @@
6581294 const ABOVE: &str = "# Project\n\nRules of our own.\n\n";
6591295 const BELOW: &str = "\n## More rules\n\nKept as they are.\n";
6601296
1297+ fn find(text: &str) -> Result<Option<Range<usize>>, String> {
1298+ scan_section(text).map(|scanned| scanned.section)
1299+ }
1300+
6611301 #[test]
6621302 fn the_section_names_the_branch_and_holds_no_marker_inside() {
6631303 let text = section("trunk");
@@ -665,17 +1305,66 @@
6651305 assert!(text.ends_with(&format!("\n{END}\n")));
6661306 assert!(text.contains("--track trunk\n"));
6671307 assert!(text.contains("land their changes on `trunk`"));
668- assert!(text.contains("--branch trunk`"));
1308+ assert!(text.contains("--branch trunk\n"));
6691309 assert!(
6701310 !text.contains("`main`") && !text.contains(" main"),
6711311 "{text}"
6721312 );
6731313 assert_eq!(named_branch(&text).as_deref(), Some("trunk"));
674- // The markers appear once each, on their own lines.
675- assert_eq!(find_section(&text), Ok(Some(0..text.len())));
1314+ // The markers appear once each, on their own lines, and the
1315+ // section's own code blocks are closed.
1316+ assert_eq!(
1317+ scan_section(&text),
1318+ Ok(Scanned {
1319+ section: Some(0..text.len()),
1320+ open_fence: None
1321+ })
1322+ );
6761323 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
6771324 }
6781325
1326+ #[test]
1327+ fn branches_the_section_can_name_read_back_exactly() {
1328+ for good in [
1329+ "main",
1330+ "master",
1331+ "trunk",
1332+ "release-1.2",
1333+ "feature/x.y_z-1",
1334+ "v1.x/beta",
1335+ "UPPER_case",
1336+ ] {
1337+ assert!(is_section_branch(good), "{good}");
1338+ assert_eq!(named_branch(&section(good)).as_deref(), Some(good));
1339+ }
1340+ for bad in [
1341+ "",
1342+ "feat(x)",
1343+ "a;b",
1344+ "a;touch${IFS}pwned",
1345+ "q$(id)",
1346+ "x`id`",
1347+ "it's",
1348+ "a|b",
1349+ "a>b",
1350+ "a b",
1351+ "-x",
1352+ "--no-claude",
1353+ "a..b",
1354+ "x.lock",
1355+ "tags/v1",
1356+ "braid/git-map",
1357+ "rama-ñ",
1358+ ] {
1359+ assert!(!is_section_branch(bad), "{bad}");
1360+ }
1361+ // A section an older braid wrote for a name it cannot hold names
1362+ // nothing, rather than a part of it.
1363+ let old =
1364+ format!("{START}\n<!-- Written by `braid agents init` (branch: feat(x)). -->\n{END}\n");
1365+ assert_eq!(named_branch(&old), None);
1366+ }
1367+
6791368 #[test]
6801369 fn a_section_is_appended_after_a_blank_line() {
6811370 let new = section("main");
@@ -695,7 +1384,7 @@
6951384 crlf,
6961385 format!("# Rules\r\n\r\n{}", new.replace('\n', "\r\n"))
6971386 );
698- let range = find_section(&crlf).unwrap().unwrap();
1387+ let range = find(&crlf).unwrap().unwrap();
6991388 assert_eq!(replace_section(&crlf, range, &new), crlf);
7001389 }
7011390
@@ -703,12 +1392,12 @@
7031392 fn only_the_text_between_the_markers_changes() {
7041393 let old = format!("{START}\nan older section\n{END}\n");
7051394 let text = format!("{ABOVE}{old}{BELOW}");
706- let range = find_section(&text).unwrap().unwrap();
1395+ let range = find(&text).unwrap().unwrap();
7071396 assert_eq!(&text[range.clone()], old);
7081397 let new = replace_section(&text, range, &section("main"));
7091398 assert_eq!(new, format!("{ABOVE}{}{BELOW}", section("main")));
7101399 // Again: nothing changes.
711- let range = find_section(&new).unwrap().unwrap();
1400+ let range = find(&new).unwrap().unwrap();
7121401 assert_eq!(replace_section(&new, range, &section("main")), new);
7131402 // The older section named no branch.
7141403 assert_eq!(named_branch(&old), None);
@@ -717,15 +1406,76 @@
7171406 #[test]
7181407 fn markers_may_be_indented_a_little_but_must_be_alone() {
7191408 let text = format!(" {START} \nx\n{END}\n");
720- assert_eq!(find_section(&text), Ok(Some(0..text.len())));
1409+ assert_eq!(find(&text), Ok(Some(0..text.len())));
7211410 for not_markers in [
7221411 format!(" {START}\n{END}\n"),
7231412 format!("see `{START}`\n{END}\n"),
7241413 format!("{START} and more\n{END}\n"),
7251414 ] {
726- assert!(find_section(&not_markers).is_err(), "{not_markers:?}");
1415+ assert!(find(&not_markers).is_err(), "{not_markers:?}");
1416+ }
1417+ assert_eq!(find("no markers at all\n"), Ok(None));
1418+ }
1419+
1420+ #[test]
1421+ fn markers_in_fenced_code_blocks_are_examples() {
1422+ let example = format!("```markdown\n{START}\n(the rules braid writes)\n{END}\n```\n");
1423+ let text = format!("# Rules\n\n{example}");
1424+ assert_eq!(
1425+ scan_section(&text),
1426+ Ok(Scanned {
1427+ section: None,
1428+ open_fence: None
1429+ })
1430+ );
1431+ // Next to a real section, the example is left alone.
1432+ let real = section("main");
1433+ let both = format!("{text}\n{real}");
1434+ let range = find(&both).unwrap().unwrap();
1435+ assert_eq!(&both[range], real);
1436+ // Tildes, longer fences, and a fence that only a fence as long
1437+ // closes.
1438+ for fenced in [
1439+ format!("~~~\n{START}\n~~~\n"),
1440+ format!("````text\n```\n{END}\n````\n"),
1441+ format!(" ```\n{START}\n{END}\n ```\n"),
1442+ ] {
1443+ assert_eq!(find(&fenced), Ok(None), "{fenced:?}");
7271444 }
728- assert_eq!(find_section("no markers at all\n"), Ok(None));
1445+ // Four spaces make no fence, and backticks in a backtick fence's
1446+ // info string make none either.
1447+ assert!(find(&format!(" ```\n{START}\n")).is_err());
1448+ assert!(find(&format!("``` a`b\n{START}\n")).is_err());
1449+ // A block that is never closed hides what follows it, and says
1450+ // where it opens.
1451+ let open = format!("# Rules\n\n```bash\nmake test\n{START}\n{END}\n");
1452+ assert_eq!(
1453+ scan_section(&open),
1454+ Ok(Scanned {
1455+ section: None,
1456+ open_fence: Some(3)
1457+ })
1458+ );
1459+ assert_eq!(open_fence(&open), Some(3));
1460+ assert_eq!(open_fence(&text), None);
1461+ }
1462+
1463+ #[test]
1464+ fn a_byte_order_mark_before_the_start_marker_stays() {
1465+ let section = section("main");
1466+ let text = format!("\u{feff}{section}");
1467+ let range = find(&text).unwrap().unwrap();
1468+ assert_eq!(range, '\u{feff}'.len_utf8()..text.len());
1469+ assert_eq!(replace_section(&text, range, &section), text);
1470+ assert!(includes_agents("\u{feff}@AGENTS.md\n"));
1471+ assert_eq!(
1472+ append_section("\u{feff}", &section),
1473+ format!("\u{feff}{section}")
1474+ );
1475+ assert_eq!(
1476+ append_section("\u{feff}# Rules\n", &section),
1477+ format!("\u{feff}# Rules\n\n{section}")
1478+ );
7291479 }
7301480
7311481 #[test]
@@ -753,7 +1503,7 @@
7531503 ),
7541504 ];
7551505 for (text, said) in cases {
756- let err = find_section(&text).unwrap_err();
1506+ let err = find(&text).unwrap_err();
7571507 assert!(err.contains(said), "{text:?}: {err}");
7581508 }
7591509 }
@@ -765,6 +1515,8 @@
7651515 "# Notes\nSee @AGENTS.md for the rules.\n",
7661516 "(@./AGENTS.md)\n",
7671517 " @AGENTS.md ",
1518+ "```text\nan example\n```\n@AGENTS.md\n",
1519+ "Read `this` and @AGENTS.md\n",
7681520 ] {
7691521 assert!(includes_agents(yes), "{yes:?}");
7701522 }
@@ -774,6 +1526,9 @@
7741526 "`@AGENTS.md`\n",
7751527 "@AGENTS.md.bak\n",
7761528 "@docs/AGENTS.md\n",
1529+ "``see @AGENTS.md here``\n",
1530+ "# Claude notes\n\n```text\n@AGENTS.md\n```\n",
1531+ "~~~\n@AGENTS.md\n",
7771532 ] {
7781533 assert!(!includes_agents(no), "{no:?}");
7791534 }
@@ -783,4 +1538,13 @@
7831538 assert_eq!(add_include("# Claude\r\n"), "# Claude\r\n@AGENTS.md\r\n");
7841539 assert!(includes_agents(&add_include("# Claude\n")));
7851540 }
1541+
1542+ #[test]
1543+ fn code_spans_are_left_out() {
1544+ assert_eq!(without_code_spans("a `b` c"), "a c");
1545+ assert_eq!(without_code_spans("a ``b ` c`` d"), "a d");
1546+ assert_eq!(without_code_spans("a ` b"), "a ` b");
1547+ assert_eq!(without_code_spans("é `x` ü"), "é ü");
1548+ assert_eq!(without_code_spans("``a` b"), "``a` b");
1549+ }
7861550 }
modified crates/cli/src/main.rs +114 −6
@@ -17,11 +17,12 @@
1717 use anyhow::{Context, Result, bail};
1818 use braid_format::changeset::decode_change_list;
1919 use braid_format::{
20- Change, ChangeOp, Changes, Changeset, IdHasher, Kind, ObjectId, Objects, Signature,
20+ Change, ChangeOp, Changes, Changeset, EntryKind, IdHasher, Kind, ObjectId, Objects, Signature,
2121 };
2222 use braid_repo::Repo;
2323 use braid_store::{FsckReport, Operation, RefUpdate};
24-use clap::{Parser, Subcommand};
24+use clap::parser::ValueSource;
25+use clap::{ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand};
2526 use serde_json::{Value, json};
2627
2728 /// Version control for many agents landing changes at once.
@@ -52,6 +53,79 @@
5253
5354 #[command(subcommand)]
5455 command: Command,
56+
57+ /// The global flags given on the command line, as a hint repeats them:
58+ /// empty, or each flag and its value followed by a space.
59+ #[arg(skip)]
60+ given: String,
61+}
62+
63+impl Cli {
64+ /// A command for a hint to print: `braid`, the global flags this
65+ /// command was given (`--repo`, `--agent`, `--workspace`), then `rest`,
66+ /// so that a hint followed as written acts on the same workspace, for
67+ /// the same agent.
68+ pub(crate) fn hint(&self, rest: &str) -> String {
69+ format!("braid {}{rest}", self.given)
70+ }
71+}
72+
73+/// The global flags typed on the command line, as [`Cli::given`] holds
74+/// them. A value that came from the environment, such as `BRAID_AGENT`, is
75+/// left out: the environment that set it sets it again.
76+fn given_flags(cli: &Cli, matches: &ArgMatches) -> String {
77+ // A global flag is recorded where it was typed, before or after a
78+ // subcommand, and copied to the others.
79+ let typed = |id: &str| {
80+ let mut current = Some(matches);
81+ while let Some(found) = current {
82+ if found.value_source(id) == Some(ValueSource::CommandLine) {
83+ return true;
84+ }
85+ current = found.subcommand().map(|(_, sub)| sub);
86+ }
87+ false
88+ };
89+ let mut given = String::new();
90+ let repo = cli.repo.as_ref().map(|repo| repo.to_string_lossy());
91+ for (id, value) in [
92+ ("repo", repo.as_deref()),
93+ ("agent", Some(cli.agent.as_str())),
94+ ("workspace", cli.workspace.as_deref()),
95+ ] {
96+ if let Some(value) = value
97+ && typed(id)
98+ {
99+ given.push_str(&flag(id, value));
100+ given.push(' ');
101+ }
102+ }
103+ given
104+}
105+
106+/// `--name value`, quoted for a POSIX shell where it needs to be, or
107+/// `--name=value` when the value starts with `-`.
108+fn flag(name: &str, value: &str) -> String {
109+ let word = shell_word(value);
110+ if value.starts_with('-') {
111+ format!("--{name}={word}")
112+ } else {
113+ format!("--{name} {word}")
114+ }
115+}
116+
117+/// `text` as one word of a POSIX shell: as it is when that is safe, or
118+/// between single quotes.
119+pub(crate) fn shell_word(text: &str) -> String {
120+ let plain = !text.is_empty()
121+ && text
122+ .bytes()
123+ .all(|byte| byte.is_ascii_alphanumeric() || b"_-./:@%+=,".contains(&byte));
124+ if plain {
125+ text.to_owned()
126+ } else {
127+ format!("'{}'", text.replace('\'', r"'\''"))
128+ }
55129 }
56130
57131 #[derive(Debug, Subcommand)]
@@ -75,9 +149,12 @@
75149 #[arg(required = true)]
76150 paths: Vec<PathBuf>,
77151 },
78- /// Write an object's raw payload to standard output.
152+ /// Write an object's raw payload to standard output: a file's content,
153+ /// for one named REV:PATH.
79154 CatObject {
80- /// A ref, an object id, or a short id (6 hex digits or more).
155+ /// A ref, an object id, a short id (6 hex digits or more), or
156+ /// REV:PATH, the file or directory at PATH, from the repository's
157+ /// root, in the changeset REV.
81158 revision: String,
82159 },
83160 /// List refs and the objects they point at.
@@ -262,7 +339,9 @@
262339 }
263340
264341 fn main() -> ExitCode {
265- let cli = Cli::parse();
342+ let matches = Cli::command().get_matches();
343+ let mut cli = Cli::from_arg_matches(&matches).unwrap_or_else(|err| err.exit());
344+ cli.given = given_flags(&cli, &matches);
266345 match run(&cli) {
267346 Ok(code) => code,
268347 Err(err) => {
@@ -433,9 +512,38 @@
433512 Ok((hasher.finalize(), size))
434513 }
435514
515+/// The object a revision names, or for `REV:PATH`, the object at PATH in
516+/// the tree of the changeset REV: the blob of a file or symlink, or the tree
517+/// of a directory. A revision that resolves as it is wins, so a ref with a
518+/// `:` in its name still names that ref.
519+fn resolve_object(repo: &Repo, revision: &str) -> Result<ObjectId> {
520+ let (rev, path) = match (repo.resolve(revision), revision.split_once(':')) {
521+ (Ok(id), _) => return Ok(id),
522+ (Err(braid_repo::Error::UnknownRevision(_)), Some(split)) => split,
523+ (Err(err), _) => return Err(err.into()),
524+ };
525+ let root = read_changeset(repo, &resolve_changeset(repo, rev)?)?.root;
526+ let path = path.strip_prefix("./").unwrap_or(path).trim_matches('/');
527+ if path.is_empty() {
528+ return Ok(root);
529+ }
530+ match braid_engine::entry_at(repo.store(), root, path.as_bytes())? {
531+ Some(
532+ EntryKind::File { blob, .. }
533+ | EntryKind::Executable { blob, .. }
534+ | EntryKind::Symlink { blob, .. },
535+ ) => Ok(blob),
536+ Some(EntryKind::Tree { tree }) => Ok(tree),
537+ Some(EntryKind::Gitlink { .. }) => {
538+ bail!("{path:?} is a submodule in {rev}: its content is in another repository")
539+ }
540+ None => bail!("{rev} has no file or directory at {path:?}"),
541+ }
542+}
543+
436544 fn cat_object(cli: &Cli, revision: &str) -> Result<ExitCode> {
437545 let repo = open_repo(cli)?;
438- let id = repo.resolve(revision)?;
546+ let id = resolve_object(&repo, revision)?;
439547 if cli.json {
440548 // The size is in the record's header: nothing needs decoding.
441549 let Some((kind, size)) = repo.store().stat(&id)? else {
modified crates/cli/src/work.rs +117 −20
@@ -16,6 +16,7 @@
1616 use braid_engine::{Conflict, ConflictKind, HunkSide};
1717 use braid_format::{ChangeOp, EntryKind, ObjectId};
1818 use braid_repo::{Location, Repo};
19+use braid_store::Refs;
1920 use braid_wc::{
2021 BEHIND_LIMIT, Blocker, ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed,
2122 Placed, RebaseProgress, UpdateReport, Updated, Workspace,
@@ -63,7 +64,8 @@
6364 next on conflicts, what to run next: braid update after land;
6465 braid commit, once the files are fixed, after update; a
6566 new change create on the branch after change create;
66- otherwise null
67+ otherwise null. It repeats the --repo, --agent and
68+ --workspace given on the command line
6769
6870 Ids in JSON are full; text output shows their first 12 hex digits."
6971 };
@@ -133,6 +135,22 @@
133135 report_fields!()
134136 );
135137
138+/// The long help of `workspace add`.
139+pub(crate) const ADD_HELP: &str = "Create a workspace and write its files: a directory, by default
140+.braid/work/<name> in the repository's root, holding a checkout of the
141+branch it tracks, a .braid file that names the workspace and the
142+repository, and a .git file that points nowhere, so that git run inside
143+the workspace stops with \"not a git repository\" instead of acting on a
144+checkout around it.
145+
146+The branch must be one the repository has: a name it does not have is
147+refused, since landing would start a new history under that name, with
148+none of the repository's. A repository with no branch yet takes any
149+name, and --new-branch takes one on purpose; the first landing starts it.
150+
151+With --json it prints name, path, branch, base (the changeset the working
152+copy is at, or null) and files (how many it wrote).";
153+
136154 /// The long help of `change create`.
137155 pub(crate) const CREATE_HELP: &str = concat!(
138156 "Make a changeset on a base without a working copy, and optionally land
@@ -147,20 +165,28 @@
147165 #[derive(Debug, Subcommand)]
148166 pub(crate) enum WorkspaceAction {
149167 /// Create a workspace and write its files.
168+ #[command(long_about = ADD_HELP)]
150169 Add {
151- /// The workspace's name: letters, digits, '.', '_' or '-'.
170+ /// The workspace's name: 1 to 64 ASCII letters, digits, '.', '_' or
171+ /// '-', starting with a letter or a digit.
152172 name: String,
153173 /// Its directory, which must not exist or be empty (default:
154- /// ./<name>).
174+ /// .braid/work/<name> in the repository's root).
155175 path: Option<PathBuf>,
156176 /// The changeset to start at: a ref, an id or a short id (default:
157177 /// the head of the tracked branch, or nothing if it does not exist
158178 /// yet).
159179 #[arg(long, value_name = "REV")]
160180 at: Option<String>,
161- /// The branch the workspace lands on and updates from.
181+ /// The branch the workspace lands on and updates from. It must be
182+ /// one the repository has, unless it has none yet or --new-branch
183+ /// is given.
162184 #[arg(long, value_name = "BRANCH", default_value = "main")]
163185 track: String,
186+ /// Track a branch the repository does not have: the workspace's
187+ /// first landing starts it.
188+ #[arg(long)]
189+ new_branch: bool,
164190 },
165191 /// List the repository's workspaces.
166192 List,
@@ -287,6 +313,53 @@
287313 }
288314 }
289315
316+/// The repository's branches, in the order the store keeps its refs: the
317+/// refs outside braid's own namespaces.
318+pub(crate) fn branches(refs: &Refs) -> Vec<&str> {
319+ refs.iter()
320+ .map(|(name, _)| name)
321+ .filter(|name| braid_repo::is_branch(name))
322+ .collect()
323+}
324+
325+/// The first few of `names`, for a message: `a, b, c`, or `a, b, c and 7
326+/// more`.
327+pub(crate) fn listed(names: &[&str]) -> String {
328+ const SHOWN: usize = 10;
329+ let mut text = names[..names.len().min(SHOWN)].join(", ");
330+ if names.len() > SHOWN {
331+ text.push_str(&format!(" and {} more", names.len() - SHOWN));
332+ }
333+ text
334+}
335+
336+/// Refuses to track `branch` unless it is a branch of the repository, the
337+/// repository has no branch yet, or a new branch is asked for. Tracking a
338+/// branch that does not exist gives an empty checkout, and its first
339+/// landing starts a history of its own under that name: in a project whose
340+/// branch is `master`, a `main` beside it with none of its history.
341+fn check_tracked(refs: &Refs, branch: &str, new_branch: bool) -> Result<()> {
342+ if !braid_repo::is_branch(branch) {
343+ bail!(
344+ "{branch:?} is in one of braid's own namespaces (braid/, git/, remote/, tags/), not a branch"
345+ );
346+ }
347+ let names = branches(refs);
348+ if names.contains(&branch) {
349+ return Ok(());
350+ }
351+ if !braid_git::is_branch_name(branch) {
352+ bail!("{branch:?} cannot name a branch");
353+ }
354+ if new_branch || names.is_empty() {
355+ return Ok(());
356+ }
357+ bail!(
358+ "the repository has no branch {branch:?}; it has {}. Track one of them, or pass --new-branch to start {branch} with this workspace's first landing",
359+ listed(&names)
360+ )
361+}
362+
290363 fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> {
291364 Ok(Identity::resolve(args.author.as_deref(), repo)?)
292365 }
@@ -330,15 +403,18 @@
330403 path,
331404 at,
332405 track,
406+ new_branch,
333407 } => {
334408 let repo = open_repo(cli)?;
409+ let refs = repo.store().refs()?;
410+ check_tracked(&refs, track, *new_branch)?;
335411 let at = match at {
336412 Some(revision) => Some(resolve_changeset(&repo, revision)?),
337- None => repo.store().refs()?.get(track),
413+ None => refs.get(track),
338414 };
339415 let dir = match path {
340416 Some(path) => path.clone(),
341- None => std::env::current_dir()?.join(name),
417+ None => Workspace::default_dir(&repo, name),
342418 };
343419 let (workspace, files) = Workspace::create(&repo, name, &dir, at, track)?;
344420 if cli.json {
@@ -487,25 +563,28 @@
487563 };
488564 writeln!(
489565 out,
490- "{} is {ahead} ahead, at {}: run `braid update`",
566+ "{} is {ahead} ahead, at {}: run `{}`",
491567 state.branch,
492- short(report.head)
568+ short(report.head),
569+ cli.hint("update")
493570 )?;
494571 }
495572 if let Some(rebase) = &state.rebase {
496573 writeln!(
497574 out,
498- "Rebase of {} in progress onto {}; resolve, then `braid commit`",
575+ "Rebase of {} in progress onto {}; resolve, then `{}`",
499576 rebase.change.short(),
500- rebase.onto.short()
577+ rebase.onto.short(),
578+ cli.hint("commit")
501579 )?;
580+ let resolve = format!("run `{}` once settled", cli.hint("resolve"));
502581 for (conflict, remain) in &report.conflicts {
503582 let note = if conflict.markers {
504583 if *remain { "markers remain" } else { "edited" }
505584 } else if conflict.resolved {
506585 "resolved"
507586 } else {
508- "run `braid resolve` once settled"
587+ &resolve
509588 };
510589 writeln!(
511590 out,
@@ -524,7 +603,11 @@
524603 }
525604 }
526605 if !status.needs_track.is_empty() {
527- writeln!(out, "New files not committed until `braid track <path>`:")?;
606+ writeln!(
607+ out,
608+ "New files not committed until `{}`:",
609+ cli.hint("track <path>")
610+ )?;
528611 for path in &status.needs_track {
529612 writeln!(out, " {}", show(path))?;
530613 }
@@ -602,8 +685,9 @@
602685 RebaseProgress::None => {}
603686 RebaseProgress::Finished { tip } => {
604687 println!(
605- "Rebase finished at {}; `braid land` when ready",
606- tip.short()
688+ "Rebase finished at {}; `{}` when ready",
689+ tip.short(),
690+ cli.hint("land")
607691 );
608692 }
609693 RebaseProgress::Stopped { change, conflicts } => {
@@ -681,7 +765,7 @@
681765 operation: None,
682766 change,
683767 conflicts,
684- next: (!conflicts.is_empty()).then(|| "braid commit".to_owned()),
768+ next: None,
685769 workspace: Some((report.base, &report.updated_paths)),
686770 }
687771 }
@@ -746,7 +830,7 @@
746830 let mut report = Report::landing(&landing);
747831 report.workspace = Some((workspace.state()?.base, &landing.updated_paths));
748832 if !report.conflicts.is_empty() {
749- report.next = Some("braid update".to_owned());
833+ report.next = Some(cli.hint("update"));
750834 }
751835 if cli.json {
752836 print_json(&report.json())?;
@@ -783,7 +867,10 @@
783867 short(landing.head_before),
784868 );
785869 print_conflicts(conflicts);
786- println!("Run `braid update` to bring the conflicts into the working copy.");
870+ println!(
871+ "Run `{}` to bring the conflicts into the working copy.",
872+ cli.hint("update")
873+ );
787874 }
788875 }
789876 report.print_updated();
@@ -795,7 +882,10 @@
795882 let workspace = target.open()?;
796883 let committer = identity(args, &target.repo)?;
797884 let updated = workspace.update(&committer)?;
798- let report = Report::update(&updated);
885+ let mut report = Report::update(&updated);
886+ if !report.conflicts.is_empty() {
887+ report.next = Some(cli.hint("commit"));
888+ }
799889 if cli.json {
800890 print_json(&report.json())?;
801891 return Ok(report.exit_code());
@@ -822,7 +912,11 @@
822912 head.short()
823913 );
824914 print_conflicts(conflicts);
825- println!("Fix the files, `braid resolve` the other conflicts, then `braid commit`.");
915+ println!(
916+ "Fix the files, `{}` the other conflicts, then `{}`.",
917+ cli.hint("resolve"),
918+ cli.hint("commit")
919+ );
826920 }
827921 }
828922 report.print_updated();
@@ -971,7 +1065,10 @@
9711065 if !report.conflicts.is_empty() {
9721066 // The change was built on a base the branch has moved past:
9731067 // it is made again on the new head.
974- report.next = Some(format!("braid change create --base {}", landing.branch));
1068+ report.next = Some(cli.hint(&format!(
1069+ "change create --base {}",
1070+ crate::shell_word(&landing.branch)
1071+ )));
9751072 }
9761073 report.json()
9771074 }
modified crates/cli/tests/agents.rs +472 −60
@@ -2,8 +2,9 @@
22 // Copyright (c) 2026 UtopiaIA
33
44 //! End-to-end tests of `braid agents init`: the braid section of a project's
5-//! AGENTS.md, written once and rewritten in place, CLAUDE.md, dry runs, JSON
6-//! and the branch the section names.
5+//! AGENTS.md, written once and rewritten in place, CLAUDE.md and GEMINI.md,
6+//! dry runs, JSON, the branch the section names, where it writes, and the
7+//! files it refuses to write.
78
89 use std::fs;
910 use std::path::{Path, PathBuf};
@@ -14,11 +15,22 @@
1415 const START: &str = "<!-- braid:start -->";
1516 const END: &str = "<!-- braid:end -->";
1617
18+/// Git without the user's or the system's configuration.
19+const GIT_ENV: [(&str, &str); 6] = [
20+ ("GIT_CONFIG_GLOBAL", "/dev/null"),
21+ ("GIT_CONFIG_NOSYSTEM", "1"),
22+ ("GIT_AUTHOR_NAME", "Ada Lovelace"),
23+ ("GIT_AUTHOR_EMAIL", "ada@example.org"),
24+ ("GIT_COMMITTER_NAME", "Ada Lovelace"),
25+ ("GIT_COMMITTER_EMAIL", "ada@example.org"),
26+];
27+
1728 /// Runs braid in `dir`.
1829 fn braid(dir: &Path, args: &[&str]) -> Output {
1930 Command::new(env!("CARGO_BIN_EXE_braid"))
2031 .current_dir(dir)
2132 .args(args)
33+ .envs(GIT_ENV)
2234 .env("BRAID_AUTHOR", "Ada <ada@example.org>")
2335 .env("BRAID_AGENT", "tester")
2436 .output()
@@ -36,6 +48,20 @@
3648 String::from_utf8(out.stdout).unwrap()
3749 }
3850
51+/// Runs braid in `dir`, expecting it to fail with exit status 1 and to
52+/// print nothing on standard output, and returns its error.
53+fn fails(dir: &Path, args: &[&str]) -> String {
54+ let out = braid(dir, args);
55+ assert_eq!(
56+ out.status.code(),
57+ Some(1),
58+ "braid {args:?}: {}",
59+ String::from_utf8_lossy(&out.stdout)
60+ );
61+ assert!(out.stdout.is_empty(), "braid {args:?}");
62+ String::from_utf8(out.stderr).unwrap()
63+}
64+
3965 /// Runs `braid agents init` with `--json` and these arguments in `dir`.
4066 fn init_json(dir: &Path, args: &[&str]) -> Value {
4167 let mut all = vec!["agents", "init", "--json"];
@@ -92,35 +118,70 @@
92118 );
93119 }
94120
121+/// A temporary braid repository whose only branch is `main`.
122+fn project() -> (tempfile::TempDir, PathBuf) {
123+ let (temp, dir) = temp();
124+ repository_with_branch(&dir, "main");
125+ (temp, dir)
126+}
127+
128+fn git(dir: &Path, args: &[&str]) {
129+ let out = Command::new("git")
130+ .current_dir(dir)
131+ .args(args)
132+ .envs(GIT_ENV)
133+ .output()
134+ .expect("git must be installed to run this test");
135+ assert!(
136+ out.status.success(),
137+ "git {args:?}: {}",
138+ String::from_utf8_lossy(&out.stderr)
139+ );
140+}
141+
95142 #[test]
96-fn a_fresh_directory_gets_an_agents_md_and_no_claude_md() {
143+fn without_a_repository_the_branch_must_be_given() {
97144 let (_temp, dir) = temp();
98- let report = init_json(&dir, &[]);
145+ let err = fails(&dir, &["agents", "init"]);
146+ assert!(err.contains("no braid repository here"), "{err}");
147+ assert!(
148+ err.contains("`braid init`, then `braid git import .`"),
149+ "{err}"
150+ );
151+ assert!(err.contains("--branch"), "{err}");
152+ assert!(!dir.join("AGENTS.md").exists());
153+
154+ let report = init_json(&dir, &["--branch", "main"]);
99155 assert_eq!(names(&report, "created"), ["AGENTS.md"]);
100156 assert!(names(&report, "updated").is_empty());
101157 assert!(names(&report, "unchanged").is_empty());
102158 assert_eq!(report["branch"], "main");
159+ assert_eq!(report["previous_branch"], Value::Null);
103160 assert_eq!(report["dry_run"], false);
104161 assert!(report["repository"].is_null());
105162 assert_eq!(report["dir"], dir.to_str().unwrap());
163+ assert_eq!(report["paths"]["AGENTS.md"], "AGENTS.md");
106164
107165 let text = read(&dir.join("AGENTS.md"));
108166 assert!(text.starts_with(&format!("{START}\n")), "{text}");
109167 assert!(text.ends_with(&format!("{END}\n")), "{text}");
110- assert!(text.contains("braid workspace add agent-1 .braid/work/agent-1 --track main\n"));
168+ assert!(text.contains("braid workspace add agent-1 --track main\n"));
111169 assert!(text.contains("https://braid.elffuss.com/agents.md"));
112170 assert!(!dir.join("CLAUDE.md").exists());
171+ assert!(!dir.join("GEMINI.md").exists());
113172
114- // In text, it says so, and that braid itself is not set up yet.
115- fs::remove_file(dir.join("AGENTS.md")).unwrap();
173+ // The section names the branch now: a second run keeps it.
116174 let said = ok(&dir, &["agents", "init"]);
117- assert!(said.contains("Created AGENTS.md"), "{said}");
118- assert!(said.contains("run `braid init`"), "{said}");
175+ assert!(said.contains("has this braid section already"), "{said}");
176+ assert!(
177+ said.contains("`braid init`, then `braid git import .`"),
178+ "{said}"
179+ );
119180 }
120181
121182 #[test]
122183 fn only_the_section_changes_and_a_second_run_changes_nothing() {
123- let (_temp, dir) = temp();
184+ let (_temp, dir) = project();
124185 let above = "# Our project\n\nTabs, not spaces.\n\n";
125186 let older = format!("{START}\n## Braid\n\nAn older section.\n{END}\n");
126187 let below = "\n## Releases\n\nTagged by hand.\n";
@@ -128,6 +189,7 @@
128189
129190 let report = init_json(&dir, &[]);
130191 assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
192+ assert_eq!(report["repository"], dir.to_str().unwrap());
131193 let text = read(&dir.join("AGENTS.md"));
132194 assert!(text.starts_with(above), "{text}");
133195 assert!(text.ends_with(below), "{text}");
@@ -136,18 +198,18 @@
136198 assert!(!section.contains("An older section"));
137199 assert!(section.contains("--track main"));
138200
139- // Idempotent: the same bytes, reported unchanged.
140201 let report = init_json(&dir, &[]);
141202 assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]);
142203 assert!(names(&report, "updated").is_empty());
143204 assert_eq!(read(&dir.join("AGENTS.md")), text);
144205 let said = ok(&dir, &["agents", "init"]);
145206 assert!(said.contains("has this braid section already"), "{said}");
207+ assert!(!said.contains("braid init"), "{said}");
146208 }
147209
148210 #[test]
149211 fn a_file_without_markers_gets_the_section_at_its_end_once() {
150- let (_temp, dir) = temp();
212+ let (_temp, dir) = project();
151213 let ours = "# Rules\n\nRun the tests before you push.";
152214 fs::write(dir.join("AGENTS.md"), ours).unwrap();
153215 let said = ok(&dir, &["agents", "init"]);
@@ -167,7 +229,7 @@
167229
168230 #[test]
169231 fn unbalanced_markers_are_refused_and_nothing_is_written() {
170- let (_temp, dir) = temp();
232+ let (_temp, dir) = project();
171233 let claude = "# Claude\n";
172234 fs::write(dir.join("CLAUDE.md"), claude).unwrap();
173235 for (text, lines) in [
@@ -186,10 +248,7 @@
186248 &["agents", "init", "--json"],
187249 &["agents", "init", "--dry-run"],
188250 ] {
189- let out = braid(&dir, args);
190- assert_eq!(out.status.code(), Some(1), "{text:?} {args:?}");
191- assert!(out.stdout.is_empty());
192- let err = String::from_utf8(out.stderr).unwrap();
251+ let err = fails(&dir, args);
193252 assert!(err.contains("unbalanced braid markers"), "{err}");
194253 assert!(err.contains(lines), "{text:?}: {err}");
195254 assert!(err.contains("nothing was written"), "{err}");
@@ -199,13 +258,59 @@
199258 }
200259 }
201260
261+#[test]
262+fn markers_in_a_code_block_are_an_example_and_stay_one() {
263+ let (_temp, dir) = project();
264+ let ours = format!(
265+ "# Rules\n\nWhat braid writes looks like this:\n\n```markdown\n{START}\n(the rules braid writes)\n{END}\n```\n\nMore rules.\n"
266+ );
267+ fs::write(dir.join("AGENTS.md"), &ours).unwrap();
268+ let report = init_json(&dir, &[]);
269+ assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
270+ let text = read(&dir.join("AGENTS.md"));
271+ assert!(text.starts_with(&ours), "the example stays: {text}");
272+ assert_eq!(text, format!("{ours}\n{}", section_of(&text[ours.len()..])));
273+ // The example next to the real section is not a second pair.
274+ assert_eq!(names(&init_json(&dir, &[]), "unchanged"), ["AGENTS.md"]);
275+ assert_eq!(read(&dir.join("AGENTS.md")), text);
276+
277+ // A file that ends inside a code block would have the section read as
278+ // code: refused.
279+ let open = "# Rules\n\n```bash\nmake test\n";
280+ fs::write(dir.join("AGENTS.md"), open).unwrap();
281+ let err = fails(&dir, &["agents", "init", "--dry-run"]);
282+ assert!(err.contains("opens on line 3 and is never closed"), "{err}");
283+ assert!(err.contains("nothing was written"), "{err}");
284+ fails(&dir, &["agents", "init"]);
285+ assert_eq!(read(&dir.join("AGENTS.md")), open);
286+}
287+
288+#[test]
289+fn a_byte_order_mark_before_the_section_stays_and_hides_nothing() {
290+ let (_temp, dir) = project();
291+ ok(&dir, &["agents", "init"]);
292+ let written = read(&dir.join("AGENTS.md"));
293+ let marked = format!("\u{feff}{written}");
294+ fs::write(dir.join("AGENTS.md"), &marked).unwrap();
295+ assert_eq!(names(&init_json(&dir, &[]), "unchanged"), ["AGENTS.md"]);
296+ assert_eq!(read(&dir.join("AGENTS.md")), marked);
297+ // A section of another branch is rewritten after the mark.
298+ ok(&dir, &["ref", "set", "trunk", "main"]);
299+ assert_eq!(
300+ names(&init_json(&dir, &["--branch", "trunk"]), "updated"),
301+ ["AGENTS.md"]
302+ );
303+ let text = read(&dir.join("AGENTS.md"));
304+ assert!(text.starts_with(&format!("\u{feff}{START}\n")), "{text:?}");
305+ assert!(text.contains("--track trunk\n"));
306+}
307+
202308 #[test]
203309 fn claude_md_gets_the_include_line_and_only_that() {
204- let (_temp, dir) = temp();
310+ let (_temp, dir) = project();
205311 let claude = "# Notes for Claude\n\nBe brief.";
206312 fs::write(dir.join("CLAUDE.md"), claude).unwrap();
207313
208- // --no-claude leaves it alone, and does not list it.
209314 let report = init_json(&dir, &["--no-claude"]);
210315 assert_eq!(names(&report, "created"), ["AGENTS.md"]);
211316 assert!(names(&report, "updated").is_empty());
@@ -215,12 +320,12 @@
215320 let report = init_json(&dir, &[]);
216321 assert_eq!(names(&report, "updated"), ["CLAUDE.md"]);
217322 assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]);
323+ assert_eq!(report["paths"]["CLAUDE.md"], "CLAUDE.md");
218324 assert_eq!(
219325 read(&dir.join("CLAUDE.md")),
220326 format!("{claude}\n@AGENTS.md\n")
221327 );
222328
223- // Once it includes AGENTS.md, it is left as it is.
224329 let report = init_json(&dir, &[]);
225330 assert_eq!(names(&report, "unchanged"), ["AGENTS.md", "CLAUDE.md"]);
226331 for including in ["See @AGENTS.md for the rules.\n", "@./AGENTS.md\n"] {
@@ -232,18 +337,52 @@
232337 );
233338 assert_eq!(read(&dir.join("CLAUDE.md")), including);
234339 }
340+
341+ // An import shown in a code block imports nothing.
342+ let shown = "# Claude notes\n\nThe import looks like this:\n\n```text\n@AGENTS.md\n```\n";
343+ fs::write(dir.join("CLAUDE.md"), shown).unwrap();
344+ assert_eq!(names(&init_json(&dir, &[]), "updated"), ["CLAUDE.md"]);
345+ assert_eq!(read(&dir.join("CLAUDE.md")), format!("{shown}@AGENTS.md\n"));
346+
347+ // A CLAUDE.md that ends inside a code block would hide the line.
348+ let open = "# Claude\n\n~~~\nan example\n";
349+ fs::write(dir.join("CLAUDE.md"), open).unwrap();
350+ let err = fails(&dir, &["agents", "init"]);
351+ assert!(
352+ err.contains("CLAUDE.md ends inside a fenced code block"),
353+ "{err}"
354+ );
355+ assert_eq!(read(&dir.join("CLAUDE.md")), open);
356+}
357+
358+#[test]
359+fn gemini_md_gets_the_include_line_too() {
360+ let (_temp, dir) = project();
361+ fs::write(dir.join("CLAUDE.md"), "# Claude\n").unwrap();
362+ fs::write(dir.join("GEMINI.md"), "# Gemini\n").unwrap();
363+ let report = init_json(&dir, &["--no-gemini"]);
364+ assert_eq!(names(&report, "updated"), ["CLAUDE.md"]);
365+ assert_eq!(read(&dir.join("GEMINI.md")), "# Gemini\n");
366+ let report = init_json(&dir, &[]);
367+ assert_eq!(names(&report, "updated"), ["GEMINI.md"]);
368+ assert_eq!(names(&report, "unchanged"), ["AGENTS.md", "CLAUDE.md"]);
369+ assert_eq!(read(&dir.join("GEMINI.md")), "# Gemini\n@AGENTS.md\n");
370+ let said = ok(&dir, &["agents", "init"]);
371+ assert!(
372+ said.contains("GEMINI.md includes AGENTS.md already"),
373+ "{said}"
374+ );
235375 }
236376
237377 #[cfg(unix)]
238378 #[test]
239-fn links_stay_links() {
240- let (_temp, dir) = temp();
241- // CLAUDE.md is AGENTS.md under another name: it holds the section, and
242- // never includes itself.
379+fn links_inside_the_project_are_followed() {
380+ let (_temp, dir) = project();
243381 std::os::unix::fs::symlink("AGENTS.md", dir.join("CLAUDE.md")).unwrap();
244382 let report = init_json(&dir, &[]);
245383 assert_eq!(names(&report, "created"), ["AGENTS.md"]);
246384 assert_eq!(names(&report, "unchanged"), ["CLAUDE.md"]);
385+ assert_eq!(report["paths"]["CLAUDE.md"], "AGENTS.md");
247386 assert!(!read(&dir.join("AGENTS.md")).contains("@AGENTS.md"));
248387 assert!(
249388 fs::symlink_metadata(dir.join("CLAUDE.md"))
@@ -251,27 +390,191 @@
251390 .file_type()
252391 .is_symlink()
253392 );
393+ let report = init_json(&dir, &[]);
394+ assert_eq!(names(&report, "unchanged"), ["AGENTS.md", "CLAUDE.md"]);
254395
255- // An AGENTS.md that links to a file elsewhere: that file is the one
256- // written, and the link stays.
257- let (_other, elsewhere) = temp();
258- let shared = elsewhere.join("rules.md");
259- fs::write(&shared, "# Shared rules\n").unwrap();
260- let (_project, project) = temp();
261- std::os::unix::fs::symlink(&shared, project.join("AGENTS.md")).unwrap();
262- let report = init_json(&project, &[]);
396+ // AGENTS.md may be the link, to a file elsewhere in the project: that
397+ // file gets the section, and the JSON names it.
398+ let (_other, linked) = project();
399+ fs::create_dir(linked.join("docs")).unwrap();
400+ fs::write(linked.join("docs/rules.md"), "# Shared rules\n").unwrap();
401+ std::os::unix::fs::symlink("docs/rules.md", linked.join("AGENTS.md")).unwrap();
402+ let report = init_json(&linked, &[]);
263403 assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
264- let link = fs::symlink_metadata(project.join("AGENTS.md")).unwrap();
404+ assert_eq!(report["paths"]["AGENTS.md"], "docs/rules.md");
405+ let link = fs::symlink_metadata(linked.join("AGENTS.md")).unwrap();
265406 assert!(link.file_type().is_symlink());
266- assert!(read(&shared).starts_with("# Shared rules\n\n<!-- braid:start -->\n"));
267- // Nothing is left behind next to it.
268- let left: Vec<_> = fs::read_dir(&elsewhere).unwrap().collect();
269- assert_eq!(left.len(), 1);
407+ assert!(
408+ read(&linked.join("docs/rules.md")).starts_with("# Shared rules\n\n<!-- braid:start -->\n")
409+ );
410+ let said = ok(&linked, &["agents", "init"]);
411+ assert!(
412+ said.contains(
413+ "AGENTS.md (docs/rules.md, which it links to) has this braid section already"
414+ ),
415+ "{said}"
416+ );
417+ let left: Vec<_> = fs::read_dir(linked.join("docs")).unwrap().collect();
418+ assert_eq!(left.len(), 1, "no temporary file is left");
419+
420+ // The layout of projects that started with Claude Code: AGENTS.md a
421+ // link to CLAUDE.md, which holds the section itself.
422+ let (_third, claude) = project();
423+ fs::write(claude.join("CLAUDE.md"), "# Claude rules\n").unwrap();
424+ std::os::unix::fs::symlink("CLAUDE.md", claude.join("AGENTS.md")).unwrap();
425+ let report = init_json(&claude, &[]);
426+ assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
427+ assert_eq!(names(&report, "unchanged"), ["CLAUDE.md"]);
428+ let text = read(&claude.join("CLAUDE.md"));
429+ assert!(
430+ text.starts_with("# Claude rules\n\n<!-- braid:start -->\n"),
431+ "{text}"
432+ );
433+ assert!(!text.contains("@AGENTS.md"), "{text}");
434+ assert_eq!(
435+ names(&init_json(&claude, &[]), "unchanged"),
436+ ["AGENTS.md", "CLAUDE.md"]
437+ );
438+}
439+
440+#[cfg(unix)]
441+#[test]
442+fn files_braid_must_not_write_are_refused_in_a_dry_run_too() {
443+ use std::os::unix::fs::{PermissionsExt, symlink};
444+
445+ let both = |dir: &Path, said: &str| {
446+ for args in [&["agents", "init", "--dry-run"][..], &["agents", "init"]] {
447+ let err = fails(dir, args);
448+ assert!(err.contains(said), "{args:?}: {err}");
449+ assert!(err.contains("nothing was written"), "{args:?}: {err}");
450+ }
451+ };
452+
453+ // A link outside the project: other projects may read that file.
454+ let (_shared, shared) = temp();
455+ fs::write(shared.join("CLAUDE.md"), "# Shared notes\n").unwrap();
456+ let (_project, dir) = project();
457+ symlink(shared.join("CLAUDE.md"), dir.join("CLAUDE.md")).unwrap();
458+ both(&dir, "CLAUDE.md is a link to");
459+ assert_eq!(read(&shared.join("CLAUDE.md")), "# Shared notes\n");
460+ assert!(!dir.join("AGENTS.md").exists());
461+ ok(&dir, &["agents", "init", "--no-claude"]);
462+ fs::remove_file(dir.join("AGENTS.md")).unwrap();
463+
464+ // A link to a file that does not exist fails the dry run as it fails
465+ // the real run.
466+ symlink("docs/rules.md", dir.join("AGENTS.md")).unwrap();
467+ both(&dir, "which does not exist");
468+ fs::remove_file(dir.join("AGENTS.md")).unwrap();
469+
470+ // A FIFO is never opened: the dry run does not wait on it.
471+ let fifo = dir.join("AGENTS.md");
472+ let made = Command::new("mkfifo").arg(&fifo).status();
473+ if made.is_ok_and(|status| status.success()) {
474+ both(&dir, "is not a regular file");
475+ fs::remove_file(&fifo).unwrap();
476+ }
477+
478+ // A read-only file is left as it is.
479+ fs::write(dir.join("AGENTS.md"), "# Rules\n").unwrap();
480+ fs::set_permissions(dir.join("AGENTS.md"), fs::Permissions::from_mode(0o444)).unwrap();
481+ both(&dir, "AGENTS.md is read-only");
482+ assert_eq!(read(&dir.join("AGENTS.md")), "# Rules\n");
483+ fs::set_permissions(dir.join("AGENTS.md"), fs::Permissions::from_mode(0o644)).unwrap();
484+
485+ // A file with a hard link elsewhere would change under that name too.
486+ fs::hard_link(dir.join("AGENTS.md"), shared.join("AGENTS.md")).unwrap();
487+ both(&dir, "has hard links");
488+ assert_eq!(read(&shared.join("AGENTS.md")), "# Rules\n");
489+}
490+
491+#[cfg(unix)]
492+#[test]
493+fn hard_linked_guides_stay_one_file() {
494+ use std::os::unix::fs::MetadataExt;
495+
496+ let (_temp, dir) = project();
497+ fs::write(
498+ dir.join("AGENTS.md"),
499+ "# Shared rules for every agent\n\nRun the tests.\n",
500+ )
501+ .unwrap();
502+ fs::hard_link(dir.join("AGENTS.md"), dir.join("CLAUDE.md")).unwrap();
503+ let report = init_json(&dir, &[]);
504+ assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
505+ assert_eq!(names(&report, "unchanged"), ["CLAUDE.md"]);
506+ let (agents, claude) = (
507+ fs::metadata(dir.join("AGENTS.md")).unwrap(),
508+ fs::metadata(dir.join("CLAUDE.md")).unwrap(),
509+ );
510+ assert_eq!(agents.ino(), claude.ino());
511+ assert_eq!(agents.nlink(), 2);
512+ let text = read(&dir.join("CLAUDE.md"));
513+ assert!(text.contains(START), "{text}");
514+ assert!(!text.contains("@AGENTS.md"), "{text}");
515+ assert_eq!(
516+ names(&init_json(&dir, &[]), "unchanged"),
517+ ["AGENTS.md", "CLAUDE.md"]
518+ );
519+}
520+
521+#[cfg(unix)]
522+#[test]
523+fn a_failed_write_leaves_every_file_as_it_was() {
524+ use std::os::unix::fs::{PermissionsExt, symlink};
525+
526+ let (_temp, dir) = project();
527+ let sub = dir.join("sub");
528+ fs::create_dir(&sub).unwrap();
529+ fs::write(sub.join("CLAUDE.md"), "# Claude\n").unwrap();
530+ symlink("sub/CLAUDE.md", dir.join("CLAUDE.md")).unwrap();
531+ fs::set_permissions(&sub, fs::Permissions::from_mode(0o555)).unwrap();
532+ // Where permissions do not bind, as for root, there is nothing to test.
533+ let binding = fs::write(sub.join("probe"), "").is_err();
534+ if binding {
535+ let err = fails(&dir, &["agents", "init", "--json"]);
536+ assert!(err.contains("cannot write sub/CLAUDE.md"), "{err}");
537+ assert!(err.contains("nothing was written"), "{err}");
538+ assert!(!dir.join("AGENTS.md").exists());
539+ assert_eq!(read(&sub.join("CLAUDE.md")), "# Claude\n");
540+ let left: Vec<_> = fs::read_dir(&dir)
541+ .unwrap()
542+ .map(|entry| entry.unwrap().file_name())
543+ .filter(|name| name.to_string_lossy().contains(".braid-"))
544+ .collect();
545+ assert!(left.is_empty(), "{left:?}");
546+ }
547+ fs::set_permissions(&sub, fs::Permissions::from_mode(0o755)).unwrap();
548+}
549+
550+#[test]
551+fn files_that_are_not_utf8_are_refused_and_left_as_they_are() {
552+ let (_temp, dir) = project();
553+ let latin1 = b"# R\xe8gles\n".to_vec();
554+ fs::write(dir.join("AGENTS.md"), &latin1).unwrap();
555+ fs::write(dir.join("CLAUDE.md"), "# Claude\n").unwrap();
556+ let err = fails(&dir, &["agents", "init"]);
557+ assert!(
558+ err.contains("AGENTS.md is not UTF-8 text: nothing was written"),
559+ "{err}"
560+ );
561+ assert_eq!(fs::read(dir.join("AGENTS.md")).unwrap(), latin1);
562+ assert_eq!(read(&dir.join("CLAUDE.md")), "# Claude\n");
563+
564+ fs::remove_file(dir.join("AGENTS.md")).unwrap();
565+ fs::write(dir.join("CLAUDE.md"), &latin1).unwrap();
566+ let err = fails(&dir, &["agents", "init"]);
567+ assert!(
568+ err.contains("CLAUDE.md is not UTF-8 text: nothing was written"),
569+ "{err}"
570+ );
571+ assert!(!dir.join("AGENTS.md").exists());
572+ assert_eq!(fs::read(dir.join("CLAUDE.md")).unwrap(), latin1);
270573 }
271574
272575 #[test]
273576 fn a_dry_run_says_what_would_change_and_writes_nothing() {
274- let (_temp, dir) = temp();
577+ let (_temp, dir) = project();
275578 fs::write(dir.join("CLAUDE.md"), "# Claude\n").unwrap();
276579 let report = init_json(&dir, &["--dry-run"]);
277580 assert_eq!(report["dry_run"], true);
@@ -284,11 +587,9 @@
284587 assert!(said.contains("Would create AGENTS.md"), "{said}");
285588 assert!(said.contains("Would add @AGENTS.md to CLAUDE.md"), "{said}");
286589 assert!(said.contains("Nothing was written."), "{said}");
287- // The section it would write, whole.
288590 assert!(said.ends_with(&format!("{END}\n")), "{said}");
289591 assert!(said.contains(START));
290592 assert!(!dir.join("AGENTS.md").exists());
291- // Nothing to do: nothing to show either.
292593 ok(&dir, &["agents", "init"]);
293594 let said = ok(&dir, &["agents", "init", "--dry-run"]);
294595 assert!(!said.contains(START), "{said}");
@@ -302,44 +603,121 @@
302603 assert_eq!(report["branch"], "master");
303604 assert_eq!(report["repository"], dir.to_str().unwrap());
304605
305- // A repository whose only branch has another name.
306606 let (_other, trunk) = temp();
307607 repository_with_branch(&trunk, "trunk");
308608 let report = init_json(&trunk, &[]);
309609 assert_eq!(report["branch"], "trunk");
310610 let text = read(&trunk.join("AGENTS.md"));
311611 assert!(text.contains("--track trunk\n"), "{text}");
312- assert!(text.contains("--branch trunk`"), "{text}");
313- // Running it again keeps that branch, even once main exists too.
612+ assert!(text.contains("--branch trunk\n"), "{text}");
314613 ok(&trunk, &["ref", "set", "main", "trunk"]);
315614 let report = init_json(&trunk, &[]);
316615 assert_eq!(report["branch"], "trunk");
317616 assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]);
318- // --branch says otherwise.
319617 let report = init_json(&trunk, &["--branch", "main"]);
320618 assert_eq!(report["branch"], "main");
619+ assert_eq!(report["previous_branch"], "trunk");
321620 assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
322621 assert!(read(&trunk.join("AGENTS.md")).contains("--track main\n"));
323622
324- // Two branches, neither main nor master: braid will not guess.
325623 let (_third, two) = temp();
326624 repository_with_branch(&two, "trunk");
327625 ok(&two, &["ref", "set", "develop", "trunk"]);
328- let out = braid(&two, &["agents", "init"]);
329- assert_eq!(out.status.code(), Some(1));
330- let err = String::from_utf8(out.stderr).unwrap();
626+ let err = fails(&two, &["agents", "init"]);
331627 assert!(err.contains("develop, trunk; pass --branch"), "{err}");
332628 assert!(!two.join("AGENTS.md").exists());
333629 for bad in ["two words", "tags/v1", "braid/git-map"] {
334- let out = braid(&two, &["agents", "init", "--branch", bad]);
335- assert_eq!(out.status.code(), Some(1), "{bad}");
630+ fails(&two, &["agents", "init", "--branch", bad]);
336631 }
337632 }
338633
339634 #[test]
340-fn it_writes_at_the_root_of_the_repository_or_of_the_workspace() {
635+fn a_branch_the_repository_does_not_have_is_refused() {
636+ let (_temp, dir) = project();
637+ let err = fails(&dir, &["agents", "init", "--branch", "mian", "--dry-run"]);
638+ assert!(err.contains("has no branch \"mian\"; it has main"), "{err}");
639+ fails(&dir, &["agents", "init", "--branch", "mian"]);
640+ assert!(!dir.join("AGENTS.md").exists());
641+}
642+
643+#[test]
644+fn branch_names_that_shell_commands_would_misread_are_refused() {
341645 let (_temp, dir) = temp();
342- repository_with_branch(&dir, "main");
646+ repository_with_branch(&dir, "feature/x.y_z-1");
647+ let report = init_json(&dir, &[]);
648+ assert_eq!(report["branch"], "feature/x.y_z-1");
649+ let text = read(&dir.join("AGENTS.md"));
650+ assert!(text.contains("--track feature/x.y_z-1\n"), "{text}");
651+ // It reads back exactly: a second run changes nothing.
652+ assert_eq!(names(&init_json(&dir, &[]), "unchanged"), ["AGENTS.md"]);
653+
654+ for bad in [
655+ "feat(x)",
656+ "a;b",
657+ "a;touch${IFS}pwned",
658+ "q$(id)",
659+ "x`id`",
660+ "it's",
661+ "a|b",
662+ "a>b",
663+ "-x",
664+ "--no-claude",
665+ ] {
666+ let flag = format!("--branch={bad}");
667+ let err = fails(&dir, &["agents", "init", "--dry-run", &flag]);
668+ assert!(
669+ err.contains("cannot name the branch agents land on"),
670+ "{bad}: {err}"
671+ );
672+ }
673+ assert_eq!(read(&dir.join("AGENTS.md")), text);
674+}
675+
676+#[test]
677+fn a_branch_named_before_the_project_was_imported_is_chosen_again() {
678+ // A project whose only branch is master, set up out of order.
679+ let (_temp, dir) = temp();
680+ git(&dir, &["init", "--quiet", "-b", "master"]);
681+ fs::write(dir.join("README.md"), "# Project\n").unwrap();
682+ git(&dir, &["add", "README.md"]);
683+ git(&dir, &["commit", "--quiet", "-m", "First"]);
684+
685+ // Before braid is set up, there is no branch to name.
686+ let err = fails(&dir, &["agents", "init"]);
687+ assert!(err.contains("--branch"), "{err}");
688+ assert!(!dir.join("AGENTS.md").exists());
689+ ok(&dir, &["init"]);
690+ let err = fails(&dir, &["agents", "init"]);
691+ assert!(err.contains("no branch yet"), "{err}");
692+ assert!(err.contains("braid git import ."), "{err}");
693+ // A guess written anyway, before the import...
694+ let report = init_json(&dir, &["--branch", "main"]);
695+ assert_eq!(report["branch"], "main");
696+
697+ // ...gives way, once the history is in, to the branch it has.
698+ ok(&dir, &["git", "import", "."]);
699+ let said = ok(&dir, &["agents", "init", "--dry-run"]);
700+ assert!(
701+ said.contains(
702+ "The section named main, which the repository does not have: it would name master now."
703+ ),
704+ "{said}"
705+ );
706+ let report = init_json(&dir, &[]);
707+ assert_eq!(report["branch"], "master");
708+ assert_eq!(report["previous_branch"], "main");
709+ assert_eq!(names(&report, "updated"), ["AGENTS.md"]);
710+ let text = read(&dir.join("AGENTS.md"));
711+ assert!(text.contains("--track master\n"), "{text}");
712+ assert!(!text.contains("--track main"), "{text}");
713+ let report = init_json(&dir, &[]);
714+ assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]);
715+ assert_eq!(report["previous_branch"], Value::Null);
716+}
717+
718+#[test]
719+fn it_writes_at_the_root_of_the_repository_or_of_the_workspace() {
720+ let (_temp, dir) = project();
343721 let deep = dir.join("src/deep");
344722 fs::create_dir_all(&deep).unwrap();
345723 let report = init_json(&deep, &[]);
@@ -347,17 +725,15 @@
347725 assert!(dir.join("AGENTS.md").is_file());
348726 assert!(!deep.join("AGENTS.md").exists());
349727
350- // A workspace, under .braid/work as the section says, on another
351- // branch: the section goes at its root and names its branch.
352728 ok(
353729 &dir,
354730 &[
355731 "workspace",
356732 "add",
357733 "agent-1",
358- ".braid/work/agent-1",
359734 "--track",
360735 "release",
736+ "--new-branch",
361737 ],
362738 );
363739 let workspace = dir.join(".braid/work/agent-1");
@@ -368,16 +744,52 @@
368744 assert_eq!(report["branch"], "release");
369745 assert_eq!(report["repository"], dir.to_str().unwrap());
370746 assert!(read(&workspace.join("AGENTS.md")).contains("--track release\n"));
371- // It is the workspace's change, to commit and land like any other.
372747 let status: Value = serde_json::from_str(&ok(&workspace, &["status", "--json"])).unwrap();
373- assert_eq!(status["added"][0], "AGENTS.md");
748+ assert_eq!(status["added"], serde_json::json!(["AGENTS.md"]));
374749
375- // --dir names the directory whatever the current one is.
376750 let (_other, elsewhere) = temp();
377751 let report = init_json(&elsewhere, &["--dir", dir.join("src").to_str().unwrap()]);
378752 assert_eq!(report["dir"], dir.join("src").to_str().unwrap());
379753 assert_eq!(report["branch"], "main");
380754 assert!(dir.join("src/AGENTS.md").is_file());
381- let out = braid(&elsewhere, &["agents", "init", "--dir", "no-such-dir"]);
382- assert_eq!(out.status.code(), Some(1));
755+ fails(&elsewhere, &["agents", "init", "--dir", "no-such-dir"]);
756+}
757+
758+#[test]
759+fn workspace_and_repo_say_where_to_write() {
760+ let (_temp, dir) = project();
761+ ok(&dir, &["workspace", "add", "agent-1"]);
762+ let workspace = dir.join(".braid/work/agent-1");
763+
764+ // From the project root, --workspace writes in that workspace, as the
765+ // section's commands run from the root do.
766+ let report = init_json(&dir, &["--workspace", "agent-1"]);
767+ assert_eq!(report["dir"], workspace.to_str().unwrap());
768+ assert_eq!(report["branch"], "main");
769+ assert_eq!(names(&report, "created"), ["AGENTS.md"]);
770+ assert!(workspace.join("AGENTS.md").is_file());
771+ assert!(!dir.join("AGENTS.md").exists());
772+ let err = fails(
773+ &dir,
774+ &["--workspace", "nope", "agents", "init", "--dry-run"],
775+ );
776+ assert!(err.contains("no workspace named \"nope\""), "{err}");
777+ let err = fails(
778+ &dir,
779+ &["--workspace", "agent-1", "agents", "init", "--dir", "."],
780+ );
781+ assert!(err.contains("give one of them"), "{err}");
782+
783+ // From outside the repository, --repo writes at its root.
784+ let (_other, elsewhere) = temp();
785+ let report = init_json(&elsewhere, &["--repo", dir.to_str().unwrap(), "--dry-run"]);
786+ assert_eq!(report["dir"], dir.to_str().unwrap());
787+ assert_eq!(report["repository"], dir.to_str().unwrap());
788+ assert_eq!(names(&report, "created"), ["AGENTS.md"]);
789+ ok(
790+ &elsewhere,
791+ &["--repo", dir.to_str().unwrap(), "agents", "init"],
792+ );
793+ assert!(dir.join("AGENTS.md").is_file());
794+ assert!(!elsewhere.join("AGENTS.md").exists());
383795 }
modified crates/cli/tests/guides.rs +47 −20
@@ -3,8 +3,9 @@
33
44 //! The guides for coding agents: part 1 of AGENTS.md, which the site also
55 //! serves as agents.md, and the section `braid agents init` writes. They say
6-//! the same things in several places, and every braid command they give must
7-//! exist, with every flag it is given.
6+//! the same things in several places, they install the braid they describe,
7+//! and every braid command they give must exist, with every flag it is
8+//! given.
89
910 use std::path::Path;
1011 use std::process::Command;
@@ -12,8 +13,13 @@
1213 const START: &str = "<!-- braid:start -->";
1314 const END: &str = "<!-- braid:end -->";
1415
15-/// The prompt that sends an agent to the guide.
16-const PROMPT: &str = "Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md";
16+/// The prompt that sends an agent to the guide. It asks for the page whole,
17+/// since some harnesses fetch a summary of a page rather than its text.
18+const PROMPT: &str = "Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md (read it whole, with curl -fsSL)";
19+
20+/// The same prompt, as the Spanish page and the README's Spanish part give
21+/// it.
22+const PROMPT_ES: &str = "Instala braid en este proyecto y configúralo para agentes siguiendo https://braid.elffuss.com/agents.md (léelo entero, con curl -fsSL)";
1723
1824 fn repository_file(path: &str) -> String {
1925 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
@@ -68,7 +74,10 @@
6874 /// The section `braid agents init` writes, as its dry run prints it.
6975 fn section() -> String {
7076 let temp = tempfile::tempdir().unwrap();
71- let said = braid(temp.path(), &["agents", "init", "--dry-run"]);
77+ let said = braid(
78+ temp.path(),
79+ &["agents", "init", "--dry-run", "--branch", "main"],
80+ );
7281 let start = said.find(START).expect("the dry run prints the section");
7382 said[start..].to_owned()
7483 }
@@ -95,14 +104,10 @@
95104 fn the_guide_for_agents_is_the_same_in_agents_md_and_on_the_site() {
96105 let agents = repository_file("AGENTS.md");
97106 let site = repository_file("site/agents.md");
98- // The site serves part 1 of AGENTS.md, from its first subsection on,
99- // one heading level up.
100107 let first = "### Install";
101108 let ours = part(&agents, first, Some("\n## 2."), true);
102109 let theirs = part(&site, &first[1..], None, false);
103110 assert_eq!(ours.trim_end(), theirs.trim_end());
104- // No line of the guides is a marker, so that `braid agents init` never
105- // takes them for a section.
106111 for text in [&agents, &site] {
107112 assert!(
108113 !text
@@ -110,7 +115,6 @@
110115 .any(|line| line.trim() == START || line.trim() == END)
111116 );
112117 }
113- // CLAUDE.md only includes AGENTS.md.
114118 assert_eq!(repository_file("CLAUDE.md"), "@AGENTS.md\n");
115119 }
116120
@@ -119,24 +123,48 @@
119123 for path in ["README.md", "site/index.html", "site/llms.txt"] {
120124 assert!(repository_file(path).contains(PROMPT), "{path}");
121125 }
122- // It points at the guide, which the site serves.
123- assert!(PROMPT.ends_with("https://braid.elffuss.com/agents.md"));
126+ for path in ["README.md", "site/index.html"] {
127+ assert!(repository_file(path).contains(PROMPT_ES), "{path}");
128+ }
129+ assert!(PROMPT.contains(" https://braid.elffuss.com/agents.md "));
124130 assert!(repository_file("site/llms.txt").contains("(https://braid.elffuss.com/agents.md)"));
125131 }
126132
133+#[test]
134+fn the_guide_installs_the_braid_it_describes() {
135+ // The guide is served apart from the code: it installs a tag, so that
136+ // the braid an agent builds is the one the guide was written for, and
137+ // the version check names that version.
138+ let version = env!("CARGO_PKG_VERSION");
139+ let guide = part_one();
140+ let install = format!(
141+ "cargo install --locked --git https://github.com/KikoCis/elffuss-braid --tag v{version} elffuss-braid-cli\n"
142+ );
143+ assert!(guide.contains(&install), "{install}");
144+ assert!(guide.contains(&format!("\"braid {version}\", or newer")));
145+ let printed = braid(Path::new("."), &["--version"]);
146+ assert_eq!(printed, format!("braid {version}\n"));
147+ // The guide's version has `agents init`: an older one is what the check
148+ // sends back to the install.
149+ braid(Path::new("."), &["agents", "init", "--help"]);
150+}
151+
127152 #[test]
128153 fn every_braid_command_in_the_guides_exists_with_its_flags() {
129- let mut commands: Vec<String> = bash_lines(&part_one());
130- commands.extend(bash_lines(&section()));
131- let commands: Vec<String> = commands
132- .into_iter()
133- .filter(|line| line.starts_with("braid "))
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`.
158+ let commands: Vec<String> = lines
159+ .iter()
160+ .flat_map(|line| line.split("||").flat_map(|part| part.split("&&")))
161+ .map(str::trim)
162+ .filter(|command| command.starts_with("braid "))
163+ .map(str::to_owned)
134164 .collect();
135165 assert!(commands.len() >= 15, "{commands:?}");
136- // Subcommands that take a subcommand of their own.
137166 let groups = ["agents", "change", "git", "op", "ref", "workspace"];
138167 for command in &commands {
139- // The words of the command, before any comment.
140168 let words: Vec<&str> = command
141169 .split(" #")
142170 .next()
@@ -144,7 +172,6 @@
144172 .split_whitespace()
145173 .skip(1)
146174 .collect();
147- // Global flags that take a value come before the subcommand.
148175 let mut rest = words.as_slice();
149176 while let [flag, _, tail @ ..] = rest {
150177 if matches!(*flag, "--agent" | "--workspace" | "--repo") {
added crates/cli/tests/sessions.rs +335 −0
@@ -0,0 +1,335 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! End-to-end tests of what an agent session that follows the braid section
5+//! of a project's AGENTS.md relies on: where `workspace add` puts a
6+//! workspace, git refusing to work inside one, the branch it tracks, hints
7+//! that repeat the session's flags, and reading a file as a changeset has
8+//! it.
9+
10+use std::fs;
11+use std::path::{Path, PathBuf};
12+use std::process::{Command, Output};
13+
14+use serde_json::Value;
15+
16+/// Git without the user's or the system's configuration.
17+const GIT_ENV: [(&str, &str); 6] = [
18+ ("GIT_CONFIG_GLOBAL", "/dev/null"),
19+ ("GIT_CONFIG_NOSYSTEM", "1"),
20+ ("GIT_AUTHOR_NAME", "Ada Lovelace"),
21+ ("GIT_AUTHOR_EMAIL", "ada@example.org"),
22+ ("GIT_COMMITTER_NAME", "Ada Lovelace"),
23+ ("GIT_COMMITTER_EMAIL", "ada@example.org"),
24+];
25+
26+/// Runs braid in `dir`, with an author but no agent from the environment.
27+fn braid(dir: &Path, args: &[&str]) -> Output {
28+ Command::new(env!("CARGO_BIN_EXE_braid"))
29+ .current_dir(dir)
30+ .args(args)
31+ .envs(GIT_ENV)
32+ .env("BRAID_AUTHOR", "Ada <ada@example.org>")
33+ .env_remove("BRAID_AGENT")
34+ .output()
35+ .unwrap()
36+}
37+
38+/// Runs braid expecting exit status `code`, and returns what it printed.
39+fn run(dir: &Path, args: &[&str], code: i32) -> String {
40+ let out = braid(dir, args);
41+ assert_eq!(
42+ out.status.code(),
43+ Some(code),
44+ "braid {args:?}: {}{}",
45+ String::from_utf8_lossy(&out.stdout),
46+ String::from_utf8_lossy(&out.stderr)
47+ );
48+ String::from_utf8(out.stdout).unwrap()
49+}
50+
51+fn ok(dir: &Path, args: &[&str]) -> String {
52+ run(dir, args, 0)
53+}
54+
55+fn json(dir: &Path, args: &[&str], code: i32) -> Value {
56+ let mut all = args.to_vec();
57+ all.push("--json");
58+ serde_json::from_str(&run(dir, &all, code)).unwrap()
59+}
60+
61+/// Runs braid expecting it to fail, and returns its error.
62+fn fails(dir: &Path, args: &[&str]) -> String {
63+ let out = braid(dir, args);
64+ assert_eq!(out.status.code(), Some(1), "braid {args:?}");
65+ assert!(out.stdout.is_empty(), "braid {args:?}");
66+ String::from_utf8(out.stderr).unwrap()
67+}
68+
69+fn git(dir: &Path, args: &[&str]) -> Output {
70+ Command::new("git")
71+ .current_dir(dir)
72+ .args(args)
73+ .envs(GIT_ENV)
74+ .output()
75+ .expect("git must be installed to run this test")
76+}
77+
78+fn git_ok(dir: &Path, args: &[&str]) -> String {
79+ let out = git(dir, args);
80+ assert!(
81+ out.status.success(),
82+ "git {args:?}: {}",
83+ String::from_utf8_lossy(&out.stderr)
84+ );
85+ String::from_utf8(out.stdout).unwrap()
86+}
87+
88+/// A git project set up for braid as agents.md does it, on `branch`, with
89+/// one commit of `notes.txt`.
90+fn project(branch: &str) -> (tempfile::TempDir, PathBuf) {
91+ let temp = tempfile::tempdir().unwrap();
92+ let dir = fs::canonicalize(temp.path()).unwrap();
93+ git_ok(&dir, &["init", "--quiet", "-b", branch]);
94+ fs::write(dir.join("notes.txt"), "one\ntwo\n").unwrap();
95+ git_ok(&dir, &["add", "notes.txt"]);
96+ git_ok(&dir, &["commit", "--quiet", "-m", "First"]);
97+ ok(&dir, &["init"]);
98+ let exclude = git_ok(&dir, &["rev-parse", "--git-path", "info/exclude"]);
99+ let exclude = dir.join(exclude.trim());
100+ fs::create_dir_all(exclude.parent().unwrap()).unwrap();
101+ let mut lines = fs::read_to_string(&exclude).unwrap_or_default();
102+ lines.push_str(".braid\n");
103+ fs::write(&exclude, lines).unwrap();
104+ ok(&dir, &["git", "import", "."]);
105+ (temp, dir)
106+}
107+
108+#[test]
109+fn a_workspace_goes_in_braid_work_and_git_refuses_to_work_in_it() {
110+ let (_temp, dir) = project("main");
111+ let deep = dir.join("src/deep");
112+ fs::create_dir_all(&deep).unwrap();
113+ // From anywhere in the project, the workspace goes in .braid/work.
114+ let made = json(&deep, &["workspace", "add", "agent-1"], 0);
115+ let workspace = dir.join(".braid/work/agent-1");
116+ assert_eq!(made["path"], workspace.to_str().unwrap());
117+ assert_eq!(made["files"], 1);
118+ assert!(!deep.join("agent-1").exists());
119+ let guard = fs::read_to_string(workspace.join(".git")).unwrap();
120+ assert!(guard.starts_with("gitdir: "), "{guard}");
121+
122+ // The user's own edit in the shared checkout, and the agent's in its
123+ // workspace.
124+ fs::write(dir.join("notes.txt"), "one, the user's\ntwo\n").unwrap();
125+ fs::write(workspace.join("notes.txt"), "one\ntwo, the agent's\n").unwrap();
126+ for args in [
127+ &["stash"][..],
128+ &["status"],
129+ &["diff"],
130+ &["reset", "--hard"],
131+ &["checkout", "--", "."],
132+ &["clean", "-fdx"],
133+ &["add", "-A"],
134+ &["rev-parse", "--show-toplevel"],
135+ ] {
136+ let out = git(&workspace, args);
137+ assert!(!out.status.success(), "git {args:?} worked in a workspace");
138+ let err = String::from_utf8_lossy(&out.stderr);
139+ assert!(err.contains("not a git repository"), "git {args:?}: {err}");
140+ assert!(err.contains("braid workspace"), "git {args:?}: {err}");
141+ }
142+ assert_eq!(
143+ fs::read_to_string(dir.join("notes.txt")).unwrap(),
144+ "one, the user's\ntwo\n"
145+ );
146+ assert_eq!(git_ok(&dir, &["stash", "list"]), "");
147+
148+ // Braid does not see the guard, nor does the shared checkout's git see
149+ // the workspace.
150+ let status = json(&workspace, &["status"], 0);
151+ assert_eq!(status["modified"], serde_json::json!(["notes.txt"]));
152+ assert_eq!(status["added"], serde_json::json!([]));
153+ assert_eq!(
154+ git_ok(&dir, &["status", "--short"]),
155+ " M notes.txt\n",
156+ "only the user's edit"
157+ );
158+ ok(&workspace, &["commit", "-m", "Agent's edit"]);
159+ ok(&workspace, &["land"]);
160+ ok(&dir, &["workspace", "remove", "agent-1"]);
161+ assert!(!workspace.exists());
162+}
163+
164+#[test]
165+fn outside_a_workspace_the_error_says_how_to_reach_one() {
166+ let (_temp, dir) = project("main");
167+ let err = fails(&dir, &["status"]);
168+ assert!(err.contains("not inside a workspace"), "{err}");
169+ assert!(err.contains("--workspace <name>"), "{err}");
170+ assert!(err.contains(".braid/work/<name>"), "{err}");
171+}
172+
173+#[test]
174+fn a_workspace_tracks_a_branch_the_repository_has() {
175+ let (_temp, dir) = project("master");
176+ let err = fails(&dir, &["workspace", "add", "s2", "--track", "main"]);
177+ assert!(
178+ err.contains("the repository has no branch \"main\"; it has master"),
179+ "{err}"
180+ );
181+ assert!(err.contains("--new-branch"), "{err}");
182+ assert!(!dir.join(".braid/work/s2").exists());
183+ assert_eq!(json(&dir, &["workspace", "list"], 0), serde_json::json!([]));
184+ for own in ["braid/git-map", "tags/v1"] {
185+ let err = fails(&dir, &["workspace", "add", "s3", "--track", own]);
186+ assert!(err.contains("braid's own namespaces"), "{err}");
187+ }
188+
189+ // The branch it has, or a new one on purpose.
190+ let made = json(&dir, &["workspace", "add", "s2", "--track", "master"], 0);
191+ assert_eq!(made["files"], 1);
192+ let made = json(
193+ &dir,
194+ &["workspace", "add", "s4", "--track", "topic", "--new-branch"],
195+ 0,
196+ );
197+ assert_eq!(made["branch"], "topic");
198+ assert_eq!(made["base"], Value::Null);
199+
200+ // A repository with no branch yet takes any name: the first landing
201+ // starts it.
202+ let temp = tempfile::tempdir().unwrap();
203+ let empty = fs::canonicalize(temp.path()).unwrap();
204+ ok(&empty, &["init"]);
205+ let made = json(&empty, &["workspace", "add", "first"], 0);
206+ assert_eq!(made["branch"], "main");
207+}
208+
209+#[test]
210+fn hints_repeat_the_flags_the_session_gave() {
211+ let (_temp, dir) = project("main");
212+ for name in ["agent-1", "agent-2"] {
213+ ok(&dir, &["--agent", name, "workspace", "add", name]);
214+ }
215+ let work = |name: &str| dir.join(".braid/work").join(name);
216+ fs::write(work("agent-1").join("notes.txt"), "one, from 1\ntwo\n").unwrap();
217+ fs::write(work("agent-2").join("notes.txt"), "one, from 2\ntwo\n").unwrap();
218+ let session = |name: &'static str| ["--agent", name, "--workspace", name];
219+ for name in ["agent-1", "agent-2"] {
220+ let mut args = session(name).to_vec();
221+ args.extend(["commit", "-m", name]);
222+ ok(&dir, &args);
223+ }
224+ let mut land = session("agent-1").to_vec();
225+ land.push("land");
226+ ok(&dir, &land);
227+
228+ // From the project root, as a shell that does not keep its directory
229+ // runs them: the hints name the agent and the workspace.
230+ let mut land = session("agent-2").to_vec();
231+ land.push("land");
232+ let landed = json(&dir, &land, 2);
233+ assert_eq!(landed["outcome"], "conflicts");
234+ assert_eq!(
235+ landed["next"],
236+ "braid --agent agent-2 --workspace agent-2 update"
237+ );
238+ let said = run(&dir, &land, 2);
239+ assert!(
240+ said.contains("Run `braid --agent agent-2 --workspace agent-2 update`"),
241+ "{said}"
242+ );
243+ let mut update = session("agent-2").to_vec();
244+ update.push("update");
245+ let updated = json(&dir, &update, 2);
246+ assert_eq!(
247+ updated["next"],
248+ "braid --agent agent-2 --workspace agent-2 commit"
249+ );
250+ // The same flags after the command name count as well.
251+ let status = run(
252+ &dir,
253+ &["status", "--workspace", "agent-2", "--agent", "agent-2"],
254+ 0,
255+ );
256+ assert!(
257+ status.contains("then `braid --agent agent-2 --workspace agent-2 commit`"),
258+ "{status}"
259+ );
260+ // Settled, committed and landed as the hints say, the op log names the
261+ // session for each step.
262+ fs::write(
263+ work("agent-2").join("notes.txt"),
264+ "one, from 1 and 2\ntwo\n",
265+ )
266+ .unwrap();
267+ let commit = run(
268+ &dir,
269+ &["--agent", "agent-2", "--workspace", "agent-2", "commit"],
270+ 0,
271+ );
272+ assert!(
273+ commit.contains("`braid --agent agent-2 --workspace agent-2 land` when ready"),
274+ "{commit}"
275+ );
276+ ok(&dir, &land);
277+ let ops = json(&dir, &["op", "log", "-n", "1"], 0);
278+ assert_eq!(ops[0]["agent"], "agent-2");
279+
280+ // agent-1 is behind now. A label that a shell would split is quoted.
281+ let behind = run(
282+ &dir,
283+ &["--agent", "agent one", "--workspace", "agent-1", "status"],
284+ 0,
285+ );
286+ assert!(
287+ behind.contains("run `braid --agent 'agent one' --workspace agent-1 update`"),
288+ "{behind}"
289+ );
290+ // With no flags, the hints are as plain as ever.
291+ let behind = run(&work("agent-1"), &["status"], 0);
292+ assert!(behind.contains("run `braid update`"), "{behind}");
293+}
294+
295+#[test]
296+fn cat_object_reads_a_file_as_a_changeset_has_it() {
297+ let (_temp, dir) = project("main");
298+ ok(&dir, &["workspace", "add", "agent-1"]);
299+ let workspace = dir.join(".braid/work/agent-1");
300+ fs::create_dir_all(workspace.join("src")).unwrap();
301+ fs::write(workspace.join("src/lib.rs"), "fn a() {}\n").unwrap();
302+ ok(&workspace, &["commit", "-m", "Add src/lib.rs"]);
303+ fs::write(workspace.join("notes.txt"), "one, changed\ntwo\n").unwrap();
304+ let base = json(&workspace, &["status"], 0)["base"]
305+ .as_str()
306+ .unwrap()
307+ .to_owned();
308+
309+ // The base's version of an edited file: what reviewing or undoing the
310+ // edit needs.
311+ assert_eq!(
312+ ok(&workspace, &["cat-object", &format!("{base}:notes.txt")]),
313+ "one\ntwo\n"
314+ );
315+ assert_eq!(
316+ ok(
317+ &workspace,
318+ &["cat-object", &format!("{}:src/lib.rs", &base[..12])]
319+ ),
320+ "fn a() {}\n"
321+ );
322+ assert_eq!(ok(&dir, &["cat-object", "main:notes.txt"]), "one\ntwo\n");
323+ let blob = json(&dir, &["cat-object", "main:./notes.txt"], 0);
324+ assert_eq!(blob["kind"], "blob");
325+ assert_eq!(blob["size"], 8);
326+ let tree = json(&workspace, &["cat-object", &format!("{base}:src")], 0);
327+ assert_eq!(tree["kind"], "tree");
328+ assert_eq!(json(&dir, &["cat-object", "main:"], 0)["kind"], "tree");
329+ let err = fails(&dir, &["cat-object", "main:src/lib.rs"]);
330+ assert!(
331+ err.contains("no file or directory at \"src/lib.rs\""),
332+ "{err}"
333+ );
334+ fails(&dir, &["cat-object", "nope:notes.txt"]);
335+}
modified crates/repo/src/lib.rs +1 −1
@@ -48,7 +48,7 @@
4848 git_ref_for_braid, is_branch, remote_ref,
4949 };
5050 pub use history::{RepoHistory, StoreIndex};
51-pub use link::{Location, WORKSPACES_DIR, WorkspaceLink, locate};
51+pub use link::{Location, WORK_DIR, WORKSPACES_DIR, WorkspaceLink, locate};
5252 pub use remote::Remote;
5353 pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport};
5454
modified crates/repo/src/link.rs +5 −0
@@ -27,6 +27,11 @@
2727 /// workspace.
2828 pub const WORKSPACES_DIR: &str = "ws";
2929
30+/// Directory inside `.braid` where workspaces go unless told otherwise:
31+/// `.braid/work/<name>`, inside the project, where git ignores them along
32+/// with the rest of `.braid`.
33+pub const WORK_DIR: &str = "work";
34+
3035 /// The first line of a workspace file.
3136 const HEADER: &str = "braid-workspace 1";
3237
modified crates/wc/src/error.rs +18 −2
@@ -48,7 +48,9 @@
4848 Assemble(#[from] braid_format::ChangesetError),
4949
5050 /// The current directory is not inside a workspace.
51- #[error("not inside a workspace; create one with `braid workspace add <name>`")]
51+ #[error(
52+ "not inside a workspace: run this in your workspace's directory, or pass --workspace <name> (`braid workspace list` shows them; `braid workspace add <name>` makes one in .braid/work/<name>)"
53+ )]
5254 NotAWorkspace,
5355
5456 /// A workspace name that is not allowed.
@@ -145,7 +147,7 @@
145147 /// The working copy cannot be committed as it is: conflict markers
146148 /// remain, conflicts are not marked resolved, or new files wait for
147149 /// `braid track`. Every reason is listed, as `status` lists them.
148- #[error("cannot commit yet:\n{}\nSettle these first, or commit anyway with --force: files waiting for `braid track` stay out.", reasons(.0))]
150+ #[error("cannot commit yet:\n{}\n{}", reasons(.0), advice(.0))]
149151 Blocked(Vec<Blocker>),
150152
151153 /// There is nothing to commit.
@@ -226,6 +228,20 @@
226228 /// How many reasons a refusal lists, at most.
227229 const REASONS_SHOWN: usize = 20;
228230
231+/// What to do about a refused commit. `--force` commits past conflicts as
232+/// they are, markers and all, so it is offered as a way out only when the
233+/// guard alone holds files back.
234+fn advice(blockers: &[Blocker]) -> &'static str {
235+ if blockers
236+ .iter()
237+ .any(|blocker| !matches!(blocker, Blocker::NeedsTrack(_)))
238+ {
239+ "Settle these first. --force would commit the conflicts as they are, markers and all, and leave out the files waiting for `braid track`."
240+ } else {
241+ "Move a secret out of the workspace, `braid track` a file that is not one, or commit without them with --force."
242+ }
243+}
244+
229245 fn reasons(blockers: &[Blocker]) -> String {
230246 let mut shown: Vec<String> = blockers
231247 .iter()
modified crates/wc/src/lib.rs +8 −3
@@ -9,7 +9,12 @@
99 //!
1010 //! A workspace is any directory holding a `.braid` file. The file is local
1111 //! and never tracked; it names the repository and the workspace (see
12-//! [`braid_repo::WorkspaceLink`]). The workspace's state lives in the
12+//! [`braid_repo::WorkspaceLink`]). Next to it, a `.git` file whose
13+//! `gitdir:` line points nowhere ([`GIT_GUARD`]) makes git stop with "not a
14+//! git repository" inside the workspace, instead of finding the repository
15+//! of a checkout around it and acting on that. The walk skips both. A
16+//! workspace goes in `.braid/work/<name>` of the repository unless told
17+//! otherwise ([`Workspace::default_dir`]). Its state lives in the
1318 //! repository, in `.braid/ws/<name>/`:
1419 //!
1520 //! ```text
@@ -81,6 +86,6 @@
8186 pub use state::{Checkout, Rebase, RecordedConflict, State};
8287 pub use status::{ChangeKind, GUARD_SIZE, PathChange, Status, is_guarded};
8388 pub use workspace::{
84- BEHIND_LIMIT, CommitOutcome, CommitRequest, LandReport, Landed, Placed, RebaseProgress,
85- StatusReport, UpdateReport, Updated, Workspace,
89+ BEHIND_LIMIT, CommitOutcome, CommitRequest, GIT_GUARD, GIT_GUARD_TEXT, LandReport, Landed,
90+ Placed, RebaseProgress, StatusReport, UpdateReport, Updated, Workspace,
8691 };
modified crates/wc/src/workspace.rs +26 −3
@@ -19,7 +19,7 @@
1919 Conflict, EMPTY_TREE, first_parent_chain_contains, read_changes, read_changeset,
2020 };
2121 use braid_format::{Change, ChangeOp, Kind, ObjectId, Objects, Signature};
22-use braid_repo::{DIR, Repo, WORKSPACES_DIR, WorkspaceLink};
22+use braid_repo::{DIR, Repo, WORK_DIR, WORKSPACES_DIR, WorkspaceLink};
2323 use braid_store::{RefUpdate, Store, TransactError};
2424
2525 use crate::blocker::{Blocker, blockers};
@@ -334,16 +334,32 @@
334334 format!("{prefix}: {outcome} {moves} ({merged} merged)")
335335 }
336336
337+/// The file every workspace holds so that git refuses to work in it.
338+pub const GIT_GUARD: &str = ".git";
339+
340+/// What it says. Git reads the line as the path of a repository, finds
341+/// none, and stops with "not a git repository: " and that path, so the text
342+/// is written to read well there.
343+pub const GIT_GUARD_TEXT: &str =
344+ "gitdir: this is a braid workspace, not a git checkout: use braid here\n";
345+
337346 impl<'r> Workspace<'r> {
338347 /// The directory that holds every workspace's state.
339348 pub fn states_dir(repo: &Repo) -> PathBuf {
340349 repo.root().join(DIR).join(WORKSPACES_DIR)
341350 }
342351
352+ /// Where the workspace named `name` goes unless told otherwise:
353+ /// `.braid/work/<name>` in the repository's root.
354+ pub fn default_dir(repo: &Repo, name: &str) -> PathBuf {
355+ repo.root().join(DIR).join(WORK_DIR).join(name)
356+ }
357+
343358 /// Creates a workspace named `name` in `dir`, which must not exist or be
344359 /// empty, at the changeset `at` (`None` for the empty tree), tracking
345- /// `branch`. Writes the whole tree. Returns the workspace and how many
346- /// files it wrote. On failure, nothing is left behind.
360+ /// `branch`. Writes the `.braid` file that names the workspace, the
361+ /// [`GIT_GUARD`] file, and the whole tree. Returns the workspace and how
362+ /// many files of the tree it wrote. On failure, nothing is left behind.
347363 pub fn create(
348364 repo: &'r Repo,
349365 name: &str,
@@ -413,6 +429,13 @@
413429 fs::File::create_new(&link_path)
414430 .and_then(|mut file| io::Write::write_all(&mut file, &link.encode()))
415431 .map_err(Error::io("write", &link_path))?;
432+ // Without it, git run in the workspace finds the repository of a
433+ // checkout around it, often the shared one the workspace sits in,
434+ // and stashes, resets or commits there. The walk skips `.git`.
435+ let guard = dir.join(GIT_GUARD);
436+ fs::File::create_new(&guard)
437+ .and_then(|mut file| io::Write::write_all(&mut file, GIT_GUARD_TEXT.as_bytes()))
438+ .map_err(Error::io("write", &guard))?;
416439
417440 let workspace = Workspace {
418441 repo,
modified docs/design.md +80 −28
@@ -247,13 +247,27 @@
247247 - One workspace per agent, all sharing one store. No staging area: tracked
248248 files are snapshotted as they are.
249249 - A workspace is any directory holding a `.braid` *file*, local and never
250- tracked, that names the repository and the workspace. The workspace's state
251- lives in the repository, under `.braid/ws/<name>/`: `state` (the base
252- changeset, the branch it lands on, its directory, the file system's name
253- rules, a rebase in progress), `stat` (the stat cache) and `lock`. Every
254- command that changes a workspace holds its lock, so two processes never
255- change one workspace at once; different workspaces never wait for each
256- other, except for the short transaction in which a landing moves a branch.
250+ tracked, that names the repository and the workspace. It goes in
251+ `.braid/work/<name>` of the repository unless `workspace add` is given a
252+ directory, and it tracks a branch the repository has: a branch that does
253+ not exist would give an empty checkout whose first landing starts a new
254+ history under that name, so it is refused unless the repository has no
255+ branch yet or `--new-branch` asks for it.
256+- Every workspace also holds a `.git` *file* whose `gitdir:` line points
257+ nowhere. A workspace inside a git checkout, as `.braid/work/` is, would
258+ otherwise let git run in it find that checkout's repository, and `git
259+ stash` or `git reset --hard` there would act on the shared checkout's
260+ files. With the file, git stops with "not a git repository" instead. The
261+ walk skips `.git`, as it skips `.braid`, so neither is ever committed.
262+ `braid cat-object <base>:<path>` gives what git would have for a review
263+ or an undo: the file as the workspace's base has it.
264+- The workspace's state lives in the repository, under
265+ `.braid/ws/<name>/`: `state` (the base changeset, the branch it lands on,
266+ its directory, the file system's name rules, a rebase in progress),
267+ `stat` (the stat cache) and `lock`. Every command that changes a
268+ workspace holds its lock, so two processes never change one workspace at
269+ once; different workspaces never wait for each other, except for the
270+ short transaction in which a landing moves a branch.
257271 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger than
258272 1 MiB need an explicit `braid track`. Until then `braid commit` refuses,
259273 naming them, and `--force` leaves them out.
@@ -307,35 +321,73 @@
307321 ### Instructions for agents
308322
309323 Coding agents learn a project's rules from its `AGENTS.md`, or, for Claude
310-Code, from a `CLAUDE.md` that can include it. `braid agents init` writes
311-there what an agent needs to work through braid, so that a project set up
312-once tells every later session, whatever harness runs it. The guide that
313-sets a project up is part 1 of the repository's `AGENTS.md`, which the site
314-also serves as `agents.md`.
324+Code and Gemini CLI, from a `CLAUDE.md` or a `GEMINI.md` that can include
325+it. `braid agents init` writes there what an agent needs to work through
326+braid, so that a project set up once tells every later session, whatever
327+harness runs it. The guide that sets a project up is part 1 of the
328+repository's `AGENTS.md`, which the site also serves as `agents.md`. It
329+installs braid from the tag of the version it describes, since the site
330+serves it apart from the code.
315331
316332 - **A section of the file, not the file.** The rules sit between a line
317333 `<!-- braid:start -->` and a line `<!-- braid:end -->`, appended to the
318334 file the first time and rewritten in place after that. Text outside them
319335 is never touched, a second run changes nothing, and markers that do not
320- pair up are refused before anything is written. A `CLAUDE.md` that does
321- not include `AGENTS.md` gets the line `@AGENTS.md`, and nothing else.
322- Files are written through a temporary file and a rename; a symbolic link
323- stays one, and the file it points to is the one replaced.
324-- **Workspaces under `.braid/work/`.** The section has each session create
325- its workspace at `.braid/work/<name>`: inside the project, where a
326- harness that only lets an agent write in the project can reach it; inside
327- `.braid/`, which the setup has git ignore, so that the shared checkout's
328- git never sees the workspaces; and gone with `.braid/` when braid is
329- taken out.
336+ pair up are refused before anything is written. Marker lines inside
337+ fenced code blocks are examples, not markers, and a file that ends inside
338+ an open block, where the section would read as code, is refused; a byte
339+ order mark before the first line stays where it is. A `CLAUDE.md` or a
340+ `GEMINI.md` that does not include `AGENTS.md` outside code gets the line
341+ `@AGENTS.md`, and nothing else.
342+- **Files written whole, or not at all.** Every check comes before any
343+ write, and the same checks run with `--dry-run`: a name that is not a
344+ regular file, a symbolic link out of the project, where other projects
345+ may read the file, a read-only file, and a file with hard links other
346+ than the project's guides are refused. Each file is written to a
347+ temporary file next to it, all of them before the first is renamed into
348+ place, so a failure while writing leaves every file as it was; one with
349+ hard links, `CLAUDE.md` and `AGENTS.md` as one file, say, is written in
350+ place, so that its names stay one file. A symbolic link stays one: the
351+ file it points to is the one written, and the JSON names it.
352+- **Only where braid is set up.** The section is committed, so every clone
353+ of the project has it, including clones where braid is not set up: CI,
354+ other machines, other people's agents. Its first rule says that a
355+ checkout without a `.braid` directory does not use braid, and that braid
356+ is set up there only when the user asks.
357+- **Workspaces under `.braid/work/`.** Each session creates its workspace
358+ at `.braid/work/<name>`, where `workspace add` puts it by default: inside
359+ the project, where a harness that only lets an agent write in the
360+ project can reach it; inside `.braid/`, which the setup has git ignore,
361+ so that the shared checkout's git never sees the workspaces; and gone
362+ with `.braid/` when braid is taken out. The setup's exclude line is
363+ `.braid`, which also covers the `.braid` file of a workspace made
364+ anywhere else in the checkout, since that file names the repository by
365+ its absolute path. Git does not run in a workspace (see
366+ [Workspaces](#workspaces)), and the section says why, and what to use
367+ instead.
330368 - **The branch.** The section names the branch agents land on: the one
331- `--branch` gives; else the one the section already names, so that a
332- later run keeps it; else, inside a workspace, the one it tracks; else
333- `main`, `master` or the repository's only branch. With several branches
334- and neither of those, the command asks for `--branch` rather than guess.
369+ `--branch` gives, which the repository must have; else the one the
370+ section already names, if the repository has it, so that a later run
371+ keeps it; else, inside a workspace, the one it tracks; else `main`,
372+ `master` or the repository's only branch. A branch the section names but
373+ the repository does not have was named before the project's history came
374+ in, or has been removed since: it is chosen again, and the command says
375+ so. With several branches and none of those, or with no repository or
376+ branch yet, the command asks for `--branch` rather than guess. The name
377+ goes into shell commands and is read back from the section, so it takes
378+ only characters that need no quoting.
335379 - **Every command names its agent.** A harness may run each command in a
336380 new shell, which keeps neither variables nor the current directory, so
337- the section passes `--agent` on every command, and `--workspace` lets
338- them run from the project root.
381+ the section passes `--agent` on every command that records an operation
382+ or a changeset, sync and undo included, and `--workspace` lets them run
383+ from the project root. The hints braid prints, and `next` in its JSON,
384+ repeat the `--repo`, `--agent` and `--workspace` typed on the command
385+ line, so that a session that follows them stays the same session.
386+- **What landed, and where.** A landing moves braid's branch only: the
387+ shared checkout and the git remote get it from `braid git sync` and
388+ `git pull --ff-only`. The section has a session that finishes say so to
389+ the user, and offer to run them, rather than leave the user looking at
390+ files that did not change.
339391
340392 ## Git bridge
341393
modified fuzz/Cargo.lock +2 −2
@@ -256,7 +256,7 @@
256256
257257 [[package]]
258258 name = "elffuss-braid-format"
259-version = "0.0.1"
259+version = "0.0.2"
260260 dependencies = [
261261 "blake3",
262262 "unicode-normalization",
@@ -273,7 +273,7 @@
273273
274274 [[package]]
275275 name = "elffuss-braid-git"
276-version = "0.0.1"
276+version = "0.0.2"
277277 dependencies = [
278278 "elffuss-braid-format",
279279 "gix",
modified site/README.md +16 −7
@@ -107,9 +107,12 @@
107107 prints (it names the directory), and change the hero card and the story
108108 together.
109109 - The prompt under "Ask your agent" is the same, word for word, in the
110- English page, in the README and in `llms.txt`, and `agents.md` is part 1
111- of `AGENTS.md`: `crates/cli/tests/agents.rs` checks both. Every command
112- `agents.md` gives runs as written.
110+ English page, in the README and in `llms.txt`, and so is its Spanish in
111+ the Spanish page and in the README's Spanish part. `agents.md` is part 1
112+ of `AGENTS.md`, and its install command names the tag of the version in
113+ `Cargo.toml`. `crates/cli/tests/guides.rs` checks all of this, and that
114+ every braid command `agents.md` gives exists with its flags; every
115+ command it gives runs as written.
113116 - The quick start and the agent's commands under "Many agents on one
114117 repository" run as one session, top to bottom. `braid undo` comes after the
115118 agent lands, so it takes that landing back; before it, it would take the
@@ -125,21 +128,27 @@
125128 `scripts/privacy-check.sh` passes. The quick start clones and builds it,
126129 and CI has run on it: the story says CI runs the scene on every push to
127130 `main`.
128-2. Every link into the repository answers from `main`. Check them against
131+2. The tag that `agents.md` installs (`--tag v` and the version in
132+ `Cargo.toml`) is on GitHub, at a commit of `main` that holds this tree.
133+ Push the commits and the tag first and serve the page after, never the
134+ other way round: `agents.md` is served apart from the code, and an
135+ agent that follows it before the tag is there gets an error from cargo
136+ instead of braid.
137+3. Every link into the repository answers from `main`. Check them against
129138 what `main` holds, not against github.com, which answers 200 for any path
130139 of an empty repository: a file answers 200 at
131140 `https://raw.githubusercontent.com/KikoCis/elffuss-braid/main/<path>`,
132141 and a directory (`crates/sim`, `fuzz/fuzz_targets`, `bench`) is listed by
133142 `gh api 'repos/KikoCis/elffuss-braid/contents/<path>?ref=main'`.
134-3. The text matches `main`. The ratios block, for one, lists the work on
143+4. The text matches `main`. The ratios block, for one, lists the work on
135144 speed that came after the commit measured, and that list grows.
136-4. `https://braid.elffuss.com/` answers 200 with a certificate for that
145+5. `https://braid.elffuss.com/` answers 200 with a certificate for that
137146 name, `http://braid.elffuss.com/` redirects to it, and
138147 `https://braid.elffuss.com/og.png` answers 200 as `image/png`. Only then
139148 does the link go anywhere: the repository's homepage
140149 (`gh repo edit KikoCis/elffuss-braid --homepage https://braid.elffuss.com`),
141150 and posts, whose link previews are fetched once and kept.
142-5. `https://braid.elffuss.com/agents.md` answers 200 as
151+6. `https://braid.elffuss.com/agents.md` answers 200 as
143152 `text/markdown; charset=utf-8` and `https://braid.elffuss.com/llms.txt`
144153 as `text/plain; charset=utf-8`, so that an agent reads them as text:
145154 `curl -sI` shows the type. A server that does not know `.md` may send
modified site/agents.md +178 −80
@@ -1,7 +1,10 @@
11 # Braid for coding agents: install it and set it up
22
33 Instructions for a coding agent asked to install braid in a project and set
4-it up for agents. The same text is part 1 of
4+it up for agents. Read this file whole before you run anything, as it is
5+written: fetch it with `curl -fsSL https://braid.elffuss.com/agents.md`
6+rather than with a tool that summarises pages. Then run its commands
7+exactly as they are given. The same text is part 1 of
58 [AGENTS.md](https://github.com/KikoCis/elffuss-braid/blob/main/AGENTS.md)
69 in braid's repository.
710
@@ -18,99 +21,165 @@
1821
1922 ## Install
2023
21-Braid builds from source with cargo. It needs Rust 1.89 or newer (from
22-<https://rustup.rs>) and git.
24+Braid builds from source with cargo. It needs:
25+
26+- Rust 1.89 or newer (`rustc --version` says which; <https://rustup.rs>
27+ installs it), a C compiler (`cc`), git, and a POSIX shell such as bash:
28+ every command here is written for one.
29+- Linux, macOS or another Unix-like system. Windows is not tested yet: use
30+ WSL there.
31+- The network, and permission to write in cargo's directory, `~/.cargo`.
32+ A sandboxed harness blocks both by default: ask the user to allow them,
33+ or to run the command themselves.
2334
2435 ```bash
25-cargo install --locked --git https://github.com/KikoCis/elffuss-braid elffuss-braid-cli
36+cargo install --locked --git https://github.com/KikoCis/elffuss-braid --tag v0.0.2 elffuss-braid-cli
2637 ```
2738
28-This puts a `braid` binary in cargo's bin directory, `~/.cargo/bin` unless
29-`CARGO_HOME` says otherwise, which must be on `PATH`. Running the same
30-command again upgrades it.
39+It compiles braid and its dependencies from source, which takes a while:
40+give the command a long timeout, or run it in the background, since a
41+command cut short starts again from the beginning. It puts a `braid` binary
42+in cargo's bin directory, `~/.cargo/bin` unless `CARGO_HOME` says
43+otherwise. If that directory is not on `PATH`, call braid as
44+`"$HOME/.cargo/bin/braid"` wherever this file says `braid`: a harness may
45+not keep a changed `PATH` from one command to the next. Running the same
46+command again replaces an older braid with this version.
3147
3248 ## Is it installed, and set up here?
3349
3450 ```bash
35-braid --version # prints "braid" and its version once it is installed
51+braid --version # "braid 0.0.2", or newer, once it is installed
3652 braid refs # in the project root: its branches, once it is set up
3753 ```
3854
39-Before it is installed, `braid --version` fails with "command not found"
40-(or cargo's bin directory is not on `PATH`). In a project where braid is
41-not set up, `braid refs` fails with "not inside a braid repository".
55+- Before braid is installed, `braid --version` fails with "command not
56+ found", as it does while cargo's bin directory is not on `PATH`. An older
57+ braid, or one that says `agents` is not a subcommand, needs the install
58+ command again.
59+- In a project where braid is not set up, `braid refs` fails with "not
60+ inside a braid repository". Where it lists the project's branches and
61+ `AGENTS.md` has a braid section (a `<!-- braid:start -->` line), braid is
62+ set up: skip to "Every agent session, from then on".
4263
4364 ## Set up a project
4465
45-Do this once, in the root of the project's git checkout: on its main
46-branch, with nothing to commit (`git status`) and nothing new to pull
47-(`git pull --ff-only`). The commands say `main`; if the project's main
48-branch has another name, such as `master`, write that instead.
66+First read the project's `AGENTS.md`, `CLAUDE.md` and the like for rules
67+about git: branches, pull requests, how to commit. Look too for what braid
68+does not run: git hooks (in `.git/hooks`, or where
69+`git config core.hooksPath` says), Git LFS (`filter=lfs` in
70+`.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+
75+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.
4982
5083 ```bash
51-braid init # creates .braid/, for the store and the agents' workspaces
52-echo '/.braid/' >> "$(git rev-parse --git-path info/exclude)"
53-printf 'name = %s\nemail = %s\n' "$(git config user.name)" "$(git config user.email)" > .braid/config
84+test -d .braid || braid init # .braid/: the store and the agents' workspaces
85+grep -qsxF .braid "$(git rev-parse --git-path info/exclude)" || echo .braid >> "$(git rev-parse --git-path info/exclude)"
86+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
5488 braid git import . # the project's whole history: every local branch and tag
5589 braid agents init # the rules for agents, in AGENTS.md
5690 ```
5791
58-- The second line makes git ignore `.braid/` in this checkout only, so that
59- nothing of braid's is ever committed with git.
92+- The second line makes git ignore every `.braid` in this checkout, and
93+ only in this one: braid's directory, and the `.braid` file that marks
94+ each workspace, so that nothing of braid's is ever committed with git.
6095 - `.braid/config` names who signs the changesets agents make, here the
6196 same person as git's commits. If git has no `user.name` or `user.email`,
62- write them in by hand; otherwise every session has to set `BRAID_AUTHOR`.
97+ write them into it by hand; otherwise every session has to set
98+ `BRAID_AUTHOR`.
99+- Most harnesses read `AGENTS.md`. Claude Code reads `CLAUDE.md` instead,
100+ and Gemini CLI `GEMINI.md`: `braid agents init` adds the line
101+ `@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`.
63106 - `braid agents init` writes a section into `AGENTS.md`, creating the file
64107 if there is none, between a `<!-- braid:start -->` line and a
65108 `<!-- braid:end -->` line. The section tells every agent session to work
66109 in a workspace of its own and to land through braid, and names the branch
67- agents land on: `main`, `master`, or the project's only branch.
68- `--branch <name>` names another, and `--dry-run` shows what it would
69- write. Text outside the markers is never touched, and running it again
70- rewrites the section in place.
71-- If the project has a `CLAUDE.md`, `braid agents init` adds the line
72- `@AGENTS.md` to it, so that Claude Code reads the section too. If agents
73- work on the project with Claude Code and there is no `CLAUDE.md`, run
74- `touch CLAUDE.md` before `braid agents init`.
110+ agents land on: `main`, `master`, or the project's only branch. With
111+ several, it asks for `--branch <name>`, which must name a branch the
112+ project has. `--dry-run` shows what it would write. Text outside the
113+ markers is never touched, and running it again rewrites the section in
114+ place.
75115
76116 Commit what `braid agents init` wrote, so that every workspace and every
77-clone has the rules, then import that commit too:
117+clone has the rules, then import that commit too. From this commit on,
118+agents in every clone of the project read the section: tell the user so
119+before you commit. Where `braid agents init` found the files as they
120+should be already, there is nothing to commit, and the `git commit` line
121+does nothing.
78122
79123 ```bash
80124 git add AGENTS.md
81-test -f CLAUDE.md && git add CLAUDE.md
82-git commit -m "Set up braid for agents"
125+if [ -f CLAUDE.md ]; then git add CLAUDE.md; fi
126+if [ -f GEMINI.md ]; then git add GEMINI.md; fi
127+git diff --cached --quiet || git commit -m "Set up braid for agents"
83128 braid git import . # braid's main takes the commit
84129 braid log main -n 1 # and shows it
85130 ```
86131
87-## Every agent session, from then on
132+If `AGENTS.md`, `CLAUDE.md` or `GEMINI.md` is a symbolic link,
133+`braid agents init` writes the file it points to, and names it: `git add`
134+that file as well.
88135
89-The section in the project's `AGENTS.md` tells each session what to do. In
90-short:
136+## Every agent session, from then on
91137
138+The section in the project's `AGENTS.md` tells each session what to do,
139+with the branch it names where the commands here say `main`. In short:
140+
141+- **Only where braid is set up.** A checkout with no `.braid` directory in
142+ its root (a fresh clone, CI, another machine) does not use braid: agents
143+ there work with git, as the project's other rules say, and set braid up
144+ only when the user asks. With `.braid` but no `braid` command, braid is
145+ not on `PATH`: `"$HOME/.cargo/bin/braid"` may be there, or it needs
146+ installing.
92147 - **Never edit files, `git add`, `git commit` or `git push` in the project
93- root.** It is the shared checkout. Every session works in a workspace of
94- its own, under `.braid/work/`.
95-- **Start** from the project root with a workspace named for the session:
96- 1 to 64 letters, digits, `.`, `_` or `-`. `braid workspace list` shows the
97- names taken, and a name that is taken is refused. Then edit, build and
98- test only in that directory. A workspace is a whole checkout of the
99- branch, so builds in it start from scratch.
148+ root.** It is the shared checkout, where the user works. Every session
149+ works in a workspace of its own, under `.braid/work/`.
150+- **Start** with a workspace named for the session: 1 to 64 ASCII letters,
151+ digits, `.`, `_` or `-`, starting with a letter or a digit.
152+ `braid workspace list` shows the names taken, and a name that is taken is
153+ refused. Wherever it runs in the project, `braid workspace add` puts the
154+ workspace in `.braid/work/<name>` of the project root, and it refuses a
155+ branch the project does not have. Then edit, build and test only in that
156+ directory. A workspace is a whole checkout of the branch, so builds in it
157+ start from scratch.
100158
101159 ```bash
102- braid workspace add agent-1 .braid/work/agent-1 --track main
103- cd .braid/work/agent-1
160+ braid workspace add agent-1 --track main
161+ cd .braid/work/agent-1 # from the project root
104162 ```
105163
106-- **Use braid, not git, in the workspace.** It has no `.git` of its own, so
107- `git` there finds the shared checkout's repository and knows nothing of
108- the session's work. `braid --agent agent-1 status` says what changed.
164+- **No git in the workspace.** A workspace holds a `.git` file that points
165+ nowhere, so `git` fails there with "not a git repository" instead of
166+ acting on the shared checkout around it, where `git stash`, `reset`,
167+ `checkout`, `restore`, `clean`, `add` or `commit` would change the user's
168+ files. Do not get around it with `git -C` or `GIT_DIR`. A build or test
169+ script that finds the project with git (`git rev-parse --show-toplevel`)
170+ fails in a workspace too: run its steps yourself. To see what an edit
171+ changed, compare the file with the workspace's `base`, which
172+ `braid status --json` gives, from the workspace's root:
173+ `braid cat-object <base>:<path> | diff -u - <path>`. To undo an edit,
174+ write the base's version back with
175+ `braid cat-object <base>:<path> > <path>`; a file the workspace added has
176+ none, so delete it.
109177 - **Record and land** from the workspace. `--agent` (or `BRAID_AGENT`)
110178 names the session in the op log and in every changeset it makes; pass it
111179 every time, since a harness may not keep variables between commands. If
112180 the shell does not keep its directory either, add `--workspace agent-1`
113- and run the commands from the project root.
181+ and run the commands from the project root. The hints braid prints, and
182+ `next` in its JSON, repeat the `--agent` and `--workspace` given.
114183
115184 ```bash
116185 braid --agent agent-1 status --json
@@ -119,28 +188,43 @@
119188 ```
120189
121190 There is no staging area: `commit` records every change in the
122- workspace. `land` puts the workspace's changesets on `main`, as a
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
123196 fast-forward or rebased onto whatever landed first.
124197 - **Before a new task**, `braid --agent agent-1 update` brings the
125198 workspace onto `main`. `status --json` says how far behind it is
126199 (`behind_by`).
200+- **When the session finishes**, what it landed is on braid's `main` only.
201+ The user's checkout and the git remote get it with `braid git sync`, then
202+ `git pull --ff-only`, both from the project root (see "Keeping the git
203+ remote up to date"). The session tells the user so, and offers to run
204+ them: when to sync is the user's call.
127205 - **Done**: once everything has landed, `braid workspace remove agent-1`
128206 from the project root. It refuses while the workspace holds work that
129207 has not landed.
130-- Every command takes `--json`. Changesets are signed by `BRAID_AUTHOR`
131- (`"Name <email>"`), or else by the `name` and `email` in `.braid/config`.
208+- Every command takes `--json`. Exit status 2 is a conflict, and 1 a
209+ failure, which braid prints as text on standard error, with nothing on
210+ standard output, even with `--json`; only `git sync` and `fsck` print
211+ their report as well when they exit with 1.
212+- Changesets are signed by `BRAID_AUTHOR` (`"Name <email>"`), or else by
213+ the `name` and `email` in `.braid/config`.
132214 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger
133215 than 1 MiB are held back until `braid track <path>`: `commit` refuses,
134- naming them, and `--force` leaves them out.
216+ naming them, and `--force` leaves them out. Never `braid track` a secret:
217+ move it out of the workspace.
135218
136219 ## Conflicts
137220
138221 When another agent landed a change to the same lines first, `land` exits
139-with status 2 and leaves `main` where it was. Exit status 2 also means a
140-command line braid could not parse, so check the JSON: only a conflict
141-prints `"outcome": "conflicts"`. Each conflict names its sides: `base`,
142-`branch` (what `main` holds now) and `workspace` (the session's own
143-change), and `next` says what to run.
222+with status 2 and leaves `main` where it was, and `update` exits with 2 as
223+it writes the conflicts into the files. Exit status 2 also means a command
224+line braid could not parse, which prints only an error, so read the JSON:
225+a conflict's `outcome` is `conflicts`. Each conflict names its sides:
226+`base`, `branch` (what `main` holds now) and `workspace` (the session's
227+own change), and `next` says what to run.
144228
145229 ```bash
146230 braid --agent agent-1 update # exit status 2: conflict markers in the files
@@ -150,7 +234,9 @@
150234 ```
151235
152236 `braid resolve <path>` settles conflicts that are not about content, such
153-as a file deleted on one side and changed on the other.
237+as a file deleted on one side and changed on the other. Never
238+`commit --force` while a rebase is in progress: it would commit the
239+conflict markers as they are.
154240
155241 ## Keeping the git remote up to date
156242
@@ -159,25 +245,31 @@
159245 braid's branch when only the remote moved, pushes braid's branch when only
160246 braid moved, and when both moved, merges them and pushes the merge. The
161247 push is a fast-forward with a lease on what was just fetched, so the
162-remote's history is never rewritten; braid never force-pushes. It runs the
163-`git` binary with your environment, so it needs the network and the
164-credentials `git push` uses. Run it from the project root, when the
165-remote should have what landed: who runs it, and when, is the user's call.
248+remote's history is never rewritten; braid never force-pushes, and runs no
249+git hooks. It runs the `git` binary with your environment, so it needs the
250+network and the credentials `git push` uses. Run it from the project root,
251+when the remote should have what landed: who runs it, and when, is the
252+user's call. Braid pushes to the remote's address, so the shared
253+checkout's own record of the remote (`origin/main`) does not move:
254+`git pull --ff-only` brings the checkout up to date.
166255
167256 ```bash
168-braid git sync "$(git remote get-url origin)" --branch main --dry-run --json
169-braid git sync "$(git remote get-url origin)" --branch main
257+braid --agent agent-1 git sync "$(git remote get-url origin)" --branch main --dry-run --json
258+braid --agent agent-1 git sync "$(git remote get-url origin)" --branch main
170259 git pull --ff-only # the shared checkout follows
171260 ```
172261
173262 - With `--json`, `outcome` is one of `up_to_date`, `created`,
174263 `fast_forwarded`, `pushed`, `merged`, `conflicts`, `remote_moved` or
175- `rejected`. `--dry-run` writes nothing.
264+ `rejected`. `--dry-run` writes nothing. `--agent` names the session in
265+ the op log, and in the merge a sync makes.
176266 - Each changeset reaches git as a commit of its own, with an `agent` header
177267 that names the agent that made it.
178268 - Exit status 1 with `remote_moved`: someone pushed meanwhile; sync again.
179269 With `rejected`, also exit status 1, the remote refused the push, as a
180- protected branch does.
270+ protected branch does: ask the user. They may let braid push there, or
271+ have it push to a branch of its own, with `--remote-branch <name>`, to
272+ open a pull request from.
181273 - Exit status 2 with `conflicts`: braid and the remote changed the same
182274 lines. Nothing moved and nothing was pushed. Merge them in git, in the
183275 shared checkout, and sync again:
@@ -200,32 +292,38 @@
200292 parents to tell what a workspace has landed, so the workspaces carry on
201293 from the merge.
202294
203-No remote? Any bare repository will do: `git init --bare ../project.git`,
204-then `git remote add origin ../project.git` and `git push -u origin main`
205-in the shared checkout.
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`.
206300
207301 ## Undoing
208302
209303 - `braid op log` lists every operation (imports, landings, syncs), newest
210- first, with the agent that made it. `braid undo` reverts the newest one
211- that is not undone yet, whoever made it, so read the log first. A landing
212- undone leaves its changeset in the workspace that made it, ready to land
213- again.
304+ first, with the agent that made it. `braid --agent agent-1 undo` reverts
305+ the newest one that is not undone yet, whoever made it, so read the log
306+ first. A landing undone leaves its changeset in the workspace that made
307+ it, ready to land again.
214308 - A change that landed under other changes cannot be undone that way.
215309 There is no revert command yet: land a change that puts the files back.
216-- To take braid out of a project: land what the workspaces hold and sync
217- it, remove each workspace (`braid workspace remove <name>`, which refuses
218- while work has not landed), delete `.braid/`, the `/.braid/` line of
219- `.git/info/exclude`, the braid section of `AGENTS.md` (its two marker
220- lines and everything between them) and the `@AGENTS.md` line it added to
221- `CLAUDE.md`, and commit that with git. Then
222- `cargo uninstall elffuss-braid-cli` removes the command.
310+- To take braid out of a project: land what the workspaces hold, sync it
311+ and run `git pull --ff-only`; remove each workspace
312+ (`braid workspace remove <name>`, which refuses while work has not
313+ landed); delete `.braid/`, the `.braid` line of the file that
314+ `git rev-parse --git-path info/exclude` names, the braid section of
315+ `AGENTS.md` (its two marker lines and everything between them) and the
316+ `@AGENTS.md` line it added to `CLAUDE.md` and `GEMINI.md`; and commit
317+ that with git. Then `cargo uninstall elffuss-braid-cli` removes the
318+ command.
223319
224320 ## What not to do
225321
226322 - Do not edit files, `git add`, `git commit`, `git push` or `git pull` in
227323 the shared checkout while you work: only setting up, syncing and merging
228324 a sync conflict touch it, as above.
325+- Do not run git in a workspace, or get around the `.git` file that stops
326+ it there.
229327 - Do not share a workspace between sessions, or work in another session's
230328 workspace.
231329 - Do not run `braid undo` without reading `braid op log` first.
modified site/index.html +14 −14
@@ -182,8 +182,8 @@
182182 <span class="x"> CONTENT notes.txt (1 region)</span>
183183 Run `braid update` to bring the conflicts into the working copy.</code></pre>
184184 </figure>
185-<p data-l="en" lang="en">It exits with status 2. A command line braid cannot parse exits with 2 as well, so to be sure an agent asks for <code class="nw">--json</code>: only a conflict prints <code>"outcome": "conflicts"</code>, and the conflict itself comes back as data. Each side is named from B's point of view: <code>base</code> is the common ancestor, <code>branch</code> is what main holds now, <code>workspace</code> is B's own change. Lines count from 0 with the end left out, and <code>next</code> says what to run:</p>
186-<p data-l="es" lang="es">Sale con código 2. Un comando que braid no sabe interpretar también sale con 2, así que, para ir sobre seguro, el agente pide <code class="nw">--json</code>: solo un conflicto imprime <code>"outcome": "conflicts"</code>, y el propio conflicto llega como datos. Cada lado se nombra desde el punto de vista de B: <code>base</code> es el ancestro común, <code>branch</code> lo que tiene main ahora y <code>workspace</code> su propio cambio. Las líneas se cuentan desde 0 y el final del tramo no se incluye; <code>next</code> le dice qué ejecutar:</p>
185+<p data-l="en" lang="en">It exits with status 2. A command line braid cannot parse exits with 2 as well, so to be sure an agent asks for <code class="nw">--json</code>: the <code>outcome</code> in the JSON is <code>conflicts</code> only for a conflict, and the conflict itself comes back as data. Each side is named from B's point of view: <code>base</code> is the common ancestor, <code>branch</code> is what main holds now, <code>workspace</code> is B's own change. Lines count from 0 with the end left out, and <code>next</code> says what to run:</p>
186+<p data-l="es" lang="es">Sale con código 2. Un comando que braid no sabe interpretar también sale con 2, así que, para ir sobre seguro, el agente pide <code class="nw">--json</code>: solo en un conflicto el <code>outcome</code> del JSON vale <code>conflicts</code>, y el propio conflicto llega como datos. Cada lado se nombra desde el punto de vista de B: <code>base</code> es el ancestro común, <code>branch</code> lo que tiene main ahora y <code>workspace</code> su propio cambio. Las líneas se cuentan desde 0 y el final del tramo no se incluye; <code>next</code> le dice qué ejecutar:</p>
187187 <figure class="term t-b" lang="en">
188188 <figcaption class="term-bar"><span>agent-b</span><span class="bar-note"><span data-l="en" lang="en">abridged; braid prints it on one line</span><span data-l="es" lang="es">abreviado; braid lo imprime en una sola línea</span></span></figcaption>
189189 <pre><code><span class="pr"><span class="ag ag-b">[agent-b]</span> $ </span><span class="cmd">braid land --json</span>
@@ -408,16 +408,16 @@
408408 <p data-l="es" lang="es">Braid trae instrucciones escritas para agentes de programación. En un proyecto que sea un repositorio de git, pídeselo al tuyo, use el arnés que use:</p>
409409 <div class="code prompt" data-l="en" lang="en">
410410 <div class="code-bar"><span>prompt</span><button class="copy" type="button" aria-label="Copy the prompt" 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>
411-<pre tabindex="0" role="region" aria-label="The prompt for your agent" data-aria-en="The prompt for your agent" data-aria-es="La petición para tu agente"><code>Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md</code></pre>
411+<pre tabindex="0" role="region" aria-label="The prompt for your agent" data-aria-en="The prompt for your agent" data-aria-es="La petición para tu agente"><code>Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md (read it whole, with curl -fsSL)</code></pre>
412412 </div>
413413 <div class="code prompt" data-l="es" lang="es">
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>
415-<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</code></pre>
415+<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, 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 and lands through braid, and git stays the source of truth.</p>
418-<p data-l="es" lang="es">Tu agente instala braid con cargo, importa la historia de git del proyecto 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 de braid y aterriza a través de braid, y git sigue siendo la fuente de verdad.</p>
419-<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, start with the quick start below.</p>
420-<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, empieza por los primeros pasos, a continuación.</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, 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>
419+<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>
420+<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>
422422 </section>
423423
@@ -479,8 +479,8 @@
479479 <pre tabindex="0" role="region" aria-label="Commands of one agent" data-aria-en="Commands of one agent" data-aria-es="Comandos de un agente"><code>cd /tmp/demo # any braid repository
480480 export BRAID_AUTHOR="Ada Lovelace &lt;ada@example.org&gt;"
481481 export BRAID_AGENT=agent-1 # recorded with everything this agent does
482-braid workspace add agent-1 # ./agent-1, tracking main
483-cd agent-1
482+braid workspace add agent-1 # .braid/work/agent-1, tracking main
483+cd .braid/work/agent-1
484484 echo 'fn main() {}' &gt; main.rs
485485 braid status
486486 braid commit -m "Add main.rs"
@@ -503,8 +503,8 @@
503503 <p data-l="en" lang="en"><code class="nw">--json</code> on every command; <code>change create</code> always prints JSON.</p>
504504 <p data-l="es" lang="es"><code class="nw">--json</code> en todos los comandos; <code>change create</code> imprime siempre JSON.</p></li>
505505 <li><h4><span data-l="en" lang="en">Exit status</span><span data-l="es" lang="es">Código de salida</span></h4>
506-<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> only a conflict prints <code>"outcome": "conflicts"</code>.</p>
507-<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 el conflicto imprime <code>"outcome": "conflicts"</code>.</p></li>
506+<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>
507+<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>
509509 <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>
510510 <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>
@@ -518,8 +518,8 @@
518518 <p data-l="en" lang="en"><code>CONTENT</code>, <code>MODIFY_DELETE</code>, <code>MODE</code>, <code>DF</code>, <code>DIR_REMOVED</code>, <code>CASE</code>. <code>braid resolve</code> settles the ones that are not about content.</p>
519519 <p data-l="es" lang="es"><code>CONTENT</code>, <code>MODIFY_DELETE</code>, <code>MODE</code>, <code>DF</code>, <code>DIR_REMOVED</code>, <code>CASE</code>. <code>braid resolve</code> zanja los que no son de contenido.</p></li>
520520 <li><h4>Checkouts</h4>
521-<p data-l="en" lang="en">They never follow symlinks, and nothing from repository content is ever run.</p>
522-<p data-l="es" lang="es">Nunca siguen enlaces simbólicos, y nunca se ejecuta nada que venga del contenido del repositorio.</p></li>
521+<p data-l="en" lang="en">They never follow symlinks, and nothing from repository content is ever run. A workspace holds a <code>.git</code> file that points nowhere, so git inside one stops instead of acting on the checkout around it.</p>
522+<p data-l="es" lang="es">Nunca siguen enlaces simbólicos, y nunca se ejecuta nada que venga del contenido del repositorio. Un espacio de trabajo lleva un fichero <code>.git</code> que no apunta a ninguna parte, así que git, dentro de él, se detiene en vez de actuar sobre el checkout que lo rodea.</p></li>
523523 <li class="wide"><h4><span data-l="en" lang="en">No checkout</span><span data-l="es" lang="es">Sin checkout</span></h4>
524524 <p data-l="en" lang="en"><code>braid change create</code> makes a changeset without a working copy, and can land it. <code class="nw">--expect</code> takes the full blob id the agent read; a mismatch is refused.</p>
525525 <p data-l="es" lang="es"><code>braid change create</code> crea un changeset sin copia de trabajo, y puede aterrizarlo. <code class="nw">--expect</code> recibe el id completo del blob que el agente leyó; si no coincide, se rechaza.</p>
modified site/llms.txt +2 −2
@@ -4,11 +4,11 @@
44
55 Each agent commits in a workspace of its own over one shared store, and landing on the main branch is one short step that agents take in turn: a fast-forward, or a rebase that merges only the files both sides touched. Conflicts come back as data, with exit status 2, and every command has a JSON form. Braid imports a git repository's whole history bit for bit, and `braid git sync` keeps a git remote such as GitHub in step. It is pre-alpha: keep git as the source of truth.
66
7-To set braid up in a project, a coding agent follows agents.md. The prompt to give it: Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md
7+To set braid up in a project, a coding agent follows agents.md. The prompt to give it: Install braid in this project and set it up for agents, following https://braid.elffuss.com/agents.md (read it whole, with curl -fsSL)
88
99 ## Docs
1010
11-- [Install braid and set it up for agents](https://braid.elffuss.com/agents.md): for coding agents. Installing with cargo, setting up a git project with `braid agents init`, each session's workspace, 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, 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.