khive-pack-knowledge 0.14.0

Knowledge verb pack — lore corpus (atoms/domains), TF-IDF retrieval, concept registration
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
//! CRUD handlers: upsert_atoms, upsert_domains, get, list, delete_atoms, stats.

use std::collections::{HashMap, HashSet};

use serde_json::{json, Value};
use uuid::Uuid;

use khive_runtime::{
    micros_to_iso, uuid_prefix_bounds, KhiveRuntime, NamespaceToken, RuntimeError,
};
use khive_storage::types::{SqlStatement, SqlValue};

use super::schema::{
    AtomWrite, DeleteAtomsParams, GetParams, ListParams, StatsParams, UpsertAtomsParams,
    UpsertDomainsParams,
};
use super::search::HYDRATION_ID_CHUNK;
use super::sections::{section_from_row, section_to_json};
use super::util::{
    atom_from_row, atom_to_json, compute_embedding_coverage, deser, domain_from_row,
    domain_to_json, has_domain_mirror_tag, new_id, now_us, row_i64, row_str, sql_err,
    status_sql_clause, status_values, tags_to_json, validate_atom_content,
};
use super::KnowledgeHandlers;

#[path = "cursor_query.rs"]
mod cursor_query;
use cursor_query::cursor_query;

const ATOM_LIST_FIELDS: &[&str] = &[
    "id",
    "namespace",
    "slug",
    "name",
    "content",
    "tags",
    "properties",
    "status",
    "source_uri",
    "source_type",
    "finalized",
    "kind",
    "created_at",
    "updated_at",
];

const DOMAIN_LIST_FIELDS: &[&str] = &[
    "id",
    "namespace",
    "slug",
    "name",
    "description",
    "tags",
    "members",
    "kind",
    "created_at",
    "updated_at",
];

const LIST_CURSOR_ORDER: &str = "created_at_asc_id_asc";
const LIST_OFFSET_ORDER: &str = "created_at_desc_id_desc";

fn invalidate_section_vectors_for_atom_rename(
    id: &str,
    namespace: &str,
    new_name: &str,
    now: i64,
) -> SqlStatement {
    SqlStatement {
        sql: khive_runtime::sql!("knowledge_sections_invalidate_atom_rename").into(),
        params: vec![
            SqlValue::Integer(now),
            SqlValue::Text(id.to_string()),
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(new_name.to_string()),
        ],
        label: None,
    }
}

#[derive(Clone, Copy)]
enum KnowledgeListKind {
    Atom,
    Domain,
}

impl KnowledgeListKind {
    fn name(self) -> &'static str {
        match self {
            Self::Atom => "atom",
            Self::Domain => "domain",
        }
    }

    fn projection_fields(self) -> &'static [&'static str] {
        match self {
            Self::Atom => ATOM_LIST_FIELDS,
            Self::Domain => DOMAIN_LIST_FIELDS,
        }
    }
}

fn parse_list_after(raw: &str) -> Result<Option<Uuid>, RuntimeError> {
    if raw.is_empty() {
        return Ok(None);
    }
    Uuid::parse_str(raw).map(Some).map_err(|error| {
        RuntimeError::InvalidInput(format!(
            "knowledge.list: `after` must be a full UUID returned as `next_after`; \
             prefixes are unsafe for keyset pagination; got {raw:?}: {error}"
        ))
    })
}

fn validate_list_fields(
    kind: KnowledgeListKind,
    fields: Option<&[String]>,
) -> Result<(), RuntimeError> {
    let Some(fields) = fields else {
        return Ok(());
    };
    if fields.is_empty() {
        return Err(RuntimeError::InvalidInput(
            "knowledge.list: `fields` must be non-empty".into(),
        ));
    }
    if let Some(unknown) = fields
        .iter()
        .find(|field| !kind.projection_fields().contains(&field.as_str()))
    {
        return Err(RuntimeError::InvalidInput(format!(
            "knowledge.list: unknown {} projection field {unknown:?}; expected one of: {}",
            kind.name(),
            kind.projection_fields().join(", ")
        )));
    }
    Ok(())
}

/// Projection reads include the sort key internally, but the renderer below
/// emits only caller-requested fields. This is the byte-saving boundary: an
/// `id`/`slug` walk never selects atom `content` from SQLite.
fn list_select_columns(fields: Option<&[String]>) -> String {
    let Some(fields) = fields else {
        return "*".into();
    };

    let mut columns: Vec<&str> = Vec::with_capacity(fields.len() + 2);
    for field in fields {
        if field != "kind" && !columns.contains(&field.as_str()) {
            columns.push(field);
        }
    }
    for pagination_column in ["id", "created_at"] {
        if !columns.contains(&pagination_column) {
            columns.push(pagination_column);
        }
    }
    columns.join(", ")
}

fn json_text_column(row: &khive_storage::types::SqlRow, column: &str) -> Value {
    row_str(row, column).map_or(Value::Null, Value::String)
}

fn json_array_column(row: &khive_storage::types::SqlRow, column: &str) -> Value {
    row_str(row, column)
        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
        .unwrap_or_else(|| Value::Array(vec![]))
}

fn json_object_column(row: &khive_storage::types::SqlRow, column: &str) -> Value {
    row_str(row, column)
        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
        .unwrap_or(Value::Null)
}

fn json_timestamp_column(row: &khive_storage::types::SqlRow, column: &str) -> Value {
    row_i64(row, column)
        .map(micros_to_iso)
        .map_or(Value::Null, Value::String)
}

fn project_list_row(
    row: &khive_storage::types::SqlRow,
    kind: KnowledgeListKind,
    fields: Option<&[String]>,
) -> Option<Value> {
    let Some(fields) = fields else {
        return match kind {
            KnowledgeListKind::Atom => atom_from_row(row).map(|atom| atom_to_json(&atom)),
            KnowledgeListKind::Domain => domain_from_row(row).map(|domain| domain_to_json(&domain)),
        };
    };

    let mut projected = serde_json::Map::new();
    for field in fields {
        let value = match field.as_str() {
            "id" | "namespace" | "slug" | "name" | "content" | "description" | "status"
            | "source_uri" | "source_type" => json_text_column(row, field),
            "tags" | "members" => json_array_column(row, field),
            "properties" => json_object_column(row, field),
            "finalized" => Value::Bool(row_i64(row, field).is_some_and(|value| value == 1)),
            "kind" => Value::String(kind.name().into()),
            "created_at" | "updated_at" => json_timestamp_column(row, field),
            _ => unreachable!("projection field was validated"),
        };
        projected.insert(field.clone(), value);
    }
    Some(Value::Object(projected))
}

