silcrow 0.2.1

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
451
452
453
454
455
456
457
458
459
460
461
462
463
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use crate::parse::{PointerKind, Scan, Target};
use crate::walk;

pub struct MarkerCounts {
    pub code: usize,
    pub doc: usize,
}

pub struct LawMeta {
    pub declared_on: Option<String>,
    pub age: Option<String>,
    pub markers: MarkerCounts,
    pub remints: usize,
    pub accepts: usize,
    pub repins: usize,
    pub past_paths: usize,
}

/// The metadata of one law, with its history counts when `full`.
pub fn for_id(root: &Path, scan: &Scan, id: &str, full: bool) -> LawMeta {
    // § c5watr20f.a@z735g
    let mut meta = for_ids(root, scan, &[id])
        .remove(id)
        .expect("for_ids holds every id it is asked for");
    if full {
        (meta.remints, meta.accepts, meta.repins) = crate::log::rewrite_counts(root, id)
            .map(|r| (r.remints, r.accepts, r.repins.len()))
            .unwrap_or((0, 0, 0));
        meta.past_paths = past_marker_paths(root, id);
    }
    meta
}

/// The metadata of each of `ids`, without the history counts, from one scan and one walk of
/// the history.
pub fn for_ids(root: &Path, scan: &Scan, ids: &[&str]) -> BTreeMap<String, LawMeta> {
    let mut declared = declared(root, ids);
    let mut markers = current_markers(root, scan);
    ids.iter()
        .map(|id| {
            let (declared_on, age) = declared.remove(*id).unwrap_or_default();
            let markers = markers
                .remove(*id)
                .unwrap_or(MarkerCounts { code: 0, doc: 0 });
            let meta = LawMeta {
                declared_on,
                age,
                markers,
                remints: 0,
                accepts: 0,
                repins: 0,
                past_paths: 0,
            };
            (id.to_string(), meta)
        })
        .collect()
}

/// The date and the age of a commit.
pub type Declared = (Option<String>, Option<String>);

/// The date and age of the earliest commit that adds each id, read in one walk.
pub fn declared(root: &Path, ids: &[&str]) -> BTreeMap<String, Declared> {
    declared_in(ids, || history_patch(root))
}

/// The walk `declared` reads, started on its own thread so it runs beside the caller's work.
pub struct History(std::thread::JoinHandle<Option<String>>);

impl History {
    pub fn start(root: &Path) -> Self {
        let root = root.to_path_buf();
        Self(std::thread::spawn(move || history_patch(&root)))
    }

    pub fn declared(self, ids: &[&str]) -> BTreeMap<String, Declared> {
        declared_in(ids, || {
            self.0
                .join()
                .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
        })
    }
}

fn declared_in(
    ids: &[&str],
    history: impl FnOnce() -> Option<String>,
) -> BTreeMap<String, Declared> {
    // § c5watr20f@hnfj7
    let mut found = BTreeMap::new();
    if ids.is_empty() {
        return found;
    }
    let alternation: Vec<String> = ids.iter().map(|id| regex::escape(id)).collect();
    let re = Regex::new(&alternation.join("|")).expect("id alternation");
    let Some(stdout) = history() else {
        return found;
    };
    let mut head: Declared = (None, None);
    for line in stdout.lines() {
        if let Some(rest) = line.strip_prefix('\u{1}') {
            let (date, age) = rest.split_once('\t').unwrap_or((rest, ""));
            let some = |s: &str| (!s.is_empty()).then(|| s.to_string());
            head = (some(date), some(age));
            continue;
        }
        if !line.starts_with('+') || line.starts_with("+++") {
            continue;
        }
        for m in re.find_iter(line) {
            found
                .entry(m.as_str().to_string())
                .or_insert_with(|| head.clone());
        }
        if found.len() == ids.len() {
            break;
        }
    }
    found
}

