ggen-engine 26.10.11

SPARQL-in-Tera code generation engine (vendored, renamed from praxis/crates/ggen)
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
//! Chicago-TDD end-to-end tests for packs: real filesystem, real oxigraph,
//! real Tera, real subprocess (`assert_cmd` spawns the NEW ggen binary).
//!
//! Layout: both `examples/demo-pack` and `examples/demo-project` are copied
//! into one `TempDir` preserving relative layout, so the project's
//! `{ path = "../demo-pack" }` reference resolves exactly as shipped.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

mod support;

use std::path::{Path, PathBuf};

use ggen_engine::sync::{sync, SyncOptions, SyncReceipt, RECEIPT_REL_PATH};
use support::{copy_tree, write_pack, write_single_pack_project, write_two_pack_project};
use tempfile::TempDir;

/// Resolve the real `ggen` binary the same way `cli_boundary.rs::ggen_bin`
/// does: `CARGO_BIN_EXE_ggen` (set by `cargo test -p ggen-cli-lib`, never by
/// `-p ggen-engine`/`-p ggen-cli` — the root package is `autobins = false`),
/// then the workspace `target/{debug,release}/ggen`, then `PATH`. Panics
/// (loudly) if no candidate resolves, so failure happens at binary
/// resolution, not at first spawn.
fn ggen_bin() -> std::path::PathBuf {
    if let Ok(path) = std::env::var("CARGO_BIN_EXE_ggen") {
        let p = std::path::PathBuf::from(path);
        if p.exists() {
            return p;
        }
    }

    let target_root = std::env::var_os("CARGO_TARGET_DIR")
        .map(std::path::PathBuf::from)
        .or_else(|| {
            let manifest_dir =
                std::env::var_os("CARGO_MANIFEST_DIR").map(std::path::PathBuf::from)?;
            let mut dir: &std::path::Path = manifest_dir.as_path();
            loop {
                if dir.join("Cargo.lock").exists() {
                    return Some(dir.join("target"));
                }
                match dir.parent() {
                    Some(p) => dir = p,
                    None => return None,
                }
            }
        });

    if let Some(target) = target_root {
        for profile in &["debug", "release"] {
            let candidate = target.join(profile).join("ggen");
            if candidate.is_file() {
                return candidate;
            }
            let candidate_exe = target.join(profile).join("ggen.exe");
            if candidate_exe.is_file() {
                return candidate_exe;
            }
        }
    }

    panic!(
        "could not resolve the `ggen` binary: CARGO_BIN_EXE_ggen unset and no \
         target/debug/ggen found; build it with `cargo build -p ggen-cli-lib --bin ggen`"
    );
}

fn examples_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("examples")
}

/// Copy demo-pack and demo-project into a fresh `TempDir`; return (dir, `project_root`).
fn scaffold() -> (TempDir, PathBuf) {
    let dir = TempDir::new().expect("tempdir");
    copy_tree(
        &examples_dir().join("demo-pack"),
        &dir.path().join("demo-pack"),
    );
    copy_tree(
        &examples_dir().join("demo-project"),
        &dir.path().join("demo-project"),
    );
    let project = dir.path().join("demo-project");
    (dir, project)
}

