anda_kip 0.13.1

A Rust SDK of KIP 2.0 (Knowledge Interaction Protocol) for building sustainable AI knowledge memory systems.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
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
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
//! # The executable KIP 2.0 AST
//!
//! This is the tree a KIP engine consumes: every construct is already collapsed
//! to the one shape it means, with the open-ended parts of the grammar closed.
//!
//! - a predicate is an atom or a path, not a nested alternation/quantifier tree;
//! - a filter is a comparison, a logical node, a negation, or a call to one of
//!   the registered functions, not a general expression tree;
//! - a variable is a name and a path of steps, not a chain of member accesses;
//! - `ASSERT` is gone: the parser desugars it into the parts it is defined as.
//!
//! A consumer matching on these enums is total: there is no "some other function
//! name" case to defend against, because the parser rejected it.
//!
//! The encoding is serde's default externally-tagged enum representation, which
//! makes this tree field-for-field identical to the `exec-ast.ts` contract of the
//! reference toolkit `@ldclabs/kip-lang`, so the two implementations can be
//! differentially tested against one another.

use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt, str::FromStr};

pub use serde_json::{Map, Number};

/// Alias for [`serde_json::Value`], used wherever KIP carries opaque JSON.
pub type Json = serde_json::Value;

/// An `object_pattern` — an open, schema-validated field map.
///
/// Unlike KIP 1.x, v2 does not close this to a fixed set of identity forms:
/// which fields identify an element is Schema's decision, not the grammar's.
pub type ObjectMatcher = BTreeMap<String, MatchValue>;

/// Assignment pairs, kept ordered so lowering stays deterministic.
pub type Assignments = Vec<(String, MutationValue)>;

/// A `{...}` block whose values may still contain unbound parameters.
pub type BoundObject = BTreeMap<String, BoundValue>;

// ---------------------------------------------------------------------------
// Values
// ---------------------------------------------------------------------------

/// A KIP literal.
///
/// Arrays and objects are not baseline Core Literals (Spec §9.2); they appear
/// here only as the option/assignment payloads that the grammar admits.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub enum KipValue {
    /// The absence of a value (Spec §9.5).
    #[default]
    Null,
    /// A boolean.
    Bool(bool),
    /// A finite JSON number (Spec §9.3).
    Number(Number),
    /// A UTF-8 string.
    String(String),
    /// A JSON array, legal only in payload positions.
    Array(Vec<KipValue>),
    /// A JSON object, legal only in payload positions.
    Object(BTreeMap<String, KipValue>),
}

impl fmt::Display for KipValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", Json::from(self.clone()))
    }
}

impl From<KipValue> for Json {
    fn from(value: KipValue) -> Self {
        match value {
            KipValue::Null => Json::Null,
            KipValue::Bool(b) => Json::Bool(b),
            KipValue::Number(n) => Json::Number(n),
            KipValue::String(s) => Json::String(s),
            KipValue::Array(items) => Json::Array(items.into_iter().map(Json::from).collect()),
            KipValue::Object(fields) => Json::Object(
                fields
                    .into_iter()
                    .map(|(k, v)| (k, Json::from(v)))
                    .collect(),
            ),
        }
    }
}

impl TryFrom<Json> for KipValue {
    type Error = String;

    fn try_from(value: Json) -> Result<Self, Self::Error> {
        Ok(match value {
            Json::Null => KipValue::Null,
            Json::Bool(b) => KipValue::Bool(b),
            Json::Number(n) => {
                // Only finite numbers are valid KIP literals (Spec §9.3);
                // serde_json cannot represent a non-finite number, but an
                // arbitrary-precision build can, so the check is not vacuous.
                if n.as_f64().is_some_and(|f| !f.is_finite()) {
                    return Err(format!("{n} is not a finite KIP number"));
                }
                KipValue::Number(n)
            }
            Json::String(s) => KipValue::String(s),
            Json::Array(items) => KipValue::Array(
                items
                    .into_iter()
                    .map(KipValue::try_from)
                    .collect::<Result<_, _>>()?,
            ),
            Json::Object(fields) => KipValue::Object(
                fields
                    .into_iter()
                    .map(|(k, v)| KipValue::try_from(v).map(|v| (k, v)))
                    .collect::<Result<_, _>>()?,
            ),
        })
    }
}

impl From<&str> for KipValue {
    fn from(s: &str) -> Self {
        KipValue::String(s.to_string())
    }
}

impl From<String> for KipValue {
    fn from(s: String) -> Self {
        KipValue::String(s)
    }
}

impl From<bool> for KipValue {
    fn from(b: bool) -> Self {
        KipValue::Bool(b)
    }
}

impl From<i64> for KipValue {
    fn from(n: i64) -> Self {
        KipValue::Number(Number::from(n))
    }
}

impl From<u64> for KipValue {
    fn from(n: u64) -> Self {
        KipValue::Number(Number::from(n))
    }
}

/// A `data_value`: a value that may still contain unbound parameters.
///
/// The grammar admits `parameter` at every depth of an array or object, so no
/// assignment, option block or epistemic setting is plain JSON. A subtree with
/// nothing left to bind collapses to [`BoundValue::Value`]; anything else keeps
/// its shape so the runtime envelope can fill the holes without touching text.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum BoundValue {
    /// A fully literal subtree.
    Value(KipValue),
    /// A `:parameter`, bound from the request envelope.
    Param(String),
    /// A `?handle` naming an element created by this mutation plan.
    Handle(String),
    /// A read of the target element's own field.
    Variable(DotPathVar),
    /// An array with at least one unbound element.
    Array(Vec<BoundValue>),
    /// An object with at least one unbound member, kept ordered.
    Object(Vec<(String, BoundValue)>),
}

/// A value slot the grammar spells `parameter | literal`.
///
/// KIP 2.0 parameters are structurally bound data, never string-spliced, so an
/// unbound `:name` survives lowering as a [`Scalar::Param`] for the runtime
/// envelope to fill — it is not an error and never becomes text.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum Scalar {
    /// A literal written inline.
    Literal(KipValue),
    /// A `:parameter` to be bound at execution time.
    Param(String),
}

/// A schema symbol: `string_literal | parameter`.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum SymbolRef {
    /// A quoted schema symbol, resolved against the Schema Environment.
    Name(String),
    /// A `:parameter` standing for a schema symbol.
    Param(String),
}

/// A mutation target: `variable | parameter | string_literal`.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum ElementRef {
    /// A `?handle` bound by this mutation plan or by the statement's WHERE.
    Handle(String),
    /// A `:parameter` carrying an element reference.
    Param(String),
    /// A literal element id.
    Id(String),
}

