Skip to main content

khive_request/
atomic.rs

1//! Pure ADR-099 atomic-admissibility preflight over parsed operations.
2
3use khive_types::pack::{atomic_admissibility, AtomicRejectionReason, ATOMIC_ADMISSIBLE_VERBS};
4
5use crate::types::ParsedOp;
6
7/// One atomic-preflight rejection.
8///
9/// See `crates/khive-request/docs/api/atomic-admissibility.md` for reason semantics.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct AtomicRejection {
12    /// Zero-based operation position.
13    pub op_index: usize,
14    /// Rejected tool name.
15    pub tool: String,
16    /// Static admissibility category.
17    pub reason: AtomicRejectionReason,
18}
19
20impl std::fmt::Display for AtomicRejection {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        let why: std::borrow::Cow<'static, str> = match self.reason {
23            AtomicRejectionReason::EmbeddingBearing => {
24                "embedding-bearing verbs are not yet atomic-eligible".into()
25            }
26            AtomicRejectionReason::Read => "read verbs have no write plan to apply".into(),
27            AtomicRejectionReason::Unlisted => "not on the v1 atomic-admissible verb list".into(),
28            AtomicRejectionReason::KnownUnimplemented if self.tool == "merge" => {
29                "merge is not yet supported under --atomic (admissible per ADR-099 D3, but \
30                 full-parity field-folding/index-cleanup/edge-conflict-resolution is deferred \
31                 this slice); use the non-atomic merge verb instead"
32                    .into()
33            }
34            AtomicRejectionReason::KnownUnimplemented => format!(
35                "admissible per ADR-099 D3 but has no --atomic prepare/apply seam implemented \
36                 in this slice yet; use the non-atomic {:?} verb instead",
37                self.tool
38            )
39            .into(),
40        };
41        write!(
42            f,
43            "op {} (`{}`) is not atomic-admissible: {}. Admissible verbs: {}",
44            self.op_index,
45            self.tool,
46            why,
47            ATOMIC_ADMISSIBLE_VERBS.join(", ")
48        )
49    }
50}
51
52/// Checks every tool name against the ADR-099 v1 atomic policy.
53///
54/// Returns every rejection in input order; an empty vector means every op is
55/// admissible. This function performs no I/O or execution and must run before
56/// an atomic prepare pass.
57/// See `crates/khive-request/docs/api/atomic-admissibility.md` for policy boundaries.
58pub fn check_atomic_admissible(ops: &[ParsedOp]) -> Vec<AtomicRejection> {
59    ops.iter()
60        .enumerate()
61        .filter_map(|(op_index, op)| {
62            atomic_admissibility(&op.tool).map(|reason| AtomicRejection {
63                op_index,
64                tool: op.tool.clone(),
65                reason,
66            })
67        })
68        .collect()
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use std::collections::BTreeMap;
75
76    fn op(tool: &str) -> ParsedOp {
77        ParsedOp {
78            tool: tool.to_string(),
79            args: BTreeMap::new(),
80        }
81    }
82
83    #[test]
84    fn all_admissible_ops_pass_with_no_rejections() {
85        let ops = vec![op("update"), op("delete"), op("link")];
86        assert!(check_atomic_admissible(&ops).is_empty());
87    }
88
89    #[test]
90    fn embedding_bearing_verb_named_in_rejection() {
91        let ops = vec![op("update"), op("create"), op("delete")];
92        let rejections = check_atomic_admissible(&ops);
93        assert_eq!(rejections.len(), 1);
94        assert_eq!(rejections[0].op_index, 1);
95        assert_eq!(rejections[0].tool, "create");
96        assert_eq!(
97            rejections[0].reason,
98            AtomicRejectionReason::EmbeddingBearing
99        );
100    }
101
102    #[test]
103    fn read_verb_named_in_rejection_before_any_write() {
104        let ops = vec![op("search"), op("update")];
105        let rejections = check_atomic_admissible(&ops);
106        assert_eq!(rejections.len(), 1);
107        assert_eq!(rejections[0].op_index, 0);
108        assert_eq!(rejections[0].tool, "search");
109        assert_eq!(rejections[0].reason, AtomicRejectionReason::Read);
110    }
111
112    #[test]
113    fn every_offending_line_is_reported_not_just_the_first() {
114        let ops = vec![op("create"), op("update"), op("comm.send"), op("search")];
115        let rejections = check_atomic_admissible(&ops);
116        let indices: Vec<usize> = rejections.iter().map(|r| r.op_index).collect();
117        assert_eq!(indices, vec![0, 2, 3]);
118    }
119
120    #[test]
121    fn rejection_display_names_verb_and_lists_admissible_set() {
122        let rejection = AtomicRejection {
123            op_index: 2,
124            tool: "create".to_string(),
125            reason: AtomicRejectionReason::EmbeddingBearing,
126        };
127        let msg = rejection.to_string();
128        assert!(msg.contains("op 2"));
129        assert!(msg.contains("`create`"));
130        assert!(
131            msg.contains("update"),
132            "must list the admissible set: {msg}"
133        );
134    }
135
136    #[test]
137    fn all_v1_admissible_verbs_from_the_ordered_ops_file_pass() {
138        let ops: Vec<ParsedOp> = ATOMIC_ADMISSIBLE_VERBS
139            .iter()
140            .filter(|v| !khive_types::pack::ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(v))
141            .map(|v| op(v))
142            .collect();
143        assert!(check_atomic_admissible(&ops).is_empty());
144    }
145
146    #[test]
147    fn known_unimplemented_verbs_rejected_before_any_write() {
148        let ops: Vec<ParsedOp> = khive_types::pack::ATOMIC_KNOWN_UNIMPLEMENTED_VERBS
149            .iter()
150            .map(|v| op(v))
151            .collect();
152        let rejections = check_atomic_admissible(&ops);
153        assert_eq!(rejections.len(), ops.len());
154        for rejection in &rejections {
155            assert_eq!(
156                rejection.reason,
157                AtomicRejectionReason::KnownUnimplemented,
158                "rejection: {rejection:?}"
159            );
160            let msg = rejection.to_string();
161            assert!(
162                msg.contains("use the non-atomic") && msg.contains("instead"),
163                "display must name the non-atomic verb as the supported route: {msg}"
164            );
165        }
166    }
167
168    #[test]
169    fn known_unimplemented_merge_names_non_atomic_merge_as_the_supported_route() {
170        let rejection = AtomicRejection {
171            op_index: 0,
172            tool: "merge".to_string(),
173            reason: AtomicRejectionReason::KnownUnimplemented,
174        };
175        let msg = rejection.to_string();
176        assert!(
177            msg.contains("use the non-atomic merge verb instead"),
178            "display: {msg}"
179        );
180    }
181}