utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | 2dd40509e7e2946fdf85f47ac0eabbba833e1582dfa9f2ba721f3b0fa4c131ea |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 10:42 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 10:42 +02:00 |
| Parents | 68c0144475c3 |
22 files changed
modified AGENTS.md +193 −81
| @@ -16,101 +16,170 @@ | ||
| 16 | 16 | |
| 17 | 17 | ## 1. Installing braid and setting it up in a project |
| 18 | 18 | |
| 19 | +Read this part whole before you run anything, and run its commands exactly | |
| 20 | +as they are written. | |
| 21 | + | |
| 19 | 22 | ### Install |
| 20 | 23 | |
| 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. | |
| 23 | 34 | |
| 24 | 35 | ```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 | |
| 26 | 37 | ``` |
| 27 | 38 | |
| 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. | |
| 31 | 47 | |
| 32 | 48 | ### Is it installed, and set up here? |
| 33 | 49 | |
| 34 | 50 | ```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 | |
| 36 | 52 | braid refs # in the project root: its branches, once it is set up |
| 37 | 53 | ``` |
| 38 | 54 | |
| 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". | |
| 42 | 63 | |
| 43 | 64 | ### Set up a project |
| 44 | 65 | |
| 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. | |
| 49 | 82 | |
| 50 | 83 | ```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 | |
| 54 | 88 | braid git import . # the project's whole history: every local branch and tag |
| 55 | 89 | braid agents init # the rules for agents, in AGENTS.md |
| 56 | 90 | ``` |
| 57 | 91 | |
| 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. | |
| 60 | 95 | - `.braid/config` names who signs the changesets agents make, here the |
| 61 | 96 | 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`. | |
| 63 | 106 | - `braid agents init` writes a section into `AGENTS.md`, creating the file |
| 64 | 107 | if there is none, between a `<!-- braid:start -->` line and a |
| 65 | 108 | `<!-- braid:end -->` line. The section tells every agent session to work |
| 66 | 109 | 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. | |
| 75 | 115 | |
| 76 | 116 | 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. | |
| 78 | 122 | |
| 79 | 123 | ```bash |
| 80 | 124 | 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" | |
| 83 | 128 | braid git import . # braid's main takes the commit |
| 84 | 129 | braid log main -n 1 # and shows it |
| 85 | 130 | ``` |
| 86 | 131 | |
| 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. | |
| 88 | 135 | |
| 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 | |
| 91 | 137 | |
| 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. | |
| 92 | 147 | - **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. | |
| 100 | 158 | |
| 101 | 159 | ```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 | |
| 104 | 162 | ``` |
| 105 | 163 | |
| 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. | |
| 109 | 177 | - **Record and land** from the workspace. `--agent` (or `BRAID_AGENT`) |
| 110 | 178 | names the session in the op log and in every changeset it makes; pass it |
| 111 | 179 | every time, since a harness may not keep variables between commands. If |
| 112 | 180 | 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. | |
| 114 | 183 | |
| 115 | 184 | ```bash |
| 116 | 185 | braid --agent agent-1 status --json |
| @@ -119,28 +188,43 @@ | ||
| 119 | 188 | ``` |
| 120 | 189 | |
| 121 | 190 | 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 | |
| 123 | 196 | fast-forward or rebased onto whatever landed first. |
| 124 | 197 | - **Before a new task**, `braid --agent agent-1 update` brings the |
| 125 | 198 | workspace onto `main`. `status --json` says how far behind it is |
| 126 | 199 | (`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. | |
| 127 | 205 | - **Done**: once everything has landed, `braid workspace remove agent-1` |
| 128 | 206 | from the project root. It refuses while the workspace holds work that |
| 129 | 207 | 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`. | |
| 132 | 214 | - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger |
| 133 | 215 | 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. | |
| 135 | 218 | |
| 136 | 219 | ### Conflicts |
| 137 | 220 | |
| 138 | 221 | 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. | |
| 144 | 228 | |
| 145 | 229 | ```bash |
| 146 | 230 | braid --agent agent-1 update # exit status 2: conflict markers in the files |
| @@ -150,7 +234,9 @@ | ||
| 150 | 234 | ``` |
| 151 | 235 | |
| 152 | 236 | `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. | |
| 154 | 240 | |
| 155 | 241 | ### Keeping the git remote up to date |
| 156 | 242 | |
| @@ -159,25 +245,31 @@ | ||
| 159 | 245 | braid's branch when only the remote moved, pushes braid's branch when only |
| 160 | 246 | braid moved, and when both moved, merges them and pushes the merge. The |
| 161 | 247 | 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. | |
| 166 | 255 | |
| 167 | 256 | ```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 | |
| 170 | 259 | git pull --ff-only # the shared checkout follows |
| 171 | 260 | ``` |
| 172 | 261 | |
| 173 | 262 | - With `--json`, `outcome` is one of `up_to_date`, `created`, |
| 174 | 263 | `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. | |
| 176 | 266 | - Each changeset reaches git as a commit of its own, with an `agent` header |
| 177 | 267 | that names the agent that made it. |
| 178 | 268 | - Exit status 1 with `remote_moved`: someone pushed meanwhile; sync again. |
| 179 | 269 | 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. | |
| 181 | 273 | - Exit status 2 with `conflicts`: braid and the remote changed the same |
| 182 | 274 | lines. Nothing moved and nothing was pushed. Merge them in git, in the |
| 183 | 275 | shared checkout, and sync again: |
| @@ -200,32 +292,38 @@ | ||
| 200 | 292 | parents to tell what a workspace has landed, so the workspaces carry on |
| 201 | 293 | from the merge. |
| 202 | 294 | |
| 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`. | |
| 206 | 300 | |
| 207 | 301 | ### Undoing |
| 208 | 302 | |
| 209 | 303 | - `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. | |
| 214 | 308 | - A change that landed under other changes cannot be undone that way. |
| 215 | 309 | 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. | |
| 223 | 319 | |
| 224 | 320 | ### What not to do |
| 225 | 321 | |
| 226 | 322 | - Do not edit files, `git add`, `git commit`, `git push` or `git pull` in |
| 227 | 323 | the shared checkout while you work: only setting up, syncing and merging |
| 228 | 324 | 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. | |
| 229 | 327 | - Do not share a workspace between sessions, or work in another session's |
| 230 | 328 | workspace. |
| 231 | 329 | - Do not run `braid undo` without reading `braid op log` first. |
| @@ -264,9 +362,12 @@ | ||
| 264 | 362 | cargo test --workspace |
| 265 | 363 | ``` |
| 266 | 364 | |
| 365 | +The tests and the quick benchmark read this repository's whole history: in | |
| 366 | +a shallow clone, run `git fetch --unshallow` first. | |
| 367 | + | |
| 267 | 368 | ### Before every commit |
| 268 | 369 | |
| 269 | -These are the checks CI runs. All of them must pass: | |
| 370 | +All of these must pass: | |
| 270 | 371 | |
| 271 | 372 | ```bash |
| 272 | 373 | cargo fmt --all |
| @@ -275,9 +376,18 @@ | ||
| 275 | 376 | cargo test --workspace |
| 276 | 377 | cargo deny check |
| 277 | 378 | 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 | |
| 278 | 382 | scripts/privacy-check.sh |
| 279 | 383 | ``` |
| 280 | 384 | |
| 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 | + | |
| 281 | 391 | ### Rules |
| 282 | 392 | |
| 283 | 393 | From [CONTRIBUTING.md](CONTRIBUTING.md), in short: |
| @@ -301,4 +411,6 @@ | ||
| 301 | 411 | - The repository is public: no absolute paths, user names, real e-mail |
| 302 | 412 | addresses (use `example.org`), hardware or timings in anything committed. |
| 303 | 413 | - 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 @@ | ||
| 5 | 5 | [format](docs/spec/format-v1.md), bug reports, and tests. |
| 6 | 6 | |
| 7 | 7 | 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. | |
| 9 | 9 | |
| 10 | 10 | ## Build and test |
| 11 | 11 |
modified Cargo.lock +8 −8
| @@ -478,7 +478,7 @@ | ||
| 478 | 478 | |
| 479 | 479 | [[package]] |
| 480 | 480 | name = "elffuss-braid-cli" |
| 481 | -version = "0.0.1" | |
| 481 | +version = "0.0.2" | |
| 482 | 482 | dependencies = [ |
| 483 | 483 | "anyhow", |
| 484 | 484 | "clap", |
| @@ -494,7 +494,7 @@ | ||
| 494 | 494 | |
| 495 | 495 | [[package]] |
| 496 | 496 | name = "elffuss-braid-engine" |
| 497 | -version = "0.0.1" | |
| 497 | +version = "0.0.2" | |
| 498 | 498 | dependencies = [ |
| 499 | 499 | "blake3", |
| 500 | 500 | "elffuss-braid-format", |
| @@ -506,7 +506,7 @@ | ||
| 506 | 506 | |
| 507 | 507 | [[package]] |
| 508 | 508 | name = "elffuss-braid-format" |
| 509 | -version = "0.0.1" | |
| 509 | +version = "0.0.2" | |
| 510 | 510 | dependencies = [ |
| 511 | 511 | "blake3", |
| 512 | 512 | "proptest", |
| @@ -515,7 +515,7 @@ | ||
| 515 | 515 | |
| 516 | 516 | [[package]] |
| 517 | 517 | name = "elffuss-braid-git" |
| 518 | -version = "0.0.1" | |
| 518 | +version = "0.0.2" | |
| 519 | 519 | dependencies = [ |
| 520 | 520 | "elffuss-braid-format", |
| 521 | 521 | "gix", |
| @@ -525,7 +525,7 @@ | ||
| 525 | 525 | |
| 526 | 526 | [[package]] |
| 527 | 527 | name = "elffuss-braid-repo" |
| 528 | -version = "0.0.1" | |
| 528 | +version = "0.0.2" | |
| 529 | 529 | dependencies = [ |
| 530 | 530 | "blake3", |
| 531 | 531 | "elffuss-braid-engine", |
| @@ -539,7 +539,7 @@ | ||
| 539 | 539 | |
| 540 | 540 | [[package]] |
| 541 | 541 | name = "elffuss-braid-sim" |
| 542 | -version = "0.0.1" | |
| 542 | +version = "0.0.2" | |
| 543 | 543 | dependencies = [ |
| 544 | 544 | "elffuss-braid-engine", |
| 545 | 545 | "elffuss-braid-format", |
| @@ -550,7 +550,7 @@ | ||
| 550 | 550 | |
| 551 | 551 | [[package]] |
| 552 | 552 | name = "elffuss-braid-store" |
| 553 | -version = "0.0.1" | |
| 553 | +version = "0.0.2" | |
| 554 | 554 | dependencies = [ |
| 555 | 555 | "blake3", |
| 556 | 556 | "crc32c", |
| @@ -566,7 +566,7 @@ | ||
| 566 | 566 | |
| 567 | 567 | [[package]] |
| 568 | 568 | name = "elffuss-braid-wc" |
| 569 | -version = "0.0.1" | |
| 569 | +version = "0.0.2" | |
| 570 | 570 | dependencies = [ |
| 571 | 571 | "cap-fs-ext", |
| 572 | 572 | "cap-std", |
modified Cargo.toml +1 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | exclude = ["fuzz"] |
| 5 | 5 | |
| 6 | 6 | [workspace.package] |
| 7 | -version = "0.0.1" | |
| 7 | +version = "0.0.2" | |
| 8 | 8 | edition = "2024" |
| 9 | 9 | rust-version = "1.89" |
| 10 | 10 | license = "Apache-2.0" |
modified README.md +41 −20
| @@ -95,14 +95,17 @@ | ||
| 95 | 95 | is a git repository, ask your agent, whatever harness runs it: |
| 96 | 96 | |
| 97 | 97 | ```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) | |
| 99 | 99 | ``` |
| 100 | 100 | |
| 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 | |
| 106 | 109 | site serves as |
| 107 | 110 | [braid.elffuss.com/agents.md](https://braid.elffuss.com/agents.md), next to |
| 108 | 111 | an [llms.txt](https://braid.elffuss.com/llms.txt). |
| @@ -160,8 +163,8 @@ | ||
| 160 | 163 | ```bash |
| 161 | 164 | export BRAID_AUTHOR="Ada Lovelace <ada@example.org>" |
| 162 | 165 | 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 | |
| 165 | 168 | echo 'fn main() {}' > main.rs |
| 166 | 169 | braid status |
| 167 | 170 | braid commit -m "Add main.rs" |
| @@ -200,15 +203,29 @@ | ||
| 200 | 203 | store: generation numbers and skip pointers for ancestry, changed-path |
| 201 | 204 | filters, and blame records, computed the first time they are needed. |
| 202 | 205 | `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. | |
| 203 | 217 | - `braid agents init` writes the rules for agents into a project's |
| 204 | 218 | `AGENTS.md`, in a section between a `<!-- braid:start -->` line and a |
| 205 | 219 | `<!-- 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. | |
| 212 | 229 | |
| 213 | 230 | `braid status --help`, `braid land --help`, `braid update --help` and |
| 214 | 231 | `braid agents init --help` describe every JSON field. |
| @@ -419,9 +436,13 @@ | ||
| 419 | 436 | Las [fases](#status-and-roadmap) dicen qué llega después y qué pruebas tiene que |
| 420 | 437 | pasar cada una. |
| 421 | 438 | |
| 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 @@ | ||
| 4 | 4 | //! `braid agents init`: the rules for coding agents, written into the |
| 5 | 5 | //! project's `AGENTS.md` between two marker lines, so that every agent |
| 6 | 6 | //! 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. | |
| 9 | 9 | //! |
| 10 | 10 | //! 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. | |
| 12 | 14 | |
| 13 | 15 | use std::fs::{self, OpenOptions}; |
| 14 | 16 | use std::io::{self, Write}; |
| @@ -20,9 +22,10 @@ | ||
| 20 | 22 | use braid_repo::{Location, Repo}; |
| 21 | 23 | use braid_wc::Workspace; |
| 22 | 24 | use clap::{Args, Subcommand}; |
| 23 | -use serde_json::json; | |
| 25 | +use serde_json::{Map, Value, json}; | |
| 24 | 26 | |
| 25 | -use crate::{Cli, print_json}; | |
| 27 | +use crate::work::{branches, listed}; | |
| 28 | +use crate::{Cli, open_repo, print_json}; | |
| 26 | 29 | |
| 27 | 30 | /// The line that opens the braid section of `AGENTS.md`. |
| 28 | 31 | pub(crate) const START: &str = "<!-- braid:start -->"; |
| @@ -36,12 +39,18 @@ | ||
| 36 | 39 | /// The file Claude Code reads, which should include `AGENTS.md`. |
| 37 | 40 | const CLAUDE_FILE: &str = "CLAUDE.md"; |
| 38 | 41 | |
| 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`. | |
| 40 | 46 | const INCLUDE: &str = "@AGENTS.md"; |
| 41 | 47 | |
| 42 | 48 | /// What the section's first comment says just before the branch it names. |
| 43 | 49 | const BRANCH_NOTE: &str = "(branch: "; |
| 44 | 50 | |
| 51 | +/// The end of every refusal: nothing is written when any check fails. | |
| 52 | +const NOTHING: &str = "nothing was written"; | |
| 53 | + | |
| 45 | 54 | /// The long help of `agents init`. |
| 46 | 55 | pub(crate) const INIT_HELP: &str = |
| 47 | 56 | "Write the rules for coding agents into the project's AGENTS.md, so that |
| @@ -51,38 +60,63 @@ | ||
| 51 | 60 | The rules go in a section between two lines, <!-- braid:start --> and |
| 52 | 61 | <!-- braid:end -->: at the end of AGENTS.md, which is created if there is |
| 53 | 62 | 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."; | |
| 81 | 115 | |
| 82 | 116 | #[derive(Debug, Subcommand)] |
| 83 | 117 | pub(crate) enum AgentsAction { |
| 84 | 118 | /// 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. | |
| 86 | 120 | #[command(long_about = INIT_HELP)] |
| 87 | 121 | Init(InitArgs), |
| 88 | 122 | } |
| @@ -94,9 +128,10 @@ | ||
| 94 | 128 | /// directory). |
| 95 | 129 | #[arg(long, value_name = "DIR")] |
| 96 | 130 | 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). | |
| 100 | 135 | #[arg(long, value_name = "BRANCH")] |
| 101 | 136 | branch: Option<String>, |
| 102 | 137 | /// Say what would change, and write nothing. |
| @@ -105,6 +140,9 @@ | ||
| 105 | 140 | /// Leave CLAUDE.md alone. |
| 106 | 141 | #[arg(long)] |
| 107 | 142 | no_claude: bool, |
| 143 | + /// Leave GEMINI.md alone. | |
| 144 | + #[arg(long)] | |
| 145 | + no_gemini: bool, | |
| 108 | 146 | } |
| 109 | 147 | |
| 110 | 148 | pub(crate) fn agents(cli: &Cli, action: &AgentsAction) -> Result<ExitCode> { |
| @@ -122,8 +160,10 @@ | ||
| 122 | 160 | |
| 123 | 161 | /// One file the command looked at, and what it does to it. |
| 124 | 162 | struct Planned { |
| 163 | + /// The name the project knows it by: `AGENTS.md`, `CLAUDE.md` or | |
| 164 | + /// `GEMINI.md`. | |
| 125 | 165 | name: &'static str, |
| 126 | - path: PathBuf, | |
| 166 | + target: Target, | |
| 127 | 167 | action: Action, |
| 128 | 168 | /// The new contents, unless unchanged. |
| 129 | 169 | contents: Option<String>, |
| @@ -134,46 +174,53 @@ | ||
| 134 | 174 | } |
| 135 | 175 | |
| 136 | 176 | 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, | |
| 148 | 194 | }; |
| 149 | - | |
| 150 | - let agents_path = dir.join(AGENTS_FILE); | |
| 151 | - let current = read_text(&agents_path)?; | |
| 152 | - let found = match ¤t { | |
| 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 ¤t { | |
| 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 | + ) | |
| 155 | 202 | })?, |
| 156 | - None => None, | |
| 203 | + None => Scanned::default(), | |
| 157 | 204 | }; |
| 158 | - let named = match (¤t, &found) { | |
| 205 | + let named = match (¤t, &scanned.section) { | |
| 159 | 206 | (Some(text), Some(range)) => named_branch(&text[range.clone()]), |
| 160 | 207 | _ => None, |
| 161 | 208 | }; |
| 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 | + } | |
| 170 | 221 | |
| 171 | 222 | 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)?; | |
| 177 | 224 | } |
| 178 | 225 | |
| 179 | 226 | if cli.json { |
| @@ -184,19 +231,33 @@ | ||
| 184 | 231 | .map(|file| file.name) |
| 185 | 232 | .collect() |
| 186 | 233 | }; |
| 234 | + let paths: Map<String, Value> = planned | |
| 235 | + .iter() | |
| 236 | + .map(|file| (file.name.to_owned(), Value::from(file.target.shown.clone()))) | |
| 237 | + .collect(); | |
| 187 | 238 | print_json(&json!({ |
| 188 | 239 | "dir": dir.to_string_lossy(), |
| 189 | - "branch": branch, | |
| 240 | + "branch": choice.branch, | |
| 241 | + "previous_branch": choice.previous, | |
| 190 | 242 | "repository": place.repo.as_ref().map(|repo| repo.root().to_string_lossy()), |
| 191 | 243 | "dry_run": args.dry_run, |
| 192 | 244 | "created": names(Action::Create), |
| 193 | 245 | "updated": names(Action::Update), |
| 194 | 246 | "unchanged": names(Action::Unchanged), |
| 247 | + "paths": paths, | |
| 195 | 248 | }))?; |
| 196 | 249 | return Ok(ExitCode::SUCCESS); |
| 197 | 250 | } |
| 198 | 251 | |
| 199 | 252 | let mut out = io::stdout().lock(); |
| 253 | + if let (Some(previous), true) = (&choice.previous, choice.missing) { | |
| 254 | + let names = if args.dry_run { "would name" } else { "names" }; | |
| 255 | + writeln!( | |
| 256 | + out, | |
| 257 | + "The section named {previous}, which the repository does not have: it {names} {} now.", | |
| 258 | + choice.branch | |
| 259 | + )?; | |
| 260 | + } | |
| 200 | 261 | for file in &planned { |
| 201 | 262 | let said = if args.dry_run { |
| 202 | 263 | &file.would |
| @@ -208,31 +269,65 @@ | ||
| 208 | 269 | if place.repo.is_none() { |
| 209 | 270 | writeln!( |
| 210 | 271 | 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." | |
| 212 | 273 | )?; |
| 213 | 274 | } |
| 214 | 275 | if args.dry_run { |
| 215 | 276 | writeln!(out, "Nothing was written.")?; |
| 216 | - if agents.action != Action::Unchanged { | |
| 277 | + if planned[0].action != Action::Unchanged { | |
| 217 | 278 | writeln!(out, "\nThe section {AGENTS_FILE} would hold:\n")?; |
| 218 | - write!(out, "{}", section(&branch))?; | |
| 279 | + write!(out, "{}", section(&choice.branch))?; | |
| 219 | 280 | } |
| 220 | 281 | } |
| 221 | 282 | Ok(ExitCode::SUCCESS) |
| 222 | 283 | } |
| 223 | 284 | |
| 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. | |
| 225 | 287 | struct Place { |
| 226 | 288 | 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. | |
| 230 | 292 | workspace_branch: Option<String>, |
| 231 | 293 | } |
| 232 | 294 | |
| 233 | 295 | 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) { | |
| 236 | 331 | Ok(location) => Some(location), |
| 237 | 332 | Err(braid_repo::Error::NotFound) => None, |
| 238 | 333 | Err(err) => return Err(err.into()), |
| @@ -243,9 +338,17 @@ | ||
| 243 | 338 | (None, Some(Location::Workspace { link, .. })) => Some(Repo::open(&link.repository)?), |
| 244 | 339 | (None, None) => None, |
| 245 | 340 | }; |
| 341 | + // What the current directory is in counts only when it belongs to | |
| 342 | + // the repository: --repo may name another. | |
| 343 | + let belongs = |root: &Path| { | |
| 344 | + cli.repo.is_none() | |
| 345 | + || repo | |
| 346 | + .as_ref() | |
| 347 | + .is_some_and(|repo| same_dir(root, repo.root())) | |
| 348 | + }; | |
| 246 | 349 | 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) => { | |
| 249 | 352 | // A workspace whose state is gone names no branch. |
| 250 | 353 | let branch = repo.as_ref().and_then(|repo| { |
| 251 | 354 | Workspace::open(repo, &link.name) |
| @@ -255,149 +358,287 @@ | ||
| 255 | 358 | }); |
| 256 | 359 | (Some(dir.clone()), branch) |
| 257 | 360 | } |
| 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, | |
| 259 | 366 | }; |
| 260 | 367 | Ok(Place { |
| 261 | 368 | repo, |
| 262 | - top, | |
| 369 | + dir, | |
| 263 | 370 | workspace_branch, |
| 264 | 371 | }) |
| 265 | 372 | } |
| 266 | 373 | } |
| 267 | 374 | |
| 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)) | |
| 277 | 413 | }; |
| 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 | + }); | |
| 280 | 427 | } |
| 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 | + }) | |
| 282 | 461 | } |
| 283 | 462 | |
| 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> { | |
| 293 | 466 | if let Some(preferred) = ["main", "master"] |
| 294 | 467 | .into_iter() |
| 295 | - .find(|preferred| branches.contains(preferred)) | |
| 468 | + .find(|preferred| names.contains(preferred)) | |
| 296 | 469 | { |
| 297 | 470 | return Ok(preferred.to_owned()); |
| 298 | 471 | } |
| 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"), | |
| 302 | 478 | several => bail!( |
| 303 | 479 | "cannot tell which branch agents land on: the repository has {}; pass --branch", |
| 304 | - several.join(", ") | |
| 480 | + listed(several) | |
| 305 | 481 | ), |
| 306 | 482 | } |
| 307 | 483 | } |
| 308 | 484 | |
| 485 | +/// Whether the section can name `branch`. The section writes it into shell | |
| 486 | +/// commands and reads it back from its first comment, so it takes only a | |
| 487 | +/// set of characters that needs no quoting and holds no `)`: ASCII letters, | |
| 488 | +/// digits, `.`, `_`, `/` and `-`, not first. It must be a git branch name | |
| 489 | +/// outside braid's own namespaces, too. | |
| 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 | + | |
| 309 | 510 | /// What `AGENTS.md` needs: to be created, to get the section, or to have |
| 310 | 511 | /// it rewritten in place. |
| 311 | 512 | fn plan_agents( |
| 312 | - path: PathBuf, | |
| 513 | + target: Target, | |
| 313 | 514 | current: Option<&str>, |
| 314 | - found: Option<Range<usize>>, | |
| 515 | + scanned: &Scanned, | |
| 315 | 516 | branch: &str, |
| 316 | -) -> Planned { | |
| 517 | +) -> Result<Planned> { | |
| 317 | 518 | 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) { | |
| 319 | 521 | (None, _) => ( |
| 320 | 522 | Action::Create, |
| 321 | 523 | 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}."), | |
| 324 | 526 | ), |
| 325 | 527 | (Some(text), Some(range)) => { |
| 326 | - let new = replace_section(text, range, §ion(branch)); | |
| 528 | + let new = replace_section(text, range.clone(), §ion(branch)); | |
| 327 | 529 | 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}."); | |
| 329 | 531 | (Action::Unchanged, None, said.clone(), said) |
| 330 | 532 | } else { |
| 331 | 533 | ( |
| 332 | 534 | Action::Update, |
| 333 | 535 | 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}."), | |
| 336 | 538 | ) |
| 337 | 539 | } |
| 338 | 540 | } |
| 541 | + (Some(_), None) if scanned.open_fence.is_some() => bail!( | |
| 542 | + "{} ends inside a fenced code block, which opens on line {} and is never closed: the section would be read as code there. Close the block, then run the command again: {NOTHING}", | |
| 543 | + target.shown, | |
| 544 | + scanned.open_fence.unwrap_or_default() | |
| 545 | + ), | |
| 339 | 546 | (Some(text), None) => ( |
| 340 | 547 | Action::Update, |
| 341 | 548 | Some(append_section(text, §ion(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}."), | |
| 344 | 551 | ), |
| 345 | 552 | }; |
| 346 | - Planned { | |
| 553 | + Ok(Planned { | |
| 347 | 554 | name: AGENTS_FILE, |
| 348 | - path, | |
| 555 | + target, | |
| 349 | 556 | action, |
| 350 | 557 | contents, |
| 351 | 558 | done, |
| 352 | 559 | would, |
| 353 | - } | |
| 560 | + }) | |
| 354 | 561 | } |
| 355 | 562 | |
| 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, | |
| 367 | 576 | action, |
| 368 | 577 | 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) | |
| 371 | 588 | }; |
| 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, | |
| 380 | 610 | }; |
| 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) | |
| 386 | 614 | { |
| 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(); | |
| 393 | 619 | 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 | + ))); | |
| 395 | 628 | } |
| 629 | + if let Some(line) = open_fence(&text) { | |
| 630 | + bail!( | |
| 631 | + "{} ends inside a fenced code block, which opens on line {line} and is never closed: the line {INCLUDE} would be read as code there. Close the block, then run the command again: {NOTHING}", | |
| 632 | + target.shown | |
| 633 | + ); | |
| 634 | + } | |
| 635 | + let called = target.called(name); | |
| 396 | 636 | Ok(Some(planned( |
| 637 | + target, | |
| 397 | 638 | Action::Update, |
| 398 | 639 | 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}."), | |
| 401 | 642 | ))) |
| 402 | 643 | } |
| 403 | 644 | |
| @@ -414,21 +655,28 @@ | ||
| 414 | 655 | each in a braid workspace of its own. Braid is pre-alpha: git stays the |
| 415 | 656 | source of truth, and `braid git sync` keeps the git remote in step. |
| 416 | 657 | |
| 658 | +- **Only where braid is set up:** in a checkout whose root has a `.braid` | |
| 659 | + directory. Without one (a fresh clone, CI, another machine), skip this | |
| 660 | + section and work with git, as the project's other rules say; set braid | |
| 661 | + up only if the user asks for it (<https://braid.elffuss.com/agents.md> | |
| 662 | + says how). With `.braid` but no `braid` command, braid is not on `PATH`: | |
| 663 | + try `\"$HOME/.cargo/bin/braid\"`, or ask the user to install it. | |
| 417 | 664 | - **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`: | |
| 422 | 672 | |
| 423 | 673 | ```bash |
| 424 | - braid workspace add agent-1 .braid/work/agent-1 --track {branch} | |
| 674 | + braid workspace add agent-1 --track {branch} | |
| 425 | 675 | cd .braid/work/agent-1 |
| 426 | 676 | ``` |
| 427 | 677 | |
| 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: | |
| 432 | 680 | |
| 433 | 681 | ```bash |
| 434 | 682 | braid --agent agent-1 status --json |
| @@ -438,28 +686,50 @@ | ||
| 438 | 686 | |
| 439 | 687 | If your shell does not stay in the workspace between commands, add |
| 440 | 688 | `--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 | |
| 443 | 706 | `braid --agent agent-1 update`, which writes conflict markers into the |
| 444 | 707 | files; fix them (`braid resolve <path>` settles conflicts that are not |
| 445 | 708 | 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`. | |
| 447 | 712 | - **Before a new task**, `braid --agent agent-1 update` brings your |
| 448 | 713 | 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. | |
| 451 | 726 | - Changesets are signed by `BRAID_AUTHOR` (`\"Name <email>\"`), or else by the |
| 452 | 727 | `name` and `email` in `.braid/config`. |
| 453 | 728 | - 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. | |
| 463 | 733 | {END} |
| 464 | 734 | " |
| 465 | 735 | ) |
| @@ -473,30 +743,120 @@ | ||
| 473 | 743 | line.len() - text.len() <= 3 && text == marker |
| 474 | 744 | } |
| 475 | 745 | |
| 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> { | |
| 480 | 823 | let mut starts = Vec::new(); |
| 481 | 824 | let mut ends = Vec::new(); |
| 825 | + let mut fences = Fences::default(); | |
| 482 | 826 | let mut offset = 0; |
| 483 | 827 | 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 | + } | |
| 488 | 842 | } |
| 489 | 843 | offset += line.len(); |
| 490 | 844 | } |
| 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 | + }) | |
| 500 | 860 | } |
| 501 | 861 | |
| 502 | 862 | /// `no line`, `line 3`, `lines 3 and 9`, `lines 3, 9 and 12`. |
| @@ -538,11 +898,13 @@ | ||
| 538 | 898 | let section = in_line_ends_of(text, section); |
| 539 | 899 | let mut out = String::with_capacity(text.len() + section.len() + 2 * end.len()); |
| 540 | 900 | out.push_str(text); |
| 541 | - if !out.is_empty() { | |
| 901 | + if !without_bom(text).is_empty() { | |
| 542 | 902 | if !out.ends_with('\n') { |
| 543 | 903 | out.push_str(end); |
| 544 | 904 | } |
| 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 | + { | |
| 546 | 908 | out.push_str(end); |
| 547 | 909 | } |
| 548 | 910 | } |
| @@ -559,23 +921,70 @@ | ||
| 559 | 921 | body.is_empty() || body.ends_with('\n') |
| 560 | 922 | } |
| 561 | 923 | |
| 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)?; | |
| 565 | 929 | 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 | |
| 567 | 972 | } |
| 568 | 973 | |
| 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. | |
| 571 | 977 | 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 | + }) | |
| 579 | 988 | }) |
| 580 | 989 | } |
| 581 | 990 | |
| @@ -591,36 +1000,256 @@ | ||
| 591 | 1000 | out |
| 592 | 1001 | } |
| 593 | 1002 | |
| 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) | |
| 598 | 1096 | .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, &[])); | |
| 617 | 1212 | } |
| 618 | - path.to_path_buf() | |
| 619 | 1213 | } |
| 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)), | |
| 621 | 1244 | }; |
| 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")); | |
| 624 | 1253 | }; |
| 625 | 1254 | let name = name.to_string_lossy(); |
| 626 | 1255 | let mut attempt = 0u32; |
| @@ -631,24 +1260,31 @@ | ||
| 631 | 1260 | Err(err) if err.kind() == io::ErrorKind::AlreadyExists && attempt < 64 => { |
| 632 | 1261 | attempt += 1; |
| 633 | 1262 | } |
| 634 | - Err(err) => { | |
| 635 | - return Err(err).with_context(|| format!("cannot write in {}", parent.display())); | |
| 636 | - } | |
| 1263 | + Err(err) => return Err(err), | |
| 637 | 1264 | } |
| 638 | 1265 | }; |
| 639 | 1266 | let mut written = || -> io::Result<()> { |
| 640 | - if let Ok(meta) = fs::metadata(&target) { | |
| 1267 | + if let Ok(meta) = fs::metadata(path) { | |
| 641 | 1268 | fs::set_permissions(&temp, meta.permissions())?; |
| 642 | 1269 | } |
| 643 | 1270 | file.write_all(contents.as_bytes())?; |
| 644 | - file.sync_all()?; | |
| 645 | - fs::rename(&temp, &target) | |
| 1271 | + file.sync_all() | |
| 646 | 1272 | }; |
| 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 | + } | |
| 650 | 1279 | } |
| 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() | |
| 652 | 1288 | } |
| 653 | 1289 | |
| 654 | 1290 | #[cfg(test)] |
| @@ -658,6 +1294,10 @@ | ||
| 658 | 1294 | const ABOVE: &str = "# Project\n\nRules of our own.\n\n"; |
| 659 | 1295 | const BELOW: &str = "\n## More rules\n\nKept as they are.\n"; |
| 660 | 1296 | |
| 1297 | + fn find(text: &str) -> Result<Option<Range<usize>>, String> { | |
| 1298 | + scan_section(text).map(|scanned| scanned.section) | |
| 1299 | + } | |
| 1300 | + | |
| 661 | 1301 | #[test] |
| 662 | 1302 | fn the_section_names_the_branch_and_holds_no_marker_inside() { |
| 663 | 1303 | let text = section("trunk"); |
| @@ -665,17 +1305,66 @@ | ||
| 665 | 1305 | assert!(text.ends_with(&format!("\n{END}\n"))); |
| 666 | 1306 | assert!(text.contains("--track trunk\n")); |
| 667 | 1307 | assert!(text.contains("land their changes on `trunk`")); |
| 668 | - assert!(text.contains("--branch trunk`")); | |
| 1308 | + assert!(text.contains("--branch trunk\n")); | |
| 669 | 1309 | assert!( |
| 670 | 1310 | !text.contains("`main`") && !text.contains(" main"), |
| 671 | 1311 | "{text}" |
| 672 | 1312 | ); |
| 673 | 1313 | 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 | + ); | |
| 676 | 1323 | assert!(text.lines().all(|line| line.len() <= 100), "{text}"); |
| 677 | 1324 | } |
| 678 | 1325 | |
| 1326 | + #[test] | |
| 1327 | + fn branches_the_section_can_name_read_back_exactly() { | |
| 1328 | + for good in [ | |
| 1329 | + "main", | |
| 1330 | + "master", | |
| 1331 | + "trunk", | |
| 1332 | + "release-1.2", | |
| 1333 | + "feature/x.y_z-1", | |
| 1334 | + "v1.x/beta", | |
| 1335 | + "UPPER_case", | |
| 1336 | + ] { | |
| 1337 | + assert!(is_section_branch(good), "{good}"); | |
| 1338 | + assert_eq!(named_branch(§ion(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 | + | |
| 679 | 1368 | #[test] |
| 680 | 1369 | fn a_section_is_appended_after_a_blank_line() { |
| 681 | 1370 | let new = section("main"); |
| @@ -695,7 +1384,7 @@ | ||
| 695 | 1384 | crlf, |
| 696 | 1385 | format!("# Rules\r\n\r\n{}", new.replace('\n', "\r\n")) |
| 697 | 1386 | ); |
| 698 | - let range = find_section(&crlf).unwrap().unwrap(); | |
| 1387 | + let range = find(&crlf).unwrap().unwrap(); | |
| 699 | 1388 | assert_eq!(replace_section(&crlf, range, &new), crlf); |
| 700 | 1389 | } |
| 701 | 1390 | |
| @@ -703,12 +1392,12 @@ | ||
| 703 | 1392 | fn only_the_text_between_the_markers_changes() { |
| 704 | 1393 | let old = format!("{START}\nan older section\n{END}\n"); |
| 705 | 1394 | let text = format!("{ABOVE}{old}{BELOW}"); |
| 706 | - let range = find_section(&text).unwrap().unwrap(); | |
| 1395 | + let range = find(&text).unwrap().unwrap(); | |
| 707 | 1396 | assert_eq!(&text[range.clone()], old); |
| 708 | 1397 | let new = replace_section(&text, range, §ion("main")); |
| 709 | 1398 | assert_eq!(new, format!("{ABOVE}{}{BELOW}", section("main"))); |
| 710 | 1399 | // Again: nothing changes. |
| 711 | - let range = find_section(&new).unwrap().unwrap(); | |
| 1400 | + let range = find(&new).unwrap().unwrap(); | |
| 712 | 1401 | assert_eq!(replace_section(&new, range, §ion("main")), new); |
| 713 | 1402 | // The older section named no branch. |
| 714 | 1403 | assert_eq!(named_branch(&old), None); |
| @@ -717,15 +1406,76 @@ | ||
| 717 | 1406 | #[test] |
| 718 | 1407 | fn markers_may_be_indented_a_little_but_must_be_alone() { |
| 719 | 1408 | 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()))); | |
| 721 | 1410 | for not_markers in [ |
| 722 | 1411 | format!(" {START}\n{END}\n"), |
| 723 | 1412 | format!("see `{START}`\n{END}\n"), |
| 724 | 1413 | format!("{START} and more\n{END}\n"), |
| 725 | 1414 | ] { |
| 726 | - assert!(find_section(¬_markers).is_err(), "{not_markers:?}"); | |
| 1415 | + assert!(find(¬_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:?}"); | |
| 727 | 1444 | } |
| 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, §ion), text); | |
| 1470 | + assert!(includes_agents("\u{feff}@AGENTS.md\n")); | |
| 1471 | + assert_eq!( | |
| 1472 | + append_section("\u{feff}", §ion), | |
| 1473 | + format!("\u{feff}{section}") | |
| 1474 | + ); | |
| 1475 | + assert_eq!( | |
| 1476 | + append_section("\u{feff}# Rules\n", §ion), | |
| 1477 | + format!("\u{feff}# Rules\n\n{section}") | |
| 1478 | + ); | |
| 729 | 1479 | } |
| 730 | 1480 | |
| 731 | 1481 | #[test] |
| @@ -753,7 +1503,7 @@ | ||
| 753 | 1503 | ), |
| 754 | 1504 | ]; |
| 755 | 1505 | for (text, said) in cases { |
| 756 | - let err = find_section(&text).unwrap_err(); | |
| 1506 | + let err = find(&text).unwrap_err(); | |
| 757 | 1507 | assert!(err.contains(said), "{text:?}: {err}"); |
| 758 | 1508 | } |
| 759 | 1509 | } |
| @@ -765,6 +1515,8 @@ | ||
| 765 | 1515 | "# Notes\nSee @AGENTS.md for the rules.\n", |
| 766 | 1516 | "(@./AGENTS.md)\n", |
| 767 | 1517 | " @AGENTS.md ", |
| 1518 | + "```text\nan example\n```\n@AGENTS.md\n", | |
| 1519 | + "Read `this` and @AGENTS.md\n", | |
| 768 | 1520 | ] { |
| 769 | 1521 | assert!(includes_agents(yes), "{yes:?}"); |
| 770 | 1522 | } |
| @@ -774,6 +1526,9 @@ | ||
| 774 | 1526 | "`@AGENTS.md`\n", |
| 775 | 1527 | "@AGENTS.md.bak\n", |
| 776 | 1528 | "@docs/AGENTS.md\n", |
| 1529 | + "``see @AGENTS.md here``\n", | |
| 1530 | + "# Claude notes\n\n```text\n@AGENTS.md\n```\n", | |
| 1531 | + "~~~\n@AGENTS.md\n", | |
| 777 | 1532 | ] { |
| 778 | 1533 | assert!(!includes_agents(no), "{no:?}"); |
| 779 | 1534 | } |
| @@ -783,4 +1538,13 @@ | ||
| 783 | 1538 | assert_eq!(add_include("# Claude\r\n"), "# Claude\r\n@AGENTS.md\r\n"); |
| 784 | 1539 | assert!(includes_agents(&add_include("# Claude\n"))); |
| 785 | 1540 | } |
| 1541 | + | |
| 1542 | + #[test] | |
| 1543 | + fn code_spans_are_left_out() { | |
| 1544 | + assert_eq!(without_code_spans("a `b` c"), "a c"); | |
| 1545 | + assert_eq!(without_code_spans("a ``b ` c`` d"), "a d"); | |
| 1546 | + assert_eq!(without_code_spans("a ` b"), "a ` b"); | |
| 1547 | + assert_eq!(without_code_spans("é `x` ü"), "é ü"); | |
| 1548 | + assert_eq!(without_code_spans("``a` b"), "``a` b"); | |
| 1549 | + } | |
| 786 | 1550 | } |
modified crates/cli/src/main.rs +114 −6
| @@ -17,11 +17,12 @@ | ||
| 17 | 17 | use anyhow::{Context, Result, bail}; |
| 18 | 18 | use braid_format::changeset::decode_change_list; |
| 19 | 19 | use braid_format::{ |
| 20 | - Change, ChangeOp, Changes, Changeset, IdHasher, Kind, ObjectId, Objects, Signature, | |
| 20 | + Change, ChangeOp, Changes, Changeset, EntryKind, IdHasher, Kind, ObjectId, Objects, Signature, | |
| 21 | 21 | }; |
| 22 | 22 | use braid_repo::Repo; |
| 23 | 23 | use braid_store::{FsckReport, Operation, RefUpdate}; |
| 24 | -use clap::{Parser, Subcommand}; | |
| 24 | +use clap::parser::ValueSource; | |
| 25 | +use clap::{ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand}; | |
| 25 | 26 | use serde_json::{Value, json}; |
| 26 | 27 | |
| 27 | 28 | /// Version control for many agents landing changes at once. |
| @@ -52,6 +53,79 @@ | ||
| 52 | 53 | |
| 53 | 54 | #[command(subcommand)] |
| 54 | 55 | 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 | + } | |
| 55 | 129 | } |
| 56 | 130 | |
| 57 | 131 | #[derive(Debug, Subcommand)] |
| @@ -75,9 +149,12 @@ | ||
| 75 | 149 | #[arg(required = true)] |
| 76 | 150 | paths: Vec<PathBuf>, |
| 77 | 151 | }, |
| 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. | |
| 79 | 154 | 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. | |
| 81 | 158 | revision: String, |
| 82 | 159 | }, |
| 83 | 160 | /// List refs and the objects they point at. |
| @@ -262,7 +339,9 @@ | ||
| 262 | 339 | } |
| 263 | 340 | |
| 264 | 341 | 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); | |
| 266 | 345 | match run(&cli) { |
| 267 | 346 | Ok(code) => code, |
| 268 | 347 | Err(err) => { |
| @@ -433,9 +512,38 @@ | ||
| 433 | 512 | Ok((hasher.finalize(), size)) |
| 434 | 513 | } |
| 435 | 514 | |
| 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 | + | |
| 436 | 544 | fn cat_object(cli: &Cli, revision: &str) -> Result<ExitCode> { |
| 437 | 545 | let repo = open_repo(cli)?; |
| 438 | - let id = repo.resolve(revision)?; | |
| 546 | + let id = resolve_object(&repo, revision)?; | |
| 439 | 547 | if cli.json { |
| 440 | 548 | // The size is in the record's header: nothing needs decoding. |
| 441 | 549 | let Some((kind, size)) = repo.store().stat(&id)? else { |
modified crates/cli/src/work.rs +117 −20
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | use braid_engine::{Conflict, ConflictKind, HunkSide}; |
| 17 | 17 | use braid_format::{ChangeOp, EntryKind, ObjectId}; |
| 18 | 18 | use braid_repo::{Location, Repo}; |
| 19 | +use braid_store::Refs; | |
| 19 | 20 | use braid_wc::{ |
| 20 | 21 | BEHIND_LIMIT, Blocker, ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, |
| 21 | 22 | Placed, RebaseProgress, UpdateReport, Updated, Workspace, |
| @@ -63,7 +64,8 @@ | ||
| 63 | 64 | next on conflicts, what to run next: braid update after land; |
| 64 | 65 | braid commit, once the files are fixed, after update; a |
| 65 | 66 | 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 | |
| 67 | 69 | |
| 68 | 70 | Ids in JSON are full; text output shows their first 12 hex digits." |
| 69 | 71 | }; |
| @@ -133,6 +135,22 @@ | ||
| 133 | 135 | report_fields!() |
| 134 | 136 | ); |
| 135 | 137 | |
| 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 | + | |
| 136 | 154 | /// The long help of `change create`. |
| 137 | 155 | pub(crate) const CREATE_HELP: &str = concat!( |
| 138 | 156 | "Make a changeset on a base without a working copy, and optionally land |
| @@ -147,20 +165,28 @@ | ||
| 147 | 165 | #[derive(Debug, Subcommand)] |
| 148 | 166 | pub(crate) enum WorkspaceAction { |
| 149 | 167 | /// Create a workspace and write its files. |
| 168 | + #[command(long_about = ADD_HELP)] | |
| 150 | 169 | 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. | |
| 152 | 172 | name: String, |
| 153 | 173 | /// Its directory, which must not exist or be empty (default: |
| 154 | - /// ./<name>). | |
| 174 | + /// .braid/work/<name> in the repository's root). | |
| 155 | 175 | path: Option<PathBuf>, |
| 156 | 176 | /// The changeset to start at: a ref, an id or a short id (default: |
| 157 | 177 | /// the head of the tracked branch, or nothing if it does not exist |
| 158 | 178 | /// yet). |
| 159 | 179 | #[arg(long, value_name = "REV")] |
| 160 | 180 | 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. | |
| 162 | 184 | #[arg(long, value_name = "BRANCH", default_value = "main")] |
| 163 | 185 | 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, | |
| 164 | 190 | }, |
| 165 | 191 | /// List the repository's workspaces. |
| 166 | 192 | List, |
| @@ -287,6 +313,53 @@ | ||
| 287 | 313 | } |
| 288 | 314 | } |
| 289 | 315 | |
| 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 | + | |
| 290 | 363 | fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> { |
| 291 | 364 | Ok(Identity::resolve(args.author.as_deref(), repo)?) |
| 292 | 365 | } |
| @@ -330,15 +403,18 @@ | ||
| 330 | 403 | path, |
| 331 | 404 | at, |
| 332 | 405 | track, |
| 406 | + new_branch, | |
| 333 | 407 | } => { |
| 334 | 408 | let repo = open_repo(cli)?; |
| 409 | + let refs = repo.store().refs()?; | |
| 410 | + check_tracked(&refs, track, *new_branch)?; | |
| 335 | 411 | let at = match at { |
| 336 | 412 | Some(revision) => Some(resolve_changeset(&repo, revision)?), |
| 337 | - None => repo.store().refs()?.get(track), | |
| 413 | + None => refs.get(track), | |
| 338 | 414 | }; |
| 339 | 415 | let dir = match path { |
| 340 | 416 | Some(path) => path.clone(), |
| 341 | - None => std::env::current_dir()?.join(name), | |
| 417 | + None => Workspace::default_dir(&repo, name), | |
| 342 | 418 | }; |
| 343 | 419 | let (workspace, files) = Workspace::create(&repo, name, &dir, at, track)?; |
| 344 | 420 | if cli.json { |
| @@ -487,25 +563,28 @@ | ||
| 487 | 563 | }; |
| 488 | 564 | writeln!( |
| 489 | 565 | out, |
| 490 | - "{} is {ahead} ahead, at {}: run `braid update`", | |
| 566 | + "{} is {ahead} ahead, at {}: run `{}`", | |
| 491 | 567 | state.branch, |
| 492 | - short(report.head) | |
| 568 | + short(report.head), | |
| 569 | + cli.hint("update") | |
| 493 | 570 | )?; |
| 494 | 571 | } |
| 495 | 572 | if let Some(rebase) = &state.rebase { |
| 496 | 573 | writeln!( |
| 497 | 574 | out, |
| 498 | - "Rebase of {} in progress onto {}; resolve, then `braid commit`", | |
| 575 | + "Rebase of {} in progress onto {}; resolve, then `{}`", | |
| 499 | 576 | rebase.change.short(), |
| 500 | - rebase.onto.short() | |
| 577 | + rebase.onto.short(), | |
| 578 | + cli.hint("commit") | |
| 501 | 579 | )?; |
| 580 | + let resolve = format!("run `{}` once settled", cli.hint("resolve")); | |
| 502 | 581 | for (conflict, remain) in &report.conflicts { |
| 503 | 582 | let note = if conflict.markers { |
| 504 | 583 | if *remain { "markers remain" } else { "edited" } |
| 505 | 584 | } else if conflict.resolved { |
| 506 | 585 | "resolved" |
| 507 | 586 | } else { |
| 508 | - "run `braid resolve` once settled" | |
| 587 | + &resolve | |
| 509 | 588 | }; |
| 510 | 589 | writeln!( |
| 511 | 590 | out, |
| @@ -524,7 +603,11 @@ | ||
| 524 | 603 | } |
| 525 | 604 | } |
| 526 | 605 | 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 | + )?; | |
| 528 | 611 | for path in &status.needs_track { |
| 529 | 612 | writeln!(out, " {}", show(path))?; |
| 530 | 613 | } |
| @@ -602,8 +685,9 @@ | ||
| 602 | 685 | RebaseProgress::None => {} |
| 603 | 686 | RebaseProgress::Finished { tip } => { |
| 604 | 687 | 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") | |
| 607 | 691 | ); |
| 608 | 692 | } |
| 609 | 693 | RebaseProgress::Stopped { change, conflicts } => { |
| @@ -681,7 +765,7 @@ | ||
| 681 | 765 | operation: None, |
| 682 | 766 | change, |
| 683 | 767 | conflicts, |
| 684 | - next: (!conflicts.is_empty()).then(|| "braid commit".to_owned()), | |
| 768 | + next: None, | |
| 685 | 769 | workspace: Some((report.base, &report.updated_paths)), |
| 686 | 770 | } |
| 687 | 771 | } |
| @@ -746,7 +830,7 @@ | ||
| 746 | 830 | let mut report = Report::landing(&landing); |
| 747 | 831 | report.workspace = Some((workspace.state()?.base, &landing.updated_paths)); |
| 748 | 832 | if !report.conflicts.is_empty() { |
| 749 | - report.next = Some("braid update".to_owned()); | |
| 833 | + report.next = Some(cli.hint("update")); | |
| 750 | 834 | } |
| 751 | 835 | if cli.json { |
| 752 | 836 | print_json(&report.json())?; |
| @@ -783,7 +867,10 @@ | ||
| 783 | 867 | short(landing.head_before), |
| 784 | 868 | ); |
| 785 | 869 | 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 | + ); | |
| 787 | 874 | } |
| 788 | 875 | } |
| 789 | 876 | report.print_updated(); |
| @@ -795,7 +882,10 @@ | ||
| 795 | 882 | let workspace = target.open()?; |
| 796 | 883 | let committer = identity(args, &target.repo)?; |
| 797 | 884 | 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 | + } | |
| 799 | 889 | if cli.json { |
| 800 | 890 | print_json(&report.json())?; |
| 801 | 891 | return Ok(report.exit_code()); |
| @@ -822,7 +912,11 @@ | ||
| 822 | 912 | head.short() |
| 823 | 913 | ); |
| 824 | 914 | 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 | + ); | |
| 826 | 920 | } |
| 827 | 921 | } |
| 828 | 922 | report.print_updated(); |
| @@ -971,7 +1065,10 @@ | ||
| 971 | 1065 | if !report.conflicts.is_empty() { |
| 972 | 1066 | // The change was built on a base the branch has moved past: |
| 973 | 1067 | // 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 | + ))); | |
| 975 | 1072 | } |
| 976 | 1073 | report.json() |
| 977 | 1074 | } |
modified crates/cli/tests/agents.rs +472 −60
| @@ -2,8 +2,9 @@ | ||
| 2 | 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | 3 | |
| 4 | 4 | //! 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. | |
| 7 | 8 | |
| 8 | 9 | use std::fs; |
| 9 | 10 | use std::path::{Path, PathBuf}; |
| @@ -14,11 +15,22 @@ | ||
| 14 | 15 | const START: &str = "<!-- braid:start -->"; |
| 15 | 16 | const END: &str = "<!-- braid:end -->"; |
| 16 | 17 | |
| 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 | + | |
| 17 | 28 | /// Runs braid in `dir`. |
| 18 | 29 | fn braid(dir: &Path, args: &[&str]) -> Output { |
| 19 | 30 | Command::new(env!("CARGO_BIN_EXE_braid")) |
| 20 | 31 | .current_dir(dir) |
| 21 | 32 | .args(args) |
| 33 | + .envs(GIT_ENV) | |
| 22 | 34 | .env("BRAID_AUTHOR", "Ada <ada@example.org>") |
| 23 | 35 | .env("BRAID_AGENT", "tester") |
| 24 | 36 | .output() |
| @@ -36,6 +48,20 @@ | ||
| 36 | 48 | String::from_utf8(out.stdout).unwrap() |
| 37 | 49 | } |
| 38 | 50 | |
| 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 | + | |
| 39 | 65 | /// Runs `braid agents init` with `--json` and these arguments in `dir`. |
| 40 | 66 | fn init_json(dir: &Path, args: &[&str]) -> Value { |
| 41 | 67 | let mut all = vec!["agents", "init", "--json"]; |
| @@ -92,35 +118,70 @@ | ||
| 92 | 118 | ); |
| 93 | 119 | } |
| 94 | 120 | |
| 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 | + | |
| 95 | 142 | #[test] |
| 96 | -fn a_fresh_directory_gets_an_agents_md_and_no_claude_md() { | |
| 143 | +fn without_a_repository_the_branch_must_be_given() { | |
| 97 | 144 | 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"]); | |
| 99 | 155 | assert_eq!(names(&report, "created"), ["AGENTS.md"]); |
| 100 | 156 | assert!(names(&report, "updated").is_empty()); |
| 101 | 157 | assert!(names(&report, "unchanged").is_empty()); |
| 102 | 158 | assert_eq!(report["branch"], "main"); |
| 159 | + assert_eq!(report["previous_branch"], Value::Null); | |
| 103 | 160 | assert_eq!(report["dry_run"], false); |
| 104 | 161 | assert!(report["repository"].is_null()); |
| 105 | 162 | assert_eq!(report["dir"], dir.to_str().unwrap()); |
| 163 | + assert_eq!(report["paths"]["AGENTS.md"], "AGENTS.md"); | |
| 106 | 164 | |
| 107 | 165 | let text = read(&dir.join("AGENTS.md")); |
| 108 | 166 | assert!(text.starts_with(&format!("{START}\n")), "{text}"); |
| 109 | 167 | 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")); | |
| 111 | 169 | assert!(text.contains("https://braid.elffuss.com/agents.md")); |
| 112 | 170 | assert!(!dir.join("CLAUDE.md").exists()); |
| 171 | + assert!(!dir.join("GEMINI.md").exists()); | |
| 113 | 172 | |
| 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. | |
| 116 | 174 | 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 | + ); | |
| 119 | 180 | } |
| 120 | 181 | |
| 121 | 182 | #[test] |
| 122 | 183 | fn only_the_section_changes_and_a_second_run_changes_nothing() { |
| 123 | - let (_temp, dir) = temp(); | |
| 184 | + let (_temp, dir) = project(); | |
| 124 | 185 | let above = "# Our project\n\nTabs, not spaces.\n\n"; |
| 125 | 186 | let older = format!("{START}\n## Braid\n\nAn older section.\n{END}\n"); |
| 126 | 187 | let below = "\n## Releases\n\nTagged by hand.\n"; |
| @@ -128,6 +189,7 @@ | ||
| 128 | 189 | |
| 129 | 190 | let report = init_json(&dir, &[]); |
| 130 | 191 | assert_eq!(names(&report, "updated"), ["AGENTS.md"]); |
| 192 | + assert_eq!(report["repository"], dir.to_str().unwrap()); | |
| 131 | 193 | let text = read(&dir.join("AGENTS.md")); |
| 132 | 194 | assert!(text.starts_with(above), "{text}"); |
| 133 | 195 | assert!(text.ends_with(below), "{text}"); |
| @@ -136,18 +198,18 @@ | ||
| 136 | 198 | assert!(!section.contains("An older section")); |
| 137 | 199 | assert!(section.contains("--track main")); |
| 138 | 200 | |
| 139 | - // Idempotent: the same bytes, reported unchanged. | |
| 140 | 201 | let report = init_json(&dir, &[]); |
| 141 | 202 | assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]); |
| 142 | 203 | assert!(names(&report, "updated").is_empty()); |
| 143 | 204 | assert_eq!(read(&dir.join("AGENTS.md")), text); |
| 144 | 205 | let said = ok(&dir, &["agents", "init"]); |
| 145 | 206 | assert!(said.contains("has this braid section already"), "{said}"); |
| 207 | + assert!(!said.contains("braid init"), "{said}"); | |
| 146 | 208 | } |
| 147 | 209 | |
| 148 | 210 | #[test] |
| 149 | 211 | fn a_file_without_markers_gets_the_section_at_its_end_once() { |
| 150 | - let (_temp, dir) = temp(); | |
| 212 | + let (_temp, dir) = project(); | |
| 151 | 213 | let ours = "# Rules\n\nRun the tests before you push."; |
| 152 | 214 | fs::write(dir.join("AGENTS.md"), ours).unwrap(); |
| 153 | 215 | let said = ok(&dir, &["agents", "init"]); |
| @@ -167,7 +229,7 @@ | ||
| 167 | 229 | |
| 168 | 230 | #[test] |
| 169 | 231 | fn unbalanced_markers_are_refused_and_nothing_is_written() { |
| 170 | - let (_temp, dir) = temp(); | |
| 232 | + let (_temp, dir) = project(); | |
| 171 | 233 | let claude = "# Claude\n"; |
| 172 | 234 | fs::write(dir.join("CLAUDE.md"), claude).unwrap(); |
| 173 | 235 | for (text, lines) in [ |
| @@ -186,10 +248,7 @@ | ||
| 186 | 248 | &["agents", "init", "--json"], |
| 187 | 249 | &["agents", "init", "--dry-run"], |
| 188 | 250 | ] { |
| 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); | |
| 193 | 252 | assert!(err.contains("unbalanced braid markers"), "{err}"); |
| 194 | 253 | assert!(err.contains(lines), "{text:?}: {err}"); |
| 195 | 254 | assert!(err.contains("nothing was written"), "{err}"); |
| @@ -199,13 +258,59 @@ | ||
| 199 | 258 | } |
| 200 | 259 | } |
| 201 | 260 | |
| 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 | + | |
| 202 | 308 | #[test] |
| 203 | 309 | fn claude_md_gets_the_include_line_and_only_that() { |
| 204 | - let (_temp, dir) = temp(); | |
| 310 | + let (_temp, dir) = project(); | |
| 205 | 311 | let claude = "# Notes for Claude\n\nBe brief."; |
| 206 | 312 | fs::write(dir.join("CLAUDE.md"), claude).unwrap(); |
| 207 | 313 | |
| 208 | - // --no-claude leaves it alone, and does not list it. | |
| 209 | 314 | let report = init_json(&dir, &["--no-claude"]); |
| 210 | 315 | assert_eq!(names(&report, "created"), ["AGENTS.md"]); |
| 211 | 316 | assert!(names(&report, "updated").is_empty()); |
| @@ -215,12 +320,12 @@ | ||
| 215 | 320 | let report = init_json(&dir, &[]); |
| 216 | 321 | assert_eq!(names(&report, "updated"), ["CLAUDE.md"]); |
| 217 | 322 | assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]); |
| 323 | + assert_eq!(report["paths"]["CLAUDE.md"], "CLAUDE.md"); | |
| 218 | 324 | assert_eq!( |
| 219 | 325 | read(&dir.join("CLAUDE.md")), |
| 220 | 326 | format!("{claude}\n@AGENTS.md\n") |
| 221 | 327 | ); |
| 222 | 328 | |
| 223 | - // Once it includes AGENTS.md, it is left as it is. | |
| 224 | 329 | let report = init_json(&dir, &[]); |
| 225 | 330 | assert_eq!(names(&report, "unchanged"), ["AGENTS.md", "CLAUDE.md"]); |
| 226 | 331 | for including in ["See @AGENTS.md for the rules.\n", "@./AGENTS.md\n"] { |
| @@ -232,18 +337,52 @@ | ||
| 232 | 337 | ); |
| 233 | 338 | assert_eq!(read(&dir.join("CLAUDE.md")), including); |
| 234 | 339 | } |
| 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 | + ); | |
| 235 | 375 | } |
| 236 | 376 | |
| 237 | 377 | #[cfg(unix)] |
| 238 | 378 | #[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(); | |
| 243 | 381 | std::os::unix::fs::symlink("AGENTS.md", dir.join("CLAUDE.md")).unwrap(); |
| 244 | 382 | let report = init_json(&dir, &[]); |
| 245 | 383 | assert_eq!(names(&report, "created"), ["AGENTS.md"]); |
| 246 | 384 | assert_eq!(names(&report, "unchanged"), ["CLAUDE.md"]); |
| 385 | + assert_eq!(report["paths"]["CLAUDE.md"], "AGENTS.md"); | |
| 247 | 386 | assert!(!read(&dir.join("AGENTS.md")).contains("@AGENTS.md")); |
| 248 | 387 | assert!( |
| 249 | 388 | fs::symlink_metadata(dir.join("CLAUDE.md")) |
| @@ -251,27 +390,191 @@ | ||
| 251 | 390 | .file_type() |
| 252 | 391 | .is_symlink() |
| 253 | 392 | ); |
| 393 | + let report = init_json(&dir, &[]); | |
| 394 | + assert_eq!(names(&report, "unchanged"), ["AGENTS.md", "CLAUDE.md"]); | |
| 254 | 395 | |
| 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, &[]); | |
| 263 | 403 | 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(); | |
| 265 | 406 | 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); | |
| 270 | 573 | } |
| 271 | 574 | |
| 272 | 575 | #[test] |
| 273 | 576 | fn a_dry_run_says_what_would_change_and_writes_nothing() { |
| 274 | - let (_temp, dir) = temp(); | |
| 577 | + let (_temp, dir) = project(); | |
| 275 | 578 | fs::write(dir.join("CLAUDE.md"), "# Claude\n").unwrap(); |
| 276 | 579 | let report = init_json(&dir, &["--dry-run"]); |
| 277 | 580 | assert_eq!(report["dry_run"], true); |
| @@ -284,11 +587,9 @@ | ||
| 284 | 587 | assert!(said.contains("Would create AGENTS.md"), "{said}"); |
| 285 | 588 | assert!(said.contains("Would add @AGENTS.md to CLAUDE.md"), "{said}"); |
| 286 | 589 | assert!(said.contains("Nothing was written."), "{said}"); |
| 287 | - // The section it would write, whole. | |
| 288 | 590 | assert!(said.ends_with(&format!("{END}\n")), "{said}"); |
| 289 | 591 | assert!(said.contains(START)); |
| 290 | 592 | assert!(!dir.join("AGENTS.md").exists()); |
| 291 | - // Nothing to do: nothing to show either. | |
| 292 | 593 | ok(&dir, &["agents", "init"]); |
| 293 | 594 | let said = ok(&dir, &["agents", "init", "--dry-run"]); |
| 294 | 595 | assert!(!said.contains(START), "{said}"); |
| @@ -302,44 +603,121 @@ | ||
| 302 | 603 | assert_eq!(report["branch"], "master"); |
| 303 | 604 | assert_eq!(report["repository"], dir.to_str().unwrap()); |
| 304 | 605 | |
| 305 | - // A repository whose only branch has another name. | |
| 306 | 606 | let (_other, trunk) = temp(); |
| 307 | 607 | repository_with_branch(&trunk, "trunk"); |
| 308 | 608 | let report = init_json(&trunk, &[]); |
| 309 | 609 | assert_eq!(report["branch"], "trunk"); |
| 310 | 610 | let text = read(&trunk.join("AGENTS.md")); |
| 311 | 611 | 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}"); | |
| 314 | 613 | ok(&trunk, &["ref", "set", "main", "trunk"]); |
| 315 | 614 | let report = init_json(&trunk, &[]); |
| 316 | 615 | assert_eq!(report["branch"], "trunk"); |
| 317 | 616 | assert_eq!(names(&report, "unchanged"), ["AGENTS.md"]); |
| 318 | - // --branch says otherwise. | |
| 319 | 617 | let report = init_json(&trunk, &["--branch", "main"]); |
| 320 | 618 | assert_eq!(report["branch"], "main"); |
| 619 | + assert_eq!(report["previous_branch"], "trunk"); | |
| 321 | 620 | assert_eq!(names(&report, "updated"), ["AGENTS.md"]); |
| 322 | 621 | assert!(read(&trunk.join("AGENTS.md")).contains("--track main\n")); |
| 323 | 622 | |
| 324 | - // Two branches, neither main nor master: braid will not guess. | |
| 325 | 623 | let (_third, two) = temp(); |
| 326 | 624 | repository_with_branch(&two, "trunk"); |
| 327 | 625 | 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"]); | |
| 331 | 627 | assert!(err.contains("develop, trunk; pass --branch"), "{err}"); |
| 332 | 628 | assert!(!two.join("AGENTS.md").exists()); |
| 333 | 629 | 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]); | |
| 336 | 631 | } |
| 337 | 632 | } |
| 338 | 633 | |
| 339 | 634 | #[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() { | |
| 341 | 645 | 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(); | |
| 343 | 721 | let deep = dir.join("src/deep"); |
| 344 | 722 | fs::create_dir_all(&deep).unwrap(); |
| 345 | 723 | let report = init_json(&deep, &[]); |
| @@ -347,17 +725,15 @@ | ||
| 347 | 725 | assert!(dir.join("AGENTS.md").is_file()); |
| 348 | 726 | assert!(!deep.join("AGENTS.md").exists()); |
| 349 | 727 | |
| 350 | - // A workspace, under .braid/work as the section says, on another | |
| 351 | - // branch: the section goes at its root and names its branch. | |
| 352 | 728 | ok( |
| 353 | 729 | &dir, |
| 354 | 730 | &[ |
| 355 | 731 | "workspace", |
| 356 | 732 | "add", |
| 357 | 733 | "agent-1", |
| 358 | - ".braid/work/agent-1", | |
| 359 | 734 | "--track", |
| 360 | 735 | "release", |
| 736 | + "--new-branch", | |
| 361 | 737 | ], |
| 362 | 738 | ); |
| 363 | 739 | let workspace = dir.join(".braid/work/agent-1"); |
| @@ -368,16 +744,52 @@ | ||
| 368 | 744 | assert_eq!(report["branch"], "release"); |
| 369 | 745 | assert_eq!(report["repository"], dir.to_str().unwrap()); |
| 370 | 746 | assert!(read(&workspace.join("AGENTS.md")).contains("--track release\n")); |
| 371 | - // It is the workspace's change, to commit and land like any other. | |
| 372 | 747 | 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"])); | |
| 374 | 749 | |
| 375 | - // --dir names the directory whatever the current one is. | |
| 376 | 750 | let (_other, elsewhere) = temp(); |
| 377 | 751 | let report = init_json(&elsewhere, &["--dir", dir.join("src").to_str().unwrap()]); |
| 378 | 752 | assert_eq!(report["dir"], dir.join("src").to_str().unwrap()); |
| 379 | 753 | assert_eq!(report["branch"], "main"); |
| 380 | 754 | 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()); | |
| 383 | 795 | } |
modified crates/cli/tests/guides.rs +47 −20
| @@ -3,8 +3,9 @@ | ||
| 3 | 3 | |
| 4 | 4 | //! The guides for coding agents: part 1 of AGENTS.md, which the site also |
| 5 | 5 | //! 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. | |
| 8 | 9 | |
| 9 | 10 | use std::path::Path; |
| 10 | 11 | use std::process::Command; |
| @@ -12,8 +13,13 @@ | ||
| 12 | 13 | const START: &str = "<!-- braid:start -->"; |
| 13 | 14 | const END: &str = "<!-- braid:end -->"; |
| 14 | 15 | |
| 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)"; | |
| 17 | 23 | |
| 18 | 24 | fn repository_file(path: &str) -> String { |
| 19 | 25 | let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); |
| @@ -68,7 +74,10 @@ | ||
| 68 | 74 | /// The section `braid agents init` writes, as its dry run prints it. |
| 69 | 75 | fn section() -> String { |
| 70 | 76 | 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 | + ); | |
| 72 | 81 | let start = said.find(START).expect("the dry run prints the section"); |
| 73 | 82 | said[start..].to_owned() |
| 74 | 83 | } |
| @@ -95,14 +104,10 @@ | ||
| 95 | 104 | fn the_guide_for_agents_is_the_same_in_agents_md_and_on_the_site() { |
| 96 | 105 | let agents = repository_file("AGENTS.md"); |
| 97 | 106 | 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. | |
| 100 | 107 | let first = "### Install"; |
| 101 | 108 | let ours = part(&agents, first, Some("\n## 2."), true); |
| 102 | 109 | let theirs = part(&site, &first[1..], None, false); |
| 103 | 110 | 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. | |
| 106 | 111 | for text in [&agents, &site] { |
| 107 | 112 | assert!( |
| 108 | 113 | !text |
| @@ -110,7 +115,6 @@ | ||
| 110 | 115 | .any(|line| line.trim() == START || line.trim() == END) |
| 111 | 116 | ); |
| 112 | 117 | } |
| 113 | - // CLAUDE.md only includes AGENTS.md. | |
| 114 | 118 | assert_eq!(repository_file("CLAUDE.md"), "@AGENTS.md\n"); |
| 115 | 119 | } |
| 116 | 120 | |
| @@ -119,24 +123,48 @@ | ||
| 119 | 123 | for path in ["README.md", "site/index.html", "site/llms.txt"] { |
| 120 | 124 | assert!(repository_file(path).contains(PROMPT), "{path}"); |
| 121 | 125 | } |
| 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 ")); | |
| 124 | 130 | assert!(repository_file("site/llms.txt").contains("(https://braid.elffuss.com/agents.md)")); |
| 125 | 131 | } |
| 126 | 132 | |
| 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 | + | |
| 127 | 152 | #[test] |
| 128 | 153 | 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(§ion())); | |
| 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(§ion())); | |
| 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) | |
| 134 | 164 | .collect(); |
| 135 | 165 | assert!(commands.len() >= 15, "{commands:?}"); |
| 136 | - // Subcommands that take a subcommand of their own. | |
| 137 | 166 | let groups = ["agents", "change", "git", "op", "ref", "workspace"]; |
| 138 | 167 | for command in &commands { |
| 139 | - // The words of the command, before any comment. | |
| 140 | 168 | let words: Vec<&str> = command |
| 141 | 169 | .split(" #") |
| 142 | 170 | .next() |
| @@ -144,7 +172,6 @@ | ||
| 144 | 172 | .split_whitespace() |
| 145 | 173 | .skip(1) |
| 146 | 174 | .collect(); |
| 147 | - // Global flags that take a value come before the subcommand. | |
| 148 | 175 | let mut rest = words.as_slice(); |
| 149 | 176 | while let [flag, _, tail @ ..] = rest { |
| 150 | 177 | 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 @@ | ||
| 48 | 48 | git_ref_for_braid, is_branch, remote_ref, |
| 49 | 49 | }; |
| 50 | 50 | 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}; | |
| 52 | 52 | pub use remote::Remote; |
| 53 | 53 | pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport}; |
| 54 | 54 |
modified crates/repo/src/link.rs +5 −0
| @@ -27,6 +27,11 @@ | ||
| 27 | 27 | /// workspace. |
| 28 | 28 | pub const WORKSPACES_DIR: &str = "ws"; |
| 29 | 29 | |
| 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 | + | |
| 30 | 35 | /// The first line of a workspace file. |
| 31 | 36 | const HEADER: &str = "braid-workspace 1"; |
| 32 | 37 |
modified crates/wc/src/error.rs +18 −2
| @@ -48,7 +48,9 @@ | ||
| 48 | 48 | Assemble(#[from] braid_format::ChangesetError), |
| 49 | 49 | |
| 50 | 50 | /// 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 | + )] | |
| 52 | 54 | NotAWorkspace, |
| 53 | 55 | |
| 54 | 56 | /// A workspace name that is not allowed. |
| @@ -145,7 +147,7 @@ | ||
| 145 | 147 | /// The working copy cannot be committed as it is: conflict markers |
| 146 | 148 | /// remain, conflicts are not marked resolved, or new files wait for |
| 147 | 149 | /// `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))] | |
| 149 | 151 | Blocked(Vec<Blocker>), |
| 150 | 152 | |
| 151 | 153 | /// There is nothing to commit. |
| @@ -226,6 +228,20 @@ | ||
| 226 | 228 | /// How many reasons a refusal lists, at most. |
| 227 | 229 | const REASONS_SHOWN: usize = 20; |
| 228 | 230 | |
| 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 | + | |
| 229 | 245 | fn reasons(blockers: &[Blocker]) -> String { |
| 230 | 246 | let mut shown: Vec<String> = blockers |
| 231 | 247 | .iter() |
modified crates/wc/src/lib.rs +8 −3
| @@ -9,7 +9,12 @@ | ||
| 9 | 9 | //! |
| 10 | 10 | //! A workspace is any directory holding a `.braid` file. The file is local |
| 11 | 11 | //! 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 | |
| 13 | 18 | //! repository, in `.braid/ws/<name>/`: |
| 14 | 19 | //! |
| 15 | 20 | //! ```text |
| @@ -81,6 +86,6 @@ | ||
| 81 | 86 | pub use state::{Checkout, Rebase, RecordedConflict, State}; |
| 82 | 87 | pub use status::{ChangeKind, GUARD_SIZE, PathChange, Status, is_guarded}; |
| 83 | 88 | 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, | |
| 86 | 91 | }; |
modified crates/wc/src/workspace.rs +26 −3
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | Conflict, EMPTY_TREE, first_parent_chain_contains, read_changes, read_changeset, |
| 20 | 20 | }; |
| 21 | 21 | 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}; | |
| 23 | 23 | use braid_store::{RefUpdate, Store, TransactError}; |
| 24 | 24 | |
| 25 | 25 | use crate::blocker::{Blocker, blockers}; |
| @@ -334,16 +334,32 @@ | ||
| 334 | 334 | format!("{prefix}: {outcome} {moves} ({merged} merged)") |
| 335 | 335 | } |
| 336 | 336 | |
| 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 | + | |
| 337 | 346 | impl<'r> Workspace<'r> { |
| 338 | 347 | /// The directory that holds every workspace's state. |
| 339 | 348 | pub fn states_dir(repo: &Repo) -> PathBuf { |
| 340 | 349 | repo.root().join(DIR).join(WORKSPACES_DIR) |
| 341 | 350 | } |
| 342 | 351 | |
| 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 | + | |
| 343 | 358 | /// Creates a workspace named `name` in `dir`, which must not exist or be |
| 344 | 359 | /// 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. | |
| 347 | 363 | pub fn create( |
| 348 | 364 | repo: &'r Repo, |
| 349 | 365 | name: &str, |
| @@ -413,6 +429,13 @@ | ||
| 413 | 429 | fs::File::create_new(&link_path) |
| 414 | 430 | .and_then(|mut file| io::Write::write_all(&mut file, &link.encode())) |
| 415 | 431 | .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))?; | |
| 416 | 439 | |
| 417 | 440 | let workspace = Workspace { |
| 418 | 441 | repo, |
modified docs/design.md +80 −28
| @@ -247,13 +247,27 @@ | ||
| 247 | 247 | - One workspace per agent, all sharing one store. No staging area: tracked |
| 248 | 248 | files are snapshotted as they are. |
| 249 | 249 | - 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. | |
| 257 | 271 | - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger than |
| 258 | 272 | 1 MiB need an explicit `braid track`. Until then `braid commit` refuses, |
| 259 | 273 | naming them, and `--force` leaves them out. |
| @@ -307,35 +321,73 @@ | ||
| 307 | 321 | ### Instructions for agents |
| 308 | 322 | |
| 309 | 323 | 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. | |
| 315 | 331 | |
| 316 | 332 | - **A section of the file, not the file.** The rules sit between a line |
| 317 | 333 | `<!-- braid:start -->` and a line `<!-- braid:end -->`, appended to the |
| 318 | 334 | file the first time and rewritten in place after that. Text outside them |
| 319 | 335 | 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. | |
| 330 | 368 | - **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. | |
| 335 | 379 | - **Every command names its agent.** A harness may run each command in a |
| 336 | 380 | 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. | |
| 339 | 391 | |
| 340 | 392 | ## Git bridge |
| 341 | 393 |
modified fuzz/Cargo.lock +2 −2
| @@ -256,7 +256,7 @@ | ||
| 256 | 256 | |
| 257 | 257 | [[package]] |
| 258 | 258 | name = "elffuss-braid-format" |
| 259 | -version = "0.0.1" | |
| 259 | +version = "0.0.2" | |
| 260 | 260 | dependencies = [ |
| 261 | 261 | "blake3", |
| 262 | 262 | "unicode-normalization", |
| @@ -273,7 +273,7 @@ | ||
| 273 | 273 | |
| 274 | 274 | [[package]] |
| 275 | 275 | name = "elffuss-braid-git" |
| 276 | -version = "0.0.1" | |
| 276 | +version = "0.0.2" | |
| 277 | 277 | dependencies = [ |
| 278 | 278 | "elffuss-braid-format", |
| 279 | 279 | "gix", |
modified site/README.md +16 −7
| @@ -107,9 +107,12 @@ | ||
| 107 | 107 | prints (it names the directory), and change the hero card and the story |
| 108 | 108 | together. |
| 109 | 109 | - 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. | |
| 113 | 116 | - The quick start and the agent's commands under "Many agents on one |
| 114 | 117 | repository" run as one session, top to bottom. `braid undo` comes after the |
| 115 | 118 | agent lands, so it takes that landing back; before it, it would take the |
| @@ -125,21 +128,27 @@ | ||
| 125 | 128 | `scripts/privacy-check.sh` passes. The quick start clones and builds it, |
| 126 | 129 | and CI has run on it: the story says CI runs the scene on every push to |
| 127 | 130 | `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 | |
| 129 | 138 | what `main` holds, not against github.com, which answers 200 for any path |
| 130 | 139 | of an empty repository: a file answers 200 at |
| 131 | 140 | `https://raw.githubusercontent.com/KikoCis/elffuss-braid/main/<path>`, |
| 132 | 141 | and a directory (`crates/sim`, `fuzz/fuzz_targets`, `bench`) is listed by |
| 133 | 142 | `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 | |
| 135 | 144 | 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 | |
| 137 | 146 | name, `http://braid.elffuss.com/` redirects to it, and |
| 138 | 147 | `https://braid.elffuss.com/og.png` answers 200 as `image/png`. Only then |
| 139 | 148 | does the link go anywhere: the repository's homepage |
| 140 | 149 | (`gh repo edit KikoCis/elffuss-braid --homepage https://braid.elffuss.com`), |
| 141 | 150 | 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 | |
| 143 | 152 | `text/markdown; charset=utf-8` and `https://braid.elffuss.com/llms.txt` |
| 144 | 153 | as `text/plain; charset=utf-8`, so that an agent reads them as text: |
| 145 | 154 | `curl -sI` shows the type. A server that does not know `.md` may send |
modified site/agents.md +178 −80
| @@ -1,7 +1,10 @@ | ||
| 1 | 1 | # Braid for coding agents: install it and set it up |
| 2 | 2 | |
| 3 | 3 | 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 | |
| 5 | 8 | [AGENTS.md](https://github.com/KikoCis/elffuss-braid/blob/main/AGENTS.md) |
| 6 | 9 | in braid's repository. |
| 7 | 10 | |
| @@ -18,99 +21,165 @@ | ||
| 18 | 21 | |
| 19 | 22 | ## Install |
| 20 | 23 | |
| 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. | |
| 23 | 34 | |
| 24 | 35 | ```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 | |
| 26 | 37 | ``` |
| 27 | 38 | |
| 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. | |
| 31 | 47 | |
| 32 | 48 | ## Is it installed, and set up here? |
| 33 | 49 | |
| 34 | 50 | ```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 | |
| 36 | 52 | braid refs # in the project root: its branches, once it is set up |
| 37 | 53 | ``` |
| 38 | 54 | |
| 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". | |
| 42 | 63 | |
| 43 | 64 | ## Set up a project |
| 44 | 65 | |
| 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. | |
| 49 | 82 | |
| 50 | 83 | ```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 | |
| 54 | 88 | braid git import . # the project's whole history: every local branch and tag |
| 55 | 89 | braid agents init # the rules for agents, in AGENTS.md |
| 56 | 90 | ``` |
| 57 | 91 | |
| 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. | |
| 60 | 95 | - `.braid/config` names who signs the changesets agents make, here the |
| 61 | 96 | 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`. | |
| 63 | 106 | - `braid agents init` writes a section into `AGENTS.md`, creating the file |
| 64 | 107 | if there is none, between a `<!-- braid:start -->` line and a |
| 65 | 108 | `<!-- braid:end -->` line. The section tells every agent session to work |
| 66 | 109 | 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. | |
| 75 | 115 | |
| 76 | 116 | 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. | |
| 78 | 122 | |
| 79 | 123 | ```bash |
| 80 | 124 | 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" | |
| 83 | 128 | braid git import . # braid's main takes the commit |
| 84 | 129 | braid log main -n 1 # and shows it |
| 85 | 130 | ``` |
| 86 | 131 | |
| 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. | |
| 88 | 135 | |
| 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 | |
| 91 | 137 | |
| 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. | |
| 92 | 147 | - **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. | |
| 100 | 158 | |
| 101 | 159 | ```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 | |
| 104 | 162 | ``` |
| 105 | 163 | |
| 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. | |
| 109 | 177 | - **Record and land** from the workspace. `--agent` (or `BRAID_AGENT`) |
| 110 | 178 | names the session in the op log and in every changeset it makes; pass it |
| 111 | 179 | every time, since a harness may not keep variables between commands. If |
| 112 | 180 | 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. | |
| 114 | 183 | |
| 115 | 184 | ```bash |
| 116 | 185 | braid --agent agent-1 status --json |
| @@ -119,28 +188,43 @@ | ||
| 119 | 188 | ``` |
| 120 | 189 | |
| 121 | 190 | 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 | |
| 123 | 196 | fast-forward or rebased onto whatever landed first. |
| 124 | 197 | - **Before a new task**, `braid --agent agent-1 update` brings the |
| 125 | 198 | workspace onto `main`. `status --json` says how far behind it is |
| 126 | 199 | (`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. | |
| 127 | 205 | - **Done**: once everything has landed, `braid workspace remove agent-1` |
| 128 | 206 | from the project root. It refuses while the workspace holds work that |
| 129 | 207 | 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`. | |
| 132 | 214 | - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger |
| 133 | 215 | 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. | |
| 135 | 218 | |
| 136 | 219 | ## Conflicts |
| 137 | 220 | |
| 138 | 221 | 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. | |
| 144 | 228 | |
| 145 | 229 | ```bash |
| 146 | 230 | braid --agent agent-1 update # exit status 2: conflict markers in the files |
| @@ -150,7 +234,9 @@ | ||
| 150 | 234 | ``` |
| 151 | 235 | |
| 152 | 236 | `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. | |
| 154 | 240 | |
| 155 | 241 | ## Keeping the git remote up to date |
| 156 | 242 | |
| @@ -159,25 +245,31 @@ | ||
| 159 | 245 | braid's branch when only the remote moved, pushes braid's branch when only |
| 160 | 246 | braid moved, and when both moved, merges them and pushes the merge. The |
| 161 | 247 | 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. | |
| 166 | 255 | |
| 167 | 256 | ```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 | |
| 170 | 259 | git pull --ff-only # the shared checkout follows |
| 171 | 260 | ``` |
| 172 | 261 | |
| 173 | 262 | - With `--json`, `outcome` is one of `up_to_date`, `created`, |
| 174 | 263 | `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. | |
| 176 | 266 | - Each changeset reaches git as a commit of its own, with an `agent` header |
| 177 | 267 | that names the agent that made it. |
| 178 | 268 | - Exit status 1 with `remote_moved`: someone pushed meanwhile; sync again. |
| 179 | 269 | 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. | |
| 181 | 273 | - Exit status 2 with `conflicts`: braid and the remote changed the same |
| 182 | 274 | lines. Nothing moved and nothing was pushed. Merge them in git, in the |
| 183 | 275 | shared checkout, and sync again: |
| @@ -200,32 +292,38 @@ | ||
| 200 | 292 | parents to tell what a workspace has landed, so the workspaces carry on |
| 201 | 293 | from the merge. |
| 202 | 294 | |
| 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`. | |
| 206 | 300 | |
| 207 | 301 | ## Undoing |
| 208 | 302 | |
| 209 | 303 | - `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. | |
| 214 | 308 | - A change that landed under other changes cannot be undone that way. |
| 215 | 309 | 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. | |
| 223 | 319 | |
| 224 | 320 | ## What not to do |
| 225 | 321 | |
| 226 | 322 | - Do not edit files, `git add`, `git commit`, `git push` or `git pull` in |
| 227 | 323 | the shared checkout while you work: only setting up, syncing and merging |
| 228 | 324 | 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. | |
| 229 | 327 | - Do not share a workspace between sessions, or work in another session's |
| 230 | 328 | workspace. |
| 231 | 329 | - Do not run `braid undo` without reading `braid op log` first. |
modified site/index.html +14 −14
| @@ -182,8 +182,8 @@ | ||
| 182 | 182 | <span class="x"> CONTENT notes.txt (1 region)</span> |
| 183 | 183 | Run `braid update` to bring the conflicts into the working copy.</code></pre> |
| 184 | 184 | </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> | |
| 187 | 187 | <figure class="term t-b" lang="en"> |
| 188 | 188 | <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> |
| 189 | 189 | <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 @@ | ||
| 408 | 408 | <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> |
| 409 | 409 | <div class="code prompt" data-l="en" lang="en"> |
| 410 | 410 | <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> | |
| 412 | 412 | </div> |
| 413 | 413 | <div class="code prompt" data-l="es" lang="es"> |
| 414 | 414 | <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> | |
| 416 | 416 | </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> | |
| 421 | 421 | </div> |
| 422 | 422 | </section> |
| 423 | 423 | |
| @@ -479,8 +479,8 @@ | ||
| 479 | 479 | <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 |
| 480 | 480 | export BRAID_AUTHOR="Ada Lovelace <ada@example.org>" |
| 481 | 481 | 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 | |
| 484 | 484 | echo 'fn main() {}' > main.rs |
| 485 | 485 | braid status |
| 486 | 486 | braid commit -m "Add main.rs" |
| @@ -503,8 +503,8 @@ | ||
| 503 | 503 | <p data-l="en" lang="en"><code class="nw">--json</code> on every command; <code>change create</code> always prints JSON.</p> |
| 504 | 504 | <p data-l="es" lang="es"><code class="nw">--json</code> en todos los comandos; <code>change create</code> imprime siempre JSON.</p></li> |
| 505 | 505 | <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> | |
| 508 | 508 | <li><h4><span data-l="en" lang="en">Status</span><span data-l="es" lang="es">Estado</span></h4> |
| 509 | 509 | <p data-l="en" lang="en"><code>braid status <span class="nw">--json</span></code> gives <code>behind_by</code>, <code>unlanded</code>, <code>ready_to_commit</code> and <code>blocking</code>, which lists the same reasons <code>braid commit</code> refuses with.</p> |
| 510 | 510 | <p data-l="es" lang="es"><code>braid status <span class="nw">--json</span></code> da <code>behind_by</code>, <code>unlanded</code>, <code>ready_to_commit</code> y <code>blocking</code>, que lista los mismos motivos por los que <code>braid commit</code> se niega.</p></li> |
| @@ -518,8 +518,8 @@ | ||
| 518 | 518 | <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> |
| 519 | 519 | <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> |
| 520 | 520 | <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> | |
| 523 | 523 | <li class="wide"><h4><span data-l="en" lang="en">No checkout</span><span data-l="es" lang="es">Sin checkout</span></h4> |
| 524 | 524 | <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> |
| 525 | 525 | <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 @@ | ||
| 4 | 4 | |
| 5 | 5 | 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. |
| 6 | 6 | |
| 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) | |
| 8 | 8 | |
| 9 | 9 | ## Docs |
| 10 | 10 | |
| 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. | |
| 12 | 12 | - [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. |
| 13 | 13 | - [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. |
| 14 | 14 | - [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. |