/// `?var` plus a resolved path, e.g. `?x.facets["MnemonicState"].salience`.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub struct DotPathVar {
    /// The bare variable name, without the `?` sigil.
    pub var: String,
    /// The resolved access path.
    pub path: Vec<PathStep>,
}

impl fmt::Display for DotPathVar {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "?{}", self.var)?;
        for step in &self.path {
            match step {
                PathStep::Field(name) => write!(f, ".{name}")?,
                PathStep::Key(key) => write!(f, "[{}]", Json::String(key.clone()))?,
            }
        }
        Ok(())
    }
}

/// A dot step names a field; an index step keys into a map-valued field.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum PathStep {
    /// `.name`
    Field(String),
    /// `["key"]`
    Key(String),
}

// ---------------------------------------------------------------------------
// Shared terms
// ---------------------------------------------------------------------------

/// A `predicate_atom` — the exact predicate slot.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum PredAtom {
    /// A `?variable` predicate, legal only in read patterns.
    Variable(String),
    /// A quoted predicate symbol.
    Literal(String),
    /// A `:parameter` standing for a predicate.
    Param(String),
}

/// A hop range written as `{n}` / `{n,}` / `{n,m}`.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub struct HopRange {
    /// Minimum hop count.
    pub min: u32,
    /// Maximum hop count; `None` means unbounded.
    pub max: Option<u32>,
}

/// One atom of a raw predicate path, with its optional quantifier.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub struct PredPathAtom {
    /// The predicate to traverse.
    pub predicate: PredAtom,
    /// The hop quantifier, when one was written.
    pub hops: Option<HopRange>,
}

/// The predicate slot of a Proposition expression.
///
/// [`PredTerm::Atom`] is the plain predicate every language accepts.
/// [`PredTerm::Path`] carries the KQL-only traversal forms — alternation and hop
/// quantifiers — which never propagate belief and are rejected in KML and
/// EXPORT selections (Spec §45).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum PredTerm {
    /// One exact predicate.
    Atom(PredAtom),
    /// A traversal path of one or more alternatives.
    Path(Vec<PredPathAtom>),
}

/// One endpoint of a tuple.
///
/// A term may itself be a tuple: KIP states things about statements.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum Term {
    /// A `?variable` binding.
    Variable(String),
    /// A `:parameter`.
    Param(String),
    /// A literal value.
    Literal(KipValue),
    /// An inline `{field: value}` matcher.
    Match(ObjectMatcher),
    /// A nested Proposition expression.
    ///
    /// Boxed to break the `Term → Proposition → Triple → Term` cycle: KIP states
    /// things about statements, so the recursion is the point, not an accident.
    /// `Box` is transparent to serde, so the encoding is unchanged.
    Proposition(Box<PropositionMatcher>),
}

/// A value inside an [`ObjectMatcher`].
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum MatchValue {
    /// A `?variable` binding.
    Variable(String),
    /// A `:parameter`.
    Param(String),
    /// A literal value.
    Literal(KipValue),
    /// An array of match values.
    Array(Vec<MatchValue>),
    /// A nested matcher.
    Match(ObjectMatcher),
    /// A nested Proposition expression.
    Proposition(PropositionMatcher),
}

/// A `(subject, predicate, object)` tuple.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct PropositionTriple {
    /// The subject endpoint, always an Element reference.
    pub subject: Term,
    /// The predicate.
    pub predicate: PredTerm,
    /// The object endpoint.
    pub object: Term,
}

/// The Proposition expression slot (Spec §43.2).
///
/// [`PropositionMatcher::Tuple`] addresses a Proposition by structure,
/// [`PropositionMatcher::Id`] by record identity. Both live in the same slot,
/// which is why an id reference works everywhere a triple does — including as a
/// [`Term`] endpoint. `Id` is match-only: it never resolves-or-creates, so the
/// parser rejects it in `ENSURE PROPOSITION` and in the `ASSERT` sugar that
/// desugars through it.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum PropositionMatcher {
    /// Addressed by structure.
    Tuple(PropositionTriple),
    /// Addressed by record identity.
    Id(Scalar),
}

// ---------------------------------------------------------------------------
// Command
// ---------------------------------------------------------------------------

/// One parsed KIP command.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum Command {
    /// A KQL read.
    Kql(KqlQuery),
    /// A KML mutation transaction.
    Kml(KmlStatement),
    /// A META introspection command.
    Meta(MetaCommand),
}

impl Command {
    /// Whether executing this command can change durable state.
    ///
    /// The runtime classifies actual semantics rather than trusting a
    /// caller-supplied language label (Spec §73.1).
    pub fn is_mutation(&self) -> bool {
        matches!(self, Command::Kml(_))
    }
}

/// The language family a command belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CommandType {
    /// KQL — the read language.
    Kql,
    /// KML — the cognitive mutation language.
    Kml,
    /// META — introspection, grounding, verification, history, export.
    Meta,
    /// The command failed to parse, so its family is unknown.
    Unknown,
}

impl CommandType {
    /// Returns the command family for a parsed [`Command`].
    pub fn from(val: &Command) -> CommandType {
        match val {
            Command::Kql(_) => CommandType::Kql,
            Command::Kml(_) => CommandType::Kml,
            Command::Meta(_) => CommandType::Meta,
        }
    }
}

impl fmt::Display for CommandType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CommandType::Kql => write!(f, "KQL"),
            CommandType::Kml => write!(f, "KML"),
            CommandType::Meta => write!(f, "META"),
            CommandType::Unknown => write!(f, "UNKNOWN"),
        }
    }
}

impl FromStr for CommandType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "KQL" => Ok(CommandType::Kql),
            "KML" => Ok(CommandType::Kml),
            "META" => Ok(CommandType::Meta),
            _ => Ok(CommandType::Unknown),
        }
    }
}

impl Serialize for CommandType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for CommandType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        CommandType::from_str(&s).map_err(serde::de::Error::custom)
    }
}

// ---------------------------------------------------------------------------
// KQL
// ---------------------------------------------------------------------------

/// A `FIND ... WHERE ...` query.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct KqlQuery {
    /// The projection list.
    pub find_clause: FindClause,
    /// The solution patterns.
    pub where_clauses: Vec<WhereClause>,
    /// Cognitive history basis — what the Brain contained/believed then.
    pub as_of: Option<AsOf>,
    /// World-valid time — what was applicable then. An independent axis.
    pub for_time: Option<Scalar>,
    /// `WITH EPISTEMIC {...}` projection settings.
    pub epistemic: Option<BoundObject>,
    /// The sort keys.
    pub order_by: Option<Vec<OrderByItem>>,
    /// The result cap.
    pub limit: Option<Scalar>,
    /// The pagination cursor.
    pub cursor: Option<Scalar>,
}

