silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use anyhow::{Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use crate::model::Law;
use crate::parse::{self, Scan};
use crate::walk;
use crate::workspace::Workspace;

#[derive(Debug, Default)]
pub struct MergeReport {
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

pub fn parent_conflicts(ws: &Workspace) -> Result<MergeReport> {
    // § dveb6b5vj@xwsq3
    let root = ws.root.as_path();
    let parents = head_parents(root)?;
    if parents.len() < 2 {
        return Ok(MergeReport::default());
    }
    let base = git_stdout(root, &["merge-base", &parents[0], &parents[1]])?;
    if base.is_empty() {
        return Ok(MergeReport::default());
    }

    let left_changed = files_changed(root, &base, &parents[0])?;
    let right_changed = files_changed(root, &base, &parents[1])?;
    let mut touched = left_changed.clone();
    touched.retain(|path| right_changed.contains(path));
    touched.retain(|rel| is_decision(ws, rel));

    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    // § dveb6b5vj.a@j6q67
    let left_laws = changed_law_ids(ws, &base, &parents[0], &left_changed)?;
    let right_laws = changed_law_ids(ws, &base, &parents[1], &right_changed)?;
    let left_markers = changed_marker_ids(ws, &base, &parents[0], &left_changed)?;
    let right_markers = changed_marker_ids(ws, &base, &parents[1], &right_changed)?;
    for key in cross_file_collisions(&left_laws, &left_markers, &right_laws, &right_markers) {
        let id = key.strip_prefix(".:").unwrap_or(&key);
        errors.push(format!(
            "semantic collision: § {id}: one parent changed the law, the other changed a marker"
        ));
    }
    // § end dveb6b5vj.a
    for rel in touched {
        let merged = scan_worktree(root, &rel);
        let left = scan_at_rev(root, &parents[0], &rel);
        let right = scan_at_rev(root, &parents[1], &rel);
        let mut ids = BTreeSet::new();
        for scan in [&merged, &left, &right] {
            for law in &scan.laws {
                ids.insert(law.id.clone());
            }
        }
        for id in ids {
            let fm = law_map(&merged).get(&id).cloned();
            let fl = law_map(&left).get(&id).cloned();
            let fr = law_map(&right).get(&id).cloned();
            match (fl, fr) {
                (Some(l), Some(r)) if l != r => {
                    if let Some(m) = fm {
                        if m != l && m != r {
                            errors.push(format!(
                                "semantic collision: § {id} in {} merges incompatible parent versions ({} vs {})",
                                rel.display(),
                                short_rev(&parents[0]),
                                short_rev(&parents[1])
                            ));
                        } else {
                            warnings.push(format!(
                                "merge: § {id} in {} differs between parents; merged tree matches {}, verify markers",
                                rel.display(),
                                if m == l { short_rev(&parents[0]) } else { short_rev(&parents[1]) }
                            ));
                        }
                    }
                }
                _ => {}
            }
        }
    }
    Ok(MergeReport { errors, warnings })
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct LawSnapshot {
    carrying: String,
    clauses: BTreeMap<String, String>,
}

impl LawSnapshot {
    fn from_law(law: &Law) -> Self {
        let mut clauses = BTreeMap::new();
        for al in &law.clauses {
            if al.struck {
                continue;
            }
            if let Some(letter) = &al.letter {
                clauses.insert(letter.clone(), al.text.clone());
            }
        }
        Self {
            carrying: law.name.clone(),
            clauses,
        }
    }
}

/// Law keys `<projectpath>:<id>`, the project being the one whose note changed.
fn changed_law_ids(
    ws: &Workspace,
    base: &str,
    rev: &str,
    changed: &BTreeSet<PathBuf>,
) -> Result<BTreeSet<String>> {
    // § dveb6b5vj.a@h6mny
    let root = ws.root.as_path();
    let mut ids = BTreeSet::new();
    for rel in changed {
        if !is_decision(ws, rel) {
            continue;
        }
        let project = project_of(ws, rel);
        let before = law_map(&scan_at_rev(root, base, rel));
        let after = law_map(&scan_at_rev(root, rev, rel));
        let mut keys: BTreeSet<_> = before.keys().cloned().collect();
        keys.extend(after.keys().cloned());
        for id in keys {
            if before.get(&id) != after.get(&id) {
                ids.insert(format!("{project}:{id}"));
            }
        }
    }
    Ok(ids)
}

/// Marker keys `<projectpath>:<id>`: the qualifier, or else the project the marker sits in.
fn changed_marker_ids(
    ws: &Workspace,
    base: &str,
    rev: &str,
    changed: &BTreeSet<PathBuf>,
) -> Result<BTreeSet<String>> {
    // § dveb6b5vj.a@n9q58
    let root = ws.root.as_path();
    let mut ids = BTreeSet::new();
    for rel in changed {
        if is_decision(ws, rel) {
            continue;
        }
        let project = project_of(ws, rel);
        let before = marker_marks_at(root, base, rel, &project);
        let after = marker_marks_at(root, rev, rel, &project);
        let mut keys: BTreeSet<_> = before.keys().cloned().collect();
        keys.extend(after.keys().cloned());
        for id in keys {
            if before.get(&id) != after.get(&id) {
                ids.insert(id);
            }
        }
    }
    Ok(ids)
}

fn marker_marks_at(
    root: &Path,
    rev: &str,
    rel: &Path,
    project: &str,
) -> BTreeMap<String, Vec<String>> {
    let Some(text) = git_show(root, rev, rel) else {
        return BTreeMap::new();
    };
    marker_marks_in_text(rel, &text, project)
}

/// Each marker of `text` by its project and id: its address and digest, and the first line of
/// code under it. Each marker counts, so a second marker of one address, or a marker moved to
/// other code, changes the marks even when it carries no pin.
fn marker_marks_in_text(rel: &Path, text: &str, project: &str) -> BTreeMap<String, Vec<String>> {
    // § dveb6b5vj@78189
    let lines: Vec<&str> = text.lines().collect();
    let rows = crate::span::marker_rows(rel, text, None);
    let marked: BTreeSet<usize> = rows.iter().map(|row| row.idx).collect();
    let mut by_id: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for row in rows {
        let code = lines[row.idx + 1..]
            .iter()
            .enumerate()
            .find(|(n, l)| !l.trim().is_empty() && !marked.contains(&(row.idx + 1 + n)))
            .map_or("", |(_, l)| l.trim());
        for addr in row.markers {
            let tok = addr
                .digest
                .as_ref()
                .map_or_else(String::new, |d| format!("@{d}"));
            let mark = format!(
                "{}.{}{tok} {code}",
                addr.id,
                addr.letter.as_deref().unwrap_or("")
            );
            let key = format!("{}:{}", addr.project.as_deref().unwrap_or(project), addr.id);
            by_id.entry(key).or_default().push(mark);
        }
    }
    for marks in by_id.values_mut() {
        marks.sort();
    }
    by_id
}

fn cross_file_collisions(
    laws_left: &BTreeSet<String>,
    markers_left: &BTreeSet<String>,
    laws_right: &BTreeSet<String>,
    markers_right: &BTreeSet<String>,
) -> BTreeSet<String> {
    // § dveb6b5vj@sktbg
    let mut out = BTreeSet::new();
    for id in laws_left.intersection(markers_right) {
        out.insert(id.clone());
    }
    for id in laws_right.intersection(markers_left) {
        out.insert(id.clone());
    }
    out
}

fn law_map(scan: &Scan) -> BTreeMap<String, LawSnapshot> {
    scan.laws
        .iter()
        .map(|law| (law.id.clone(), LawSnapshot::from_law(law)))
        .collect()
}

/// The project path of the nearest project above a workspace-relative path.
fn project_of(ws: &Workspace, rel: &Path) -> String {
    ws.enclosing(&ws.root.join(rel))
        .map_or_else(|| ".".to_string(), |project| project.key.clone())
}

fn is_decision(ws: &Workspace, rel: &Path) -> bool {
    let abs = ws.root.join(rel);
    let Some(project) = ws.enclosing(&abs) else {
        return false;
    };
    let Ok(paths) = walk::Project::at(&project.dir) else {
        return false;
    };
    abs.strip_prefix(&project.dir)
        .is_ok_and(|rel| paths.is_note(rel))
}

fn scan_worktree(root: &Path, rel: &Path) -> Scan {
    let path = root.join(rel);
    let Ok(text) = std::fs::read_to_string(&path) else {
        return Scan::default();
    };
    parse::scan_text(rel, &text)
}

fn scan_at_rev(root: &Path, rev: &str, rel: &Path) -> Scan {
    let Some(text) = git_show(root, rev, rel) else {
        return Scan::default();
    };
    parse::scan_text(rel, &text)
}

fn files_changed(root: &Path, base: &str, rev: &str) -> Result<BTreeSet<PathBuf>> {
    let out = git_stdout(root, &["diff", "--name-only", &format!("{base}..{rev}")])?;
    Ok(out
        .lines()
        .filter(|line| !line.is_empty())
        .map(PathBuf::from)
        .collect())
}

fn head_parents(root: &Path) -> Result<Vec<String>> {
    let out = crate::workspace::git(root)
        .args(["rev-parse", "HEAD^@"])
        .output()
        .context("git rev-parse HEAD^@")?;
    if !out.status.success() {
        return Ok(Vec::new());
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .split_whitespace()
        .map(str::to_string)
        .collect())
}

fn short_rev(rev: &str) -> &str {
    rev.get(..7).unwrap_or(rev)
}

fn git_show(root: &Path, rev: &str, rel: &Path) -> Option<String> {
    let spec = format!("{}:{}", rev, rel.to_string_lossy());
    let out = crate::workspace::git(root)
        .args(["show", &spec])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    String::from_utf8(out.stdout).ok()
}

fn git_stdout(root: &Path, args: &[&str]) -> Result<String> {
    let out = crate::workspace::git(root)
        .args(args)
        .output()
        .with_context(|| format!("git {}", args.join(" ")))?;
    if !out.status.success() {
        anyhow::bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr)
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Clause, Location};

    fn law(id: &str, carrying: &str, clauses: &[(&str, &str)]) -> Law {
        Law {
            draft: false,
            body: String::new(),
            end: 1,
            context: String::new(),
            aliases: Vec::new(),
            id: id.into(),
            name: carrying.into(),
            loc: Location {
                path: PathBuf::from("docs/decisions/n.md"),
                line: 1,
            },
            struck: false,
            clauses: clauses
                .iter()
                .map(|(letter, text)| Clause {
                    draft: false,
                    body: String::new(),
                    header: String::new(),
                    end: 1,
                    stable_id: None,
                    letter: Some((*letter).into()),
                    text: (*text).into(),
                    struck: false,
                    loc: Location {
                        path: PathBuf::from("docs/decisions/n.md"),
                        line: 2,
                    },
                })
                .collect(),
            public: false,
        }
    }

    #[test]
    fn snapshots_differ_when_carrying_changes() {
        let a = LawSnapshot::from_law(&law("abcdefgh1", "First.", &[]));
        let b = LawSnapshot::from_law(&law("abcdefgh1", "Second.", &[]));
        assert_ne!(a, b);
    }

    #[test]
    fn snapshots_differ_when_clause_changes() {
        let a = LawSnapshot::from_law(&law("abcdefgh1", "Law.", &[("a", "one")]));
        let b = LawSnapshot::from_law(&law("abcdefgh1", "Law.", &[("a", "two")]));
        assert_ne!(a, b);
    }

    #[test]
    fn cross_file_join_finds_note_versus_marker() {
        let laws_left = BTreeSet::from(["abcdefgh1".into()]);
        let markers_left = BTreeSet::new();
        let laws_right = BTreeSet::new();
        let markers_right = BTreeSet::from(["abcdefgh1".into()]);
        let hits = cross_file_collisions(&laws_left, &markers_left, &laws_right, &markers_right);
        assert!(hits.contains("abcdefgh1"));
    }

    fn marks(text: &str, project: &str) -> BTreeMap<String, Vec<String>> {
        marker_marks_in_text(Path::new("src/a.rs"), text, project)
    }

    #[test]
    fn a_marker_line_inside_a_string_is_code() {
        let text =
            "fn f() {\n    // § abcdefgh1.a\n    let s = r\"\n// § abcdefgh1.a@aaaaa\n\";\n}\n";
        let marks = marks(text, ".");
        assert_eq!(
            marks.get(".:abcdefgh1").map(Vec::as_slice),
            Some(&["abcdefgh1.a let s = r\"".to_string()][..])
        );
    }

    #[test]
    fn a_pin_change_counts_as_a_marker_change() {
        let before = marks("// § abcdefgh1\n", ".");
        let after = marks("// § abcdefgh1@aaaaa\n", ".");
        assert_ne!(before.get(".:abcdefgh1"), after.get(".:abcdefgh1"));
        assert!(before.contains_key(".:abcdefgh1"));
        assert!(after.contains_key(".:abcdefgh1"));
    }

    #[test]
    fn a_second_or_moved_bare_marker_counts_as_a_marker_change() {
        let one = marks(
            "// § abcdefgh1.a\nconst X: u8 = 1;\n\nconst Y: u8 = 2;\n",
            ".",
        );
        let two = marks(
            "// § abcdefgh1.a\nconst X: u8 = 1;\n\n// § abcdefgh1.a\nconst Y: u8 = 2;\n",
            ".",
        );
        let moved = marks(
            "const X: u8 = 1;\n\n// § abcdefgh1.a\nconst Y: u8 = 2;\n",
            ".",
        );
        let shifted = marks("\n// § abcdefgh1.a\nconst X: u8 = 1;\n", ".");
        assert_ne!(one.get(".:abcdefgh1"), two.get(".:abcdefgh1"));
        assert_ne!(one.get(".:abcdefgh1"), moved.get(".:abcdefgh1"));
        assert_eq!(one.get(".:abcdefgh1"), shifted.get(".:abcdefgh1"));
    }

    #[test]
    fn a_qualified_marker_joins_on_its_origin_project() {
        let marks = marks("// § pkg:abcdefgh1\n// § abcdefgh2\n", "app");
        assert!(marks.contains_key("pkg:abcdefgh1"));
        assert!(marks.contains_key("app:abcdefgh2"));
    }

    #[test]
    fn frankenstein_merge_is_detected() {
        let left = LawSnapshot::from_law(&law("abcdefgh1", "Left.", &[("a", "L")]));
        let right = LawSnapshot::from_law(&law("abcdefgh1", "Right.", &[("a", "R")]));
        let merged = LawSnapshot::from_law(&law("abcdefgh1", "Mixed.", &[("a", "X")]));
        assert_ne!(left, right);
        assert_ne!(merged, left);
        assert_ne!(merged, right);
    }
}