1use super::origin::{Paragraphs, SOURCE_ONLY, written_places};
15use super::prepared::{Blame, PrepareOptions, PreparedEdit, prepare, prepare_blaming};
16use super::{
17 ControlSelector, EditError, EditOutcome, EditPlan, ExistingRevisions, Operation, OperationKind,
18 Selector, kind_name,
19};
20use std::collections::BTreeSet;
21
22const GROUP_FAILED: &str = "GROUP_FAILED";
25
26#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct SkippedOperation {
29 pub index: usize,
31 pub operation: Operation,
33 pub code: String,
36 pub message: String,
38}
39
40pub(super) fn prepare_skipping(
44 source: &[u8],
45 plan: &EditPlan,
46 options: &PrepareOptions,
47) -> Result<PreparedEdit, EditError> {
48 let mine = plan.operations.len();
53 let mut named =
54 super::visible::lower(source, plan, options.syntax)?.unwrap_or_else(|| plan.clone());
55 for (i, op) in named.operations.iter_mut().enumerate() {
56 op.id.get_or_insert_with(|| format!("op-{}", i + 1));
57 }
58 let once = PrepareOptions {
59 skip_failed: false,
60 ..*options
61 };
62 let mut live: Vec<usize> = (0..mine).collect();
63 let mut skipped: Vec<(SkippedOperation, EditOutcome)> = Vec::new();
64 loop {
65 let attempt = EditPlan {
66 operations: live
67 .iter()
68 .copied()
69 .chain(mine..named.operations.len())
70 .map(|i| named.operations[i].clone())
71 .collect(),
72 ..named.clone()
73 };
74 let blame = match prepare_blaming(source, &attempt, live.len(), &once) {
78 Ok(prepared) => return Ok(merged(prepared, skipped)),
79 Err(blame) => *blame,
80 };
81 let (mut e, failed, reasons) = match blame {
82 Blame::Plain(e) => {
83 let Some(failed) = blamed(&e, &named, &live, mine) else {
84 return Err(e);
85 };
86 (e, failed, Vec::new())
87 }
88 Blame::Candidate(e, blamed) => {
89 if blamed.is_empty() {
90 return Err(e);
91 }
92 let reasons: Vec<(usize, EditError)> =
93 blamed.into_iter().map(|(i, why)| (live[i], why)).collect();
94 (e, reasons.iter().map(|(i, _)| *i).collect(), reasons)
95 }
96 };
97 let groups: BTreeSet<&str> = failed
98 .iter()
99 .filter_map(|&i| named.operations[i].group.as_deref())
100 .collect();
101 let mates: Vec<usize> = live
102 .iter()
103 .copied()
104 .filter(|i| !failed.contains(i))
105 .filter(|&i| {
106 named.operations[i]
107 .group
108 .as_deref()
109 .is_some_and(|g| groups.contains(g))
110 })
111 .collect();
112 for &i in &failed {
113 let id = op_id(&named, i);
114 let outcome = outcome_of(&e, &named, i);
115 let (code, message) = match reasons.iter().find(|(r, _)| *r == i) {
116 Some((_, why)) => (why.code.clone(), why.message.clone()),
117 None => (
118 outcome.code.clone().unwrap_or_else(|| e.code.clone()),
119 outcome.message.clone().unwrap_or_else(|| e.message.clone()),
120 ),
121 };
122 skipped.push((
123 SkippedOperation {
124 index: i,
125 operation: named.operations[i].clone(),
126 code: code.clone(),
127 message: message.clone(),
128 },
129 EditOutcome {
130 id,
131 status: "skipped".into(),
132 code: Some(code),
133 message: Some(message),
134 context: None,
135 comment_id: None,
136 ..outcome
137 },
138 ));
139 }
140 for &i in &mates {
141 let group = named.operations[i].group.clone().unwrap_or_default();
142 let first = failed
143 .iter()
144 .find(|&&f| named.operations[f].group.as_deref() == Some(group.as_str()))
145 .map(|&f| op_id(&named, f))
146 .unwrap_or_default();
147 let message = format!("skipped with group {group:?}: {first} failed");
148 skipped.push((
149 SkippedOperation {
150 index: i,
151 operation: named.operations[i].clone(),
152 code: GROUP_FAILED.into(),
153 message: message.clone(),
154 },
155 EditOutcome {
156 id: op_id(&named, i),
157 status: "skipped".into(),
158 code: Some(GROUP_FAILED.into()),
159 message: Some(message),
160 context: None,
161 comment_id: None,
162 ..outcome_of(&e, &named, i)
163 },
164 ));
165 }
166 live.retain(|i| !failed.contains(i) && !mates.contains(i));
167 if live.is_empty() {
168 skipped.sort_by_key(|(s, _)| s.index);
169 if let Some((first, _)) = skipped.iter().find(|(s, _)| s.code != GROUP_FAILED) {
172 e.code.clone_from(&first.code);
173 e.message.clone_from(&first.message);
174 e.operation = first.operation.id.clone();
175 }
176 e.outcomes = skipped
177 .into_iter()
178 .map(|(s, outcome)| EditOutcome {
179 status: if s.code == GROUP_FAILED {
180 "skipped".into()
181 } else {
182 "failed".into()
183 },
184 ..outcome
185 })
186 .collect();
187 return Err(e);
188 }
189 }
190}
191
192fn op_id(plan: &EditPlan, i: usize) -> String {
194 plan.operations[i]
195 .id
196 .clone()
197 .unwrap_or_else(|| format!("op-{}", i + 1))
198}
199
200fn blamed(e: &EditError, plan: &EditPlan, live: &[usize], mine: usize) -> Option<Vec<usize>> {
207 if e.code == "STALE_SOURCE" {
208 return None;
209 }
210 let added = |id: &str| {
211 plan.operations[mine..]
212 .iter()
213 .any(|op| op.id.as_deref() == Some(id))
214 };
215 let mut ids: Vec<&str> = e
216 .outcomes
217 .iter()
218 .filter(|o| o.status == "failed")
219 .map(|o| o.id.as_str())
220 .collect();
221 if ids.is_empty() {
222 ids.push(e.operation.as_deref()?);
223 }
224 let mut failed = Vec::new();
225 for id in ids {
226 if added(id) {
227 return None;
228 }
229 let mut holders = live
230 .iter()
231 .copied()
232 .filter(|&i| plan.operations[i].id.as_deref() == Some(id));
233 let (Some(i), None) = (holders.next(), holders.next()) else {
234 return None;
235 };
236 if !failed.contains(&i) {
237 failed.push(i);
238 }
239 }
240 Some(failed)
241}
242
243fn outcome_of(e: &EditError, plan: &EditPlan, i: usize) -> EditOutcome {
245 let id = op_id(plan, i);
246 e.outcomes
247 .iter()
248 .find(|o| o.id == id)
249 .cloned()
250 .unwrap_or_else(|| EditOutcome {
251 id,
252 kind: kind_name(&plan.operations[i].kind).to_string(),
253 status: String::new(),
254 paragraph: None,
255 matches: 0,
256 context: None,
257 comment_id: None,
258 anchor_given: None,
259 anchor_read_as: None,
260 near: None,
261 candidates: Vec::new(),
262 code: None,
263 message: None,
264 })
265}
266
267fn merged(
269 mut prepared: PreparedEdit,
270 mut skipped: Vec<(SkippedOperation, EditOutcome)>,
271) -> PreparedEdit {
272 skipped.sort_by_key(|(s, _)| s.index);
273 let report = &mut prepared.result.report;
274 let mut landed = std::mem::take(&mut report.operations).into_iter();
275 let total = landed.len() + skipped.len();
276 let mut skips = skipped.iter().peekable();
277 for i in 0..total {
278 match skips.peek() {
279 Some((s, outcome)) if s.index == i => {
280 report.operations.push(outcome.clone());
281 skips.next();
282 }
283 _ => report.operations.extend(landed.next()),
284 }
285 }
286 report.skipped = skipped.len();
287 report.ok &= skipped.is_empty();
288 prepared.skipped = skipped.into_iter().map(|(s, _)| s).collect();
289 prepared
290}
291
292pub fn failed_plan_json(
301 source: &[u8],
302 plan: &EditPlan,
303 skipped: &[SkippedOperation],
304 date: &str,
305 output_sha256: &str,
306 existing_revisions: ExistingRevisions,
307 redline: bool,
308) -> String {
309 let mut operations: Vec<Operation> = skipped.iter().map(|s| s.operation.clone()).collect();
310 let notes = rename_positions(source, plan, skipped, redline, &mut operations);
311 let failed = EditPlan {
312 source_sha256: Some(output_sha256.to_string()),
313 date: Some(date.to_string()),
314 resolve_revisions: None,
315 existing_revisions,
316 update_fields: plan.update_fields && existing_revisions != ExistingRevisions::Keep,
318 operations,
319 ..plan.clone()
320 };
321 let mut value = serde_json::to_value(&failed).expect("plan serializes");
322 if let Some(ops) = value["operations"].as_array_mut() {
323 for ((op, s), notes) in ops.iter_mut().zip(skipped).zip(¬es) {
324 let keep = keep_note(kind_name(&s.operation.kind), existing_revisions);
325 let mut why = format!("{}: {}", s.code, s.message);
326 for note in notes.iter().chain(keep.as_ref()) {
327 why.push_str("; ");
328 why.push_str(note);
329 }
330 op["why"] = why.into();
331 }
332 }
333 let mut json = serde_json::to_string_pretty(&value).expect("plan serializes");
334 json.push('\n');
335 json
336}
337
338pub fn keep_notes(
342 skipped: &[SkippedOperation],
343 existing_revisions: ExistingRevisions,
344) -> Vec<String> {
345 let mut notes = Vec::new();
346 for s in skipped {
347 if let Some(note) = keep_note(kind_name(&s.operation.kind), existing_revisions)
348 && !notes.contains(¬e)
349 {
350 notes.push(note);
351 }
352 }
353 notes
354}
355
356fn keep_note(kind: &str, existing_revisions: ExistingRevisions) -> Option<String> {
357 (existing_revisions == ExistingRevisions::Keep && !super::operation_supports_keep(kind)).then(
358 || {
359 format!(
360 "{kind} cannot run under existing_revisions keep: fix it in the original plan and run that on the source"
361 )
362 },
363 )
364}
365
366enum Named {
368 Paragraph(usize),
370 Control(String),
372}
373
374fn source_only(operation: &mut Operation, what: &Named, shown: &str) {
378 let id = format!("{SOURCE_ONLY}{shown}");
379 match what {
380 Named::Paragraph(n) => {
381 let selector = &mut *super::selectors_mut(&mut operation.kind).swap_remove(*n);
382 *selector = match selector {
383 Selector::Id { .. } => Selector::Id { id },
384 _ => Selector::Name(id),
385 };
386 }
387 Named::Control(_) => {
388 if let OperationKind::FillControl { control, .. } = &mut operation.kind {
389 *control = match control {
390 ControlSelector::Id { .. } => ControlSelector::Id { id },
391 _ => ControlSelector::Name(id),
392 };
393 }
394 }
395 }
396}
397
398fn control_paragraph(control: &ControlSelector) -> Option<(&str, &str)> {
401 let (ControlSelector::Name(id) | ControlSelector::Id { id }) = control else {
402 return None;
403 };
404 let (paragraph, k) = id.rsplit_once(".cc")?;
405 (!paragraph.is_empty() && k.parse::<usize>().is_ok()).then_some((paragraph, k))
406}
407
408fn keeps_its_paragraphs(kind: &OperationKind) -> bool {
415 matches!(
416 kind,
417 OperationKind::Replace { .. }
418 | OperationKind::Insert { .. }
419 | OperationKind::Delete { .. }
420 | OperationKind::Comment { .. }
421 | OperationKind::FormatParagraph { .. }
422 | OperationKind::Rewrite { .. }
423 | OperationKind::ReplyComment { .. }
424 | OperationKind::ResolveComment { .. }
425 | OperationKind::EditComment { .. }
426 | OperationKind::DeleteComment { .. }
427 | OperationKind::List { .. }
428 | OperationKind::FormatRun { .. }
429 | OperationKind::PageSetup { .. }
430 | OperationKind::Redact { .. }
431 | OperationKind::Settings { .. }
432 )
433}
434
435fn places_stay(plan: &EditPlan, left_out: &BTreeSet<usize>) -> bool {
440 plan.resolve_revisions.is_none()
441 && !plan.update_fields
442 && matches!(
443 plan.existing_revisions,
444 ExistingRevisions::Refuse | ExistingRevisions::Keep
445 )
446 && plan
447 .operations
448 .iter()
449 .enumerate()
450 .filter(|(i, _)| !left_out.contains(i))
451 .all(|(_, op)| keeps_its_paragraphs(&op.kind))
452}
453
454fn rename_positions(
462 source: &[u8],
463 plan: &EditPlan,
464 skipped: &[SkippedOperation],
465 redline: bool,
466 operations: &mut [Operation],
467) -> Vec<Vec<String>> {
468 let mut notes = vec![Vec::new(); operations.len()];
469 let Ok(read) = Paragraphs::open(source) else {
470 return notes;
471 };
472 let ids = read.ids();
473 let mut named = Vec::new();
476 for (o, op) in operations.iter_mut().enumerate() {
477 if let OperationKind::FillControl { control, .. } = &op.kind
478 && let Some((paragraph, k)) = control_paragraph(control)
479 && let Ok(Ok(g)) = ids.position(&Selector::Name(paragraph.to_string()))
480 {
481 named.push((o, Named::Control(k.to_string()), g, paragraph.to_string()));
482 }
483 for (n, selector) in super::selectors_mut(&mut op.kind).into_iter().enumerate() {
484 if let Ok(Ok(g)) = ids.position(selector) {
485 let spelled = match selector {
486 Selector::Name(id) | Selector::Id { id } => id.clone(),
487 _ => ids.id(g),
488 };
489 named.push((o, Named::Paragraph(n), g, spelled));
490 }
491 }
492 }
493 if named.is_empty() {
494 return notes;
495 }
496 let left_out: BTreeSet<usize> = skipped.iter().map(|s| s.index).collect();
497 if places_stay(plan, &left_out) {
501 return notes;
502 }
503 let survivors = EditPlan {
504 source_sha256: None,
505 operations: plan
506 .operations
507 .iter()
508 .enumerate()
509 .filter(|(i, _)| !left_out.contains(i))
510 .map(|(_, op)| op.clone())
511 .collect(),
512 ..plan.clone()
513 };
514 let landed = written_places(source, |tagged| {
515 let prepared = prepare(tagged, &survivors, &PrepareOptions::default())?;
516 Ok(if redline {
517 prepared.result.redline
518 } else {
519 prepared.result.clean
520 })
521 });
522 for (o, what, g, spelled) in named {
523 let shown = match &what {
524 Named::Paragraph(_) => spelled,
525 Named::Control(k) => format!("{spelled}.cc{k}"),
526 };
527 let Ok((places, written)) = &landed else {
528 source_only(&mut operations[o], &what, &shown);
529 notes[o].push(format!(
530 "{shown} names a paragraph of the source: give it again from the output"
531 ));
532 continue;
533 };
534 let Some(post) = places[g].filter(|&post| written.place(post).0 == read.place(g).0) else {
535 source_only(&mut operations[o], &what, &shown);
536 notes[o].push(format!(
537 "{shown} has no one-to-one paragraph in the output: give it again from the output"
538 ));
539 continue;
540 };
541 if matches!(what, Named::Control(_)) && written.control_count(post) != read.control_count(g)
544 {
545 source_only(&mut operations[o], &what, &shown);
546 notes[o].push(format!(
547 "{shown} has no one-to-one control in the output: give it again from the output"
548 ));
549 continue;
550 }
551 let to = written.ids().id(post);
552 if to == ids.id(g) {
553 continue;
554 }
555 let renamed = match what {
556 Named::Paragraph(n) => {
557 let selector = &mut *super::selectors_mut(&mut operations[o].kind).swap_remove(n);
558 *selector = match selector {
559 Selector::Index { story, .. } => Selector::Index {
560 index: written.place(post).1,
561 story: story.clone(),
562 },
563 Selector::Id { .. } => Selector::Id { id: to.clone() },
564 _ => Selector::Name(to.clone()),
565 };
566 to
567 }
568 Named::Control(k) => {
569 let OperationKind::FillControl { control, .. } = &mut operations[o].kind else {
570 continue;
571 };
572 let id = format!("{to}.cc{k}");
573 *control = match control {
574 ControlSelector::Id { .. } => ControlSelector::Id { id: id.clone() },
575 _ => ControlSelector::Name(id.clone()),
576 };
577 id
578 }
579 };
580 notes[o].push(format!("{shown} is {renamed} in the output"));
581 }
582 notes
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 fn plan(ops: &str) -> EditPlan {
590 EditPlan::from_json(&format!(
591 r#"{{"schema_version":1,"author":"Ann","existing_revisions":"keep","operations":{ops}}}"#
592 ))
593 .unwrap()
594 }
595
596 #[test]
599 fn only_survivors_that_keep_every_paragraph_skip_the_second_run() {
600 let replace = r#"{"kind":"replace","paragraph":"p0","find":"a","replacement":"b"}"#;
601 let none = BTreeSet::new();
602 assert!(places_stay(&plan(&format!("[{replace}]")), &none));
603 for mover in [
604 r#"{"kind":"strike","revision":"r1"}"#,
605 r#"{"kind":"restore","revision":"r1"}"#,
606 r#"{"kind":"insert_paragraph","paragraph":"p0","position":"after","runs":[{"text":"x"}]}"#,
607 r#"{"kind":"delete_paragraph","paragraph":"p0"}"#,
608 ] {
609 assert!(
610 !places_stay(&plan(&format!("[{replace},{mover}]")), &none),
611 "{mover}"
612 );
613 assert!(
615 places_stay(&plan(&format!("[{replace},{mover}]")), &BTreeSet::from([1])),
616 "{mover}"
617 );
618 }
619 }
620}
621
622#[cfg(test)]
623#[cfg_attr(all(coverage_nightly, test), coverage(off))]
624mod note_branch_tests {
625 use super::*;
626
627 fn plan(extra: serde_json::Value, ops: serde_json::Value) -> EditPlan {
628 let mut value = serde_json::json!({
629 "schema_version": 1,
630 "author": "Ed",
631 "date": "2026-02-02T00:00:00Z",
632 });
633 let serde_json::Value::Object(extra) = extra else {
634 panic!("plan fields are an object");
635 };
636 for (k, v) in extra {
637 value[k.as_str()] = v;
638 }
639 value["operations"] = ops;
640 EditPlan::from_json(&value.to_string()).unwrap()
641 }
642
643 #[test]
644 fn keep_notes_name_each_refused_kind_once() {
645 let fills = plan(
646 serde_json::json!({}),
647 serde_json::json!([
648 {"kind": "fill_control", "control": "p0.cc0", "text": "a"},
649 {"kind": "fill_control", "control": "p1.cc0", "text": "b"},
650 {"kind": "replace", "paragraph": "p0", "find": "x", "replacement": "y"},
651 ]),
652 );
653 let skipped: Vec<SkippedOperation> = fills
654 .operations
655 .iter()
656 .enumerate()
657 .map(|(index, operation)| SkippedOperation {
658 index,
659 operation: operation.clone(),
660 code: "ANCHOR_NOT_FOUND".into(),
661 message: "missing".into(),
662 })
663 .collect();
664 let notes = keep_notes(&skipped, ExistingRevisions::Keep);
665 assert_eq!(notes.len(), 1, "{notes:?}");
666 assert!(notes[0].starts_with("fill_control cannot run under existing_revisions keep"));
667 assert!(keep_notes(&skipped, ExistingRevisions::Refuse).is_empty());
668 }
669
670 #[test]
671 fn control_names_split_into_paragraph_and_index() {
672 let name = |s: &str| ControlSelector::Name(s.into());
673 assert_eq!(control_paragraph(&name("p3.cc0")), Some(("p3", "0")));
674 assert_eq!(
675 control_paragraph(&ControlSelector::Id {
676 id: "t0.row1.cell2.cc4".into()
677 }),
678 Some(("t0.row1.cell2", "4"))
679 );
680 assert_eq!(control_paragraph(&name(".cc0")), None);
681 assert_eq!(control_paragraph(&name("p3.ccx")), None);
682 assert_eq!(control_paragraph(&name("cc1")), None);
683 assert_eq!(
684 control_paragraph(&ControlSelector::Tag { tag: "T".into() }),
685 None
686 );
687 }
688
689 #[test]
690 fn settling_revisions_moves_places() {
691 let ops = serde_json::json!([
692 {"kind": "replace", "paragraph": "p0", "find": "x", "replacement": "y"}
693 ]);
694 let none = BTreeSet::new();
695 assert!(places_stay(
696 &plan(serde_json::json!({}), ops.clone()),
697 &none
698 ));
699 let settling = plan(
700 serde_json::json!({"resolve_revisions": {"accept": {"ids": ["r1"]}}}),
701 ops.clone(),
702 );
703 assert!(!places_stay(&settling, &none));
704 let refreshing = plan(serde_json::json!({"update_fields": true}), ops);
705 assert!(!places_stay(&refreshing, &none));
706 }
707}