Skip to main content

nb_api/
transaction.rs

1//! Collect-then-commit [`Transaction`] plan and apply engine.
2
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use crate::NbClient;
8use crate::error::NbError;
9use crate::fingerprint::{self, Fingerprint};
10use crate::gate;
11use crate::git;
12use crate::lines::{
13    apply_line_edits, apply_substring, require_contiguous_body, splice_body, splice_title,
14};
15use crate::parser::{DocumentKind, NoteDocument, ParseContext, parse};
16use crate::types::{ByteString, CommitOutcome, LineEdit, NoteTarget, Occurrence, OpOutcome};
17
18/// In-memory plan bound to one notebook. Drop discards; no begin/rollback.
19pub struct Transaction {
20    client: NbClient,
21    notebook: String,
22    plan: Vec<PlanOp>,
23    gate_timeout: Duration,
24}
25
26#[derive(Debug, Clone)]
27enum PlanOp {
28    AddNote {
29        path: String,
30        title: Option<String>,
31        content: String,
32        tags: Vec<String>,
33    },
34    AddTodo {
35        path: String,
36        title: String,
37        description: Option<String>,
38        tasks: Vec<String>,
39        tags: Vec<String>,
40    },
41    AddBookmark {
42        path: String,
43        url: String,
44        title: Option<String>,
45        tags: Vec<String>,
46        comment: Option<String>,
47    },
48    AddFolder {
49        path: String,
50    },
51    DeleteNote {
52        target: NoteTarget,
53    },
54    MoveNote {
55        target: NoteTarget,
56        destination: String,
57    },
58    MarkTaskDone {
59        target: NoteTarget,
60        task_number: Option<u32>,
61    },
62    UnmarkTaskDone {
63        target: NoteTarget,
64        task_number: Option<u32>,
65    },
66    ReplaceNoteBody {
67        target: NoteTarget,
68        new_body: Vec<u8>,
69        fingerprint: Fingerprint,
70    },
71    EditNoteSubstring {
72        target: NoteTarget,
73        pattern: Vec<u8>,
74        replacement: Vec<u8>,
75        occurrence: Occurrence,
76        expected_count: u32,
77        fingerprint: Option<Fingerprint>,
78    },
79    EditNoteLines {
80        target: NoteTarget,
81        edits: Vec<LineEdit>,
82    },
83    RetitleNote {
84        target: NoteTarget,
85        title: Vec<u8>,
86    },
87    EditNoteTags {
88        target: NoteTarget,
89        add: Vec<String>,
90        remove: Vec<String>,
91    },
92}
93
94#[derive(Debug, Clone)]
95enum VirtualNode {
96    File(Vec<u8>),
97    Folder,
98}
99
100struct VirtualTree {
101    /// Notebook-relative paths using `/` separators.
102    nodes: HashMap<String, VirtualNode>,
103}
104
105impl VirtualTree {
106    fn from_disk(root: &Path) -> Result<Self, NbError> {
107        let mut nodes = HashMap::new();
108        let paths = git::list_notebook_paths(root)?;
109        for rel in paths {
110            let key = normalize_rel(&rel);
111            let abs = root.join(&rel);
112            let meta = std::fs::symlink_metadata(&abs).map_err(|e| NbError::Io {
113                path: abs.clone(),
114                source: e.into(),
115            })?;
116            if meta.file_type().is_symlink() {
117                return Err(NbError::UnsupportedStructure {
118                    reason: format!(
119                        "notebook path `{key}` is a symlink; transactions refuse symlink snapshot/materialization"
120                    ),
121                });
122            }
123            if meta.is_dir() {
124                nodes.insert(key, VirtualNode::Folder);
125            } else if meta.is_file() {
126                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
127                    path: abs,
128                    source: e.into(),
129                })?;
130                nodes.insert(key, VirtualNode::File(bytes));
131            }
132        }
133        Ok(Self { nodes })
134    }
135
136    fn exists(&self, path: &str) -> bool {
137        self.nodes.contains_key(path)
138    }
139
140    fn get_file(&self, path: &str) -> Option<&[u8]> {
141        match self.nodes.get(path) {
142            Some(VirtualNode::File(b)) => Some(b),
143            _ => None,
144        }
145    }
146
147    fn insert_file(&mut self, path: String, bytes: Vec<u8>) {
148        // Ensure parent folders exist virtually.
149        if let Some(parent) = parent_path(&path) {
150            self.ensure_folder_chain(&parent);
151        }
152        self.nodes.insert(path, VirtualNode::File(bytes));
153    }
154
155    fn insert_folder(&mut self, path: String) {
156        self.ensure_folder_chain(&path);
157        self.nodes.insert(path, VirtualNode::Folder);
158    }
159
160    fn ensure_folder_chain(&mut self, path: &str) {
161        let mut acc = String::new();
162        for part in path.split('/').filter(|p| !p.is_empty()) {
163            if !acc.is_empty() {
164                acc.push('/');
165            }
166            acc.push_str(part);
167            self.nodes.entry(acc.clone()).or_insert(VirtualNode::Folder);
168        }
169    }
170
171    fn remove(&mut self, path: &str) {
172        self.nodes.remove(path);
173    }
174
175    fn rename(&mut self, from: &str, to: &str) -> Result<(), NbError> {
176        let node = self.nodes.remove(from).ok_or_else(|| NbError::NotFound {
177            selector: from.to_string(),
178        })?;
179        if let Some(parent) = parent_path(to) {
180            self.ensure_folder_chain(&parent);
181        }
182        self.nodes.insert(to.to_string(), node);
183        Ok(())
184    }
185}
186
187impl Transaction {
188    pub(crate) fn new(client: NbClient, notebook: String, gate_timeout: Duration) -> Self {
189        Self {
190            client,
191            notebook,
192            plan: Vec::new(),
193            gate_timeout,
194        }
195    }
196
197    pub fn add_note(
198        &mut self,
199        path: &str,
200        title: Option<&str>,
201        content: &str,
202        tags: &[String],
203    ) -> Result<(), NbError> {
204        let path = validate_create_path(path, true)?;
205        if let Some(t) = title
206            && let Some(heading) = crate::validate::detect_duplicate_title_heading(t, content)
207        {
208            return Err(NbError::DuplicateTitleHeading {
209                title: t.to_string(),
210                heading,
211            });
212        }
213        self.plan.push(PlanOp::AddNote {
214            path,
215            title: title.map(str::to_string),
216            content: content.to_string(),
217            tags: tags.to_vec(),
218        });
219        Ok(())
220    }
221
222    pub fn add_todo(
223        &mut self,
224        path: &str,
225        title: &str,
226        description: Option<&str>,
227        tasks: &[String],
228        tags: &[String],
229    ) -> Result<(), NbError> {
230        let path = validate_create_path(path, true)?;
231        if title.trim().is_empty() {
232            return Err(NbError::ValidationError {
233                reason: "todo title must not be empty".into(),
234                location: None,
235            });
236        }
237        self.plan.push(PlanOp::AddTodo {
238            path,
239            title: title.to_string(),
240            description: description.map(str::to_string),
241            tasks: tasks.to_vec(),
242            tags: tags.to_vec(),
243        });
244        Ok(())
245    }
246
247    pub fn add_bookmark(
248        &mut self,
249        path: &str,
250        url: &str,
251        title: Option<&str>,
252        tags: &[String],
253        comment: Option<&str>,
254    ) -> Result<(), NbError> {
255        let path = validate_create_path(path, true)?;
256        if url.trim().is_empty() {
257            return Err(NbError::ValidationError {
258                reason: "bookmark url must not be empty".into(),
259                location: None,
260            });
261        }
262        self.plan.push(PlanOp::AddBookmark {
263            path,
264            url: url.to_string(),
265            title: title.map(str::to_string),
266            tags: tags.to_vec(),
267            comment: comment.map(str::to_string),
268        });
269        Ok(())
270    }
271
272    pub fn add_folder(&mut self, path: &str) -> Result<(), NbError> {
273        let path = validate_create_path(path, false)?;
274        self.plan.push(PlanOp::AddFolder { path });
275        Ok(())
276    }
277
278    pub fn delete_note(&mut self, target: NoteTarget) -> Result<(), NbError> {
279        validate_target(&target)?;
280        self.plan.push(PlanOp::DeleteNote { target });
281        Ok(())
282    }
283
284    pub fn move_note(&mut self, target: NoteTarget, destination: &str) -> Result<(), NbError> {
285        validate_target(&target)?;
286        crate::validate::validate_destination(destination)?;
287        let destination = normalize_rel(destination);
288        if destination.is_empty() || destination.contains("..") {
289            return Err(NbError::ValidationError {
290                reason: "invalid move destination".into(),
291                location: None,
292            });
293        }
294        self.plan.push(PlanOp::MoveNote {
295            target,
296            destination,
297        });
298        Ok(())
299    }
300
301    pub fn mark_task_done(
302        &mut self,
303        target: NoteTarget,
304        task_number: Option<u32>,
305    ) -> Result<(), NbError> {
306        validate_target(&target)?;
307        self.plan.push(PlanOp::MarkTaskDone {
308            target,
309            task_number,
310        });
311        Ok(())
312    }
313
314    pub fn unmark_task_done(
315        &mut self,
316        target: NoteTarget,
317        task_number: Option<u32>,
318    ) -> Result<(), NbError> {
319        validate_target(&target)?;
320        self.plan.push(PlanOp::UnmarkTaskDone {
321            target,
322            task_number,
323        });
324        Ok(())
325    }
326
327    pub fn replace_note_body(
328        &mut self,
329        target: NoteTarget,
330        new_body: impl AsRef<[u8]>,
331        fingerprint: Fingerprint,
332    ) -> Result<(), NbError> {
333        validate_target(&target)?;
334        self.plan.push(PlanOp::ReplaceNoteBody {
335            target,
336            new_body: new_body.as_ref().to_vec(),
337            fingerprint,
338        });
339        Ok(())
340    }
341
342    pub fn edit_note_substring(
343        &mut self,
344        target: NoteTarget,
345        pattern: impl AsRef<[u8]>,
346        replacement: impl AsRef<[u8]>,
347        occurrence: Occurrence,
348        expected_count: u32,
349        fingerprint: Option<Fingerprint>,
350    ) -> Result<(), NbError> {
351        validate_target(&target)?;
352        if pattern.as_ref().is_empty() {
353            return Err(NbError::EmptySubstringPattern);
354        }
355        self.plan.push(PlanOp::EditNoteSubstring {
356            target,
357            pattern: pattern.as_ref().to_vec(),
358            replacement: replacement.as_ref().to_vec(),
359            occurrence,
360            expected_count,
361            fingerprint,
362        });
363        Ok(())
364    }
365
366    pub fn edit_note_lines(
367        &mut self,
368        target: NoteTarget,
369        edits: Vec<LineEdit>,
370    ) -> Result<(), NbError> {
371        validate_target(&target)?;
372        if edits.is_empty() {
373            return Err(NbError::ValidationError {
374                reason: "edit_note_lines requires a non-empty edits batch".into(),
375                location: None,
376            });
377        }
378        self.plan.push(PlanOp::EditNoteLines { target, edits });
379        Ok(())
380    }
381
382    pub fn retitle_note(
383        &mut self,
384        target: NoteTarget,
385        title: impl AsRef<[u8]>,
386    ) -> Result<(), NbError> {
387        validate_target(&target)?;
388        self.plan.push(PlanOp::RetitleNote {
389            target,
390            title: title.as_ref().to_vec(),
391        });
392        Ok(())
393    }
394
395    pub fn edit_note_tags(
396        &mut self,
397        target: NoteTarget,
398        add: &[String],
399        remove: &[String],
400    ) -> Result<(), NbError> {
401        validate_target(&target)?;
402        let add_set: HashSet<&str> = add.iter().map(|s| s.trim_start_matches('#')).collect();
403        for r in remove {
404            let key = r.trim_start_matches('#');
405            if add_set.contains(key) {
406                return Err(NbError::ValidationError {
407                    reason: format!("contradictory tag add/remove for `{key}`"),
408                    location: None,
409                });
410            }
411        }
412        self.plan.push(PlanOp::EditNoteTags {
413            target,
414            add: add.to_vec(),
415            remove: remove.to_vec(),
416        });
417        Ok(())
418    }
419
420    /// Validate-all, apply-all, at most one Git checkpoint.
421    pub async fn commit(self) -> Result<CommitOutcome, NbError> {
422        // Resolve root without invoking `nb` when possible (avoids nb
423        // auto-checkpoint clearing dirty state before the baseline check).
424        let notebook_root = self
425            .client
426            .show_notebook_path_unguarded(Some(&self.notebook))
427            .await?;
428        let gate_key = gate::git_common_dir_realpath(&notebook_root)?;
429        let _hold = gate::acquire_notebook(gate_key, self.gate_timeout, false).await?;
430
431        if git::notebook_is_dirty(&notebook_root)? {
432            return Err(NbError::DirtyBaseline {
433                guidance: "commit or clean the notebook worktree/index before Transaction::commit"
434                    .into(),
435            });
436        }
437
438        let pre_revision = git::notebook_head(&notebook_root)?;
439        if self.plan.is_empty() {
440            return Ok(CommitOutcome {
441                commit_created: false,
442                revision_id: None,
443                pre_revision,
444                ops: Vec::new(),
445            });
446        }
447
448        let ignored_existing: HashSet<String> = git::list_ignored_paths(&notebook_root)?
449            .into_iter()
450            .map(|p| normalize_rel(&p))
451            .collect();
452        let mut tree = VirtualTree::from_disk(&notebook_root)?;
453        let mut op_meta: Vec<OpMeta> = Vec::with_capacity(self.plan.len());
454
455        for (index, op) in self.plan.iter().enumerate() {
456            match validate_and_apply_virtual(
457                &self.notebook,
458                &notebook_root,
459                &mut tree,
460                &ignored_existing,
461                op,
462                index,
463            ) {
464                Ok(meta) => op_meta.push(meta),
465                Err(err) => {
466                    return Err(annotate_plan_index(err, index as u32));
467                }
468            }
469        }
470
471        // Disk baseline before materialize (for rollback of new owned outputs).
472        // Virtual tree already includes planned ops; disk is still pre-apply.
473        let baseline_on_disk: HashSet<String> = {
474            let mut s: HashSet<String> = git::list_notebook_paths(&notebook_root)?
475                .into_iter()
476                .map(|p| normalize_rel(&p))
477                .collect();
478            s.extend(ignored_existing.iter().cloned());
479            s
480        };
481
482        // Force-stage every final file path so ignore rules cannot drop
483        // transaction-owned outputs (new ignored names, `.gitkeep`, etc.).
484        let force_paths: Vec<String> = tree
485            .nodes
486            .iter()
487            .filter_map(|(p, n)| match n {
488                VirtualNode::File(_) => Some(p.clone()),
489                VirtualNode::Folder => None,
490            })
491            .collect();
492
493        // Directories that already exist before materialize must never be
494        // pruned during rollback (including empty ignored parents).
495        let baseline_dirs = existing_dirs_under(&notebook_root);
496
497        // Materialize to disk under gate, then single checkpoint.
498        let apply_result = (|| -> Result<bool, NbError> {
499            materialize_tree(&notebook_root, &tree)?;
500            git::notebook_commit_all(
501                &notebook_root,
502                &format!("nb-api transaction ({} ops)", self.plan.len()),
503                &force_paths,
504            )
505        })();
506
507        match apply_result {
508            Ok(created) => {
509                let revision_id = if created {
510                    match git::notebook_head(&notebook_root) {
511                        Ok(head) => Some(head),
512                        Err(_) => {
513                            return Err(NbError::IndeterminateCommit {
514                                pre_revision,
515                                post_revision_observed: None,
516                                guidance: "git commit may have succeeded but HEAD could not be re-read; do not retry blindly".into(),
517                            });
518                        }
519                    }
520                } else {
521                    None
522                };
523                let ops = op_meta
524                    .into_iter()
525                    .enumerate()
526                    .map(|(i, meta)| OpOutcome {
527                        index: i as u32,
528                        path: meta.path,
529                        selector: meta.selector,
530                        noop: meta.noop,
531                        fingerprint: meta.fingerprint,
532                    })
533                    .collect();
534                Ok(CommitOutcome {
535                    commit_created: created,
536                    revision_id,
537                    pre_revision,
538                    ops,
539                })
540            }
541            Err(err) => {
542                let post = git::notebook_head(&notebook_root).ok();
543                if post.as_deref().is_some_and(|h| h != pre_revision.as_str()) {
544                    return Err(NbError::IndeterminateCommit {
545                        pre_revision,
546                        post_revision_observed: post,
547                        guidance: "checkpoint may have completed; re-read HEAD/status and do not retry the same plan blindly".into(),
548                    });
549                }
550                // Owned outputs that did not exist at baseline must be removed
551                // even when ignored (git clean -fd keeps ignored files).
552                let owned_new: Vec<String> = force_paths
553                    .into_iter()
554                    .filter(|p| !baseline_on_disk.contains(p))
555                    .collect();
556                match try_restore(&notebook_root, &pre_revision, &owned_new, &baseline_dirs) {
557                    Ok(()) => Err(err),
558                    Err(recovery) => Err(recovery),
559                }
560            }
561        }
562    }
563}
564
565/// All directory paths under the notebook root before materialize (relative,
566/// `/`-separated). Used so rollback never deletes pre-existing dirs.
567fn existing_dirs_under(notebook_root: &Path) -> HashSet<String> {
568    let mut dirs = HashSet::new();
569    fn walk(base: &Path, rel: &Path, out: &mut HashSet<String>) {
570        let entries = match std::fs::read_dir(base) {
571            Ok(e) => e,
572            Err(_) => return,
573        };
574        for entry in entries.flatten() {
575            let name = entry.file_name();
576            if name == ".git" {
577                continue;
578            }
579            let Ok(ft) = entry.file_type() else {
580                continue;
581            };
582            // Do not follow symlinks.
583            if ft.is_symlink() || !ft.is_dir() {
584                continue;
585            }
586            let child_rel = if rel.as_os_str().is_empty() {
587                PathBuf::from(&name)
588            } else {
589                rel.join(&name)
590            };
591            let key = child_rel.to_string_lossy().replace('\\', "/");
592            out.insert(key);
593            walk(&entry.path(), &child_rel, out);
594        }
595    }
596    walk(notebook_root, Path::new(""), &mut dirs);
597    dirs
598}
599
600fn try_restore(
601    notebook_root: &Path,
602    pre_revision: &str,
603    remove_new_owned: &[String],
604    baseline_dirs: &HashSet<String>,
605) -> Result<(), NbError> {
606    if let Err(e) = git::notebook_reset_clean(notebook_root, pre_revision) {
607        let post = git::notebook_head(notebook_root).ok();
608        let status = git::notebook_status_porcelain(notebook_root).ok();
609        return Err(NbError::RecoveryRequired {
610            pre_revision: pre_revision.to_string(),
611            post_revision_observed: post,
612            status_observed: status,
613            preserved_paths: Some(remove_new_owned.to_vec()),
614            guidance: format!(
615                "cleanup after failed commit could not be verified; inspect HEAD/status before retry. underlying: {e}"
616            ),
617        });
618    }
619    // `git clean -fd` can remove empty untracked dirs (including ignored
620    // parents) once staged children are cleared by reset --hard. Restore any
621    // baseline directory that disappeared.
622    for d in baseline_dirs {
623        let abs = notebook_root.join(d);
624        if !abs.exists()
625            && let Err(e) = std::fs::create_dir_all(&abs)
626        {
627            return Err(NbError::RecoveryRequired {
628                pre_revision: pre_revision.to_string(),
629                post_revision_observed: git::notebook_head(notebook_root).ok(),
630                status_observed: git::notebook_status_porcelain(notebook_root).ok(),
631                preserved_paths: Some(vec![d.clone()]),
632                guidance: format!(
633                    "failed to restore baseline directory `{d}` after cleanup; do not retry blindly. underlying: {e}"
634                ),
635            });
636        }
637    }
638    // Explicitly delete transaction-owned outputs that reset/clean leave behind
639    // when they are Git-ignored untracked files.
640    let mut remaining = Vec::new();
641    for rel in remove_new_owned {
642        let abs = notebook_root.join(rel);
643        match std::fs::symlink_metadata(&abs) {
644            Ok(meta) if meta.file_type().is_symlink() || meta.is_file() => {
645                if let Err(e) = std::fs::remove_file(&abs) {
646                    remaining.push(format!("{rel} ({e})"));
647                }
648            }
649            Ok(meta) if meta.is_dir() => {
650                if let Err(e) = std::fs::remove_dir_all(&abs) {
651                    remaining.push(format!("{rel} ({e})"));
652                }
653            }
654            Ok(_) => {}
655            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
656            Err(e) => remaining.push(format!("{rel} ({e})")),
657        }
658        // Prune only empty parents that the transaction created — never a
659        // directory that existed at baseline (e.g. pre-existing ignored parent).
660        if let Some(parent) = parent_path(rel) {
661            let mut cur = parent;
662            loop {
663                if baseline_dirs.contains(&cur) {
664                    break;
665                }
666                let p = notebook_root.join(&cur);
667                match std::fs::remove_dir(&p) {
668                    Ok(()) => {}
669                    Err(_) => break,
670                }
671                match parent_path(&cur) {
672                    Some(next) => cur = next,
673                    None => break,
674                }
675            }
676        }
677    }
678    if !remaining.is_empty() {
679        return Err(NbError::RecoveryRequired {
680            pre_revision: pre_revision.to_string(),
681            post_revision_observed: git::notebook_head(notebook_root).ok(),
682            status_observed: git::notebook_status_porcelain(notebook_root).ok(),
683            preserved_paths: Some(remaining),
684            guidance: "failed to remove transaction-owned outputs after aborted commit; do not retry blindly".into(),
685        });
686    }
687    // Verify none of the new owned paths remain (including ignored).
688    let mut still_present = Vec::new();
689    for rel in remove_new_owned {
690        if notebook_root.join(rel).exists() {
691            still_present.push(rel.clone());
692        }
693    }
694    let head = match restore_verify_head(notebook_root) {
695        Ok(h) => h,
696        Err(e) => {
697            return Err(NbError::RecoveryRequired {
698                pre_revision: pre_revision.to_string(),
699                post_revision_observed: None,
700                status_observed: git::notebook_status_porcelain(notebook_root).ok(),
701                preserved_paths: if still_present.is_empty() {
702                    None
703                } else {
704                    Some(still_present)
705                },
706                guidance: format!(
707                    "cleanup ran but HEAD re-read failed during verification; do not retry blindly. underlying: {e}"
708                ),
709            });
710        }
711    };
712    let dirty = match restore_verify_dirty(notebook_root) {
713        Ok(d) => d,
714        Err(e) => {
715            return Err(NbError::RecoveryRequired {
716                pre_revision: pre_revision.to_string(),
717                post_revision_observed: Some(head),
718                status_observed: git::notebook_status_porcelain(notebook_root).ok(),
719                preserved_paths: if still_present.is_empty() {
720                    None
721                } else {
722                    Some(still_present)
723                },
724                guidance: format!(
725                    "cleanup ran but dirty-status check failed during verification; do not retry blindly. underlying: {e}"
726                ),
727            });
728        }
729    };
730    if head != pre_revision || dirty || !still_present.is_empty() {
731        return Err(NbError::RecoveryRequired {
732            pre_revision: pre_revision.to_string(),
733            post_revision_observed: Some(head),
734            status_observed: git::notebook_status_porcelain(notebook_root).ok(),
735            preserved_paths: if still_present.is_empty() {
736                None
737            } else {
738                Some(still_present)
739            },
740            guidance:
741                "cleanup ran but HEAD/status/owned-path verification failed; do not retry blindly"
742                    .into(),
743        });
744    }
745    Ok(())
746}
747
748/// HEAD observation used only in post-cleanup verification.
749fn restore_verify_head(notebook_root: &Path) -> Result<String, NbError> {
750    #[cfg(feature = "testing")]
751    if std::env::var_os("NB_API_FAIL_RESTORE_HEAD").is_some() {
752        return Err(NbError::CommandFailed {
753            command: "nb-api://fail-restore-head".into(),
754            stderr: "injected HEAD verify failure for rollback tests".into(),
755            exit_code: Some(1),
756        });
757    }
758    git::notebook_head(notebook_root)
759}
760
761/// Dirty-status observation used only in post-cleanup verification.
762fn restore_verify_dirty(notebook_root: &Path) -> Result<bool, NbError> {
763    #[cfg(feature = "testing")]
764    if std::env::var_os("NB_API_FAIL_RESTORE_DIRTY").is_some() {
765        return Err(NbError::CommandFailed {
766            command: "nb-api://fail-restore-dirty".into(),
767            stderr: "injected dirty-status verify failure for rollback tests".into(),
768            exit_code: Some(1),
769        });
770    }
771    git::notebook_is_dirty(notebook_root)
772}
773
774fn materialize_tree(root: &Path, tree: &VirtualTree) -> Result<(), NbError> {
775    // Preflight: no path may traverse an existing symlink ancestor (including
776    // ignored directory symlinks excluded from the virtual snapshot).
777    for rel in tree.nodes.keys() {
778        refuse_symlink_ancestors(root, rel)?;
779    }
780
781    // Remove tracked/untracked/ignored files not present as files in the virtual tree.
782    let disk_paths = git::list_notebook_paths(root)?;
783    for rel in &disk_paths {
784        let key = normalize_rel(rel);
785        let abs = root.join(rel);
786        let meta = match std::fs::symlink_metadata(&abs) {
787            Ok(m) => m,
788            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
789            Err(e) => {
790                return Err(NbError::Io {
791                    path: abs,
792                    source: e.into(),
793                });
794            }
795        };
796        if meta.file_type().is_symlink() {
797            return Err(NbError::UnsupportedStructure {
798                reason: format!("refusing to materialize through symlink `{key}`"),
799            });
800        }
801        if meta.is_file() {
802            match tree.nodes.get(&key) {
803                Some(VirtualNode::File(_)) => {}
804                _ => {
805                    std::fs::remove_file(&abs).map_err(|e| NbError::Io {
806                        path: abs,
807                        source: e.into(),
808                    })?;
809                }
810            }
811        }
812    }
813    for (rel, node) in &tree.nodes {
814        let abs = root.join(rel);
815        // Never write through an existing symlink leaf or ancestor.
816        refuse_symlink_ancestors(root, rel)?;
817        if let Ok(meta) = std::fs::symlink_metadata(&abs)
818            && meta.file_type().is_symlink()
819        {
820            return Err(NbError::UnsupportedStructure {
821                reason: format!("refusing to write through symlink `{rel}`"),
822            });
823        }
824        match node {
825            VirtualNode::Folder => {
826                std::fs::create_dir_all(&abs).map_err(|e| NbError::Io {
827                    path: abs.clone(),
828                    source: e.into(),
829                })?;
830            }
831            VirtualNode::File(bytes) => {
832                if let Some(parent) = abs.parent() {
833                    std::fs::create_dir_all(parent).map_err(|e| NbError::Io {
834                        path: parent.to_path_buf(),
835                        source: e.into(),
836                    })?;
837                }
838                std::fs::write(&abs, bytes).map_err(|e| NbError::Io {
839                    path: abs,
840                    source: e.into(),
841                })?;
842            }
843        }
844    }
845    Ok(())
846}
847
848/// Reject `rel` when any existing path component under `root` is a symlink.
849///
850/// Uses no-follow metadata so ignored directory symlinks (absent from the
851/// virtual snapshot) cannot redirect `create_dir_all` / `write` outside the
852/// notebook root.
853fn refuse_symlink_ancestors(root: &Path, rel: &str) -> Result<(), NbError> {
854    let mut acc = PathBuf::new();
855    for part in rel.split('/').filter(|p| !p.is_empty()) {
856        acc.push(part);
857        let abs = root.join(&acc);
858        match std::fs::symlink_metadata(&abs) {
859            Ok(meta) if meta.file_type().is_symlink() => {
860                let key = acc.to_string_lossy().replace('\\', "/");
861                return Err(NbError::UnsupportedStructure {
862                    reason: format!(
863                        "refusing path through symlink `{key}`; transactions do not follow symlinks"
864                    ),
865                });
866            }
867            Ok(_) => {}
868            Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
869            Err(e) => {
870                return Err(NbError::Io {
871                    path: abs,
872                    source: e.into(),
873                });
874            }
875        }
876    }
877    Ok(())
878}
879
880fn outcome_selector(notebook: &str, target: &NoteTarget, resolved_path: &str) -> String {
881    match target {
882        NoteTarget::Selector { value } => {
883            if value.contains(':') {
884                value.clone()
885            } else {
886                format!("{notebook}:{value}")
887            }
888        }
889        NoteTarget::Path { .. } => format!("{notebook}:{resolved_path}"),
890    }
891}
892
893struct OpMeta {
894    path: Option<String>,
895    selector: Option<String>,
896    noop: bool,
897    fingerprint: Option<Fingerprint>,
898}
899
900fn validate_and_apply_virtual(
901    notebook: &str,
902    notebook_root: &Path,
903    tree: &mut VirtualTree,
904    ignored_existing: &HashSet<String>,
905    op: &PlanOp,
906    _index: usize,
907) -> Result<OpMeta, NbError> {
908    match op {
909        PlanOp::AddNote {
910            path,
911            title,
912            content,
913            tags,
914        } => {
915            refuse_create_collision(notebook_root, tree, ignored_existing, path)?;
916            let bytes = build_note_bytes(title.as_deref(), content, tags);
917            let fp = fingerprint_bytes(&bytes, path)?;
918            tree.insert_file(path.clone(), bytes);
919            Ok(OpMeta {
920                path: Some(path.clone()),
921                selector: Some(format!("{notebook}:{path}")),
922                noop: false,
923                fingerprint: Some(fp),
924            })
925        }
926        PlanOp::AddTodo {
927            path,
928            title,
929            description,
930            tasks,
931            tags,
932        } => {
933            refuse_create_collision(notebook_root, tree, ignored_existing, path)?;
934            let bytes = build_todo_bytes(title, description.as_deref(), tasks, tags);
935            let fp = fingerprint_bytes(&bytes, path)?;
936            tree.insert_file(path.clone(), bytes);
937            Ok(OpMeta {
938                path: Some(path.clone()),
939                selector: Some(format!("{notebook}:{path}")),
940                noop: false,
941                fingerprint: Some(fp),
942            })
943        }
944        PlanOp::AddBookmark {
945            path,
946            url,
947            title,
948            tags,
949            comment,
950        } => {
951            refuse_create_collision(notebook_root, tree, ignored_existing, path)?;
952            let bytes = build_bookmark_bytes(url, title.as_deref(), tags, comment.as_deref());
953            let fp = fingerprint_bytes(&bytes, path)?;
954            tree.insert_file(path.clone(), bytes);
955            Ok(OpMeta {
956                path: Some(path.clone()),
957                selector: Some(format!("{notebook}:{path}")),
958                noop: false,
959                fingerprint: Some(fp),
960            })
961        }
962        PlanOp::AddFolder { path } => {
963            refuse_create_collision(notebook_root, tree, ignored_existing, path)?;
964            let keep = format!("{path}/.gitkeep");
965            refuse_create_collision(notebook_root, tree, ignored_existing, &keep)?;
966            tree.insert_folder(path.clone());
967            // Git cannot track empty dirs; persist a keep file so the folder
968            // survives commit/checkout/clone. Force-staged at checkpoint.
969            if !tree.exists(&keep) {
970                tree.insert_file(keep, Vec::new());
971            }
972            Ok(OpMeta {
973                path: Some(path.clone()),
974                selector: None,
975                noop: false,
976                fingerprint: None,
977            })
978        }
979        PlanOp::DeleteNote { target } => {
980            let path = resolve_target_path(tree, ignored_existing, target)?;
981            if !tree.exists(&path) {
982                return Err(NbError::NotFound {
983                    selector: target.value().to_string(),
984                });
985            }
986            tree.remove(&path);
987            Ok(OpMeta {
988                path: Some(path.clone()),
989                selector: Some(outcome_selector(notebook, target, &path)),
990                noop: false,
991                fingerprint: None,
992            })
993        }
994        PlanOp::MoveNote {
995            target,
996            destination,
997        } => {
998            let from = resolve_target_path(tree, ignored_existing, target)?;
999            let to = resolve_move_destination(&from, destination);
1000            refuse_create_collision(notebook_root, tree, ignored_existing, &to)?;
1001            tree.rename(&from, &to)?;
1002            Ok(OpMeta {
1003                path: Some(to.clone()),
1004                selector: Some(format!("{notebook}:{to}")),
1005                noop: false,
1006                fingerprint: None,
1007            })
1008        }
1009        PlanOp::MarkTaskDone {
1010            target,
1011            task_number,
1012        } => {
1013            let path = resolve_target_path(tree, ignored_existing, target)?;
1014            let bytes = tree
1015                .get_file(&path)
1016                .ok_or_else(|| NbError::NotFound {
1017                    selector: target.value().to_string(),
1018                })?
1019                .to_vec();
1020            let new_bytes = set_todo_state(&bytes, &path, true, *task_number)?;
1021            let noop = new_bytes == bytes;
1022            let fp = fingerprint_bytes(&new_bytes, &path)?;
1023            tree.insert_file(path.clone(), new_bytes);
1024            Ok(OpMeta {
1025                path: Some(path.clone()),
1026                selector: Some(outcome_selector(notebook, target, &path)),
1027                noop,
1028                fingerprint: Some(fp),
1029            })
1030        }
1031        PlanOp::UnmarkTaskDone {
1032            target,
1033            task_number,
1034        } => {
1035            let path = resolve_target_path(tree, ignored_existing, target)?;
1036            let bytes = tree
1037                .get_file(&path)
1038                .ok_or_else(|| NbError::NotFound {
1039                    selector: target.value().to_string(),
1040                })?
1041                .to_vec();
1042            let new_bytes = set_todo_state(&bytes, &path, false, *task_number)?;
1043            let noop = new_bytes == bytes;
1044            let fp = fingerprint_bytes(&new_bytes, &path)?;
1045            tree.insert_file(path.clone(), new_bytes);
1046            Ok(OpMeta {
1047                path: Some(path.clone()),
1048                selector: Some(outcome_selector(notebook, target, &path)),
1049                noop,
1050                fingerprint: Some(fp),
1051            })
1052        }
1053        PlanOp::ReplaceNoteBody {
1054            target,
1055            new_body,
1056            fingerprint: expected,
1057        } => {
1058            let path = resolve_target_path(tree, ignored_existing, target)?;
1059            let bytes = tree
1060                .get_file(&path)
1061                .ok_or_else(|| NbError::NotFound {
1062                    selector: target.value().to_string(),
1063                })?
1064                .to_vec();
1065            let doc = parse_doc(&bytes, &path)?;
1066            // Contiguity before fingerprint so fragmented bodies always surface
1067            // FragmentedBody even with a stale fingerprint.
1068            require_contiguous_body(&doc)?;
1069            let current = fingerprint::fingerprint(&doc);
1070            if &current != expected {
1071                return Err(NbError::FingerprintMismatch {
1072                    target: target.clone(),
1073                    guidance: "body fingerprint does not match; re-read and retry".into(),
1074                });
1075            }
1076            let new_bytes = splice_body(&doc, new_body)?;
1077            let fp = fingerprint_bytes(&new_bytes, &path)?;
1078            let noop = new_bytes == bytes;
1079            tree.insert_file(path.clone(), new_bytes);
1080            Ok(OpMeta {
1081                path: Some(path.clone()),
1082                selector: Some(outcome_selector(notebook, target, &path)),
1083                noop,
1084                fingerprint: Some(fp),
1085            })
1086        }
1087        PlanOp::EditNoteSubstring {
1088            target,
1089            pattern,
1090            replacement,
1091            occurrence,
1092            expected_count,
1093            fingerprint: expected,
1094        } => {
1095            let path = resolve_target_path(tree, ignored_existing, target)?;
1096            let bytes = tree
1097                .get_file(&path)
1098                .ok_or_else(|| NbError::NotFound {
1099                    selector: target.value().to_string(),
1100                })?
1101                .to_vec();
1102            let doc = parse_doc(&bytes, &path)?;
1103            let body = require_contiguous_body(&doc)?;
1104            if let Some(exp) = expected {
1105                let current = fingerprint::fingerprint(&doc);
1106                if &current != exp {
1107                    return Err(NbError::FingerprintMismatch {
1108                        target: target.clone(),
1109                        guidance: "body fingerprint does not match; re-read and retry".into(),
1110                    });
1111                }
1112            }
1113            let new_body =
1114                apply_substring(&body, pattern, replacement, occurrence, *expected_count)?;
1115            let new_bytes = splice_body(&doc, &new_body)?;
1116            let fp = fingerprint_bytes(&new_bytes, &path)?;
1117            let noop = new_bytes == bytes;
1118            tree.insert_file(path.clone(), new_bytes);
1119            Ok(OpMeta {
1120                path: Some(path.clone()),
1121                selector: Some(outcome_selector(notebook, target, &path)),
1122                noop,
1123                fingerprint: Some(fp),
1124            })
1125        }
1126        PlanOp::EditNoteLines { target, edits } => {
1127            let path = resolve_target_path(tree, ignored_existing, target)?;
1128            let bytes = tree
1129                .get_file(&path)
1130                .ok_or_else(|| NbError::NotFound {
1131                    selector: target.value().to_string(),
1132                })?
1133                .to_vec();
1134            let doc = parse_doc(&bytes, &path)?;
1135            let body = require_contiguous_body(&doc)?;
1136            let new_body = apply_line_edits(&body, edits)?;
1137            let new_bytes = splice_body(&doc, &new_body)?;
1138            let fp = fingerprint_bytes(&new_bytes, &path)?;
1139            let noop = new_bytes == bytes;
1140            tree.insert_file(path.clone(), new_bytes);
1141            Ok(OpMeta {
1142                path: Some(path.clone()),
1143                selector: Some(outcome_selector(notebook, target, &path)),
1144                noop,
1145                fingerprint: Some(fp),
1146            })
1147        }
1148        PlanOp::RetitleNote { target, title } => {
1149            let path = resolve_target_path(tree, ignored_existing, target)?;
1150            let bytes = tree
1151                .get_file(&path)
1152                .ok_or_else(|| NbError::NotFound {
1153                    selector: target.value().to_string(),
1154                })?
1155                .to_vec();
1156            let doc = parse_doc(&bytes, &path)?;
1157            let mut title_line = title.clone();
1158            if !title_line.starts_with(b"#") {
1159                let mut prefixed = b"# ".to_vec();
1160                prefixed.extend_from_slice(&title_line);
1161                title_line = prefixed;
1162            }
1163            let new_bytes = splice_title(&doc, &title_line)?;
1164            let fp = fingerprint_bytes(&new_bytes, &path)?;
1165            let noop = new_bytes == bytes;
1166            tree.insert_file(path.clone(), new_bytes);
1167            Ok(OpMeta {
1168                path: Some(path.clone()),
1169                selector: Some(outcome_selector(notebook, target, &path)),
1170                noop,
1171                fingerprint: Some(fp),
1172            })
1173        }
1174        PlanOp::EditNoteTags {
1175            target,
1176            add,
1177            remove,
1178        } => {
1179            let path = resolve_target_path(tree, ignored_existing, target)?;
1180            let bytes = tree
1181                .get_file(&path)
1182                .ok_or_else(|| NbError::NotFound {
1183                    selector: target.value().to_string(),
1184                })?
1185                .to_vec();
1186            let doc = parse_doc(&bytes, &path)?;
1187            let new_bytes = apply_tag_edit(&doc, &path, add, remove)?;
1188            let fp = fingerprint_bytes(&new_bytes, &path)?;
1189            let noop = new_bytes == bytes;
1190            tree.insert_file(path.clone(), new_bytes);
1191            Ok(OpMeta {
1192                path: Some(path.clone()),
1193                selector: Some(outcome_selector(notebook, target, &path)),
1194                noop,
1195                fingerprint: Some(fp),
1196            })
1197        }
1198    }
1199}
1200
1201fn refuse_create_collision(
1202    notebook_root: &Path,
1203    tree: &VirtualTree,
1204    ignored_existing: &HashSet<String>,
1205    path: &str,
1206) -> Result<(), NbError> {
1207    if ignored_existing.contains(path) {
1208        return Err(NbError::PathIgnored {
1209            path: path.to_string(),
1210            guidance: "path exists as a Git-ignored file; un-ignore or remove it outside the transaction before creating here".into(),
1211            plan_index: None,
1212        });
1213    }
1214    // Ignored directory/file symlinks are absent from the virtual tree; reject
1215    // creates whose prefix is an ignored symlink (or any on-disk symlink).
1216    refuse_symlink_ancestors(notebook_root, path)?;
1217    for ig in ignored_existing {
1218        if path == ig || path.starts_with(&format!("{ig}/")) {
1219            let abs = notebook_root.join(ig);
1220            if let Ok(meta) = std::fs::symlink_metadata(&abs)
1221                && meta.file_type().is_symlink()
1222            {
1223                return Err(NbError::UnsupportedStructure {
1224                    reason: format!(
1225                        "refusing path through symlink `{ig}`; transactions do not follow symlinks"
1226                    ),
1227                });
1228            }
1229        }
1230    }
1231    if tree.exists(path) {
1232        return Err(NbError::PathCollision {
1233            path: path.to_string(),
1234            plan_index: None,
1235        });
1236    }
1237    Ok(())
1238}
1239
1240fn refuse_existing_ignored(ignored_existing: &HashSet<String>, path: &str) -> Result<(), NbError> {
1241    if ignored_existing.contains(path) {
1242        return Err(NbError::PathIgnored {
1243            path: path.to_string(),
1244            guidance:
1245                "cannot edit, delete, or move an existing Git-ignored path inside a transaction"
1246                    .into(),
1247            plan_index: None,
1248        });
1249    }
1250    Ok(())
1251}
1252
1253fn resolve_target_path(
1254    tree: &VirtualTree,
1255    ignored_existing: &HashSet<String>,
1256    target: &NoteTarget,
1257) -> Result<String, NbError> {
1258    match target {
1259        NoteTarget::Path { value } => {
1260            let path = normalize_rel(value);
1261            refuse_existing_ignored(ignored_existing, &path)?;
1262            if tree.exists(&path) {
1263                return Ok(path);
1264            }
1265            // Allow selector-like numeric ids only via Selector variant.
1266            Err(NbError::NotFound {
1267                selector: value.clone(),
1268            })
1269        }
1270        NoteTarget::Selector { value } => {
1271            // Prefer exact path match when value looks like a path.
1272            let stripped = value
1273                .rsplit_once(':')
1274                .map(|(_, rest)| rest)
1275                .unwrap_or(value.as_str());
1276            let candidate = normalize_rel(stripped);
1277            refuse_existing_ignored(ignored_existing, &candidate)?;
1278            if tree.exists(&candidate) {
1279                return Ok(candidate);
1280            }
1281            // Match by basename or unique suffix.
1282            let matches: Vec<_> = tree
1283                .nodes
1284                .iter()
1285                .filter_map(|(p, n)| match n {
1286                    VirtualNode::File(_)
1287                        if p == &candidate
1288                            || p.ends_with(&format!("/{candidate}"))
1289                            || Path::new(p).file_stem().and_then(|s| s.to_str())
1290                                == Some(stripped)
1291                            || p.ends_with(stripped) =>
1292                    {
1293                        Some(p.clone())
1294                    }
1295                    _ => None,
1296                })
1297                .collect();
1298            match matches.as_slice() {
1299                [one] => Ok(one.clone()),
1300                [] => {
1301                    // Existing ignored paths are not in the editable tree.
1302                    if ignored_existing.contains(&candidate) {
1303                        return Err(NbError::PathIgnored {
1304                            path: candidate,
1305                            guidance: "cannot edit, delete, or move an existing Git-ignored path inside a transaction".into(),
1306                            plan_index: None,
1307                        });
1308                    }
1309                    for ig in ignored_existing {
1310                        if ig.ends_with(&format!("/{candidate}")) || ig.ends_with(stripped) {
1311                            return Err(NbError::PathIgnored {
1312                                path: ig.clone(),
1313                                guidance: "cannot edit, delete, or move an existing Git-ignored path inside a transaction".into(),
1314                                plan_index: None,
1315                            });
1316                        }
1317                    }
1318                    Err(NbError::NotFound {
1319                        selector: value.clone(),
1320                    })
1321                }
1322                _ => Err(NbError::ValidationError {
1323                    reason: format!("selector `{value}` is ambiguous across multiple paths"),
1324                    location: None,
1325                }),
1326            }
1327        }
1328    }
1329}
1330
1331fn resolve_move_destination(from: &str, destination: &str) -> String {
1332    let dest = normalize_rel(destination);
1333    if dest.ends_with('/') {
1334        let base = Path::new(from)
1335            .file_name()
1336            .and_then(|s| s.to_str())
1337            .unwrap_or(from);
1338        return normalize_rel(&format!("{dest}{base}"));
1339    }
1340    // Destination is a folder path without slash if no extension and exists as folder —
1341    // treat as basename rename when it has a file extension or contains a dot filename.
1342    dest
1343}
1344
1345fn parse_doc(bytes: &[u8], path: &str) -> Result<NoteDocument, NbError> {
1346    parse(bytes, ParseContext::FromPath(PathBuf::from(path)))
1347}
1348
1349fn fingerprint_bytes(bytes: &[u8], path: &str) -> Result<Fingerprint, NbError> {
1350    let doc = parse_doc(bytes, path)?;
1351    Ok(fingerprint::fingerprint(&doc))
1352}
1353
1354fn build_note_bytes(title: Option<&str>, content: &str, tags: &[String]) -> Vec<u8> {
1355    let mut out = Vec::new();
1356    if let Some(t) = title {
1357        out.extend_from_slice(format!("# {t}\n\n").as_bytes());
1358    }
1359    if !tags.is_empty() {
1360        let mut first = true;
1361        for tag in tags {
1362            if !first {
1363                out.push(b' ');
1364            }
1365            first = false;
1366            if tag.starts_with('#') {
1367                out.extend_from_slice(tag.as_bytes());
1368            } else {
1369                out.push(b'#');
1370                out.extend_from_slice(tag.as_bytes());
1371            }
1372        }
1373        out.extend_from_slice(b"\n\n");
1374    }
1375    out.extend_from_slice(content.as_bytes());
1376    out
1377}
1378
1379fn build_todo_bytes(
1380    title: &str,
1381    description: Option<&str>,
1382    tasks: &[String],
1383    tags: &[String],
1384) -> Vec<u8> {
1385    let mut out = Vec::new();
1386    let title_line = if title.contains('[') {
1387        format!("# {title}\n\n")
1388    } else {
1389        format!("# [ ] {title}\n\n")
1390    };
1391    out.extend_from_slice(title_line.as_bytes());
1392    if !tasks.is_empty() {
1393        out.extend_from_slice(b"## Tasks\n\n");
1394        for task in tasks {
1395            out.extend_from_slice(format!("- [ ] {task}\n").as_bytes());
1396        }
1397        out.push(b'\n');
1398    }
1399    if let Some(desc) = description {
1400        out.extend_from_slice(b"## Description\n\n");
1401        out.extend_from_slice(desc.as_bytes());
1402        if !desc.ends_with('\n') {
1403            out.push(b'\n');
1404        }
1405        out.push(b'\n');
1406    }
1407    if !tags.is_empty() {
1408        out.extend_from_slice(b"## Tags\n\n");
1409        let mut first = true;
1410        for tag in tags {
1411            if !first {
1412                out.push(b' ');
1413            }
1414            first = false;
1415            if tag.starts_with('#') {
1416                out.extend_from_slice(tag.as_bytes());
1417            } else {
1418                out.push(b'#');
1419                out.extend_from_slice(tag.as_bytes());
1420            }
1421        }
1422        out.push(b'\n');
1423    }
1424    out
1425}
1426
1427fn build_bookmark_bytes(
1428    url: &str,
1429    title: Option<&str>,
1430    tags: &[String],
1431    comment: Option<&str>,
1432) -> Vec<u8> {
1433    let mut out = Vec::new();
1434    if let Some(t) = title {
1435        out.extend_from_slice(format!("# {t}\n\n").as_bytes());
1436    }
1437    out.extend_from_slice(format!("<{url}>\n\n").as_bytes());
1438    if let Some(c) = comment {
1439        out.extend_from_slice(b"## Content\n\n");
1440        out.extend_from_slice(c.as_bytes());
1441        if !c.ends_with('\n') {
1442            out.push(b'\n');
1443        }
1444        out.push(b'\n');
1445    }
1446    if !tags.is_empty() {
1447        out.extend_from_slice(b"## Tags\n\n");
1448        let mut first = true;
1449        for tag in tags {
1450            if !first {
1451                out.push(b' ');
1452            }
1453            first = false;
1454            if tag.starts_with('#') {
1455                out.extend_from_slice(tag.as_bytes());
1456            } else {
1457                out.push(b'#');
1458                out.extend_from_slice(tag.as_bytes());
1459            }
1460        }
1461        out.push(b'\n');
1462    }
1463    out
1464}
1465
1466fn set_todo_state(
1467    bytes: &[u8],
1468    path: &str,
1469    done: bool,
1470    task_number: Option<u32>,
1471) -> Result<Vec<u8>, NbError> {
1472    let doc = parse_doc(bytes, path)?;
1473    if doc.kind() != DocumentKind::Todo {
1474        return Err(NbError::UnsupportedStructure {
1475            reason: "mark_task_done/unmark_task_done require a Todo document".into(),
1476        });
1477    }
1478    let mut out = bytes.to_vec();
1479    if let Some(n) = task_number {
1480        // Flip Nth `- [ ]` / `- [x]` checklist item (1-based).
1481        let mut count = 0u32;
1482        let mut i = 0usize;
1483        while i + 5 < out.len() {
1484            if out[i] == b'-' && out[i + 1] == b' ' && out[i + 2] == b'[' {
1485                let close = out[i + 4];
1486                if close == b']' {
1487                    count += 1;
1488                    if count == n {
1489                        let mark = if done { b'x' } else { b' ' };
1490                        out[i + 3] = mark;
1491                        return Ok(out);
1492                    }
1493                }
1494            }
1495            i += 1;
1496        }
1497        return Err(NbError::ValidationError {
1498            reason: format!("task_number {n} not found"),
1499            location: None,
1500        });
1501    }
1502    // Title checkbox.
1503    if let Some(range) = doc.title_byte_range() {
1504        let title = &out[range.clone()];
1505        let replaced = if done {
1506            replace_checkbox(title, true)
1507        } else {
1508            replace_checkbox(title, false)
1509        };
1510        out.splice(range, replaced);
1511    }
1512    Ok(out)
1513}
1514
1515fn replace_checkbox(title: &[u8], done: bool) -> Vec<u8> {
1516    let s = String::from_utf8_lossy(title);
1517    let mark = if done { "[x]" } else { "[ ]" };
1518    let new = if s.contains("[x]") || s.contains("[X]") {
1519        s.replacen("[x]", mark, 1).replacen("[X]", mark, 1)
1520    } else if s.contains("[ ]") {
1521        s.replacen("[ ]", mark, 1)
1522    } else {
1523        // Insert after `# `
1524        if let Some(rest) = s.strip_prefix("# ") {
1525            format!("# {mark} {rest}")
1526        } else {
1527            s.into_owned()
1528        }
1529    };
1530    new.into_bytes()
1531}
1532
1533fn apply_tag_edit(
1534    doc: &NoteDocument,
1535    path: &str,
1536    add: &[String],
1537    remove: &[String],
1538) -> Result<Vec<u8>, NbError> {
1539    let mut tags: Vec<String> = doc
1540        .tags_str()
1541        .filter_map(|t| t.ok().map(|s| s.trim_start_matches('#').to_string()))
1542        .collect();
1543    for r in remove {
1544        let key = r.trim_start_matches('#');
1545        tags.retain(|t| t != key);
1546    }
1547    for a in add {
1548        let key = a.trim_start_matches('#').to_string();
1549        if !tags.iter().any(|t| t == &key) {
1550            tags.push(key);
1551        }
1552    }
1553    let source = doc.source();
1554    let result = match doc.kind() {
1555        DocumentKind::Note => {
1556            let tag_line = if tags.is_empty() {
1557                None
1558            } else {
1559                Some(
1560                    tags.iter()
1561                        .map(|t| format!("#{t}"))
1562                        .collect::<Vec<_>>()
1563                        .join(" ")
1564                        + "\n",
1565                )
1566            };
1567            if let Some(range) = doc.tags_byte_range() {
1568                let mut out = source.to_vec();
1569                match tag_line {
1570                    Some(line) => {
1571                        out.splice(range, line.into_bytes());
1572                    }
1573                    None => {
1574                        out.splice(range, std::iter::empty::<u8>());
1575                    }
1576                }
1577                Ok(out)
1578            } else if let Some(line) = tag_line {
1579                // Insert after title or at start.
1580                let insert_at = doc.title_byte_range().map(|r| r.end).unwrap_or(0);
1581                let mut block = Vec::new();
1582                if insert_at > 0 {
1583                    block.push(b'\n');
1584                }
1585                block.extend_from_slice(line.as_bytes());
1586                block.push(b'\n');
1587                let mut out = source.to_vec();
1588                out.splice(insert_at..insert_at, block);
1589                Ok(out)
1590            } else {
1591                Ok(source.to_vec())
1592            }
1593        }
1594        DocumentKind::Todo | DocumentKind::Bookmark => {
1595            let section = if tags.is_empty() {
1596                None
1597            } else {
1598                Some(format!(
1599                    "## Tags\n\n{}\n",
1600                    tags.iter()
1601                        .map(|t| format!("#{t}"))
1602                        .collect::<Vec<_>>()
1603                        .join(" ")
1604                ))
1605            };
1606            if let Some(range) = doc.tags_byte_range() {
1607                let mut out = source.to_vec();
1608                let replacement = section.map(|s| s.into_bytes()).unwrap_or_default();
1609                out.splice(range, replacement);
1610                Ok(out)
1611            } else if let Some(s) = section {
1612                let mut out = source.to_vec();
1613                if !out.ends_with(b"\n") {
1614                    out.push(b'\n');
1615                }
1616                out.push(b'\n');
1617                out.extend_from_slice(s.as_bytes());
1618                Ok(out)
1619            } else {
1620                Ok(source.to_vec())
1621            }
1622        }
1623    };
1624    let _ = path;
1625    result
1626}
1627
1628fn annotate_plan_index(err: NbError, index: u32) -> NbError {
1629    match err {
1630        NbError::PathCollision { path, .. } => NbError::PathCollision {
1631            path,
1632            plan_index: Some(index),
1633        },
1634        NbError::PathIgnored { path, guidance, .. } => NbError::PathIgnored {
1635            path,
1636            guidance,
1637            plan_index: Some(index),
1638        },
1639        NbError::FingerprintMismatch { .. }
1640        | NbError::AnchorMismatch { .. }
1641        | NbError::OccurrenceMismatch { .. }
1642        | NbError::OverlappingEdits { .. }
1643        | NbError::FragmentedBody { .. }
1644        | NbError::EmptySubstringPattern
1645        | NbError::NotFound { .. }
1646        | NbError::UnsupportedStructure { .. } => err,
1647        NbError::PlanValidation {
1648            kind,
1649            message,
1650            plan_index: _,
1651        } => NbError::PlanValidation {
1652            kind,
1653            message,
1654            plan_index: Some(index),
1655        },
1656        other => NbError::PlanValidation {
1657            kind: "op_failed".into(),
1658            message: other.to_string(),
1659            plan_index: Some(index),
1660        },
1661    }
1662}
1663
1664fn validate_target(target: &NoteTarget) -> Result<(), NbError> {
1665    if target.value().trim().is_empty() {
1666        return Err(NbError::ValidationError {
1667            reason: "note target must not be empty".into(),
1668            location: None,
1669        });
1670    }
1671    Ok(())
1672}
1673
1674fn validate_create_path(path: &str, file: bool) -> Result<String, NbError> {
1675    // Validate the caller-supplied string before any normalization so
1676    // absolute and backslash forms cannot be silently rewritten.
1677    let raw = path.trim();
1678    if raw.is_empty() {
1679        return Err(NbError::ValidationError {
1680            reason: "path must not be empty".into(),
1681            location: None,
1682        });
1683    }
1684    if raw.starts_with('/') || raw.starts_with('\\') || Path::new(raw).is_absolute() {
1685        return Err(NbError::ValidationError {
1686            reason: "path must be notebook-relative (absolute paths refused)".into(),
1687            location: None,
1688        });
1689    }
1690    if raw.contains('\\') {
1691        return Err(NbError::ValidationError {
1692            reason: "path must not contain backslash separators".into(),
1693            location: None,
1694        });
1695    }
1696    if raw.contains('\0') {
1697        return Err(NbError::ValidationError {
1698            reason: "path must not contain NUL".into(),
1699            location: None,
1700        });
1701    }
1702    let path = normalize_rel(raw);
1703    if path.is_empty() {
1704        return Err(NbError::ValidationError {
1705            reason: "path must not be empty".into(),
1706            location: None,
1707        });
1708    }
1709    if path
1710        .split('/')
1711        .any(|p| p.is_empty() || p == "." || p == "..")
1712    {
1713        return Err(NbError::ValidationError {
1714            reason: "path must not contain empty, `.`, or `..` segments".into(),
1715            location: None,
1716        });
1717    }
1718    if file {
1719        let name = Path::new(&path)
1720            .file_name()
1721            .and_then(|s| s.to_str())
1722            .unwrap_or("");
1723        if name.is_empty() {
1724            return Err(NbError::ValidationError {
1725                reason: "create path must include a filename".into(),
1726                location: None,
1727            });
1728        }
1729    }
1730    Ok(path)
1731}
1732
1733fn normalize_rel(path: &str) -> String {
1734    path.trim()
1735        .trim_start_matches("./")
1736        .trim_matches('/')
1737        .replace('\\', "/")
1738}
1739
1740fn parent_path(path: &str) -> Option<String> {
1741    let p = Path::new(path).parent()?;
1742    let s = p.to_string_lossy().replace('\\', "/");
1743    if s.is_empty() || s == "." {
1744        None
1745    } else {
1746        Some(s)
1747    }
1748}
1749
1750/// Generate an nb-style timestamp basename for one-shot auto-name creates.
1751pub(crate) fn auto_filename(extension: &str) -> String {
1752    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1753    let secs = SystemTime::now()
1754        .duration_since(UNIX_EPOCH)
1755        .map(|d| d.as_secs())
1756        .unwrap_or(0);
1757    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1758    format!("{secs}-{n}.{extension}")
1759}
1760
1761pub(crate) fn join_folder_file(folder: Option<&str>, filename: &str) -> String {
1762    match folder {
1763        Some(f) if !f.trim().is_empty() => {
1764            format!("{}/{}", normalize_rel(f), filename.trim_start_matches('/'))
1765        }
1766        _ => filename.to_string(),
1767    }
1768}
1769
1770// Silence unused import warning if ByteString only used in tests later.
1771#[allow(dead_code)]
1772fn _bytestring_touch(b: ByteString) -> ByteString {
1773    b
1774}