evolving 0.1.3

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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! `ev migrate` — multi-source idempotent backfill + reconcile, driven end-to-end against the real
//! binary. Each test writes a source fixture, runs `ev migrate`, and asserts on the printed summary
//! and the on-disk store. The fixtures are minimal, self-contained substrates with no proprietary
//! content.
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

fn ev() -> Command {
    Command::new(env!("CARGO_BIN_EXE_ev"))
}

/// A fresh, initialized ev store in a unique temp dir.
fn repo() -> std::path::PathBuf {
    static N: AtomicU64 = AtomicU64::new(0);
    let p = std::env::temp_dir().join(format!(
        "ev-migrate-{}-{}",
        std::process::id(),
        N.fetch_add(1, Ordering::Relaxed)
    ));
    let _ = std::fs::remove_dir_all(&p);
    std::fs::create_dir_all(&p).unwrap();
    assert!(ev()
        .arg("init")
        .current_dir(&p)
        .output()
        .unwrap()
        .status
        .success());
    p
}

fn run(repo: &std::path::Path, args: &[&str]) -> std::process::Output {
    ev().args(args).current_dir(repo).output().unwrap()
}

/// Write a source fixture file under the repo and return its `<kind>:<path>` source spec.
fn write_source(repo: &std::path::Path, kind: &str, name: &str, body: &str) -> String {
    let path = repo.join(name);
    std::fs::write(&path, body).unwrap();
    format!("{kind}:{}", path.display())
}

/// Write a `--jurisdiction-map` file under the repo and return its path as a string.
fn write_map(repo: &std::path::Path, name: &str, body: &str) -> String {
    let path = repo.join(name);
    std::fs::write(&path, body).unwrap();
    path.display().to_string()
}

/// How many tick files the store holds.
fn tick_count(repo: &std::path::Path) -> usize {
    std::fs::read_dir(repo.join(".evolving/ticks"))
        .unwrap()
        .filter(|e| e.as_ref().unwrap().path().is_file())
        .count()
}

const TWO_ROUNDS: &str = "\
## R2289 restore-safety counter DB-backed
- rejected: Redis: would add a new infra dependency
## R2290 ship the cross-pod drain
";

#[test]
fn migrate_should_skip_every_record_when_run_twice() {
    // given: a store and a 2-record gitlog source, imported once with a --blame fallback
    let r = repo();
    let src = write_source(&r, "gitlog", "chat-room.md", TWO_ROUNDS);
    let first = run(&r, &["migrate", "--source", &src, "--blame", "Wang Yu"]);
    assert!(
        first.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&first.stderr)
    );
    let after_first = tick_count(&r);
    assert_eq!(after_first, 2, "first import writes both records");

    // when: the SAME migrate runs a second time
    let second = run(&r, &["migrate", "--source", &src, "--blame", "Wang Yu"]);

    // then: it succeeds, writes nothing new (idempotent), and reports both records skipped
    assert!(second.status.success());
    assert_eq!(tick_count(&r), after_first, "a re-run writes no new ticks");
    let out = String::from_utf8_lossy(&second.stdout);
    assert!(
        out.contains("imported 0") && out.contains("skipped 2"),
        "summary was {out:?}"
    );
}

#[test]
fn migrate_should_report_the_relinked_count_when_a_record_is_back_dated() {
    // given: a store that already holds the LATER round R2290 as genesis (parent ""), captured
    // before the earlier round was ever migrated.
    let r = repo();
    let later = write_source(
        &r,
        "gitlog",
        "later.md",
        "## R2290 ship the cross-pod drain\n",
    );
    assert!(
        run(&r, &["migrate", "--source", &later, "--blame", "Wang Yu"])
            .status
            .success()
    );

    // when: a source brings BOTH the EARLIER R2289 and the existing R2290 — sorted, R2289 lands
    // first, so R2290 should now sit AFTER it, but its stored parent is still "" (a back-dated
    // mid-chain insert: the chain is being re-linked around the already-present R2290).
    let both = write_source(
        &r,
        "gitlog",
        "both.md",
        "## R2289 restore-safety counter DB-backed\n## R2290 ship the cross-pod drain\n",
    );
    let out = run(&r, &["migrate", "--source", &both, "--blame", "Wang Yu"]);

    // then: it succeeds, imports the new earlier round, and reports the existing one re-linked
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(
        s.contains("imported 1") && s.contains("re-linked 1"),
        "summary was {s:?}"
    );
}