fn knowledge_get_prefix_statement(prefix: &str) -> Option<SqlStatement> {
    let (lower, upper) = uuid_prefix_bounds(prefix)?;
    Some(SqlStatement {
        // A domain's FTS mirror atom has the same UUID. UNION (rather than
        // UNION ALL) deduplicates that legitimate cross-table duplicate so
        // one domain is not reported as an ambiguous prefix.
        sql: khive_runtime::sql!("knowledge_get_prefix").into(),
        params: vec![SqlValue::Text(lower), SqlValue::Text(upper)],
        label: Some("knowledge.get.resolve_prefix".into()),
    })
}

/// Match a chunk of ids-or-slugs against the live rows of one table, as one
/// statement per key column. A single `id IN (..) OR slug IN (..)` predicate
/// makes the planner scan the namespace, so each column gets its own
/// statement: the primary key drives the id probe (`+namespace` keeps the
/// namespace term out of index selection, as in `hydrate_atoms_statement`)
/// and `(namespace, slug)` drives the slug probe. `+deleted_at` keeps the
/// liveness term out of index selection too, so the count index on
/// `(namespace, deleted_at, ..)` cannot win the slug probe and filter the
/// whole live namespace. `head` is the statement up
/// to `WHERE`; `lead` holds the binds before the keys, and its first entry is
/// the namespace (`?1`).
fn key_match_statements(head: &str, lead: Vec<SqlValue>, keys: &[String]) -> [SqlStatement; 2] {
    let first_key = lead.len() + 1;
    let placeholders = (first_key..first_key + keys.len())
        .map(|n| format!("?{n}"))
        .collect::<Vec<_>>()
        .join(",");
    let mut params = lead;
    params.extend(keys.iter().cloned().map(SqlValue::Text));
    [("id", "+namespace"), ("slug", "namespace")].map(|(column, namespace)| SqlStatement {
        sql: format!(
            "{head} WHERE {column} IN ({placeholders}) AND {namespace} = ?1 AND +deleted_at IS NULL"
        ),
        params: params.clone(),
        label: None,
    })
}

impl KnowledgeHandlers {
    /// Feedback accepts IDs from knowledge retrieval only; no KG table lookup
    /// and no slug fallback. Domain mirror atoms share the domain UUID.
    pub(crate) async fn resolve_feedback_target(
        runtime: &KhiveRuntime,
        input: &str,
    ) -> Result<(Uuid, &'static str), RuntimeError> {
        let sql = runtime.sql();
        let mut reader = sql
            .reader()
            .await
            .map_err(|e| sql_err("feedback target reader", e))?;
        let id = if let Ok(id) = input.parse::<Uuid>() {
            id
        } else if let Some(statement) = knowledge_get_prefix_statement(input) {
            let rows = reader
                .query_all(statement)
                .await
                .map_err(|e| sql_err("feedback target prefix", e))?;
            let ids: Vec<Uuid> = rows
                .iter()
                .filter_map(|r| row_str(r, "id"))
                .map(|id| {
                    id.parse()
                        .map_err(|_| RuntimeError::Internal("invalid stored knowledge UUID".into()))
                })
                .collect::<Result<_, _>>()?;
            match ids.as_slice() {
                [] => {
                    return Err(
                        khive_types::KhiveError::not_found("knowledge target", input).into(),
                    )
                }
                [id] => *id,
                _ => {
                    return Err(RuntimeError::AmbiguousPrefix {
                        prefix: input.into(),
                        matches: ids,
                    })
                }
            }
        } else {
            return Err(khive_types::KhiveError::invalid_input(
                "knowledge feedback target must be a full UUID or 8+ hex prefix",
            )
            .into());
        };
        // UUID reads, like knowledge.get, are namespace-agnostic (ADR-007).
        for (table, kind) in [("knowledge_domains", "domain"), ("knowledge_atoms", "atom")] {
            let row = reader
                .query_row(SqlStatement {
                    sql: format!(
                        "SELECT id FROM {table} WHERE id = ?1 AND deleted_at IS NULL LIMIT 1"
                    ),
                    params: vec![SqlValue::Text(id.to_string())],
                    label: Some("knowledge.feedback.target".into()),
                })
                .await
                .map_err(|e| sql_err("feedback target", e))?;
            if row.is_some() {
                return Ok((id, kind));
            }
        }
        Err(khive_types::KhiveError::not_found("knowledge target", input).into())
    }

    pub(crate) async fn upsert_atoms(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        Self::upsert_atoms_with_content_policy(runtime, token, params, false).await
    }

    /// Import has already validated the complete source document and must retain its
    /// boundary whitespace. The public upsert verb keeps its established trim behavior.
    pub(super) async fn upsert_import_atoms(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        Self::upsert_atoms_with_content_policy(runtime, token, params, true).await
    }