/// `AS OF SEQ` — which cognitive history the read runs against (Spec §48.1).
///
/// Cognitive time is a sequence coordinate, and it is the only historical
/// axis: a transaction id resolves to its sequence through `DESCRIBE
/// TRANSACTION`, a wall-clock instant through `DESCRIBE SNAPSHOT AT TIME`, so
/// a historical read always names the exact coordinate it was served from.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum AsOf {
    /// A Space sequence coordinate.
    Seq(Scalar),
}

/// The projection list of a query.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct FindClause {
    /// One entry per projected column.
    pub expressions: Vec<FindExpression>,
}

/// One projected column.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum FindExpression {
    /// A variable or dot path.
    Variable(DotPathVar),
    /// An aggregate over a variable or dot path.
    Aggregation {
        /// The aggregate function.
        func: AggregationFunction,
        /// The aggregated variable.
        var: DotPathVar,
        /// Whether `DISTINCT` was written.
        distinct: bool,
    },
}

/// The aggregate functions KQL registers (Spec §44.6).
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum AggregationFunction {
    /// `COUNT`
    Count,
    /// `SUM`
    Sum,
    /// `AVG`
    Avg,
    /// `MIN`
    Min,
    /// `MAX`
    Max,
}

/// One `ORDER BY` key.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct OrderByItem {
    /// The sorted variable or dot path.
    pub variable: DotPathVar,
    /// The sort direction; `ASC` when unwritten.
    pub direction: OrderDirection,
    /// The aggregate applied before sorting, when the key is an aggregate.
    pub aggregation: Option<AggregationFunction>,
    /// Deduplicate the aggregate's non-null inputs before sorting.
    #[serde(default, skip_serializing_if = "order_distinct_is_false")]
    pub distinct: bool,
}

fn order_distinct_is_false(value: &bool) -> bool {
    !value
}

/// Sort direction.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum OrderDirection {
    /// Ascending, the default.
    #[default]
    Asc,
    /// Descending.
    Desc,
}

/// One pattern inside a `WHERE` block.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum WhereClause {
    /// `?c CONCEPT {...}` — a Concept by its fields.
    Concept {
        /// The bound variable.
        variable: String,
        /// The field matcher.
        matcher: ObjectMatcher,
    },
    /// `?p PROPOSITION (s, p, o)` — a raw Proposition, truth-neutral.
    Proposition {
        /// The bound variable, when one was written.
        variable: Option<String>,
        /// The Proposition expression.
        matcher: PropositionMatcher,
    },
    /// `?a ASSERTION {...}` — one actor's epistemic commitment.
    Assertion {
        /// The bound variable.
        variable: String,
        /// The field matcher.
        matcher: ObjectMatcher,
    },
    /// `?e EVIDENCE {...}` — an observation record.
    Evidence {
        /// The bound variable.
        variable: String,
        /// The field matcher.
        matcher: ObjectMatcher,
    },
    /// `?act ACTIVITY {...}` — a provenance record.
    Activity {
        /// The bound variable.
        variable: String,
        /// The field matcher.
        matcher: ObjectMatcher,
    },
    /// `?edge STRUCTURAL (?src, "has_step", ?dst)` — record topology.
    ///
    /// Never a semantic Proposition: a claim *about* a structural relation is a
    /// separate Proposition + Assertion (Spec §17.3).
    Structural {
        /// The bound variable, when one was written.
        variable: Option<String>,
        /// The referencing element.
        subject: Term,
        /// The structural field.
        field: SymbolRef,
        /// The referenced element.
        object: Term,
    },
    /// `?b BELIEF (...)` — an Epistemic Projection, virtual and read-only.
    Belief {
        /// The bound variable.
        variable: String,
        /// What is projected.
        target: BeliefTarget,
    },
    /// `?slot BELIEF SLOT (?s, "pred")` — candidates and conflicts for one slot.
    BeliefSlot {
        /// The bound variable.
        variable: String,
        /// The slot subject.
        subject: Term,
        /// The slot predicate.
        predicate: PredAtom,
    },
    /// `FILTER (...)`
    Filter {
        /// The filter expression.
        expression: FilterExpression,
    },
    /// `NOT { ... }`
    Not(Vec<WhereClause>),
    /// `OPTIONAL { ... }`
    Optional(Vec<WhereClause>),
    /// `UNION { ... }`
    Union(Vec<WhereClause>),
}

/// What a `BELIEF` projects.
///
/// `BELIEF (...)` is the Proposition expression slot, so the id form that names
/// a Proposition in a pattern names it here too (Spec §43.2 / §46.1). The inline
/// tuple always carries an exact predicate: projection never walks a raw path
/// (Spec §45).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum BeliefTarget {
    /// An already-bound Proposition variable.
    Proposition(String),
    /// A Proposition named by id.
    Id(Scalar),
    /// A tuple stated inline.
    Tuple(PropositionTriple),
}

/// A `FILTER` expression.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum FilterExpression {
    /// A binary comparison.
    Comparison {
        /// Left operand.
        left: FilterOperand,
        /// The operator.
        operator: ComparisonOperator,
        /// Right operand.
        right: FilterOperand,
    },
    /// A logical combination.
    Logical {
        /// Left branch.
        left: Box<FilterExpression>,
        /// The operator.
        operator: LogicalOperator,
        /// Right branch.
        right: Box<FilterExpression>,
    },
    /// `!expr`
    Not(Box<FilterExpression>),
    /// A call to a registered filter function.
    Function {
        /// The function.
        func: FilterFunction,
        /// The arguments.
        args: Vec<FilterOperand>,
    },
}

/// An operand of a filter comparison or function call.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum FilterOperand {
    /// A variable or dot path.
    Variable(DotPathVar),
    /// A literal value.
    Literal(KipValue),
    /// A `:parameter`.
    Param(String),
    /// A bracketed list, e.g. the second argument of `IN`.
    List(Vec<FilterOperand>),
    /// A negated operand.
    Negate(Box<FilterOperand>),
}

/// Comparison operators.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum ComparisonOperator {
    /// `==`
    Equal,
    /// `!=`
    NotEqual,
    /// `<`
    LessThan,
    /// `>`
    GreaterThan,
    /// `<=`
    LessEqual,
    /// `>=`
    GreaterEqual,
}

/// Logical operators.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum LogicalOperator {
    /// `&&`
    And,
    /// `||`
    Or,
}