#[test]
fn migrate_reconcile_should_surface_a_source_only_ruling_as_a_gap() {
    // given: a store holding ONLY R2289 (imported), and a source that ALSO declares R9999 — a
    // ruling the source has but the ledger never captured (the capture gap).
    let r = repo();
    let seed = write_source(
        &r,
        "gitlog",
        "seed.md",
        "## R2289 restore-safety counter DB-backed\n",
    );
    assert!(
        run(&r, &["migrate", "--source", &seed, "--blame", "Wang Yu"])
            .status
            .success()
    );
    let against = write_source(
        &r,
        "gitlog",
        "against.md",
        "## R2289 restore-safety counter DB-backed\n## R9999 a ruling never captured\n",
    );

    // when: reconcile joins the source against the store
    let out = run(&r, &["migrate", "--reconcile", "--against", &against]);

    // then: it succeeds and surfaces R2289 as IN-BOTH and R9999 as a SOURCE-ONLY gap
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("in-both 1"), "summary was {s:?}");
    assert!(s.contains("source-only 1"), "summary was {s:?}");
}

#[test]
fn migrate_should_require_a_blame_fallback_when_a_source_lacks_authors() {
    // given: a store and a gitlog source whose records carry NO author, run WITHOUT --blame
    let r = repo();
    let src = write_source(&r, "gitlog", "no-authors.md", TWO_ROUNDS);

    // when: migrate runs with no --blame fallback
    let out = run(&r, &["migrate", "--source", &src]);

    // then: R5 stays intact — no author is fabricated, no tick is written, and the gap is surfaced
    assert!(out.status.success(), "a surfaced gap is not a hard failure");
    assert_eq!(tick_count(&r), 0, "no tick is written without an author");
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(
        s.contains("source-only gap") || s.contains("source-only"),
        "the gap must be surfaced; summary was {s:?}"
    );
}

#[test]
fn migrate_dry_run_should_write_no_tick_when_asked_to_preview() {
    // given: a store and a 2-record source
    let r = repo();
    let src = write_source(&r, "gitlog", "chat-room.md", TWO_ROUNDS);

    // when: migrate runs with --dry-run
    let out = run(
        &r,
        &[
            "migrate",
            "--source",
            &src,
            "--blame",
            "Wang Yu",
            "--dry-run",
        ],
    );

    // then: it reports what WOULD import but writes nothing
    assert!(out.status.success());
    assert_eq!(tick_count(&r), 0, "--dry-run writes no ticks");
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(
        s.contains("imported 2"),
        "preview should count both; was {s:?}"
    );
}

#[test]
fn migrate_bind_check_should_print_a_harvested_check_when_a_selector_is_given() {
    // given: a store
    let r = repo();

    // when: migrate --bind-check harvests a test with full liveness (no counter-test)
    let out = run(
        &r,
        &[
            "migrate",
            "--bind-check",
            "pytest tests/test_invariant_no_redis.py",
            "--on-platform",
            "linux-ci",
            "--triggered-by",
            "pyproject.toml",
            "--surface",
            "pyproject-deps",
            "--verified-at-sha",
            "d308afac1b2c3d4e5f60718293a4b5c6d7e8f901",
        ],
    );

    // then: it succeeds and prints the harvested (counter-test-less) binding honestly
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("harvested"), "output was {s:?}");
    assert!(
        s.contains("pytest tests/test_invariant_no_redis.py"),
        "output was {s:?}"
    );
}