    async fn upsert_atoms_with_content_policy(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
        preserve_content_whitespace: bool,
    ) -> Result<Value, RuntimeError> {
        let p: UpsertAtomsParams = deser(params)?;
        if p.chunk_size.is_some() {
            tracing::warn!(
                chunk_size = ?p.chunk_size,
                "upsert_atoms: chunk_size is accepted but not yet implemented; \
                 server-side chunking is not performed"
            );
        }
        if p.atoms.is_empty() {
            return Err(RuntimeError::InvalidInput(
                "atoms list must not be empty".into(),
            ));
        }
        if p.atoms.len() > 5000 {
            return Err(RuntimeError::InvalidInput(
                "max 5000 atoms per request".into(),
            ));
        }

        if p.dry_run {
            return super::atom_validation::dry_run(
                runtime,
                token,
                &p.atoms,
                preserve_content_whitespace,
            )
            .await;
        }

        let ns = token.namespace().as_str().to_owned();
        let sql = runtime.sql();
        let now = now_us();

        let failures: Vec<_> = p
            .atoms
            .iter()
            .enumerate()
            .map(|(index, atom)| {
                super::refusal::validate_submission(atom, index, preserve_content_whitespace).err()
            })
            .collect();
        if failures.iter().any(Option::is_some) {
            return Err(super::refusal::refuse_batch(
                runtime,
                token,
                &p.atoms,
                failures,
                preserve_content_whitespace,
            )
            .await);
        }

        let mut reader = sql
            .reader()
            .await
            .map_err(|e| sql_err("upsert_atoms reader", e))?;
        let mut ids_by_slug: HashMap<String, String> = HashMap::new();
        let mut operations = Vec::with_capacity(p.atoms.len());
        let mut failed_index = 0;
        let preparation: Result<(), RuntimeError> = async {
            for (index, atom_in) in p.atoms.iter().enumerate() {
                failed_index = index;
                if let AtomWrite::Upsert(input) = atom_in {
                    if let Some(id) = ids_by_slug.get(input.slug.trim()) {
                        operations.push((id.clone(), false));
                        continue;
                    }
                }
                let target = super::atom_validation::target(reader.as_mut(), &ns, atom_in).await?;
                let (id, insert) = match target {
                    Some(id) => (id, false),
                    None => (new_id(), true),
                };
                if let AtomWrite::Upsert(input) = atom_in {
                    ids_by_slug.insert(input.slug.trim().to_owned(), id.clone());
                }
                operations.push((id, insert));
            }
            Ok(())
        }
        .await;
        drop(reader);
        if let Err(error) = preparation {
            if matches!(
                error,
                RuntimeError::InvalidInput(_) | RuntimeError::NotFound(_)
            ) {
                let mut failures: Vec<_> = (0..p.atoms.len()).map(|_| None).collect();
                failures[failed_index] = Some(error);
                return Err(super::refusal::refuse_batch(
                    runtime,
                    token,
                    &p.atoms,
                    failures,
                    preserve_content_whitespace,
                )
                .await);
            }
            return Err(error);
        }

        let mut created = 0usize;
        let mut updated = 0usize;
        let mut statements = Vec::with_capacity(p.atoms.len());
        for (atom_in, (id, insert)) in p.atoms.iter().zip(operations) {
            let atom_in = match atom_in {
                AtomWrite::Upsert(atom_in) => atom_in,
                AtomWrite::PropertiesOnly(atom_in) => {
                    statements.push(SqlStatement {
                        sql: khive_runtime::sql!("knowledge_atom_properties_update").into(),
                        params: vec![
                            if atom_in.properties.is_null() {
                                SqlValue::Null
                            } else {
                                SqlValue::Text(atom_in.properties.to_string())
                            },
                            SqlValue::Integer(now),
                            SqlValue::Text(id),
                        ],
                        label: None,
                    });
                    updated += 1;
                    continue;
                }
            };
            let slug = atom_in.slug.trim().to_string();
            let raw_content = atom_in.content.as_deref().unwrap_or("");
            let content = if preserve_content_whitespace {
                raw_content.to_string()
            } else {
                raw_content.trim().to_string()
            };
            let tags_json = tags_to_json(atom_in.tags.as_ref());
            let props_json = atom_in
                .properties
                .as_ref()
                .map(|v| serde_json::to_string(v).unwrap_or_default());
            let source_uri = atom_in
                .source_uri
                .as_ref()
                .and_then(Option::as_ref)
                .map(|s| s.trim())
                .filter(|s| !s.is_empty());
            // Blank strings keep their established update behavior (preserve),
            // while JSON null is now an explicit clear.
            let source_uri_present =
                matches!(&atom_in.source_uri, Some(None)) || source_uri.is_some();
            let source_type = atom_in
                .source_type
                .as_ref()
                .and_then(Option::as_ref)
                .map(|s| s.trim())
                .filter(|s| !s.is_empty());
            let source_type_present =
                matches!(&atom_in.source_type, Some(None)) || source_type.is_some();
            let finalized_present = atom_in.finalized.is_some();
            let finalized = atom_in.finalized.flatten().unwrap_or(false);

            if insert {
                statements.push(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_atom_insert").into(),
                    params: vec![
                        SqlValue::Text(id),
                        SqlValue::Text(ns.clone()),
                        SqlValue::Text(slug.clone()),
                        SqlValue::Text(atom_in.name.clone()),
                        SqlValue::Text(content.clone()),
                        SqlValue::Text(tags_json.clone()),
                        props_json
                            .as_ref()
                            .map_or(SqlValue::Null, |p| SqlValue::Text(p.clone())),
                        source_uri.map_or(SqlValue::Null, |s| SqlValue::Text(s.to_string())),
                        source_type.map_or(SqlValue::Null, |s| SqlValue::Text(s.to_string())),
                        // status mirrors the lifecycle backfill (finalized => reviewed) so a
                        // freshly-finalized atom is never left at the 'draft' default.
                        SqlValue::Text(if finalized { "reviewed" } else { "draft" }.to_string()),
                        SqlValue::Integer(finalized as i64),
                        SqlValue::Integer(now),
                        SqlValue::Integer(now),
                    ],
                    label: None,
                });
                created += 1;
            } else {
                statements.push(invalidate_section_vectors_for_atom_rename(
                    &id,
                    &ns,
                    &atom_in.name,
                    now,
                ));
                statements.push(SqlStatement {
                    // Presence/value pairs distinguish omission from explicit JSON
                    // null. Finalized is non-nullable, so its null value is bound as
                    // false. Only true promotes draft -> reviewed; clearing the flag
                    // does not demote an independent lifecycle status.
                    sql: khive_runtime::sql!("knowledge_atom_content_update").into(),
                    params: vec![
                        SqlValue::Text(atom_in.name.clone()),
                        SqlValue::Text(content),
                        SqlValue::Text(tags_json),
                        props_json.map_or(SqlValue::Null, SqlValue::Text),
                        SqlValue::Integer(source_uri_present as i64),
                        source_uri.map_or(SqlValue::Null, |s| SqlValue::Text(s.to_string())),
                        SqlValue::Integer(source_type_present as i64),
                        source_type.map_or(SqlValue::Null, |s| SqlValue::Text(s.to_string())),
                        SqlValue::Integer(finalized_present as i64),
                        SqlValue::Integer(finalized as i64),
                        SqlValue::Integer(now),
                        SqlValue::Text(id.clone()),
                        SqlValue::Text(ns.clone()),
                    ],
                    label: None,
                });
                updated += 1;
            }
        }