/// The filter functions KIP 2.0 registers by name.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum FilterFunction {
    /// `CONTAINS(?x, "sub")`
    Contains,
    /// `STARTS_WITH(?x, "pre")`
    StartsWith,
    /// `ENDS_WITH(?x, "suf")`
    EndsWith,
    /// `REGEX(?x, "pattern")`
    Regex,
    /// `IN(?expr, [a, b])` — membership. A function, not a comparison operator.
    In,
    /// `IS_NULL(?x)`
    IsNull,
    /// `IS_NOT_NULL(?x)`
    IsNotNull,
    /// `IS_LITERAL(?x)`
    IsLiteral,
    /// `IS_ELEMENT(?x)`
    IsElement,
    /// `IS_KIND(?x, "Concept")`
    IsKind,
    /// `LITERAL_TYPE(?x)`
    LiteralType,
}

// ---------------------------------------------------------------------------
// KML
// ---------------------------------------------------------------------------

/// One atomic cognitive transition.
///
/// A KML mutation becomes durable only via a Transaction, so a statement written
/// on its own is still a one-clause transaction. `explicit_transaction` records
/// which spelling the source used without changing that meaning.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct KmlStatement {
    /// Whether the source wrote `MUTATE { ... }`.
    pub explicit_transaction: bool,
    /// The mutations, in source order.
    pub clauses: Vec<MutationClause>,
}

/// One mutation inside a transaction.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum MutationClause {
    /// `CREATE CONCEPT ?h { ... }`
    CreateConcept(ConceptCreate),
    /// `UPSERT CONCEPT ?h { ... }`
    UpsertConcept(ConceptUpsert),
    /// `ENSURE PROPOSITION [?h] (s, p, o)`
    EnsureProposition(EnsureProposition),
    /// `CREATE EVIDENCE ?h { ... }`
    CreateEvidence(RecordCreate),
    /// `CREATE ASSERTION ?h { ... }`
    CreateAssertion(RecordCreate),
    /// `CREATE ACTIVITY ?h { ... }`
    CreateActivity(RecordCreate),
    /// `UPDATE target ...`
    Update(UpdateStatement),
    /// `TRANSITION target TO "state" [BY ref] ...` — the one lifecycle statement.
    Transition(Transition),
    /// `SET RETENTION target { ... }`
    SetRetention(SetRetention),
    /// `PURGE target ... CONFIRM "PURGE"`
    Purge(PurgeStatement),
    /// `PURGE PAYLOAD target ... CONFIRM "PURGE"`
    PurgePayload(PurgePayloadStatement),
    /// `MERGE CONCEPT source INTO target`
    MergeConcept(MergeConcept),
}

impl MutationClause {
    /// The local handle this clause binds, when it binds one.
    pub fn handle(&self) -> Option<&str> {
        match self {
            MutationClause::CreateConcept(c) => Some(c.handle.as_str()),
            MutationClause::UpsertConcept(c) => Some(c.handle.as_str()),
            MutationClause::CreateEvidence(c)
            | MutationClause::CreateAssertion(c)
            | MutationClause::CreateActivity(c) => Some(c.handle.as_str()),
            MutationClause::EnsureProposition(c) => c.handle.as_deref(),
            _ => None,
        }
    }
}

/// `CREATE CONCEPT` — a new Concept with engine-minted identity.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct ConceptCreate {
    /// The block-local handle this clause binds.
    pub handle: String,
    /// `TYPE "..."`
    pub r#type: Option<SymbolRef>,
    /// `CLIENT KEY ...` — retry-safe logical identity.
    pub client_key: Option<Scalar>,
    /// `NAME ...` — mutable grounding state, never identity.
    pub name: Option<Scalar>,
    /// `SET FIELDS { ... }`
    pub set_fields: Option<Assignments>,
    /// `SET ATTRIBUTES { ... }`
    pub set_attributes: Option<Assignments>,
    /// `SET FACET "..." { ... }`, one entry per facet.
    pub set_facets: Vec<FacetAssignment>,
    /// `SET STRUCTURAL { ... }`
    pub set_structural: Option<Vec<StructuralEdge>>,
}

/// `UPSERT CONCEPT` — resolve-or-create against a stable identity.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct ConceptUpsert {
    /// The block-local handle this clause binds.
    pub handle: String,
    /// `MATCH { ... }` — must carry `id` or `key`.
    pub r#match: Option<ObjectMatcher>,
    /// The trailing `EXPECT VERSION` guards, after the closing brace (§52.8).
    pub expect_versions: Vec<ExpectVersion>,
    /// `SET FIELDS { ... }`
    pub set_fields: Option<Assignments>,
    /// `SET ATTRIBUTES { ... }`
    pub set_attributes: Option<Assignments>,
    /// `SET FACET "..." { ... }`
    pub set_facets: Vec<FacetAssignment>,
    /// `UNSET ATTRIBUTES { ... }`
    pub unset_attributes: Option<Vec<String>>,
    /// `UNSET FACET "..." { ... }`
    pub unset_facets: Vec<FacetUnset>,
    /// `SET STRUCTURAL { ... }`
    pub set_structural: Option<Vec<StructuralEdge>>,
    /// `UNSET STRUCTURAL { ... }`
    pub unset_structural: Option<Vec<StructuralRemoval>>,
}

/// `CREATE EVIDENCE` / `ASSERTION` / `ACTIVITY` share one shape.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct RecordCreate {
    /// The block-local handle this clause binds.
    pub handle: String,
    /// `CLIENT KEY ...`
    pub client_key: Option<Scalar>,
    /// `SET FIELDS { ... }`
    pub set_fields: Option<Assignments>,
    /// `SET FACET "..." { ... }`
    pub set_facets: Vec<FacetAssignment>,
    /// `SET STRUCTURAL { ... }`
    pub set_structural: Option<Vec<StructuralEdge>>,
}

/// `ENSURE PROPOSITION` — resolve-or-create a truth-neutral tuple.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct EnsureProposition {
    /// The block-local handle, when one was written.
    pub handle: Option<String>,
    /// The subject endpoint.
    pub subject: Term,
    /// The exact predicate.
    pub predicate: PredAtom,
    /// The object endpoint.
    pub object: Term,
    /// The trailing `EXPECT VERSION` guards; `EXPECT VERSION 0` is the
    /// create-only form (§35.2).
    pub expect_versions: Vec<ExpectVersion>,
}

/// `EXPECT VERSION n [OF plane]` — one optimistic-concurrency guard (Spec §35.1).
///
/// Without a plane the guard compares the element's `_system.version`; with
/// one, that plane's own counter in `_system.plane_versions`, so a Facet sweep
/// and an attribute write on the same element do not spoil each other's guard.
/// A statement carries at most one guard per plane, and every mutation carries
/// them in the same place: last (§52.8).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct ExpectVersion {
    /// The version the caller believes the element (or plane) is at.
    pub version: Scalar,
    /// The version plane, or `None` for the element's whole version.
    pub plane: Option<VersionPlane>,
}

