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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
//! Hand-written handler implementations behind the generated noun-verb routes.
//!
//! The route files (`sync.rs`, `graph.rs`, `receipt.rs`, `mod.rs`) are pure
//! projections of `schema/praxis.ttl` and are regenerated by `ggen sync`;
//! only this module carries logic.

use std::path::PathBuf;

use camino::Utf8PathBuf;
use clap_noun_verb::{NounVerbError, Result};

use crate::config::GgenConfig;
use crate::error::AppError;
use crate::graph::{DeterministicGraph, GraphEngine, TurtleDocument};
use crate::receipt_chain_seam as receipt_record;
use crate::sync::{sync, SyncOptions, SyncReceipt, RECEIPT_LOG_REL_PATH, RECEIPT_REL_PATH};

/// Resolve the project root: the process working directory.
fn project_root() -> Result<PathBuf> {
    std::env::current_dir()
        .map_err(|e| NounVerbError::execution_error(format!("cannot resolve cwd: {e}")))
}

/// Map any crate error into a `NounVerbError` (non-zero exit).
fn exec_err(e: impl std::fmt::Display) -> NounVerbError {
    NounVerbError::execution_error(e.to_string())
}

/// Borrow the raw `payload` bytes out of a stored receipt document.
///
/// Payload-hash verification hashes the payload bytes exactly as stored,
/// never a re-serialization of the typed [`crate::sync::ReceiptPayload`] —
/// re-serializing would inject `#[serde(default)]` fields (e.g. `packs`,
/// `decisions`) into receipts written before those fields existed and fail
/// legitimate old records.
#[derive(serde::Deserialize)]
struct RawPayloadProbe<'a> {
    #[serde(borrow)]
    payload: &'a serde_json::value::RawValue,
}

/// BLAKE3 hex of the raw stored payload bytes of `receipt_doc` (one full
/// receipt JSON document).
fn stored_payload_hash(receipt_doc: &str) -> Result<String> {
    let probe: RawPayloadProbe<'_> = serde_json::from_str(receipt_doc)
        .map_err(|e| exec_err(format!("receipt payload unreadable: {e}")))?;
    Ok(blake3::hash(probe.payload.get().as_bytes())
        .to_hex()
        .to_string())
}

/// `ggen sync run` — the five-stage pipeline: resolve, enrich, extract,
/// render, write. `dry_run` computes every write decision without touching
/// the filesystem or emitting a receipt. `watch` runs one sync then blocks,
/// re-running the pipeline on every debounced filesystem change under the
/// project root (see [`crate::watch`]); in practice it never returns.
///
/// # Errors
/// Any pipeline failure (`FM-*` codes) is mapped to a `NounVerbError`
/// execution error, exiting non-zero.
pub fn handle_sync_run(
    dry_run: bool, watch: bool, consumer_mode: bool,
) -> Result<serde_json::Value> {
    let root = project_root()?;
    if watch {
        crate::watch::watch(&root, dry_run).map_err(exec_err)?;
        return Ok(serde_json::json!({ "watch": "stopped" }));
    }
    let report = sync(
        &root,
        SyncOptions {
            dry_run,
            consumer_mode,
            ..Default::default()
        },
    )
    .map_err(exec_err)?;
    serde_json::to_value(report).map_err(exec_err)
}

/// `ggen graph validate [--files <TTL>...] [--shapes <TTL>...]` — validate
/// RDF/Turtle graphs.
///
/// Two modes, selected by whether any `files` were passed:
///
/// * **No files (project mode)** — load `ggen.toml` + ontology, report quad
///   count and deterministic state hash, then run the static
///   frontmatter/SPARQL cross-checks ([`crate::lint`]) over every discovered
///   template (project plus resolved packs). Any parse failure or lint
///   violation is a hard error (fail closed): the response lists every
///   violation at once. This branch is byte-for-byte the pre-multi-file
///   behavior. `shapes` is ignored in this mode.
/// * **One or more files (file mode)** — parse and hash each file
///   independently against a fresh, isolated store (file B's contents can
///   never taint file A). Every unreadable or unparseable file is collected;
///   if any file is invalid the call fails closed (non-zero) naming *every*
///   bad file with its error. The project ontology and templates are NOT
///   touched in this mode — validating arbitrary user Turtle is not linting
///   the project's own codegen templates. When `shapes` is non-empty, every
///   `files` target is additionally SHACL-validated against the union of
///   all `shapes` graphs (see `validate_files`); with `shapes` empty this
///   branch is byte-for-byte the pre-`--shapes` (parse-only) behavior.
///
/// `files`/`shapes` are each transported as a repeatable option (published
/// clap-noun-verb 26.7.4 does not carry multi-value bare positionals), and
/// both default to empty, so every existing zero- and one-flag invocation
/// lands in the same mode as before this option existed.
///
/// # Errors
/// Project mode: missing/invalid `ggen.toml`, unreadable ontology, Turtle
/// parse failures, pack resolution failures, or any
/// `FM-TPL-003`/`FM-TPL-004`/`FM-TPL-005` template diagnostic exit non-zero.
/// File mode: any unreadable file, Turtle parse failure, or hash failure on
/// any supplied file exits non-zero, naming each offending file. With
/// `shapes` supplied: an unreadable/unparseable shapes file, or any SHACL
/// violation (naming focus node, source shape, and message) also exits
/// non-zero.
// `files`/`shapes` arrive by value because the GENERATED clap-noun-verb call
// site (`crate::verbs::graph::graph_validate`, `mode = Overwrite` from the
// ontology — not hand-editable here) passes the owned `Vec<Utf8PathBuf>`
// clap produced for a repeatable `pathbufs` arg; accepting `&[Utf8PathBuf]`
// instead would require changing that shared code-generation template for
// every `pathbufs`-typed command, not just this one.
#[allow(clippy::needless_pass_by_value)]
pub fn handle_graph_validate(
    files: Vec<Utf8PathBuf>, shapes: Vec<Utf8PathBuf>,
) -> Result<serde_json::Value> {
    if !files.is_empty() {
        return validate_files(&files, &shapes);
    }

    let root = project_root()?;
    match crate::schema_dispatch::load(&root).map_err(exec_err)? {
        crate::schema_dispatch::ParsedGgenToml::Frontmatter(config) => {
            graph_validate_frontmatter(&root, &config)
        }
        crate::schema_dispatch::ParsedGgenToml::DeclarativeRules(manifest) => {
            graph_validate_declarative_rules(&root, &manifest)
        }
    }
}

