Skip to main content

jubarte_cli/cli/
edit_actions.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Typed edit grammar. The legacy `edit FILE` grammar remains versioned.
6
7use std::{ffi::OsString, path::PathBuf};
8
9use clap::{Args, Subcommand};
10use serde::Serialize;
11
12/// The typed edit route, selected before legacy flag grouping.
13#[derive(Args, Debug, Serialize)]
14pub struct TypedEdit {
15    /// Exactly one operation grammar, or application of a saved plan.
16    #[command(subcommand)]
17    #[serde(flatten)]
18    pub action: EditAction,
19}
20
21/// The initial PlanV2 text action profile.
22#[derive(Subcommand, Debug, Serialize)]
23#[serde(tag = "action", rename_all = "snake_case")]
24pub enum EditAction {
25    /// Replace exact literal text; without --at, search one declared story.
26    #[command(
27        override_usage = "jubarte edit replace [OPTIONS] <FILE> --find TEXT (--text TEXT|--text-file FILE)"
28    )]
29    Replace {
30        /// Frozen policy and new-edit attribution.
31        #[command(flatten)]
32        inline: InlineOptions,
33        /// Exact nonempty literal text.
34        #[arg(long)]
35        find: String,
36        /// Original paragraph ID from read; never silently retargeted.
37        #[arg(long)]
38        at: Option<String>,
39        /// Search story when --at is omitted (default body).
40        #[arg(long, conflicts_with = "at")]
41        story: Option<String>,
42        /// 1-based exact match, including overlapping candidate starts.
43        #[arg(long, value_parser = positive, conflicts_with = "all_matches")]
44        occurrence: Option<usize>,
45        /// Replace every candidate; refuses when any two candidates overlap. Requires --expect-count.
46        #[arg(long, requires = "expect_count")]
47        all_matches: bool,
48        /// Required complete candidate count for --all-matches.
49        #[arg(long, requires = "all_matches", value_parser = positive)]
50        expect_count: Option<usize>,
51        /// Exact text and optional attached comment.
52        #[command(flatten)]
53        payload: TextPayload,
54    },
55    /// Set exact desired paragraph text; an empty value retains the paragraph.
56    #[command(
57        override_usage = "jubarte edit rewrite [OPTIONS] <FILE> --at ID (--text TEXT|--text-file FILE)"
58    )]
59    Rewrite {
60        /// Frozen policy and new-edit attribution.
61        #[command(flatten)]
62        inline: InlineOptions,
63        /// Original paragraph ID.
64        #[arg(long)]
65        at: String,
66        /// Exact text and optional attached comment.
67        #[command(flatten)]
68        payload: TextPayload,
69    },
70    /// Insert an explicitly typed text or paragraph payload.
71    #[command(
72        override_usage = "jubarte edit insert [OPTIONS] <FILE> --kind text|paragraph --at ID (--text TEXT|--text-file FILE)"
73    )]
74    Insert {
75        /// Frozen policy and new-edit attribution.
76        #[command(flatten)]
77        inline: InlineOptions,
78        /// Object type; position never infers the kind.
79        #[arg(long, value_parser = ["text", "paragraph"])]
80        kind: String,
81        /// Original paragraph ID.
82        #[arg(long)]
83        at: String,
84        /// Insert text before this exact nonempty literal.
85        #[arg(long, conflicts_with_all = ["after_text", "edge", "position"])]
86        before_text: Option<String>,
87        /// Insert text after this exact nonempty literal.
88        #[arg(long, conflicts_with_all = ["edge", "position"])]
89        after_text: Option<String>,
90        /// Insert text at a paragraph edge.
91        #[arg(long, value_parser = ["start", "end"], conflicts_with_all = ["position", "occurrence"])]
92        edge: Option<String>,
93        /// Insert a paragraph beside the target paragraph.
94        #[arg(long, value_parser = ["before", "after"], conflicts_with = "occurrence")]
95        position: Option<String>,
96        /// 1-based literal candidate.
97        #[arg(long, value_parser = positive)]
98        occurrence: Option<usize>,
99        /// Exact text and optional attached comment.
100        #[command(flatten)]
101        payload: TextPayload,
102    },
103    /// Delete one exact range, or explicitly delete a whole paragraph.
104    #[command(
105        override_usage = "jubarte edit delete [OPTIONS] <FILE> --at ID (--find TEXT|--whole-block)"
106    )]
107    Delete {
108        /// Frozen policy and new-edit attribution.
109        #[command(flatten)]
110        inline: InlineOptions,
111        /// Original paragraph ID; mandatory even for a range deletion.
112        #[arg(long)]
113        at: String,
114        /// Exact nonempty literal range to remove.
115        #[arg(
116            long,
117            required_unless_present = "whole_block",
118            conflicts_with = "whole_block"
119        )]
120        find: Option<String>,
121        /// Explicit structural deletion (PlanV2 delete_paragraph).
122        #[arg(long, required_unless_present = "find", conflicts_with = "occurrence")]
123        whole_block: bool,
124        /// 1-based literal candidate.
125        #[arg(long, value_parser = positive, requires = "find")]
126        occurrence: Option<usize>,
127    },
128    /// Apply only: never record into, consume, or rewrite the plan.
129    // apply has no --save-plan, so its output is required unless it bundles
130    // or dry-runs.
131    #[command(
132        override_usage = "jubarte edit apply [OPTIONS] <FILE> --plan FILE",
133        mut_arg("output", |a| a.help("Primary edited DOCX; required unless bundling, replacing FILE or dry-running"))
134    )]
135    Apply {
136        /// Immutable source document.
137        file: PathBuf,
138        /// Input plan; v2 policy and attribution belong exclusively to it.
139        #[arg(long, value_name = "FILE", value_parser = super::plan_path())]
140        plan: PathBuf,
141        /// Advanced v1-only waiver when neither plan nor CLI supplies a hash.
142        #[arg(long)]
143        allow_unbound_plan: bool,
144        /// Publication and source preconditions.
145        #[command(flatten)]
146        delivery: DeliveryOptions,
147    },
148}
149
150/// Exact text input; file bytes must be UTF-8 and are never trimmed.
151#[derive(Args, Debug, Serialize)]
152#[group(skip)]
153pub struct TextPayload {
154    /// Exact plain text (not Markdown); empty text is meaningful.
155    #[arg(
156        long,
157        required_unless_present = "text_file",
158        conflicts_with = "text_file"
159    )]
160    pub text: Option<String>,
161    /// Exact UTF-8 file; all trailing newlines are preserved.
162    #[arg(long, value_name = "FILE", required_unless_present = "text")]
163    pub text_file: Option<PathBuf>,
164    /// Attach a comment to the nonempty resulting text.
165    #[arg(long)]
166    pub comment: Option<String>,
167}
168
169/// Policy and attribution for a newly compiled inline plan.
170#[derive(Args, Debug, Serialize)]
171pub struct InlineOptions {
172    /// Immutable source document.
173    pub file: PathBuf,
174    /// New revision and comment author. A write that adds markup needs it
175    /// spelled here or in JUBARTE_AUTHOR.
176    #[arg(short = 'a', long, default_value = "Jubarte", value_parser = super::parse_author)]
177    pub author: String,
178    /// Whether `-a`/`--author` was spelled on the command line (set after
179    /// parsing). The typed receipt uses this to say when the default signed
180    /// the new markup (#1891).
181    #[arg(skip)]
182    #[serde(skip)]
183    pub author_given: bool,
184    /// Frozen timestamp; timezone required. Default current UTC.
185    #[arg(short = 'd', long = "datetime", value_parser = super::parse_datetime)]
186    pub datetime: Option<String>,
187    /// Track new edits, preserving earlier history according to policy.
188    #[arg(long, default_value = "on", value_parser = ["on", "off"])]
189    pub track: String,
190    /// Policy for history remaining after explicit selected decisions.
191    #[arg(long, default_value = "keep", value_parser = ["keep", "accept", "reject", "refuse"])]
192    pub existing_revisions: String,
193    /// Original-source revision ID to accept; repeat to select a set.
194    #[arg(long)]
195    pub accept_change: Vec<String>,
196    /// Original-source revision ID to reject; repeat to select a set.
197    #[arg(long)]
198    pub reject_change: Vec<String>,
199    /// Save a source-bound PlanV2 without applying. Freezes targets, policy and time.
200    #[arg(long, value_name = "FILE", value_parser = super::plan_path(), conflicts_with_all = ["output", "out_dir", "report", "emit", "expect", "dry_run", "in_place"])]
201    pub save_plan: Option<PathBuf>,
202    /// Publication and source preconditions.
203    #[command(flatten)]
204    pub delivery: DeliveryOptions,
205}
206
207/// Publication and preparation options; never serialized into a saved plan.
208#[derive(Args, Debug, Serialize)]
209pub struct DeliveryOptions {
210    /// Replace FILE through the same atomic write as -o. A refused edit leaves FILE unchanged. Not with -o or --out-dir.
211    #[arg(long, conflicts_with_all = ["output", "out_dir", "dry_run"])]
212    pub in_place: bool,
213    /// Primary edited DOCX; required unless saving, bundling, replacing FILE or dry-running.
214    #[arg(short = 'o', long, value_name = "FILE", conflicts_with = "out_dir")]
215    pub output: Option<PathBuf>,
216    /// Publish a new bundle directory (document.docx, changes.diff, report.json).
217    #[arg(long, value_name = "NEW_DIR")]
218    pub out_dir: Option<PathBuf>,
219    /// JSON receipt, irrespective of filename suffix.
220    #[arg(long, value_name = "FILE")]
221    pub report: Option<PathBuf>,
222    /// Bundle roles: document,patch,report (primary document always included).
223    #[arg(long, value_delimiter = ',', value_parser = ["document", "patch", "report"])]
224    pub emit: Vec<String>,
225    /// Optional expectation contract, evaluated on the prepared primary
226    /// before publication (PlanV2 requests only; use `jubarte check` for a
227    /// standalone pass over a published output).
228    #[arg(long, value_name = "FILE")]
229    pub expect: Option<PathBuf>,
230    /// Redundant source digest must agree with a plan's embedded digest.
231    #[arg(long, value_name = "HASH", value_parser = digest)]
232    pub expect_sha256: Option<String>,
233    /// Prepare and validate the actual candidate; write no files.
234    #[arg(long, conflicts_with_all = ["output", "out_dir"])]
235    pub dry_run: bool,
236    /// Require a primary document change, independently of derived artifacts.
237    #[arg(long)]
238    pub require_change: bool,
239    /// Replace an explicitly named existing output; never overwrite an input.
240    #[arg(long)]
241    pub force: bool,
242    /// Refuse to accept or reject another author's tracked change, and
243    /// to delete, resolve, reopen or reword their comment. Restore,
244    /// strike, a comment and a reply stay allowed. JUBARTE_KEEP_OTHERS=1
245    /// sets the same guard. Another author is anyone other than
246    /// --author (Jubarte when --author is left out).
247    #[arg(long)]
248    pub keep_others: bool,
249    /// One result envelope, including empty results and refusals.
250    #[arg(long, conflicts_with = "jsonl")]
251    pub json: bool,
252    /// Header and exactly one terminal result.
253    #[arg(long)]
254    pub jsonl: bool,
255}
256
257pub(super) fn positive(s: &str) -> Result<usize, String> {
258    s.parse()
259        .ok()
260        .filter(|n| *n > 0)
261        .ok_or_else(|| "must be a positive, 1-based integer".into())
262}
263pub(super) fn digest(s: &str) -> Result<String, String> {
264    if s.len() == 64
265        && s.bytes()
266            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
267    {
268        Ok(s.into())
269    } else {
270        Err("must be 64 lowercase hexadecimal characters".into())
271    }
272}
273
274/// Route typed actions only when the tokens are not a valid legacy invocation.
275/// No filesystem probing: a filename cannot change parsing by appearing/disappearing.
276/// `./replace` always denotes a legacy filename; bare `replace -p ...` remains v1.
277pub fn route(arguments: &[OsString], model: &clap::Command) -> Vec<OsString> {
278    let mut routed = arguments.to_vec();
279    if arguments.get(1).is_none_or(|a| a != "edit") {
280        return routed;
281    }
282    let action = arguments.iter().skip(2).find(|a| {
283        !a.to_str().is_some_and(|s| {
284            s == "--quiet" || s.starts_with('-') && s.len() > 1 && s[1..].bytes().all(|b| b == b'q')
285        })
286    });
287    if !action.is_some_and(|a| {
288        matches!(
289            a.to_str(),
290            Some("replace" | "rewrite" | "insert" | "delete" | "apply" | "template")
291        )
292    }) {
293        return routed;
294    }
295    if model.clone().try_get_matches_from(arguments).is_ok() {
296        return routed;
297    }
298    if action.is_some_and(|a| a == "template") {
299        routed[1] = "__edit-template".into();
300        return routed;
301    }
302    routed[1] = "__edit-v2".into();
303    routed
304}
305
306pub(super) fn validate(
307    args: &clap::ArgMatches,
308    model: &mut clap::Command,
309) -> Result<(), clap::Error> {
310    let (action, args) = args.subcommand().expect("typed action required");
311    let present = |id| {
312        args.try_contains_id(id).unwrap_or(false)
313            && args.value_source(id) == Some(clap::parser::ValueSource::CommandLine)
314    };
315    let error = |message: &str| {
316        model
317            .clone()
318            .error(clap::error::ErrorKind::ArgumentConflict, message)
319    };
320    if !["output", "out_dir", "dry_run", "save_plan", "in_place"]
321        .into_iter()
322        .any(present)
323    {
324        return Err(error(
325            "writes require -o FILE or --out-dir NEW_DIR or --in-place; use --dry-run or inline --save-plan FILE",
326        ));
327    }
328    if action == "insert" {
329        let paragraph = args
330            .get_one::<String>("kind")
331            .is_some_and(|s| s == "paragraph");
332        if paragraph != present("position")
333            || !paragraph
334                && !["before_text", "after_text", "edge"]
335                    .into_iter()
336                    .any(present)
337        {
338            return Err(error(
339                "--kind paragraph requires --position before|after; --kind text requires --before-text, --after-text or --edge",
340            ));
341        }
342    }
343    Ok(())
344}
345
346impl EditAction {
347    /// Canonical action name for receipts.
348    pub fn name(&self) -> &'static str {
349        match self {
350            Self::Replace { .. } => "replace",
351            Self::Rewrite { .. } => "rewrite",
352            Self::Insert { .. } => "insert",
353            Self::Delete { .. } => "delete",
354            Self::Apply { .. } => "apply",
355        }
356    }
357    /// Inline policy, when this action compiles a new plan.
358    pub fn inline(&self) -> Option<&InlineOptions> {
359        match self {
360            Self::Replace { inline, .. }
361            | Self::Rewrite { inline, .. }
362            | Self::Insert { inline, .. }
363            | Self::Delete { inline, .. } => Some(inline),
364            Self::Apply { .. } => None,
365        }
366    }
367    /// Inline policy, mutable, when this action compiles a new plan.
368    pub fn inline_mut(&mut self) -> Option<&mut InlineOptions> {
369        match self {
370            Self::Replace { inline, .. }
371            | Self::Rewrite { inline, .. }
372            | Self::Insert { inline, .. }
373            | Self::Delete { inline, .. } => Some(inline),
374            Self::Apply { .. } => None,
375        }
376    }
377    /// Whether `-a` was spelled for this action. `edit apply` has none:
378    /// the plan's author is the signature.
379    pub fn author_was_given(&self) -> bool {
380        self.inline().is_none_or(|inline| inline.author_given)
381    }
382    /// Exact payload or resource input for actions with text.
383    pub fn payload(&self) -> Option<&TextPayload> {
384        match self {
385            Self::Replace { payload, .. }
386            | Self::Rewrite { payload, .. }
387            | Self::Insert { payload, .. } => Some(payload),
388            _ => None,
389        }
390    }
391    /// Source path.
392    pub fn file(&self) -> &std::path::Path {
393        match self {
394            Self::Apply { file, .. } => file,
395            _ => &self.inline().expect("inline").file,
396        }
397    }
398    /// Delivery options, independent of plan-owned policy.
399    pub fn delivery(&self) -> &DeliveryOptions {
400        match self {
401            Self::Apply { delivery, .. } => delivery,
402            _ => &self.inline().expect("inline").delivery,
403        }
404    }
405}