/// The age of each draft: the date and age of the earliest commit that adds its head or its
/// item line as the tree writes it, `None` for a line no commit adds. `None` outside git.
pub fn draft_ages(root: &Path, drafts: &[crate::list::Draft]) -> Option<Vec<Option<Declared>>> {
    // § pxmeee9ra.f@z7y0c
    let mut notes: BTreeMap<&Path, String> = BTreeMap::new();
    let lines: Vec<String> = drafts
        .iter()
        .map(|draft| {
            let loc = draft.loc();
            let text = notes.entry(loc.path.as_path()).or_insert_with(|| {
                std::fs::read_to_string(root.join(&loc.path)).unwrap_or_default()
            });
            text.lines()
                .nth(loc.line.saturating_sub(1))
                .unwrap_or_default()
                .trim()
                .to_string()
        })
        .collect();
    let needles: Vec<&str> = lines
        .iter()
        .map(String::as_str)
        .filter(|line| !line.is_empty())
        .collect();
    // Each line maps to the date and the id of the commit that first adds it.
    let walk = || {
        let history = patch_walk(
            root,
            &[
                "--format=%x01%ad%x09%H",
                "--date=short",
                "--",
                "*.md",
                "*.markdown",
                "*.mdx",
            ],
        )
        .ok()?;
        Some(declared_in(&needles, || Some(history)))
    };
    // § faq86xmas.j@ej80z
    let found = match head_commit(root) {
        Some(head) => crate::cache::memo(root, &head, &("draft commits", &needles), walk),
        None => walk(),
    }?;
    let ages = commit_ages(
        root,
        found.values().filter_map(|(_, commit)| commit.as_deref()),
    )?;
    // § end faq86xmas.j
    Some(
        lines
            .iter()
            .map(|line| {
                found.get(line).map(|(date, commit)| {
                    let age = commit.as_ref().and_then(|commit| ages.get(commit));
                    (date.clone(), age.cloned())
                })
            })
            .collect(),
    )
}

/// The commit `HEAD` names in the repository of `root`, none before the first commit or outside
/// git.
fn head_commit(root: &Path) -> Option<String> {
    let out = crate::workspace::git(root)
        .args(["rev-parse", "--verify", "-q", "HEAD"])
        .output()
        .ok()?;
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// The age of each of `commits` as git writes it now, `3 weeks ago`: it moves with the clock, so
/// a run reads it again rather than keep it.
fn commit_ages<'a>(
    root: &Path,
    commits: impl Iterator<Item = &'a str>,
) -> Option<BTreeMap<String, String>> {
    let commits: BTreeSet<&str> = commits.collect();
    if commits.is_empty() {
        return Some(BTreeMap::new());
    }
    let out = crate::workspace::git(root)
        .args(["log", "--no-walk=unsorted", "--format=%H%x09%ar"])
        .args(&commits)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(
        String::from_utf8_lossy(&out.stdout)
            .lines()
            .filter_map(|line| line.split_once('\t'))
            .map(|(commit, age)| (commit.to_string(), age.to_string()))
            .collect(),
    )
}

/// Every commit's patch, oldest first, each opened by its date and age.
fn history_patch(root: &Path) -> Option<String> {
    // No pathspec: the id may first appear bare, or in a file the head has since left.
    patch_walk(root, &["--format=%x01%ad%x09%ar", "--date=short"]).ok()
}