#[test]
fn migrate_should_tag_an_imported_decision_from_the_jurisdiction_map() {
    // given: a store, a 1-record gitlog source (R2289), and a map line tagging R2289 as C
    let r = repo();
    let src = write_source(
        &r,
        "gitlog",
        "chat-room.md",
        "## R2289 restore-safety counter DB-backed\n",
    );
    let map = write_map(&r, "jurisdiction.map", "# round -> bucket\nR2289 C\n");

    // when: migrate imports it WITH the --jurisdiction-map
    let out = run(
        &r,
        &[
            "migrate",
            "--source",
            &src,
            "--blame",
            "Wang Yu",
            "--jurisdiction-map",
            &map,
        ],
    );

    // then: it succeeds and the imported decision carries jurisdiction=C on both list and show
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let list = run(&r, &["list"]);
    let l = String::from_utf8_lossy(&list.stdout);
    assert!(
        l.contains("jurisdiction=C"),
        "list did not render the imported jurisdiction: {l:?}"
    );
    // the id leads the list row — pull it and confirm `show` agrees (the from_value round-trip)
    let id = l
        .lines()
        .find(|line| line.contains("jurisdiction=C"))
        .and_then(|line| line.split('\t').next())
        .expect("a row with the tagged decision");
    let show = run(&r, &["show", id]);
    assert!(
        String::from_utf8_lossy(&show.stdout).contains("jurisdiction: C"),
        "show did not render jurisdiction: {}",
        String::from_utf8_lossy(&show.stdout)
    );
}

#[test]
fn migrate_should_leave_a_decision_untagged_when_its_key_is_absent_from_the_map() {
    // given: a store, a 1-record source (R2290), and a map that names a DIFFERENT key only
    let r = repo();
    let src = write_source(
        &r,
        "gitlog",
        "chat-room.md",
        "## R2290 ship the cross-pod drain\n",
    );
    let map = write_map(&r, "jurisdiction.map", "R9999 C\n");

    // when: migrate imports it with the map (whose only entry does not match R2290)
    let out = run(
        &r,
        &[
            "migrate",
            "--source",
            &src,
            "--blame",
            "Wang Yu",
            "--jurisdiction-map",
            &map,
        ],
    );

    // then: it succeeds and the imported decision is UNTAGGED (purely additive — absent key ⇒ None)
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let list = run(&r, &["list"]);
    assert!(
        !String::from_utf8_lossy(&list.stdout).contains("jurisdiction="),
        "an unmapped key must import untagged: {}",
        String::from_utf8_lossy(&list.stdout)
    );
}

#[test]
fn migrate_should_reject_an_out_of_vocab_bucket_in_the_jurisdiction_map() {
    // given: a store, a source, and a map whose bucket is outside the {A,B,C,D} vocabulary
    let r = repo();
    let src = write_source(
        &r,
        "gitlog",
        "chat-room.md",
        "## R2289 restore-safety counter DB-backed\n",
    );
    let map = write_map(&r, "jurisdiction.map", "R2289 Z\n");

    // when: migrate runs with that map
    let out = run(
        &r,
        &[
            "migrate",
            "--source",
            &src,
            "--blame",
            "Wang Yu",
            "--jurisdiction-map",
            &map,
        ],
    );

    // then: it is a hard error (out-of-vocab bucket), names the offending line, and writes nothing
    assert!(!out.status.success(), "an out-of-vocab bucket must fail");
    assert_eq!(tick_count(&r), 0, "no tick is written on a bad map");
    let e = String::from_utf8_lossy(&out.stderr);
    assert!(
        e.contains("R2289 Z") || e.contains("R2289"),
        "the error should name the offending line: {e:?}"
    );
}

