knowyourbusiness 0.3.1

Git-backed, searchable knowledge base and incident tracker for AI agent fleets
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
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::OnceLock;

pub const KIND_KNOWLEDGE: &str = "knowledge";
pub const KIND_INCIDENT: &str = "incident";
pub const KIND_TASK: &str = "task";
/// Incident/task keys carry a prefix so the flat key space stays readable and
/// a knowledge entry can never collide with a report or a task.
pub const INCIDENT_PREFIX: &str = "inc-";
pub const TASK_PREFIX: &str = "task-";

pub const SEVERITIES: [&str; 4] = ["low", "medium", "high", "critical"];
pub const STATUSES: [&str; 3] = ["open", "mitigated", "resolved"];
/// Task lifecycle, listing order included: the live states first, then the two
/// terminal ones. Only the terminal states close (and archive) a task.
pub const TASK_STATUSES: [&str; 5] = ["open", "in_progress", "blocked", "done", "dropped"];
/// The statuses a task can sit in while it is still work: `kyb tasks` and the
/// health counter must see all three, not just "open".
pub const TASK_LIVE_STATUSES: [&str; 3] = ["open", "in_progress", "blocked"];
pub const TASK_TERMINAL_STATUSES: [&str; 2] = ["done", "dropped"];
/// Task-only, optional: an empty priority means "not ranked", which is the
/// default and stays the default — nothing infers one.
pub const PRIORITIES: [&str; 4] = ["low", "medium", "high", "critical"];
pub const STATUS_BLOCKED: &str = "blocked";
/// Task-only, optional: who holds the task right now. A short label, not an
/// identity system — bounded so a whole prose paragraph cannot squat in it.
pub const ASSIGNEE_MAX_LEN: usize = 80;

fn default_kind() -> String {
    KIND_KNOWLEDGE.to_string()
}

fn is_default_kind(k: &str) -> bool {
    k == KIND_KNOWLEDGE
}

