decapod 0.55.0

Decapod is a Rust-built governance runtime for AI agents: repo-native state, enforced workflow, proof gates, safe coordination.
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
//! Obligations Engine - Mentor/Babysitter for Agents
//!
//! This module provides deterministic guidance that pushes agents back to:
//! - Prior decisions (ADRs)
//! - Specs/architecture/security docs
//! - Knowledge graph nodes
//! - Active todos/commitments
//!
//! # Design Principles
//!
//! - Deterministic: Same repo state + input = same obligations
//! - Immutable sources: Never modifies existing docs/KG
//! - Compact views: Max 5 items per obligations list
//! - Optional LLM: Only for ranking/phrasing, never adding obligations

use crate::core::error::DecapodError;
use crate::core::rpc::{Blocker, BlockerKind};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// An obligation item - a pointer to relevant context
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Obligation {
    /// Kind of obligation
    pub kind: ObligationKind,
    /// Reference path/ID
    pub ref_path: String,
    /// Human-readable title
    pub title: String,
    /// Brief explanation of why this matters now
    pub why_short: String,
    /// Evidence/provenance
    pub evidence: Evidence,
    /// Relevance score (0.0-1.0, higher = more relevant)
    pub relevance_score: f64,
}

/// Types of obligations
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ObligationKind {
    /// Reference to a doc section/anchor
    DocAnchor,
    /// Architecture Decision Record
    Adr,
    /// Knowledge graph node
    KgNode,
    /// Active todo/commitment
    Todo,
    /// Validation gate that must pass
    Gate,
    /// Container/Docker requirement - Silicon Valley hygiene
    Container,
}

/// Evidence/provenance for an obligation
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Evidence {
    /// Source type
    pub source: String,
    /// ID within source
    pub id: String,
    /// Optional content hash
    pub hash: Option<String>,
    /// Timestamp of source
    pub timestamp: Option<String>,
}

/// Computed obligations for an operation
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Obligations {
    /// Must-address obligations (<= 5 items)
    pub must: Vec<Obligation>,
    /// Recommended obligations (<= 5 items)
    pub recommended: Vec<Obligation>,
    /// Detected contradictions
    pub contradictions: Vec<Contradiction>,
    /// Co-player snapshots for in-context inference
    pub coplayer_snapshots: Vec<crate::core::coplayer::CoPlayerSnapshot>,
}

/// A detected contradiction
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Contradiction {
    /// Description of the contradiction
    pub description: String,
    /// Current state/assumption
    pub current: String,
    /// Prior decision/spec that conflicts
    pub prior: String,
    /// Suggested resolution
    pub resolution_hint: String,
}

/// Input context for computing obligations
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ObligationsContext {
    /// Operation being performed
    pub op: String,
    /// Operation parameters
    pub params: serde_json::Value,
    /// Paths touched by operation
    pub touched_paths: Vec<String>,
    /// Diff summary (if applicable)
    pub diff_summary: Option<String>,
    /// Project profile ID
    pub project_profile_id: Option<String>,
    /// Session ID
    pub session_id: Option<String>,
    /// High-risk operation flag
    pub high_risk: bool,
}

/// Candidate source for obligation retrieval
#[derive(Debug, Clone)]
enum CandidateSource {
    Adr {
        path: PathBuf,
        content: String,
    },
    Doc {
        path: PathBuf,
        section: String,
        content: String,
    },
    KgNode {
        id: String,
        title: String,
        node_type: String,
        tags: Vec<String>,
    },
    Todo {
        id: String,
        title: String,
        status: String,
        category: Option<String>,
    },
    AptitudeSkill {
        name: String,
        description: String,
        workflow: String,
        context: Option<String>,
        usage_count: i64,
    },
    AptitudePreference {
        category: String,
        key: String,
        value: String,
        context: Option<String>,
        confidence: i64,
    },
    FederationLesson {
        id: String,
        title: String,
        body: String,
        tags: Vec<String>,
    },
}

/// Mentor engine for computing obligations
pub struct MentorEngine {
    repo_root: PathBuf,
}