// One Chicago-TDD end-to-end scenario (single scaffold + sync, many real
// on-disk assertions against the full generated surface); splitting it
// would either re-run the expensive scaffold+sync setup per assertion
// group or share state between tests, not shrink real complexity.
#[allow(clippy::too_many_lines)]
#[test]
fn pack_sync_end_to_end() {
    let (_dir, project) = scaffold();

    // (1) First sync writes the pack's widget file in place under the
    // project — no generated/ dir anywhere.
    let first = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync");
    let widget = project.join("src/widget.rs");
    assert!(
        widget.is_file(),
        "pack template must write src/widget.rs under the project"
    );
    assert!(
        !project.join("generated").exists(),
        "no generated/ dir allowed"
    );
    let widget_src = std::fs::read_to_string(&widget).expect("widget");
    assert!(
        widget_src.contains("pub struct Widget"),
        "widget body: {widget_src}"
    );
    assert!(
        widget_src.contains("pub name: String"),
        "widget fields: {widget_src}"
    );
    assert!(
        widget_src.contains("pub count: String"),
        "widget fields: {widget_src}"
    );
    // Local project template also ran, driven by the union graph.
    let instances = std::fs::read_to_string(project.join("out/instances.txt")).expect("instances");
    assert_eq!(instances, "demo\n");

    // (2) ggen.lock written with a real blake3 hash matching content_hash().
    let lock = std::fs::read_to_string(project.join("ggen.lock")).expect("ggen.lock");
    assert!(lock.contains("[packs.widget]"), "lock: {lock}");
    assert!(
        lock.contains("source = \"path:../demo-pack\""),
        "lock: {lock}"
    );
    let expected_hash = first.packs.get("widget").expect("pack hash in report");
    assert_eq!(expected_hash.len(), 64, "blake3 hex");
    assert!(
        lock.contains(&format!("content_hash = \"blake3:{expected_hash}\"")),
        "lock: {lock}"
    );

    // Report decisions bind why each file landed.
    assert_eq!(
        first.decisions.get("src/widget.rs").map(String::as_str),
        Some("written")
    );

    // (3) Receipt verify passes via the NEW binary (spawned subprocess).
    assert_cmd::Command::new(ggen_bin())
        .current_dir(&project)
        .args(["receipt", "verify"])
        .assert()
        .success();

    // Receipt payload carries pack hashes and decisions.
    let receipt: SyncReceipt = serde_json::from_str(
        &std::fs::read_to_string(project.join(RECEIPT_REL_PATH)).expect("receipt"),
    )
    .expect("receipt parses");
    assert_eq!(receipt.payload.packs.get("widget"), Some(expected_hash));
    assert_eq!(
        receipt
            .payload
            .decisions
            .get("src/widget.rs")
            .map(String::as_str),
        Some("written")
    );

    // (4) Second sync is a no-op: skipped-unchanged, lock byte-identical.
    let second = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("second sync");
    assert!(
        second.written.is_empty(),
        "second sync wrote: {:?}",
        second.written
    );
    assert!(
        second
            .skipped
            .iter()
            .any(|(p, r)| p == Path::new("src/widget.rs") && r.contains("unchanged")),
        "expected skipped-unchanged widget: {:?}",
        second.skipped
    );
    assert_eq!(
        second.decisions.get("src/widget.rs").map(String::as_str),
        Some("skipped: unchanged: content identical")
    );
    let lock2 = std::fs::read_to_string(project.join("ggen.lock")).expect("ggen.lock");
    assert_eq!(
        lock2, lock,
        "ggen.lock must be byte-identical across identical runs"
    );

    // Payloads are deterministic across identical runs, and since v2
    // chaining each new receipt links onto the previous one: a third no-op
    // sync reproduces the second run's payload hash byte-for-byte while its
    // record chains from the second receipt's chain hash.
    let receipt2_raw = std::fs::read(project.join(RECEIPT_REL_PATH)).expect("receipt 2");
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("third sync");
    let receipt3_raw = std::fs::read(project.join(RECEIPT_REL_PATH)).expect("receipt 3");
    let receipt2: SyncReceipt = serde_json::from_slice(&receipt2_raw).expect("receipt 2 parses");
    let receipt3: SyncReceipt = serde_json::from_slice(&receipt3_raw).expect("receipt 3 parses");
    assert_eq!(
        receipt3.record.payload_hash_hex, receipt2.record.payload_hash_hex,
        "identical runs must yield identical payload hashes"
    );
    assert_eq!(
        receipt3.record.prev_chain_hash_hex, receipt2.record.chain_hash_hex,
        "third receipt must chain onto the second"
    );
    assert_eq!(receipt2.payload.outputs, receipt.payload.outputs);
    assert_eq!(receipt2.payload.packs, receipt.payload.packs);

    // (5) Corrupt the pack ontology…
    let pack_ontology = project
        .parent()
        .expect("root")
        .join("demo-pack/ontology.ttl");
    let mut ttl = std::fs::read_to_string(&pack_ontology).expect("pack ttl");
    ttl.push_str("\n<http://example.com/ontology#evil> <http://example.com/ontology#hasName> \"tampered\" .\n");
    std::fs::write(&pack_ontology, ttl).expect("corrupt pack");

    // (6) …and the next sync refuses by name with the pack-hash-mismatch code.
    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must refuse");
    let msg = err.to_string();
    assert!(msg.contains("FM-PACK-008"), "refusal code: {msg}");
    assert!(msg.contains("widget"), "refusal must name the pack: {msg}");
}

#[test]
fn tampered_receipt_decision_fails_verification() {
    let (_dir, project) = scaffold();
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("sync");

    // (7) Tamper a decision string inside the receipt payload.
    let receipt_path = project.join(RECEIPT_REL_PATH);
    let raw = std::fs::read_to_string(&receipt_path).expect("receipt");
    let mut json: serde_json::Value = serde_json::from_str(&raw).expect("json");
    json["payload"]["decisions"]["src/widget.rs"] =
        serde_json::Value::String("skipped: nothing to see here".to_string());
    std::fs::write(
        &receipt_path,
        serde_json::to_vec_pretty(&json).expect("ser"),
    )
    .expect("write tampered");

    let output = assert_cmd::Command::new(ggen_bin())
        .current_dir(&project)
        .args(["receipt", "verify"])
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&output.get_output().stderr).into_owned();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout).into_owned();
    assert!(
        (stderr.clone() + &stdout).contains("payload hash mismatch"),
        "expected payload hash mismatch, got stderr={stderr} stdout={stdout}"
    );
}

