Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 23.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The edits agents make: small random changes to a state, kept as
5//! operations so that an agent can redo them on a newer head after a
6//! conflict.
7//!
8//! Paths come from a small set of names, so agents often touch the same files
9//! and directories. Some names differ only in letter case or Unicode
10//! normalisation, and some are used both as file and directory names. Every
11//! line of text is new when it is written, so no line appears twice in a
12//! version of a file and lines never move, which keeps the model's line
13//! merge exact.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use braid_format::tree::MAX_FLAT_ENTRIES;
18
19use crate::model::{Files, Mode, Value, files_below, inside, prefix_lengths};
20use crate::rng::Rng;
21
22/// Directory names.
23const DIRS: &[&str] = &[
24 "src",
25 "docs",
26 "Docs",
27 "lib",
28 "a",
29 "b",
30 "caf\u{e9}",
31 "cafe\u{301}",
32];
33
34/// File names.
35const LEAVES: &[&str] = &[
36 "main.rs",
37 "lib.rs",
38 "README",
39 "readme",
40 "ReadMe",
41 "notes",
42 "x",
43 "y",
44 "a",
45 "b",
46 "caf\u{e9}",
47 "cafe\u{301}",
48 "Makefile",
49];
50
51/// Files that many edits go to.
52const HOT: &[&str] = &["src/main.rs", "docs/README", "notes"];
53
54/// The directory that holds about a thousand files, on either side of the
55/// largest flat directory, in the runs that have it.
56pub const WIDE: &[u8] = b"w";
57
58/// The most entries a directory stored as one flat node has.
59pub const FLAT_LIMIT: usize = MAX_FLAT_ENTRIES;
60
61/// One edit.
62#[derive(Clone, Debug)]
63pub enum Op {
64 /// Sets a file, deleting whatever is in the way: a file at a prefix of
65 /// the path, or the files below it.
66 Write {
67 /// Where.
68 path: Vec<u8>,
69 /// The file.
70 value: Value,
71 },
72 /// Edits lines of a text file.
73 Edit {
74 /// The file.
75 path: Vec<u8>,
76 /// The line edits, in order.
77 edits: Vec<LineEdit>,
78 },
79 /// Deletes a file.
80 Delete {
81 /// The file.
82 path: Vec<u8>,
83 },
84 /// Deletes every file below a directory.
85 DeleteDir {
86 /// The directory.
87 dir: Vec<u8>,
88 },
89 /// Changes the mode of a regular file.
90 SetMode {
91 /// The file.
92 path: Vec<u8>,
93 /// Its new mode.
94 mode: Mode,
95 },
96}
97
98/// One edit of the lines of a text, by line content rather than position, so
99/// that it still means something on another version of the text.
100#[derive(Clone, Debug)]
101pub enum LineEdit {
102 /// Replaces a line.
103 Replace {
104 /// The line replaced.
105 old: Vec<u8>,
106 /// The new line.
107 new: Vec<u8>,
108 },
109 /// Inserts a line after another, or first.
110 Insert {
111 /// The line before it; `None` for the first line.
112 after: Option<Vec<u8>>,
113 /// The new line.
114 new: Vec<u8>,
115 },
116 /// Removes a line.
117 Remove {
118 /// The line removed.
119 old: Vec<u8>,
120 },
121}
122
123/// Applies an edit. An edit that no longer fits the state, such as changing
124/// lines of a file that is gone, does nothing.
125pub fn apply(files: &mut Files, op: &Op) {
126 match op {
127 Op::Write { path, value } => write(files, path, value.clone()),
128 Op::Edit { path, edits } => {
129 if let Some(value) = files.get(path)
130 && value.is_text()
131 {
132 let content = edit_lines(value.content(), edits);
133 if content != value.content() {
134 let edited = Value::new(value.mode(), content);
135 files.insert(path.clone(), edited);
136 }
137 }
138 }
139 Op::Delete { path } => {
140 files.remove(path);
141 }
142 Op::DeleteDir { dir } => {
143 let doomed: Vec<Vec<u8>> = files_below(files, dir).map(|(p, _)| p.clone()).collect();
144 for path in doomed {
145 files.remove(&path);
146 }
147 }
148 Op::SetMode { path, mode } => {
149 if let Some(value) = files.get(path)
150 && value.is_regular()
151 && value.mode() != *mode
152 {
153 let changed = value.with_mode(*mode);
154 files.insert(path.clone(), changed);
155 }
156 }
157 }
158}
159
160/// Sets `path`, after deleting a file at one of its prefixes and the files
161/// below it.
162fn write(files: &mut Files, path: &[u8], value: Value) {
163 for len in prefix_lengths(path) {
164 files.remove(&path[..len]);
165 }
166 let doomed: Vec<Vec<u8>> = files_below(files, path).map(|(p, _)| p.clone()).collect();
167 for below in doomed {
168 files.remove(&below);
169 }
170 files.insert(path.to_vec(), value);
171}
172
173fn split_lines(content: &[u8]) -> Vec<Vec<u8>> {
174 if content.is_empty() {
175 return Vec::new();
176 }
177 content
178 .split_inclusive(|byte| *byte == b'\n')
179 .map(<[u8]>::to_vec)
180 .collect()
181}
182
183/// Applies line edits. A new line already in the text is not added again,
184/// and an edit whose line is gone does nothing.
185fn edit_lines(content: &[u8], edits: &[LineEdit]) -> Vec<u8> {
186 let mut lines = split_lines(content);
187 for edit in edits {
188 match edit {
189 LineEdit::Replace { old, new } => {
190 if !lines.contains(new)
191 && let Some(at) = lines.iter().position(|line| line == old)
192 {
193 lines[at] = new.clone();
194 }
195 }
196 LineEdit::Insert { after, new } => {
197 if !lines.contains(new) {
198 let at = match after {
199 None => 0,
200 Some(after) => lines
201 .iter()
202 .position(|line| line == after)
203 .map_or(lines.len(), |at| at + 1),
204 };
205 lines.insert(at, new.clone());
206 }
207 }
208 LineEdit::Remove { old } => {
209 if let Some(at) = lines.iter().position(|line| line == old) {
210 lines.remove(at);
211 }
212 }
213 }
214 }
215 lines.concat()
216}
217
218/// Makes random edits, with lines and names that are new each time.
219#[derive(Debug, Default)]
220pub struct Generator {
221 fresh: u64,
222}
223
224impl Generator {
225 fn next(&mut self) -> u64 {
226 self.fresh += 1;
227 self.fresh
228 }
229
230 /// A line no text has had before.
231 pub fn line(&mut self) -> Vec<u8> {
232 format!("line {}\n", self.next()).into_bytes()
233 }
234
235 /// `count` new lines.
236 pub fn text(&mut self, count: usize) -> Vec<u8> {
237 (0..count).flat_map(|_| self.line()).collect()
238 }
239
240 fn wide_name(&mut self) -> Vec<u8> {
241 // Long names, so that rewriting the whole directory needs a change
242 // list too long to be inline.
243 let mut path = WIDE.to_vec();
244 path.extend_from_slice(format!("/entry-{:06}-with-a-longer-name", self.next()).as_bytes());
245 path
246 }
247
248 /// The state a run starts from, with a directory of about a thousand
249 /// files if `wide`.
250 pub fn initial(&mut self, rng: &mut Rng, wide: bool) -> Files {
251 let mut files = Files::new();
252 // The files most edits go to are long enough for edits of different
253 // agents to fall apart and merge, or to touch and conflict.
254 let texts: [(&str, usize); 7] = [
255 ("src/main.rs", 30),
256 ("src/lib.rs", 12),
257 ("docs/README", 20),
258 ("notes", 20),
259 ("a/x", 4),
260 ("b/y", 4),
261 ("lib/util.rs", 6),
262 ];
263 for (path, lines) in texts {
264 let value = Value::new(Mode::File, self.text(lines));
265 files.insert(path.as_bytes().to_vec(), value);
266 }
267 files.insert(b"run.sh".to_vec(), Value::new(Mode::Exec, self.text(3)));
268 files.insert(b"link".to_vec(), Value::new(Mode::Link, b"notes".to_vec()));
269 files.insert(
270 b"logo.bin".to_vec(),
271 Value::new(Mode::File, b"\0\x01binary".to_vec()),
272 );
273 if wide {
274 for _ in 0..rng.range(FLAT_LIMIT - 24, FLAT_LIMIT + 25) {
275 let path = self.wide_name();
276 files.insert(path, Value::new(Mode::File, self.line()));
277 }
278 }
279 files
280 }
281
282 /// A random small change to `files`: the edits, and the state they give.
283 pub fn change(&mut self, rng: &mut Rng, files: &Files) -> (Vec<Op>, Files) {
284 let mut state = files.clone();
285 let mut ops = Vec::new();
286 let count = match rng.below(20) {
287 0..=9 => 1,
288 10..=15 => 2,
289 16..=18 => 3,
290 _ => 5,
291 };
292 for _ in 0..count {
293 for op in self.one(rng, &state) {
294 apply(&mut state, &op);
295 ops.push(op);
296 }
297 }
298 (ops, state)
299 }
300
301 /// The same edits with new lines, to redo them on a newer head. A line
302 /// that a later edit refers to is renamed there too.
303 pub fn refresh(&mut self, ops: &[Op]) -> Vec<Op> {
304 let mut renamed: BTreeMap<Vec<u8>, Vec<u8>> = BTreeMap::new();
305 let mut fresh = |line: &Vec<u8>, renamed: &mut BTreeMap<Vec<u8>, Vec<u8>>| {
306 let new = self.line();
307 renamed.insert(line.clone(), new.clone());
308 new
309 };
310 let rename = |line: &Vec<u8>, renamed: &BTreeMap<Vec<u8>, Vec<u8>>| {
311 renamed.get(line).cloned().unwrap_or_else(|| line.clone())
312 };
313 ops.iter()
314 .map(|op| match op {
315 Op::Edit { path, edits } => Op::Edit {
316 path: path.clone(),
317 edits: edits
318 .iter()
319 .map(|edit| match edit {
320 LineEdit::Replace { old, new } => LineEdit::Replace {
321 old: rename(old, &renamed),
322 new: fresh(new, &mut renamed),
323 },
324 LineEdit::Insert { after, new } => LineEdit::Insert {
325 after: after.as_ref().map(|after| rename(after, &renamed)),
326 new: fresh(new, &mut renamed),
327 },
328 LineEdit::Remove { old } => LineEdit::Remove {
329 old: rename(old, &renamed),
330 },
331 })
332 .collect(),
333 },
334 other => other.clone(),
335 })
336 .collect()
337 }
338
339 /// One random edit; several for edits of the wide directory.
340 fn one(&mut self, rng: &mut Rng, files: &Files) -> Vec<Op> {
341 let ordinary: Vec<&Vec<u8>> = files.keys().filter(|path| !inside(WIDE, path)).collect();
342 let pick = |rng: &mut Rng, paths: &[&Vec<u8>]| -> Option<Vec<u8>> {
343 (!paths.is_empty()).then(|| (*rng.pick(paths)).clone())
344 };
345 match rng.below(100) {
346 0..=34 => {
347 let hot: Vec<&Vec<u8>> = ordinary
348 .iter()
349 .copied()
350 .filter(|path| HOT.iter().any(|hot| hot.as_bytes() == path.as_slice()))
351 .filter(|path| files[*path].is_text())
352 .collect();
353 let texts: Vec<&Vec<u8>> = ordinary
354 .iter()
355 .copied()
356 .filter(|path| files[*path].is_text())
357 .collect();
358 let from = if !hot.is_empty() && rng.chance(0.5) {
359 &hot
360 } else {
361 &texts
362 };
363 if let Some(path) = pick(rng, from) {
364 let edits = self.line_edits(rng, &files[&path]);
365 return vec![Op::Edit { path, edits }];
366 }
367 }
368 35..=46 => {}
369 47..=51 => {
370 if let Some(path) = pick(rng, &ordinary) {
371 let value = self.file(rng);
372 return vec![Op::Write { path, value }];
373 }
374 }
375 52..=60 => {
376 if let Some(path) = pick(rng, &ordinary) {
377 return vec![Op::Delete { path }];
378 }
379 }
380 61..=64 => {
381 let dirs = directories(&ordinary);
382 if !dirs.is_empty() {
383 let dir = rng.pick(&dirs).clone();
384 return vec![Op::DeleteDir { dir }];
385 }
386 }
387 65..=69 => {
388 let regular: Vec<&Vec<u8>> = ordinary
389 .iter()
390 .copied()
391 .filter(|path| files[*path].is_regular())
392 .collect();
393 if let Some(path) = pick(rng, &regular) {
394 let mode = match files[&path].mode() {
395 Mode::Exec => Mode::File,
396 _ => Mode::Exec,
397 };
398 return vec![Op::SetMode { path, mode }];
399 }
400 }
401 70..=71 => {
402 let target = format!("target-{}", self.next()).into_bytes();
403 let path = self.path(rng);
404 return vec![Op::Write {
405 path,
406 value: Value::new(Mode::Link, target),
407 }];
408 }
409 72..=76 => {
410 if let Some(path) = pick(rng, &ordinary)
411 && let Some(twin) = self.twin_path(rng, &path)
412 {
413 let value = self.file(rng);
414 return vec![Op::Write { path: twin, value }];
415 }
416 }
417 77..=80 => {
418 // A file where a directory is, or a directory where a file is.
419 let dirs = directories(&ordinary);
420 if !dirs.is_empty() && rng.chance(0.5) {
421 let path = rng.pick(&dirs).clone();
422 let value = self.file(rng);
423 return vec![Op::Write { path, value }];
424 }
425 if let Some(mut path) = pick(rng, &ordinary) {
426 path.push(b'/');
427 path.extend_from_slice(rng.pick(LEAVES).as_bytes());
428 let value = self.file(rng);
429 return vec![Op::Write { path, value }];
430 }
431 }
432 81..=84 => {
433 let ops = self.wide(rng, files);
434 if !ops.is_empty() {
435 return ops;
436 }
437 }
438 85..=97 => {}
439 _ => {
440 let path = self.path(rng);
441 let content = format!("\0binary {}", self.next()).into_bytes();
442 return vec![Op::Write {
443 path,
444 value: Value::new(Mode::File, content),
445 }];
446 }
447 }
448 let path = self.path(rng);
449 let value = self.file(rng);
450 vec![Op::Write { path, value }]
451 }
452
453 /// A random path of one to three names.
454 fn path(&mut self, rng: &mut Rng) -> Vec<u8> {
455 let depth = match rng.below(20) {
456 0..=6 => 1,
457 7..=15 => 2,
458 _ => 3,
459 };
460 let mut names: Vec<Vec<u8>> = (1..depth)
461 .map(|_| rng.pick(DIRS).as_bytes().to_vec())
462 .collect();
463 if rng.chance(0.25) {
464 names.push(format!("f{}", self.next()).into_bytes());
465 } else {
466 names.push(rng.pick(LEAVES).as_bytes().to_vec());
467 }
468 names.join(&b'/')
469 }
470
471 /// A random new file: mostly text, sometimes executable, now and then
472 /// empty.
473 fn file(&mut self, rng: &mut Rng) -> Value {
474 match rng.below(20) {
475 0..=1 => Value::new(Mode::Exec, self.text(rng.range(1, 5))),
476 2 => Value::new(Mode::File, Vec::new()),
477 _ => Value::new(Mode::File, self.text(rng.range(1, 9))),
478 }
479 }
480
481 /// One to three edits of the lines of a text file.
482 fn line_edits(&mut self, rng: &mut Rng, value: &Value) -> Vec<LineEdit> {
483 let mut lines = split_lines(value.content());
484 let mut edits = Vec::new();
485 for _ in 0..rng.range(1, 4) {
486 let edit = if lines.is_empty() {
487 LineEdit::Insert {
488 after: None,
489 new: self.line(),
490 }
491 } else {
492 match rng.below(3) {
493 0 => LineEdit::Replace {
494 old: rng.pick(&lines).clone(),
495 new: self.line(),
496 },
497 1 if rng.chance(0.15) => LineEdit::Insert {
498 after: None,
499 new: self.line(),
500 },
501 1 => LineEdit::Insert {
502 after: Some(rng.pick(&lines).clone()),
503 new: self.line(),
504 },
505 _ => LineEdit::Remove {
506 old: rng.pick(&lines).clone(),
507 },
508 }
509 };
510 lines = split_lines(&edit_lines(&lines.concat(), std::slice::from_ref(&edit)));
511 edits.push(edit);
512 }
513 edits
514 }
515
516 /// A path next to `path` whose name at some level differs from `path`'s
517 /// only in case or normalisation.
518 fn twin_path(&mut self, rng: &mut Rng, path: &[u8]) -> Option<Vec<u8>> {
519 let names: Vec<&[u8]> = path.split(|byte| *byte == b'/').collect();
520 let level = rng.below(names.len());
521 let twin = twin_name(rng, names[level])?;
522 let mut out: Vec<Vec<u8>> = names[..level].iter().map(|name| name.to_vec()).collect();
523 out.push(twin);
524 if level + 1 < names.len() {
525 out.push(rng.pick(LEAVES).as_bytes().to_vec());
526 }
527 Some(out.join(&b'/'))
528 }
529
530 /// Adds or deletes files in the wide directory, mostly toward the other
531 /// side of the flat limit; now and then rewrites all of them.
532 fn wide(&mut self, rng: &mut Rng, files: &Files) -> Vec<Op> {
533 let entries: Vec<Vec<u8>> = files_below(files, WIDE).map(|(p, _)| p.clone()).collect();
534 if entries.is_empty() {
535 return Vec::new();
536 }
537 if rng.chance(0.02) {
538 return entries
539 .into_iter()
540 .map(|path| Op::Write {
541 path,
542 value: Value::new(Mode::File, self.line()),
543 })
544 .collect();
545 }
546 let count = rng.range(1, 41);
547 let add = if entries.len() <= FLAT_LIMIT {
548 rng.chance(0.75)
549 } else {
550 rng.chance(0.25)
551 };
552 if add {
553 return (0..count)
554 .map(|_| Op::Write {
555 path: self.wide_name(),
556 value: Value::new(Mode::File, self.line()),
557 })
558 .collect();
559 }
560 let mut doomed = BTreeSet::new();
561 for _ in 0..count {
562 doomed.insert(rng.pick(&entries).clone());
563 }
564 doomed.into_iter().map(|path| Op::Delete { path }).collect()
565 }
566}
567
568/// The directories that hold the given files.
569fn directories(paths: &[&Vec<u8>]) -> Vec<Vec<u8>> {
570 let dirs: BTreeSet<Vec<u8>> = paths
571 .iter()
572 .flat_map(|path| prefix_lengths(path).map(|len| path[..len].to_vec()))
573 .collect();
574 dirs.into_iter().collect()
575}
576
577/// Another name that folds to the same name: other letter case, or the other
578/// normalisation of `café`.
579fn twin_name(rng: &mut Rng, name: &[u8]) -> Option<Vec<u8>> {
580 let text = std::str::from_utf8(name).ok()?;
581 let mut twins: Vec<String> = Vec::new();
582 match text {
583 "caf\u{e9}" => twins.extend(["cafe\u{301}".to_owned(), "CAF\u{c9}".to_owned()]),
584 "cafe\u{301}" => twins.extend(["caf\u{e9}".to_owned(), "Cafe\u{301}".to_owned()]),
585 _ => {
586 twins.push(text.to_ascii_uppercase());
587 twins.push(text.to_ascii_lowercase());
588 let mut chars = text.chars();
589 if let Some(first) = chars.next() {
590 twins.push(first.to_ascii_uppercase().to_string() + chars.as_str());
591 }
592 }
593 }
594 twins.retain(|twin| twin != text);
595 twins.dedup();
596 (!twins.is_empty()).then(|| rng.pick(&twins).clone().into_bytes())
597}
598
599#[cfg(test)]
600mod tests {
601 use super::*;
602 use crate::model::{fold, merge_text};
603
604 #[test]
605 fn writes_clear_the_way() {
606 let mut files = Files::new();
607 let value = Value::new(Mode::File, b"1\n".to_vec());
608 apply(
609 &mut files,
610 &Op::Write {
611 path: b"a/b".to_vec(),
612 value: value.clone(),
613 },
614 );
615 apply(
616 &mut files,
617 &Op::Write {
618 path: b"a/b/c".to_vec(),
619 value: value.clone(),
620 },
621 );
622 assert_eq!(files.keys().collect::<Vec<_>>(), [b"a/b/c"]);
623 apply(
624 &mut files,
625 &Op::Write {
626 path: b"a".to_vec(),
627 value,
628 },
629 );
630 assert_eq!(files.keys().collect::<Vec<_>>(), [b"a"]);
631 }
632
633 #[test]
634 fn line_edits_never_repeat_a_line() {
635 let edits = [
636 LineEdit::Insert {
637 after: None,
638 new: b"x\n".to_vec(),
639 },
640 LineEdit::Insert {
641 after: Some(b"b\n".to_vec()),
642 new: b"x\n".to_vec(),
643 },
644 LineEdit::Replace {
645 old: b"a\n".to_vec(),
646 new: b"b\n".to_vec(),
647 },
648 LineEdit::Remove {
649 old: b"gone\n".to_vec(),
650 },
651 ];
652 assert_eq!(edit_lines(b"a\nb\n", &edits), b"x\na\nb\n");
653 }
654
655 #[test]
656 fn twins_fold_alike() {
657 let mut rng = Rng::new(3);
658 for name in ["README", "caf\u{e9}", "cafe\u{301}", "src", "a"] {
659 let twin = twin_name(&mut rng, name.as_bytes()).unwrap();
660 assert_ne!(twin, name.as_bytes());
661 assert_eq!(fold(&twin), fold(name.as_bytes()), "{name}");
662 }
663 assert_eq!(twin_name(&mut rng, b"123"), None);
664 }
665
666 #[test]
667 fn random_changes_keep_lines_unique_and_in_order() {
668 let mut rng = Rng::new(11);
669 let mut generator = Generator::default();
670 let start = generator.initial(&mut rng, false);
671 let mut state = start.clone();
672 for _ in 0..300 {
673 let (ops, next) = generator.change(&mut rng, &state);
674 // A redo on the old state, with new lines, is just as valid.
675 let mut redone = state.clone();
676 for op in &generator.refresh(&ops) {
677 apply(&mut redone, op);
678 }
679 for version in [&next, &redone] {
680 for (path, value) in version {
681 if let Some(before) = start.get(path)
682 && before.is_text()
683 && value.is_text()
684 {
685 // A third version that differs from both, so that
686 // the merge has to diff them.
687 let other = [before.content(), b"unrelated\n"].concat();
688 merge_text(before.content(), value.content(), &other).unwrap();
689 }
690 }
691 }
692 state = next;
693 }
694 }
695}