impl ExpectVersion {
    /// A guard on the element's whole `_system.version`.
    pub fn element(version: Scalar) -> Self {
        Self {
            version,
            plane: None,
        }
    }

    /// The deduplication key of this guard's plane: two guards with the same
    /// key cannot both be meant.
    pub fn plane_key(&self) -> String {
        match &self.plane {
            None => "element".to_string(),
            Some(VersionPlane::Attributes) => "attributes".to_string(),
            Some(VersionPlane::Structural) => "structural".to_string(),
            Some(VersionPlane::Retention) => "retention".to_string(),
            Some(VersionPlane::Facet(SymbolRef::Name(name))) => format!("facet:{name}"),
            Some(VersionPlane::Facet(SymbolRef::Param(name))) => format!("facet::{name}"),
        }
    }
}

/// The version planes `EXPECT VERSION ... OF` may name (Spec §6.3, §35.1).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum VersionPlane {
    /// Fields and attributes.
    Attributes,
    /// Structural References.
    Structural,
    /// The retention record.
    Retention,
    /// One Facet, by symbol.
    Facet(SymbolRef),
}

/// One `SET FACET` clause.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct FacetAssignment {
    /// The facet symbol.
    pub facet: SymbolRef,
    /// The assigned members.
    pub values: Assignments,
}

/// One `UNSET FACET` clause.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct FacetUnset {
    /// The facet symbol.
    pub facet: SymbolRef,
    /// The removed member names.
    pub fields: Vec<String>,
}

/// One structural edge, optionally placed.
///
/// The options object carries edge options; `index` is meaningful only on a
/// field declared ordered, and index order is never causality (Spec §17.4).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct StructuralEdge {
    /// The structural field.
    pub field: SymbolRef,
    /// The referenced element.
    pub value: MutationValue,
    /// Edge options, when written.
    pub options: Option<BoundObject>,
}

/// `UNSET STRUCTURAL { (field, target) }` — one reference to remove.
///
/// The `SET STRUCTURAL` edge without options: removal is per reference, ordered
/// fields re-densify, cardinality is validated at commit (Spec §17.5).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct StructuralRemoval {
    /// The structural field.
    pub field: SymbolRef,
    /// The referenced element to remove.
    pub value: MutationValue,
}

/// A KML right-hand side: a bound value, or arithmetic over the target's *own*
/// fields.
///
/// References to any other variable are rejected during lowering, which is what
/// lets each matched element be updated from its own row without a join.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum MutationValue {
    /// A fully literal subtree.
    Value(KipValue),
    /// A `:parameter`.
    Param(String),
    /// A `?handle` naming an element created by this mutation plan.
    Handle(String),
    /// A read of the target element's own field.
    Variable(DotPathVar),
    /// An array with at least one unbound element.
    Array(Vec<BoundValue>),
    /// An object with at least one unbound member.
    Object(Vec<(String, BoundValue)>),
    /// A deterministic update expression.
    Expr(UpdateExpr),
}

impl From<BoundValue> for MutationValue {
    fn from(value: BoundValue) -> Self {
        match value {
            BoundValue::Value(v) => MutationValue::Value(v),
            BoundValue::Param(p) => MutationValue::Param(p),
            BoundValue::Handle(h) => MutationValue::Handle(h),
            BoundValue::Variable(v) => MutationValue::Variable(v),
            BoundValue::Array(items) => MutationValue::Array(items),
            BoundValue::Object(fields) => MutationValue::Object(fields),
        }
    }
}

/// A deterministic arithmetic expression over the target's own fields.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum UpdateExpr {
    /// A read of the target element's own field.
    Variable(DotPathVar),
    /// A numeric literal.
    Number(Number),
    /// A `:parameter`.
    Param(String),
    /// A call to a registered update function.
    Function {
        /// The function.
        func: UpdateFunction,
        /// The arguments.
        args: Vec<UpdateExpr>,
    },
}

/// The deterministic update functions KIP 2.0 registers (Spec §59).
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum UpdateFunction {
    /// `ADD(a, b)`
    Add,
    /// `MUL(a, b)`
    Mul,
    /// `CLAMP(x, lo, hi)`
    Clamp,
    /// `COALESCE(a, b)`
    Coalesce,
}

impl UpdateFunction {
    /// The exact number of arguments this function takes.
    pub fn arity(&self) -> usize {
        match self {
            UpdateFunction::Add | UpdateFunction::Mul | UpdateFunction::Coalesce => 2,
            UpdateFunction::Clamp => 3,
        }
    }
}

/// `UPDATE` reaches mutable state only.
///
/// Proposition tuples, Assertion epistemic payload, Evidence payload, terminal
/// Activity topology, `_system` and Governance are all out of reach; the parser
/// rejects those targets rather than letting an engine discover them.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct UpdateStatement {
    /// The element to update.
    pub target: ElementRef,
    /// The actions, in source order.
    pub actions: Vec<UpdateAction>,
    /// `None` when the statement names its target directly and omits WHERE —
    /// the same shape as `TRANSITION` and the removal family (Spec §58).
    pub where_clauses: Option<Vec<WhereClause>>,
    /// The bound on how many matched elements may be updated.
    pub limit: Option<Scalar>,
    /// The trailing `EXPECT VERSION` guards (§52.8).
    pub expect_versions: Vec<ExpectVersion>,
}

/// One action of an `UPDATE`.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum UpdateAction {
    /// `SET FIELDS { ... }`
    SetFields(Assignments),
    /// `SET ATTRIBUTES { ... }`
    SetAttributes(Assignments),
    /// `SET FACET "..." { ... }`
    SetFacet(FacetAssignment),
    /// `UNSET ATTRIBUTES { ... }`
    UnsetAttributes(Vec<String>),
    /// `UNSET FACET "..." { ... }`
    UnsetFacet(FacetUnset),
    /// `SET STRUCTURAL { ... }`
    SetStructural(Vec<StructuralEdge>),
    /// `UNSET STRUCTURAL { ... }`
    UnsetStructural(Vec<StructuralRemoval>),
}

