Skip to main content

jubarte_edit/edit/
refusal.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Review choices retained as data until the caller's grammar is known.
6
7use serde::{Deserialize, Serialize};
8
9use super::{EditError, Transaction, v2::Target};
10use crate::namespaces::W;
11use crate::result::NextAction;
12use crate::xmllinq::NodeId;
13
14/// What v2 puts before a refusal it cannot place on the requested side of
15/// an insertion point (`UNSUPPORTED_INSERTION_SIDE`).
16pub(super) const INSERTION_SIDE_PREFIX: &str = "requested insertion side cannot be preserved: ";
17
18/// The syntax the caller can use to resolve a blocking revision.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum RevisionSyntax {
22    /// Legacy JSON filter selections.
23    #[default]
24    V1Plan,
25    /// Source-bound paired-target decision arrays.
26    V2Plan,
27    /// Legacy `-p r7 --accept` / `--reject` groups.
28    LegacyFlags,
29    /// Typed inline `--accept-change` / `--reject-change` options.
30    TypedAction,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34struct Revision {
35    target: Target,
36    kind: String,
37    author: String,
38    accept: String,
39    reject: String,
40}
41
42/// The blocking carriers and both consequences, independent of message text.
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub struct RevisionRefusal {
45    reason: String,
46    revisions: Vec<Revision>,
47    syntax: RevisionSyntax,
48    /// The plan keeps another author's markup. Not on the wire: the message
49    /// already says which routes exist.
50    #[serde(skip)]
51    keep_others: bool,
52    /// The plan's author. Not on the wire.
53    #[serde(skip)]
54    actor: String,
55}
56
57impl RevisionRefusal {
58    pub(super) fn new(tx: &Transaction<'_>, reason: &str, nodes: &[NodeId]) -> Self {
59        let dom = &tx.opened.dom;
60        let mut revisions = Vec::new();
61        for &node in nodes {
62            let ancestors = dom.ancestors(node, None);
63            let story = tx
64                .stories
65                .iter()
66                .find(|s| ancestors.contains(&s.root))
67                .expect("a blocking revision belongs to a loaded story");
68            let pair = super::for_edit::revision_pair(dom, node, &story.id, &story.part);
69            let target = Target {
70                short_id: pair.short_id,
71                long_id: pair.long_id,
72            };
73            if revisions.iter().any(|r: &Revision| r.target == target) {
74                continue;
75            }
76            let local = dom
77                .name(node)
78                .expect("revision element")
79                .local_name()
80                .to_string();
81            let mark = dom.parent(node).is_some_and(|rpr| {
82                dom.name_is(rpr, &W::r_pr())
83                    && dom
84                        .parent(rpr)
85                        .is_some_and(|ppr| dom.name_is(ppr, &W::p_pr()))
86            });
87            let (kind, accept, reject) = match (local.as_str(), mark) {
88                ("ins", true) => (
89                    "insertion",
90                    "keeps the proposed paragraph break",
91                    "removes the proposed paragraph break",
92                ),
93                ("ins", false) => (
94                    "insertion",
95                    "keeps the proposed content as plain text",
96                    "removes the proposed content",
97                ),
98                ("del", true) => (
99                    "deletion",
100                    "removes the deleted paragraph break",
101                    "restores the deleted paragraph break",
102                ),
103                ("del", false) => (
104                    "deletion",
105                    "removes the deleted content",
106                    "restores the deleted content",
107                ),
108                ("moveFrom" | "moveTo", _) => (
109                    "move",
110                    "keeps the moved content at its destination",
111                    "restores the moved content at its origin",
112                ),
113                _ => (
114                    "formatting",
115                    "keeps the proposed formatting",
116                    "restores the previous formatting",
117                ),
118            };
119            revisions.push(Revision {
120                target,
121                kind: kind.into(),
122                author: dom.attribute(node, &W::author()).unwrap_or_default().into(),
123                accept: accept.into(),
124                reject: reject.into(),
125            });
126        }
127        Self {
128            reason: reason.into(),
129            revisions,
130            // The message quotes its routes in the transaction's syntax.
131            syntax: tx.syntax.revision(),
132            keep_others: tx.plan.others.keeps(),
133            actor: tx.plan.author.clone(),
134        }
135    }
136
137    /// A revision someone other than the plan's author wrote. A missing
138    /// author is not the plan's.
139    fn foreign(&self, author: &str) -> bool {
140        author != self.actor
141    }
142
143    fn effect(&self, revision: &Revision, accept: bool) -> String {
144        // Rejecting another author's deletion erases their change. The
145        // stored consequence still says what the mark itself does.
146        if !accept && revision.kind == "deletion" && self.foreign(&revision.author) {
147            "rejecting erases their change".to_string()
148        } else if accept {
149            revision.accept.clone()
150        } else {
151            revision.reject.clone()
152        }
153    }
154
155    fn consequence(&self, accept: bool) -> String {
156        self.revisions
157            .iter()
158            .map(|r| {
159                let effect = self.effect(r, accept);
160                if self.revisions.len() == 1 {
161                    effect
162                } else {
163                    format!("{effect} for {}", r.target.short_id)
164                }
165            })
166            .collect::<Vec<_>>()
167            .join(" and ")
168    }
169}
170
171impl EditError {
172    /// Render all revision refusals, including operation outcomes, for a caller.
173    #[must_use]
174    pub fn with_revision_syntax(mut self, syntax: RevisionSyntax) -> Self {
175        // The message's routes are already in the caller's syntax
176        // (`hint::PlanSyntax`); the data records the same choice.
177        for refusal in self.revision_refusals.iter_mut() {
178            refusal.syntax = syntax;
179        }
180        self
181    }
182
183    /// Two explicit decisions as executable template-generation argument arrays.
184    /// The templates go to stdout; source documents are never changed here.
185    #[must_use]
186    pub fn revision_next_actions(&self, source_path: &str, source_digest: &str) -> Vec<NextAction> {
187        // Only the refusal the message names: a revision another operation
188        // met must not answer for a refusal of a different kind. The
189        // message's first line starts with the refusal's lead and its first
190        // revision, after v2's insertion-side prefix; an error of another
191        // kind may quote text shaped like it (an anchor the caller typed),
192        // and those choices are not its own.
193        let header = self.message.lines().next().unwrap_or_default();
194        let header = header.strip_prefix(INSERTION_SIDE_PREFIX).unwrap_or(header);
195        let Some(refusal) = self.revision_refusals.first().filter(|refusal| {
196            refusal.revisions.first().is_some_and(|first| {
197                header.starts_with(&format!("{} {}", refusal.reason, first.target.short_id))
198            }) && refusal
199                .revisions
200                .iter()
201                .all(|r| self.message.contains(&r.target.short_id))
202        }) else {
203            return Vec::new();
204        };
205        let all_foreign = refusal.revisions.iter().all(|r| refusal.foreign(&r.author));
206        let any_foreign = refusal.revisions.iter().any(|r| refusal.foreign(&r.author));
207        // One keeping command only when every revision is the same kind of
208        // answer: restore a deletion, strike an insertion. A mix, or a move
209        // or a formatting change, has no single keeping flag.
210        let keeping = if all_foreign {
211            if refusal.revisions.iter().all(|r| r.kind == "deletion") {
212                Some("restore")
213            } else if refusal.revisions.iter().all(|r| r.kind == "insertion") {
214                Some("strike")
215            } else {
216                None
217            }
218        } else {
219            None
220        };
221        let mut actions = Vec::new();
222        if let Some(flag) = keeping {
223            let mut argv = vec!["jubarte".into(), "edit".into(), source_path.into()];
224            for revision in &refusal.revisions {
225                argv.extend([
226                    "-p".into(),
227                    revision.target.short_id.clone(),
228                    format!("--{flag}"),
229                ]);
230            }
231            argv.extend(["--author".into(), refusal.actor.clone()]);
232            if refusal.keep_others {
233                argv.push("--keep-others".into());
234            }
235            argv.extend(["-o".into(), "-".into()]);
236            let purpose = if flag == "restore" {
237                "their deletion stays, your insertion shows"
238            } else {
239                "their insertion stays, your deletion shows"
240            };
241            actions.push(NextAction::new(argv).with_purpose(purpose));
242        }
243        // The guard offers no accept or reject of someone else's markup.
244        if refusal.keep_others && any_foreign {
245            return actions;
246        }
247        actions.extend([true, false].into_iter().map(|accept| {
248            let key = if accept { "accept" } else { "reject" };
249            let mut argv = vec!["jubarte".into(), "edit".into(), "template".into(), source_path.into(),
250                "--expect-sha256".into(), source_digest.into()];
251            for revision in &refusal.revisions {
252                argv.extend([format!("--{key}-change"), revision.target.short_id.clone()]);
253            }
254            argv.extend(["-o".into(), "-".into()]);
255            let action = NextAction::new(argv).with_purpose(format!(
256                "{}; generate a fresh plan and deliberately author the refreshed edit before applying it",
257                refusal.consequence(accept)
258            ));
259            if any_foreign { action.with_destructive() } else { action }
260        }));
261        actions
262    }
263}
264
265impl Transaction<'_> {
266    pub(super) fn attach_revision_refusal(&self, mut error: EditError) -> EditError {
267        if let Some(refusal) = self.revision_refusal.take() {
268            let mut refusals = error.revision_refusals.into_vec();
269            refusals.push(refusal);
270            error.revision_refusals = refusals.into_boxed_slice();
271        }
272        error
273    }
274}