/// One poisoned/affected slice of the world: what (`scope` — an exchange, a
/// table, a host) and when (`from`/`to`, UTC). Machine-readable so a backtest
/// can exclude the windows without parsing prose.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Window {
    pub scope: String,
    pub from: String,
    pub to: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct Meta {
    key: String,
    title: String,
    #[serde(default = "default_kind", skip_serializing_if = "is_default_kind")]
    kind: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    service: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    hosts: Vec<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    severity: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    status: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    priority: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    blocked_reason: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    assignee: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    parent_task: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    knowledge: Vec<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    resolution: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    detection: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    affected: Vec<Window>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    started_at: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    detected_at: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    mitigated_at: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    resolved_at: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    refs: Vec<String>,
    #[serde(default)]
    updated_at: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Entry {
    pub key: String,
    pub title: String,
    /// "knowledge" (default) or "incident".
    pub kind: String,
    /// Incident-only fields; empty on knowledge entries.
    pub service: String,
    pub hosts: Vec<String>,
    pub severity: String,
    pub status: String,
    /// Task-only, optional: "" | low | medium | high | critical. Empty means
    /// unranked — the server never guesses one.
    pub priority: String,
    /// Task-only, optional: what the task is waiting on. Only meaningful while
    /// status=blocked; a leftover reason on any other status is a lie about the
    /// state, so it is rejected on write and cleared on a transition.
    pub blocked_reason: String,
    /// Task-only, optional: who holds the task right now — a short, stable,
    /// non-secret label ("agent-a", "ops-rotation"). Empty means unclaimed;
    /// nothing infers an owner. Every change is a new git version, so the
    /// history reconstructs who held it when.
    pub assignee: String,
    /// Task-only, optional: the `task-` key this task hangs under. Empty means
    /// top-level. A dangling parent is allowed (a child may be filed before its
    /// parent), self-parenting is not.
    pub parent_task: String,
    /// Keys of the knowledge entries this incident is tied to.
    pub knowledge: Vec<String>,
    /// How the incident ended: what fixed it, or the accepted outcome.
    /// Required to close (status=resolved).
    pub resolution: String,
    /// Executable "is it still happening?" check: a command/SQL plus what the
    /// healthy result looks like. The most actionable field of a report.
    pub detection: String,
    /// Poisoned/affected windows, machine-readable.
    pub affected: Vec<Window>,
    /// Incident timeline, RFC3339 UTC. started/detected come from the writer
    /// (detected_at defaults to filing time); mitigated/resolved are stamped
    /// by the server on the status transition.
    pub started_at: String,
    pub detected_at: String,
    pub mitigated_at: String,
    pub resolved_at: String,
    pub tags: Vec<String>,
    pub refs: Vec<String>,
    /// YYYY-MM-DD; set by the server, and only when content actually changes.
    pub updated_at: String,
    pub body: String,
}

impl Entry {
    pub fn from_markdown(s: &str) -> Result<Entry> {
        let rest = s
            .strip_prefix("---\n")
            .ok_or_else(|| anyhow!("missing frontmatter (file must start with ---)"))?;
        let end = rest
            .find("\n---\n")
            .ok_or_else(|| anyhow!("unclosed frontmatter (---)"))?;
        let meta: Meta = serde_yaml::from_str(&rest[..end]).context("broken yaml in frontmatter")?;
        let body = rest[end + 5..].trim_start_matches('\n').trim_end().to_string();
        Ok(Entry {
            key: meta.key,
            title: meta.title,
            kind: meta.kind,
            service: meta.service,
            hosts: meta.hosts,
            severity: meta.severity,
            status: meta.status,
            priority: meta.priority,
            blocked_reason: meta.blocked_reason,
            assignee: meta.assignee,
            parent_task: meta.parent_task,
            knowledge: meta.knowledge,
            resolution: meta.resolution,
            detection: meta.detection,
            affected: meta.affected,
            started_at: meta.started_at,
            detected_at: meta.detected_at,
            mitigated_at: meta.mitigated_at,
            resolved_at: meta.resolved_at,
            tags: meta.tags,
            refs: meta.refs,
            updated_at: meta.updated_at,
            body,
        })
    }

    pub fn to_markdown(&self) -> String {
        let meta = Meta {
            key: self.key.clone(),
            title: self.title.clone(),
            kind: self.kind.clone(),
            service: self.service.clone(),
            hosts: self.hosts.clone(),
            severity: self.severity.clone(),
            status: self.status.clone(),
            priority: self.priority.clone(),
            blocked_reason: self.blocked_reason.clone(),
            assignee: self.assignee.clone(),
            parent_task: self.parent_task.clone(),
            knowledge: self.knowledge.clone(),
            resolution: self.resolution.clone(),
            detection: self.detection.clone(),
            affected: self.affected.clone(),
            started_at: self.started_at.clone(),
            detected_at: self.detected_at.clone(),
            mitigated_at: self.mitigated_at.clone(),
            resolved_at: self.resolved_at.clone(),
            tags: self.tags.clone(),
            refs: self.refs.clone(),
            updated_at: self.updated_at.clone(),
        };
        let yaml = serde_yaml::to_string(&meta).expect("meta always serializes");
        format!("---\n{yaml}---\n\n{}\n", self.body.trim_end())
    }

    /// Content comparison ignoring updated_at: identical content makes upsert
    /// a no-op — no date bump, no empty commit.
    pub fn same_content(&self, other: &Entry) -> bool {
        self.key == other.key
            && self.title == other.title
            && self.kind == other.kind
            && self.service == other.service
            && self.hosts == other.hosts
            && self.severity == other.severity
            && self.status == other.status
            && self.priority == other.priority
            && self.blocked_reason == other.blocked_reason
            && self.assignee == other.assignee
            && self.parent_task == other.parent_task
            && self.knowledge == other.knowledge
            && self.resolution == other.resolution
            && self.detection == other.detection
            && self.affected == other.affected
            && self.started_at == other.started_at
            && self.detected_at == other.detected_at
            && self.mitigated_at == other.mitigated_at
            && self.resolved_at == other.resolved_at
            && self.tags == other.tags
            && self.refs == other.refs
            && self.body.trim_end() == other.body.trim_end()
    }

    pub fn is_incident(&self) -> bool {
        self.kind == KIND_INCIDENT
    }

    pub fn is_task(&self) -> bool {
        self.kind == KIND_TASK
    }

    /// A closed entry leaves the working tree (archive-on-close); its latest
    /// version stays in the default search. in_progress and blocked are work in
    /// flight, not an ending: they keep the task live in the canon.
    pub fn is_closed(&self) -> bool {
        (self.is_incident() && self.status == "resolved")
            || (self.is_task() && TASK_TERMINAL_STATUSES.contains(&self.status.as_str()))
    }

    /// A task that is still work — the three live statuses. What `kyb tasks`
    /// and `open_tasks` count.
    pub fn is_live_task(&self) -> bool {
        self.is_task() && TASK_LIVE_STATUSES.contains(&self.status.as_str())
    }

    /// Unfinished follow-ups: `- [ ]` checklist items in the body (a body
    /// convention, not schema). Lets a resolve warn about loose ends and a
    /// listing surface reports that still need work.
    pub fn open_followups(&self) -> usize {
        self.body.lines().filter(|l| l.trim_start().starts_with("- [ ]")).count()
    }

    pub fn validate(&self) -> Result<()> {
        if !is_valid_key(&self.key) {
            bail!("key must be a slug: [a-z0-9-], no leading/trailing dash, ≤100 chars");
        }
        if self.title.trim().is_empty() {
            bail!("title is empty");
        }
        match self.kind.as_str() {
            KIND_KNOWLEDGE => {
                if self.key.starts_with(INCIDENT_PREFIX) {
                    bail!("keys starting with '{INCIDENT_PREFIX}' are reserved for incident reports");
                }
                if self.key.starts_with(TASK_PREFIX) {
                    bail!("keys starting with '{TASK_PREFIX}' are reserved for tasks");
                }
            }
            KIND_TASK => {
                if !self.key.starts_with(TASK_PREFIX) {
                    bail!("task keys must start with '{TASK_PREFIX}' (e.g. task-raise-log-retention)");
                }
                if !TASK_STATUSES.contains(&self.status.as_str()) {
                    bail!("task status must be one of: {}", TASK_STATUSES.join("|"));
                }
                if !self.priority.is_empty() && !PRIORITIES.contains(&self.priority.as_str()) {
                    bail!("task priority must be empty or one of: {}", PRIORITIES.join("|"));
                }
                // a reason left over from an earlier block would describe a
                // state the task is no longer in — refuse instead of lying
                if self.status != STATUS_BLOCKED && !self.blocked_reason.trim().is_empty() {
                    bail!(
                        "blocked_reason belongs to status={STATUS_BLOCKED}, not '{}' — clear it or block the task",
                        self.status
                    );
                }
                if self.is_closed() && self.resolution.trim().is_empty() {
                    bail!("closing a task needs a resolution: what came of it, or why it was dropped");
                }
                // an owner label, not a paragraph and not a second body: one
                // line, bounded, and never a place to park a credential
                if !self.assignee.is_empty() {
                    if self.assignee.trim().is_empty() {
                        bail!("assignee is blank — leave it out to mark the task unclaimed");
                    }
                    if self.assignee.chars().count() > ASSIGNEE_MAX_LEN {
                        bail!(
                            "assignee must be at most {ASSIGNEE_MAX_LEN} chars — it is a short owner label, not a note"
                        );
                    }
                    if self.assignee.contains(&['\n', '\r'][..]) {
                        bail!("assignee must be a single line");
                    }
                }
                if !self.parent_task.is_empty() {
                    // a parent that is not a task key would point the tree at a
                    // knowledge entry or an incident, which is not a parent at all
                    if !is_valid_key(&self.parent_task)
                        || !self.parent_task.starts_with(TASK_PREFIX)
                    {
                        bail!(
                            "parent_task must be empty or a valid task key starting with '{TASK_PREFIX}' (got '{}')",
                            self.parent_task
                        );
                    }
                    if self.parent_task == self.key {
                        bail!("a task cannot be its own parent ('{}')", self.key);
                    }
                }
                for k in &self.knowledge {
                    if !is_valid_key(k) {
                        bail!("knowledge link '{k}' is not a valid key slug");
                    }
                }
                if let Some(hit) = find_secret(&self.resolution) {
                    bail!("resolution looks like a secret ({hit}…) — store secrets as pointers in refs");
                }
                if let Some(hit) = find_secret(&self.blocked_reason) {
                    bail!("blocked_reason looks like a secret ({hit}…) — store secrets as pointers in refs");
                }
                if let Some(hit) = find_secret(&self.assignee) {
                    bail!("assignee looks like a secret ({hit}…) — use a stable public label");
                }
            }
            KIND_INCIDENT => {
                if !self.key.starts_with(INCIDENT_PREFIX) {
                    bail!("incident keys must start with '{INCIDENT_PREFIX}' (e.g. inc-2026-07-22-orders-api-oom)");
                }
                if self.service.trim().is_empty() {
                    bail!("incident needs a service (what broke)");
                }
                if !SEVERITIES.contains(&self.severity.as_str()) {
                    bail!("severity must be one of: {}", SEVERITIES.join("|"));
                }
                if !STATUSES.contains(&self.status.as_str()) {
                    bail!("status must be one of: {}", STATUSES.join("|"));
                }
                if self.status == "resolved" && self.resolution.trim().is_empty() {
                    bail!("closing an incident needs a resolution: what fixed it, or the accepted outcome");
                }
                for k in &self.knowledge {
                    if !is_valid_key(k) {
                        bail!("knowledge link '{k}' is not a valid key slug");
                    }
                }
                for w in &self.affected {
                    if w.scope.trim().is_empty() || w.from.trim().is_empty() || w.to.trim().is_empty()
                    {
                        bail!("affected window needs scope, from and to (got scope='{}' from='{}' to='{}')",
                            w.scope, w.from, w.to);
                    }
                }
                if let Some(hit) = find_secret(&self.resolution) {
                    bail!("resolution looks like a secret ({hit}…) — store secrets as pointers in refs");
                }
                if let Some(hit) = find_secret(&self.detection) {
                    bail!("detection looks like a secret ({hit}…) — store secrets as pointers in refs");
                }
            }
            other => bail!(
                "kind must be '{KIND_KNOWLEDGE}', '{KIND_INCIDENT}' or '{KIND_TASK}', got '{other}'"
            ),
        }
        // priority, blocked_reason, assignee and parent_task are the task lane
        // only: an incident is ranked by severity and owned by whoever is on
        // call, a knowledge entry is a fact and has no owner at all
        if !self.is_task() {
            if !self.priority.trim().is_empty() {
                bail!("priority is a task-only field (got '{}' on kind '{}')", self.priority, self.kind);
            }
            if !self.blocked_reason.trim().is_empty() {
                bail!("blocked_reason is a task-only field (kind '{}')", self.kind);
            }
            if !self.assignee.trim().is_empty() {
                bail!("assignee is a task-only field (kind '{}')", self.kind);
            }
            if !self.parent_task.trim().is_empty() {
                bail!("parent_task is a task-only field (kind '{}')", self.kind);
            }
        }
        if let Some(hit) = find_secret(&self.body) {
            bail!("body looks like a secret ({hit}…) — store secrets as pointers in refs");
        }
        for r in &self.refs {
            if let Some(hit) = find_secret(r) {
                bail!("refs look like a secret ({hit}…) — refs are pointers, not the secrets");
            }
        }
        Ok(())
    }
}

impl Default for Entry {
    fn default() -> Entry {
        Entry {
            key: String::new(),
            title: String::new(),
            kind: default_kind(),
            service: String::new(),
            hosts: vec![],
            severity: String::new(),
            status: String::new(),
            priority: String::new(),
            blocked_reason: String::new(),
            assignee: String::new(),
            parent_task: String::new(),
            knowledge: vec![],
            resolution: String::new(),
            detection: String::new(),
            affected: vec![],
            started_at: String::new(),
            detected_at: String::new(),
            mitigated_at: String::new(),
            resolved_at: String::new(),
            tags: vec![],
            refs: vec![],
            updated_at: String::new(),
            body: String::new(),
        }
    }
}

/// One validator for every key input: upsert payloads AND path params of
/// GET/DELETE/history (otherwise `..%2F` in a URL walks the filesystem).
pub fn is_valid_key(k: &str) -> bool {
    !k.is_empty()
        && k.len() <= 100
        && k.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        && !k.starts_with('-')
        && !k.ends_with('-')
}

static SECRET_RES: OnceLock<Vec<regex::Regex>> = OnceLock::new();

fn secret_res() -> &'static [regex::Regex] {
    SECRET_RES.get_or_init(|| {
        [
            r"ghp_[A-Za-z0-9]{20,}",
            r"github_pat_[A-Za-z0-9_]{20,}",
            r"xox[baprs]-[A-Za-z0-9-]{10,}",
            r"\bsk-[A-Za-z0-9_-]{24,}",
            r"AKIA[0-9A-Z]{16}",
            r"-----BEGIN [A-Z ]*PRIVATE KEY",
            r#"(?i)(password|passwd|пароль)\s*[:=]\s*[^\s"']{6,}"#,
        ]
        .iter()
        .map(|p| regex::Regex::new(p).expect("valid pattern"))
        .collect()
    })
}