        let mut writer = sql
            .writer()
            .await
            .map_err(|e| sql_err("upsert_atoms writer", e))?;
        writer
            .execute_batch(statements)
            .await
            .map_err(|e| sql_err("upsert_atoms batch", e))?;
        Ok(json!({
            "created": created,
            "updated": updated,
            "total": p.atoms.len(),
        }))
    }

    pub(crate) async fn upsert_domains(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        let p: UpsertDomainsParams = deser(params)?;
        if p.domains.is_empty() {
            return Err(RuntimeError::InvalidInput(
                "domains list must not be empty".into(),
            ));
        }

        let ns = token.namespace().as_str().to_owned();
        let sql = runtime.sql();
        let now = now_us();
        let mut created = 0usize;
        let mut updated = 0usize;

        for domain_in in &p.domains {
            let slug = domain_in.slug.trim().to_string();
            let name = domain_in.name.trim().to_string();
            if slug.is_empty() {
                return Err(RuntimeError::InvalidInput(
                    "domain slug must not be empty".into(),
                ));
            }
            if name.is_empty() {
                return Err(RuntimeError::InvalidInput(
                    "domain name must not be empty".into(),
                ));
            }
            // Secret gate: scan slug and name first (before content-length validation)
            // so security violations short-circuit before business logic errors.
            khive_runtime::secret_gate::check_at(&slug, "domain", "slug")?;
            khive_runtime::secret_gate::check_at(&name, "domain", "name")?;
            // Domain mirror atoms are written to knowledge_atoms with the description
            // as content. Enforce the same 20-word minimum that normal atoms must satisfy
            // so the FTS and embedding surfaces receive adequate content.
            let mirror_content = domain_in.description.as_deref().unwrap_or("").trim();
            validate_atom_content(mirror_content).map_err(|e| {
                RuntimeError::InvalidInput(format!("domain {slug:?}: description {e}"))
            })?;
            // Secret gate: scan remaining caller-supplied text.
            khive_runtime::secret_gate::check_at(mirror_content, "domain", "description")?;
            if let Some(ref tags_vec) = domain_in.tags {
                khive_runtime::secret_gate::check_tags_at(tags_vec, "domain", "tags")?;
            }
            if let Some(ref members_vec) = domain_in.members {
                khive_runtime::secret_gate::check_tags_at(members_vec, "domain", "members")?;
            }

            let mut tags: Vec<String> = domain_in.tags.clone().unwrap_or_default();
            if !tags.iter().any(|t| t == "type:domain") {
                tags.push("type:domain".to_string());
            }
            let tags_json = serde_json::to_string(&tags).unwrap_or_else(|_| "[]".into());
            let members_json = match &domain_in.members {
                Some(m) => serde_json::to_string(m).unwrap_or_else(|_| "[]".into()),
                None => "[]".to_string(),
            };
            // The mirror's properties are synthesized entirely from `members`
            // (a `Vec<String>`, no arbitrary-key input); `DomainInput` carries no
            // `properties` field, so the top-level reserved key is unreachable here.
            let properties_json = serde_json::to_string(
                &serde_json::json!({ "members": domain_in.members.as_deref().unwrap_or(&[]) }),
            )
            .unwrap_or_else(|_| "{}".into());

            let mut reader = sql
                .reader()
                .await
                .map_err(|e| sql_err("upsert_domains reader", e))?;
            // Look up by slug WITHOUT the deleted_at filter so a tombstoned domain
            // that still owns the (namespace, slug) unique index is detected before
            // the insert path runs, instead of leaking a raw unique-constraint error.
            let existing = reader
                .query_row(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_domain_slug_probe").into(),
                    params: vec![SqlValue::Text(ns.clone()), SqlValue::Text(slug.clone())],
                    label: None,
                })
                .await
                .map_err(|e| sql_err("upsert_domains lookup", e))?;
            if let Some(row) = &existing {
                if row_i64(row, "deleted_at").is_some() {
                    return Err(RuntimeError::InvalidInput(format!(
                        "domain slug {slug:?} was previously deleted; choose a new slug"
                    )));
                }
            }

            let id = match &existing {
                Some(row) => row_str(row, "id").ok_or_else(|| {
                    RuntimeError::Internal("missing id in existing domain row".into())
                })?,
                None => new_id(),
            };

            // Preflight: a normal atom (or a tombstoned atom that still owns the
            // unique (namespace, slug) index) must never share this domain's slug.
            // The mirror atom for THIS domain shares its id with the domain, so the
            // collision is only real when the colliding row belongs to a different
            // id. This must run BEFORE any write so a collision never leaves a
            // partially-committed domain row behind.
            let atom_collision = reader
                .query_row(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_atom_slug_probe").into(),
                    params: vec![SqlValue::Text(ns.clone()), SqlValue::Text(slug.clone())],
                    label: None,
                })
                .await
                .map_err(|e| sql_err("upsert_domains atom collision check", e))?;
            if let Some(row) = &atom_collision {
                let collision_id = row_str(row, "id").ok_or_else(|| {
                    RuntimeError::Internal("missing id in colliding atom row".into())
                })?;
                if collision_id != id {
                    return Err(RuntimeError::InvalidInput(format!(
                        "domain slug {slug:?} collides with an existing atom of the same slug"
                    )));
                }
            }

            // Mirror write is keyed by id (shared with the domain), never by slug —
            // ON CONFLICT(namespace, slug) would blind-overwrite an unrelated atom
            // that merely happens to share this slug.
            let mirror_stmt = SqlStatement {
                sql: khive_runtime::sql!("knowledge_domain_mirror_upsert").into(),
                params: vec![
                    SqlValue::Text(id.clone()),
                    SqlValue::Text(ns.clone()),
                    SqlValue::Text(slug.clone()),
                    SqlValue::Text(name.clone()),
                    SqlValue::Text(domain_in.description.clone().unwrap_or_default()),
                    SqlValue::Text(tags_json.clone()),
                    SqlValue::Text(properties_json.clone()),
                    SqlValue::Integer(now),
                    SqlValue::Integer(now),
                ],
                label: None,
            };

            let mut writer = sql
                .writer()
                .await
                .map_err(|e| sql_err("upsert_domains writer", e))?;
            if existing.is_some() {
                let domain_stmt = SqlStatement {
                    sql: khive_runtime::sql!("knowledge_domain_update").into(),
                    params: vec![
                        SqlValue::Text(name.clone()),
                        domain_in
                            .description
                            .as_ref()
                            .map_or(SqlValue::Null, |d| SqlValue::Text(d.clone())),
                        SqlValue::Text(tags_json.clone()),
                        SqlValue::Text(members_json.clone()),
                        SqlValue::Integer(now),
                        SqlValue::Text(id.clone()),
                        SqlValue::Text(ns.clone()),
                    ],
                    label: None,
                };
                // Atomic: the canonical domain row and its FTS mirror atom are one
                // logical record; a mirror-write failure must roll back the domain
                // update too.
                writer
                    .execute_batch(vec![
                        domain_stmt,
                        invalidate_section_vectors_for_atom_rename(&id, &ns, &name, now),
                        mirror_stmt,
                    ])
                    .await
                    .map_err(|e| sql_err("upsert_domains update batch", e))?;
                updated += 1;
            } else {
                let domain_stmt = SqlStatement {
                    sql: khive_runtime::sql!("knowledge_domain_insert").into(),
                    params: vec![
                        SqlValue::Text(id.clone()),
                        SqlValue::Text(ns.clone()),
                        SqlValue::Text(slug.clone()),
                        SqlValue::Text(name.clone()),
                        domain_in
                            .description
                            .as_ref()
                            .map_or(SqlValue::Null, |d| SqlValue::Text(d.clone())),
                        SqlValue::Text(tags_json.clone()),
                        SqlValue::Text(members_json.clone()),
                        SqlValue::Integer(now),
                        SqlValue::Integer(now),
                    ],
                    label: None,
                };
                // Atomic: a mirror-insert failure must roll back the domain insert
                // too, so no domain row is ever left committed without its mirror.
                writer
                    .execute_batch(vec![
                        domain_stmt,
                        invalidate_section_vectors_for_atom_rename(&id, &ns, &name, now),
                        mirror_stmt,
                    ])
                    .await
                    .map_err(|e| sql_err("upsert_domains insert batch", e))?;
                created += 1;
            }
        }

        Ok(json!({
            "created": created,
            "updated": updated,
            "total": p.domains.len(),
        }))
    }

    pub(crate) async fn get(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        let p: GetParams = deser(params)?;
        let ns = token.namespace().as_str().to_owned();
        let sql = runtime.sql();
        let id = p.id.trim().to_string();
        let with_sections = p.include_sections.unwrap_or(false);

        let mut reader = sql.reader().await.map_err(|e| sql_err("get reader", e))?;

        // ADR-007 Rule 2: UUID and short-prefix forms are by-ID reads, so they
        // are namespace-agnostic. Parse a complete UUID first so 32-character
        // compact UUIDs are complete identifiers, not prefixes. For non-UUID
        // input, preserve the pack's registered-slug contract: an exact slug in
        // the caller namespace wins before an all-hex value is interpreted as a
        // UUID prefix.
        let resolved_id = if let Ok(uuid) = id.parse::<Uuid>() {
            Some(uuid.to_string())
        } else {
            // Exact slug lookup precedes prefix interpretation so a registered
            // all-hex slug remains addressable. Domains are authoritative over
            // their same-slug mirror atoms.
            let row = reader
                .query_row(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_domain_get_slug").into(),
                    params: vec![SqlValue::Text(ns.clone()), SqlValue::Text(id.clone())],
                    label: Some("knowledge.get.domain_by_slug".into()),
                })
                .await
                .map_err(|e| sql_err("get domain by slug", e))?;
            if let Some(r) = row {
                return domain_from_row(&r)
                    .map(|d| domain_to_json(&d))
                    .ok_or_else(|| RuntimeError::Internal("domain row parse failed".into()));
            }

            let row = reader
                .query_row(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_atom_get_slug").into(),
                    params: vec![SqlValue::Text(ns.clone()), SqlValue::Text(id.clone())],
                    label: Some("knowledge.get.atom_by_slug".into()),
                })
                .await
                .map_err(|e| sql_err("get atom by slug", e))?;
            if let Some(r) = row {
                let atom = atom_from_row(&r)
                    .ok_or_else(|| RuntimeError::Internal("atom row parse failed".into()))?;
                let atom_id = atom.id.to_string();
                let mut out = atom_to_json(&atom);
                if with_sections {
                    out["sections"] = fetch_sections(runtime, &ns, &atom_id).await?;
                }
                return Ok(out);
            }

            if id.len() >= 8 && id.chars().all(|c| c.is_ascii_hexdigit()) {
                let rows = if let Some(statement) = knowledge_get_prefix_statement(&id) {
                    reader
                        .query_all(statement)
                        .await
                        .map_err(|e| sql_err("get by prefix", e))?
                } else {
                    Vec::new()
                };
                let matches: Vec<String> =
                    rows.iter().filter_map(|row| row_str(row, "id")).collect();
                match matches.as_slice() {
                    [] => {
                        return Err(RuntimeError::InvalidInput(format!(
                            "no knowledge record matches prefix: {id:?}"
                        )))
                    }
                    [only] => Some(only.clone()),
                    _ => {
                        return Err(RuntimeError::AmbiguousPrefix {
                            prefix: id.clone(),
                            matches: matches
                                .iter()
                                .filter_map(|matched| matched.parse::<Uuid>().ok())
                                .collect(),
                        })
                    }
                }
            } else {
                None
            }
        };

        if let Some(resolved_id) = resolved_id {
            // Domain-first: a domain's canonical row and its FTS mirror atom share
            // the same UUID, so the UUID branch must match the slug branch below
            // and prefer knowledge_domains — otherwise a domain UUID resolves to
            // its own mirror atom instead of the canonical domain record.
            let row = reader
                .query_row(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_domain_get_id").into(),
                    params: vec![SqlValue::Text(resolved_id.clone())],
                    label: Some("knowledge.get.domain_by_id".into()),
                })
                .await
                .map_err(|e| sql_err("get domain by id", e))?;
            if let Some(r) = row {
                return domain_from_row(&r)
                    .map(|d| domain_to_json(&d))
                    .ok_or_else(|| RuntimeError::Internal("domain row parse failed".into()));
            }
            let row = reader
                .query_row(SqlStatement {
                    sql: khive_runtime::sql!("knowledge_atom_get_id").into(),
                    params: vec![SqlValue::Text(resolved_id)],
                    label: Some("knowledge.get.atom_by_id".into()),
                })
                .await
                .map_err(|e| sql_err("get atom by id", e))?;
            if let Some(r) = row {
                let atom = atom_from_row(&r)
                    .ok_or_else(|| RuntimeError::Internal("atom row parse failed".into()))?;
                let atom_id = atom.id.to_string();
                let atom_namespace = atom.namespace.clone();
                let mut out = atom_to_json(&atom);
                if with_sections {
                    out["sections"] = fetch_sections(runtime, &atom_namespace, &atom_id).await?;
                }
                return Ok(out);
            }

            // An ID-shaped input names one record or misses. It must not fall
            // through and accidentally resolve a slug with the same spelling.
            return Err(RuntimeError::NotFound(format!(
                "atom or domain not found: {id:?}"
            )));
        }

        Err(RuntimeError::NotFound(format!(
            "atom or domain not found: {id:?}"
        )))
    }

    pub(crate) async fn list(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        let p: ListParams = deser(params)?;
        let kind = match p.kind.as_deref() {
            Some("domain") => KnowledgeListKind::Domain,
            Some("atom") | None => KnowledgeListKind::Atom,
            Some(other) => {
                return Err(RuntimeError::InvalidInput(format!(
                    "unknown type {other:?}; valid: atom | domain"
                )))
            }
        };
        let cursor_mode = p.after.is_some();
        if cursor_mode && p.offset.is_some() {
            return Err(RuntimeError::InvalidInput(
                "knowledge.list: `after` and `offset` are mutually exclusive".into(),
            ));
        }
        validate_list_fields(kind, p.fields.as_deref())?;
        let after_id = p
            .after
            .as_deref()
            .map(parse_list_after)
            .transpose()?
            .flatten();

        if matches!(kind, KnowledgeListKind::Atom) {
            if let Some(status) = p.status.as_ref() {
                let valid = match status {
                    Value::String(_) => true,
                    Value::Array(items) => items.iter().all(Value::is_string),
                    _ => false,
                };
                if !valid {
                    return Err(RuntimeError::InvalidInput(
                        "status must be a string or an array of strings".into(),
                    ));
                }
            }
        }

        let ns = token.namespace().as_str().to_owned();
        let sql = runtime.sql();
        let limit_usize = p.limit.unwrap_or(20).clamp(1, 500);
        let limit = limit_usize as i64;
        let offset = i64::try_from(p.offset.unwrap_or(0)).map_err(|_| {
            RuntimeError::InvalidInput("knowledge.list offset exceeds the supported range".into())
        })?;
        let select_columns = list_select_columns(p.fields.as_deref());

        let mut reader = sql.reader().await.map_err(|e| sql_err("list reader", e))?;

        // A full cursor UUID resolves to the immutable seek tuple. Deliberately
        // allow a soft-deleted boundary to keep an in-flight walk resumable;
        // hard deletion, the wrong namespace, or the wrong list type fails.
        let cursor_key = if let Some(after_id) = after_id {
            let cursor_sql = match kind {
                KnowledgeListKind::Atom => {
                    khive_runtime::sql!("knowledge_atom_cursor_key")
                }
                KnowledgeListKind::Domain => {
                    khive_runtime::sql!("knowledge_domain_cursor_key")
                }
            };
            let row = reader
                .query_row(SqlStatement {
                    sql: cursor_sql.into(),
                    params: vec![
                        SqlValue::Text(ns.clone()),
                        SqlValue::Text(after_id.to_string()),
                    ],
                    label: Some(format!("knowledge.list.{}.cursor", kind.name())),
                })
                .await
                .map_err(|e| sql_err("resolve list cursor", e))?
                .ok_or_else(|| {
                    RuntimeError::NotFound(format!(
                        "knowledge.list: {} cursor {} not found in namespace {ns:?}",
                        kind.name(),
                        after_id
                    ))
                })?;
            let created_at = row_i64(&row, "created_at").ok_or_else(|| {
                RuntimeError::Internal("knowledge.list cursor row lacks created_at".into())
            })?;
            let id = row_str(&row, "id").ok_or_else(|| {
                RuntimeError::Internal("knowledge.list cursor row lacks id".into())
            })?;
            Some((created_at, id))
        } else {
            None
        };

        match kind {
            KnowledgeListKind::Domain => {
                let (data_sql, data_params) = if cursor_mode {
                    let fetch_limit = limit.saturating_add(1);
                    match cursor_key.as_ref() {
                        Some((created_at, id)) => (
                            cursor_query("knowledge_domains", &select_columns, true, ""),
                            vec![
                                SqlValue::Text(ns.clone()),
                                SqlValue::Integer(*created_at),
                                SqlValue::Text(id.clone()),
                                SqlValue::Integer(fetch_limit),
                            ],
                        ),
                        None => (
                            cursor_query("knowledge_domains", &select_columns, false, ""),
                            vec![SqlValue::Text(ns.clone()), SqlValue::Integer(fetch_limit)],
                        ),
                    }
                } else {
                    (
                        // #1671: `id` tiebreak — deterministic total order for offset pages.
                        format!(
                            "SELECT {select_columns} FROM knowledge_domains \
                             WHERE namespace = ?1 AND deleted_at IS NULL \
                             ORDER BY created_at DESC, id DESC LIMIT ?2 OFFSET ?3"
                        ),
                        vec![
                            SqlValue::Text(ns.clone()),
                            SqlValue::Integer(limit),
                            SqlValue::Integer(offset),
                        ],
                    )
                };
                let mut rows = reader
                    .query_all(SqlStatement {
                        sql: data_sql,
                        params: data_params,
                        label: Some("knowledge.list.domains".into()),
                    })
                    .await
                    .map_err(|e| sql_err("list domains", e))?;

                let has_more = cursor_mode && rows.len() > limit_usize;
                if has_more {
                    rows.truncate(limit_usize);
                }
                let next_after = has_more
                    .then(|| rows.last().and_then(|row| row_str(row, "id")))
                    .flatten();
                let items: Vec<Value> = rows
                    .iter()
                    .filter_map(|row| project_list_row(row, kind, p.fields.as_deref()))
                    .collect();

                // A cursor page carries no total: counting the namespace is a
                // full scan per page, and next_after is the completion signal.
                if cursor_mode {
                    Ok(json!({
                        "results": items,
                        "limit": limit,
                        "order": LIST_CURSOR_ORDER,
                        "next_after": next_after,
                    }))
                } else {
                    let total = reader
                        .count(SqlStatement {
                            sql: khive_runtime::sql!("knowledge_domain_count").into(),
                            params: vec![SqlValue::Text(ns)],
                            label: None,
                        })
                        .await
                        .map_err(|e| sql_err("list domains count", e))?;
                    Ok(json!({
                        "results": items,
                        "total": total,
                        "limit": limit,
                        "offset": offset,
                        "order": LIST_OFFSET_ORDER,
                    }))
                }
            }
            KnowledgeListKind::Atom => {
                let requested_statuses = status_values(p.status.as_ref());
                let exclude_buf: Vec<&str> = p
                    .exclude_status
                    .as_deref()
                    .filter(|s| !s.trim().is_empty())
                    .into_iter()
                    .collect();
                let (count_status_clause, count_status_params) =
                    status_sql_clause(&requested_statuses, &exclude_buf, 2);

                let (sql_str, row_params) = if cursor_mode {
                    let fetch_limit = limit.saturating_add(1);
                    match cursor_key.as_ref() {
                        Some((created_at, id)) => {
                            let (data_status_clause, data_status_params) =
                                status_sql_clause(&requested_statuses, &exclude_buf, 5);
                            let mut row_params = vec![
                                SqlValue::Text(ns.clone()),
                                SqlValue::Integer(*created_at),
                                SqlValue::Text(id.clone()),
                                SqlValue::Integer(fetch_limit),
                            ];
                            row_params.extend(data_status_params);
                            (
                                cursor_query(
                                    "knowledge_atoms",
                                    &select_columns,
                                    true,
                                    &data_status_clause,
                                ),
                                row_params,
                            )
                        }
                        None => {
                            let (data_status_clause, data_status_params) =
                                status_sql_clause(&requested_statuses, &exclude_buf, 3);
                            let mut row_params =
                                vec![SqlValue::Text(ns.clone()), SqlValue::Integer(fetch_limit)];
                            row_params.extend(data_status_params);
                            (
                                cursor_query(
                                    "knowledge_atoms",
                                    &select_columns,
                                    false,
                                    &data_status_clause,
                                ),
                                row_params,
                            )
                        }
                    }
                } else {
                    let (data_status_clause, data_status_params) =
                        status_sql_clause(&requested_statuses, &exclude_buf, 4);
                    let mut row_params = vec![
                        SqlValue::Text(ns.clone()),
                        SqlValue::Integer(limit),
                        SqlValue::Integer(offset),
                    ];
                    row_params.extend(data_status_params);
                    (
                        format!(
                            "SELECT {select_columns} FROM knowledge_atoms \
                             WHERE namespace = ?1 AND deleted_at IS NULL \
                             AND NOT khive_tag_contains(tags, 'type:domain'){} \
                             ORDER BY created_at DESC, id DESC LIMIT ?2 OFFSET ?3",
                            data_status_clause
                        ),
                        row_params,
                    )
                };
                let count_sql = format!(
                    "SELECT COUNT(*) FROM knowledge_atoms WHERE namespace = ?1 AND deleted_at IS NULL AND NOT khive_tag_contains(tags, 'type:domain'){}",
                    count_status_clause
                );

                let mut rows = reader
                    .query_all(SqlStatement {
                        sql: sql_str,
                        params: row_params,
                        label: Some("knowledge.list.atoms".into()),
                    })
                    .await
                    .map_err(|e| sql_err("list atoms", e))?;

                let has_more = cursor_mode && rows.len() > limit_usize;
                if has_more {
                    rows.truncate(limit_usize);
                }
                let next_after = has_more
                    .then(|| rows.last().and_then(|row| row_str(row, "id")))
                    .flatten();
                let items: Vec<Value> = rows
                    .iter()
                    .filter_map(|row| project_list_row(row, kind, p.fields.as_deref()))
                    .collect();

                // A cursor page carries no total: counting the namespace is a
                // full scan per page, and next_after is the completion signal.
                if cursor_mode {
                    Ok(json!({
                        "results": items,
                        "limit": limit,
                        "order": LIST_CURSOR_ORDER,
                        "next_after": next_after,
                    }))
                } else {
                    let mut count_params = vec![SqlValue::Text(ns)];
                    count_params.extend(count_status_params);
                    let total = reader
                        .count(SqlStatement {
                            sql: count_sql,
                            params: count_params,
                            label: Some("knowledge.list.atom_count".into()),
                        })
                        .await
                        .map_err(|e| sql_err("list atoms count", e))?;
                    Ok(json!({
                        "results": items,
                        "total": total,
                        "limit": limit,
                        "offset": offset,
                        "order": LIST_OFFSET_ORDER,
                    }))
                }
            }
        }
    }

    pub(crate) async fn delete_atoms(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        let p: DeleteAtomsParams = deser(params)?;
        if p.cascade.is_some() {
            tracing::warn!(
                cascade = ?p.cascade,
                "delete_atoms: cascade is accepted but not yet implemented; \
                 sections are not cascade-deleted when atoms are soft-deleted"
            );
        }
        if p.ids.is_empty() {
            return Err(RuntimeError::InvalidInput("ids must not be empty".into()));
        }

        let ns = token.namespace().as_str().to_owned();
        let sql = runtime.sql();
        let now = now_us();
        // Keys are matched a chunk at a time so the namespace bind plus the key
        // binds stay below SQLite's portable variable ceiling.
        let keys: Vec<String> = p.ids.iter().map(|id| id.trim().to_string()).collect();

        // Preflight the full request before mutating anything: knowledge.delete_atoms
        // is documented as atom-only. A domain's canonical row and its FTS mirror
        // atom share an id/slug, so deleting the mirror here would tombstone one
        // half of the domain while leaving knowledge_domains live — a split-brain
        // where direct lookup and search/suggest disagree. Domains must go through
        // the generic delete verb, which deletes both halves together.
        let mut reader = sql
            .reader()
            .await
            .map_err(|e| sql_err("delete_atoms reader", e))?;
        for chunk in keys.chunks(HYDRATION_ID_CHUNK) {
            let mut domains: HashSet<String> = HashSet::new();
            for statement in key_match_statements(
                "SELECT id, slug FROM knowledge_domains",
                vec![SqlValue::Text(ns.clone())],
                chunk,
            ) {
                let rows = reader
                    .query_all(statement)
                    .await
                    .map_err(|e| sql_err("delete_atoms domain preflight", e))?;
                for row in &rows {
                    domains.extend(row_str(row, "id"));
                    domains.extend(row_str(row, "slug"));
                }
            }
            let mut mirrors: HashSet<String> = HashSet::new();
            for statement in key_match_statements(
                "SELECT id, slug, tags FROM knowledge_atoms",
                vec![SqlValue::Text(ns.clone())],
                chunk,
            ) {
                let rows = reader
                    .query_all(statement)
                    .await
                    .map_err(|e| sql_err("delete_atoms mirror preflight", e))?;
                for row in &rows {
                    let tags = row_str(row, "tags").unwrap_or_default();
                    if has_domain_mirror_tag(&tags) {
                        mirrors.extend(row_str(row, "id"));
                        mirrors.extend(row_str(row, "slug"));
                    }
                }
            }
            // Keys keep request order, so the first refused key is the same one
            // a per-key check would have stopped at.
            for key in chunk {
                if domains.contains(key) {
                    return Err(RuntimeError::InvalidInput(format!(
                        "knowledge.delete_atoms cannot delete domain {key:?}; use the generic delete verb by domain UUID"
                    )));
                }
                if mirrors.contains(key) {
                    return Err(RuntimeError::InvalidInput(format!(
                        "knowledge.delete_atoms cannot delete domain mirror {key:?}; use the generic delete verb by domain UUID"
                    )));
                }
            }
        }

        let mut statements: Vec<SqlStatement> = Vec::new();
        for chunk in keys.chunks(HYDRATION_ID_CHUNK) {
            statements.extend(key_match_statements(
                "UPDATE knowledge_atoms SET deleted_at = ?2",
                vec![SqlValue::Text(ns.clone()), SqlValue::Integer(now)],
                chunk,
            ));
        }
        // One batch is one transaction and one writer round trip however many
        // ids were sent. A storage error now rolls the whole request back;
        // before, the ids ahead of the failing one stayed deleted. A repeated
        // request converges either way, since deleted rows no longer match.
        let mut writer = sql
            .writer()
            .await
            .map_err(|e| sql_err("delete_atoms writer", e))?;
        let deleted = writer
            .execute_batch(statements)
            .await
            .map_err(|e| sql_err("delete_atoms update", e))? as usize;

        Ok(json!({
            "deleted": deleted,
            "requested": p.ids.len(),
        }))
    }

    pub(crate) async fn stats(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        let _: StatsParams = deser(params)?;
        let ns = token.namespace().as_str().to_owned();
        let sql = runtime.sql();
        let mut reader = sql.reader().await.map_err(|e| sql_err("stats reader", e))?;

        // Atom totals and finalized coverage share the same expensive
        // namespace/live/non-domain predicate. Keep them in one aggregate so
        // large corpora pay for a single table pass and one request-deadline
        // slice rather than two sequential scans (#2218).
        let atom_stats = reader
            .query_row(SqlStatement {
                sql: khive_runtime::sql!("knowledge_atom_stats").into(),
                params: vec![SqlValue::Text(ns.clone())],
                label: Some("knowledge.stats.atom_aggregates".into()),
            })
            .await
            .map_err(|e| sql_err("stats atom aggregates", e))?;

        let total_domains = reader
            .count(SqlStatement {
                sql: khive_runtime::sql!("knowledge_domain_count").into(),
                params: vec![SqlValue::Text(ns.clone())],
                label: None,
            })
            .await
            .map_err(|e| sql_err("stats domains", e))?;

        let total_events = reader
            .count(SqlStatement {
                sql: khive_runtime::sql!("knowledge_event_count").into(),
                params: vec![SqlValue::Text(ns.clone())],
                label: Some("knowledge.stats.event_count".into()),
            })
            .await
            .map_err(|e| sql_err("stats events", e))?;

        let retrieval_eval_run_count = reader
            .count(SqlStatement {
                sql: khive_runtime::sql!("knowledge_eval_run_count").into(),
                params: vec![SqlValue::Text(ns.clone())],
                label: Some("knowledge.stats.eval_run_count".into()),
            })
            .await
            .map_err(|e| sql_err("stats eval run count", e))?;

        let latest_retrieval_eval = reader
            .query_row(SqlStatement {
                sql: khive_runtime::sql!("knowledge_eval_latest").into(),
                params: vec![SqlValue::Text(ns.clone())],
                label: Some("knowledge.stats.latest_eval_run".into()),
            })
            .await
            .map_err(|e| sql_err("stats latest eval run", e))?;

        let total_atoms = atom_stats
            .as_ref()
            .and_then(|row| row_i64(row, "total_atoms"))
            .unwrap_or(0);
        let finalized = atom_stats
            .as_ref()
            .and_then(|row| row_i64(row, "finalized_atoms"))
            .unwrap_or(0);
        let retrieval_eval_coverage = latest_retrieval_eval
            .as_ref()
            .and_then(|row| row.f64("precision_at_5").ok())
            .unwrap_or(0.0);
        let retrieval_eval_last_run_at = latest_retrieval_eval
            .as_ref()
            .and_then(|row| row.i64_or_none("run_at"));
        let retrieval_eval_last_mrr = latest_retrieval_eval
            .as_ref()
            .and_then(|row| row.f64("mrr").ok());

        let eval_coverage = if total_atoms > 0 {
            finalized as f64 / total_atoms as f64
        } else {
            0.0
        };

        let embedding_coverage =
            compute_embedding_coverage(runtime, token, &ns, total_atoms).await?;

        Ok(json!({
            "total_atoms": total_atoms,
            "total_domains": total_domains,
            "total_events": total_events,
            "eval_coverage": eval_coverage,
            "embedding_coverage": embedding_coverage,
            "retrieval_eval_coverage": retrieval_eval_coverage,
            "retrieval_eval_run_count": retrieval_eval_run_count,
            "retrieval_eval_last_run_at": retrieval_eval_last_run_at,
            "retrieval_eval_last_mrr": retrieval_eval_last_mrr,
            "namespace": ns,
        }))
    }
}