#[test]
fn dry_run_never_writes_or_mutates_lock() {
    let (_dir, project) = scaffold();

    // Dry-run on a fresh project: no lock, no receipt, no outputs.
    let report = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: true,
            ..Default::default()
        },
    )
    .expect("dry run");
    assert!(!report.written.is_empty(), "dry run should plan writes");
    assert!(
        !project.join("ggen.lock").exists(),
        "dry run must not write ggen.lock"
    );
    assert!(
        !project.join("src/widget.rs").exists(),
        "dry run must not write outputs"
    );
    assert!(
        !project.join(RECEIPT_REL_PATH).exists(),
        "dry run must not emit a receipt"
    );

    // After a real sync, a dry-run leaves the lock byte-identical even if
    // decisions change (nothing to write).
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("real sync");
    let lock = std::fs::read(project.join("ggen.lock")).expect("lock");
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: true,
            ..Default::default()
        },
    )
    .expect("dry run 2");
    let lock2 = std::fs::read(project.join("ggen.lock")).expect("lock");
    assert_eq!(lock, lock2, "dry run must never mutate ggen.lock");
}

#[test]
fn unreachable_git_pack_url_fails_closed_with_a_typed_error() {
    let (_dir, project) = scaffold();
    let manifest = project.join("ggen.toml");
    let toml = std::fs::read_to_string(&manifest).expect("ggen.toml");
    // A syntactically valid but unreachable/nonexistent path git URL — no
    // network access needed to prove the clone failure is caught and
    // reported as a typed FM-PACK-010, not a panic or a raw process error.
    let toml = toml.replace(
        "widget = { path = \"../demo-pack\" }",
        "widget = { git = \"/nonexistent/path/to/nowhere.git\", version = \"main\" }",
    );
    std::fs::write(&manifest, toml).expect("rewrite");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("clone must fail");
    let msg = err.to_string();
    assert!(msg.contains("FM-PACK-010"), "{msg}");
    assert!(msg.contains("git clone"), "{msg}");
}

#[test]
fn broken_packs_refuse_by_name() {
    // Missing pack dir.
    let (_dir, project) = scaffold();
    std::fs::remove_dir_all(project.parent().expect("root").join("demo-pack")).expect("rm");
    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("missing dir");
    assert!(err.to_string().contains("FM-PACK-001"), "{err}");
    assert!(err.to_string().contains("widget"), "{err}");

    // Missing ontology.ttl.
    let (_dir, project) = scaffold();
    std::fs::remove_file(
        project
            .parent()
            .expect("root")
            .join("demo-pack/ontology.ttl"),
    )
    .expect("rm ttl");
    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("missing ontology");
    assert!(err.to_string().contains("FM-PACK-004"), "{err}");

    // Syntactically invalid pack.toml. (Unknown top-level keys are no longer
    // a refusal: `PackToml`/`PackMeta` deliberately dropped
    // `deny_unknown_fields` in favor of a flattened open schema -- 12/352
    // real marketplace packs carry author metadata beyond the closed keys --
    // so the broken-pack refusal this case anchors is now invalid TOML, which
    // `[FM-PACK-003]` still covers.)
    let (_dir, project) = scaffold();
    let manifest = project.parent().expect("root").join("demo-pack/pack.toml");
    let mut toml = std::fs::read_to_string(&manifest).expect("pack.toml");
    toml.push_str("not = [valid toml\n");
    std::fs::write(&manifest, toml).expect("rewrite");
    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("invalid pack.toml");
    assert!(err.to_string().contains("FM-PACK-003"), "{err}");
    assert!(err.to_string().contains("widget"), "{err}");

    // Zero templates.
    let (_dir, project) = scaffold();
    std::fs::remove_file(
        project
            .parent()
            .expect("root")
            .join("demo-pack/templates/widget.rs.tmpl"),
    )
    .expect("rm tmpl");
    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("zero templates");
    assert!(err.to_string().contains("FM-PACK-005"), "{err}");
}

// ---------------------------------------------------------------------------
// Two-pack composition
// ---------------------------------------------------------------------------

#[test]
fn two_packs_disjoint_outputs_both_succeed() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "pack-a",
        "Alpha",
        "src/alpha.rs",
        "pub const ALPHA: &str = \"a\";",
    );
    write_pack(
        dir.path(),
        "pack-b",
        "Beta",
        "src/beta.rs",
        "pub const BETA: &str = \"b\";",
    );
    let project = write_two_pack_project(dir.path(), "pack-a", "pack-b");

    let report = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("sync");

    let alpha = std::fs::read_to_string(project.join("src/alpha.rs")).expect("alpha.rs");
    assert_eq!(alpha, "pub const ALPHA: &str = \"a\";\n");
    let beta = std::fs::read_to_string(project.join("src/beta.rs")).expect("beta.rs");
    assert_eq!(beta, "pub const BETA: &str = \"b\";\n");

    assert_eq!(
        report.decisions.get("src/alpha.rs").map(String::as_str),
        Some("written")
    );
    assert_eq!(
        report.decisions.get("src/beta.rs").map(String::as_str),
        Some("written")
    );

    let lock = std::fs::read_to_string(project.join("ggen.lock")).expect("ggen.lock");
    let idx_a = lock.find("[packs.pack-a]").expect("pack-a entry in lock");
    let idx_b = lock.find("[packs.pack-b]").expect("pack-b entry in lock");
    assert!(
        idx_a < idx_b,
        "ggen.lock must list packs alphabetically: {lock}"
    );

    assert!(
        report.packs.contains_key("pack-a"),
        "report.packs: {:?}",
        report.packs
    );
    assert!(
        report.packs.contains_key("pack-b"),
        "report.packs: {:?}",
        report.packs
    );

    assert_cmd::Command::new(ggen_bin())
        .current_dir(&project)
        .args(["receipt", "verify"])
        .assert()
        .success();
}