/// `ggen graph validate` project mode for the frontmatter (`GgenConfig`)
/// schema — byte-for-byte the pre-dispatch-repointing behavior (see
/// `handle_graph_validate`'s own doc comment above).
fn graph_validate_frontmatter(
    root: &std::path::Path, config: &GgenConfig,
) -> Result<serde_json::Value> {
    let ontology_path = root.join(&config.ontology.source);
    let ttl = std::fs::read_to_string(&ontology_path).map_err(|e| {
        exec_err(format!(
            "ontology `{}` unreadable: {e}",
            ontology_path.display()
        ))
    })?;
    let graph = DeterministicGraph::new().map_err(exec_err)?;
    let quads = graph.insert_turtle(&ttl).map_err(exec_err)?;
    let hash = graph.state_hash().map_err(exec_err)?;
    let hash_hex = crate::sync::hex32(&hash);

    // Static template lint over the exact template set a sync would process.
    let packs = crate::pack::resolve(config, root).map_err(exec_err)?;
    let templates = crate::sync::discover_templates(root, config, &packs).map_err(exec_err)?;
    let violations: Vec<String> = templates
        .iter()
        .flat_map(|(path, tpl)| crate::lint::lint_template(path, tpl))
        .map(|e| e.to_string())
        .collect();
    if !violations.is_empty() {
        return Err(exec_err(format!(
            "graph validate failed: {} template violation(s): {}",
            violations.len(),
            violations.join("; ")
        )));
    }

    Ok(serde_json::json!({
        "quads": quads,
        "hash": hash_hex,
        "templates_checked": templates.len(),
    }))
}

/// `ggen graph validate` project mode for the declarative-rules
/// (`GgenManifest`) schema.
///
/// Only the ontology (+ imports) is validated here: this schema has no
/// pack-resolution or frontmatter-template-lint equivalent yet
/// (`crate::pack::resolve` is typed against `crate::config::GgenConfig`
/// only, and `crate::lint::lint_template` lints `crate::template::
/// Frontmatter`, a shape `GenerationRule` does not have — the same
/// documented gap `crate::generation_rules`'s own module doc comment
/// already names for pack resolution). Reports `templates_checked: 0` with
/// an explicit note rather than silently omitting the field, so a caller
/// cannot mistake this for "zero violations found in N templates."
fn graph_validate_declarative_rules(
    root: &std::path::Path, manifest: &ggen_config::manifest::GgenManifest,
) -> Result<serde_json::Value> {
    let ontology_path = root.join(&manifest.ontology.source);
    let ttl = std::fs::read_to_string(&ontology_path).map_err(|e| {
        exec_err(format!(
            "ontology `{}` unreadable: {e}",
            ontology_path.display()
        ))
    })?;
    let mut ontology_sources = Vec::with_capacity(1 + manifest.ontology.imports.len());
    ontology_sources.push((ontology_path.display().to_string(), ttl));
    for import in &manifest.ontology.imports {
        let import_path = root.join(import);
        let import_ttl = std::fs::read_to_string(&import_path).map_err(|e| {
            exec_err(format!(
                "ontology import `{}` unreadable: {e}",
                import_path.display()
            ))
        })?;
        ontology_sources.push((import_path.display().to_string(), import_ttl));
    }
    let documents: Vec<TurtleDocument<'_>> = ontology_sources
        .iter()
        .map(|(label, content)| TurtleDocument::new(label, content))
        .collect();
    let graph = DeterministicGraph::new().map_err(exec_err)?;
    let receipt = graph
        .insert_turtle_documents(&documents)
        .map_err(exec_err)?;
    let quads = receipt.inserted_quads;
    let hash = graph.state_hash().map_err(exec_err)?;

    Ok(serde_json::json!({
        "quads": quads,
        "hash": crate::sync::hex32(&hash),
        "templates_checked": 0,
        "note": "declarative-rules ([[generation.rules]]) schema: pack resolution and \
                 frontmatter template lint are not implemented for this schema yet; only \
                 the ontology graph (source + imports) was validated.",
    }))
}