pub fn find_secret(text: &str) -> Option<String> {
    secret_res()
        .iter()
        .find_map(|re| re.find(text).map(|m| m.as_str().chars().take(20).collect()))
}

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

    fn entry() -> Entry {
        Entry {
            key: "nats-streams".into(),
            title: "NATS — always CreateOrUpdateStream".into(),
            tags: vec!["nats".into(), "infra".into()],
            refs: vec!["see .env on host-a".into()],
            updated_at: "2026-07-19".into(),
            body: "Always use CreateOrUpdateStream.\n\nRelated: [[orders-api]].".into(),
            ..Default::default()
        }
    }

    fn incident() -> Entry {
        Entry {
            key: "inc-2026-07-22-orders-api-oom".into(),
            title: "orders_api OOM on host-a".into(),
            kind: KIND_INCIDENT.into(),
            service: "orders_api".into(),
            hosts: vec!["host-a".into()],
            severity: "high".into(),
            status: "open".into(),
            knowledge: vec!["orders-api-architecture".into()],
            tags: vec!["acme".into()],
            updated_at: "2026-07-22".into(),
            body: "What happened: the container hit the memory limit.\nWorkaround: restart it.".into(),
            ..Default::default()
        }
    }

    #[test]
    fn roundtrip() {
        let e = entry();
        let md = e.to_markdown();
        let back = Entry::from_markdown(&md).unwrap();
        assert_eq!(e, back);
    }

    #[test]
    fn incident_roundtrip() {
        let e = incident();
        let md = e.to_markdown();
        assert!(md.contains("kind: incident"), "{md}");
        assert!(md.contains("service: orders_api"), "{md}");
        let back = Entry::from_markdown(&md).unwrap();
        assert_eq!(e, back);
        assert!(back.is_incident());
    }

    // knowledge entries must not leak incident frontmatter noise
    #[test]
    fn knowledge_frontmatter_stays_clean() {
        let md = entry().to_markdown();
        for f in ["kind:", "service:", "severity:", "status:", "hosts:", "knowledge:"] {
            assert!(!md.contains(f), "unexpected '{f}' in:\n{md}");
        }
    }

    // files written before the incident feature (no kind field) stay readable
    #[test]
    fn legacy_file_defaults_to_knowledge() {
        let md = "---\nkey: old-entry\ntitle: An old fact\n---\n\nbody\n";
        let e = Entry::from_markdown(md).unwrap();
        assert_eq!(e.kind, KIND_KNOWLEDGE);
        assert!(!e.is_incident());
        assert!(e.validate().is_ok());
    }

    #[test]
    fn incident_validation_ok() {
        assert!(incident().validate().is_ok());
    }

    // --- incident validation: each rule fires ---
    #[rstest]
    #[case::key_without_prefix(|e: &mut Entry| e.key = "orders-api-oom".into())]
    #[case::no_service(|e: &mut Entry| e.service = "  ".into())]
    #[case::bad_severity(|e: &mut Entry| e.severity = "huge".into())]
    #[case::empty_severity(|e: &mut Entry| e.severity = String::new())]
    #[case::bad_status(|e: &mut Entry| e.status = "wip".into())]
    #[case::empty_status(|e: &mut Entry| e.status = String::new())]
    #[case::bad_knowledge_link(|e: &mut Entry| e.knowledge = vec!["Bad Key".into()])]
    #[case::bad_kind(|e: &mut Entry| e.kind = "report".into())]
    #[case::resolved_without_resolution(|e: &mut Entry| e.status = "resolved".into())]
    #[case::secret_in_resolution(|e: &mut Entry| {
        e.status = "resolved".into();
        e.resolution = "rotated to password: super123secret".into();
    })]
    fn incident_validation_rejects(#[case] mutate: fn(&mut Entry)) {
        let mut e = incident();
        mutate(&mut e);
        assert!(e.validate().is_err(), "must be rejected: {e:?}");
    }

    // the actionable fields (detection, windows, timeline) roundtrip intact
    #[test]
    fn incident_actionable_fields_roundtrip() {
        let mut e = incident();
        e.detection = "SELECT count() FROM t WHERE price > 50 * yesterday_max; healthy = 0 rows".into();
        e.affected = vec![
            Window { scope: "okx".into(), from: "2026-07-22T08:09:40Z".into(), to: "2026-07-22T21:09:37Z".into() },
            Window { scope: "gateio".into(), from: "2026-07-22T08:20:09Z".into(), to: "2026-07-22T20:04:41Z".into() },
        ];
        e.started_at = "2026-07-22T08:09:40Z".into();
        e.detected_at = "2026-07-22T19:30:00Z".into();
        e.mitigated_at = "2026-07-22T20:04:41Z".into();
        e.resolved_at = "2026-07-22T21:55:00Z".into();
        assert!(e.validate().is_ok());
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back, e);
        // and they count as content: adding a window is a new version
        let mut f = back.clone();
        f.affected.pop();
        assert!(!e.same_content(&f));
    }

    #[rstest]
    #[case::empty_scope(Window { scope: " ".into(), from: "a".into(), to: "b".into() })]
    #[case::empty_from(Window { scope: "okx".into(), from: "".into(), to: "b".into() })]
    #[case::empty_to(Window { scope: "okx".into(), from: "a".into(), to: " ".into() })]
    fn bad_affected_window_rejected(#[case] w: Window) {
        let mut e = incident();
        e.affected = vec![w];
        assert!(e.validate().is_err());
    }

    #[test]
    fn secret_in_detection_rejected() {
        let mut e = incident();
        e.detection = "curl -u admin --password: super123secret host".into();
        assert!(e.validate().is_err());
    }

    // follow-ups: a body convention the server can count
    #[test]
    fn open_followups_counted() {
        let mut e = incident();
        assert_eq!(e.open_followups(), 0);
        e.body = "Follow-ups:\n- [ ] guard dev NATS\n  - [ ] nested also counts\n- [x] webui filter\n- [] not a checkbox\n".into();
        assert_eq!(e.open_followups(), 2);
    }

    // closing with a resolution is the happy path; roundtrips through markdown
    #[test]
    fn incident_close_with_resolution() {
        let mut e = incident();
        e.status = "resolved".into();
        e.resolution = "Raised the memory limit to 2G and fixed the batch flush leak.".into();
        assert!(e.validate().is_ok());
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back, e);
        // mitigated does not demand a resolution yet
        e.status = "mitigated".into();
        e.resolution = String::new();
        assert!(e.validate().is_ok());
    }

    // the inc- prefix is reserved: a knowledge entry cannot squat on it
    #[test]
    fn knowledge_cannot_use_incident_prefix() {
        let mut e = entry();
        e.key = "inc-2026-07-22-fake".into();
        assert!(e.validate().is_err());
    }

    // incident status/severity changes are content changes (versioned), not no-ops
    #[test]
    fn incident_status_change_is_a_change() {
        let a = incident();
        let mut b = incident();
        b.status = "resolved".into();
        assert!(!a.same_content(&b));
        let mut c = incident();
        c.knowledge.push("nats-streams".into());
        assert!(!a.same_content(&c));
    }

    fn task() -> Entry {
        Entry {
            key: "task-raise-log-retention".into(),
            title: "Raise container log retention to 72h".into(),
            kind: KIND_TASK.into(),
            status: "open".into(),
            tags: vec!["idea".into()],
            updated_at: "2026-08-15".into(),
            body: "Short retention loses evidence.\n\n- [ ] measure log volume first".into(),
            ..Default::default()
        }
    }

    // --- task priority: optional, and only the four ranks ---
    #[rstest]
    #[case::unranked("", true)]
    #[case::low("low", true)]
    #[case::medium("medium", true)]
    #[case::high("high", true)]
    #[case::critical("critical", true)]
    #[case::unknown_rank("urgent", false)]
    #[case::wrong_case("HIGH", false)]
    #[case::blank("  ", false)]
    #[case::numeric("1", false)]
    fn task_priority_validation(#[case] priority: &str, #[case] ok: bool) {
        let mut e = task();
        e.priority = priority.into();
        assert_eq!(e.validate().is_ok(), ok, "priority '{priority}'");
    }

    // priority is the task lane only — the other kinds are not ranked this way
    #[rstest]
    #[case::knowledge_priority(entry(), |e: &mut Entry| e.priority = "high".into())]
    #[case::knowledge_blocked_reason(entry(), |e: &mut Entry| e.blocked_reason = "waiting".into())]
    #[case::knowledge_assignee(entry(), |e: &mut Entry| e.assignee = "agent-a".into())]
    #[case::knowledge_parent(entry(), |e: &mut Entry| e.parent_task = "task-parent".into())]
    #[case::incident_priority(incident(), |e: &mut Entry| e.priority = "high".into())]
    #[case::incident_blocked_reason(incident(), |e: &mut Entry| e.blocked_reason = "waiting".into())]
    #[case::incident_assignee(incident(), |e: &mut Entry| e.assignee = "agent-a".into())]
    #[case::incident_parent(incident(), |e: &mut Entry| e.parent_task = "task-parent".into())]
    fn task_only_fields_rejected_elsewhere(#[case] mut e: Entry, #[case] mutate: fn(&mut Entry)) {
        assert!(e.validate().is_ok(), "baseline must be valid: {e:?}");
        mutate(&mut e);
        assert!(e.validate().is_err(), "task-only field must be rejected: {e:?}");
    }

    // --- task statuses: three live, two terminal ---
    #[rstest]
    #[case("open", true, false)]
    #[case("in_progress", true, false)]
    #[case("blocked", true, false)]
    #[case("done", false, true)]
    #[case("dropped", false, true)]
    fn task_status_lifecycle(#[case] status: &str, #[case] live: bool, #[case] closed: bool) {
        let mut e = task();
        e.status = status.into();
        // only the terminal statuses demand an outcome
        e.resolution = "what came of it".into();
        assert!(e.validate().is_ok(), "status '{status}' must be accepted");
        assert_eq!(e.is_live_task(), live, "live('{status}')");
        assert_eq!(e.is_closed(), closed, "closed('{status}')");
    }

    #[rstest]
    #[case::unknown("wip")]
    #[case::empty("")]
    #[case::dash("in-progress")]
    #[case::incident_status("mitigated")]
    fn bad_task_status_rejected(#[case] status: &str) {
        let mut e = task();
        e.status = status.into();
        assert!(e.validate().is_err(), "status '{status}' must be rejected");
    }

    // in_progress and blocked are work in flight: they do NOT need a resolution
    // and do NOT archive
    #[test]
    fn live_statuses_need_no_resolution() {
        for status in ["in_progress", "blocked"] {
            let mut e = task();
            e.status = status.into();
            assert!(e.validate().is_ok(), "{status} must not demand a resolution");
            assert!(!e.is_closed());
        }
        // the terminal ones still do
        let mut e = task();
        e.status = "done".into();
        assert!(e.validate().is_err(), "done still needs a resolution");
    }

    // a blocked reason on any other status describes a state the task is not in
    #[test]
    fn blocked_reason_belongs_to_blocked() {
        let mut e = task();
        e.status = STATUS_BLOCKED.into();
        e.blocked_reason = "waiting on the vendor to ship the fix".into();
        assert!(e.validate().is_ok());
        // blocked without a reason stays legal — the field is optional
        e.blocked_reason = String::new();
        assert!(e.validate().is_ok());
        // but a stale reason on a live or terminal status is refused
        for status in ["open", "in_progress", "done"] {
            let mut stale = task();
            stale.status = status.into();
            stale.resolution = "outcome".into();
            stale.blocked_reason = "waiting on the vendor".into();
            let err = stale.validate().unwrap_err().to_string();
            assert!(err.contains("blocked_reason"), "status '{status}': {err}");
        }
    }

    #[test]
    fn secret_in_blocked_reason_rejected() {
        let mut e = task();
        e.status = STATUS_BLOCKED.into();
        e.blocked_reason = "waiting for the password: super123secret rotation".into();
        assert!(e.validate().is_err());
    }

    // the new fields survive markdown and count as content
    #[test]
    fn task_roundtrip_with_priority_and_block() {
        let mut e = task();
        e.priority = "critical".into();
        e.status = STATUS_BLOCKED.into();
        e.blocked_reason = "waiting on the host-a disk upgrade".into();
        e.knowledge = vec!["web-app-architecture".into()];
        assert!(e.validate().is_ok());
        let md = e.to_markdown();
        assert!(md.contains("kind: task"), "{md}");
        assert!(md.contains("priority: critical"), "{md}");
        assert!(md.contains("blocked_reason: waiting on the host-a disk upgrade"), "{md}");
        let back = Entry::from_markdown(&md).unwrap();
        assert_eq!(back, e);
        assert!(back.is_task());

        // both fields are content: changing either is a new version
        let mut other = back.clone();
        other.priority = "low".into();
        assert!(!e.same_content(&other));
        let mut other = back.clone();
        other.blocked_reason = "waiting on something else".into();
        assert!(!e.same_content(&other));
    }

    // --- task ownership: an optional, bounded, non-secret label ---
    #[rstest]
    #[case::unclaimed("", true)]
    #[case::label("agent-a", true)]
    #[case::rotation("ops-rotation", true)]
    #[case::spaces_inside("release duty", true)]
    #[case::blank("   ", false)]
    #[case::multiline("agent-a\nagent-b", false)]
    #[case::carriage_return("agent-a\ragent-b", false)]
    #[case::too_long("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false)]
    #[case::secret("token: ghp_abcdefghijklmnopqrstuvwxyz123456", false)]
    fn task_assignee_validation(#[case] assignee: &str, #[case] ok: bool) {
        let mut e = task();
        e.assignee = assignee.into();
        assert_eq!(e.validate().is_ok(), ok, "assignee '{assignee}'");
    }

    #[test]
    fn assignee_length_boundary() {
        let mut e = task();
        e.assignee = "a".repeat(ASSIGNEE_MAX_LEN);
        assert!(e.validate().is_ok(), "exactly the limit is fine");
        e.assignee = "a".repeat(ASSIGNEE_MAX_LEN + 1);
        assert!(e.validate().is_err(), "one over the limit is not");
    }

    // --- parent_task: empty or a real task key, never itself ---
    #[rstest]
    #[case::top_level("", true)]
    #[case::task_key("task-migrate-logs", true)]
    // a forward reference is legal: a child may be filed before its parent
    #[case::dangling_parent("task-not-written-yet", true)]
    #[case::knowledge_key("nats-streams", false)]
    #[case::incident_key("inc-2026-08-15-oom", false)]
    #[case::not_a_slug("task-Bad Key", false)]
    #[case::traversal("../task-x", false)]
    #[case::bare_prefix("task-", false)]
    #[case::blank("  ", false)]
    fn task_parent_validation(#[case] parent: &str, #[case] ok: bool) {
        let mut e = task();
        e.parent_task = parent.into();
        assert_eq!(e.validate().is_ok(), ok, "parent_task '{parent}'");
    }

    // a task that parents itself is a cycle of one — the smallest broken tree
    #[test]
    fn self_parenting_rejected() {
        let mut e = task();
        e.parent_task = e.key.clone();
        let err = e.validate().unwrap_err().to_string();
        assert!(err.contains("own parent"), "{err}");
    }

    // ownership and the parent link survive markdown and count as content
    #[test]
    fn task_assignee_parent_roundtrip() {
        let mut e = task();
        e.status = "in_progress".into();
        e.assignee = "agent-a".into();
        e.parent_task = "task-migrate-logs".into();
        assert!(e.validate().is_ok());
        let md = e.to_markdown();
        assert!(md.contains("assignee: agent-a"), "{md}");
        assert!(md.contains("parent_task: task-migrate-logs"), "{md}");
        let back = Entry::from_markdown(&md).unwrap();
        assert_eq!(back, e);

        // both are content: changing either is a new version, not a no-op
        let mut other = back.clone();
        other.assignee = "agent-b".into();
        assert!(!e.same_content(&other));
        let mut other = back.clone();
        other.parent_task = "task-other-parent".into();
        assert!(!e.same_content(&other));
        let mut other = back.clone();
        other.assignee.clear();
        assert!(!e.same_content(&other), "handing a task back is a change too");
        // and the date still is not
        let mut same = back.clone();
        same.updated_at = "2020-01-01".into();
        assert!(e.same_content(&same));
    }

    // an unranked, unblocked, unclaimed task writes no new frontmatter at all —
    // files from before the feature parse identically
    #[test]
    fn task_frontmatter_stays_clean_without_new_fields() {
        let md = task().to_markdown();
        for f in ["priority:", "blocked_reason:", "assignee:", "parent_task:"] {
            assert!(!md.contains(f), "unexpected '{f}' in:\n{md}");
        }
        let legacy = "---\nkey: task-old\ntitle: An old task\nkind: task\nstatus: open\n---\n\nbody\n";
        let e = Entry::from_markdown(legacy).unwrap();
        assert_eq!(e.priority, "");
        assert_eq!(e.blocked_reason, "");
        assert_eq!(e.assignee, "");
        assert_eq!(e.parent_task, "");
        assert!(e.validate().is_ok());
        assert!(e.is_live_task());
        // and a task written by this version reads back unchanged after a
        // round-trip through the legacy-shaped parser
        assert_eq!(Entry::from_markdown(&e.to_markdown()).unwrap(), e);
    }

    #[test]
    fn roundtrip_empty_lists() {
        let mut e = entry();
        e.tags.clear();
        e.refs.clear();
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(e, back);
    }

    #[test]
    fn body_with_dashes_survives() {
        let mut e = entry();
        e.body = "before\n---\nafter".into();
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back.body, e.body);
    }

    // --- keys: valid slugs ---
    #[rstest]
    #[case("a")]
    #[case("key")]
    #[case("nats-streams")]
    #[case("a-b-c-d")]
    #[case("key9")]
    #[case("9key")]
    #[case("a--b")]
    #[case("orders-api-deploy-2026")]
    #[case("x1")]
    #[case("0")]
    fn valid_keys(#[case] k: &str) {
        assert!(is_valid_key(k), "'{k}' must be accepted");
    }

    // --- keys: garbage and traversal ---
    #[rstest]
    #[case("")]
    #[case("-a")]
    #[case("a-")]
    #[case("-")]
    #[case("A")]
    #[case("Key")]
    #[case("a b")]
    #[case("a_b")]
    #[case("a.b")]
    #[case("a/b")]
    #[case("../etc")]
    #[case("..")]
    #[case(".git")]
    #[case("ключ")]
    #[case("key!")]
    #[case("a\\b")]
    fn invalid_keys(#[case] k: &str) {
        assert!(!is_valid_key(k), "'{k}' must be rejected");
    }

    #[test]
    fn key_length_limit() {
        assert!(is_valid_key(&"a".repeat(100)));
        assert!(!is_valid_key(&"a".repeat(101)));
    }

    // --- secret heuristics: must detect ---
    #[rstest]
    #[case("ghp_abcdefghijklmnopqrstuvwxyz123456")]
    #[case("token: github_pat_11ABCDEFGH_abcdefghijklmnopqrst")]
    #[case("xoxb-123456789012-abcdefghijklmnop")]
    #[case("slack xoxp-1-2-3-abcdefghij")]
    #[case("key sk-proj-abcdefghijklmnopqrstuvwxyz")]
    #[case("AKIAIOSFODNN7EXAMPLE")]
    #[case("-----BEGIN RSA PRIVATE KEY-----")]
    #[case("-----BEGIN OPENSSH PRIVATE KEY-----")]
    #[case("-----BEGIN PRIVATE KEY-----")]
    #[case("password: hunter2secret")]
    #[case("password=SuperSecret99")]
    #[case("passwd = qwerty123456")]
    #[case("Пароль: сложный123пароль")] // cyrillic keyword, case-insensitive — data on purpose
    fn secrets_detected(#[case] s: &str) {
        assert!(find_secret(s).is_some(), "must be detected: {s}");
        let mut e = entry();
        e.body = s.into();
        assert!(e.validate().is_err());
    }

    // --- secret heuristics: no false positives ---
    #[rstest]
    #[case("commit a77ed01118d25f8cd76c9ec38f2a77ed01118d25")]
    #[case("mentions the ghp_ prefix, no token")]
    #[case("sk-short")]
    #[case("AKIA alone is not a key")]
    #[case("-----BEGIN CERTIFICATE-----")]
    #[case("-----BEGIN PUBLIC KEY-----")]
    #[case("ssh-rsa AAAAB3NzaC1yc2E user@host is a public key")]
    #[case("пароль лежит в 1Password")] // cyrillic keyword without a value — data on purpose
    #[case("password policy: minimum 12 chars")]
    #[case("plain text about nats and streams")]
    #[case("xoxb- truncated is harmless")]
    #[case("[[task-web-app-symbol-references-coordinate-base]]")]
    fn secrets_not_flagged(#[case] s: &str) {
        assert!(find_secret(s).is_none(), "false positive on: {s}");
    }

    // secrets in refs are rejected too
    #[test]
    fn secret_in_refs_rejected() {
        let mut e = entry();
        e.refs = vec!["ghp_abcdefghijklmnopqrstuvwxyz123456".into()];
        assert!(e.validate().is_err());
    }

    #[test]
    fn empty_title_rejected() {
        let mut e = entry();
        e.title = "   ".into();
        assert!(e.validate().is_err());
    }

    // --- round-trip of wild bodies ---
    #[rstest]
    #[case("")]
    #[case("plain body")]
    #[case("---\nstarts with a delimiter")]
    #[case("```rust\nfn main() {}\n```")]
    #[case("[[link-one]] and [[link-two]]")]
    #[case("emoji 🚀🔥 and «guillemets»")]
    #[case("tabs\tand   spaces")]
    #[case("multiline\n\n\nwith blanks")]
    #[case("internal\r\nCRLF preserved")]
    #[case("yaml-like:\n  key: value\n---\n- list")]
    #[case("# heading\n## another")]
    #[case("<html><b>markup</b></html>")]
    #[case("кириллица, 中文, العربية")] // unicode payloads stay intact — data on purpose
    fn body_roundtrip(#[case] body: &str) {
        let mut e = entry();
        e.body = body.trim_end().to_string();
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back, e);
    }

    // --- round-trip of yaml-special titles ---
    #[rstest]
    #[case("plain title")]
    #[case("NATS: with a colon")]
    #[case("\"quoted\"")]
    #[case("with 'apostrophes'")]
    #[case("[brackets] and {braces}")]
    #[case("- starts with a dash")]
    #[case("123")]
    #[case("null")]
    #[case("true")]
    #[case("multiline\ntitle")]
    #[case("#hash and *stars*")]
    #[case("| pipe and > arrow")]
    #[case("Русский тайтл со смыслом")] // real titles will be Russian — data on purpose
    fn title_roundtrip(#[case] title: &str) {
        let mut e = entry();
        e.title = title.to_string();
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back.title, e.title);
    }

    #[test]
    fn tags_refs_special_chars_roundtrip() {
        let mut e = entry();
        e.tags = vec!["UPPER".into(), "with-dash".into(), "кириллица".into(), "a:b".into()];
        e.refs = vec!["see .env on host-a".into(), "https://example.com/path?q=1&x=2".into()];
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back, e);
    }

    #[test]
    fn huge_body_roundtrip() {
        let mut e = entry();
        e.body = "a line of knowledge about services and infra\n".repeat(20_000).trim_end().to_string();
        let back = Entry::from_markdown(&e.to_markdown()).unwrap();
        assert_eq!(back.body.len(), e.body.len());
    }

    #[test]
    fn bad_frontmatter_is_error() {
        assert!(Entry::from_markdown("plain text without frontmatter").is_err());
        assert!(Entry::from_markdown("---\nkey: x\ntitle: t\n").is_err()); // unclosed
        assert!(Entry::from_markdown("---\nnot yaml at all: [\n---\n\nbody\n").is_err());
    }

    #[test]
    fn same_content_ignores_date() {
        let a = entry();
        let mut b = entry();
        b.updated_at = "2020-01-01".into();
        assert!(a.same_content(&b));
        b.body = "different".into();
        assert!(!a.same_content(&b));
    }

    /// The case that prompted this: two agents wrote the same rule minutes
    /// apart, one key ending in "base" and the other in "baseline".
    #[test]
    fn a_near_twin_key_is_surfaced() {
        let existing = [
            "rule-name-your-comparison-baseline",
            "rule-limitations-section-verified-last",
            "kyb-temporal-query-gap",
        ];
        assert_eq!(
            similar_keys("rule-name-your-comparison-base", existing.into_iter()),
            vec!["rule-name-your-comparison-baseline"]
        );
    }

    /// A deliberate series is not a slip, and a warning that fires on one
    /// teaches people to ignore it. Calibrated against the operator's own key
    /// space, where these three shapes are the whole of the false positives.
    #[rstest]
    #[case("questiontocase-benchmark-v2-2026-09-17", "questiontocase-benchmark-v1-2026-09-17")]
    #[case("tester-run16-analysis", "tester-run15-analysis")]
    #[case("task-prod-code-rag-rat-rust-receiver-resolution", "prod-code-rag-rat-rust-receiver-resolution")]
    fn a_series_is_not_a_duplicate(#[case] new: &str, #[case] existing: &str) {
        assert!(
            similar_keys(new, [existing].into_iter()).is_empty(),
            "{new} vs {existing} differ only by a number or a kind prefix"
        );
    }

    #[test]
    fn unrelated_keys_stay_quiet() {
        let existing = ["nats-streams", "kyb-architecture", "inc-2026-08-06-orders-api-oom"];
        assert!(similar_keys("queue-retention", existing.into_iter()).is_empty());
        // and a key never reports itself
        assert!(similar_keys("nats-streams", ["nats-streams"].into_iter()).is_empty());
    }

    #[test]
    fn diff_reports_the_fields_that_moved() {
        let mut a = Entry {
            key: "svc".into(),
            title: "Service".into(),
            status: "open".into(),
            tags: vec!["infra".into()],
            body: "line one\nthe port is 8080\nline three".into(),
            ..Default::default()
        };
        let mut b = a.clone();
        b.status = "resolved".into();
        b.tags = vec!["infra".into(), "postmortem".into()];
        b.body = "line one\nthe port is 9090\nline three".into();

        let (fields, body) = diff_entries(&a, &b);
        assert_eq!(
            fields,
            vec![
                FieldChange { field: "status", from: "open".into(), to: "resolved".into() },
                FieldChange { field: "tags", from: "infra".into(), to: "infra, postmortem".into() },
            ]
        );
        assert_eq!(body.removed, vec!["the port is 8080"]);
        assert_eq!(body.added, vec!["the port is 9090"]);

        // identical versions produce nothing at all
        a.status = "resolved".into();
        a.tags = b.tags.clone();
        a.body = b.body.clone();
        let (fields, body) = diff_entries(&a, &b);
        assert!(fields.is_empty());
        assert_eq!(body, BodyDiff::default());
    }

    /// The point of the LCS: inserting one line must report one added line, not
    /// every line after it.
    #[test]
    fn diff_does_not_cascade_after_an_insert() {
        let a = Entry { body: "a\nb\nc\nd".into(), ..Default::default() };
        let b = Entry { body: "a\nb\nNEW\nc\nd".into(), ..Default::default() };
        let (_, body) = diff_entries(&a, &b);
        assert_eq!(body.added, vec!["NEW"]);
        assert!(body.removed.is_empty(), "nothing was removed: {:?}", body.removed);
    }

    #[test]
    fn diff_falls_back_on_a_body_too_large_to_align() {
        let big: String = (0..LCS_MAX_LINES + 10).map(|i| format!("line {i}\n")).collect();
        let a = Entry { body: big.clone(), ..Default::default() };
        let b = Entry { body: format!("{big}extra tail\n"), ..Default::default() };
        let (_, body) = diff_entries(&a, &b);
        assert_eq!(body.added, vec!["extra tail"], "the fallback still finds what appeared");
        assert!(body.removed.is_empty());
    }

}