#[test]
fn two_packs_colliding_output_aborts_sync_without_rollback_or_lock() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(dir.path(), "pack-a", "Alpha", "src/collision.rs", "AAA");
    write_pack(dir.path(), "pack-b", "Beta", "src/collision.rs", "BBB");
    let project = write_two_pack_project(dir.path(), "pack-a", "pack-b");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must refuse collision");
    let msg = err.to_string();
    assert!(msg.contains("FM-WRITE-008"), "{msg}");
    assert!(msg.contains("src/collision.rs"), "{msg}");

    // The collision is detected before the write stage begins, so neither
    // pack's file lands — no partial state.
    assert!(
        !project.join("src/collision.rs").exists(),
        "collision must refuse before any write"
    );

    assert!(
        !project.join("ggen.lock").exists(),
        "ggen.lock must not be written"
    );
    assert!(
        !project.join(RECEIPT_REL_PATH).exists(),
        "receipt must not be written"
    );
}

/// Write `root/<name>/` as a pack with TWO separate template files (distinct
/// filenames, so `load_templates`'s sorted-path walk sees two distinct
/// entries) whose frontmatter both set the identical `to:` target
/// `to_path` — the intra-pack analogue of `write_pack`'s single-template
/// packs used by the cross-pack collision test above.
fn write_pack_with_intra_pack_collision(root: &Path, name: &str, to_path: &str) {
    let pack_dir = root.join(name);
    std::fs::create_dir_all(pack_dir.join("templates")).expect("mkdir pack templates");

    std::fs::write(
        pack_dir.join("pack.toml"),
        format!(
            "[pack]\nname = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test pack {name}\"\n"
        ),
    )
    .expect("write pack.toml");

    std::fs::write(
        pack_dir.join("ontology.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:Widget a dom:DomainClass .\n",
    )
    .expect("write ontology.ttl");

    std::fs::write(
        pack_dir.join("templates").join("rule_one.rs.tmpl"),
        format!("---\nto: {to_path}\n---\npub const ONE: &str = \"one\";\n"),
    )
    .expect("write template rule_one");
    std::fs::write(
        pack_dir.join("templates").join("rule_two.rs.tmpl"),
        format!("---\nto: {to_path}\n---\npub const TWO: &str = \"two\";\n"),
    )
    .expect("write template rule_two");
}

/// Condition 9 (一出力一所有が守られる, `packs/ggen-release-pack/ontology.ttl`)
/// narrow gap: `two_packs_colliding_output_aborts_sync_without_rollback_or_lock`
/// above proves CROSS-pack collisions are refused. It does not prove that
/// ONE pack's own two templates/rules claiming the same output are caught
/// the same way. `discover_templates` (`sync.rs`) flattens project
/// templates and every resolved pack's templates into a single
/// `Vec<(PathBuf, Template)>` with no pack-affinity tag preserved on either
/// the `Template` or the later `PendingWrite`, and the duplicate-target
/// refusal (`sync.rs`, the `seen: BTreeMap<&str, usize>` scan right before
/// Stage 5) counts occurrences of `to:` across that whole flat list with no
/// notion of "owner" at all — so reading the code strongly suggests an
/// intra-pack collision hits the identical `FM-WRITE-008` refusal. This
/// test proves that empirically instead of leaving it as an inference.
#[test]
fn same_pack_two_templates_colliding_output_aborts_sync_identically() {
    let dir = TempDir::new().expect("tempdir");
    write_pack_with_intra_pack_collision(dir.path(), "pack-solo", "src/collision.rs");
    let project = write_single_pack_project(dir.path(), "solo-project", "pack-solo");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must refuse intra-pack collision the same way as cross-pack");
    let msg = err.to_string();
    assert!(msg.contains("FM-WRITE-008"), "{msg}");
    assert!(msg.contains("src/collision.rs"), "{msg}");

    // Same no-partial-state guarantee as the cross-pack case: the refusal
    // fires during Stage 4 (render), before Stage 5 (write) ever starts, so
    // neither template's content lands and no lock/receipt appears.
    assert!(
        !project.join("src/collision.rs").exists(),
        "intra-pack collision must refuse before any write"
    );
    assert!(
        !project.join("ggen.lock").exists(),
        "ggen.lock must not be written"
    );
    assert!(
        !project.join(RECEIPT_REL_PATH).exists(),
        "receipt must not be written"
    );
}

/// Path to the real, production `[validation].gates`-wired cross-pack
/// contamination gate at the repo root (condition 8, 合成時に意味汚染がない) —
/// `../..` from this crate's manifest dir to the workspace root, the same
/// traversal already used by `cross_pack_matrix.rs`/`framework_packs_e2e.rs`/
/// `lint_validate_e2e.rs` in this same tests/ directory.
fn contamination_gate_source() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.specify/gates/cross-pack-contamination.rq")
}