/// The lifecycle states `TRANSITION ... TO` may name (Spec §52.5).
///
/// Which states fit which target kind — and which current state a move is
/// legal from — is the engine's check (`InvalidLifecycleTransition`); what the
/// language fixes is the vocabulary, which is why the list lives here rather
/// than in a Schema Package.
pub mod transition_state {
    /// The assertor withdraws the claim (§57.3). Assertion only.
    pub const RETRACTED: &str = "retracted";
    /// The claim was wrong; revision lineage (§57.4). Assertion only, `BY` the
    /// newer Assertion.
    pub const SUPERSEDED: &str = "superseded";
    /// Wrong record; correction lineage (§57.2). Evidence only, `BY` the new
    /// Evidence.
    pub const CORRECTED: &str = "corrected";
    /// An Activity has started (§16).
    pub const RUNNING: &str = "running";
    /// An Activity ended successfully (§16.6).
    pub const COMPLETED: &str = "completed";
    /// An Activity ended in failure (§16.6).
    pub const FAILED: &str = "failed";
    /// An Activity was cancelled (§16.6).
    pub const CANCELLED: &str = "cancelled";
    /// Out of ordinary recall, history preserved (§60). Any element.
    pub const ARCHIVED: &str = "archived";
    /// Logical deletion, identity and audit preserved (§60). Any element.
    pub const TOMBSTONED: &str = "tombstoned";

    /// Every state the statement may name, in Spec §52.5 order.
    pub const ALL: &[&str] = &[
        RETRACTED, SUPERSEDED, CORRECTED, RUNNING, COMPLETED, FAILED, CANCELLED, ARCHIVED,
        TOMBSTONED,
    ];
    /// The moves that name the replacing element with `BY`.
    pub const WITH_BY: &[&str] = &[SUPERSEDED, CORRECTED];
    /// The Activity status moves: the only ones that may finalize fields or
    /// topology in the same statement.
    pub const ACTIVITY: &[&str] = &[RUNNING, COMPLETED, FAILED, CANCELLED];
}

/// `TRANSITION target TO "state" [BY ref] [SET FIELDS] [SET STRUCTURAL]
/// [WHERE] [LIMIT] {EXPECT VERSION}` — the one lifecycle statement (Spec §52.5).
///
/// The quoted state names the move and the engine validates it against the
/// target's kind and current lifecycle state, which is why there is no
/// `EXPECT STATE`: a move from the wrong state fails
/// `InvalidLifecycleTransition`, and a version guard covers the rest. `by`
/// carries the replacing element for `superseded` / `corrected`; `set_fields`
/// and `set_structural` finalize a pending Activity in the same transition.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct Transition {
    /// The element whose lifecycle moves.
    pub target: ElementRef,
    /// The state the move goes to.
    pub to: Scalar,
    /// The replacing element, for `superseded` / `corrected`.
    pub by: Option<ElementRef>,
    /// Terminal fields finalized in the same transition (Activity states only).
    pub set_fields: Option<Assignments>,
    /// Terminal topology finalized in the same transition (Activity states only).
    pub set_structural: Option<Vec<StructuralEdge>>,
    /// The selection block, when the target is bound by one.
    pub where_clauses: Option<Vec<WhereClause>>,
    /// The bound on how many matched elements may move.
    pub limit: Option<Scalar>,
    /// The trailing `EXPECT VERSION` guards (§52.8).
    pub expect_versions: Vec<ExpectVersion>,
}

impl Transition {
    /// The state the statement names, when it was written as a literal.
    ///
    /// `None` for a `:parameter`, which is bound at execution time.
    pub fn state(&self) -> Option<&str> {
        match &self.to {
            Scalar::Literal(KipValue::String(state)) => Some(state.as_str()),
            _ => None,
        }
    }

    /// Whether the statement finalizes fields or topology.
    pub fn finalizes(&self) -> bool {
        self.set_fields.is_some() || self.set_structural.is_some()
    }
}

/// `SET RETENTION` — storage lifecycle, never valid time (Spec §19).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct SetRetention {
    /// The element whose retention changes.
    pub target: ElementRef,
    /// The retention members.
    pub values: Assignments,
    /// The selection block, when the target is bound by one.
    pub where_clauses: Option<Vec<WhereClause>>,
    /// The bound on how many matched elements may be changed.
    pub limit: Option<Scalar>,
    /// The trailing `EXPECT VERSION` guards (§52.8).
    pub expect_versions: Vec<ExpectVersion>,
}

/// `PURGE` — physical erasure. The grammar freezes the confirmation spelling.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct PurgeStatement {
    /// The element to erase.
    pub target: ElementRef,
    /// The selection block, when the target is bound by one.
    pub where_clauses: Option<Vec<WhereClause>>,
    /// The bound on how many matched elements may be erased.
    pub limit: Option<Scalar>,
    /// The `EXPECT VERSION` guards, before the statement's own trailing words.
    pub expect_versions: Vec<ExpectVersion>,
    /// `REFERENCE POLICY ...`
    pub reference_policy: Option<Scalar>,
    /// Always the literal `PURGE`; the grammar freezes the spelling.
    pub confirm: String,
}

/// `PURGE PAYLOAD` — Evidence bytes only (Spec §60.6).
///
/// The element survives, so there is no `REFERENCE POLICY` clause: nothing can
/// dangle. The confirmation literal is the same `CONFIRM "PURGE"` element purge
/// takes, because the byte destruction is just as irreversible.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct PurgePayloadStatement {
    /// The Evidence whose payload is erased.
    pub target: ElementRef,
    /// The selection block, when the target is bound by one.
    pub where_clauses: Option<Vec<WhereClause>>,
    /// The bound on how many matched elements may be erased.
    pub limit: Option<Scalar>,
    /// The `EXPECT VERSION` guards, before `CONFIRM`.
    pub expect_versions: Vec<ExpectVersion>,
    /// Always the literal `PURGE`; the grammar freezes the spelling.
    pub confirm: String,
}

/// `MERGE CONCEPT` — non-destructive: the source stays addressable as merged
/// history (Spec §11.1).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct MergeConcept {
    /// The merged-away Concept.
    pub source: ElementRef,
    /// The surviving canonical Concept.
    pub into: ElementRef,
    /// A guard block; MERGE never selects its operands by pattern.
    pub where_clauses: Option<Vec<WhereClause>>,
    /// The trailing `EXPECT VERSION` guards, on the source (§52.8).
    pub expect_versions: Vec<ExpectVersion>,
}

// ---------------------------------------------------------------------------
// META
// ---------------------------------------------------------------------------

/// A META command. META is semantically read-only (Spec §63.2).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum MetaCommand {
    /// `DESCRIBE ...`
    Describe(DescribeTarget),
    /// `LIST ...`
    List(ListCommand),
    /// `SEARCH ...`
    Search(SearchCommand),
    /// `VERIFY ...`
    Verify {
        /// What kind of artifact is verified.
        target: VerifyTarget,
        /// The artifact operand.
        value: Scalar,
    },
    /// `VALIDATE ...`
    Validate(ValidateCommand),
    /// `PREVIEW ...`
    Preview(PreviewCommand),
    /// `HISTORY ...`
    History(HistoryCommand),
    /// `CHANGES ...`
    Changes(ChangesCommand),
    /// `EXPORT CAPSULE ...`
    ExportCapsule(ExportCapsuleCommand),
}