/// One scalar or list field that differs between two versions of an entry.
#[derive(Debug, Clone, serde::Serialize, PartialEq)]
pub struct FieldChange {
    pub field: &'static str,
    pub from: String,
    pub to: String,
}

/// Body lines that appeared and disappeared between two versions.
#[derive(Debug, Clone, Default, serde::Serialize, PartialEq)]
pub struct BodyDiff {
    pub added: Vec<String>,
    pub removed: Vec<String>,
}

/// Longest common subsequence over lines, so the diff reports the lines that
/// actually moved rather than every line after the first edit.
///
/// Quadratic, which is fine for entry-sized bodies. Past `LCS_MAX_LINES` it
/// falls back to comparing line multisets: still correct about what appeared and
/// disappeared, just blind to order. An entry that large is prose nobody diffs
/// line by line anyway, and the alternative is an endpoint that can hang.
const LCS_MAX_LINES: usize = 2_000;

fn line_diff(from: &str, to: &str) -> BodyDiff {
    let a: Vec<&str> = from.lines().collect();
    let b: Vec<&str> = to.lines().collect();
    if a.len() > LCS_MAX_LINES || b.len() > LCS_MAX_LINES {
        let mut counts: HashMap<&str, i64> = HashMap::new();
        for l in &a {
            *counts.entry(l).or_default() += 1;
        }
        for l in &b {
            *counts.entry(l).or_default() -= 1;
        }
        let mut out = BodyDiff::default();
        for l in &a {
            if counts.get(l).copied().unwrap_or(0) > 0 {
                out.removed.push((*l).to_string());
                *counts.get_mut(l).unwrap() -= 1;
            }
        }
        for l in &b {
            if counts.get(l).copied().unwrap_or(0) < 0 {
                out.added.push((*l).to_string());
                *counts.get_mut(l).unwrap() += 1;
            }
        }
        return out;
    }

    let (n, m) = (a.len(), b.len());
    let mut table = vec![0u32; (n + 1) * (m + 1)];
    let at = |i: usize, j: usize| i * (m + 1) + j;
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            table[at(i, j)] = if a[i] == b[j] {
                table[at(i + 1, j + 1)] + 1
            } else {
                table[at(i + 1, j)].max(table[at(i, j + 1)])
            };
        }
    }
    let mut out = BodyDiff::default();
    let (mut i, mut j) = (0usize, 0usize);
    while i < n && j < m {
        if a[i] == b[j] {
            i += 1;
            j += 1;
        } else if table[at(i + 1, j)] >= table[at(i, j + 1)] {
            out.removed.push(a[i].to_string());
            i += 1;
        } else {
            out.added.push(b[j].to_string());
            j += 1;
        }
    }
    out.removed.extend(a[i..].iter().map(|s| s.to_string()));
    out.added.extend(b[j..].iter().map(|s| s.to_string()));
    out
}

