evolving 0.0.1

git for decisions — an immutable, content-addressed ledger of human-authored decisions that resurfaces when a bound check goes red
Documentation
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! `ev decide` — walk the trailing args left-to-right into a draft, validate, append a child.
use crate::canonical::compute_id;
use crate::store::Store;
use crate::tick::{Check, Ground, Tick};
use std::path::Path;
use std::process::Command;

#[derive(Default)]
struct DraftGround {
    claim: String,
    supports: String, // "chosen" | "rejected:<opt>"
    revisit: Option<String>,
    test_ref: Option<String>,
    counter_test: Option<String>,
    platforms: Vec<String>,
    triggered_by: Vec<String>,
    surfaces: Vec<String>,
}

fn need(args: &[String], i: usize, flag: &str) -> Result<String, String> {
    args.get(i + 1)
        .cloned()
        .ok_or(format!("{flag} requires a value"))
}

fn last<'a>(g: &'a mut [DraftGround], flag: &str) -> Result<&'a mut DraftGround, String> {
    g.last_mut()
        .ok_or(format!("{flag} has no preceding --assume/--reject ground"))
}

/// Resolve the declared author: --blame, else `git config user.name`.
pub(crate) fn resolve_blame(repo: &Path, blame_override: Option<String>) -> Result<String, String> {
    if let Some(b) = blame_override {
        let b = b.trim();
        if b.is_empty() {
            return Err("--blame must be non-empty".into());
        }
        return Ok(b.to_string());
    }
    let out = Command::new("git")
        .arg("config")
        .arg("user.name")
        .current_dir(repo)
        .output()
        .map_err(|e| format!("cannot run git: {e}"))?;
    let name = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if name.is_empty() {
        return Err("no author: pass --blame, or set git config user.name".into());
    }
    Ok(name)
}

pub(crate) fn resolve_sha(repo: &Path, sha_override: &Option<String>) -> Result<String, String> {
    let sha = match sha_override {
        Some(s) => s.trim().to_string(),
        None => {
            let out = std::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(repo)
                .output()
                .map_err(|e| format!("cannot run git: {e}"))?;
            if !out.status.success() {
                return Err(
                    "cannot resolve verified_at_sha (not a git repo?) — pass --verified-at-sha"
                        .into(),
                );
            }
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        }
    };
    let ok = sha.len() == 40
        && sha
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
    if !ok {
        return Err(format!("verified_at_sha must be 40 lowercase hex: {sha}"));
    }
    Ok(sha)
}

fn t_grounds_text(grounds: &[Ground]) -> Vec<String> {
    grounds.iter().map(|g| g.claim.clone()).collect()
}

fn build_ground(
    repo: &Path,
    d: DraftGround,
    sha_override: &Option<String>,
) -> Result<Ground, String> {
    use crate::tick::Liveness;
    if d.claim.is_empty() {
        return Err("ground claim is empty".into());
    }
    if d.supports.starts_with("rejected:") && (d.test_ref.is_some() || d.revisit.is_some()) {
        return Err("a road-not-taken (rejected) ground cannot carry a check in 0.1.0 — reserved for a future rejection-rationale liveness feature".into());
    }
    if d.revisit.is_some() && d.test_ref.is_some() {
        return Err("a ground cannot be both --revisit and --assume-test (R2)".into());
    }
    let has_test_fields = d.counter_test.is_some()
        || !d.platforms.is_empty()
        || !d.triggered_by.is_empty()
        || !d.surfaces.is_empty();
    let check = match (d.test_ref, d.revisit) {
        (Some(reference), _) => {
            let counter_test = d
                .counter_test
                .ok_or("a test binding requires --counter-test (no vacuous binding)".to_string())?;
            if d.platforms.is_empty() || d.triggered_by.is_empty() || d.surfaces.is_empty() {
                return Err("a test binding requires at least one --on-platform, --triggered-by, and --surface".into());
            }
            let verified_at_sha = resolve_sha(repo, sha_override)?;
            Some(Check::Test {
                reference,
                verified_at_sha,
                counter_test,
                liveness: Liveness {
                    platforms: d.platforms,
                    triggered_by: d.triggered_by,
                    surfaces: d.surfaces,
                },
            })
        }
        (None, Some(when)) => {
            if has_test_fields {
                return Err(
                    "--counter-test/--on-platform/--triggered-by/--surface require --assume-test"
                        .into(),
                );
            }
            Some(Check::Person { reference: when })
        }
        (None, None) => {
            if has_test_fields {
                return Err(
                    "--counter-test/--on-platform/--triggered-by/--surface require --assume-test"
                        .into(),
                );
            }
            None
        }
    };
    Ok(Ground {
        claim: d.claim,
        supports: d.supports,
        check,
    })
}