/// Write `root/<project_name>/` referencing `pack_a` and `pack_b`, wired
/// with `[law].gates` pointing at a copy of the real repo-root contamination
/// gate (copied into the project so the gate's own path resolves relative
/// to this `TempDir` project root, exactly as `[law].gates` paths always do).
fn write_two_pack_project_with_contamination_gate(
    root: &Path, pack_a: &str, pack_b: &str,
) -> PathBuf {
    let project = root.join("contamination-project");
    std::fs::create_dir_all(project.join("templates")).expect("mkdir templates");
    std::fs::write(project.join("ontology.ttl"), "").expect("write ontology.ttl");
    std::fs::copy(
        contamination_gate_source(),
        project.join("contamination-gate.rq"),
    )
    .expect("copy real contamination gate into project");
    std::fs::write(
        project.join("ggen.toml"),
        format!(
            "[project]\nname = \"contamination-project\"\n\n\
             [ontology]\nsource = \"ontology.ttl\"\n\n\
             [packs]\npack-a = {{ path = \"../{pack_a}\" }}\npack-b = {{ path = \"../{pack_b}\" }}\n\n\
             [templates]\ndir = \"templates\"\n\n\
             [law]\ngates = [\"contamination-gate.rq\"]\n"
        ),
    )
    .expect("write ggen.toml");
    project
}