/// Validate each supplied Turtle file independently (file mode), optionally
/// against a union SHACL shapes graph.
///
/// Errors are accumulated, never short-circuited, so a single call reports
/// *every* invalid file at once (same convention as the project-mode
/// template-violation join). A fresh store per file keeps files isolated:
/// file B's triples never contaminate file A's parse, hash, or SHACL
/// conformance check.
///
/// When `shapes` is empty this is exactly the pre-`--shapes` behavior: a
/// fresh [`DeterministicGraph`] per file, Turtle-parse plus BLAKE3 state
/// hash only, no SHACL evaluation. `oxigraph`'s Turtle-load error carries
/// only the parser message, not the path, so each error is path-prefixed
/// here before collection — otherwise the aggregate could not name the
/// offending file.
///
/// When `shapes` is non-empty, every shapes file is read once and
/// concatenated into a single Turtle document (a single [`ShapesGraph`
/// parse](praxis_graphlaw) call, so shorthand blank nodes `[ ... ]` across
/// shape files get distinct auto-generated labels from one continuous
/// parser pass — no cross-file blank-node collision). Each `files` target
/// is then loaded into a fresh [`crate::graph::GraphLawStore`] (rather than
/// the bare oxigraph mirror) and validated against that union shapes
/// document via [`crate::graph::GraphEngine::validate_shacl`]; `quads`/
/// `hash` are unchanged (`GraphLawStore`'s hash delegates to the same
/// oxigraph mirror algorithm as `DeterministicGraph`). Any non-conforming
/// file is reported with every violation naming its focus node, source
/// shape, and message (never a bare "invalid", and never silently coerced
/// to a warning). Known scope: shape files sharing a `@prefix` name with
/// *different* IRIs would silently take the last declaration's binding —
/// no shape file in this repo does that today, so it is not guarded here.
///
/// # Complexity
/// O(sum over files of parse+hash cost) plus, when `shapes` is non-empty,
/// O(sum over files of SHACL evaluation cost against the union shapes
/// graph); one linear pass over `files`, no cross-file work.
// One linear file-mode validation orchestrator (parse, hash, optional SHACL
// evaluation, per-file diagnostics); splitting it would scatter one
// sequential pass across call boundaries rather than shrink real complexity.
#[allow(clippy::too_many_lines)]
fn validate_files(files: &[Utf8PathBuf], shapes: &[Utf8PathBuf]) -> Result<serde_json::Value> {
    use crate::graph::{GraphEngine as _, GraphLawStore};

    let shapes_ttl: Option<String> = if shapes.is_empty() {
        None
    } else {
        let mut combined = String::new();
        for shape_path in shapes {
            let ttl = std::fs::read_to_string(shape_path)
                .map_err(|e| exec_err(format!("shapes file `{shape_path}` unreadable: {e}")))?;
            combined.push_str(&ttl);
            combined.push('\n');
        }
        Some(combined)
    };

    let mut ok_records: Vec<serde_json::Value> = Vec::with_capacity(files.len());
    let mut bad: Vec<String> = Vec::new();

    for path in files {
        let ttl = match std::fs::read_to_string(path) {
            Ok(t) => t,
            Err(e) => {
                bad.push(format!("{path}: unreadable: {e}"));
                continue;
            }
        };

        let Some(shapes_ttl) = shapes_ttl.as_deref() else {
            // Unchanged parse-only path (fresh isolated oxigraph store).
            let graph = DeterministicGraph::new().map_err(exec_err)?;
            let quads = match graph.insert_turtle(&ttl) {
                Ok(q) => q,
                Err(e) => {
                    bad.push(format!("{path}: {e}"));
                    continue;
                }
            };
            match graph.state_hash() {
                Ok(hash) => ok_records.push(serde_json::json!({
                    "path": path.as_str(),
                    "quads": quads,
                    "hash": crate::sync::hex32(&hash),
                })),
                Err(e) => bad.push(format!("{path}: {e}")),
            }
            continue;
        };

        // Shapes path: fresh isolated GraphLaw engine per file (same
        // per-file isolation guarantee as the parse-only path above).
        let engine = match GraphLawStore::new() {
            Ok(e) => e,
            Err(e) => {
                bad.push(format!("{path}: {e}"));
                continue;
            }
        };
        let quads = match engine.insert_turtle(&ttl) {
            Ok(q) => q,
            Err(e) => {
                bad.push(format!("{path}: {e}"));
                continue;
            }
        };
        let hash = match engine.state_hash() {
            Ok(h) => h,
            Err(e) => {
                bad.push(format!("{path}: {e}"));
                continue;
            }
        };
        let report = match engine.validate_shacl(shapes_ttl) {
            Ok(r) => r,
            Err(e) => {
                bad.push(format!("{path}: {e}"));
                continue;
            }
        };
        if !report.conforms {
            bad.push(format!(
                "{path}: SHACL validation failed, {} violation(s): {}",
                report.violations.len(),
                report.violations.join("; ")
            ));
            continue;
        }
        ok_records.push(serde_json::json!({
            "path": path.as_str(),
            "quads": quads,
            "hash": crate::sync::hex32(&hash),
            "shapes_conform": true,
        }));
    }

    if !bad.is_empty() {
        return Err(exec_err(format!(
            "graph validate failed: {} of {} file(s) invalid: {}",
            bad.len(),
            files.len(),
            bad.join("; ")
        )));
    }

    let mut out = serde_json::json!({
        "files": ok_records,
        "files_checked": files.len(),
    });
    if !shapes.is_empty() {
        out["shapes_checked"] = serde_json::json!(shapes.len());
    }
    Ok(out)
}

/// `ggen receipt verify` — read `.ggen-v2/receipt.json`, recompute the
/// chain hash via praxis-core, then (T063) check the ed25519 signature when
/// the record carries one, and fail (non-zero exit) on any mismatch.
///
/// # Errors
/// A missing/malformed receipt, a payload-hash mismatch, a chain-hash
/// mismatch, or (when `signature_hex` is present) a signature mismatch all
/// exit non-zero, each with a distinct message naming which check failed
/// (an invalid receipt is never a cheerful `valid: false`). A record with no
/// `signature_hex` (a receipt written before signing existed) is not an
/// error: the chain-integrity check above still runs and must still pass;
/// the response simply reports `"signed": false`.
pub fn handle_receipt_verify() -> Result<serde_json::Value> {
    let root = project_root()?;
    handle_receipt_verify_in(&root)
}