pub fn run(repo: &Path, decision: &str, args: &[String]) -> Result<Tick, String> {
    if decision.trim().is_empty() {
        return Err("decision text is empty".into());
    }
    let mut observe = String::new();
    let mut blame_override: Option<String> = None;
    let mut sha_override: Option<String> = None;
    let mut drafts: Vec<DraftGround> = Vec::new();
    let mut i = 0;
    while i < args.len() {
        let flag = args[i].clone();
        match flag.as_str() {
            "--observe" => {
                observe = need(args, i, &flag)?;
            }
            "--blame" => {
                blame_override = Some(need(args, i, &flag)?);
            }
            "--verified-at-sha" => {
                sha_override = Some(need(args, i, &flag)?);
            }
            "--reject" => {
                let v = need(args, i, &flag)?;
                let (opt, why) = v
                    .split_once(':')
                    .ok_or("--reject expects \"<option>: <why>\"".to_string())?;
                let (opt, why) = (opt.trim(), why.trim());
                if opt.is_empty() || why.is_empty() {
                    return Err("--reject needs non-empty <option> and <why>".into());
                }
                drafts.push(DraftGround {
                    claim: why.into(),
                    supports: format!("rejected:{opt}"),
                    ..Default::default()
                });
            }
            "--assume" => {
                let claim = need(args, i, &flag)?;
                drafts.push(DraftGround {
                    claim,
                    supports: "chosen".into(),
                    ..Default::default()
                });
            }
            "--revisit" => {
                last(&mut drafts, &flag)?.revisit = Some(need(args, i, &flag)?);
            }
            "--assume-test" => {
                last(&mut drafts, &flag)?.test_ref = Some(need(args, i, &flag)?);
            }
            "--counter-test" => {
                last(&mut drafts, &flag)?.counter_test = Some(need(args, i, &flag)?);
            }
            "--on-platform" => {
                let v = need(args, i, &flag)?;
                last(&mut drafts, &flag)?.platforms.push(v);
            }
            "--triggered-by" => {
                let v = need(args, i, &flag)?;
                last(&mut drafts, &flag)?.triggered_by.push(v);
            }
            "--surface" => {
                let v = need(args, i, &flag)?;
                last(&mut drafts, &flag)?.surfaces.push(v);
            }
            other => return Err(format!("decide: unknown flag {other}")),
        }
        i += 2;
    }
    let blame = resolve_blame(repo, blame_override)?;
    let mut grounds = Vec::new();
    for d in drafts {
        grounds.push(build_ground(repo, d, &sha_override)?);
    }
    for field in std::iter::once(decision.to_string())
        .chain(std::iter::once(observe.clone()))
        .chain(t_grounds_text(&grounds))
    {
        for verb in crate::lint::r3_self_evolve(&field) {
            eprintln!("warning: \"{verb}\" should take a human subject, not the system (best-effort lint; a re-wording evades it)");
        }
    }
    let store = Store::at(repo);
    if !store.exists() {
        return Err("no .evolving/ store here — run `ev init` first".into());
    }
    let parent_id = store
        .read_head()
        .map_err(|e| format!("reading HEAD: {e}"))?;
    let mut t = Tick {
        id: String::new(),
        parent_id,
        observe,
        decision: decision.to_string(),
        grounds,
        status: "live".into(),
        held_since: String::new(),
        blame,
    };
    t.id = compute_id(&t);
    store
        .write_tick(&t)
        .map_err(|e| format!("writing tick: {e}"))?;
    Ok(t)
}

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

    fn repo() -> std::path::PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let p = std::env::temp_dir().join(format!(
            "ev-capture-{}-{}",
            std::process::id(),
            N.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).unwrap();
        Store::at(&p).init().unwrap();
        p
    }
    fn s(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| x.to_string()).collect()
    }

    #[test]
    fn decide_should_record_a_chosen_a_revisit_and_a_rejected_road_when_all_are_passed() {
        // given: a store and decide args with a chosen+revisit ground and a rejected road
        let r = repo();

        // when: the decision is captured
        let t = run(
            &r,
            "build our own retrieval; reject pgvector",
            &s(&[
                "--observe",
                "evaluating backend",
                "--assume",
                "team has bandwidth long-term",
                "--revisit",
                "Q3 review",
                "--reject",
                "pgvector: would lock our schema",
                "--blame",
                "Wang Yu",
            ]),
        )
        .expect("ok");

        // then: both grounds, the person check, the rejected support, blame, and HEAD all hold
        assert_eq!(t.grounds.len(), 2);
        assert!(matches!(t.grounds[0].check, Some(Check::Person { .. })));
        assert_eq!(t.grounds[1].supports, "rejected:pgvector");
        assert_eq!(t.blame, "Wang Yu");
        assert_eq!(Store::at(&r).read_head().unwrap(), t.id);
    }

    #[test]
    fn decide_should_store_a_trimmed_blame_when_the_blame_is_padded() {
        // given: a store and decide args with a padded --blame
        let r = repo();

        // when: the decision is captured
        let t = run(&r, "d", &s(&["--assume", "c", "--blame", "  Wang Yu  "])).expect("ok");

        // then: the stored blame is trimmed
        assert_eq!(t.blame, "Wang Yu");
    }

    #[test]
    fn decide_should_refuse_the_ground_when_it_is_both_revisit_and_assume_test() {
        // given: a store and decide args binding one ground to both --revisit and --assume-test
        let r = repo();

        // when: the decision is captured
        let e = run(
            &r,
            "d",
            &s(&[
                "--assume",
                "c",
                "--revisit",
                "Q3",
                "--assume-test",
                "pytest x",
                "--blame",
                "Wang Yu",
            ]),
        );

        // then: it is refused
        assert!(e.is_err());
    }

    #[test]
    fn decide_should_refuse_a_check_when_the_ground_is_a_rejected_road() {
        // given: a store and decide args attaching an --assume-test to a --reject road
        let r = repo();

        // when: the decision is captured
        let e = run(
            &r,
            "d",
            &s(&[
                "--reject",
                "pgvector: would lock our schema",
                "--assume-test",
                "pytest x",
                "--counter-test",
                "ct",
                "--on-platform",
                "linux-ci",
                "--triggered-by",
                "f",
                "--surface",
                "s",
                "--verified-at-sha",
                "d308afac1b2c3d4e5f60718293a4b5c6d7e8f901",
                "--blame",
                "Wang Yu",
            ]),
        );

        // then: it is refused
        assert!(e.is_err());
    }

    #[test]
    fn decide_should_error_when_there_is_no_store() {
        // given: a directory with no .evolving/ store
        let p = std::env::temp_dir().join(format!("ev-nostore-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).unwrap();

        // when: a decision is captured there
        let e = run(&p, "d", &s(&["--blame", "x"]));

        // then: it errors
        assert!(e.is_err());
    }

    #[test]
    fn decide_should_build_a_self_verifying_test_binding_when_all_test_fields_are_present() {
        // given: a store and decide args with a fully specified test binding plus a rejected road
        let r = repo();

        // when: the decision is captured
        let t = run(
            &r,
            "restore-safety counter DB-backed; reject Redis",
            &s(&[
                "--assume",
                "Argus introduces no Redis; multi-pod coord via existing DB",
                "--assume-test",
                "pytest tests/test_redis_absent.py",
                "--counter-test",
                "pytest tests/test_redis_absent.py::test_redis_injection_flips_red",
                "--on-platform",
                "linux-ci",
                "--triggered-by",
                "pyproject.toml",
                "--surface",
                "pyproject-deps",
                "--verified-at-sha",
                "d308afac1b2c3d4e5f60718293a4b5c6d7e8f901",
                "--reject",
                "Redis: a new infra dependency",
                "--blame",
                "Wang Yu",
            ]),
        )
        .expect("ok");

        // then: the first ground carries a fully populated test check
        match &t.grounds[0].check {
            Some(Check::Test {
                reference,
                counter_test,
                liveness,
                verified_at_sha,
            }) => {
                assert_eq!(reference, "pytest tests/test_redis_absent.py");
                assert!(counter_test.contains("flips_red"));
                assert_eq!(liveness.platforms, vec!["linux-ci".to_string()]);
                assert_eq!(verified_at_sha.len(), 40);
            }
            _ => panic!("expected a test check"),
        }
    }

    #[test]
    fn decide_should_reject_a_test_binding_when_there_is_no_counter_test() {
        // given: a store and a test binding missing --counter-test
        let r = repo();

        // when: the decision is captured
        let e = run(
            &r,
            "d",
            &s(&[
                "--assume",
                "c",
                "--assume-test",
                "pytest x",
                "--on-platform",
                "linux-ci",
                "--triggered-by",
                "f",
                "--surface",
                "s",
                "--verified-at-sha",
                "d308afac1b2c3d4e5f60718293a4b5c6d7e8f901",
                "--blame",
                "Wang Yu",
            ]),
        );

        // then: it is rejected
        assert!(e.is_err());
    }

    #[test]
    fn decide_should_reject_a_test_binding_when_there_is_no_verified_at_sha_and_no_git() {
        // given: a store and a test binding with no --verified-at-sha in a non-git dir
        let r = repo();

        // when: the decision is captured
        let e = run(
            &r,
            "d",
            &s(&[
                "--assume",
                "c",
                "--assume-test",
                "pytest x",
                "--counter-test",
                "ct",
                "--on-platform",
                "linux-ci",
                "--triggered-by",
                "f",
                "--surface",
                "s",
                "--blame",
                "Wang Yu",
            ]),
        );

        // then: it is rejected
        assert!(e.is_err());
    }

    #[test]
    fn decide_should_take_blame_from_git_config_when_no_blame_flag_is_given() {
        // given: a store inside a git repo with a configured author, and no --blame
        let r = repo();
        for a in [
            ["init"].as_slice(),
            ["config", "user.name", "Ada Lovelace"].as_slice(),
        ] {
            std::process::Command::new("git")
                .args(a)
                .current_dir(&r)
                .output()
                .unwrap();
        }

        // when: a decision is captured without --blame
        let t = run(&r, "d", &s(&["--assume", "c"])).expect("ok");

        // then: blame is resolved from git config user.name
        assert_eq!(t.blame, "Ada Lovelace");
    }
}