/// What changed between two versions of one entry.
///
/// `/history` answers *that* an entry changed. This answers *what* — the
/// question an agent has when a fact it is holding turns out to have moved.
pub fn diff_entries(from: &Entry, to: &Entry) -> (Vec<FieldChange>, BodyDiff) {
    let join = |v: &[String]| v.join(", ");
    let mut fields = vec![];
    let mut scalar = |name: &'static str, a: &str, b: &str| {
        if a != b {
            fields.push(FieldChange { field: name, from: a.to_string(), to: b.to_string() });
        }
    };
    scalar("title", &from.title, &to.title);
    scalar("kind", &from.kind, &to.kind);
    scalar("service", &from.service, &to.service);
    scalar("severity", &from.severity, &to.severity);
    scalar("status", &from.status, &to.status);
    scalar("priority", &from.priority, &to.priority);
    scalar("blocked_reason", &from.blocked_reason, &to.blocked_reason);
    scalar("assignee", &from.assignee, &to.assignee);
    scalar("parent_task", &from.parent_task, &to.parent_task);
    scalar("resolution", &from.resolution, &to.resolution);
    scalar("detection", &from.detection, &to.detection);
    scalar("started_at", &from.started_at, &to.started_at);
    scalar("detected_at", &from.detected_at, &to.detected_at);
    scalar("mitigated_at", &from.mitigated_at, &to.mitigated_at);
    scalar("resolved_at", &from.resolved_at, &to.resolved_at);
    scalar("updated_at", &from.updated_at, &to.updated_at);
    scalar("hosts", &join(&from.hosts), &join(&to.hosts));
    scalar("tags", &join(&from.tags), &join(&to.tags));
    scalar("refs", &join(&from.refs), &join(&to.refs));
    scalar("knowledge", &join(&from.knowledge), &join(&to.knowledge));
    (fields, line_diff(&from.body, &to.body))
}