/// [`handle_receipt_verify`] against an explicit project root.
///
/// The verb form resolves its root from the process cwd, which makes it
/// unusable for any caller that must verify several projects (self-play
/// arenas, a test harness) without mutating global process state. This is
/// the same logic with the root passed in; `handle_receipt_verify` is now a
/// thin cwd-resolving delegate to it, so there is exactly one
/// receipt-verification implementation rather than two that can drift.
///
/// # Errors
/// See [`handle_receipt_verify`].
// One linear verification sequence (schema version, payload hash, chain
// hash, signature); splitting it would scatter a single sequential check
// across call boundaries rather than shrink real complexity -- same
// reasoning as the sibling `handle_receipt_history`'s identical attribute.
// Grew past the 100-line threshold when this pass tagged each error path
// with its own `FM-CHAIN-0NN` code (previously plain strings).
#[allow(clippy::too_many_lines)]
pub fn handle_receipt_verify_in(root: &std::path::Path) -> Result<serde_json::Value> {
    let receipt_path = root.join(RECEIPT_REL_PATH);
    let raw = std::fs::read_to_string(&receipt_path).map_err(|e| {
        exec_err(format!(
            "receipt `{}` unreadable: {e}",
            receipt_path.display()
        ))
    })?;
    let receipt: SyncReceipt = serde_json::from_str(&raw).map_err(|e| {
        exec_err(format!(
            "receipt `{}` malformed: {e}",
            receipt_path.display()
        ))
    })?;

    // 0. Schema version: a record written by a schema this binary doesn't
    //    know how to interpret must be refused before any hash/signature
    //    check runs -- `recompute_chain_hash`'s `build_admission_frame`
    //    construction is only guaranteed to match the emission path for the
    //    version it was built against.
    if receipt.record.version != receipt_record::RECEIPT_RECORD_VERSION {
        return Err(exec_err(AppError::fm_chain(
            12,
            format!(
                "receipt invalid: unsupported receipt schema version {} (this binary supports \
                 {}). Remediation: re-sync with a matching ggen version, or upgrade/downgrade \
                 to a binary that supports this receipt's schema version.",
                receipt.record.version,
                receipt_record::RECEIPT_RECORD_VERSION
            ),
        )));
    }

    // 1. Payload binding: the stored payload bytes must hash to
    //    payload_hash_hex (raw bytes, not a re-serialization; see
    //    `stored_payload_hash`).
    let payload_hash_hex = stored_payload_hash(&raw)?;
    if payload_hash_hex != receipt.record.payload_hash_hex {
        return Err(exec_err(AppError::fm_chain(
            13,
            format!(
                "receipt invalid: payload hash mismatch (stored {}, recomputed {payload_hash_hex})",
                receipt.record.payload_hash_hex
            ),
        )));
    }

    // 2. Chain integrity: rule-aware recompute via praxis-core's
    //    emission-path frame (`ReceiptRecord::verify_chain`): a declared
    //    rule is checked exactly; an undeclared pre-F1 record may verify
    //    only under the base rule, and then reports the capped
    //    `legacy-v2-unbound` standing instead of `fully-bound`.
    let chain_standing = match receipt
        .record
        .verify_chain()
        .map_err(|e| exec_err(AppError::fm_chain(14, e.to_string())))?
    {
        receipt_record::ChainVerification::Verified(standing) => standing,
        receipt_record::ChainVerification::Mismatch { rule, recomputed } => {
            let stored_chain_hash = &receipt.record.chain_hash_hex;
            let recomputed_hex = crate::sync::hex32(&recomputed);
            return Err(exec_err(AppError::fm_chain(
                14,
                format!(
                    "receipt invalid: chain hash mismatch (stored {stored_chain_hash}, \
                     recomputed {recomputed_hex} under chain rule `{}`). Remediation: the \
                     receipt's own record fields (payload/chain hashes, andon, object_ids, \
                     v2, ...) were tampered with -- restore from `receipt history`/git.",
                    rule.as_str()
                ),
            )));
        }
    };

    // 2b. Chain-rule downgrade guard (FM-CHAIN-009): a legacy head is lawful
    //     only when no record in the log declared a chain rule -- the same
    //     monotonicity law `receipt history` applies record by record.
    if chain_standing == receipt_record::ChainStanding::LegacyV2Unbound {
        let log_path = root.join(RECEIPT_LOG_REL_PATH);
        if let Some(first) =
            crate::sync::first_declared_chain_rule_in_log(&log_path, 14).map_err(exec_err)?
        {
            return Err(exec_err(AppError::fm_chain(
                14,
                format!(
                    "receipt invalid: chain-rule downgrade -- the head verifies only as `{}` \
                     but receipt log record {first} declared a chain rule. Remediation: the \
                     head was re-sealed under the legacy base rule -- restore from `receipt \
                     history`/git.",
                    receipt_record::ChainStanding::LegacyV2Unbound.as_str()
                ),
            )));
        }
    }

    // 3. Signature (T063): only when the record was signed. A legacy/unsigned
    //    record is not a failure -- chain integrity above already ran and
    //    passed, which is everything a pre-signing receipt can prove.
    let signed = receipt.record.signature_hex.is_some();
    let signature_valid = match &receipt.record.signature_hex {
        None => None,
        Some(sig_hex) => {
            use ed25519_dalek::Verifier as _;

            let verifying_key = crate::keys::resolve_verifying_key(root).map_err(exec_err)?;
            let sig_bytes = hex::decode(sig_hex).map_err(|e| {
                exec_err(AppError::fm_chain(
                    15,
                    format!("receipt invalid: signature_hex is not valid hex: {e}"),
                ))
            })?;
            let sig_arr: [u8; 64] = sig_bytes.try_into().map_err(|v: Vec<u8>| {
                exec_err(AppError::fm_chain(
                    16,
                    format!(
                        "receipt invalid: signature must be 64 bytes (128 hex chars), got {} bytes",
                        v.len()
                    ),
                ))
            })?;
            let signature = ed25519_dalek::Signature::from_bytes(&sig_arr);
            match verifying_key.verify(receipt.record.chain_hash_hex.as_bytes(), &signature) {
                Ok(()) => Some(true),
                Err(_) => {
                    return Err(exec_err(AppError::fm_chain(
                        17,
                        "receipt invalid: signature mismatch (chain integrity OK, but the \
                         ed25519 signature does not verify against the resolved verifying key). \
                         Remediation: check GGEN_SIGNING_KEY / .ggen/keys/verifying.key match \
                         the key that signed this receipt, or the receipt's signature_hex field \
                         was tampered with.",
                    )));
                }
            }
        }
    };

    let mut out = serde_json::json!({
        "valid": true,
        "chain_hash": receipt.record.chain_hash_hex,
        "payload_hash": receipt.record.payload_hash_hex,
        "graph_hash": receipt.payload.graph_hash,
        "outputs": receipt.payload.outputs.len(),
        "signed": signed,
        "chain_standing": chain_standing.as_str(),
    });
    if let Some(v) = signature_valid {
        out["signature_valid"] = serde_json::json!(v);
    }
    Ok(out)
}

/// `ggen receipt history` — verify the full chain of sync receipts in
/// `.ggen-v2/receipt-log.jsonl`.
///
/// For every logged receipt: (1) the stored payload must hash to the
/// record's `payload_hash_hex`, (2) the record's `chain_hash_hex` must
/// match a praxis-core recompute, and (3) each record's `chain_hash_hex`
/// must equal the next record's `prev_chain_hash_hex`. The first record
/// must chain from all-zeros (genesis).
///
/// # Errors
/// A missing or empty log, any malformed line, or the first broken link
/// (named by zero-based index and failed check) exits non-zero — fail
/// closed, never a cheerful `valid: false`.
pub fn handle_receipt_history() -> Result<serde_json::Value> {
    let root = project_root()?;
    handle_receipt_history_in(&root)
}