impl MentorEngine {
    /// Create a new mentor engine
    pub fn new(repo_root: &Path) -> Self {
        Self {
            repo_root: repo_root.to_path_buf(),
        }
    }

    /// Compute obligations for a given operation context
    pub fn compute_obligations(
        &self,
        context: &ObligationsContext,
    ) -> Result<Obligations, DecapodError> {
        // Step 1: Get container obligations FIRST (Silicon Valley hygiene priority)
        let container_obligations = self.get_container_candidates()?;

        // Step 2: Retrieve candidates from all other sources
        let candidates = self.retrieve_candidates(context)?;

        // Step 3: Score candidates based on relevance
        let scored = self.score_candidates(&candidates, context);

        // Step 4: Check for contradictions
        let contradictions = self.detect_contradictions(&scored, context);

        // Step 5: Build obligations lists (capped at 5 each)
        let (mut must, mut recommended) = self.build_obligations(scored, context);

        // Step 6: Prepend container obligations (they take precedence)
        // Container obligations are MUST if Dockerfile missing or work not containerized
        for container_obligation in container_obligations {
            if container_obligation.relevance_score >= 0.9 {
                // High-priority container obligations go to must
                must.insert(0, container_obligation);
            } else {
                // Lower priority go to recommended
                recommended.insert(0, container_obligation);
            }
        }

        // Ensure caps are maintained after adding container obligations
        must.truncate(5);
        recommended.truncate(5);

        // Step 7: Resolve co-player snapshots for in-context inference
        let mut coplayer_snapshots = Vec::new();
        let agent_id = std::env::var("DECAPOD_AGENT_ID").unwrap_or_else(|_| "unknown".to_string());

        let mut has_high_risk_coplayer = false;

        // Get all actors from traces
        let trace_path = self.repo_root.join(".decapod/data/traces.jsonl");
        if trace_path.exists() {
            let mut actors = std::collections::HashSet::new();
            if let Ok(content) = std::fs::read_to_string(&trace_path) {
                for line in content.lines() {
                    if let Ok(ev) = serde_json::from_str::<crate::core::trace::TraceEvent>(line) {
                        actors.insert(ev.actor);
                    }
                }
            }

            for actor in actors {
                if actor != agent_id
                    && let Ok(snap) =
                        crate::core::coplayer::resolve_snapshot(&self.repo_root, &actor)
                {
                    if snap.risk_profile == "high" {
                        has_high_risk_coplayer = true;
                    }
                    coplayer_snapshots.push(snap);
                }
            }
        }

        // Step 8: Adaptive constraints
        if has_high_risk_coplayer {
            must.insert(0, Obligation {
                kind: ObligationKind::Gate,
                ref_path: ".decapod/data/traces.jsonl".to_string(),
                title: "ADAPTIVE: High-Risk Co-player Detected".to_string(),
                why_short: "A co-player has a high risk profile. Require granular state-commits and full validation for every change.".to_string(),
                evidence: Evidence {
                    source: "coplayer_inference".to_string(),
                    id: "high_risk_detected".to_string(),
                    hash: None,
                    timestamp: Some(crate::core::time::now_epoch_z()),
                },
                relevance_score: 1.0,
            });
        }

        Ok(Obligations {
            must,
            recommended,
            contradictions,
            coplayer_snapshots,
        })
    }