/// Real, Chicago-TDD proof of condition 8's new closure (see
/// `packs/ggen-release-pack/ontology.ttl`'s condition-8 row): two packs
/// whose `ontology.ttl` files assert CONFLICTING `rdf:type` facts about the
/// exact same subject IRI (`dom:Widget`, `TypeA` vs `TypeB`) — disjoint output
/// paths, so the pre-existing output-path-collision gate
/// (`two_packs_colliding_output_aborts_sync_without_rollback_or_lock` above)
/// does not fire; only the new cross-pack contamination gate can refuse
/// this sync. Runs the REAL `sync()` (real filesystem, real graph union,
/// real SPARQL gate evaluation) against the REAL repo-root gate file — not
/// a standalone SPARQL string checked in isolation.
#[test]
fn cross_pack_conflicting_rdf_type_aborts_sync_citing_contamination_gate() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "pack-a",
        "Alpha",
        "src/alpha.rs",
        "pub const ALPHA: &str = \"a\";",
    );
    write_pack(
        dir.path(),
        "pack-b",
        "Beta",
        "src/beta.rs",
        "pub const BETA: &str = \"b\";",
    );
    // Overwrite both packs' ontology.ttl (written above by write_pack with
    // disjoint dom:Alpha/dom:Beta subjects) so they instead assert
    // conflicting rdf:type facts about the SAME subject IRI, `dom:Widget`.
    std::fs::write(
        dir.path().join("pack-a/ontology.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:Widget a dom:TypeA .\n",
    )
    .expect("overwrite pack-a ontology.ttl");
    std::fs::write(
        dir.path().join("pack-b/ontology.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:Widget a dom:TypeB .\n",
    )
    .expect("overwrite pack-b ontology.ttl");
    let project = write_two_pack_project_with_contamination_gate(dir.path(), "pack-a", "pack-b");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must refuse cross-pack rdf:type contamination");
    let msg = err.to_string();
    assert!(msg.contains("FM-LAW-013"), "{msg}");
    assert!(msg.contains("contamination-gate.rq"), "{msg}");
    assert!(
        msg.contains("cross-pack term contamination"),
        "gate's own # MESSAGE text must surface in the refusal: {msg}"
    );
    assert!(
        msg.contains("http://example.com/ontology#Widget")
            || msg.contains("dom:Widget")
            || msg.contains("#Widget"),
        "refusal must cite the contaminated subject: {msg}"
    );

    // The gate runs before Extract/Render/Write, so neither pack's output
    // file lands, and no lock/receipt is written -- same no-partial-state
    // guarantee as the output-path-collision gate above.
    assert!(
        !project.join("src/alpha.rs").exists(),
        "contamination must refuse before any write"
    );
    assert!(
        !project.join("src/beta.rs").exists(),
        "contamination must refuse before any write"
    );
    assert!(
        !project.join("ggen.lock").exists(),
        "ggen.lock must not be written"
    );
    assert!(
        !project.join(RECEIPT_REL_PATH).exists(),
        "receipt must not be written"
    );
}

fn git(args: &[&str], cwd: &Path) {
    let out = std::process::Command::new("git")
        .args(args)
        .current_dir(cwd)
        .output()
        .expect("run git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Turn `examples/demo-pack` into a real, tagged local git repo (no network)
/// under `dir`, returning its path.
fn make_git_pack_source(dir: &Path) -> PathBuf {
    let source = dir.join("demo-pack-git-source");
    copy_tree(&examples_dir().join("demo-pack"), &source);
    git(&["init", "--quiet"], &source);
    git(&["config", "user.email", "test@example.com"], &source);
    git(&["config", "user.name", "Test"], &source);
    git(&["add", "."], &source);
    git(&["commit", "--quiet", "-m", "v1"], &source);
    git(&["tag", "v1"], &source);
    source
}

#[test]
fn git_resolved_pack_syncs_end_to_end_and_caches_across_runs() {
    let dir = TempDir::new().expect("tempdir");
    let source = make_git_pack_source(dir.path());

    let project = dir.path().join("consumer");
    std::fs::create_dir_all(project.join("templates")).expect("mkdir templates");
    std::fs::write(project.join("ontology.ttl"), "").expect("write ontology.ttl");
    std::fs::write(
        project.join("ggen.toml"),
        format!(
            "[project]\nname = \"consumer\"\n\n\
             [ontology]\nsource = \"ontology.ttl\"\n\n\
             [packs]\nwidget = {{ git = \"{}\", version = \"v1\" }}\n\n\
             [templates]\ndir = \"templates\"\n",
            source.display()
        ),
    )
    .expect("write ggen.toml");

    // (1) First sync clones the pack and generates from it exactly like a
    // local { path = "…" } pack would.
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync clones and generates");
    let widget = project.join("src/widget.rs");
    assert!(widget.is_file(), "git pack must write src/widget.rs");
    assert!(
        std::fs::read_to_string(&widget)
            .expect("widget")
            .contains("pub struct Widget"),
        "widget must come from the cloned pack's template"
    );

    // (2) ggen.lock records the pack by its git source string.
    let lock = std::fs::read_to_string(project.join("ggen.lock")).expect("ggen.lock");
    assert!(lock.contains("[packs.widget]"), "lock: {lock}");
    assert!(
        lock.contains(&format!("source = \"git:{}@v1\"", source.display())),
        "lock must record the git source and pinned version: {lock}"
    );
    assert!(lock.contains("content_hash = \"blake3:"), "lock: {lock}");

    // (3) Second sync reuses the pinned clone cache — no re-clone, since
    // `version` hasn't changed. Prove it via a sentinel file that a
    // wipe-and-re-clone would remove.
    //
    // Written under `.git/` (not the cache dir root) deliberately: LEAD 2 of
    // the 2026-08-03 unverified-leads audit ("ggen.lock's content_hash
    // excludes gates/ and hooks") was fixed by making `content_hash` walk
    // every file under the pack root -- so a sentinel written directly into
    // the cache dir root would now (correctly) be treated as pack content
    // and invalidate the very lock this test just wrote, failing the second
    // `sync()` with a content-hash-mismatch it did not intend to test.
    // `.git/` is the one path `content_hash` deliberately excludes (see
    // `collect_pack_files_sorted`'s doc comment: hashing a git clone's own
    // reflogs would make the hash depend on wall-clock clone time), so it is
    // simultaneously invisible to the hash and destroyed by any real
    // wipe-and-reclone -- exactly the two properties this sentinel needs.
    let cache_dir = project.join(".ggen-v2/git-packs/widget");
    let sentinel = cache_dir.join(".git/sentinel.txt");
    std::fs::write(&sentinel, "still here").expect("write sentinel");
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("second sync");
    assert!(
        sentinel.is_file(),
        "unchanged version must reuse the cached clone, not re-clone"
    );
    let widget_after = std::fs::read_to_string(&widget).expect("widget after second sync");
    assert!(
        widget_after.contains("pub struct Widget"),
        "output unaffected by cache reuse"
    );
}

/// Write `root/extra-project/` referencing `pack_name` by relative path with
/// an in-project extra ontology (`extra/extra.ttl`) declared via
/// `extra_ontologies` — the in-manifest union that replaces per-pack
/// make-ontology.sh committed unions.
fn write_extra_ontology_project(root: &Path, pack_name: &str) -> PathBuf {
    let project = root.join("extra-project");
    std::fs::create_dir_all(project.join("templates")).expect("mkdir templates");
    std::fs::create_dir_all(project.join("extra")).expect("mkdir extra");
    std::fs::write(project.join("ontology.ttl"), "").expect("write ontology.ttl");
    std::fs::write(
        project.join("extra/extra.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:ExtraClass a dom:DomainClass .\n",
    )
    .expect("write extra.ttl");
    std::fs::write(
        project.join("ggen.toml"),
        format!(
            "[project]\nname = \"extra-project\"\n\n\
             [ontology]\nsource = \"ontology.ttl\"\n\n\
             [packs]\npack-a = {{ path = \"../{pack_name}\", extra_ontologies = [\"extra/extra.ttl\"] }}\n\n\
             [templates]\ndir = \"templates\"\n"
        ),
    )
    .expect("write ggen.toml");
    project
}

#[test]
fn extra_ontology_syncs_and_its_edit_invalidates_the_lock() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "extra-pack-a",
        "Alpha",
        "src/alpha.rs",
        "pub struct Alpha;",
    );
    let project = write_extra_ontology_project(dir.path(), "extra-pack-a");

    // First sync succeeds: the extra ontology is readable, unioned, and
    // locked into the pack's content hash.
    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync with extra ontology");
    assert!(
        project.join("src/alpha.rs").is_file(),
        "pack output written"
    );
    let lock_1 =
        std::fs::read_to_string(project.join("ggen.lock")).expect("lockfile after first sync");
    assert!(lock_1.contains("pack-a"), "lock records the pack: {lock_1}");

    // Editing the EXTRA source (outside the pack directory) must invalidate
    // the lock exactly like an in-pack edit — this is the drift the old
    // committed-union make-ontology.sh convention could not detect.
    std::fs::write(
        project.join("extra/extra.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:ExtraClassEdited a dom:DomainClass .\n",
    )
    .expect("edit extra.ttl");
    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("edited extra ontology must refuse against the stale lock");
    let msg = format!("{err}");
    assert!(
        msg.contains("content hash mismatch"),
        "typed FM-PACK-008 lock mismatch expected, got: {msg}"
    );
}

#[test]
fn missing_extra_ontology_refuses_with_a_typed_error() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "extra-pack-b",
        "Beta",
        "src/beta.rs",
        "pub struct Beta;",
    );
    let project = write_extra_ontology_project(dir.path(), "extra-pack-b");
    std::fs::remove_file(project.join("extra/extra.ttl")).expect("remove extra.ttl");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("missing extra ontology must refuse");
    let msg = format!("{err}");
    assert!(
        msg.contains("extra ontology") && msg.contains("missing"),
        "typed FM-PACK-004 missing-extra error expected, got: {msg}"
    );
}

// ---------------------------------------------------------------------------
// `lock = false` opt-out (PackRef::Path)
// ---------------------------------------------------------------------------

/// Write `root/<project_name>/` referencing `pack_a` (locked, default) and
/// `pack_b` (with `lock = {lock_b}`) by relative path.
fn write_two_pack_project_with_lock(
    root: &Path, project_name: &str, pack_a: &str, pack_b: &str, lock_b: bool,
) -> PathBuf {
    let project = root.join(project_name);
    std::fs::create_dir_all(project.join("templates")).expect("mkdir templates");
    std::fs::write(project.join("ontology.ttl"), "").expect("write ontology.ttl");
    std::fs::write(
        project.join("ggen.toml"),
        format!(
            "[project]\nname = \"{project_name}\"\n\n\
             [ontology]\nsource = \"ontology.ttl\"\n\n\
             [packs]\npack-a = {{ path = \"../{pack_a}\" }}\n\
             pack-b = {{ path = \"../{pack_b}\", lock = {lock_b} }}\n\n\
             [templates]\ndir = \"templates\"\n"
        ),
    )
    .expect("write ggen.toml");
    project
}

/// A pack declared `lock = false` is never checked against `ggen.lock` and
/// never written to it — a second sync after editing its `ontology.ttl`
/// must succeed instead of tripping `FM-PACK-008`. The companion locked
/// pack (`pack-a`, default `lock = true`) proves the lockfile genuinely
/// gets written in this run (not vacuously absent), so `pack-b`'s absence
/// from it is a real assertion, not a no-op.
#[test]
fn lock_false_pack_is_never_locked_and_its_edit_does_not_refuse() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "lockopt-pack-a",
        "Alpha",
        "src/alpha.rs",
        "pub struct Alpha;",
    );
    write_pack(
        dir.path(),
        "lockopt-pack-b",
        "Beta",
        "src/beta.rs",
        "pub struct Beta;",
    );
    let project = write_two_pack_project_with_lock(
        dir.path(),
        "lock-false-project",
        "lockopt-pack-a",
        "lockopt-pack-b",
        false,
    );

    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync");
    assert!(
        project.join("src/alpha.rs").is_file(),
        "pack-a output written"
    );
    assert!(
        project.join("src/beta.rs").is_file(),
        "pack-b output written"
    );

    let lock_1 = std::fs::read_to_string(project.join("ggen.lock"))
        .expect("ggen.lock must exist: pack-a is locked, so lock_entries is non-empty");
    assert!(
        lock_1.contains("[packs.pack-a]"),
        "default lock=true pack must still be locked: {lock_1}"
    );
    assert!(
        !lock_1.contains("pack-b"),
        "lock=false pack must never appear in ggen.lock: {lock_1}"
    );

    // Edit the unlocked pack's ontology.ttl (the exact mutation that trips
    // FM-PACK-008 for a locked pack, per
    // `pack_sync_end_to_end`'s tampering step).
    std::fs::write(
        dir.path().join("lockopt-pack-b/ontology.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:BetaEdited a dom:DomainClass .\n",
    )
    .expect("edit lock=false pack ontology");

    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("second sync must NOT refuse: pack-b opted out of lock checking");

    let lock_2 = std::fs::read_to_string(project.join("ggen.lock"))
        .expect("ggen.lock must still exist after second sync");
    assert!(
        !lock_2.contains("pack-b"),
        "lock=false pack must still never appear in ggen.lock after re-sync: {lock_2}"
    );
    assert!(
        lock_2.contains("[packs.pack-a]"),
        "locked pack must remain locked after re-sync: {lock_2}"
    );
}