/// The one walk of history every reader of it shares: each commit `args` selects, oldest
/// first, with its patch at no context and no rename.
pub fn patch_walk(root: &Path, args: &[&str]) -> anyhow::Result<String> {
    let out = crate::workspace::git(root)
        .args([
            "-c",
            "core.quotePath=false",
            "log",
            "--reverse",
            "-p",
            "-U0",
            "--no-color",
            "--no-ext-diff",
            "--no-renames",
            "--src-prefix=a/",
            "--dst-prefix=b/",
        ])
        .args(args)
        .output()?;
    if !out.status.success() {
        anyhow::bail!(
            "git log failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// The markers of each id by surface: a file the `docs` list matches, or code the `code` list
/// matches outside Markdown. A marker on neither surface pays no duty and counts in neither.
fn current_markers(root: &Path, scan: &Scan) -> BTreeMap<String, MarkerCounts> {
    // § c5watr20f.a@kqc7k
    let policy = crate::policy::ProjectPolicy::from_root(root)
        .expect("the block parsed when the scan was read");
    let project = crate::walk::Project::at(root).expect("the block parsed when the scan was read");
    let mut out: BTreeMap<String, MarkerCounts> = BTreeMap::new();
    for ptr in &scan.pointers {
        if ptr.kind != PointerKind::Implements {
            continue;
        }
        let Target::Stable { id, .. } = &ptr.target else {
            continue;
        };
        let counts = out
            .entry(id.clone())
            .or_insert(MarkerCounts { code: 0, doc: 0 });
        let path = ptr.loc.path.as_path();
        if project.is_note(path) {
            continue;
        }
        if policy.docs.matches(path) {
            counts.doc += 1;
        } else if policy.code.matches(path) && !crate::marker::is_markdown(path) {
            counts.code += 1;
        }
    }
    out
}

/// The distinct files of the project's own walk whose history ever changed the id.
fn past_marker_paths(root: &Path, id: &str) -> usize {
    let out = crate::workspace::git(root)
        .args([
            "log",
            "-S",
            id,
            "--name-only",
            "--relative",
            "--pretty=format:",
            "--",
            ".",
        ])
        .output();
    let Ok(out) = out else {
        return 0;
    };
    if !out.status.success() {
        return 0;
    }
    let Ok(project) = walk::Project::at(root) else {
        return 0;
    };
    let mut paths = BTreeSet::new();
    for line in String::from_utf8_lossy(&out.stdout).lines() {
        let rel = Path::new(line.trim());
        if rel.as_os_str().is_empty() || project.is_note(rel) || !walk::walks_to(&project, rel) {
            continue;
        }
        paths.insert(rel.to_path_buf());
    }
    paths.len()
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    pub(crate) const NOTE: &str = "notes/decisions/x.md";
    pub(crate) const SENTENCE: &str = "The workload fails closed.";

    /// A git tree whose docs base is `notes`, whose code sits in `lib/`, with a README doc
    /// marker and a nested project that carries a marker of the same id.
    pub(crate) fn notes_tree(root: &Path, id: &str) {
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        let block = "<silcrow notes=\"notes/decisions/**/*.md\" default-branch=\"main\" docs=\"README.md\">\n</silcrow>\n";
        for (path, text) in [
            ("AGENTS.md".to_string(), block.to_string()),
            (
                NOTE.to_string(),
                format!("# X\n\n**§ <a id=\"{id}\">{id}</a> {SENTENCE}**\n"),
            ),
            (
                "lib/a.rs".to_string(),
                format!("fn f() {{\n    // § {id}\n    go();\n}}\n"),
            ),
            (
                "README.md".to_string(),
                format!("# Guide\n\n<!-- § {id} -->\n\nProse.\n"),
            ),
            ("sub/AGENTS.md".to_string(), block.to_string()),
            (
                "sub/lib/b.rs".to_string(),
                format!("fn g() {{\n    // § .:{id}\n    go();\n}}\n"),
            ),
        ] {
            let path = root.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        }
        commit(root, "2026-01-02T12:00:00Z", "declare");
    }

    #[test]
    fn metadata_reads_the_project_walk_and_its_docs_base() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        notes_tree(root, id);
        let scan = crate::parse::scan_root(root).unwrap();
        let meta = for_id(root, &scan, id, true);
        assert_eq!(meta.declared_on.as_deref(), Some("2026-01-02"));
        assert_eq!((meta.markers.code, meta.markers.doc), (1, 1));
        assert_eq!(meta.past_paths, 2);
        let bulk = for_ids(root, &scan, &[id, "abcdefgh2"]);
        assert_eq!(bulk[id].declared_on.as_deref(), Some("2026-01-02"));
        assert_eq!((bulk[id].markers.code, bulk[id].markers.doc), (1, 1));
        assert!(bulk["abcdefgh2"].declared_on.is_none());
    }

    #[test]
    fn a_markdown_marker_counts_as_documentation_only_where_the_docs_list_matches() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        notes_tree(root, id);
        std::fs::write(
            root.join("AGENTS.md"),
            "<silcrow notes=\"notes/decisions/**/*.md\" default-branch=\"main\">\n</silcrow>\n",
        )
        .unwrap();
        let scan = crate::parse::scan_root(root).unwrap();
        let meta = for_ids(root, &scan, &[id]);
        assert_eq!((meta[id].markers.code, meta[id].markers.doc), (1, 0));
    }

    pub(crate) fn commit(dir: &Path, date: &str, msg: &str) {
        for args in [
            vec!["add", "-A"],
            vec!["commit", "-q", "--no-verify", "-m", msg],
        ] {
            let out = crate::test_git()
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(&args)
                .env("GIT_AUTHOR_DATE", date)
                .env("GIT_COMMITTER_DATE", date)
                .current_dir(dir)
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
        }
    }

    #[test]
    fn declaration_is_the_first_commit_naming_the_id_in_any_form_and_any_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        std::fs::create_dir_all(root.join("docs")).unwrap();
        std::fs::write(
            root.join("docs/old.md"),
            format!("§ {id} The workload fails closed.\n"),
        )
        .unwrap();
        commit(root, "2026-01-05T12:00:00Z", "bare form outside the notes");
        std::fs::remove_file(root.join("docs/old.md")).unwrap();
        std::fs::create_dir_all(root.join("docs/decisions")).unwrap();
        std::fs::write(
            root.join("docs/decisions/graph.md"),
            format!("**§ <a id=\"{id}\">{id}</a> The workload fails closed.**\n"),
        )
        .unwrap();
        commit(root, "2026-02-05T12:00:00Z", "anchor wrap in its new note");
        std::fs::write(
            root.join("docs/decisions/other.md"),
            format!("See [{id}](graph.md#{id}).\n"),
        )
        .unwrap();
        commit(root, "2026-03-05T12:00:00Z", "a cite");
        let scan = Scan::default();
        let meta = for_ids(root, &scan, &[id]);
        assert_eq!(meta[id].declared_on.as_deref(), Some("2026-01-05"));
    }
}