Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 10.0 KiB · executableRawPermalink
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3# Copyright (c) 2026 UtopiaIA
4"""Records the README's terminal demos as asciicast v2 files.
5
6Every command runs for real, in a throwaway directory, and its output is kept
7as braid printed it; only that directory's prefix is shortened to ~/demo. The
8typing and the pauses are paced for a reader, so the recordings say nothing
9about how long anything takes. render.sh turns them into GIFs.
10
11usage: record.py <braid binary> <empty work dir> <out dir>
12"""
13import json
14import os
15import random
16import subprocess
17import sys
18
19BRAID, WORK, OUT = (os.path.realpath(p) for p in sys.argv[1:4])
20
21AGENT = {
22 "agent-a": (200, 160, 106),
23 "agent-b": (84, 220, 198),
24 "agent-c": (130, 114, 255),
25}
26MUTED = (127, 124, 160)
27PINK = (231, 121, 207)
28RESET = "\x1b[0m"
29WIDTH, HEIGHT = 100, 26
30GIT = "git -c user.name='Ada Lovelace' -c user.email=ada@example.org -c init.defaultBranch=main"
31
32
33def rgb(color):
34 return "\x1b[38;2;%d;%d;%dm" % color
35
36
37class Scene:
38 """One recording: a directory, an environment and a clock."""
39
40 def __init__(self, name, root, env, cwd="."):
41 self.name = name
42 self.root = root
43 self.env = env
44 self.cwd = cwd
45 self.t = 0.0
46 self.events = []
47 self.rng = random.Random(name)
48
49 def emit(self, text, dt=0.0):
50 self.t += dt
51 self.events.append([round(self.t, 3), "o", text])
52
53 def prompt(self, who):
54 if who:
55 return f"{rgb(AGENT[who])}[{who}]{RESET} {rgb(MUTED)}${RESET} "
56 return f"{rgb(MUTED)}${RESET} "
57
58 def note(self, text):
59 self.emit(rgb(MUTED) + "# ", 0.5)
60 for ch in text:
61 self.emit(ch, 0.014 + self.rng.random() * 0.012)
62 self.emit(RESET + "\r\n", 0.25)
63
64 def quiet(self, cmd, who=None, cwd=None):
65 """Runs a command off camera."""
66 env = dict(self.env)
67 if who:
68 env["BRAID_AGENT"] = who
69 res = subprocess.run(
70 ["bash", "-c", cmd],
71 cwd=os.path.join(self.root, cwd or self.cwd),
72 env=env,
73 stdout=subprocess.PIPE,
74 stderr=subprocess.STDOUT,
75 )
76 return res.returncode, res.stdout.decode()
77
78 def run(self, cmd, who=None, cwd=None, hold=None):
79 """Types a command, runs it and shows what it printed."""
80 self.emit(self.prompt(who), 0.45)
81 for ch in cmd:
82 self.emit(ch, 0.02 + self.rng.random() * 0.028)
83 self.emit("\r\n", 0.35)
84 code, out = self.quiet(cmd, who, cwd)
85 lines = out.replace(self.root, "~/demo").splitlines()
86 for line in lines:
87 self.emit(line + "\r\n", 0.035)
88 if code != 0:
89 self.emit(f"{rgb(PINK)}exit status {code}{RESET}\r\n", 0.1)
90 self.emit("", hold if hold is not None else 0.9 + 0.12 * len(lines))
91 return code, out
92
93 def save(self):
94 self.emit("", 2.5)
95 text = "".join(event[2] for event in self.events)
96 user = os.environ.get("USER")
97 for leak in (os.path.expanduser("~"), WORK, f"/{user}/" if user else None):
98 if leak and leak in text:
99 sys.exit(f"{self.name}: the recording contains {leak!r}")
100 header = {"version": 2, "width": WIDTH, "height": HEIGHT,
101 "env": {"TERM": "xterm-256color", "SHELL": "/bin/bash"}}
102 path = os.path.join(OUT, self.name + ".cast")
103 with open(path, "w") as f:
104 f.write(json.dumps(header) + "\n")
105 for event in self.events:
106 f.write(json.dumps(event) + "\n")
107 print("recorded", self.name)
108
109
110def check(result, want, what):
111 code, out = result
112 if code != want:
113 sys.exit(f"{what}: exit status {code}, expected {want}\n{out}")
114
115
116def directory(name):
117 """A fresh directory with its own HOME and no git or braid configuration."""
118 root = os.path.join(WORK, name)
119 home = os.path.join(root, "home")
120 bin_dir = os.path.join(root, "bin")
121 os.makedirs(home)
122 os.makedirs(bin_dir)
123 os.symlink(BRAID, os.path.join(bin_dir, "braid"))
124 env = {
125 "PATH": bin_dir + os.pathsep + os.environ["PATH"],
126 "HOME": home,
127 "TZ": "UTC",
128 "GIT_CONFIG_GLOBAL": os.devnull,
129 "GIT_CONFIG_NOSYSTEM": "1",
130 "BRAID_AUTHOR": "Ada Lovelace <ada@example.org>",
131 }
132 return root, env
133
134
135def seed(scene):
136 """A small git project in a bare repository that plays GitHub."""
137 check(scene.quiet(
138 f"""set -e
139 mkdir seed && cd seed && {GIT} init -q
140 printf '# shop\\n\\nA tiny shop.\\n' > README.md
141 printf 'free_over = 60\\n' > shipping.toml
142 {GIT} add README.md shipping.toml
143 GIT_AUTHOR_DATE=2026-10-14T10:00:00Z GIT_COMMITTER_DATE=2026-10-14T10:00:00Z {GIT} commit -q -m 'Start the shop'
144 printf '# shop\\n\\nA tiny shop.\\n\\nShipping rules live in shipping.toml.\\n' > README.md
145 GIT_AUTHOR_DATE=2026-10-15T09:00:00Z GIT_COMMITTER_DATE=2026-10-15T09:00:00Z {GIT} commit -q -am 'Say where shipping rules live'
146 cd .. && {GIT} clone -q --bare seed github.git && rm -rf seed"""), 0, "seed")
147
148
149def agents_and_conflict():
150 root, env = directory("agents")
151 a = Scene("agents", root, env)
152 seed(a)
153 check(a.quiet("braid init shop && cd shop && braid git sync ../github.git"), 0, "setup")
154 a.cwd = "shop"
155 a.note("one repository, three agents: each gets a workspace of its own")
156 check(a.run("for a in a b c; do braid workspace add agent-$a; done"), 0, "workspaces")
157 a.note("they edit and commit at the same time: no shared index, no lock")
158 check(a.run("echo 'free_over = 50' > shipping.toml && braid commit -m 'Free shipping from 50'",
159 who="agent-a", cwd="shop/.braid/work/agent-a"), 0, "commit a")
160 check(a.run("echo 'Ships in a day.' >> README.md && braid commit -m 'Next-day shipping'",
161 who="agent-b", cwd="shop/.braid/work/agent-b"), 0, "commit b")
162 check(a.run("echo 'free_over = 40' > shipping.toml && braid commit -m 'Free shipping from 40'",
163 who="agent-c", cwd="shop/.braid/work/agent-c"), 0, "commit c")
164 a.note("landing on main is one short step that they take in turn")
165 check(a.run("braid land", who="agent-a", cwd="shop/.braid/work/agent-a"), 0, "land a")
166 check(a.run("braid land", who="agent-b", cwd="shop/.braid/work/agent-b"), 0, "land b")
167 check(a.run("braid land", who="agent-c", cwd="shop/.braid/work/agent-c", hold=3.0), 2, "land c")
168 a.save()
169
170 # The same repository, picked up where the first recording stops.
171 b = Scene("conflict", root, env, cwd="shop/.braid/work/agent-c")
172 b.note("agent-c changed the line agent-a landed first: main did not move")
173 b.note("the conflict comes back as data, with all three sides")
174 check(b.run("braid land --json | jq '.outcome, .next, (.conflicts[0].hunks[0] | map_values(.text))'",
175 who="agent-c"), 0, "land json")
176 b.note("update brings it into the working copy, with conflict markers")
177 check(b.run("braid update", who="agent-c"), 2, "update")
178 check(b.run("cat shipping.toml", who="agent-c"), 0, "cat")
179 b.note("settle it, commit, land")
180 check(b.run("echo 'free_over = 45' > shipping.toml", who="agent-c", hold=0.4), 0, "fix")
181 check(b.run("braid commit -m 'Free shipping from 45' && braid land", who="agent-c"), 0, "resolve")
182 check(b.run("braid log main -n 5", cwd="shop", hold=3.5), 0, "log")
183 b.save()
184
185
186def git_sync():
187 root, env = directory("sync")
188 s = Scene("git-sync", root, env)
189 seed(s)
190 s.note("github.git plays GitHub: a git repository with some history")
191 check(s.run("git -C github.git log --oneline"), 0, "git log")
192 s.note("braid takes a branch of it, history and all")
193 check(s.run("braid init shop"), 0, "init")
194 s.cwd = "shop"
195 check(s.run("braid git sync ../github.git"), 0, "first sync")
196 # Off camera: two agents land work in braid, and a person pushes to GitHub.
197 for who, edit, message in (
198 ("agent-a", "echo 'free_over = 50' > shipping.toml", "Free shipping from 50"),
199 ("agent-b", "echo 'Ships in a day.' >> README.md", "Next-day shipping"),
200 ):
201 check(s.quiet(f"braid workspace add {who}"), 0, "workspace")
202 check(s.quiet(f"{edit} && braid commit -m '{message}' && braid land",
203 who=who, cwd=f"shop/.braid/work/{who}"), 0, message)
204 check(s.quiet(
205 f"""set -e
206 {GIT} clone -q github.git laptop && cd laptop
207 printf 'vat = 21\\n' > prices.toml && {GIT} add prices.toml
208 {GIT} -c user.name='Grace Hopper' -c user.email=grace@example.org commit -q -m 'Add VAT'
209 {GIT} push -q origin main && cd .. && rm -rf laptop""", cwd="."), 0, "outside push")
210 s.note("meanwhile agents landed two changes, and a person pushed to GitHub")
211 check(s.run("braid log main -n 4"), 0, "log")
212 check(s.run("braid git sync ../github.git"), 0, "sync")
213 s.note("a fast-forward push with a lease: the old commits keep their ids")
214 check(s.run("git -C ../github.git log --oneline --graph", hold=4.0), 0, "graph")
215 s.save()
216
217
218def agents_init():
219 root, env = directory("setup")
220 s = Scene("agents-init", root, env)
221 seed(s)
222 check(s.quiet(f"{GIT} clone -q github.git shop"), 0, "clone")
223 s.cwd = "shop"
224 s.note("what setting braid up comes down to, in a project's git checkout")
225 s.note("(braid.elffuss.com/agents.md gives an agent the full steps)")
226 check(s.run("braid init"), 0, "init")
227 check(s.run("echo .braid >> .git/info/exclude", hold=0.4), 0, "exclude")
228 check(s.run("braid git import ."), 0, "import")
229 check(s.run("braid agents init"), 0, "agents init")
230 check(s.run("git status --short"), 0, "status")
231 s.note("the rules every later agent session reads, in the project's AGENTS.md")
232 check(s.run("grep '^- [*][*]' AGENTS.md | cut -c1-76", hold=4.0), 0, "rules")
233 s.note("a new session starts in a workspace of its own")
234 check(s.run("braid workspace add agent-1 --track main", hold=3.5), 0, "workspace")
235 s.save()
236
237
238def main():
239 os.makedirs(WORK)
240 os.makedirs(OUT, exist_ok=True)
241 agents_and_conflict()
242 git_sync()
243 agents_init()
244
245
246main()