    /// Retrieve candidates from all sources
    fn retrieve_candidates(
        &self,
        context: &ObligationsContext,
    ) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];

        // Get ADRs
        candidates.extend(self.get_adr_candidates()?);

        // Get doc candidates
        candidates.extend(self.get_doc_candidates(context)?);

        // Get knowledge graph candidates
        candidates.extend(self.get_kg_candidates()?);

        // Get todo candidates
        candidates.extend(self.get_todo_candidates()?);

        // Get aptitude skills
        candidates.extend(self.get_aptitude_skill_candidates()?);

        // Get aptitude preferences
        candidates.extend(self.get_aptitude_preference_candidates()?);

        // Get federation lessons
        candidates.extend(self.get_federation_lesson_candidates()?);

        Ok(candidates)
    }

    /// Get ADR candidates from docs/decisions/
    fn get_adr_candidates(&self) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];
        let decisions_dir = self.repo_root.join("docs").join("decisions");

        if !decisions_dir.exists() {
            return Ok(candidates);
        }

        for entry in std::fs::read_dir(&decisions_dir).map_err(DecapodError::IoError)? {
            let entry = entry.map_err(DecapodError::IoError)?;
            let path = entry.path();

            if path.extension().and_then(|e| e.to_str()) == Some("md") {
                let content = std::fs::read_to_string(&path).unwrap_or_default();
                candidates.push(CandidateSource::Adr { path, content });
            }
        }

        Ok(candidates)
    }

    /// Get doc candidates from docs/*.md
    fn get_doc_candidates(
        &self,
        context: &ObligationsContext,
    ) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];
        let docs_dir = self.repo_root.join("docs");

        if !docs_dir.exists() {
            return Ok(candidates);
        }

        let doc_files = ["spec.md", "architecture.md", "security.md", "ops.md"];

        for filename in &doc_files {
            let path = docs_dir.join(filename);
            if path.exists() {
                let content = std::fs::read_to_string(&path).unwrap_or_default();

                // Extract sections (simple markdown header parsing)
                let sections = self.extract_sections(&content);

                for (section, section_content) in sections {
                    // Check if section is relevant to operation
                    if self.is_section_relevant(&section, &section_content, context) {
                        candidates.push(CandidateSource::Doc {
                            path: path.clone(),
                            section,
                            content: section_content,
                        });
                    }
                }
            }
        }

        Ok(candidates)
    }

    /// Extract markdown sections (## headers)
    fn extract_sections(&self, content: &str) -> Vec<(String, String)> {
        let mut sections = vec![];
        let lines: Vec<&str> = content.lines().collect();
        let mut current_section = "Introduction".to_string();
        let mut current_content = String::new();

        for line in &lines {
            if let Some(stripped) = line.strip_prefix("## ") {
                // Save previous section
                if !current_content.is_empty() {
                    sections.push((current_section.clone(), current_content.clone()));
                }
                current_section = stripped.trim().to_string();
                current_content.clear();
            } else {
                current_content.push_str(line);
                current_content.push('\n');
            }
        }

        // Save last section
        if !current_content.is_empty() {
            sections.push((current_section, current_content));
        }

        sections
    }

    /// Check if a section is relevant to the operation
    fn is_section_relevant(
        &self,
        section: &str,
        content: &str,
        context: &ObligationsContext,
    ) -> bool {
        let section_lower = section.to_lowercase();
        let content_lower = content.to_lowercase();

        // Check against touched paths
        for path in &context.touched_paths {
            let path_lower = path.to_lowercase();
            if section_lower.contains(&path_lower) || content_lower.contains(&path_lower) {
                return true;
            }
        }

        // Check against operation type
        let op_lower = context.op.to_lowercase();
        if section_lower.contains(&op_lower) || content_lower.contains(&op_lower) {
            return true;
        }

        // Check for high-risk keywords
        if context.high_risk {
            let risk_keywords = ["security", "auth", "network", "credential", "secret"];
            for keyword in &risk_keywords {
                if section_lower.contains(keyword) || content_lower.contains(keyword) {
                    return true;
                }
            }
        }

        false
    }

    /// Get knowledge graph candidates
    fn get_kg_candidates(&self) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];

        // Query federation database for active nodes
        let db_path = self
            .repo_root
            .join(".decapod")
            .join("data")
            .join("federation.db");

        if !db_path.exists() {
            return Ok(candidates);
        }

        let conn = rusqlite::Connection::open(&db_path)?;

        let mut stmt = conn.prepare(
            "SELECT id, title, node_type, tags FROM nodes 
                 WHERE status = 'active' 
                 AND (node_type = 'decision' OR node_type = 'commitment')
                 ORDER BY created_at DESC
                 LIMIT 20",
        )?;

        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, String>(3)?,
            ))
        })?;

        for row in rows {
            let (id, title, node_type, tags_str) = row?;
            let tags: Vec<String> = tags_str
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();

            candidates.push(CandidateSource::KgNode {
                id,
                title,
                node_type,
                tags,
            });
        }

        Ok(candidates)
    }

    /// Get todo candidates
    fn get_todo_candidates(&self) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];

        // Query todo database for active tasks
        let db_path = self.repo_root.join(".decapod").join("data").join("todo.db");

        if !db_path.exists() {
            return Ok(candidates);
        }

        let conn = rusqlite::Connection::open(&db_path)?;

        let mut stmt = conn.prepare(
            "SELECT id, title, status, category FROM todos 
                 WHERE status IN ('open', 'claimed', 'in_progress')
                 ORDER BY priority DESC, created_at DESC
                 LIMIT 20",
        )?;

        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, Option<String>>(3)?,
            ))
        })?;

        for row in rows {
            let (id, title, status, category) = row?;

            candidates.push(CandidateSource::Todo {
                id,
                title,
                status,
                category,
            });
        }

        Ok(candidates)
    }

    /// Get aptitude skill candidates
    fn get_aptitude_skill_candidates(&self) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];
        let db_path = self
            .repo_root
            .join(".decapod")
            .join("data")
            .join("aptitude.db");

        if !db_path.exists() {
            return Ok(candidates);
        }

        let conn = rusqlite::Connection::open(&db_path)?;
        let mut stmt = conn.prepare(
            "SELECT name, description, workflow, context, usage_count FROM skills ORDER BY usage_count DESC LIMIT 20",
        )?;

        let rows = stmt.query_map([], |row| {
            Ok(CandidateSource::AptitudeSkill {
                name: row.get(0)?,
                description: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                workflow: row.get(2)?,
                context: row.get(3)?,
                usage_count: row.get(4)?,
            })
        })?;

        for row in rows {
            candidates.push(row?);
        }

        Ok(candidates)
    }

    /// Get aptitude preference candidates
    fn get_aptitude_preference_candidates(&self) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];
        let db_path = self
            .repo_root
            .join(".decapod")
            .join("data")
            .join("aptitude.db");

        if !db_path.exists() {
            return Ok(candidates);
        }

        let conn = rusqlite::Connection::open(&db_path)?;
        let mut stmt = conn.prepare(
            "SELECT category, key, value, context, confidence FROM preferences ORDER BY access_count DESC LIMIT 50",
        )?;

        let rows = stmt.query_map([], |row| {
            Ok(CandidateSource::AptitudePreference {
                category: row.get(0)?,
                key: row.get(1)?,
                value: row.get(2)?,
                context: row.get(3)?,
                confidence: row.get(4)?,
            })
        })?;

        for row in rows {
            candidates.push(row?);
        }

        Ok(candidates)
    }

    /// Get federation lesson candidates
    fn get_federation_lesson_candidates(&self) -> Result<Vec<CandidateSource>, DecapodError> {
        let mut candidates = vec![];
        let db_path = self
            .repo_root
            .join(".decapod")
            .join("data")
            .join("federation.db");

        if !db_path.exists() {
            return Ok(candidates);
        }

        let conn = rusqlite::Connection::open(&db_path)?;
        let mut stmt = conn.prepare(
            "SELECT id, title, body, tags FROM nodes WHERE node_type = 'lesson' AND status = 'active' ORDER BY created_at DESC LIMIT 20",
        )?;

        let rows = stmt.query_map([], |row| {
            let tags_str: String = row.get(3)?;
            let tags = tags_str
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            Ok(CandidateSource::FederationLesson {
                id: row.get(0)?,
                title: row.get(1)?,
                body: row.get(2)?,
                tags,
            })
        })?;

        for row in rows {
            candidates.push(row?);
        }

        Ok(candidates)
    }

    /// Score candidates by relevance
    fn score_candidates(
        &self,
        candidates: &[CandidateSource],
        context: &ObligationsContext,
    ) -> Vec<(CandidateSource, f64)> {
        let mut scored = vec![];

        for candidate in candidates {
            let score = self.compute_relevance_score(candidate, context);
            scored.push((candidate.clone(), score));
        }

        // Sort by score descending
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());

        scored
    }

    /// Compute relevance score for a candidate
    fn compute_relevance_score(
        &self,
        candidate: &CandidateSource,
        context: &ObligationsContext,
    ) -> f64 {
        let mut score = 0.0;

        match candidate {
            CandidateSource::Adr { path, content } => {
                // ADRs are high priority for architectural decisions
                score += 0.8;

                // Check for recency (newer ADRs slightly higher)
                if let Some(filename) = path.file_stem().and_then(|s| s.to_str())
                    && filename.starts_with("ADR-")
                {
                    // Parse ADR number (lower number = older, slight penalty)
                    if let Some(num_str) = filename.split('-').nth(1)
                        && let Ok(num) = num_str.parse::<u32>()
                    {
                        score += (100.0 - num as f64).max(0.0) * 0.001;
                    }
                }

                // Check content relevance
                let content_lower = content.to_lowercase();
                for path in &context.touched_paths {
                    if content_lower.contains(&path.to_lowercase()) {
                        score += 0.15;
                    }
                }
            }
            CandidateSource::Doc {
                path,
                section,
                content,
            } => {
                // Base score for docs
                score += 0.6;

                // Security docs get boost for high-risk ops
                if context.high_risk && path.to_string_lossy().contains("security") {
                    score += 0.2;
                }

                // Check section relevance
                let section_lower = section.to_lowercase();
                for touched in &context.touched_paths {
                    let touched_lower = touched.to_lowercase();
                    if section_lower.contains(&touched_lower) {
                        score += 0.2;
                    }
                }

                // Check content relevance
                let content_lower = content.to_lowercase();
                for touched in &context.touched_paths {
                    if content_lower.contains(&touched.to_lowercase()) {
                        score += 0.1;
                    }
                }
            }
            CandidateSource::KgNode {
                id: _,
                title,
                node_type,
                tags,
            } => {
                // Decisions and commitments are high priority
                match node_type.as_str() {
                    "decision" => score += 0.75,
                    "commitment" => score += 0.7,
                    _ => score += 0.5,
                }

                // Check tag relevance
                for tag in tags {
                    for path in &context.touched_paths {
                        if tag.to_lowercase().contains(&path.to_lowercase()) {
                            score += 0.15;
                        }
                    }
                }

                // Check title relevance
                let title_lower = title.to_lowercase();
                for path in &context.touched_paths {
                    if title_lower.contains(&path.to_lowercase()) {
                        score += 0.1;
                    }
                }
            }
            CandidateSource::Todo {
                id: _,
                title,
                status,
                category,
            } => {
                // Active todos are medium priority
                match status.as_str() {
                    "claimed" => score += 0.6,
                    "in_progress" => score += 0.55,
                    "open" => score += 0.5,
                    _ => score += 0.3,
                }

                // Category match
                if let Some(cat) = category {
                    for path in &context.touched_paths {
                        if cat.to_lowercase().contains(&path.to_lowercase()) {
                            score += 0.1;
                        }
                    }
                }

                // Title relevance
                let title_lower = title.to_lowercase();
                for path in &context.touched_paths {
                    if title_lower.contains(&path.to_lowercase()) {
                        score += 0.1;
                    }
                }
            }
            CandidateSource::AptitudeSkill {
                name,
                description,
                workflow,
                context: skill_context,
                usage_count,
            } => {
                // Base score for skills
                score += 0.5;

                // Boost for high usage
                if *usage_count > 5 {
                    score += 0.1;
                }

                // Check context match (e.g. "git", "style")
                if let Some(ctx) = skill_context
                    && context.op.contains(ctx)
                {
                    score += 0.3;
                }

                // Check content relevance
                let combined = format!("{} {} {}", name, description, workflow).to_lowercase();
                for path in &context.touched_paths {
                    if combined.contains(&path.to_lowercase()) {
                        score += 0.2;
                    }
                }
            }
            CandidateSource::AptitudePreference {
                category,
                key,
                value: _,
                context: pref_context,
                confidence,
            } => {
                // Base score
                score += 0.4;

                // High confidence boost
                if *confidence > 90 {
                    score += 0.1;
                }

                // Category match
                if context.op.contains(category) {
                    score += 0.2;
                }

                // Context match
                if let Some(ctx) = pref_context
                    && context.op.contains(ctx)
                {
                    score += 0.2;
                }

                // Key relevance
                let key_lower = key.to_lowercase();
                for path in &context.touched_paths {
                    if key_lower.contains(&path.to_lowercase()) {
                        score += 0.2;
                    }
                }
            }
            CandidateSource::FederationLesson {
                id: _,
                title,
                body,
                tags,
            } => {
                // Lessons are valuable
                score += 0.6;

                // Check tags
                for tag in tags {
                    for path in &context.touched_paths {
                        if tag.to_lowercase().contains(&path.to_lowercase()) {
                            score += 0.2;
                        }
                    }
                }

                // Check content
                let content_lower = format!("{} {}", title, body).to_lowercase();
                for path in &context.touched_paths {
                    if content_lower.contains(&path.to_lowercase()) {
                        score += 0.15;
                    }
                }
            }
        }

        // Cap at 1.0
        score.min(1.0)
    }

    /// Detect contradictions between candidates and context
    fn detect_contradictions(
        &self,
        scored: &[(CandidateSource, f64)],
        context: &ObligationsContext,
    ) -> Vec<Contradiction> {
        let mut contradictions = vec![];

        // Simple contradiction detection: if operation modifies X but ADR says Y about X
        for (candidate, score) in scored {
            if *score < 0.5 {
                continue; // Skip low-relevance candidates
            }

            if let CandidateSource::Adr { path, content } = candidate {
                // Check if ADR imposes constraints that operation might violate
                let content_lower = content.to_lowercase();

                for touched in &context.touched_paths {
                    let touched_lower = touched.to_lowercase();
                    if content_lower.contains(&format!("must use {}", touched_lower))
                        || content_lower.contains(&format!("shall use {}", touched_lower))
                        || content_lower.contains(&format!("decided: {}", touched_lower))
                    {
                        // Potential contradiction if operation changes this
                        if context.op.contains("change")
                            || context.op.contains("modify")
                            || context.op.contains("update")
                        {
                            contradictions.push(Contradiction {
                                description: format!(
                                    "Operation may contradict ADR decision regarding {}",
                                    touched
                                ),
                                current: format!("Operation: {}", context.op),
                                prior: format!(
                                    "ADR {} specifies requirements",
                                    path.file_name().unwrap_or_default().to_string_lossy()
                                ),
                                resolution_hint:
                                    "Review ADR or create new ADR if decision has changed"
                                        .to_string(),
                            });
                        }
                    }
                }
            }
        }

        contradictions
    }

    /// Build obligations lists (capped at 5 each)
    fn build_obligations(
        &self,
        scored: Vec<(CandidateSource, f64)>,
        context: &ObligationsContext,
    ) -> (Vec<Obligation>, Vec<Obligation>) {
        let mut must = vec![];
        let mut recommended = vec![];

        // Determine thresholds based on risk
        let must_threshold = if context.high_risk { 0.7 } else { 0.8 };
        let recommended_threshold = if context.high_risk { 0.5 } else { 0.6 };

        for (candidate, score) in scored {
            // Cap at 5 per list
            if must.len() >= 5 && recommended.len() >= 5 {
                break;
            }

            let obligation = self.candidate_to_obligation(&candidate, score);

            if score >= must_threshold && must.len() < 5 {
                must.push(obligation);
            } else if score >= recommended_threshold && recommended.len() < 5 {
                recommended.push(obligation);
            }
        }

        (must, recommended)
    }

    /// Convert candidate to obligation
    fn candidate_to_obligation(&self, candidate: &CandidateSource, score: f64) -> Obligation {
        match candidate {
            CandidateSource::Adr { path, content } => {
                let title = self.extract_title(content).unwrap_or_else(|| {
                    path.file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("ADR")
                        .to_string()
                });

                Obligation {
                    kind: ObligationKind::Adr,
                    ref_path: path.to_string_lossy().to_string(),
                    title,
                    why_short: "Prior architectural decision may affect this work".to_string(),
                    evidence: Evidence {
                        source: "docs/decisions".to_string(),
                        id: path
                            .file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                            .to_string(),
                        hash: Some(self.compute_hash(content)),
                        timestamp: None,
                    },
                    relevance_score: score,
                }
            }
            CandidateSource::Doc {
                path,
                section,
                content: _,
            } => Obligation {
                kind: ObligationKind::DocAnchor,
                ref_path: format!("{}# {}", path.to_string_lossy(), section),
                title: section.clone(),
                why_short: "Relevant documentation section".to_string(),
                evidence: Evidence {
                    source: "docs".to_string(),
                    id: path
                        .file_name()
                        .unwrap_or_default()
                        .to_string_lossy()
                        .to_string(),
                    hash: None,
                    timestamp: None,
                },
                relevance_score: score,
            },
            CandidateSource::KgNode {
                id,
                title,
                node_type,
                tags: _,
            } => {
                let why = match node_type.as_str() {
                    "decision" => "Prior decision may constrain this work",
                    "commitment" => "Active commitment may affect approach",
                    _ => "Relevant knowledge graph entry",
                };

                Obligation {
                    kind: ObligationKind::KgNode,
                    ref_path: format!(".decapod/data/federation# {}", id),
                    title: title.clone(),
                    why_short: why.to_string(),
                    evidence: Evidence {
                        source: ".decapod/data".to_string(),
                        id: id.clone(),
                        hash: None,
                        timestamp: None,
                    },
                    relevance_score: score,
                }
            }
            CandidateSource::Todo {
                id,
                title,
                status,
                category: _,
            } => {
                let why = match status.as_str() {
                    "claimed" => "Claimed work may overlap or conflict",
                    "in_progress" => "In-progress work may be related",
                    _ => "Active task may be relevant",
                };

                Obligation {
                    kind: ObligationKind::Todo,
                    ref_path: format!(".decapod/data/todo# {}", id),
                    title: title.clone(),
                    why_short: why.to_string(),
                    evidence: Evidence {
                        source: ".decapod/data".to_string(),
                        id: id.clone(),
                        hash: None,
                        timestamp: None,
                    },
                    relevance_score: score,
                }
            }
            CandidateSource::AptitudeSkill {
                name,
                description,
                workflow,
                context: _,
                usage_count: _,
            } => Obligation {
                kind: ObligationKind::DocAnchor, // Reusing DocAnchor as it fits the "read this" model
                ref_path: format!("aptitude.db/skills/{}", name),
                title: format!("Skill: {}", name),
                why_short: description.clone(),
                evidence: Evidence {
                    source: "aptitude.db".to_string(),
                    id: name.clone(),
                    hash: Some(self.compute_hash(workflow)),
                    timestamp: None,
                },
                relevance_score: score,
            },
            CandidateSource::AptitudePreference {
                category,
                key,
                value,
                context: _,
                confidence,
            } => Obligation {
                kind: ObligationKind::DocAnchor,
                ref_path: format!("aptitude.db/preferences/{}.{}", category, key),
                title: format!("Preference: {}.{}", category, key),
                why_short: format!("User preference (confidence {}%): {}", confidence, value),
                evidence: Evidence {
                    source: "aptitude.db".to_string(),
                    id: format!("{}.{}", category, key),
                    hash: None,
                    timestamp: None,
                },
                relevance_score: score,
            },
            CandidateSource::FederationLesson {
                id,
                title,
                body,
                tags: _,
            } => Obligation {
                kind: ObligationKind::KgNode,
                ref_path: format!(".decapod/data/federation# {}", id),
                title: format!("Learned Lesson: {}", title),
                why_short: "Applying past learnings to current context".to_string(),
                evidence: Evidence {
                    source: ".decapod/data".to_string(),
                    id: id.clone(),
                    hash: Some(self.compute_hash(body)),
                    timestamp: None,
                },
                relevance_score: score,
            },
        }
    }

    /// Extract title from markdown content
    fn extract_title(&self, content: &str) -> Option<String> {
        for line in content.lines() {
            if let Some(stripped) = line.strip_prefix("# ") {
                return Some(stripped.trim().to_string());
            }
        }
        None
    }

    /// Compute hash of content
    fn compute_hash(&self, content: &str) -> String {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(content.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// Get container/Docker obligation candidates
    fn get_container_candidates(&self) -> Result<Vec<Obligation>, DecapodError> {
        let mut obligations = vec![];

        // Check for Dockerfile
        let dockerfile_paths = [
            self.repo_root.join("Dockerfile"),
            self.repo_root.join(".devcontainer").join("Dockerfile"),
            self.repo_root.join("docker").join("Dockerfile"),
        ];

        let mut found_dockerfile = false;
        for path in &dockerfile_paths {
            if path.exists() {
                found_dockerfile = true;
                let content = std::fs::read_to_string(path).unwrap_or_default();
                let hash = self.compute_hash(&content);

                obligations.push(Obligation {
                    kind: ObligationKind::Container,
                    ref_path: path.to_string_lossy().to_string(),
                    title: "Dockerfile exists - Containerization Required".to_string(),
                    why_short: "Silicon Valley hygiene: All work must be containerized".to_string(),
                    evidence: Evidence {
                        source: "workspace".to_string(),
                        id: path
                            .file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                            .to_string(),
                        hash: Some(hash),
                        timestamp: None,
                    },
                    relevance_score: 0.95,
                });
                break;
            }
        }

        // If no Dockerfile, add obligation to create one
        if !found_dockerfile {
            obligations.push(Obligation {
                kind: ObligationKind::Container,
                ref_path: "Dockerfile".to_string(),
                title: "No Dockerfile - Containerization Required".to_string(),
                why_short: "Silicon Valley hygiene: Create Dockerfile before proceeding"
                    .to_string(),
                evidence: Evidence {
                    source: "workspace".to_string(),
                    id: "dockerfile_missing".to_string(),
                    hash: None,
                    timestamp: None,
                },
                relevance_score: 0.90,
            });
        }

        // Check for .dockerignore
        let dockerignore_path = self.repo_root.join(".dockerignore");
        if !dockerignore_path.exists() {
            obligations.push(Obligation {
                kind: ObligationKind::Container,
                ref_path: ".dockerignore".to_string(),
                title: "No .dockerignore - Add for efficient builds".to_string(),
                why_short: "Prevent unnecessary files from being copied to containers".to_string(),
                evidence: Evidence {
                    source: "workspace".to_string(),
                    id: "dockerignore_missing".to_string(),
                    hash: None,
                    timestamp: None,
                },
                relevance_score: 0.70,
            });
        }

        Ok(obligations)
    }

    /// Check if an operation is high-risk
    pub fn is_high_risk_op(&self, op: &str, touched_paths: &[String]) -> bool {
        let high_risk_ops = [
            "git", "push", "deploy", "release", "auth", "security", "network",
        ];

        // Check operation name
        for risk_op in &high_risk_ops {
            if op.to_lowercase().contains(risk_op) {
                return true;
            }
        }

        // Check paths
        let high_risk_paths = [
            "auth",
            "credential",
            "secret",
            "password",
            "key",
            "cert",
            "network",
            "firewall",
            "security",
            "permission",
            "role",
            "deploy",
            "production",
            "release",
        ];

        for path in touched_paths {
            let path_lower = path.to_lowercase();
            for risk_path in &high_risk_paths {
                if path_lower.contains(risk_path) {
                    return true;
                }
            }
        }

        false
    }
}

/// Convert obligations to RPC blockers (for contradictions)
pub fn contradictions_to_blockers(contradictions: &[Contradiction]) -> Vec<Blocker> {
    contradictions
        .iter()
        .map(|c| Blocker {
            kind: BlockerKind::Conflict,
            message: c.description.clone(),
            resolve_hint: c.resolution_hint.clone(),
        })
        .collect()
}