#[test]
fn migrate_should_still_skip_a_tagged_record_on_a_re_run_because_jurisdiction_is_non_hashed() {
    // given: a store with R2289 imported once, tagged C from the map
    let r = repo();
    let src = write_source(
        &r,
        "gitlog",
        "chat-room.md",
        "## R2289 restore-safety counter DB-backed\n",
    );
    let map = write_map(&r, "jurisdiction.map", "R2289 C\n");
    let args = [
        "migrate",
        "--source",
        &src,
        "--blame",
        "Wang Yu",
        "--jurisdiction-map",
        &map,
    ];
    assert!(run(&r, &args).status.success());
    assert_eq!(tick_count(&r), 1, "first import writes the record");

    // when: the SAME tagged migrate runs again (jurisdiction is non-hashed ⇒ the id is unchanged)
    let second = run(&r, &args);

    // then: it is idempotent — nothing new is written and the record is reported skipped
    assert!(second.status.success());
    assert_eq!(tick_count(&r), 1, "a re-run writes no new ticks");
    let s = String::from_utf8_lossy(&second.stdout);
    assert!(
        s.contains("imported 0") && s.contains("skipped 1"),
        "summary was {s:?}"
    );
}

// One Canonical Decision Intake line: a user ruling carrying its author + an opaque source_ref.
const CANONICAL_RULING: &str = "{\"kind\":\"ev-decision-intake\",\
\"decision\":\"rate-limit lives at the edge proxy\",\
\"grounds\":[{\"claim\":\"the edge sees every request first\",\"supports\":\"chosen\"},\
{\"claim\":\"the app tier double-counts\",\"supports\":\"rejected:app-tier\"}],\
\"blame\":\"Wang Yu\",\"authority\":\"user-ruled\",\"source_ref\":\"R1043\"}\n";

#[test]
fn migrate_should_ingest_a_canonical_jsonl_source_through_the_shared_backfill() {
    // given: a store and a canonical decision-intake JSONL source (the format-neutral primary intake)
    let r = repo();
    let src = write_source(&r, "canonical", "intake.jsonl", CANONICAL_RULING);

    // when: migrate ingests it through the shared idempotent backfill
    let out = run(&r, &["migrate", "--source", &src]);

    // then: it succeeds and writes the one decision (one hashing path, like every other source)
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(tick_count(&r), 1, "the canonical record is imported");
    let v = run(&r, &["verify"]);
    assert!(
        v.status.success(),
        "the imported canonical chain must verify clean: {}",
        String::from_utf8_lossy(&v.stderr)
    );
}

#[test]
fn migrate_canonical_should_be_idempotent_on_source_ref_when_a_line_is_reingested() {
    // given: a canonical source imported once, keyed on its opaque source_ref
    let r = repo();
    let src = write_source(&r, "canonical", "intake.jsonl", CANONICAL_RULING);
    assert!(run(&r, &["migrate", "--source", &src]).status.success());
    assert_eq!(tick_count(&r), 1);

    // when: the SAME canonical line is ingested again
    let second = run(&r, &["migrate", "--source", &src]);

    // then: it is idempotent on the source_ref — nothing new written, the record reported skipped
    assert!(second.status.success());
    assert_eq!(tick_count(&r), 1, "a re-run writes no new ticks");
    let s = String::from_utf8_lossy(&second.stdout);
    assert!(
        s.contains("imported 0") && s.contains("skipped 1"),
        "summary was {s:?}"
    );
}

#[test]
fn migrate_canonical_should_stamp_authority_user_ruled_so_the_ruling_surfaces_in_brief() {
    // given: a canonical user ruling imported (carrying authority=user-ruled inline) — the two-link fix
    let r = repo();
    let src = write_source(&r, "canonical", "intake.jsonl", CANONICAL_RULING);
    assert!(
        run(&r, &["migrate", "--source", &src]).status.success(),
        "the canonical ruling imports"
    );

    // when: a fresh agent runs the boot-read
    let brief = run(&r, &["brief"]);

    // then: the imported ruling SURFACES (authority carried inline → it reaches the user-ruled boot-read,
    // closing the chain the old hardcoded-None migrate path silently broke)
    assert!(brief.status.success());
    let b = String::from_utf8_lossy(&brief.stdout);
    assert!(
        b.contains("rate-limit lives at the edge proxy") && b.contains("[user-ruled]"),
        "the imported user ruling must surface in brief; was {b:?}"
    );
}