/// What a `DESCRIBE` introspects.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum DescribeTarget {
    /// `DESCRIBE PRIMER [MODE ...]`
    Primer {
        /// `"compact"` or `"full"`.
        mode: Option<Scalar>,
    },
    /// `DESCRIBE PROTOCOL`
    Protocol,
    /// `DESCRIBE CAPABILITIES` — projection capability included (§67).
    Capabilities,
    /// `DESCRIBE SPACE [...]`
    Space {
        /// The Space id; the current Space when absent.
        value: Option<Scalar>,
    },
    /// `DESCRIBE SCHEMA ENVIRONMENT [AS OF ...]`
    SchemaEnvironment {
        /// The history coordinate, when written.
        as_of: Option<AsOf>,
    },
    /// `DESCRIBE PACKAGE ...`
    Package(Scalar),
    /// `DESCRIBE TYPE ...`
    Type(Scalar),
    /// `DESCRIBE PREDICATE ...`
    Predicate(Scalar),
    /// `DESCRIBE FACET ...`
    Facet(Scalar),
    /// `DESCRIBE STRUCTURAL FIELD ...`
    StructuralField(Scalar),
    /// `DESCRIBE COMPATIBILITY FROM ... TO ...`
    Compatibility {
        /// The source version.
        from: Scalar,
        /// The target version.
        to: Scalar,
    },
    /// `DESCRIBE ERROR ...`
    Error(Scalar),
    /// `DESCRIBE TRANSACTION ...`
    Transaction(Scalar),
    /// `DESCRIBE TRANSACTION BY IDEMPOTENCY KEY ...`
    TransactionByIdempotencyKey(Scalar),
    /// `DESCRIBE SNAPSHOT [AS OF SEQ :s | AT TIME :t]` — the snapshot
    /// coordinate; `AT TIME` resolves an instant to a sequence (§68).
    Snapshot {
        /// The history coordinate, when written.
        as_of: Option<AsOf>,
        /// The wall-clock instant to resolve, when written. Never both.
        at_time: Option<Scalar>,
    },
    /// `DESCRIBE CAPSULE ...`
    Capsule(Scalar),
    /// `DESCRIBE EPISTEMIC POLICY [...]`
    EpistemicPolicy {
        /// The policy name; the active policy when absent.
        value: Option<Scalar>,
    },
    /// `DESCRIBE TRUST [...]`
    Trust {
        /// The trust subject; the whole trust state when absent.
        value: Option<Scalar>,
    },
    /// `DESCRIBE ACCESS [WITH {...}]`
    Access {
        /// The operation/resource/purpose input block.
        with: Option<BoundObject>,
    },
}

/// `LIST ...`
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct ListCommand {
    /// What is listed.
    pub target: ListTarget,
    /// `LIST SCHEMA PACKAGES STATUS ...` only.
    pub status: Option<Scalar>,
    /// `LIST DEPENDENTS :id` only — the traversal root.
    pub element: Option<Scalar>,
    /// `LIST DEPENDENTS ... DEPTH :n` only — the traversal bound (§63.5).
    pub depth: Option<Scalar>,
    /// The page size.
    pub limit: Option<Scalar>,
    /// The page cursor.
    pub cursor: Option<Scalar>,
}

/// What a `LIST` enumerates.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum ListTarget {
    /// `LIST SPACES`
    Spaces,
    /// `LIST SCHEMA PACKAGES`
    SchemaPackages,
    /// `LIST TYPES`
    Types,
    /// `LIST PREDICATES`
    Predicates,
    /// `LIST FACETS`
    Facets,
    /// `LIST STRUCTURAL FIELDS`
    StructuralFields,
    /// `LIST EPISTEMIC POLICIES`
    EpistemicPolicies,
    /// `LIST DEPENDENTS :id [DEPTH :n]` (§63.5)
    Dependents,
}

/// `SEARCH ...`
///
/// Grounding only: a SEARCH score is not confidence, and a miss is not absence.
/// The golden path is SEARCH → exact id → BELIEF/FIND.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct SearchCommand {
    /// What kind of element is searched.
    pub target: SearchTarget,
    /// The search term.
    pub term: Scalar,
    /// `WITH TYPE ...`
    pub with_type: Option<Scalar>,
    /// `WITH PREDICATE ...`
    pub with_predicate: Option<Scalar>,
    /// `MODE "keyword" | "semantic" | "hybrid"`
    pub mode: Option<Scalar>,
    /// `THRESHOLD ...`
    pub threshold: Option<Scalar>,
    /// Historical index basis, `AS OF SEQ`.
    pub as_of_seq: Option<Scalar>,
    /// The page size.
    pub limit: Option<Scalar>,
    /// The page cursor.
    pub cursor: Option<Scalar>,
}

/// What a `SEARCH` looks through.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum SearchTarget {
    /// `SEARCH CONCEPT`
    Concept,
    /// `SEARCH PROPOSITION`
    Proposition,
    /// `SEARCH ASSERTION`
    Assertion,
    /// `SEARCH EVIDENCE`
    Evidence,
    /// `SEARCH ACTIVITY`
    Activity,
    /// `SEARCH COGNITION`
    Cognition,
}

/// What a `VERIFY` checks.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum VerifyTarget {
    /// `VERIFY CAPSULE`
    Capsule,
    /// `VERIFY SCHEMA PACKAGE`
    SchemaPackage,
    /// `VERIFY RECEIPT`
    Receipt,
}

/// `VALIDATE ...`
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct ValidateCommand {
    /// What kind of input is validated.
    pub target: ValidateTarget,
    /// The input operand.
    pub value: Scalar,
    /// `WITH { ... }` validation options.
    pub options: Option<BoundObject>,
}

/// What a `VALIDATE` checks.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum ValidateTarget {
    /// `VALIDATE KQL`
    Kql,
    /// `VALIDATE KML`
    Kml,
    /// `VALIDATE CAPSULE`
    Capsule,
    /// `VALIDATE SCHEMA PACKAGE`
    SchemaPackage,
    /// `VALIDATE IMPORT PLAN`
    ImportPlan,
}

/// `PREVIEW ...` — computes an effect plan without committing (Spec §69.3).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum PreviewCommand {
    /// `PREVIEW KML ...`
    Kml(Scalar),
    /// `PREVIEW IMPORT CAPSULE ... INTO ...`
    ImportCapsule {
        /// The capsule artifact.
        capsule: Scalar,
        /// The destination Space.
        into: Scalar,
    },
}