/// [`handle_receipt_history`] against an explicit project root (same
/// reason as [`handle_receipt_verify_in`]: in-process callers and tests
/// must exercise the exact verifier without depending on the process cwd
/// or on a separately built `ggen` binary being current).
///
/// # Errors
/// Same as [`handle_receipt_history`].
// One linear chain-verification loop (payload hash, chain-hash recompute,
// prev-link check per record); splitting it would scatter one sequential
// per-record check across call boundaries rather than shrink real
// complexity.
#[allow(clippy::too_many_lines)]
pub fn handle_receipt_history_in(root: &std::path::Path) -> Result<serde_json::Value> {
    let log_path = root.join(RECEIPT_LOG_REL_PATH);
    let raw = std::fs::read_to_string(&log_path).map_err(|e| {
        exec_err(AppError::fm_chain(
            5,
            format!(
                "receipt log `{}` unreadable: {e}. \
                 Remediation: run `ggen sync run` at least once.",
                log_path.display()
            ),
        ))
    })?;

    let mut receipts: Vec<(SyncReceipt, &str)> = Vec::new();
    for (idx, line) in raw.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let receipt: SyncReceipt = serde_json::from_str(line).map_err(|e| {
            exec_err(AppError::fm_chain(
                6,
                format!("receipt log entry {idx} malformed: {e}"),
            ))
        })?;
        receipts.push((receipt, line));
    }
    if receipts.is_empty() {
        return Err(exec_err(AppError::fm_chain(
            5,
            format!(
                "receipt log `{}` is empty. \
                 Remediation: run `ggen sync run` at least once.",
                log_path.display()
            ),
        )));
    }

    let genesis = "0".repeat(64);
    if receipts[0].0.record.prev_chain_hash_hex != genesis {
        return Err(exec_err(AppError::fm_chain(
            7,
            "history invalid at index 0: \
             first record does not chain from genesis (all-zeros prev_chain_hash_hex)",
        )));
    }

    // Records that verify only under the pre-F1 base rule (their `v2`
    // payload is outside their chain hash); reported, never hidden.
    let mut legacy_v2_unbound = 0usize;
    // Chain-rule downgrade guard: a legacy base-rule record is lawful only
    // in the pre-F1 prefix, never after a record that declared its rule.
    let mut rule_monotonicity = receipt_record::ChainRuleMonotonicity::new();
    for (idx, (receipt, line)) in receipts.iter().enumerate() {
        // 0. Schema version: refuse a record whose schema this binary
        //    doesn't know how to interpret before trusting any hash it
        //    carries (mirrors `handle_receipt_verify`'s check 0).
        if receipt.record.version != receipt_record::RECEIPT_RECORD_VERSION {
            return Err(exec_err(AppError::fm_chain(
                7,
                format!(
                    "history invalid at index {idx}: unsupported receipt schema version {} \
                     (this binary supports {})",
                    receipt.record.version,
                    receipt_record::RECEIPT_RECORD_VERSION
                ),
            )));
        }
        // 1. Payload binding: hash the raw stored payload bytes (see
        //    `stored_payload_hash`), never a re-serialization.
        let payload_hash_hex = stored_payload_hash(line)?;
        if payload_hash_hex != receipt.record.payload_hash_hex {
            return Err(exec_err(AppError::fm_chain(
                7,
                format!(
                    "history invalid at index {idx}: payload hash mismatch \
                     (stored {}, recomputed {payload_hash_hex})",
                    receipt.record.payload_hash_hex
                ),
            )));
        }
        // 2. Rule-aware chain-hash recomputation via praxis-core's
        //    emission-path frame (`ReceiptRecord::verify_chain`).
        match receipt.record.verify_chain().map_err(|e| {
            exec_err(AppError::fm_chain(
                7,
                format!("history invalid at index {idx}: chain recompute failed: {e}"),
            ))
        })? {
            receipt_record::ChainVerification::Verified(standing) => {
                rule_monotonicity
                    .observe(idx, &receipt.record, standing)
                    .map_err(|e| {
                        exec_err(AppError::fm_chain(
                            7,
                            format!("history invalid at index {idx}: {e}"),
                        ))
                    })?;
                if standing == receipt_record::ChainStanding::LegacyV2Unbound {
                    legacy_v2_unbound += 1;
                }
            }
            receipt_record::ChainVerification::Mismatch { rule, recomputed } => {
                let recomputed_hex = crate::sync::hex32(&recomputed);
                return Err(exec_err(AppError::fm_chain(
                    7,
                    format!(
                        "history invalid at index {idx}: chain hash mismatch \
                         (stored {}, recomputed {recomputed_hex} under chain rule `{}`)",
                        receipt.record.chain_hash_hex,
                        rule.as_str()
                    ),
                )));
            }
        }
        // 3. Adjacent link: this chain hash must be the next record's prev.
        if let Some((next, _)) = receipts.get(idx + 1) {
            if receipt.record.chain_hash_hex != next.record.prev_chain_hash_hex {
                return Err(exec_err(AppError::fm_chain(
                    7,
                    format!(
                        "history invalid at index {idx}: broken link \
                         (record {idx} chain_hash_hex {} != record {} prev_chain_hash_hex {})",
                        receipt.record.chain_hash_hex,
                        idx + 1,
                        next.record.prev_chain_hash_hex
                    ),
                )));
            }
        }
    }

    let last = &receipts[receipts.len() - 1].0;

    // 4. Head-pointer consistency: `receipt.json` is meant to always mirror
    //    the log's tail record (see `crate::sync::write_receipt`'s doc
    //    comment: log append happens first, head-pointer write second). If
    //    it exists, it must actually equal that tail record's chain hash --
    //    otherwise the log has been truncated (its most recent entries
    //    dropped) while the head pointer was left pointing at the removed
    //    record, which the per-record checks above cannot detect on their
    //    own since they only verify internal log consistency, never the
    //    log's length/tail against anything external.
    let receipt_path = root.join(RECEIPT_REL_PATH);
    match std::fs::read_to_string(&receipt_path) {
        Ok(head_raw) => {
            let head: SyncReceipt = serde_json::from_str(&head_raw).map_err(|e| {
                exec_err(AppError::fm_chain(
                    7,
                    format!("receipt `{}` malformed: {e}", receipt_path.display()),
                ))
            })?;
            if head.record.chain_hash_hex != last.record.chain_hash_hex {
                return Err(exec_err(AppError::fm_chain(
                    7,
                    format!(
                        "history invalid: `.ggen-v2/receipt.json` chain hash {} does not match \
                         the log tail's chain hash {} -- the log has been truncated (or \
                         `receipt.json` was left stale) since this head was recorded. \
                         Remediation: restore the missing log entries or re-run `ggen sync run`.",
                        head.record.chain_hash_hex, last.record.chain_hash_hex
                    ),
                )));
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => {
            return Err(exec_err(format!(
                "receipt `{}` unreadable: {e}",
                receipt_path.display()
            )))
        }
    }

    Ok(serde_json::json!({
        "valid": true,
        "records": receipts.len(),
        "head_chain_hash": last.record.chain_hash_hex,
        "legacy_v2_unbound_records": legacy_v2_unbound,
    }))
}

/// Whether `path` could have been produced by the templated `to:` pattern
/// `pattern` (containing `{{ … }}` placeholders). Placeholders match any
/// substring; the literal chunks around them must appear in order, with the
/// first anchored at the start and the last at the end. A malformed pattern
/// (unclosed `{{`) matches nothing — fail closed.
fn templated_to_matches(pattern: &str, path: &str) -> bool {
    let mut chunks: Vec<&str> = Vec::new();
    let mut rest = pattern;
    while let Some(start) = rest.find("{{") {
        chunks.push(&rest[..start]);
        match rest[start..].find("}}") {
            Some(rel_end) => rest = &rest[start + rel_end + 2..],
            None => return false,
        }
    }
    chunks.push(rest);

    let mut pos = 0usize;
    for (i, chunk) in chunks.iter().enumerate() {
        if chunk.is_empty() {
            continue;
        }
        if i == 0 {
            if !path.starts_with(chunk) {
                return false;
            }
            pos = chunk.len();
        } else if let Some(found) = path.get(pos..).and_then(|tail| tail.find(chunk)) {
            pos += found + chunk.len();
        } else {
            return false;
        }
    }
    match chunks.last() {
        Some(last) if !last.is_empty() => path.ends_with(last),
        _ => true,
    }
}

/// The `orphaned_artifacts` doctor check: every output recorded in the
/// receipt must still be producible by some template today. Static `to:`
/// targets match exactly; templated targets (`{{ … }}` per-row expansion)
/// match via literal-chunk pattern matching, since the concrete path
/// depends on SPARQL row values not known statically.
fn orphaned_artifacts_check(
    receipt: &SyncReceipt, templates: &[(std::path::PathBuf, crate::template::Template)],
) -> serde_json::Value {
    let mut static_tos: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
    let mut templated_tos: Vec<&str> = Vec::new();
    for (_, tpl) in templates {
        let to = tpl.frontmatter.to.as_str();
        if to.contains("{{") {
            templated_tos.push(to);
        } else {
            static_tos.insert(to);
        }
    }
    let orphans: Vec<String> = receipt
        .payload
        .outputs
        .keys()
        .filter(|path| {
            !static_tos.contains(path.as_str())
                && !templated_tos.iter().any(|p| templated_to_matches(p, path))
        })
        .cloned()
        .collect();
    if orphans.is_empty() {
        serde_json::json!({
            "status": "pass",
            "detail": "every receipt output is still produced by a template",
            "orphans": Vec::<String>::new(),
        })
    } else {
        serde_json::json!({
            "status": "fail",
            "detail": format!(
                "{} output(s) recorded in the receipt with no producing template: {}",
                orphans.len(),
                orphans.join(", ")
            ),
            "orphans": orphans,
        })
    }
}

/// `ggen doctor run` — a non-invasive health check over three independently
/// computed conditions: lockfile/pack drift, orphaned generated artifacts
/// (a receipt output with no template that would produce it today), and
/// receipt-vs-disk staleness (a receipt output missing or hash-mismatched
/// on disk). All three checks are always computed (never short-circuited)
/// and `ANDed` into `healthy`, so a caller can see every drift independently.
///
/// A project that has never been synced (no `.ggen-v2/receipt.json`) is
/// healthy by definition for the artifact/staleness checks: there is
/// nothing to have drifted from yet.
///
/// # Errors
/// Any individual check failing (lockfile drift, an orphaned artifact, or
/// a stale/missing receipt output) is a hard error naming every failing
/// check's detail in one message — fail closed, same convention as every
/// other integrity check in this crate.
// Three independently-computed, always-run checks (lockfile drift, orphaned
// artifacts, receipt-vs-disk staleness) ANDed into one `healthy` verdict;
// splitting it would scatter that deliberate "always compute all three"
// invariant across call boundaries rather than shrink real complexity.
#[allow(clippy::too_many_lines)]
pub fn handle_doctor() -> Result<serde_json::Value> {
    let root = project_root()?;

    // Check 1 (lockfile_drift)'s inputs, and the template set Check 2
    // (orphaned_artifacts) needs, both depend on which of ggen.toml's two
    // schemas this project resolves to -- see `crate::schema_dispatch`'s own
    // doc comment (the shared dispatch point every ggen.toml-reading call
    // site in this crate now goes through, repointed off the unconditional
    // `GgenConfig::load` that made this function reject any real
    // declarative-rules project outright). The frontmatter schema runs both
    // exactly as before repointing. The declarative-rules
    // ([[generation.rules]]) schema has no pack-resolution or
    // template-discovery equivalent yet (`crate::pack::resolve` and
    // `crate::sync::discover_templates` are typed against the frontmatter
    // `GgenConfig` only -- the same documented gap
    // `crate::generation_rules`'s own module doc comment names for pack
    // resolution), so both checks report an explicit, typed `"skip"` there
    // -- never a fabricated `"pass"` for something that was never actually
    // checked.
    let (lockfile_check, templates_for_orphan_check): (
        serde_json::Value,
        Option<Vec<(PathBuf, crate::template::Template)>>,
    ) = match crate::schema_dispatch::load(&root).map_err(exec_err)? {
        crate::schema_dispatch::ParsedGgenToml::Frontmatter(config) => {
            let config = *config;
            let packs = crate::pack::resolve(&config, &root).map_err(exec_err)?;
            let lock_entries = crate::pack::lock_entries(&config, &packs).map_err(exec_err)?;
            let lockfile_check = match crate::pack::check_lock(&root, &lock_entries) {
                Ok(()) => {
                    let detail = if lock_entries.is_empty() {
                        "no packs configured".to_string()
                    } else {
                        "ggen.lock matches resolved packs".to_string()
                    };
                    serde_json::json!({ "status": "pass", "detail": detail })
                }
                Err(e) => serde_json::json!({ "status": "fail", "detail": e.to_string() }),
            };
            let templates =
                crate::sync::discover_templates(&root, &config, &packs).map_err(exec_err)?;
            (lockfile_check, Some(templates))
        }
        crate::schema_dispatch::ParsedGgenToml::DeclarativeRules(_manifest) => (
            serde_json::json!({
                "status": "skip",
                "detail": "skipped: pack resolution is not implemented for the \
                    declarative-rules ([[generation.rules]]) schema yet -- \
                    crate::pack::resolve is typed against the frontmatter GgenConfig \
                    schema only. See crate::generation_rules's own documented scope gap.",
            }),
            None,
        ),
    };
    let lockfile_pass = lockfile_check["status"] != "fail";

    // Load the receipt, if any. Absence is not an error for doctor.
    let receipt_path = root.join(RECEIPT_REL_PATH);
    let receipt: Option<SyncReceipt> = match std::fs::read_to_string(&receipt_path) {
        Ok(raw) => Some(serde_json::from_str(&raw).map_err(|e| {
            exec_err(format!(
                "receipt `{}` malformed: {e}",
                receipt_path.display()
            ))
        })?),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => {
            return Err(exec_err(format!(
                "receipt `{}` unreadable: {e}",
                receipt_path.display()
            )))
        }
    };

    // Check 2: orphaned_artifacts.
    let orphaned_check = match (&receipt, &templates_for_orphan_check) {
        (None, _) => serde_json::json!({
            "status": "pass",
            "detail": "no receipt found; nothing has been generated yet",
            "orphans": Vec::<String>::new(),
        }),
        (Some(_), None) => serde_json::json!({
            "status": "skip",
            "detail": "skipped: template discovery is not implemented for the \
                declarative-rules ([[generation.rules]]) schema yet.",
            "orphans": Vec::<String>::new(),
        }),
        (Some(receipt), Some(templates)) => orphaned_artifacts_check(receipt, templates),
    };
    let orphaned_pass = orphaned_check["status"] != "fail";

    // Check 3: receipt_staleness.
    let staleness_check = match &receipt {
        None => serde_json::json!({
            "status": "pass",
            "detail": "no receipt found; nothing has been generated yet",
            "stale": Vec::<serde_json::Value>::new(),
        }),
        Some(receipt) => {
            let mut stale: Vec<serde_json::Value> = Vec::new();
            for (path, expected_hash) in &receipt.payload.outputs {
                let target = root.join(path);
                match std::fs::read(&target) {
                    Ok(bytes) => {
                        let actual_hash = blake3::hash(&bytes).to_hex().to_string();
                        if &actual_hash != expected_hash {
                            stale.push(serde_json::json!({
                                "path": path,
                                "reason": "hash mismatch",
                                "expected_hash": expected_hash,
                                "actual_hash": actual_hash,
                            }));
                        }
                    }
                    Err(_) => {
                        stale.push(serde_json::json!({
                            "path": path,
                            "reason": "file missing",
                            "expected_hash": expected_hash,
                        }));
                    }
                }
            }
            if stale.is_empty() {
                serde_json::json!({
                    "status": "pass",
                    "detail": "every receipt output matches its recorded hash on disk",
                    "stale": Vec::<serde_json::Value>::new(),
                })
            } else {
                let paths: Vec<&str> = stale.iter().filter_map(|s| s["path"].as_str()).collect();
                serde_json::json!({
                    "status": "fail",
                    "detail": format!(
                        "{} receipt output(s) missing or hash-mismatched on disk: {}",
                        stale.len(),
                        paths.join(", ")
                    ),
                    "stale": stale,
                })
            }
        }
    };
    let staleness_pass = staleness_check["status"] == "pass";

    let healthy = lockfile_pass && orphaned_pass && staleness_pass;
    let report = serde_json::json!({
        "healthy": healthy,
        "checks": {
            "lockfile_drift": lockfile_check,
            "orphaned_artifacts": orphaned_check,
            "receipt_staleness": staleness_check,
        },
    });

    if healthy {
        Ok(report)
    } else {
        let mut failing: Vec<String> = Vec::new();
        if !lockfile_pass {
            failing.push(format!(
                "lockfile_drift: {}",
                lockfile_check["detail"].as_str().unwrap_or("")
            ));
        }
        if !orphaned_pass {
            failing.push(format!(
                "orphaned_artifacts: {}",
                orphaned_check["detail"].as_str().unwrap_or("")
            ));
        }
        if !staleness_pass {
            failing.push(format!(
                "receipt_staleness: {}",
                staleness_check["detail"].as_str().unwrap_or("")
            ));
        }
        Err(exec_err(format!(
            "doctor found {} failing check(s): {}",
            failing.len(),
            failing.join("; ")
        )))
    }
}

// ---------------------------------------------------------------------------
// `ggen law *` — law-state operations on the project graph (GraphLaw engine)
// ---------------------------------------------------------------------------

/// Build the `GraphLaw` engine over the project's law inputs: `ggen.toml`,
/// the ontology, every resolved pack ontology, and every law-rules file
/// (loaded, not yet materialized). Shared by all `ggen law` verbs so each
/// verb sees the identical fact/rule state a sync's law stage sees (minus
/// template `construct:` enrichment, which is a sync concern).
///
/// Repointed through `crate::schema_dispatch::load` (specs/014-ggen-core-replacement,
/// correction 2 / Blocker A part 2): this function used to unconditionally
/// call `GgenConfig::load` and reject any real declarative-rules project.
/// Both schemas' law-rules/law-shapes fields resolve to the exact same
/// `Vec<PathBuf>` shape (`GgenConfig::law.{rules,shapes}` vs.
/// `GgenManifest.law.rules` / `GgenManifest.validation.shacl` -- SHACL
/// shapes deliberately live under `[validation].shacl` on that schema, not
/// a duplicated `law.shapes` field, see `GgenManifest`'s own struct doc
/// comment), so the return type is the schema-agnostic shapes list rather
/// than either concrete config type.
///
/// The declarative-rules schema has no pack-resolution equivalent yet (the
/// same documented gap `crate::generation_rules::run` itself has: it does
/// not resolve `manifest.packs` either), so that branch loads only the
/// primary ontology plus its declared imports -- no packs are unioned in.
/// `(law_shapes, engine, loaded_law_rule_files)` — see [`build_law_engine`].
type LawEngineBuild = (
    Vec<PathBuf>,
    crate::graph::GraphLawStore,
    Vec<(String, usize)>,
);

fn build_law_engine(root: &std::path::Path) -> Result<LawEngineBuild> {
    use crate::graph::GraphEngine as _;
    let engine = crate::graph::GraphLawStore::new().map_err(exec_err)?;

    let (law_rules, law_shapes): (Vec<PathBuf>, Vec<PathBuf>) =
        match crate::schema_dispatch::load(root).map_err(exec_err)? {
            crate::schema_dispatch::ParsedGgenToml::Frontmatter(config) => {
                let config = *config;
                let ontology_path = root.join(&config.ontology.source);
                let ttl = std::fs::read_to_string(&ontology_path).map_err(|e| {
                    exec_err(format!(
                        "ontology `{}` unreadable: {e}",
                        ontology_path.display()
                    ))
                })?;
                engine.insert_turtle(&ttl).map_err(exec_err)?;
                let packs = crate::pack::resolve(&config, root).map_err(exec_err)?;
                for pack in &packs {
                    let pack_ttl = std::fs::read_to_string(&pack.ontology_path).map_err(|e| {
                        exec_err(format!(
                            "pack `{}`: ontology `{}` unreadable: {e}",
                            pack.name,
                            pack.ontology_path.display()
                        ))
                    })?;
                    engine.insert_turtle(&pack_ttl).map_err(exec_err)?;
                }
                (config.law.rules, config.law.shapes)
            }
            crate::schema_dispatch::ParsedGgenToml::DeclarativeRules(manifest) => {
                let ontology_path = root.join(&manifest.ontology.source);
                let ttl = std::fs::read_to_string(&ontology_path).map_err(|e| {
                    exec_err(format!(
                        "ontology `{}` unreadable: {e}",
                        ontology_path.display()
                    ))
                })?;
                engine.insert_turtle(&ttl).map_err(exec_err)?;
                for import in &manifest.ontology.imports {
                    let import_path = root.join(import);
                    let import_ttl = std::fs::read_to_string(&import_path).map_err(|e| {
                        exec_err(format!(
                            "ontology import `{}` unreadable: {e}",
                            import_path.display()
                        ))
                    })?;
                    engine.insert_turtle(&import_ttl).map_err(exec_err)?;
                }
                (
                    manifest.law.rules.clone(),
                    manifest.validation.shacl.clone(),
                )
            }
        };

    let mut loaded: Vec<(String, usize)> = Vec::new();
    for rel in &law_rules {
        let rule_path = root.join(rel);
        let src = std::fs::read_to_string(&rule_path).map_err(|e| {
            exec_err(format!(
                "rule file `{}` unreadable: {e}",
                rule_path.display()
            ))
        })?;
        let n = engine.load_rules(&src).map_err(exec_err)?;
        loaded.push((rel.display().to_string(), n));
    }
    Ok((law_shapes, engine, loaded))
}

/// `ggen law load` — load every `[law].rules` file and report the rule
/// count per file. Refuses (non-zero exit) on the first unparseable rule
/// document; never materializes.
///
/// # Errors
/// Missing/invalid `ggen.toml`, or any `[law].rules` file that is missing,
/// unreadable, or fails to parse.
pub fn handle_law_load() -> Result<serde_json::Value> {
    let root = project_root()?;
    let (_, _, loaded) = build_law_engine(&root)?;
    let files: serde_json::Map<String, serde_json::Value> = loaded
        .iter()
        .map(|(f, n)| (f.clone(), serde_json::json!(n)))
        .collect();
    Ok(serde_json::json!({
        "rule_files": loaded.len(),
        "rules_per_file": files,
    }))
}

/// `ggen law validate` — materialize, then run every `[law].shapes` SHACL
/// gate and the denial check; any violation exits non-zero with a typed
/// FM-LAW message.
///
/// # Errors
/// Missing/invalid `ggen.toml`, an unparseable `[law].rules`/`[law].shapes`
/// file, a denial-rule violation, or any non-conforming SHACL shapes file
/// (naming the offending violations).
pub fn handle_law_validate() -> Result<serde_json::Value> {
    use crate::graph::GraphEngine as _;
    let root = project_root()?;
    let (law_shapes, engine, _) = build_law_engine(&root)?;
    let outcome = engine.materialize().map_err(exec_err)?;
    let denials = engine.check_denials().map_err(exec_err)?;
    if !denials.is_empty() {
        return Err(exec_err(AppError::fm_law(
            11,
            format!(
                "{} denial rule(s) violated after materialization: {}",
                denials.len(),
                denials.join("; ")
            ),
        )));
    }
    let mut shapes_checked = 0usize;
    for rel in &law_shapes {
        let shape_path = root.join(rel);
        let shapes_ttl = std::fs::read_to_string(&shape_path).map_err(|e| {
            exec_err(format!(
                "SHACL shapes file `{}` unreadable: {e}",
                shape_path.display()
            ))
        })?;
        let report = engine.validate_shacl(&shapes_ttl).map_err(exec_err)?;
        if !report.conforms {
            return Err(exec_err(AppError::fm_law(
                13,
                format!(
                    "SHACL shapes `{}` report {} violation(s): {}",
                    rel.display(),
                    report.violations.len(),
                    report.violations.join("; ")
                ),
            )));
        }
        shapes_checked += 1;
    }
    Ok(serde_json::json!({
        "conforms": true,
        "rules_loaded": outcome.rules_loaded,
        "derived": outcome.derived.len(),
        "denials": 0,
        "shapes_checked": shapes_checked,
    }))
}

/// `ggen law derive` — materialize `[law].rules` to fixpoint and report
/// the derived-triple count plus the post-materialization graph hash.
///
/// # Errors
/// Missing/invalid `ggen.toml`, or any `[law].rules` file that is missing,
/// unreadable, or fails to parse.
pub fn handle_law_derive() -> Result<serde_json::Value> {
    use crate::graph::GraphEngine as _;
    let root = project_root()?;
    let (_, engine, _) = build_law_engine(&root)?;
    let outcome = engine.materialize().map_err(exec_err)?;
    let hash = engine.state_hash().map_err(exec_err)?;
    Ok(serde_json::json!({
        "rules_loaded": outcome.rules_loaded,
        "derived": outcome.derived.len(),
        "graph_hash": crate::sync::hex32(&hash),
    }))
}

/// `ggen law explain` — materialize and report which facts the rules
/// derived: rules-loaded count and the full derived-triple diff.
///
/// # Errors
/// Missing/invalid `ggen.toml`, or any `[law].rules` file that is missing,
/// unreadable, or fails to parse.
pub fn handle_law_explain() -> Result<serde_json::Value> {
    use crate::graph::GraphEngine as _;
    let root = project_root()?;
    let (_, engine, loaded) = build_law_engine(&root)?;
    let outcome = engine.materialize().map_err(exec_err)?;
    let files: serde_json::Map<String, serde_json::Value> = loaded
        .iter()
        .map(|(f, n)| (f.clone(), serde_json::json!(n)))
        .collect();
    Ok(serde_json::json!({
        "rules_loaded": outcome.rules_loaded,
        "rules_per_file": files,
        "derived": outcome.derived.len(),
        "derived_triples": outcome.derived,
    }))
}

/// `ggen law export` — dump the fully materialized graph as canonical
/// N-Triples with its BLAKE3 state hash.
///
/// # Errors
/// Missing/invalid `ggen.toml`, or any `[law].rules` file that is missing,
/// unreadable, or fails to parse.
pub fn handle_law_export() -> Result<serde_json::Value> {
    use std::fmt::Write as _;

    use crate::graph::GraphEngine as _;
    let root = project_root()?;
    let (_, engine, _) = build_law_engine(&root)?;
    engine.materialize().map_err(exec_err)?;
    let lines = engine.canonical_quads().map_err(exec_err)?;
    let hash = engine.state_hash().map_err(exec_err)?;
    let ntriples: String = lines.iter().fold(String::new(), |mut doc, l| {
        let _ = writeln!(doc, "{l} .");
        doc
    });
    Ok(serde_json::json!({
        "triples": lines.len(),
        "graph_hash": crate::sync::hex32(&hash),
        "ntriples": ntriples,
    }))
}