#[test]
fn migrate_canonical_should_report_a_source_only_gap_when_a_line_has_no_blame_and_no_fallback() {
    // given: a canonical line carrying NO blame, ingested WITHOUT a --blame fallback
    let r = repo();
    let no_author = "{\"kind\":\"ev-decision-intake\",\"decision\":\"x\",\"grounds\":[],\"source_ref\":\"R7\"}\n";
    let src = write_source(&r, "canonical", "intake.jsonl", no_author);

    // when: migrate ingests it with no author available
    let out = run(&r, &["migrate", "--source", &src]);

    // then: R5 stays intact — no author invented, no tick written, the gap surfaced
    assert!(out.status.success(), "a surfaced gap is not a hard failure");
    assert_eq!(tick_count(&r), 0, "no tick is written without an author");
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(
        s.contains("source-only"),
        "the gap must be surfaced; was {s:?}"
    );
}

#[test]
fn migrate_should_reject_a_canonical_line_with_an_unknown_kind() {
    // given: a JSONL line whose envelope kind is not ev-decision-intake (a mis-piped file)
    let r = repo();
    let bad = "{\"kind\":\"notes\",\"decision\":\"x\",\"grounds\":[]}\n";
    let src = write_source(&r, "canonical", "intake.jsonl", bad);

    // when: migrate ingests it
    let out = run(&r, &["migrate", "--source", &src]);

    // then: it is a hard error and writes nothing (the wire envelope is strict, not tolerant)
    assert!(!out.status.success(), "an unknown kind must fail loudly");
    assert_eq!(tick_count(&r), 0, "nothing is written on a rejected source");
}

// A canonical line carrying a Test check, parameterized by the bits the ingest gates act on:
// `extra_tags` splices in provenance/jurisdiction; `counter` is "" (harvested) or a counter_test field.
fn canonical_with_test(extra_tags: &str, counter: &str) -> String {
    format!(
        "{{\"kind\":\"ev-decision-intake\",\"decision\":\"keep the schema frozen\",\
\"grounds\":[{{\"claim\":\"the frozen schema still holds\",\"supports\":\"chosen\",\
\"check\":{{\"by\":\"test\",\"ref\":\"pytest test_schema.py\",\
\"verified_at_sha\":\"d308afac1b2c3d4e5f60718293a4b5c6d7e8f901\"{counter},\
\"liveness\":{{\"platforms\":[\"linux-ci\"],\"triggered_by\":[\"schema.sql\"],\"surfaces\":[\"schema-ddl\"]}}}}}}],\
\"blame\":\"Wang Yu\",\"source_ref\":\"R5\"{extra_tags}}}\n"
    )
}

#[test]
fn ingest_should_accept_a_harvested_check_when_provenance_is_imported() {
    // given: an imported record whose Test check carries NO counter-test (a harvested binding)
    let r = repo();
    let body = canonical_with_test(",\"provenance\":\"imported\"", "");
    let src = write_source(&r, "canonical", "intake.jsonl", &body);

    // when: migrate ingests it
    let out = run(&r, &["migrate", "--source", &src]);

    // then: it is accepted — imported history may carry a harvested (falsifiability-unproven) binding
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(tick_count(&r), 1);
}

#[test]
fn ingest_should_refuse_a_harvested_check_when_provenance_is_agent_proposed() {
    // given: an agent-proposed record whose Test check carries NO counter-test
    let r = repo();
    let body = canonical_with_test(",\"provenance\":\"agent-proposed\"", "");
    let src = write_source(&r, "canonical", "intake.jsonl", &body);

    // when: migrate ingests it
    let out = run(&r, &["migrate", "--source", &src]);

    // then: it is refused — a fresh agent binding must prove falsifiability with a counter-test
    assert!(!out.status.success(), "an agent-proposed harvest must fail");
    assert_eq!(tick_count(&r), 0, "nothing is written on a refused record");
}