/// `HISTORY ...`
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum HistoryCommand {
    /// `HISTORY ELEMENT ...`
    Element {
        /// The element id.
        value: Scalar,
        /// `FROM SEQ ...`
        from_seq: Option<Scalar>,
        /// `TO SEQ ...`
        to_seq: Option<Scalar>,
        /// The page size.
        limit: Option<Scalar>,
        /// The page cursor.
        cursor: Option<Scalar>,
    },
    /// `HISTORY SPACE ...`
    Space {
        /// `FROM SEQ ...`
        from_seq: Option<Scalar>,
        /// `TO SEQ ...`
        to_seq: Option<Scalar>,
        /// The page size.
        limit: Option<Scalar>,
        /// The page cursor.
        cursor: Option<Scalar>,
    },
}

/// `CHANGES ...`
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum ChangesCommand {
    /// `CHANGES SINCE ...`
    Since {
        /// The change cursor.
        cursor: Scalar,
        /// The page size.
        limit: Option<Scalar>,
    },
    /// `CHANGES AFTER SEQ ...`
    AfterSeq {
        /// The Space sequence.
        seq: Scalar,
        /// The page size.
        limit: Option<Scalar>,
    },
}

/// `EXPORT CAPSULE ...`
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct ExportCapsuleCommand {
    /// The capsule target reference.
    pub target: ElementRef,
    /// The selection block.
    pub where_clauses: Vec<WhereClause>,
    /// `WITH { ... }` export options.
    pub options: Option<BoundObject>,
    /// The history coordinate, when written.
    pub as_of: Option<AsOf>,
}

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

    #[test]
    fn kip_value_encodes_externally_tagged() {
        assert_eq!(serde_json::to_string(&KipValue::Null).unwrap(), r#""Null""#);
        assert_eq!(
            serde_json::to_string(&KipValue::Bool(true)).unwrap(),
            r#"{"Bool":true}"#
        );
        assert_eq!(
            serde_json::to_string(&KipValue::String("a".into())).unwrap(),
            r#"{"String":"a"}"#
        );
        assert_eq!(
            serde_json::to_string(&KipValue::Number(Number::from(3))).unwrap(),
            r#"{"Number":3}"#
        );
    }

    #[test]
    fn scalar_and_refs_match_the_reference_encoding() {
        assert_eq!(
            serde_json::to_string(&Scalar::Param("limit".into())).unwrap(),
            r#"{"Param":"limit"}"#
        );
        assert_eq!(
            serde_json::to_string(&Scalar::Literal(KipValue::Number(Number::from(10)))).unwrap(),
            r#"{"Literal":{"Number":10}}"#
        );
        assert_eq!(
            serde_json::to_string(&SymbolRef::Name("has_step".into())).unwrap(),
            r#"{"Name":"has_step"}"#
        );
        assert_eq!(
            serde_json::to_string(&ElementRef::Id("E-1".into())).unwrap(),
            r#"{"Id":"E-1"}"#
        );
    }

    #[test]
    fn unit_enums_encode_as_bare_strings() {
        assert_eq!(
            serde_json::to_string(&DescribeTarget::Protocol).unwrap(),
            r#""Protocol""#
        );
        assert_eq!(
            serde_json::to_string(&AggregationFunction::Count).unwrap(),
            r#""Count""#
        );
        assert_eq!(
            serde_json::to_string(&OrderDirection::Desc).unwrap(),
            r#""Desc""#
        );
    }

    #[test]
    fn assignments_encode_as_ordered_pairs() {
        let assignments: Assignments = vec![
            (
                "stance".to_string(),
                MutationValue::Value(KipValue::String("support".into())),
            ),
            ("evidence".to_string(), MutationValue::Handle("e1".into())),
        ];
        assert_eq!(
            serde_json::to_string(&assignments).unwrap(),
            r#"[["stance",{"Value":{"String":"support"}}],["evidence",{"Handle":"e1"}]]"#
        );
    }

    #[test]
    fn command_round_trips_through_json() {
        let command = Command::Kml(KmlStatement {
            explicit_transaction: true,
            clauses: vec![MutationClause::EnsureProposition(EnsureProposition {
                handle: Some("p".into()),
                subject: Term::Param("alice".into()),
                predicate: PredAtom::Literal("prefers".into()),
                object: Term::Param("dark_mode".into()),
                expect_versions: Vec::new(),
            })],
        });
        let encoded = serde_json::to_string(&command).unwrap();
        let decoded: Command = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded, command);
        assert!(decoded.is_mutation());
    }

    #[test]
    fn version_planes_encode_the_way_the_reference_toolkit_does() {
        // `exec-ast.ts`: `plane: 'Attributes' | { Facet: SymbolRef } | null`.
        assert_eq!(
            serde_json::to_string(&ExpectVersion::element(Scalar::Param("v".into()))).unwrap(),
            r#"{"version":{"Param":"v"},"plane":null}"#
        );
        assert_eq!(
            serde_json::to_string(&ExpectVersion {
                version: Scalar::Literal(KipValue::Number(Number::from(3))),
                plane: Some(VersionPlane::Attributes),
            })
            .unwrap(),
            r#"{"version":{"Literal":{"Number":3}},"plane":"Attributes"}"#
        );
        assert_eq!(
            serde_json::to_string(&VersionPlane::Facet(SymbolRef::Name(
                "MnemonicState".into()
            )))
            .unwrap(),
            r#"{"Facet":{"Name":"MnemonicState"}}"#
        );
    }

    #[test]
    fn a_transition_knows_its_literal_state() {
        let transition = Transition {
            target: ElementRef::Param("a".into()),
            to: Scalar::Literal(KipValue::String("retracted".into())),
            by: None,
            set_fields: None,
            set_structural: None,
            where_clauses: None,
            limit: None,
            expect_versions: Vec::new(),
        };
        assert_eq!(transition.state(), Some("retracted"));
        assert!(!transition.finalizes());
        let bound = Transition {
            to: Scalar::Param("state".into()),
            ..transition
        };
        assert_eq!(bound.state(), None);
        assert!(transition_state::ALL.contains(&"tombstoned"));
    }

    #[test]
    fn kip_value_rejects_nothing_finite_and_converts_to_json() {
        let value = KipValue::try_from(serde_json::json!({"a": [1, "b", null]})).unwrap();
        assert_eq!(Json::from(value), serde_json::json!({"a": [1, "b", null]}));
    }

    #[test]
    fn dot_path_var_displays_both_step_kinds() {
        let path = DotPathVar {
            var: "x".into(),
            path: vec![
                PathStep::Field("facets".into()),
                PathStep::Key("MnemonicState".into()),
                PathStep::Field("salience".into()),
            ],
        };
        assert_eq!(path.to_string(), r#"?x.facets["MnemonicState"].salience"#);
    }
}