/// Regression guard: a pack with no `lock` key (default `lock = true`) keeps
/// exactly the pre-existing behavior — locked into `ggen.lock`, and a
/// tampering edit still refuses with the typed `FM-PACK-008` content-hash
/// mismatch, asserting the same error-message shape as
/// `extra_ontology_syncs_and_its_edit_invalidates_the_lock`.
#[test]
fn default_locked_pack_still_refuses_on_tampering_regression_guard() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "lockopt-pack-c",
        "Gamma",
        "src/gamma.rs",
        "pub struct Gamma;",
    );
    let project = write_single_pack_project(dir.path(), "lock-default-project", "lockopt-pack-c");

    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync with default lock=true pack");
    let lock_1 = std::fs::read_to_string(project.join("ggen.lock")).expect("ggen.lock");
    assert!(
        lock_1.contains("[packs.pack-a]"),
        "default lock=true pack must be locked: {lock_1}"
    );

    std::fs::write(
        dir.path().join("lockopt-pack-c/ontology.ttl"),
        "@prefix dom: <http://example.com/ontology#> .\ndom:GammaTampered a dom:DomainClass .\n",
    )
    .expect("tamper default-locked pack ontology");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("default-locked pack must still refuse on tampering");
    let msg = format!("{err}");
    assert!(
        msg.contains("content hash mismatch"),
        "typed FM-PACK-008 lock mismatch expected, got: {msg}"
    );
    assert!(msg.contains("FM-PACK-008"), "refusal code: {msg}");
}