#[test]
fn ingest_should_accept_an_agent_proposed_binding_when_it_carries_a_counter_test() {
    // given: an agent-proposed record whose Test check carries a counter-test (falsifiability proven)
    let r = repo();
    let body = canonical_with_test(
        ",\"provenance\":\"agent-proposed\"",
        ",\"counter_test\":\"pytest test_schema.py::test_change_flips_red\"",
    );
    let src = write_source(&r, "canonical", "intake.jsonl", &body);

    // when: migrate ingests it
    let out = run(&r, &["migrate", "--source", &src]);

    // then: it is accepted — an agent binding with a counter-test is exactly as sound as decide/guard
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(tick_count(&r), 1);
}

#[test]
fn ingest_should_refuse_a_c_jurisdiction_record_that_carries_a_test_check() {
    // given: a C-jurisdiction (detect-only) record that carries a fully-proven Test check
    let r = repo();
    let body = canonical_with_test(
        ",\"jurisdiction\":\"C\",\"provenance\":\"imported\"",
        ",\"counter_test\":\"pytest test_schema.py::test_change_flips_red\"",
    );
    let src = write_source(&r, "canonical", "intake.jsonl", &body);

    // when: migrate ingests it
    let out = run(&r, &["migrate", "--source", &src]);

    // then: it is refused at the door — a detect-only decision must hold no runnable test binding
    assert!(!out.status.success(), "a C/D test binding must fail");
    assert_eq!(tick_count(&r), 0, "nothing is written on a refused record");
}

#[test]
fn migrate_canonical_should_default_provenance_to_imported_when_a_line_omits_it() {
    // given: a canonical ruling that declares NO provenance (the migrate verb backfills history)
    let r = repo();
    let src = write_source(&r, "canonical", "intake.jsonl", CANONICAL_RULING);

    // when: migrate imports it
    assert!(run(&r, &["migrate", "--source", &src]).status.success());

    // then: the on-disk tick is stamped provenance=imported (so verify treats its text as transcribed)
    let id = std::fs::read_dir(r.join(".evolving/ticks"))
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().into_string().unwrap())
        .find(|n| n.len() == 12)
        .expect("one imported tick");
    let raw = std::fs::read_to_string(r.join(".evolving/ticks").join(&id)).unwrap();
    let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
    assert_eq!(
        v.get("provenance").and_then(|x| x.as_str()),
        Some("imported"),
        "an undeclared canonical import defaults to imported; tick was {v}"
    );
}

#[test]
fn reconcile_should_accept_a_canonical_source_and_report_the_capture_gap() {
    // given: a store seeded with the R1043 ruling (via canonical import)
    let r = repo();
    let seed = write_source(&r, "canonical", "seed.jsonl", CANONICAL_RULING);
    assert!(run(&r, &["migrate", "--source", &seed]).status.success());

    // and: a canonical source that ALSO declares an uncaptured ruling R9999
    let extra = "{\"kind\":\"ev-decision-intake\",\"decision\":\"a ruling never captured\",\
\"grounds\":[],\"blame\":\"Wang Yu\",\"source_ref\":\"R9999\"}\n";
    let against = write_source(
        &r,
        "canonical",
        "against.jsonl",
        &format!("{CANONICAL_RULING}{extra}"),
    );

    // when: reconcile joins the canonical source against the store
    let out = run(&r, &["migrate", "--reconcile", "--against", &against]);

    // then: it succeeds and surfaces R1043 as IN-BOTH and R9999 as a SOURCE-ONLY capture gap
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("in-both 1"), "summary was {s:?}");
    assert!(s.contains("source-only 1"), "summary was {s:?}");
}

