Skip to main content

khive_request/
atomic.rs

1//! ADR-099 migration step 2 — parse-time rejection of atomic-inadmissible
2//! verbs.
3//!
4//! `--atomic` bulk apply (ADR-099 migration step 4, not yet built) must
5//! reject an inadmissible op **before any execution**. This module exposes
6//! that check as a pure function over already-parsed ops so the future
7//! `--atomic` runner can call it without re-deriving the admissible set —
8//! the set itself lives in `khive_types::pack` (shared pack metadata, ADR-099
9//! D3: admissibility is a static per-verb property, "declared per verb as
10//! pack metadata").
11
12use khive_types::pack::{atomic_admissibility, AtomicRejectionReason, ATOMIC_ADMISSIBLE_VERBS};
13
14use crate::types::ParsedOp;
15
16/// One rejected op inside a would-be `--atomic` file: its zero-based index in
17/// the op list, its tool name, and why it was rejected.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct AtomicRejection {
20    pub op_index: usize,
21    pub tool: String,
22    pub reason: AtomicRejectionReason,
23}
24
25impl std::fmt::Display for AtomicRejection {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        let why: std::borrow::Cow<'static, str> = match self.reason {
28            AtomicRejectionReason::EmbeddingBearing => {
29                "embedding-bearing verbs are not yet atomic-eligible".into()
30            }
31            AtomicRejectionReason::Read => "read verbs have no write plan to apply".into(),
32            AtomicRejectionReason::Unlisted => "not on the v1 atomic-admissible verb list".into(),
33            AtomicRejectionReason::KnownUnimplemented if self.tool == "merge" => {
34                "merge is not yet supported under --atomic (admissible per ADR-099 D3, but \
35                 full-parity field-folding/index-cleanup/edge-conflict-resolution is deferred \
36                 this slice); use the non-atomic merge verb instead"
37                    .into()
38            }
39            AtomicRejectionReason::KnownUnimplemented => format!(
40                "admissible per ADR-099 D3 but has no --atomic prepare/apply seam implemented \
41                 in this slice yet; use the non-atomic {:?} verb instead",
42                self.tool
43            )
44            .into(),
45        };
46        write!(
47            f,
48            "op {} (`{}`) is not atomic-admissible: {}. Admissible verbs: {}",
49            self.op_index,
50            self.tool,
51            why,
52            ATOMIC_ADMISSIBLE_VERBS.join(", ")
53        )
54    }
55}
56
57/// Check every op's tool name against the ADR-099 v1 admissible verb set.
58///
59/// Returns every rejection found (not just the first), so a caller preparing
60/// to reject the whole file up front can report every offending line in one
61/// pass, naming the line and verb per op (ADR-099 acceptance criteria). An
62/// empty result means every op in `ops` is atomic-admissible.
63///
64/// This function is pure: it performs no I/O and does not execute any op. It
65/// is the seam the future `--atomic` runner (ADR-099 migration step 4) calls
66/// before the prepare pass begins.
67pub fn check_atomic_admissible(ops: &[ParsedOp]) -> Vec<AtomicRejection> {
68    ops.iter()
69        .enumerate()
70        .filter_map(|(op_index, op)| {
71            atomic_admissibility(&op.tool).map(|reason| AtomicRejection {
72                op_index,
73                tool: op.tool.clone(),
74                reason,
75            })
76        })
77        .collect()
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use std::collections::BTreeMap;
84
85    fn op(tool: &str) -> ParsedOp {
86        ParsedOp {
87            tool: tool.to_string(),
88            args: BTreeMap::new(),
89        }
90    }
91
92    #[test]
93    fn all_admissible_ops_pass_with_no_rejections() {
94        // `merge` is deferred (B3 fix round, Leo refinement) — see
95        // `known_unimplemented_verbs_rejected_before_any_write` below.
96        let ops = vec![op("update"), op("delete"), op("link")];
97        assert!(check_atomic_admissible(&ops).is_empty());
98    }
99
100    #[test]
101    fn embedding_bearing_verb_named_in_rejection() {
102        let ops = vec![op("update"), op("create"), op("delete")];
103        let rejections = check_atomic_admissible(&ops);
104        assert_eq!(rejections.len(), 1);
105        assert_eq!(rejections[0].op_index, 1);
106        assert_eq!(rejections[0].tool, "create");
107        assert_eq!(
108            rejections[0].reason,
109            AtomicRejectionReason::EmbeddingBearing
110        );
111    }
112
113    #[test]
114    fn read_verb_named_in_rejection_before_any_write() {
115        let ops = vec![op("search"), op("update")];
116        let rejections = check_atomic_admissible(&ops);
117        assert_eq!(rejections.len(), 1);
118        assert_eq!(rejections[0].op_index, 0);
119        assert_eq!(rejections[0].tool, "search");
120        assert_eq!(rejections[0].reason, AtomicRejectionReason::Read);
121    }
122
123    #[test]
124    fn every_offending_line_is_reported_not_just_the_first() {
125        let ops = vec![op("create"), op("update"), op("comm.send"), op("search")];
126        let rejections = check_atomic_admissible(&ops);
127        let indices: Vec<usize> = rejections.iter().map(|r| r.op_index).collect();
128        assert_eq!(indices, vec![0, 2, 3]);
129    }
130
131    #[test]
132    fn rejection_display_names_verb_and_lists_admissible_set() {
133        let rejection = AtomicRejection {
134            op_index: 2,
135            tool: "create".to_string(),
136            reason: AtomicRejectionReason::EmbeddingBearing,
137        };
138        let msg = rejection.to_string();
139        assert!(msg.contains("op 2"));
140        assert!(msg.contains("`create`"));
141        assert!(
142            msg.contains("update"),
143            "must list the admissible set: {msg}"
144        );
145    }
146
147    #[test]
148    fn all_v1_admissible_verbs_from_the_ordered_ops_file_pass() {
149        // ADR-099 D3's full v1 list, exercised through the ops-file shape
150        // (tool name only — the parse-time check does not need args),
151        // EXCLUDING the governance verbs: those are still on
152        // ATOMIC_ADMISSIBLE_VERBS (conceptually admissible per the ADR) but
153        // are rejected at this same static layer as known-unimplemented (B3
154        // fix round, codex REJECT Medium finding) — see the dedicated test
155        // below.
156        let ops: Vec<ParsedOp> = ATOMIC_ADMISSIBLE_VERBS
157            .iter()
158            .filter(|v| !khive_types::pack::ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(v))
159            .map(|v| op(v))
160            .collect();
161        assert!(check_atomic_admissible(&ops).is_empty());
162    }
163
164    #[test]
165    fn known_unimplemented_verbs_rejected_before_any_write() {
166        // B3 fix round (codex REJECT, Medium finding + Leo refinement on
167        // Blocker 2): propose/review/withdraw AND (deferred) merge must all
168        // be rejected at THIS pre-runtime static check — not admitted here
169        // and left to fail later inside `atomic_prepare::prepare_op` after a
170        // runtime has already been constructed.
171        let ops: Vec<ParsedOp> = khive_types::pack::ATOMIC_KNOWN_UNIMPLEMENTED_VERBS
172            .iter()
173            .map(|v| op(v))
174            .collect();
175        let rejections = check_atomic_admissible(&ops);
176        assert_eq!(rejections.len(), ops.len());
177        for rejection in &rejections {
178            assert_eq!(
179                rejection.reason,
180                AtomicRejectionReason::KnownUnimplemented,
181                "rejection: {rejection:?}"
182            );
183            let msg = rejection.to_string();
184            assert!(
185                msg.contains("use the non-atomic") && msg.contains("instead"),
186                "display must name the non-atomic verb as the supported route: {msg}"
187            );
188        }
189    }
190
191    #[test]
192    fn known_unimplemented_merge_names_non_atomic_merge_as_the_supported_route() {
193        // Leo refinement (2026-07-07): merge's rejection message must be
194        // specific and actionable, naming the non-atomic merge verb (the
195        // blessed defer shape), not just the generic
196        // "no --atomic prepare/apply seam yet" phrasing governance verbs use.
197        let rejection = AtomicRejection {
198            op_index: 0,
199            tool: "merge".to_string(),
200            reason: AtomicRejectionReason::KnownUnimplemented,
201        };
202        let msg = rejection.to_string();
203        assert!(
204            msg.contains("use the non-atomic merge verb instead"),
205            "display: {msg}"
206        );
207    }
208}