/// LEAD 2 (2026-08-03 unverified-leads audit): "ggen.lock's `content_hash`
/// excludes gates/ and hooks." Confirmed real: `content_hash` used to hash
/// only `ontology.ttl`, declared extra ontologies, and `templates/*.tmpl` --
/// a pack's `gates/*.rq` SPARQL gate files (real, sync-time-enforced
/// governing inputs, see the pack-gate loop in `crate::sync::sync`) were
/// silently excluded from the hash `check_lock` verifies. Tampering with a
/// LOCKED pack's gate file after `ggen.lock` was written went completely
/// undetected -- the exact tampering-detection gap this session already
/// closed once for `ggen-marketplace`'s `compute_pack_digest`.
#[test]
fn tampering_with_a_locked_packs_gate_file_is_caught() {
    let dir = TempDir::new().expect("tempdir");
    write_pack(
        dir.path(),
        "gate-pack",
        "Delta",
        "src/delta.rs",
        "pub struct Delta;",
    );
    // A pack-shipped SPARQL gate: harmless (ASK false = Pass) so the first
    // sync succeeds and locks it in.
    std::fs::create_dir_all(dir.path().join("gate-pack/gates")).expect("mkdir gates");
    std::fs::write(
        dir.path().join("gate-pack/gates/no_op.rq"),
        "ASK { FILTER(false) }\n",
    )
    .expect("write gate");
    let project = write_single_pack_project(dir.path(), "gate-project", "gate-pack");

    sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync locks the pack, gate included");
    let lock_1 = std::fs::read_to_string(project.join("ggen.lock")).expect("ggen.lock");
    assert!(lock_1.contains("[packs.pack-a]"), "lock: {lock_1}");

    // Tamper with ONLY the gate file -- ontology.ttl, pack.toml, and every
    // template are untouched.
    std::fs::write(
        dir.path().join("gate-pack/gates/no_op.rq"),
        "ASK { FILTER(true) }\n", // now a real violation if it ran, but the
                                  // point is the CONTENT changed, whether or
                                  // not sync gets far enough to evaluate it
    )
    .expect("tamper gate file");

    let err = sync(
        &project,
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err(
        "a locked pack's gate file was tampered with after ggen.lock was written -- \
         content_hash must now catch this, not silently reuse the stale hash",
    );
    let msg = format!("{err}");
    assert!(
        msg.contains("FM-PACK-008") && msg.contains("content hash mismatch"),
        "expected a content-hash mismatch refusal naming the tampered gate file's pack, got: {msg}"
    );
}