#[test]
fn ingest_should_error_when_an_inline_jurisdiction_conflicts_with_the_jurisdiction_map() {
    // given: a canonical record declaring jurisdiction=C inline, and a map tagging the SAME key as D
    let r = repo();
    let body = "{\"kind\":\"ev-decision-intake\",\"decision\":\"x\",\"grounds\":[],\
\"blame\":\"Wang Yu\",\"jurisdiction\":\"C\",\"source_ref\":\"R1043\"}\n";
    let src = write_source(&r, "canonical", "intake.jsonl", body);
    let map = write_map(&r, "jurisdiction.map", "R1043 D\n");

    // when: migrate ingests it with the conflicting map
    let out = run(
        &r,
        &["migrate", "--source", &src, "--jurisdiction-map", &map],
    );

    // then: it is a hard error (two sources of truth disagree) and writes nothing
    assert!(!out.status.success(), "a jurisdiction conflict must fail");
    assert_eq!(tick_count(&r), 0, "nothing is written on a conflict");
    let e = String::from_utf8_lossy(&out.stderr);
    assert!(
        e.contains("conflicts"),
        "the error should name the conflict: {e:?}"
    );
}

#[test]
fn ingest_should_let_an_inline_jurisdiction_agree_with_a_matching_map_entry() {
    // given: a canonical record declaring jurisdiction=C inline, and a map tagging the SAME key C too
    let r = repo();
    let body = "{\"kind\":\"ev-decision-intake\",\"decision\":\"x\",\"grounds\":[],\
\"blame\":\"Wang Yu\",\"jurisdiction\":\"C\",\"source_ref\":\"R1043\"}\n";
    let src = write_source(&r, "canonical", "intake.jsonl", body);
    let map = write_map(&r, "jurisdiction.map", "R1043 C\n");

    // when: migrate ingests it with the agreeing map
    let out = run(
        &r,
        &["migrate", "--source", &src, "--jurisdiction-map", &map],
    );

    // then: agreement is not a conflict — the record imports tagged C
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let list = run(&r, &["list"]);
    assert!(
        String::from_utf8_lossy(&list.stdout).contains("jurisdiction=C"),
        "list did not render the agreed jurisdiction"
    );
}

#[test]
fn canonical_ingest_of_the_genesis_payload_with_non_hashed_extras_still_computes_the_frozen_id() {
    // given: a canonical line whose HASHED payload is exactly the genesis golden, plus every non-hashed
    // extra the contract carries (source_ref + provenance=imported + jurisdiction=C, legal with a person
    // check). The trust boundary: ev computes parent_id=HEAD("") and the same id regardless of the extras.
    let r = repo();
    let genesis = "{\"kind\":\"ev-decision-intake\",\
\"decision\":\"freeze the retrieval schema for v2\",\
\"observe\":\"evaluating retrieval backend\",\
\"grounds\":[{\"claim\":\"team still wants a frozen schema\",\"supports\":\"chosen\",\
\"check\":{\"by\":\"person\",\"ref\":\"Q3 infra review\"}},\
{\"claim\":\"pgvector would lock our schema\",\"supports\":\"rejected:pgvector\"}],\
\"blame\":\"Wang Yu\",\"source_ref\":\"R-genesis\",\"provenance\":\"imported\",\"jurisdiction\":\"C\"}\n";
    let src = write_source(&r, "canonical", "genesis.jsonl", genesis);

    // when: it is ingested onto an empty store (so parent_id == "")
    let out = run(&r, &["migrate", "--source", &src]);

    // then: the written tick is the FROZEN genesis golden id — the non-hashed extras never move it
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        r.join(".evolving/ticks/e2b337f53a1f").exists(),
        "the canonical path must compute the same frozen genesis id; ticks: {:?}",
        std::fs::read_dir(r.join(".evolving/ticks"))
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect::<Vec<_>>()
    );
}

#[test]
fn migrate_should_round_trip_clean_through_verify_when_records_are_imported() {
    // given: a store and a 2-record source imported with a fallback author
    let r = repo();
    let src = write_source(&r, "gitlog", "chat-room.md", TWO_ROUNDS);
    assert!(
        run(&r, &["migrate", "--source", &src, "--blame", "Wang Yu"])
            .status
            .success()
    );

    // when: the store is verified
    let v = run(&r, &["verify"]);

    // then: the migrated chain passes verify (id == hash, lineage forward-only, schema closed)
    assert!(
        v.status.success(),
        "verify failed: {}",
        String::from_utf8_lossy(&v.stderr)
    );
}