/// Keys close enough to a new one that the author should see them before
/// committing to a name.
///
/// A knowledge base is worth what it is findable at, and two near-identical keys
/// split one topic in half without anything failing: both entries exist, both
/// answer, and a search finds whichever it likes. Nothing in the system objects,
/// because nothing is wrong - which is the shape of every expensive failure we
/// keep meeting.
///
/// This informs, it does not block. Calibrated on the operator's own 866 keys:
/// at a 0.85 similarity threshold, 12 of 374,545 pairs come close, and 5 of
/// those are deliberate series - `benchmark-v1`/`v2`, `run14`/`run15`, a
/// `task-` twin of a knowledge entry - which the shape rule below suppresses.
/// The rest are real families (one exchange name apart), and they are shown
/// without alarm: the author knows whether the resemblance is intended, and a
/// warning that cries wolf teaches people to scroll past it.
const SIMILAR_KEY_THRESHOLD: f64 = 0.85;

/// Two keys with the same shape differ only by a number or by a kind prefix,
/// which is a series, not a slip.
fn key_shape(key: &str) -> String {
    let stripped = key.strip_prefix(TASK_PREFIX).or_else(|| key.strip_prefix(INCIDENT_PREFIX)).unwrap_or(key);
    let mut out = String::with_capacity(stripped.len());
    let mut in_digits = false;
    for ch in stripped.chars() {
        if ch.is_ascii_digit() {
            if !in_digits {
                out.push('#');
                in_digits = true;
            }
        } else {
            out.push(ch);
            in_digits = false;
        }
    }
    out
}

