Skip to main content

jubarte_edit/edit/
for_edit.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `read --for-edit` (V2-10): the exact working document W that
6//! template/apply derive, exposed for inspection.
7//!
8//! Selection is frozen on the original source S before settlement:
9//! printed IDs and literal/regex searches match S's final logical text,
10//! `--changed`/`--by` match S's original revision/comment inventory, and
11//! `--context` neighbours are read-only original-S observations. The
12//! selected decisions (`accept`/`reject`) and the remaining-revision
13//! policy then produce W through the same `settle` path apply uses, so
14//! the hashes and readiness a caller sees describe the same basis a plan
15//! would be checked against. Readiness is operation- and range-specific
16//! evidence about the present document, never a promise about an
17//! unwritten rewrite: apply recomputes every constraint.
18
19use std::collections::{HashMap, HashSet};
20
21use serde::Serialize;
22
23use crate::changes::ChangeFilter;
24use crate::inspect::{Opened, Piece, project_paragraph, source_sha256};
25use crate::namespaces::{MC, W, W14};
26use crate::xmllinq::{Dom, NodeId};
27
28use super::origin::{Fate, Origin};
29use super::{
30    EditError, EditPlan, ExistingRevisions, Loaded, ResolveRevisions, Settled, load_stories,
31    settle, v2,
32};
33
34/// The working-basis inputs `read --for-edit` shares with template and
35/// apply: the same settlement produces the same W.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct ForEditRequest {
38    /// Printed IDs or closed ranges (`p5`, `p4-p7`, `t0`), resolved on S.
39    pub select: Option<String>,
40    /// Original story ID, or all (the default).
41    pub story: Option<String>,
42    /// First N body paragraphs.
43    pub head: Option<usize>,
44    /// Last N body paragraphs.
45    pub tail: Option<usize>,
46    /// Literal search on S's final logical text.
47    pub find: Option<String>,
48    /// Regex search on S's final logical text (conflicts with `find`).
49    pub regex: Option<String>,
50    /// Case-insensitive search.
51    pub ignore_case: bool,
52    /// Blocks intersecting a revision or comment of S.
53    pub changed: bool,
54    /// `--changed` author filter (a handle or full name).
55    pub by: Option<String>,
56    /// Additional author filters, unioned with by for original marks.
57    pub by_any: Vec<String>,
58    /// Read-only original-S neighbours around matches.
59    pub context: usize,
60    /// Primary records per page (default 100); ignored under `all`.
61    pub limit: Option<usize>,
62    /// Character budget across all emitted text (default 24000); ignored
63    /// under `all`.
64    pub max_chars: Option<usize>,
65    /// Disable presentation limits.
66    pub all: bool,
67    /// Continuation cursor of an earlier bounded query.
68    pub cursor: Option<String>,
69    /// Selected revisions to accept in the working view (S ids).
70    pub accept: Vec<String>,
71    /// Selected revisions to reject in the working view (S ids).
72    pub reject: Vec<String>,
73    /// Remaining-revision policy; default keep, matching new plans.
74    pub existing_revisions: ExistingRevisions,
75    /// Readiness for tracked new edits (default) or direct ones.
76    pub track: bool,
77    /// `edit template` (and other plan surfaces) allow only closed ranges
78    /// (proposal §2); `read --for-edit` keeps the open-ended `p17-` /
79    /// `-p3` spellings its shipped help documents, transitionally.
80    pub closed_ranges_only: bool,
81}
82
83impl Default for ForEditRequest {
84    fn default() -> Self {
85        Self {
86            select: None,
87            story: None,
88            head: None,
89            tail: None,
90            find: None,
91            regex: None,
92            ignore_case: false,
93            changed: false,
94            by: None,
95            by_any: Vec::new(),
96            context: 0,
97            limit: None,
98            max_chars: None,
99            all: false,
100            cursor: None,
101            accept: Vec::new(),
102            reject: Vec::new(),
103            existing_revisions: ExistingRevisions::Keep,
104            track: true,
105            closed_ranges_only: false,
106        }
107    }
108}
109
110/// The established short/long pair of one entity reference.
111#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
112pub struct TargetPair {
113    /// Snapshot-relative short ID (`p12`, `r5`, `c3`).
114    pub short_id: String,
115    /// Four-field long ID (`document.w:p.w14:paraId.3F2A1B7C`,
116    /// `document.w:p.j:short.p12` when the source gives no usable key).
117    pub long_id: String,
118}
119
120/// One text value with its completeness declared. A truncated value puts
121/// its bounded piece in `text_preview` and keeps `text` absent, so a
122/// preview can never be copied as a complete rewrite payload.
123#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
124pub struct TextValue {
125    /// The complete exact text; absent when `complete` is false.
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub text: Option<String>,
128    /// Bounded piece of the text when `complete` is false.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub text_preview: Option<String>,
131    /// Whether `text` holds the whole value.
132    pub complete: bool,
133}
134
135impl TextValue {
136    fn complete(text: String) -> Self {
137        Self {
138            text: Some(text),
139            text_preview: None,
140            complete: true,
141        }
142    }
143
144    /// The value bounded to `chars` Unicode scalar positions; a preview
145    /// keeps `text` absent so it cannot pose as a complete payload.
146    fn bounded(text: &str, chars: usize) -> Self {
147        let mut preview: String = text.chars().take(chars).collect();
148        // A preview never cuts a word in two: a mid-word cut finishes it.
149        if preview.len() < text.len()
150            && !preview.ends_with(char::is_whitespace)
151            && text[preview.len()..]
152                .chars()
153                .next()
154                .is_some_and(|c| !c.is_whitespace())
155        {
156            preview.extend(
157                text[preview.len()..]
158                    .chars()
159                    .take_while(|c| !c.is_whitespace()),
160            );
161        }
162        if preview.len() == text.len() {
163            return Self::complete(text.to_string());
164        }
165        Self {
166            text: None,
167            text_preview: Some(preview),
168            complete: false,
169        }
170    }
171
172    /// Unicode scalar count of the emitted text.
173    fn chars(&self) -> usize {
174        self.text
175            .as_deref()
176            .or(self.text_preview.as_deref())
177            .map_or(0, |t| t.chars().count())
178    }
179}
180
181/// The working view of one selected paragraph.
182#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
183pub struct WorkingText {
184    /// Exact logical working text and its completeness.
185    #[serde(flatten)]
186    pub value: TextValue,
187    /// SHA-256 of the complete UTF-8 logical working text, shown even
188    /// under a bounded preview (a preview is still not a payload).
189    /// Absent when the codec cannot represent the text.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub before_sha256: Option<String>,
192}
193
194/// A known blocker: a range of the working text (zero-based Unicode
195/// scalar positions, exclusive end; observations, not an address
196/// family) an operation cannot assume editable.
197#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
198pub struct Blocker {
199    /// `[start, end)` in Unicode scalar positions of the working text;
200    /// a zero-length range marks a position.
201    pub range: [usize; 2],
202    /// `tracked_insertion`, `tracked_deletion`, `move`, `hyperlink`,
203    /// `field`, `content_control`, `symbol` or `opaque`.
204    pub kind: String,
205    /// `conditional` when a selected revision decision can free the
206    /// range, `unavailable` when the structure itself blocks edits.
207    pub decision: String,
208    /// The revision this blocker belongs to.
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub revision: Option<TargetPair>,
211    /// Human-readable detail.
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub detail: Option<String>,
214}
215
216/// Readiness of one operation family on a paragraph: `available`,
217/// `conditional`, `unavailable` or `unknown`. Range operations are
218/// available on every range the blockers leave free.
219#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
220pub struct Readiness {
221    /// Operation family (`replace`, `insert`, `delete`, `rewrite`,
222    /// `insert_paragraph`, `delete_paragraph`, `comment`).
223    pub operation: String,
224    /// `available`, `conditional`, `unavailable` or `unknown`.
225    pub status: String,
226    /// Indices into the row's `blockers`.
227    #[serde(default, skip_serializing_if = "Vec::is_empty")]
228    pub blockers: Vec<usize>,
229    /// Why the status is not `available`.
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub reason: Option<String>,
232}
233
234/// One original revision mark intersecting the paragraph.
235#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
236pub struct RevisionRef {
237    /// The revision's paired identity.
238    pub target: TargetPair,
239    /// `insertion`, `deletion`, `move`, `paragraph_mark` or `formatting`.
240    pub kind: String,
241    /// Revision author.
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub author: Option<String>,
244    /// Range of the working text the revision covers, when it has one.
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub range: Option<[usize; 2]>,
247    /// Whether the reference is an original-S observation (`"original"`)
248    /// or a working-view fact (`"working"`).
249    pub basis: String,
250}
251
252/// One original comment whose range intersects the paragraph.
253#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
254pub struct CommentRef {
255    /// `c{id}`.
256    pub short_id: String,
257    /// The comment's long ID (`comments.w:comment.w:id.N`).
258    pub long_id: String,
259    /// `open` or `done`.
260    pub status: String,
261    /// Why the reference is partial (`cross_story_range`: the range's
262    /// endpoints lie in different stories — malformed input a part-based
263    /// format cannot carry — so each endpoint names the comment).
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub limitation: Option<String>,
266}
267
268/// Where a source paragraph went under settlement.
269#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
270#[serde(rename_all = "snake_case")]
271pub enum Correspondence {
272    /// The paragraph kept its exact one-to-one working correspondence.
273    OneToOne,
274    /// Settlement merged it with its neighbours.
275    Merged,
276    /// Settlement removed it with its text.
277    Removed,
278}
279
280/// One selected original paragraph, its working text and readiness.
281#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
282pub struct ForEditRow {
283    /// Paired identity in the original source.
284    pub target: TargetPair,
285    /// `body` or the story stem (`header1`, `footnotes`, ...).
286    pub story: String,
287    /// Selection filters the paragraph matched (`ids`, `find`, `regex`,
288    /// `changed`); empty for the unfiltered default.
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub matched_by: Vec<String>,
291    /// Original-S final logical text (an immutable observation).
292    pub original: TextValue,
293    /// SHA-256 of the complete original text, when it is representable.
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub original_sha256: Option<String>,
296    /// Working text and `before_sha256`; absent when settlement merged or
297    /// removed the paragraph.
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub working: Option<WorkingText>,
300    /// Original-to-working correspondence.
301    pub correspondence: Correspondence,
302    /// The working paragraph a merged paragraph's text went to.
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub merged_into: Option<String>,
305    /// Whether the exact text codec represents the working text.
306    pub text_codec: String,
307    /// Original revision marks intersecting the paragraph.
308    #[serde(default, skip_serializing_if = "Vec::is_empty")]
309    pub revisions: Vec<RevisionRef>,
310    /// Original comments whose ranges intersect the paragraph.
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub comments: Vec<CommentRef>,
313    /// Ranges no operation may assume editable.
314    #[serde(default, skip_serializing_if = "Vec::is_empty")]
315    pub blockers: Vec<Blocker>,
316    /// Per-operation readiness evidence.
317    pub readiness: Vec<Readiness>,
318    /// Operation families the scan does not assess.
319    #[serde(default, skip_serializing_if = "Vec::is_empty")]
320    pub unassessed_operations: Vec<String>,
321}
322
323/// A read-only original-S observation; never a rewrite row.
324#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
325pub struct SourceContextRow {
326    /// `paragraph` (or `opaque` for unrepresented regions).
327    pub kind: String,
328    /// Paired identity in the original source.
329    pub target: TargetPair,
330    /// Original-S final logical text.
331    #[serde(flatten)]
332    pub value: TextValue,
333    /// `final`, the view `value` was projected under: inserted text in,
334    /// deleted text out. The revision marks below say which parts of the
335    /// text are pending decisions.
336    pub text_view: String,
337    /// Whether the exact text codec represents this paragraph
338    /// (`supported` / `unsupported`): context is never editable, but an
339    /// unrepresentable neighbour must not look like one.
340    pub text_codec: String,
341    /// Constructs present but not represented in `value` (`sym`,
342    /// `field`, `revision`, `drawing`, ...).
343    #[serde(default, skip_serializing_if = "Vec::is_empty")]
344    pub limitations: Vec<String>,
345    /// Original revision marks the neighbour holds (`basis` is always
346    /// `original`): a pending insertion's text or an emptied paragraph
347    /// is labelled, not silent.
348    #[serde(default, skip_serializing_if = "Vec::is_empty")]
349    pub revisions: Vec<RevisionRef>,
350    /// Why the record is context (`context`, `unsupported_text_codec`,
351    /// `merged`, `removed`).
352    pub reason_codes: Vec<String>,
353}
354
355/// What the query returned and what it left out.
356#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
357pub struct ForEditCoverage {
358    /// Whether the whole frozen selection was returned, complete.
359    pub selection_complete: bool,
360    /// Frozen selection size.
361    pub paragraphs_selected: usize,
362    /// Rows returned this page.
363    pub paragraphs_returned: usize,
364    /// Read-only context records returned this page.
365    pub context_paragraphs: usize,
366    /// Whether presentation limits cut anything.
367    pub truncated: bool,
368    /// Known omissions.
369    #[serde(default, skip_serializing_if = "Vec::is_empty")]
370    pub omissions: Vec<String>,
371}
372
373/// The frozen basis the result and any cursor are bound to.
374#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
375pub struct ForEditBasis {
376    /// `final`, the only working text view.
377    pub text_view: String,
378    /// [`v2::TEXT_CODEC_VERSION`].
379    pub text_codec_version: u32,
380    /// `on` or `off`.
381    pub track: String,
382    /// The remaining-revision policy.
383    pub existing_revisions: String,
384    /// Selected revision decisions, sorted (decisions are a set).
385    pub accept: Vec<String>,
386    /// Selected revision decisions, sorted (decisions are a set).
387    pub reject: Vec<String>,
388    /// SHA-256 of the bytes W was derived from (S after settlement).
389    pub working_sha256: String,
390    /// SHA-256 of every input the basis binds (source digest, frozen
391    /// selection, filters, codec, policy, decisions); cursor validity.
392    pub digest: String,
393}
394
395/// What settlement did before the working view was read.
396#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
397pub struct ForEditSettled {
398    /// Selected decisions or the policy rewrote the document.
399    pub changed: bool,
400    /// Selected revisions accepted.
401    #[serde(default, skip_serializing_if = "Vec::is_empty")]
402    pub accepted: Vec<String>,
403    /// Selected revisions rejected.
404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
405    pub rejected: Vec<String>,
406}
407
408/// The `read --for-edit` result document.
409#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
410pub struct ForEdit {
411    /// `jubarte-read-for-edit-v1`.
412    pub schema: String,
413    /// The bound original source digest.
414    pub source_sha256: String,
415    /// The working basis the rows describe.
416    pub basis: ForEditBasis,
417    /// Settlement facts.
418    pub settled: ForEditSettled,
419    /// The frozen selection, in document order.
420    pub paragraphs: Vec<ForEditRow>,
421    /// Original comments with no anchor in any story: marks too,
422    /// labelled at document level instead of silently dropped.
423    #[serde(default, skip_serializing_if = "Vec::is_empty")]
424    pub unanchored_comments: Vec<CommentRef>,
425    /// Read-only original-S observations (`--context` neighbours).
426    #[serde(default, skip_serializing_if = "Vec::is_empty")]
427    pub source_context: Vec<SourceContextRow>,
428    /// The original source's comment inventory, so consumers that build on
429    /// the same view (template generation) need not reparse the package.
430    /// Not part of the wire document.
431    #[serde(skip)]
432    pub comments: Vec<crate::comments::CommentRecord>,
433    /// Completeness and omissions.
434    pub coverage: ForEditCoverage,
435    /// Continuation token; `null` when the selection is exhausted.
436    #[serde(skip_serializing_if = "Option::is_none")]
437    pub next_cursor: Option<String>,
438    /// The input's validity findings, as `read --json` carries them in
439    /// `summary.input_validity`: set only by the CLI, which read the file
440    /// (#1340); absent from the library's result.
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub input_validity: Option<crate::validate::InputValidity>,
443}
444
445fn existing_revisions_name(policy: ExistingRevisions) -> &'static str {
446    match policy {
447        ExistingRevisions::Keep => "keep",
448        ExistingRevisions::Accept => "accept",
449        ExistingRevisions::Reject => "reject",
450        ExistingRevisions::Refuse => "refuse",
451    }
452}
453
454/// Everything a cursor binds: the source digest, the frozen selection,
455/// the filters that produced it, the codec, and the working policy.
456fn basis_digest(source_digest: &str, request: &ForEditRequest, selection: &Selection) -> String {
457    // Decisions are a set: order and repetition are no part of the basis.
458    let mut accept = request.accept.clone();
459    let mut reject = request.reject.clone();
460    accept.sort();
461    accept.dedup();
462    reject.sort();
463    reject.dedup();
464    let basis = serde_json::json!({
465        "v": 1,
466        "source_sha256": source_digest,
467        "codec": v2::TEXT_CODEC_VERSION,
468        "view": "final",
469        "track": request.track,
470        "existing_revisions": existing_revisions_name(request.existing_revisions),
471        "accept": accept,
472        "reject": reject,
473        "select": request.select,
474        "story": request.story,
475        "head": request.head,
476        "tail": request.tail,
477        "find": request.find,
478        "regex": request.regex,
479        "ignore_case": request.ignore_case,
480        "changed": request.changed,
481        "by": request.by,
482        "by_any": request.by_any,
483        "context": request.context,
484        "frozen": selection.selected,
485    });
486    source_sha256(
487        serde_json::to_string(&basis)
488            .expect("basis serializes")
489            .as_bytes(),
490    )
491}
492
493/// The cursor token: a version, the bound basis digest and the next
494/// index into the frozen selection, base64url-encoded.
495fn cursor_token(basis: &str, offset: usize) -> String {
496    use base64::Engine;
497    let json = serde_json::json!({"v": 1, "basis": basis, "offset": offset});
498    base64::engine::general_purpose::URL_SAFE_NO_PAD
499        .encode(serde_json::to_string(&json).expect("cursor serializes"))
500}
501
502/// The offset a continuation resumes at; its bound basis must still hold.
503fn cursor_offset(token: &str, basis: &str) -> Result<usize, EditError> {
504    use base64::Engine;
505    let decode = || -> Option<serde_json::Value> {
506        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
507            .decode(token)
508            .ok()?;
509        serde_json::from_slice(&bytes).ok()
510    };
511    let cursor = decode().ok_or_else(|| {
512        super::err(
513            "USAGE",
514            None,
515            "the cursor is not a read --for-edit continuation token",
516        )
517    })?;
518    if cursor["v"] != 1 || !cursor["offset"].is_u64() || !cursor["basis"].is_string() {
519        return Err(super::err(
520            "USAGE",
521            None,
522            "the cursor is not a read --for-edit continuation token",
523        ));
524    }
525    if cursor["basis"].as_str() != Some(basis) {
526        return Err(super::err(
527            "CURSOR_BASIS_CHANGED",
528            None,
529            "the cursor is bound to another source, selection, filter or working basis; start a new query",
530        ));
531    }
532    Ok(cursor["offset"].as_u64().unwrap_or(0) as usize)
533}
534
535/// The frozen selection: the paragraphs of S the query names, in
536/// document order, and which filters named each of them.
537struct Selection {
538    /// Global S paragraph indexes, in document order.
539    selected: Vec<usize>,
540    /// The filter names each selected paragraph matched.
541    matched_by: HashMap<usize, Vec<String>>,
542    /// Neighbour count for `--context` rows.
543    context: usize,
544}
545
546impl Selection {
547    fn build(
548        request: &ForEditRequest,
549        s_opened: &Opened,
550        s_loaded: &Loaded,
551        source: &[u8],
552    ) -> Result<Self, EditError> {
553        let total = s_loaded.paragraph_nodes.len();
554        let mut filters: Vec<(&'static str, HashSet<usize>)> = Vec::new();
555
556        if let Some(story) = request.story.as_deref().filter(|s| *s != "all") {
557            let si = s_loaded
558                .stories
559                .iter()
560                .position(|s| s.id == story)
561                .ok_or_else(|| {
562                    super::err("USAGE", None, format!("unknown source story {story}"))
563                })?;
564            filters.push((
565                "story",
566                s_loaded
567                    .paragraph_story
568                    .iter()
569                    .enumerate()
570                    .filter(|(_, pair)| pair.0 == si)
571                    .map(|(g, _)| g)
572                    .collect(),
573            ));
574        }
575        if let Some(spec) = &request.select {
576            filters.push((
577                "ids",
578                id_selection(spec, source, request.closed_ranges_only)?,
579            ));
580        }
581        if let Some(head) = request.head {
582            filters.push((
583                "ids",
584                s_loaded
585                    .paragraph_story
586                    .iter()
587                    .enumerate()
588                    .filter(|(_, pair)| pair.0 == 0 && pair.1 < head)
589                    .map(|(g, _)| g)
590                    .collect(),
591            ));
592        }
593        if let Some(tail) = request.tail {
594            let body = s_loaded
595                .paragraph_story
596                .iter()
597                .filter(|pair| pair.0 == 0)
598                .count();
599            let from = body.saturating_sub(tail);
600            filters.push((
601                "ids",
602                s_loaded
603                    .paragraph_story
604                    .iter()
605                    .enumerate()
606                    .filter(|(_, pair)| pair.0 == 0 && pair.1 >= from)
607                    .map(|(g, _)| g)
608                    .collect(),
609            ));
610        }
611        if request.find.is_some() || request.regex.is_some() {
612            filters.push((
613                if request.find.is_some() {
614                    "find"
615                } else {
616                    "regex"
617                },
618                text_selection(request, &s_opened.dom, &s_loaded.paragraph_nodes)?,
619            ));
620        }
621        if request.changed {
622            filters.push(("changed", changed_selection(request, s_loaded, source)?));
623        }
624
625        let mut matched_by: HashMap<usize, Vec<String>> = HashMap::new();
626        let selected: Vec<usize> = if filters.is_empty() {
627            (0..total).collect()
628        } else {
629            let mut it = filters.iter();
630            let mut keep: HashSet<usize> = it.next().map_or_else(HashSet::new, |(_, s)| s.clone());
631            for (_, set) in it {
632                keep.retain(|g| set.contains(g));
633            }
634            for (name, set) in &filters {
635                for &g in &keep {
636                    if set.contains(&g) {
637                        matched_by.entry(g).or_default().push((*name).to_string());
638                    }
639                }
640            }
641            (0..total).filter(|g| keep.contains(g)).collect()
642        };
643        for names in matched_by.values_mut() {
644            names.dedup();
645        }
646        Ok(Self {
647            selected,
648            matched_by,
649            context: request.context,
650        })
651    }
652}
653
654/// The paragraphs `spec` names: `pN`/`pN-pM` closed ranges and `tN`
655/// whole tables, against the body's own numbering on S; the transitional
656/// open-ended `pN-` / `-pN` spellings parse unless the caller requires
657/// closed ranges.
658fn id_selection(spec: &str, source: &[u8], closed_only: bool) -> Result<HashSet<usize>, EditError> {
659    super::v2_apply::SourceModel::new(source)?.selected_paragraphs(spec, !closed_only)
660}
661
662/// Body paragraph indexes matching the same original final logical text as
663/// `read --for-edit`, in document order. The Markdown view's `-p` selectors
664/// cannot address other stories yet.
665///
666/// # Errors
667///
668/// The package cannot be opened, or the regular expression does not compile.
669pub fn matching_body_paragraphs(
670    source: &[u8],
671    find: Option<&str>,
672    regex: Option<&str>,
673    ignore_case: bool,
674) -> Result<Vec<usize>, EditError> {
675    let opened = Opened::open(source).map_err(super::open_error)?;
676    let paragraphs = crate::inspect::body_paragraph_nodes(&opened.dom, opened.body);
677    let request = ForEditRequest {
678        find: find.map(str::to_owned),
679        regex: regex.map(str::to_owned),
680        ignore_case,
681        ..ForEditRequest::default()
682    };
683    let matches = text_selection(&request, &opened.dom, &paragraphs)?;
684    Ok((0..paragraphs.len())
685        .filter(|p| matches.contains(p))
686        .collect())
687}
688
689/// The largest program a `--regex` pattern may compile into: 10 MiB, the
690/// regex crate's own default, pinned here so a dependency upgrade cannot
691/// loosen it.
692const REGEX_SIZE_LIMIT: usize = 10 * (1 << 20);
693
694/// The paragraphs whose original final logical text the search matches.
695fn text_selection(
696    request: &ForEditRequest,
697    dom: &Dom,
698    paragraph_nodes: &[NodeId],
699) -> Result<HashSet<usize>, EditError> {
700    let matcher: Box<dyn Fn(&str) -> bool> = if let Some(find) = &request.find {
701        let needle = if request.ignore_case {
702            find.to_lowercase()
703        } else {
704            find.clone()
705        };
706        let ignore_case = request.ignore_case;
707        Box::new(move |text: &str| {
708            if ignore_case {
709                text.to_lowercase().contains(&needle)
710            } else {
711                text.contains(&needle)
712            }
713        })
714    } else {
715        let pattern = request.regex.as_deref().unwrap_or("");
716        let pattern = if request.ignore_case {
717            format!("(?i){pattern}")
718        } else {
719            pattern.to_string()
720        };
721        // The pattern can come from an untrusted caller (WASM, Python, an
722        // agent). The regex crate matches in linear time, so the risk is
723        // a short pattern that compiles into a huge program
724        // (`a{1000}{1000}`). The size limit refuses that; a cap on the
725        // pattern's length would not, and would refuse long alternations
726        // of defined terms.
727        let compiled = regex::RegexBuilder::new(&pattern)
728            .size_limit(REGEX_SIZE_LIMIT)
729            .build()
730            .map_err(|e| super::err("USAGE", None, format!("--regex does not compile: {e}")))?;
731        Box::new(move |text: &str| compiled.is_match(text))
732    };
733    Ok(paragraph_nodes
734        .iter()
735        .enumerate()
736        .filter(|(_, p)| matcher(&project_paragraph(dom, **p).text))
737        .map(|(g, _)| g)
738        .collect())
739}
740
741/// The paragraphs an original revision or comment intersects; `--by`
742/// keeps only marks of that author.
743fn changed_selection(
744    request: &ForEditRequest,
745    s_loaded: &Loaded,
746    source: &[u8],
747) -> Result<HashSet<usize>, EditError> {
748    let story_index: HashMap<String, usize> = s_loaded
749        .stories
750        .iter()
751        .enumerate()
752        .map(|(i, s)| (s.id.clone(), i))
753        .collect();
754    let place = |id: Option<&String>| -> Option<(usize, usize)> {
755        let (story, local) = crate::ids::paragraph_place(id?)?;
756        Some((*story_index.get(&story)?, local))
757    };
758    let global = |at: (usize, usize)| -> Option<usize> {
759        s_loaded.paragraph_story.iter().position(|&pair| pair == at)
760    };
761    // `--by` matches an author exactly, or a comment's explicit
762    // `w:initials` exactly; it never derives a handle from a name.
763    let authors: Vec<&str> = request
764        .by
765        .iter()
766        .chain(&request.by_any)
767        .map(|a| {
768            let a = a.trim();
769            a.strip_prefix('@').unwrap_or(a)
770        })
771        .collect();
772    let by = |name: Option<&str>, initials: Option<&str>| -> bool {
773        if authors.is_empty() {
774            return true;
775        }
776        authors
777            .iter()
778            .any(|want| name.is_some_and(|a| a == *want) || initials.is_some_and(|i| i == *want))
779    };
780    let mut out = HashSet::new();
781    let changes = crate::changes::list_changes(source)
782        .map_err(|e| super::err("INVALID_DOCUMENT", None, e.to_string()))?;
783    for change in &changes {
784        if !by(change.author.as_deref(), None) {
785            continue;
786        }
787        if let Some(g) = place(change.paragraph.as_ref()).and_then(global) {
788            out.insert(g);
789        }
790    }
791    let comments = crate::comments::list_comments(source)
792        .map_err(|e| super::err(e.code(), None, e.to_string()))?;
793    for comment in &comments {
794        if !by(Some(&comment.author), comment.initials.as_deref()) {
795            continue;
796        }
797        for at in comment_paragraphs(comment, s_loaded).0 {
798            if let Some(g) = global(at) {
799                out.insert(g);
800            }
801        }
802    }
803    Ok(out)
804}
805
806/// The `(story, local)` paragraphs a comment's range covers: min to max
807/// of its endpoints inside one story, and each endpoint separately when
808/// a malformed range crosses stories (OOXML cannot carry one, so the
809/// comment is attached where its markers are instead of dropped).
810fn comment_paragraphs(
811    comment: &crate::comments::CommentRecord,
812    s_loaded: &Loaded,
813) -> (Vec<(usize, usize)>, bool) {
814    let story_index: HashMap<&str, usize> = s_loaded
815        .stories
816        .iter()
817        .enumerate()
818        .map(|(i, s)| (s.id.as_str(), i))
819        .collect();
820    let place = |id: Option<&String>| -> Option<(usize, usize)> {
821        let (story, local) = crate::ids::paragraph_place(id?)?;
822        Some((*story_index.get(story.as_str())?, local))
823    };
824    let Some(first) = place(comment.paragraph.as_ref()) else {
825        return (Vec::new(), false);
826    };
827    match comment.last_paragraph.as_ref() {
828        None => (vec![first], false),
829        Some(_) => match place(comment.last_paragraph.as_ref()) {
830            None => (vec![first], true),
831            Some(l) if l.0 == first.0 => {
832                let (lo, hi) = (first.1.min(l.1), first.1.max(l.1));
833                ((lo..=hi).map(|local| (first.0, local)).collect(), false)
834            }
835            Some(l) => (vec![first, l], true),
836        },
837    }
838}
839
840/// The comment reference of `comment`.
841fn comment_ref(comment: &crate::comments::CommentRecord) -> CommentRef {
842    CommentRef {
843        short_id: format!("c{}", comment.id),
844        long_id: format!("comments.w:comment.w:id.{}", comment.id),
845        status: if comment.done {
846            "done".to_string()
847        } else {
848            "open".to_string()
849        },
850        limitation: None,
851    }
852}
853
854/// The comments intersecting each global S paragraph index, and the
855/// comments no paragraph holds (no anchor in any story).
856fn comments_by_paragraph(
857    comments: &[crate::comments::CommentRecord],
858    s_loaded: &Loaded,
859) -> (HashMap<usize, Vec<CommentRef>>, Vec<CommentRef>) {
860    let global = |at: (usize, usize)| s_loaded.paragraph_story.iter().position(|&p| p == at);
861    let mut out: HashMap<usize, Vec<CommentRef>> = HashMap::new();
862    let mut unanchored = Vec::new();
863    for comment in comments {
864        let (paragraphs, cross_story) = comment_paragraphs(comment, s_loaded);
865        if paragraphs.is_empty() {
866            unanchored.push(comment_ref(comment));
867            continue;
868        }
869        let mut reference = comment_ref(comment);
870        if cross_story {
871            reference.limitation = Some("cross_story_range".to_string());
872        }
873        for at in paragraphs {
874            if let Some(g) = global(at) {
875                out.entry(g).or_default().push(reference.clone());
876            }
877        }
878    }
879    (out, unanchored)
880}
881
882/// Per-story usable native `w14:paraId` keys of S, for the long IDs:
883/// a value is a key only when lexical (8 hex digits), in Word's range
884/// (`1..=0x7FFFFFFF`) and unique in its part.
885struct NativeKeys {
886    /// Count of each paraId value per story index.
887    counts: Vec<HashMap<u32, usize>>,
888}
889
890impl NativeKeys {
891    fn collect(dom: &Dom, stories: &[super::StoryPart]) -> Self {
892        let counts = stories
893            .iter()
894            .map(|story| {
895                let mut counts: HashMap<u32, usize> = HashMap::new();
896                for p in dom.descendants(story.root, Some(&W::p())) {
897                    if let Some(value) = native_para_id(dom, p) {
898                        *counts.entry(value).or_default() += 1;
899                    }
900                }
901                counts
902            })
903            .collect();
904        Self { counts }
905    }
906
907    /// The pair `paragraph` gets: its paraId when it is a usable native
908    /// key, else the `j:short` long form of its short ID.
909    fn pair(
910        &self,
911        dom: &Dom,
912        story: usize,
913        part: &str,
914        short_id: &str,
915        paragraph: NodeId,
916    ) -> TargetPair {
917        let stem = crate::ids::part_story(part);
918        let key = native_para_id(dom, paragraph)
919            .filter(|value| self.counts[story].get(value) == Some(&1));
920        let long_id = match key.and_then(|_| {
921            dom.attribute(paragraph, &W14::name("paraId"))
922                .map(str::to_string)
923        }) {
924            Some(lexical) => format!("{stem}.w:p.w14:paraId.{lexical}"),
925            None => format!("{stem}.w:p.j:short.{short_id}"),
926        };
927        TargetPair {
928            short_id: short_id.to_string(),
929            long_id,
930        }
931    }
932}
933
934/// The `w14:paraId` of `paragraph` when it is a key Word could have
935/// written, under the shared native-key policy: exactly eight ASCII hex
936/// digits in `1..=0x7FFFFFFF`.
937fn native_para_id(dom: &Dom, paragraph: NodeId) -> Option<u32> {
938    super::native_keys::para_id(dom.attribute(paragraph, &W14::name("paraId"))?)
939}
940
941/// The long ID of the revision element `el` (a `w:ins`, `w:del`,
942/// `w:moveFrom` or `w:moveTo`): its native `w:id` when usable, else the
943/// `j:short` form of its printed short ID.
944pub(super) fn revision_pair(dom: &Dom, el: NodeId, story: &str, part: &str) -> TargetPair {
945    let local = dom
946        .name(el)
947        .map(|n| n.local_name().to_string())
948        .unwrap_or_default();
949    let wid = dom.attribute(el, &W::id()).unwrap_or_default();
950    let short = crate::ids::ChangeId::new(story, wid).short();
951    let stem = crate::ids::part_story(part);
952    let usable = super::native_keys::revision_id(wid).is_some();
953    let long_id = if usable {
954        format!("{stem}.w:{local}.w:id.{}", escape_value(wid))
955    } else {
956        format!("{stem}.w:{local}.j:short.{short}")
957    };
958    TargetPair {
959        short_id: short,
960        long_id,
961    }
962}
963
964/// The VALUE escaping of the long-ID contract: ASCII letters, digits,
965/// dot, underscore and colon stay literal; every other UTF-8 byte is a
966/// hyphen and two uppercase hex digits.
967fn escape_value(text: &str) -> String {
968    let mut out = String::with_capacity(text.len());
969    for &b in text.as_bytes() {
970        if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':') {
971            out.push(char::from(b));
972        } else {
973            out.push_str(&format!("-{b:02X}"));
974        }
975    }
976    out
977}
978
979/// The element a projection segment's text comes from.
980fn piece_element(piece: &Piece) -> NodeId {
981    match piece {
982        Piece::Text { t, .. } => *t,
983        Piece::Glyph { element, .. } => *element,
984    }
985}
986
987/// What an opaque segment sits inside, in order of strictness: a
988/// revision first (a decision frees it), then the structure that holds
989/// the text (no edit kind may cross it).
990fn classify(
991    dom: &Dom,
992    run: NodeId,
993    paragraph: NodeId,
994    story: &str,
995    part: &str,
996) -> (String, String, Option<TargetPair>, Option<String>) {
997    for &node in &dom.ancestors(run, None) {
998        if node == paragraph {
999            break;
1000        }
1001        let Some(name) = dom.name(node) else {
1002            continue;
1003        };
1004        if name.namespace_name() == MC::URI {
1005            return (
1006                "opaque".to_string(),
1007                "unavailable".to_string(),
1008                None,
1009                Some("alternate content".to_string()),
1010            );
1011        }
1012        if name.namespace_name() != W::URI {
1013            continue;
1014        }
1015        match name.local_name() {
1016            "ins" | "moveTo" => {
1017                let kind = if name.local_name() == "ins" {
1018                    "tracked_insertion"
1019                } else {
1020                    "move"
1021                };
1022                let revision = revision_pair(dom, node, story, part);
1023                let author = dom.attribute(node, &W::author());
1024                return (
1025                    kind.to_string(),
1026                    "conditional".to_string(),
1027                    Some(revision),
1028                    author.map(|a| format!("a tracked change by {a:?}; a decision frees it")),
1029                );
1030            }
1031            "hyperlink" => {
1032                return (
1033                    "hyperlink".to_string(),
1034                    "unavailable".to_string(),
1035                    None,
1036                    Some("edit beside it or comment on it".to_string()),
1037                );
1038            }
1039            "fldSimple" => {
1040                return (
1041                    "field".to_string(),
1042                    "unavailable".to_string(),
1043                    None,
1044                    Some("the result of a field".to_string()),
1045                );
1046            }
1047            "sdt" => {
1048                return (
1049                    "content_control".to_string(),
1050                    "unavailable".to_string(),
1051                    None,
1052                    Some("a content control; fill it or comment on it".to_string()),
1053                );
1054            }
1055            "smartTag" | "customXml" | "dir" | "bdo" | "del" | "moveFrom" => {
1056                return (
1057                    "opaque".to_string(),
1058                    "unavailable".to_string(),
1059                    None,
1060                    Some(format!("inside w:{}", name.local_name())),
1061                );
1062            }
1063            _ => {}
1064        }
1065    }
1066    (
1067        "field".to_string(),
1068        "unavailable".to_string(),
1069        None,
1070        Some("the result of a field".to_string()),
1071    )
1072}
1073
1074/// Byte offset to Unicode scalar position in `text`.
1075fn char_pos(text: &str, byte: usize) -> usize {
1076    text[..byte].chars().count()
1077}
1078
1079/// The blockers, revision references and mark revisions of a working
1080/// paragraph, from its projection and XML.
1081fn obstacles(
1082    dom: &Dom,
1083    paragraph: NodeId,
1084    story: &str,
1085    part: &str,
1086) -> (Vec<Blocker>, Vec<RevisionRef>, Vec<RevisionRef>) {
1087    let projection = project_paragraph(dom, paragraph);
1088    let text = projection.text.as_str();
1089    let order: HashMap<NodeId, usize> = dom
1090        .descendants(paragraph, None)
1091        .into_iter()
1092        .enumerate()
1093        .map(|(i, n)| (n, i))
1094        .collect();
1095
1096    let mut blockers: Vec<Blocker> = Vec::new();
1097    let mut revisions: Vec<RevisionRef> = Vec::new();
1098    let mut seen: HashSet<String> = HashSet::new();
1099    let revision = |dom: &Dom,
1100                    el: NodeId,
1101                    kind: &str,
1102                    range: Option<[usize; 2]>,
1103                    revisions: &mut Vec<RevisionRef>,
1104                    seen: &mut HashSet<String>| {
1105        let pair = revision_pair(dom, el, story, part);
1106        if seen.insert(pair.short_id.clone()) {
1107            revisions.push(RevisionRef {
1108                target: pair,
1109                kind: kind.to_string(),
1110                author: dom.attribute(el, &W::author()).map(str::to_string),
1111                range,
1112                basis: "working".to_string(),
1113            });
1114        }
1115    };
1116
1117    // Opaque segments, merged per contiguous run of the same cause.
1118    /// A blocker in formation: its start, kind, decision, revision and detail.
1119    type Open = (usize, String, String, Option<TargetPair>, Option<String>);
1120    let mut open: Option<Open> = None;
1121    let close = |blockers: &mut Vec<Blocker>, open: &mut Option<Open>, end: usize| {
1122        if let Some((start, kind, decision, rev, detail)) = open.take() {
1123            blockers.push(Blocker {
1124                range: [start, end],
1125                kind,
1126                decision,
1127                revision: rev,
1128                detail,
1129            });
1130        }
1131    };
1132    for seg in &projection.segments {
1133        let el = piece_element(&seg.piece);
1134        // A symbol is never editable even at a direct position.
1135        if dom.name_is(el, &W::name("sym")) {
1136            close(&mut blockers, &mut open, char_pos(text, seg.start));
1137            blockers.push(Blocker {
1138                range: [char_pos(text, seg.start), char_pos(text, seg.end)],
1139                kind: "symbol".to_string(),
1140                decision: "unavailable".to_string(),
1141                revision: None,
1142                detail: Some("a symbol run; its font would draw the text".to_string()),
1143            });
1144            continue;
1145        }
1146        if seg.direct {
1147            close(&mut blockers, &mut open, char_pos(text, seg.start));
1148            continue;
1149        }
1150        let run = match &seg.piece {
1151            Piece::Text { run, .. } | Piece::Glyph { run, .. } => *run,
1152        };
1153        let (kind, decision, rev, detail) = classify(dom, run, paragraph, story, part);
1154        if let Some(el) = dom.ancestors(run, None).into_iter().find(|&a| {
1155            dom.name(a)
1156                .is_some_and(|n| n.namespace_name() == W::URI && n.local_name() == "ins")
1157        }) {
1158            revision(
1159                dom,
1160                el,
1161                "insertion",
1162                Some([char_pos(text, seg.start), char_pos(text, seg.end)]),
1163                &mut revisions,
1164                &mut seen,
1165            );
1166        }
1167        if let Some(el) = dom.ancestors(run, None).into_iter().find(|&a| {
1168            dom.name(a)
1169                .is_some_and(|n| n.namespace_name() == W::URI && n.local_name() == "moveTo")
1170        }) {
1171            revision(
1172                dom,
1173                el,
1174                "move",
1175                Some([char_pos(text, seg.start), char_pos(text, seg.end)]),
1176                &mut revisions,
1177                &mut seen,
1178            );
1179        }
1180        let start = char_pos(text, seg.start);
1181        let same = matches!(
1182          &open,
1183            Some((_, k, d, r, dt)) if *k == kind && *d == decision && *r == rev && *dt == detail
1184        );
1185        if !same {
1186            close(&mut blockers, &mut open, start);
1187            open = Some((start, kind, decision, rev, detail));
1188        }
1189    }
1190    close(&mut blockers, &mut open, text.chars().count());
1191
1192    // Zero-width blockers: complex-field markers and deleted content,
1193    // which project no text of their own.
1194    for &mark in &projection.field_marks {
1195        blockers.push(Blocker {
1196            range: [char_pos(text, mark), char_pos(text, mark)],
1197            kind: "field".to_string(),
1198            decision: "unavailable".to_string(),
1199            revision: None,
1200            detail: Some("a field marker; edits may not cross it".to_string()),
1201        });
1202    }
1203    for &el in dom.descendants(paragraph, None).iter() {
1204        let Some(name) = dom.name(el) else {
1205            continue;
1206        };
1207        if name.namespace_name() != W::URI {
1208            continue;
1209        }
1210        let local = name.local_name();
1211        // Mark revisions live in w:pPr/w:rPr and are listed separately.
1212        let in_ppr = dom
1213            .ancestors(el, None)
1214            .into_iter()
1215            .take_while(|&a| a != paragraph)
1216            .any(|a| dom.name_is(a, &W::p_pr()));
1217        if in_ppr {
1218            continue;
1219        }
1220        if !matches!(
1221            local,
1222            "del" | "moveFrom" | "moveFromRangeStart" | "moveFromRangeEnd"
1223        ) {
1224            continue;
1225        }
1226        let kind = if local == "del" {
1227            "tracked_deletion"
1228        } else {
1229            "move"
1230        };
1231        // The projected position right after everything this element
1232        // still leaves: the start of the first segment beyond its
1233        // subtree, or the end of the text.
1234        let order_of = order.get(&el).copied().unwrap_or(usize::MAX);
1235        let subtree = dom.descendants_and_self(el, None).len();
1236        let pos = projection
1237            .segments
1238            .iter()
1239            .filter(|seg| {
1240                order
1241                    .get(&piece_element(&seg.piece))
1242                    .is_some_and(|&o| o >= order_of + subtree)
1243            })
1244            .map(|seg| seg.start)
1245            .min()
1246            .unwrap_or(text.len());
1247        blockers.push(Blocker {
1248            range: [char_pos(text, pos), char_pos(text, pos)],
1249            kind: kind.to_string(),
1250            decision: "conditional".to_string(),
1251            revision: Some(revision_pair(dom, el, story, part)),
1252            detail: Some("a pending deletion; a decision removes it".to_string()),
1253        });
1254        revision(dom, el, "deletion", None, &mut revisions, &mut seen);
1255    }
1256
1257    // Paragraph-mark and formatting revisions: they carry no text span
1258    // but gate whole-paragraph operations.
1259    let mut mark_revisions: Vec<RevisionRef> = Vec::new();
1260    if let Some(rpr) = dom
1261        .element(paragraph, &W::p_pr())
1262        .and_then(|ppr| dom.element(ppr, &W::r_pr()))
1263    {
1264        for el in dom.elements(rpr, None) {
1265            let Some(name) = dom.name(el) else {
1266                continue;
1267            };
1268            if name.namespace_name() != W::URI {
1269                continue;
1270            }
1271            let kind = match name.local_name() {
1272                "ins" => "paragraph_mark",
1273                "del" | "moveFrom" | "moveTo" => "paragraph_mark",
1274                _ => continue,
1275            };
1276            let pair = revision_pair(dom, el, story, part);
1277            mark_revisions.push(RevisionRef {
1278                target: pair,
1279                kind: kind.to_string(),
1280                author: dom.attribute(el, &W::author()).map(str::to_string),
1281                range: None,
1282                basis: "working".to_string(),
1283            });
1284        }
1285    }
1286    // Recorded formatting changes stay visible as references, not blockers.
1287    for el in dom.descendants(paragraph, Some(&W::r_pr_change())) {
1288        let pair = revision_pair(dom, el, story, part);
1289        revisions.push(RevisionRef {
1290            target: pair,
1291            kind: "formatting".to_string(),
1292            author: dom.attribute(el, &W::author()).map(str::to_string),
1293            range: None,
1294            basis: "working".to_string(),
1295        });
1296    }
1297    (blockers, revisions, mark_revisions)
1298}
1299
1300/// The characters a row emits, for the text budget.
1301fn text_chars(row: &ForEditRow) -> usize {
1302    row.original.chars() + row.working.as_ref().map_or(0, |w| w.value.chars())
1303}
1304
1305/// Bound a row's text values to `budget` characters, working first.
1306fn bound_row(row: &mut ForEditRow, budget: usize) {
1307    if let Some(working) = &mut row.working
1308        && let Some(text) = working.value.text.take()
1309    {
1310        working.value = TextValue::bounded(&text, budget);
1311    }
1312    let remaining = budget.saturating_sub(row.working.as_ref().map_or(0, |w| w.value.chars()));
1313    if let Some(text) = row.original.text.take() {
1314        row.original = TextValue::bounded(&text, remaining);
1315    }
1316}
1317
1318/// What `make_row` needs of S, W and the frozen selection.
1319struct RowCtx<'a> {
1320    selection: &'a Selection,
1321    fates: &'a [Fate],
1322    s_opened: &'a Opened,
1323    s_loaded: &'a Loaded,
1324    w_opened: &'a Opened,
1325    w_stories: &'a [super::StoryPart],
1326    w_nodes: &'a [NodeId],
1327    w_story: &'a [(usize, usize)],
1328    native: &'a NativeKeys,
1329    comments: &'a HashMap<usize, Vec<CommentRef>>,
1330}
1331
1332/// Build one row of the result for original paragraph `g`.
1333fn make_row(g: usize, ctx: &RowCtx<'_>) -> ForEditRow {
1334    let selection = ctx.selection;
1335    let fates = ctx.fates;
1336    let s_opened = ctx.s_opened;
1337    let s_loaded = ctx.s_loaded;
1338    let w_opened = ctx.w_opened;
1339    let w_stories = ctx.w_stories;
1340    let w_nodes = ctx.w_nodes;
1341    let w_story = ctx.w_story;
1342    let native = ctx.native;
1343    let comments = ctx.comments;
1344    let (story, local) = s_loaded.paragraph_story[g];
1345    let story_id = s_loaded.stories[story].id.as_str();
1346    let part = s_loaded.stories[story].part.as_str();
1347    let short_id = crate::ids::paragraph_id(story_id, local);
1348    let s_node = s_loaded.paragraph_nodes[g];
1349    let original_text = project_paragraph(&s_opened.dom, s_node).text;
1350    let original_sha256 = v2::logical_text(&s_opened.dom, s_node)
1351        .ok()
1352        .map(|text| source_sha256(text.as_bytes()));
1353
1354    let (correspondence, w_at) = match fates[g] {
1355        Fate::Kept(post) => (Correspondence::OneToOne, Some(post)),
1356        Fate::Merged(post) => (Correspondence::Merged, Some(post)),
1357        Fate::Gone => (Correspondence::Removed, None),
1358    };
1359    let merged_into = match fates[g] {
1360        Fate::Merged(post) => {
1361            let (story, local) = w_story[post];
1362            Some(crate::ids::paragraph_id(
1363                w_stories[story].id.as_str(),
1364                local,
1365            ))
1366        }
1367        _ => None,
1368    };
1369
1370    let mut blockers = Vec::new();
1371    let mut revisions = Vec::new();
1372    let mut mark_revisions = Vec::new();
1373    let mut text_codec = "supported".to_string();
1374    let mut working = None;
1375    if let Some(post) = w_at {
1376        let w_node = w_nodes[post];
1377        let w_story_id = w_stories[w_story[post].0].id.as_str();
1378        let w_part = w_stories[w_story[post].0].part.as_str();
1379        let w_text = project_paragraph(&w_opened.dom, w_node).text;
1380        let codec = v2::logical_text(&w_opened.dom, w_node);
1381        let before_sha256 = codec.ok().map(|text| source_sha256(text.as_bytes()));
1382        if before_sha256.is_none() {
1383            text_codec = "unsupported".to_string();
1384        }
1385        working = Some(WorkingText {
1386            value: TextValue::complete(w_text),
1387            before_sha256,
1388        });
1389        if matches!(fates[g], Fate::Kept(_)) {
1390            let (b, r, m) = obstacles(&w_opened.dom, w_node, w_story_id, w_part);
1391            blockers = b;
1392            revisions = r;
1393            mark_revisions = m;
1394        }
1395    }
1396    if !matches!(fates[g], Fate::Kept(_)) {
1397        // The working paragraph is not this one: its marks are
1398        // original-S observations.
1399        let (_, r, m) = obstacles(&s_opened.dom, s_node, story_id, part);
1400        for mut reference in r.into_iter().chain(m) {
1401            reference.basis = "original".to_string();
1402            revisions.push(reference);
1403        }
1404    }
1405    let readiness = readiness(
1406        fates[g],
1407        before_sha256_present(&working),
1408        &blockers,
1409        &mark_revisions,
1410    );
1411    ForEditRow {
1412        target: native.pair(&s_opened.dom, story, part, &short_id, s_node),
1413        story: story_id.to_string(),
1414        matched_by: selection.matched_by.get(&g).cloned().unwrap_or_default(),
1415        original: TextValue::complete(original_text),
1416        original_sha256,
1417        working,
1418        correspondence,
1419        merged_into,
1420        text_codec,
1421        revisions,
1422        comments: comments.get(&g).cloned().unwrap_or_default(),
1423        blockers,
1424        readiness,
1425        unassessed_operations: vec![
1426            "format".to_string(),
1427            "fill".to_string(),
1428            "fields".to_string(),
1429            "merge".to_string(),
1430        ],
1431    }
1432}
1433
1434fn before_sha256_present(working: &Option<WorkingText>) -> bool {
1435    working.as_ref().is_some_and(|w| w.before_sha256.is_some())
1436}
1437
1438/// The readiness rows of one paragraph: range operations share the
1439/// blockers; whole-paragraph operations add the mark revisions.
1440fn readiness(
1441    fate: Fate,
1442    representable: bool,
1443    blockers: &[Blocker],
1444    mark_revisions: &[RevisionRef],
1445) -> Vec<Readiness> {
1446    let all: Vec<usize> = (0..blockers.len()).collect();
1447    let gone = matches!(fate, Fate::Gone);
1448    let merged = matches!(fate, Fate::Merged(_));
1449    let status = |conditional: bool| -> String {
1450        if gone {
1451            "unavailable".to_string()
1452        } else if conditional {
1453            "conditional".to_string()
1454        } else {
1455            "available".to_string()
1456        }
1457    };
1458    let reason = |text: &str| Some(text.to_string());
1459    let mut rows = Vec::new();
1460    // A range operation is gated by a blocker that covers text, or by a
1461    // structural point no edit may cross. A pending deletion's hidden
1462    // text is no working range: it blocks nothing and stays a `revisions`
1463    // entry.
1464    let gated = blockers
1465        .iter()
1466        .any(|b| b.range[0] < b.range[1] || b.decision == "unavailable");
1467    for operation in ["replace", "insert", "delete"] {
1468        rows.push(Readiness {
1469            operation: operation.to_string(),
1470            status: if gone || merged {
1471                "unavailable".to_string()
1472            } else {
1473                status(gated)
1474            },
1475            blockers: all.clone(),
1476            reason: (gone || merged).then(|| {
1477                if gone {
1478                    "the paragraph is gone once revisions settle".to_string()
1479                } else {
1480                    "the paragraph merged with its neighbours; name the settled paragraph"
1481                        .to_string()
1482                }
1483            }),
1484        });
1485    }
1486    rows.push(Readiness {
1487        operation: "rewrite".to_string(),
1488        status: if gone || merged || !representable {
1489            "unavailable".to_string()
1490        } else {
1491            status(!blockers.is_empty() || !mark_revisions.is_empty())
1492        },
1493        blockers: all.clone(),
1494        reason: if gone {
1495            reason("the paragraph is gone once revisions settle")
1496        } else if merged {
1497            reason("a rewrite needs exact one-to-one working correspondence")
1498        } else if !representable {
1499            reason("the exact text codec does not represent this paragraph")
1500        } else if !blockers.is_empty() || !mark_revisions.is_empty() {
1501            reason("desired text must not change the blocked ranges")
1502        } else {
1503            None
1504        },
1505    });
1506    rows.push(Readiness {
1507        operation: "insert_paragraph".to_string(),
1508        status: if gone || merged {
1509            "unavailable".to_string()
1510        } else {
1511            status(!blockers.is_empty() || !mark_revisions.is_empty())
1512        },
1513        blockers: all.clone(),
1514        reason: gone.then(|| "the paragraph is gone once revisions settle".to_string()),
1515    });
1516    rows.push(Readiness {
1517        operation: "delete_paragraph".to_string(),
1518        status: if gone || merged {
1519            "unavailable".to_string()
1520        } else {
1521            status(!blockers.is_empty() || !mark_revisions.is_empty())
1522        },
1523        blockers: all.clone(),
1524        reason: if gone {
1525            reason("the paragraph is gone once revisions settle")
1526        } else if merged {
1527            reason("the paragraph merged with its neighbours; name the settled paragraph")
1528        } else if !blockers.is_empty() || !mark_revisions.is_empty() {
1529            reason("the paragraph still holds revisions; a decision frees it")
1530        } else {
1531            None
1532        },
1533    });
1534    rows.push(Readiness {
1535        operation: "comment".to_string(),
1536        status: status(false),
1537        blockers: Vec::new(),
1538        reason: gone.then(|| "the paragraph is gone once revisions settle".to_string()),
1539    });
1540    rows
1541}
1542
1543/// The read-only context neighbours of selected paragraph `g`, charged
1544/// to `budget`.
1545fn context_of(
1546    g: usize,
1547    selection: &Selection,
1548    s_opened: &Opened,
1549    s_loaded: &Loaded,
1550    native: &NativeKeys,
1551    budget: &mut usize,
1552) -> Vec<SourceContextRow> {
1553    if selection.context == 0 {
1554        return Vec::new();
1555    }
1556    let (story, local) = s_loaded.paragraph_story[g];
1557    let from = local.saturating_sub(selection.context);
1558    let to = local.saturating_add(selection.context);
1559    let mut out = Vec::new();
1560    for l in from..=to {
1561        if l == local {
1562            continue;
1563        }
1564        let Some(neighbour) = s_loaded
1565            .paragraph_story
1566            .iter()
1567            .position(|&pair| pair == (story, l))
1568        else {
1569            continue;
1570        };
1571        // Context never repeats a selected row.
1572        if selection.selected.contains(&neighbour) {
1573            continue;
1574        }
1575        let node = s_loaded.paragraph_nodes[neighbour];
1576        let story_id = s_loaded.stories[story].id.as_str();
1577        let part = s_loaded.stories[story].part.as_str();
1578        let short_id = crate::ids::paragraph_id(story_id, l);
1579        let projection = project_paragraph(&s_opened.dom, node);
1580        let representable = v2::logical_text(&s_opened.dom, node).is_ok();
1581        let text_codec = if representable {
1582            "supported"
1583        } else {
1584            "unsupported"
1585        };
1586        let (_, mut revisions, mark_revisions) = obstacles(&s_opened.dom, node, story_id, part);
1587        revisions.extend(mark_revisions);
1588        for reference in &mut revisions {
1589            reference.basis = "original".to_string();
1590        }
1591        let value = TextValue::bounded(&projection.text, *budget);
1592        *budget = budget.saturating_sub(value.chars());
1593        out.push(SourceContextRow {
1594            kind: if representable { "paragraph" } else { "opaque" }.to_string(),
1595            target: native.pair(&s_opened.dom, story, part, &short_id, node),
1596            value,
1597            text_view: "final".to_string(),
1598            text_codec: text_codec.to_string(),
1599            limitations: projection.limitations.into_iter().collect(),
1600            revisions,
1601            reason_codes: if representable {
1602                vec!["context".to_string()]
1603            } else {
1604                vec!["context".to_string(), "unsupported_text_codec".to_string()]
1605            },
1606        });
1607    }
1608    out
1609}
1610
1611/// Read `source` for editing: selection frozen on S, text and readiness
1612/// derived from the working document `request` settles S to.
1613///
1614/// # Errors
1615///
1616/// [`EditError`] codes: `USAGE` for malformed flags, `EXISTING_REVISIONS`
1617/// when the policy cannot form a working basis (its blockers are the
1618/// document's remaining revisions), `UNKNOWN_CHANGE`/`AMBIGUOUS_CHANGE`/
1619/// `REVISION_CONFLICT` for bad decisions, `CURSOR_BASIS_CHANGED` when a
1620/// cursor's bound basis no longer matches.
1621pub fn for_edit(source: &[u8], request: &ForEditRequest) -> Result<ForEdit, EditError> {
1622    for_edit_quoting(source, request, super::PlanSyntax::V1)
1623}
1624
1625/// Build the working view with refusals in the caller's syntax.
1626#[doc(hidden)]
1627pub fn for_edit_quoting(
1628    source: &[u8],
1629    request: &ForEditRequest,
1630    syntax: super::PlanSyntax,
1631) -> Result<ForEdit, EditError> {
1632    if request.find.is_some() && request.regex.is_some() {
1633        return Err(super::err("USAGE", None, "--find and --regex conflict"));
1634    }
1635    if (request.by.is_some() || !request.by_any.is_empty()) && !request.changed {
1636        return Err(super::err("USAGE", None, "--by needs --changed"));
1637    }
1638    let source_digest = source_sha256(source);
1639    let probe = Opened::open(source).map_err(super::open_error)?;
1640    let plan = EditPlan {
1641        schema_version: crate::inspect::SCHEMA_VERSION,
1642        source_sha256: Some(source_digest.clone()),
1643        author: "jubarte read --for-edit".to_string(),
1644        date: None,
1645        initials: None,
1646        resolve_revisions: (!request.accept.is_empty() || !request.reject.is_empty()).then(|| {
1647            ResolveRevisions {
1648                accept: (!request.accept.is_empty())
1649                    .then(|| ChangeFilter::ids(request.accept.iter().cloned())),
1650                reject: (!request.reject.is_empty())
1651                    .then(|| ChangeFilter::ids(request.reject.iter().cloned())),
1652                reject_visible: false,
1653            }
1654        }),
1655        removed_anchor_comments: Default::default(),
1656        existing_revisions: request.existing_revisions,
1657        operations: Vec::new(),
1658        update_fields: false,
1659        rewrite_others_comments: false,
1660        others: super::Others::Allow,
1661    };
1662    let Settled {
1663        base,
1664        mut opened,
1665        resolved_revisions,
1666        changed,
1667        ..
1668    } = settle(source, &plan, probe, syntax)?;
1669    let Loaded {
1670        stories,
1671        paragraph_nodes,
1672        paragraph_story,
1673    } = load_stories(&mut opened)?;
1674
1675    // S, the original snapshot every ID and observation is bound to.
1676    let mut s_opened = Opened::open(source).map_err(super::open_error)?;
1677    let s_loaded = load_stories(&mut s_opened)?;
1678
1679    // Original-to-working correspondence.
1680    let fates: Vec<Fate> = if changed {
1681        let ids: Vec<String> = stories.iter().map(|s| s.id.clone()).collect();
1682        let origin = Origin::build(source, &plan, &ids, &paragraph_story)?;
1683        (0..s_loaded.paragraph_nodes.len())
1684            .map(|g| match origin.exact(g) {
1685                Ok(post) => Fate::Kept(post),
1686                Err(_) => match origin.fate(g) {
1687                    Fate::Kept(post) | Fate::Merged(post) => Fate::Merged(post),
1688                    Fate::Gone => Fate::Gone,
1689                },
1690            })
1691            .collect()
1692    } else {
1693        (0..s_loaded.paragraph_nodes.len())
1694            .map(Fate::Kept)
1695            .collect()
1696    };
1697
1698    // Long IDs need the per-story native-key inventory of S.
1699    let native = NativeKeys::collect(&s_opened.dom, &s_loaded.stories);
1700
1701    // The frozen selection, resolved on S before anything settles.
1702    let selection = Selection::build(request, &s_opened, &s_loaded, source)?;
1703    let basis_digest = basis_digest(&source_digest, request, &selection);
1704    let offset = match &request.cursor {
1705        Some(token) => cursor_offset(token, &basis_digest)?,
1706        None => 0,
1707    };
1708    if offset > selection.selected.len() {
1709        return Err(super::err(
1710            "CURSOR_BASIS_CHANGED",
1711            None,
1712            "the cursor continues past the frozen selection; start a new query",
1713        ));
1714    }
1715
1716    // Comments of S, for references and the --changed/--by selection.
1717    let comment_list = crate::comments::list_comments(source)
1718        .map_err(|e| super::err(e.code(), None, e.to_string()))?;
1719    let (comments, unanchored_comments) = comments_by_paragraph(&comment_list, &s_loaded);
1720
1721    // Pagination over the frozen selection.
1722    let limit = if request.all {
1723        usize::MAX
1724    } else {
1725        request.limit.unwrap_or(100)
1726    };
1727    let max_chars = if request.all {
1728        usize::MAX
1729    } else {
1730        request.max_chars.unwrap_or(24_000)
1731    };
1732    let mut rows: Vec<ForEditRow> = Vec::new();
1733    let mut context_rows = Vec::new();
1734    let mut omissions = Vec::new();
1735    let mut budget = max_chars;
1736    let mut next = selection.selected.len();
1737    let mut truncated = false;
1738    for (i, &g) in selection.selected.iter().enumerate().skip(offset) {
1739        if rows.len() >= limit {
1740            next = i;
1741            truncated = true;
1742            break;
1743        }
1744        let mut row = make_row(
1745            g,
1746            &RowCtx {
1747                selection: &selection,
1748                fates: &fates,
1749                s_opened: &s_opened,
1750                s_loaded: &s_loaded,
1751                w_opened: &opened,
1752                w_stories: &stories,
1753                w_nodes: &paragraph_nodes,
1754                w_story: &paragraph_story,
1755                native: &native,
1756                comments: &comments,
1757            },
1758        );
1759        bound_row(&mut row, budget);
1760        let used = text_chars(&row);
1761        let complete =
1762            row.original.complete && row.working.as_ref().is_none_or(|w| w.value.complete);
1763        budget = budget.saturating_sub(used);
1764        for ctx in context_of(g, &selection, &s_opened, &s_loaded, &native, &mut budget) {
1765            context_rows.push(ctx);
1766        }
1767        let id = row.target.short_id.clone();
1768        rows.push(row);
1769        if !complete {
1770            truncated = true;
1771            next = i + 1;
1772            if next < selection.selected.len() {
1773                omissions.push(format!(
1774                    "text budget exhausted inside {id}; its previews are not complete text"
1775                ));
1776            }
1777            break;
1778        }
1779    }
1780    if selection.selected.is_empty() {
1781        let filters: Vec<&str> = [
1782            request.select.is_some().then_some("ids"),
1783            request.head.is_some().then_some("ids"),
1784            request.tail.is_some().then_some("ids"),
1785            request.find.is_some().then_some("find"),
1786            request.regex.is_some().then_some("regex"),
1787            request.changed.then_some("changed"),
1788            request.by.is_some().then_some("by"),
1789        ]
1790        .into_iter()
1791        .flatten()
1792        .collect();
1793        if !filters.is_empty() {
1794            // Filters narrow to a conjunction: an empty result names
1795            // them so a miss is not mistaken for a refusal.
1796            omissions.push(format!(
1797                "no paragraphs match every filter given: {}",
1798                filters.join(", ")
1799            ));
1800        }
1801    }
1802    let next_cursor = (next < selection.selected.len()).then(|| cursor_token(&basis_digest, next));
1803    if next_cursor.is_some() {
1804        truncated = true;
1805        omissions.push(format!(
1806            "{} of {} selected paragraphs returned; continue with --cursor",
1807            rows.len(),
1808            selection.selected.len()
1809        ));
1810    }
1811
1812    let mut accept = request.accept.clone();
1813    let mut reject = request.reject.clone();
1814    accept.sort();
1815    accept.dedup();
1816    reject.sort();
1817    reject.dedup();
1818    Ok(ForEdit {
1819        schema: "jubarte-read-for-edit-v1".to_string(),
1820        source_sha256: source_digest,
1821        basis: ForEditBasis {
1822            text_view: "final".to_string(),
1823            text_codec_version: v2::TEXT_CODEC_VERSION,
1824            track: if request.track {
1825                "on".to_string()
1826            } else {
1827                "off".to_string()
1828            },
1829            existing_revisions: existing_revisions_name(request.existing_revisions).to_string(),
1830            accept,
1831            reject,
1832            working_sha256: source_sha256(&base),
1833            digest: basis_digest,
1834        },
1835        settled: ForEditSettled {
1836            changed,
1837            accepted: resolved_revisions.accepted,
1838            rejected: resolved_revisions.rejected,
1839        },
1840        coverage: ForEditCoverage {
1841            selection_complete: next_cursor.is_none(),
1842            paragraphs_selected: selection.selected.len(),
1843            paragraphs_returned: rows.len(),
1844            context_paragraphs: context_rows.len(),
1845            truncated,
1846            omissions,
1847        },
1848        paragraphs: rows,
1849        unanchored_comments,
1850        source_context: context_rows,
1851        comments: comment_list,
1852        next_cursor,
1853        input_validity: None,
1854    })
1855}
1856
1857/// [`for_edit`]'s result as `read --for-edit` prints it: the document
1858/// carries `validity` (the input's findings, `None` when the caller read
1859/// none — #1340), serialized to the one JSON line the binary writes to
1860/// stdout or a `.json` file. The native binary, the Python module and the
1861/// WASM binding all print this string.
1862///
1863/// # Errors
1864///
1865/// [`for_edit`]'s.
1866pub fn for_edit_json(
1867    source: &[u8],
1868    request: &ForEditRequest,
1869    validity: Option<crate::validate::InputValidity>,
1870) -> Result<String, EditError> {
1871    let mut result = for_edit(source, request)?;
1872    result.input_validity = validity;
1873    let json = serde_json::to_string(&result).expect("ForEdit serializes");
1874    Ok(format!("{json}\n"))
1875}
1876
1877#[cfg(test)]
1878mod tests {
1879    use super::*;
1880
1881    #[test]
1882    fn cursor_binds_frozen_membership_independently_of_request_filters() {
1883        let request = ForEditRequest::default();
1884        let mut selection = Selection {
1885            selected: vec![0, 1],
1886            matched_by: HashMap::new(),
1887            context: 0,
1888        };
1889        let source = source_sha256(b"source");
1890        let basis = basis_digest(&source, &request, &selection);
1891        let cursor = cursor_token(&basis, 1);
1892        assert_eq!(cursor_offset(&cursor, &basis).unwrap(), 1);
1893        selection.selected = vec![1, 2];
1894        let changed = basis_digest(&source, &request, &selection);
1895        let error = cursor_offset(&cursor, &changed).unwrap_err();
1896        assert_eq!(error.code, "CURSOR_BASIS_CHANGED");
1897    }
1898
1899    #[test]
1900    fn cursor_binds_source_digest_independently_of_selection() {
1901        let request = ForEditRequest::default();
1902        let selection = Selection {
1903            selected: vec![0, 1],
1904            matched_by: HashMap::new(),
1905            context: 0,
1906        };
1907        let source = source_sha256(b"source");
1908        let basis = basis_digest(&source, &request, &selection);
1909        let cursor = cursor_token(&basis, 1);
1910        assert_eq!(cursor_offset(&cursor, &basis).unwrap(), 1);
1911        let changed = basis_digest(&source_sha256(b"other"), &request, &selection);
1912        let error = cursor_offset(&cursor, &changed).unwrap_err();
1913        assert_eq!(error.code, "CURSOR_BASIS_CHANGED");
1914    }
1915}
1916
1917#[cfg(test)]
1918#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1919mod request_branch_tests {
1920    use super::super::deeper_boundary_fixture::{docx, para};
1921    use super::*;
1922
1923    fn source() -> Vec<u8> {
1924        docx(&format!(
1925            "{}{}{}",
1926            para("Alpha one."),
1927            para("Beta two."),
1928            para("Gamma three.")
1929        ))
1930    }
1931
1932    fn token(json: &serde_json::Value) -> String {
1933        use base64::Engine;
1934        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json.to_string())
1935    }
1936
1937    #[test]
1938    fn previews_cut_only_between_words() {
1939        let at_space = TextValue::bounded("ab cd", 3);
1940        assert_eq!(at_space.text_preview.as_deref(), Some("ab "));
1941        let before_space = TextValue::bounded("ab cd", 2);
1942        assert_eq!(before_space.text_preview.as_deref(), Some("ab"));
1943        let mid_word = TextValue::bounded("abcd ef", 2);
1944        assert_eq!(mid_word.text_preview.as_deref(), Some("abcd"));
1945        assert!(TextValue::bounded("abcd", 2).complete);
1946    }
1947
1948    #[test]
1949    fn requests_refuse_conflicting_or_incomplete_filters() {
1950        let source = source();
1951        let both = ForEditRequest {
1952            find: Some("a".into()),
1953            regex: Some("b".into()),
1954            ..ForEditRequest::default()
1955        };
1956        assert_eq!(
1957            for_edit(&source, &both).unwrap_err().message,
1958            "--find and --regex conflict"
1959        );
1960        let by = ForEditRequest {
1961            by: Some("Bo".into()),
1962            ..ForEditRequest::default()
1963        };
1964        assert_eq!(
1965            for_edit(&source, &by).unwrap_err().message,
1966            "--by needs --changed"
1967        );
1968        let by_any = ForEditRequest {
1969            by_any: vec!["Bo".into()],
1970            ..ForEditRequest::default()
1971        };
1972        assert_eq!(
1973            for_edit(&source, &by_any).unwrap_err().message,
1974            "--by needs --changed"
1975        );
1976    }
1977
1978    #[test]
1979    fn cursors_must_be_ours_and_inside_the_selection() {
1980        let source = source();
1981        let page = ForEditRequest {
1982            limit: Some(1),
1983            ..ForEditRequest::default()
1984        };
1985        let first = for_edit(&source, &page).unwrap();
1986        assert_eq!(first.paragraphs.len(), 1);
1987        let next = first.next_cursor.clone().expect("more to read");
1988        let second = for_edit(
1989            &source,
1990            &ForEditRequest {
1991                cursor: Some(next.clone()),
1992                ..page.clone()
1993            },
1994        )
1995        .unwrap();
1996        assert_eq!(second.paragraphs.len(), 1);
1997        assert_ne!(second.paragraphs[0].target, first.paragraphs[0].target);
1998        let basis = {
1999            use base64::Engine;
2000            let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
2001                .decode(&next)
2002                .unwrap();
2003            let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2004            v["basis"].as_str().unwrap().to_string()
2005        };
2006        for bad in [
2007            serde_json::json!({"v": 2, "basis": basis, "offset": 1}),
2008            serde_json::json!({"v": 1, "basis": basis, "offset": "1"}),
2009            serde_json::json!({"v": 1, "basis": 7, "offset": 1}),
2010        ] {
2011            let e = for_edit(
2012                &source,
2013                &ForEditRequest {
2014                    cursor: Some(token(&bad)),
2015                    ..page.clone()
2016                },
2017            )
2018            .unwrap_err();
2019            assert_eq!(e.code, "USAGE", "{bad}");
2020        }
2021        let past = for_edit(
2022            &source,
2023            &ForEditRequest {
2024                cursor: Some(cursor_token(&basis, 99)),
2025                ..page.clone()
2026            },
2027        )
2028        .unwrap_err();
2029        assert_eq!(past.code, "CURSOR_BASIS_CHANGED");
2030        assert!(
2031            past.message.contains("past the frozen selection"),
2032            "{}",
2033            past.message
2034        );
2035    }
2036
2037    #[test]
2038    fn head_and_tail_pick_body_paragraphs() {
2039        let source = source();
2040        let ids = |request: ForEditRequest| -> Vec<String> {
2041            for_edit(&source, &request)
2042                .unwrap()
2043                .paragraphs
2044                .into_iter()
2045                .map(|r| r.original.text.unwrap_or_default())
2046                .collect()
2047        };
2048        let head = ids(ForEditRequest {
2049            head: Some(1),
2050            ..ForEditRequest::default()
2051        });
2052        assert_eq!(head, ["Alpha one."]);
2053        let tail = ids(ForEditRequest {
2054            tail: Some(2),
2055            ..ForEditRequest::default()
2056        });
2057        assert_eq!(tail, ["Beta two.", "Gamma three."]);
2058        let none = for_edit(
2059            &source,
2060            &ForEditRequest {
2061                find: Some("zzz".into()),
2062                ..ForEditRequest::default()
2063            },
2064        )
2065        .unwrap();
2066        assert!(none.paragraphs.is_empty());
2067        assert!(
2068            none.coverage
2069                .omissions
2070                .iter()
2071                .any(|o| o.contains("every filter given: find")),
2072            "{:?}",
2073            none.coverage.omissions
2074        );
2075    }
2076}
2077
2078#[cfg(test)]
2079#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2080mod reference_branch_tests {
2081    use super::*;
2082
2083    #[test]
2084    fn values_escape_every_byte_outside_the_literal_set() {
2085        assert_eq!(escape_value("a.b_c:9"), "a.b_c:9");
2086        assert_eq!(escape_value("a b/é"), "a-20b-2F-C3-A9");
2087    }
2088
2089    #[test]
2090    fn a_resolved_comment_reads_done() {
2091        let mut record = crate::comments::CommentRecord {
2092            id: 4,
2093            r#ref: "c4".into(),
2094            author: "Bo".into(),
2095            initials: None,
2096            date: None,
2097            text: "Note".into(),
2098            parent: None,
2099            done: true,
2100            paragraph: None,
2101            last_paragraph: None,
2102            anchor_text: String::new(),
2103            before: String::new(),
2104            after: String::new(),
2105        };
2106        let done = comment_ref(&record);
2107        assert_eq!(done.short_id, "c4");
2108        assert_eq!(done.status, "done");
2109        record.done = false;
2110        assert_eq!(comment_ref(&record).status, "open");
2111    }
2112}