/// Fetch all sections for `atom_id` scoped to `ns`, ordered by `sort_order`.
/// Namespace isolation is preserved: `atom_id` was resolved under `ns` by the
/// caller, and we additionally filter `knowledge_sections.namespace = ns`.
async fn fetch_sections(
    runtime: &KhiveRuntime,
    ns: &str,
    atom_id: &str,
) -> Result<Value, RuntimeError> {
    let sql = runtime.sql();
    let mut reader = sql
        .reader()
        .await
        .map_err(|e| sql_err("get sections reader", e))?;

    let rows = reader
        .query_all(SqlStatement {
            sql: khive_runtime::sql!("knowledge_sections_for_atom").into(),
            params: vec![
                SqlValue::Text(atom_id.to_owned()),
                SqlValue::Text(ns.to_owned()),
            ],
            label: None,
        })
        .await
        .map_err(|e| sql_err("get sections query", e))?;

    let mut sections: Vec<Value> = Vec::with_capacity(rows.len());
    for r in &rows {
        match section_from_row(r) {
            Some(s) => sections.push(section_to_json(&s)),
            None => {
                return Err(RuntimeError::Internal(
                    "knowledge_sections row is malformed (invalid UUID or section_type); \
                     data integrity check required"
                        .into(),
                ));
            }
        }
    }

    Ok(Value::Array(sections))
}

#[cfg(test)]
#[path = "crud_tests.rs"]
mod tests;