/// Levenshtein distance, abandoned as soon as it exceeds `cap`. The cap is what
/// makes this cheap enough to run against every existing key on every create.
fn edit_distance_within(a: &str, b: &str, cap: usize) -> Option<usize> {
    let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
    if a.len().abs_diff(b.len()) > cap {
        return None;
    }
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut cur = vec![0usize; b.len() + 1];
    for i in 1..=a.len() {
        cur[0] = i;
        let mut best = i;
        for j in 1..=b.len() {
            let sub = prev[j - 1] + usize::from(a[i - 1] != b[j - 1]);
            cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(sub);
            best = best.min(cur[j]);
        }
        if best > cap {
            return None;
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    let d = prev[b.len()];
    (d <= cap).then_some(d)
}

pub fn similar_keys<'a>(new: &str, existing: impl Iterator<Item = &'a str>) -> Vec<String> {
    let shape_new = key_shape(new);
    let mut out: Vec<(usize, String)> = vec![];
    for other in existing {
        if other == new {
            continue;
        }
        let longest = new.chars().count().max(other.chars().count());
        let cap = (longest as f64 * (1.0 - SIMILAR_KEY_THRESHOLD)) as usize;
        if cap == 0 {
            continue;
        }
        let Some(d) = edit_distance_within(new, other, cap) else { continue };
        if key_shape(other) == shape_new {
            continue;
        }
        out.push((d, other.to_string()));
    }
    out.sort();
    out.into_iter().map(|(_, k)| k).take(3).collect()
}