rightkit-pdf 0.3.0

Product-neutral PDF engine: inspect, compose (source-text replace / add text / OCR correction), font subsetting, staged atomic save, plus optional page merge/select and text extraction
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! PDF editor save protocol (Dispatch C, lane C2): `prepare_pdf_save`'s structural recheck,
//! save-token lifecycle, and `commit_pdf_save`'s atomic write — `docs/PDF-EDITOR-NOW.md` §10.
//!
//! Owns the two-phase save handshake described in §10: Rust composes and structurally verifies a
//! candidate before ever handing it back (§10.1), the frontend independently renders/verifies it
//! (§10.2, entirely frontend-side — nothing here), and only then does a short-lived, single-use
//! token authorize one atomic disk write (§10.3). This file consumes the frozen
//! `compose_candidate` seam (`pdf_compose.rs`, lane C1) and the shared wire types it depends on
//! (`pdf_model.rs`, lane A1); it defines no new PDF-composition logic of its own.
//!
//! ## Judgment calls this file had to make (§10/§4/§14.1 leave these open)
//!
//! - **Byte channel shape for `prepare_pdf_save` (§4).** Incoming annotation bytes use base64 in
//!   normal JSON because WKWebView cannot complete this command with Tauri's raw request body.
//!   Candidate bytes return as a JSON byte array in the same response. This is larger than a raw
//!   response but reliable in WKWebView, while the raw response path fails during stream decoding.
//! - **No `AppState` exists in this codebase** (confirmed absent by `pdf_font.rs`'s and
//!   `pdf_inspect.rs`'s own notes) — this module introduces [`PdfSaveTokenStore`] as the Tauri
//!   `.manage()`-registered state for in-flight save tokens; wiring that `.manage()` call belongs
//!   to whichever lane owns `lib.rs`, out of this file's scope.
//! - **"Document session" (§10.3: "at most two candidates per document session"; §10.3: "token
//!   ... is invalidated after any source revision")** is not a concept this codebase threads
//!   anywhere yet, so both rules are scoped to `source_path`: at most two live tokens per source
//!   path (oldest evicted first), and a *successful* [`commit_pdf_save`] for a path invalidates
//!   every other outstanding token for that same path (the source's on-disk bytes just changed
//!   out from under them).
//! - **§11's frozen error taxonomy has no dedicated "token expired/unknown/replayed" variant.**
//!   Every token-lifecycle failure in [`commit_pdf_save`] (unknown token, expired token, already-
//!   consumed/replayed token, source changed since prepare) maps to
//!   [`PdfEditError::WriteConflict`] ("target changed before save") as the closest existing
//!   variant, per §14.1's own grouping of "expired/replayed/mismatched candidate token" as one
//!   fixture category distinct from `StaleSource` (which §10.1 reserves for the *prepare-time*
//!   source-SHA mismatch).
//! - **Single-use enforcement removes the token record on the very first `commit_pdf_save` call
//!   for it**, success or failure — a token that fails to commit (e.g. a same-path SHA race) is
//!   dead, not retryable; the caller must re-run `prepare_pdf_save` against fresh source bytes.
//!   This matches §10.3's "single-use" wording literally rather than only-consume-on-success.
//! - **"Same path" is a caller-supplied comparison.** [`resolve_commit_with`] takes the decision as
//!   a closure; [`resolve_commit`] compares the strings. A path alias (`dir/./memo.pdf`, a hard
//!   link, a case variant) defeats the strings, so [`crate::commit::commit_pdf_save`] passes a
//!   filesystem-identity comparison, and holds a per-destination lock across recheck, replacement
//!   and sibling invalidation. [`stage_prepared_save_against_base`] additionally refuses a
//!   candidate in which a page lost a resource it resolved in the bytes it was composed from.
//! - **Structural recheck (§10.1 step 7: "lopdf reopens candidate, checks page count/resources/
//!   content streams, & re-inspects expected text")** is implemented as: candidate parses via
//!   `lopdf::Document::load_mem`, has at least one page, every page's `/Contents` (when present)
//!   resolves without error, and every [`ExpectedTextCheck`] page has at least one text island
//!   (via `pdf_inspect::walk_page_graph`, the same walker `inspect_pdf_page` uses) whose text
//!   contains the expected substring. `ExpectedTextCheck` itself is a new type — §10.1 names the
//!   field (`expected_text: Vec<ExpectedTextCheck>`) but never defines the type; this file defines
//!   it as `{ page, text }`, the minimal shape `pdf_compose.rs` can populate per touched page and
//!   this recheck (and the frontend's `verifyPdfCandidate`, per §10.2) can check against.

use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use crate::inspect::{content_stream_ids, walk_page_graph};
use crate::model::{
    document_sha256, effective_pdf_edit_commands, sha256_hex, PdfEditCommand, PdfEditError,
};

/// A save token is valid for this long after `prepare_pdf_save` issues it (§10.3).
const TOKEN_TTL: Duration = Duration::from_secs(5 * 60);

/// §10.3: "Keep at most two candidates per document session" (scoped to `source_path` — see
/// module doc comment).
const MAX_TOKENS_PER_SOURCE: usize = 2;

// -------------------------------------------------------------------------------------------
// Wire types this file owns (§10.1 names these fields but leaves their shapes to this lane)
// -------------------------------------------------------------------------------------------

/// One page-level assertion a composed candidate must satisfy before `prepare_pdf_save` will hand
/// out a token for it: page `page` must contain `text` somewhere in its extracted text. Built from
/// each [`PdfEditCommand`]'s "after" text, one entry per touched page.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExpectedTextCheck {
    pub page: u32,
    pub text: String,
}

/// JSON result returned by `prepare_pdf_save`. Candidate bytes use a numeric array because
/// WKWebView's raw-response and large-base64 decoding paths are unreliable here.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreparedPdfSaveMeta {
    pub token: String,
    pub candidate_sha256: String,
    pub candidate_bytes: Vec<u8>,
    pub affected_pages: Vec<u32>,
    pub expected_text: Vec<ExpectedTextCheck>,
}

/// Result of a successful [`commit_pdf_save`].
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PdfCommitResult {
    pub target_path: String,
    pub document_sha256: String,
}

/// JSON request for `prepare_pdf_save`; byte content is base64 rather than a numeric JSON array.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreparePdfSaveRequestMeta {
    pub source_path: String,
    pub expected_source_sha256: String,
    pub annotation_pdf_base64: String,
    pub source_commands: Vec<PdfEditCommand>,
}

// -------------------------------------------------------------------------------------------
// Token store (Tauri-managed state; see module doc comment on the missing `AppState`)
// -------------------------------------------------------------------------------------------

struct SaveTokenRecord {
    source_path: String,
    /// Source document SHA-256 at the moment this candidate was staged (i.e. the same value
    /// `stage_prepared_save`'s caller already verified as `actual_source_sha256`). Stored on the
    /// record itself so `commit_pdf_save`'s same-path recheck (§10.3) has a prepare-time value to
    /// compare against without needing a separate session ledger.
    source_sha256: String,
    candidate_bytes: Vec<u8>,
    created_at: Instant,
}

#[derive(Default)]
struct TokenStoreInner {
    tokens: HashMap<String, SaveTokenRecord>,
    /// Insertion-ordered token ids per source path, oldest first — drives §10.3's two-candidate
    /// cap.
    by_source: HashMap<String, VecDeque<String>>,
}

/// In-memory save-token registry for the prepare/commit handshake (§10.3). One instance is
/// managed as Tauri state (`app.manage(PdfSaveTokenStore::default())`, wired by whichever lane
/// owns `lib.rs`) and shared across `prepare_pdf_save` and `commit_pdf_save`.
#[derive(Default)]
pub struct PdfSaveTokenStore {
    inner: Mutex<TokenStoreInner>,
}

impl PdfSaveTokenStore {
    /// Registers a newly composed+verified candidate under a fresh token, evicting the oldest
    /// token for `source_path` if this would exceed [`MAX_TOKENS_PER_SOURCE`]. Returns the token.
    fn insert(&self, source_path: &str, source_sha256: &str, candidate_bytes: Vec<u8>) -> String {
        let token = random_save_token();
        let mut inner = self.inner.lock().expect("token store mutex poisoned");

        let mut evicted = Vec::new();
        {
            let queue = inner.by_source.entry(source_path.to_string()).or_default();
            while queue.len() >= MAX_TOKENS_PER_SOURCE {
                match queue.pop_front() {
                    Some(oldest) => evicted.push(oldest),
                    None => break,
                }
            }
        }
        for oldest in evicted {
            inner.tokens.remove(&oldest);
        }
        inner
            .by_source
            .entry(source_path.to_string())
            .or_default()
            .push_back(token.clone());
        inner.tokens.insert(
            token.clone(),
            SaveTokenRecord {
                source_path: source_path.to_string(),
                source_sha256: source_sha256.to_string(),
                candidate_bytes,
                created_at: Instant::now(),
            },
        );
        token
    }

    /// Test-only, non-consuming liveness check: `Ok(())` if `token` exists and has not expired.
    /// (The caller-less `fetch_prepared_pdf_save_candidate` command that cloned the whole
    /// candidate out through this lookup was removed; `prepare_pdf_save` already returns the bytes.)
    #[cfg(test)]
    fn peek(&self, token: &str) -> Result<(), PdfEditError> {
        let inner = self.inner.lock().expect("token store mutex poisoned");
        let record = inner.tokens.get(token).ok_or(PdfEditError::WriteConflict)?;
        if record.created_at.elapsed() > TOKEN_TTL {
            return Err(PdfEditError::WriteConflict);
        }
        Ok(())
    }

    /// Single-use consume for [`commit_pdf_save`]: removes and returns the record regardless of
    /// whether it turns out to be expired (still consumed — see module doc comment on single-use
    /// semantics). Returns `Err(WriteConflict)` for an unknown/already-consumed/replayed token,
    /// or an expired one.
    fn consume(&self, token: &str) -> Result<SaveTokenRecord, PdfEditError> {
        let mut inner = self.inner.lock().expect("token store mutex poisoned");
        let Some(record) = inner.tokens.remove(token) else {
            return Err(PdfEditError::WriteConflict);
        };
        if let Some(queue) = inner.by_source.get_mut(&record.source_path) {
            queue.retain(|t| t != token);
        }
        if record.created_at.elapsed() > TOKEN_TTL {
            return Err(PdfEditError::WriteConflict);
        }
        Ok(record)
    }

    /// The source path `token` was staged against, or `None` for an unknown or already-consumed
    /// token. An expired token still reports it (consuming it is `consume`'s job): the commit
    /// needs the destination to serialise on before it touches the token.
    pub(crate) fn source_path_of(&self, token: &str) -> Option<String> {
        let inner = self.inner.lock().expect("token store mutex poisoned");
        inner
            .tokens
            .get(token)
            .map(|record| record.source_path.clone())
    }

    /// Every source path that has a live token, each once.
    pub(crate) fn source_paths(&self) -> Vec<String> {
        let inner = self.inner.lock().expect("token store mutex poisoned");
        inner
            .by_source
            .iter()
            .filter(|(_, queue)| !queue.is_empty())
            .map(|(path, _)| path.clone())
            .collect()
    }

    /// §10.3 "invalidated after any source revision" (scoped to `source_path` — see module doc
    /// comment): drops every remaining token for `source_path`, e.g. after a successful commit
    /// changes that path's on-disk bytes out from under any other outstanding token.
    pub fn invalidate_source(&self, source_path: &str) {
        let mut inner = self.inner.lock().expect("token store mutex poisoned");
        if let Some(queue) = inner.by_source.remove(source_path) {
            for token in queue {
                inner.tokens.remove(&token);
            }
        }
    }

    #[cfg(test)]
    fn live_token_count(&self, source_path: &str) -> usize {
        let inner = self.inner.lock().expect("token store mutex poisoned");
        inner
            .by_source
            .get(source_path)
            .map(|q| q.len())
            .unwrap_or(0)
    }
}

/// Mirrors `path_broker.rs`'s `random_token` shape (16 random bytes, lowercase hex) so save
/// tokens look and behave like every other opaque token this codebase hands to the frontend.
fn random_save_token() -> String {
    let mut bytes = [0_u8; 16];
    getrandom::fill(&mut bytes).expect("OS RNG unavailable");
    let mut token = String::with_capacity(32);
    for byte in bytes {
        use std::fmt::Write;
        let _ = write!(&mut token, "{byte:02x}");
    }
    token
}

// -------------------------------------------------------------------------------------------
// §10.1 — Prepare: structural recheck + staging (pure/testable core)
// -------------------------------------------------------------------------------------------

/// Verifies a just-composed candidate is structurally sound and contains every expected-text
/// assertion, then stages it in `store` under a fresh token. Separated from the `#[tauri::command]`
/// wrapper so it is directly unit-testable against hand-built [`lopdf::Document`] fixtures with no
/// filesystem/broker/IPC involved (mirrors `pdf_inspect.rs`'s `walk_page_graph`/`inspect_pdf_page`
/// split).
///
/// `actual_source_sha256` is the freshly read source bytes' digest; `expected_source_sha256` is
/// what the frontend's session believed it was editing. A mismatch means the backing file changed
/// since the edit session started (§10.1 step 2) — rejected before composition is even trusted.
///
/// This entry point sees only digests, so it cannot compare the candidate with the bytes it was
/// composed from. Prefer [`stage_prepared_save_against_base`], which also refuses a candidate in
/// which a page no longer resolves a font, XObject or graphics state it resolved before.
pub fn stage_prepared_save(
    store: &PdfSaveTokenStore,
    source_path: &str,
    expected_source_sha256: &str,
    actual_source_sha256: &str,
    candidate_bytes: Vec<u8>,
    affected_pages: Vec<u32>,
    expected_text: Vec<ExpectedTextCheck>,
) -> Result<PreparedPdfSaveMeta, PdfEditError> {
    stage_checked(
        store,
        source_path,
        expected_source_sha256,
        actual_source_sha256,
        None,
        candidate_bytes,
        affected_pages,
        expected_text,
    )
}

/// [`stage_prepared_save`] plus a comparison with the bytes the candidate was composed from
/// (`base_bytes`: the source, or the annotation-extended source `select_compose_base` picked).
/// Besides the structural recheck, every page of the candidate must still resolve every font,
/// XObject, graphics state, colour space, pattern, shading and property list name that page
/// resolved in `base_bytes`, to the same object: an edit may add a resource, never hide one
/// (adding a font to a page whose `/Resources` sat on an ancestor `/Pages` node once did). A
/// `base_bytes` that does not parse is `VerificationFailed`.
#[allow(clippy::too_many_arguments)]
pub fn stage_prepared_save_against_base(
    store: &PdfSaveTokenStore,
    source_path: &str,
    expected_source_sha256: &str,
    actual_source_sha256: &str,
    base_bytes: &[u8],
    candidate_bytes: Vec<u8>,
    affected_pages: Vec<u32>,
    expected_text: Vec<ExpectedTextCheck>,
) -> Result<PreparedPdfSaveMeta, PdfEditError> {
    stage_checked(
        store,
        source_path,
        expected_source_sha256,
        actual_source_sha256,
        Some(base_bytes),
        candidate_bytes,
        affected_pages,
        expected_text,
    )
}

#[allow(clippy::too_many_arguments)]
fn stage_checked(
    store: &PdfSaveTokenStore,
    source_path: &str,
    expected_source_sha256: &str,
    actual_source_sha256: &str,
    base_bytes: Option<&[u8]>,
    candidate_bytes: Vec<u8>,
    affected_pages: Vec<u32>,
    expected_text: Vec<ExpectedTextCheck>,
) -> Result<PreparedPdfSaveMeta, PdfEditError> {
    if expected_source_sha256 != actual_source_sha256 {
        return Err(PdfEditError::StaleSource);
    }

    structurally_verify_candidate_against(&candidate_bytes, &expected_text, base_bytes)?;

    let candidate_sha256 = sha256_hex(&candidate_bytes);
    let returned_candidate_bytes = candidate_bytes.clone();
    let token = store.insert(source_path, actual_source_sha256, candidate_bytes);

    Ok(PreparedPdfSaveMeta {
        token,
        candidate_sha256,
        candidate_bytes: returned_candidate_bytes,
        affected_pages,
        expected_text,
    })
}

/// §10.1 step 7: reopen the candidate independently of whatever composed it, and refuse to hand
/// out a token for anything that doesn't survive a fresh parse — "never trust your own composer
/// blindly." See module doc comment for exactly what this checks.
#[cfg(test)]
fn structurally_verify_candidate(
    candidate_bytes: &[u8],
    expected_text: &[ExpectedTextCheck],
) -> Result<(), PdfEditError> {
    structurally_verify_candidate_against(candidate_bytes, expected_text, None)
}

/// The structural recheck and - when the bytes the candidate was composed from are given - the
/// check that no page lost a resource name it resolved there.
fn structurally_verify_candidate_against(
    candidate_bytes: &[u8],
    expected_text: &[ExpectedTextCheck],
    base_bytes: Option<&[u8]>,
) -> Result<(), PdfEditError> {
    let doc =
        crate::inspect::load_pdf(candidate_bytes).map_err(|_| PdfEditError::VerificationFailed)?;

    let pages = doc.get_pages();
    if pages.is_empty() {
        return Err(PdfEditError::VerificationFailed);
    }

    for page_id in pages.values() {
        let page_obj = doc
            .get_object(*page_id)
            .map_err(|_| PdfEditError::VerificationFailed)?;
        let page_dict = page_obj
            .as_dict()
            .map_err(|_| PdfEditError::VerificationFailed)?;
        if let Ok(lopdf::Object::Reference(id)) = page_dict.get(b"Resources") {
            doc.get_object(*id)
                .map_err(|_| PdfEditError::VerificationFailed)?;
        }
        if let Ok(contents) = page_dict.get(b"Contents") {
            // A stream, an array of streams, or an indirect reference to an array of streams.
            if !matches!(
                contents,
                lopdf::Object::Reference(_) | lopdf::Object::Array(_)
            ) {
                return Err(PdfEditError::VerificationFailed);
            }
            let ids =
                content_stream_ids(&doc, contents).map_err(|_| PdfEditError::VerificationFailed)?;
            for id in ids {
                let obj = doc
                    .get_object(id)
                    .map_err(|_| PdfEditError::VerificationFailed)?;
                obj.as_stream()
                    .map_err(|_| PdfEditError::VerificationFailed)?;
            }
        }
    }

    if let Some(base_bytes) = base_bytes {
        let base =
            crate::inspect::load_pdf(base_bytes).map_err(|_| PdfEditError::VerificationFailed)?;
        let before = crate::inspect::resource_fingerprint(&base)
            .map_err(|_| PdfEditError::VerificationFailed)?;
        let after = crate::inspect::resource_fingerprint(&doc)
            .map_err(|_| PdfEditError::VerificationFailed)?;
        if !crate::inspect::resources_preserved(&before, &after) {
            return Err(PdfEditError::VerificationFailed);
        }
    }

    let candidate_sha256 = document_sha256(candidate_bytes);
    for check in expected_text {
        let graph = walk_page_graph(&doc, &candidate_sha256, check.page)
            .map_err(|_| PdfEditError::VerificationFailed)?;
        let found = graph
            .islands
            .iter()
            .any(|island| island.text.contains(&check.text));
        if !found {
            return Err(PdfEditError::VerificationFailed);
        }
    }

    Ok(())
}

/// Picks which bytes `prepare_pdf_save` should compose `source_commands` on top of. The frontend
/// sends pdf.js's `saveDocument()` output as `annotation_pdf`: a one-byte sentinel `[0]` when there
/// are no annotation edits, or (per pdf.js's own incremental-save format) the original file bytes
/// verbatim followed by appended annotation objects/xref when there are. Composing on top of the
/// annotation bytes (rather than discarding them) is what makes annotation edits survive Save.
pub fn select_compose_base<'a>(
    source: &'a [u8],
    annotation_pdf: &'a [u8],
) -> Result<&'a [u8], PdfEditError> {
    if annotation_pdf.len() <= 1 {
        return Ok(source);
    }
    if annotation_pdf.len() > source.len() && annotation_pdf.starts_with(source) {
        return Ok(annotation_pdf);
    }
    Err(PdfEditError::AnnotationSerializationFailed)
}

/// Derives one [`ExpectedTextCheck`] per page touched by `commands`, from each command's "after"
/// text — the substring `structurally_verify_candidate` (and the frontend's `verifyPdfCandidate`,
/// §10.2) must find on that page post-composition.
pub fn expected_text_checks(commands: &[PdfEditCommand]) -> Vec<ExpectedTextCheck> {
    effective_pdf_edit_commands(commands)
        .into_iter()
        .map(|command| match command {
            PdfEditCommand::ReplaceSourceText { locator, after, .. } => ExpectedTextCheck {
                page: locator.page,
                text: after.text.clone(),
            },
            PdfEditCommand::AddText { page, text, .. } => ExpectedTextCheck {
                page: *page,
                text: text.clone(),
            },
            PdfEditCommand::CorrectOcrLine { page, text, .. } => ExpectedTextCheck {
                page: *page,
                text: text.clone(),
            },
        })
        .collect()
}

// -------------------------------------------------------------------------------------------
// §10.3 — Commit: token resolution + atomic write (pure/testable core + Tauri command)
// -------------------------------------------------------------------------------------------

/// Resolves and consumes `token`, returning the bytes to write and the commit result — but
/// performs no filesystem I/O itself beyond what `read_current_source_for_recheck` does.
/// `read_current_source_for_recheck` is called only for a same-path Save (§10.3: "Same-path Save
/// rechecks source SHA immediately before atomic replacement") and must return the *current*
/// on-disk bytes at `source_path`, compared against the SHA-256 recorded when the token's
/// candidate was staged ([`SaveTokenRecord::source_sha256`]). Kept filesystem-free otherwise so
/// token lifecycle (expiry/replay/conflict) is directly unit-testable.
///
/// "Same path" here is string equality, which a path alias (`/tmp/./memo.pdf`, a hard link, a case
/// variant on a case-insensitive volume) defeats. A host that touches the filesystem should call
/// [`resolve_commit_with`] with a real file-identity comparison; [`crate::commit::commit_pdf_save`]
/// does.
pub fn resolve_commit<F>(
    store: &PdfSaveTokenStore,
    token: &str,
    target_path: Option<String>,
    read_current_source_for_recheck: F,
) -> Result<(String, Vec<u8>, PdfCommitResult), PdfEditError>
where
    F: FnOnce(&str) -> Result<Vec<u8>, PdfEditError>,
{
    resolve_commit_with(
        store,
        token,
        target_path,
        |source, target| source == target,
        read_current_source_for_recheck,
    )
}

/// [`resolve_commit`] with the "is the target the source file?" decision supplied by the caller:
/// `same_file(source_path, target_path)` is called once, after the token is consumed, and the
/// source recheck runs exactly when it returns `true`. Passing a comparison of filesystem
/// identities (device and file id, canonical path as the fallback) closes the alias bypass that
/// plain string equality leaves open.
pub fn resolve_commit_with<F, S>(
    store: &PdfSaveTokenStore,
    token: &str,
    target_path: Option<String>,
    same_file: S,
    read_current_source_for_recheck: F,
) -> Result<(String, Vec<u8>, PdfCommitResult), PdfEditError>
where
    F: FnOnce(&str) -> Result<Vec<u8>, PdfEditError>,
    S: FnOnce(&str, &str) -> bool,
{
    let record = store.consume(token)?;
    let target = target_path.unwrap_or_else(|| record.source_path.clone());

    if same_file(&record.source_path, &target) {
        let current_bytes = read_current_source_for_recheck(&record.source_path)?;
        let current_sha256 = document_sha256(&current_bytes);
        if current_sha256 != record.source_sha256 {
            return Err(PdfEditError::WriteConflict);
        }
    }

    let document_sha256_value = document_sha256(&record.candidate_bytes);
    let result = PdfCommitResult {
        target_path: target.clone(),
        document_sha256: document_sha256_value,
    };
    Ok((record.source_path, record.candidate_bytes, result))
}

// -------------------------------------------------------------------------------------------
// Tests (§14.1: token/stale/conflict fixtures)
// -------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// One-page PDF whose single `Tj` run is exactly the text
    /// `structurally_verify_candidate`'s expected-text recheck looks for — the crate's shared
    /// `build_one_page_pdf_bytes` fixture (base-14 Helvetica/WinAnsiEncoding, verified against real
    /// lopdf/PDF-spec structure).
    use crate::test_fixtures::build_one_page_pdf_bytes as build_pdf;

    fn hello_pdf() -> Vec<u8> {
        build_pdf(b"BT /F1 12 Tf 72 700 Td (Hello) Tj ET")
    }

    #[test]
    fn structural_recheck_accepts_wellformed_candidate_with_matching_text() {
        let bytes = hello_pdf();
        let checks = vec![ExpectedTextCheck {
            page: 1,
            text: "Hello".to_string(),
        }];
        assert!(structurally_verify_candidate(&bytes, &checks).is_ok());
    }

    #[test]
    fn structural_recheck_accepts_contents_that_is_an_indirect_array_of_streams() {
        let doc = crate::test_fixtures::custom_page_pdf(
            |d| vec![("F1", crate::test_fixtures::helvetica_font(d))],
            &[b"BT /F1 12 Tf 72 700 Td ", b"(Hello) Tj ET"],
            true,
        );
        let bytes = crate::test_fixtures::pdf_bytes(&doc);
        let checks = vec![ExpectedTextCheck {
            page: 1,
            text: "Hello".to_string(),
        }];
        assert!(structurally_verify_candidate(&bytes, &checks).is_ok());
    }

    #[test]
    fn structural_recheck_rejects_missing_expected_text() {
        let bytes = hello_pdf();
        let checks = vec![ExpectedTextCheck {
            page: 1,
            text: "Goodbye".to_string(),
        }];
        let err = structurally_verify_candidate(&bytes, &checks).unwrap_err();
        assert!(matches!(err, PdfEditError::VerificationFailed));
    }

    #[test]
    fn structural_recheck_rejects_unparseable_candidate() {
        let bytes = b"not a pdf at all".to_vec();
        let err = structurally_verify_candidate(&bytes, &[]).unwrap_err();
        assert!(matches!(err, PdfEditError::VerificationFailed));
    }

    #[test]
    fn stage_prepared_save_rejects_stale_source_before_touching_candidate() {
        let store = PdfSaveTokenStore::default();
        let bytes = hello_pdf();
        let err = stage_prepared_save(
            &store,
            "/doc.pdf",
            "sha-expected",
            "sha-actual-different",
            bytes,
            vec![1],
            vec![],
        )
        .unwrap_err();
        assert!(matches!(err, PdfEditError::StaleSource));
        assert_eq!(store.live_token_count("/doc.pdf"), 0);
    }

    #[test]
    fn stage_prepared_save_issues_token_for_valid_candidate() {
        let store = PdfSaveTokenStore::default();
        let bytes = hello_pdf();
        let checks = vec![ExpectedTextCheck {
            page: 1,
            text: "Hello".to_string(),
        }];
        let meta =
            stage_prepared_save(&store, "/doc.pdf", "sha-x", "sha-x", bytes, vec![1], checks)
                .expect("valid candidate stages");
        assert_eq!(meta.token.len(), 32);
        assert_eq!(meta.affected_pages, vec![1]);
        assert_eq!(store.live_token_count("/doc.pdf"), 1);
    }

    #[test]
    fn stage_prepared_save_rejects_verification_failure_without_issuing_token() {
        let store = PdfSaveTokenStore::default();
        let bytes = hello_pdf();
        let checks = vec![ExpectedTextCheck {
            page: 1,
            text: "Not Present".to_string(),
        }];
        let err = stage_prepared_save(&store, "/doc.pdf", "sha-x", "sha-x", bytes, vec![1], checks)
            .unwrap_err();
        assert!(matches!(err, PdfEditError::VerificationFailed));
        assert_eq!(store.live_token_count("/doc.pdf"), 0);
    }

    #[test]
    fn store_evicts_oldest_token_beyond_two_per_source() {
        let store = PdfSaveTokenStore::default();
        let t1 = store.insert("/doc.pdf", "sha", hello_pdf());
        let t2 = store.insert("/doc.pdf", "sha", hello_pdf());
        let t3 = store.insert("/doc.pdf", "sha", hello_pdf());

        assert_eq!(store.live_token_count("/doc.pdf"), 2);
        assert!(store.peek(&t1).is_err(), "oldest token must be evicted");
        assert!(store.peek(&t2).is_ok());
        assert!(store.peek(&t3).is_ok());
    }

    #[test]
    fn peek_unknown_token_is_write_conflict() {
        let store = PdfSaveTokenStore::default();
        let err = store.peek("does-not-exist").unwrap_err();
        assert!(matches!(err, PdfEditError::WriteConflict));
    }

    #[test]
    fn commit_consumes_token_so_replay_fails() {
        let store = PdfSaveTokenStore::default();
        let sha = document_sha256(&hello_pdf());
        let token = store.insert("/doc.pdf", &sha, hello_pdf());

        let first = resolve_commit(&store, &token, None, |_| Ok(hello_pdf()));
        assert!(first.is_ok());

        let replay = resolve_commit(&store, &token, None, |_| Ok(hello_pdf()));
        let err = replay.unwrap_err();
        assert!(matches!(err, PdfEditError::WriteConflict));
    }

    #[test]
    fn commit_rejects_expired_token() {
        let store = PdfSaveTokenStore::default();
        let token = random_save_token();
        {
            let mut inner = store.inner.lock().unwrap();
            inner
                .by_source
                .entry("/doc.pdf".to_string())
                .or_default()
                .push_back(token.clone());
            inner.tokens.insert(
                token.clone(),
                SaveTokenRecord {
                    source_path: "/doc.pdf".to_string(),
                    source_sha256: document_sha256(&hello_pdf()),
                    candidate_bytes: hello_pdf(),
                    created_at: Instant::now() - TOKEN_TTL - Duration::from_secs(1),
                },
            );
        }

        let err = resolve_commit(&store, &token, None, |_| Ok(hello_pdf())).unwrap_err();
        assert!(matches!(err, PdfEditError::WriteConflict));
        // Expiry still consumes the token (single-use is unconditional — see module doc comment).
        assert!(store.peek(&token).is_err());
    }

    #[test]
    fn commit_rejects_source_changed_since_prepare_for_same_path_save() {
        let store = PdfSaveTokenStore::default();
        let prepare_time_sha = document_sha256(&hello_pdf());
        let token = store.insert("/doc.pdf", &prepare_time_sha, hello_pdf());
        let different_current_bytes = build_pdf(b"BT /F1 12 Tf 72 700 Td (Changed) Tj ET");

        let err = resolve_commit(
            &store,
            &token,
            None, // same-path Save
            |_| Ok(different_current_bytes.clone()),
        )
        .unwrap_err();
        assert!(matches!(err, PdfEditError::WriteConflict));
    }

    #[test]
    fn commit_allows_same_path_save_when_source_unchanged() {
        let store = PdfSaveTokenStore::default();
        let source_bytes = hello_pdf();
        let prepare_time_sha = document_sha256(&source_bytes);
        let token = store.insert("/doc.pdf", &prepare_time_sha, source_bytes.clone());

        let (source_path, bytes, result) =
            resolve_commit(&store, &token, None, |_| Ok(source_bytes.clone()))
                .expect("unchanged source commits cleanly");
        assert_eq!(source_path, "/doc.pdf");
        assert_eq!(result.target_path, "/doc.pdf");
        assert_eq!(bytes, source_bytes);
    }

    #[test]
    fn commit_save_as_does_not_recheck_source_sha() {
        // Save As targets a different path than the source; §10.3 only requires the immediate
        // SHA recheck for a *same-path* Save, so this must succeed even though the closure below
        // would fail the recheck if it were (wrongly) invoked.
        let store = PdfSaveTokenStore::default();
        let sha = document_sha256(&hello_pdf());
        let token = store.insert("/doc.pdf", &sha, hello_pdf());

        let (source_path, _bytes, result) =
            resolve_commit(&store, &token, Some("/doc-copy.pdf".to_string()), |_| {
                panic!("same-path recheck must not run for Save As")
            })
            .expect("Save As commits without a same-path recheck");
        assert_eq!(source_path, "/doc.pdf");
        assert_eq!(result.target_path, "/doc-copy.pdf");
    }

    #[test]
    fn invalidate_source_drops_every_remaining_token_for_that_path() {
        let store = PdfSaveTokenStore::default();
        let sha = document_sha256(&hello_pdf());
        let t1 = store.insert("/doc.pdf", &sha, hello_pdf());
        assert!(store.peek(&t1).is_ok());

        store.invalidate_source("/doc.pdf");

        assert!(store.peek(&t1).is_err());
        assert_eq!(store.live_token_count("/doc.pdf"), 0);
    }

    #[test]
    fn select_compose_base_uses_source_for_sentinel_annotation_bytes() {
        let source = hello_pdf();
        let sentinel = vec![0u8];
        let base = select_compose_base(&source, &sentinel).expect("sentinel selects source");
        assert_eq!(base, source.as_slice());
    }

    #[test]
    fn select_compose_base_uses_annotation_bytes_when_incremental_update() {
        let source = hello_pdf();
        let mut annotation_pdf = source.clone();
        annotation_pdf.extend_from_slice(b"\n% appended annotation objects + new xref\n");
        let base =
            select_compose_base(&source, &annotation_pdf).expect("incremental update selects it");
        assert_eq!(base, annotation_pdf.as_slice());
    }

    #[test]
    fn select_compose_base_rejects_annotation_bytes_not_extending_source() {
        let source = hello_pdf();
        let unrelated = build_pdf(b"BT /F1 12 Tf 72 700 Td (Different) Tj ET");
        let err = select_compose_base(&source, &unrelated).unwrap_err();
        assert!(matches!(err, PdfEditError::AnnotationSerializationFailed));
    }

    #[test]
    fn expected_text_checks_derives_one_entry_per_command() {
        use crate::model::{
            PdfColor, PdfPoint, PdfRect, PdfSourceLocator, PdfTextAppearance, PdfTextEditState,
        };

        let appearance = PdfTextAppearance {
            font_id: "f".to_string(),
            family: "F".to_string(),
            size_pt: 12.0,
            color: PdfColor {
                r: 0.0,
                g: 0.0,
                b: 0.0,
                alpha: 1.0,
            },
        };
        let commands = vec![
            PdfEditCommand::ReplaceSourceText {
                id: "e1".to_string(),
                locator: PdfSourceLocator {
                    document_sha256: "sha".to_string(),
                    page: 2,
                    spans: vec![],
                    island_digest: "digest".to_string(),
                },
                before: PdfTextEditState {
                    text: "old".to_string(),
                    appearance: appearance.clone(),
                },
                after: PdfTextEditState {
                    text: "new text".to_string(),
                    appearance: appearance.clone(),
                },
                available_bounds: PdfRect {
                    x: 0.0,
                    y: 0.0,
                    width: 10.0,
                    height: 10.0,
                },
            },
            PdfEditCommand::AddText {
                id: "a1".to_string(),
                page: 3,
                anchor: PdfPoint { x: 1.0, y: 1.0 },
                text: "added text".to_string(),
                appearance,
            },
        ];

        let checks = expected_text_checks(&commands);
        assert_eq!(checks.len(), 2);
        assert_eq!(
            checks[0],
            ExpectedTextCheck {
                page: 2,
                text: "new text".to_string()
            }
        );
        assert_eq!(
            checks[1],
            ExpectedTextCheck {
                page: 3,
                text: "added text".to_string()
            }
        );
    }

    #[test]
    fn expected_text_checks_last_ocr_correction_wins_by_line_id() {
        use crate::model::{PdfColor, PdfOcrBackgroundProof, PdfRect, PdfTextAppearance};
        let appearance = PdfTextAppearance {
            font_id: "f".to_string(),
            family: "F".to_string(),
            size_pt: 12.0,
            color: PdfColor {
                r: 0.0,
                g: 0.0,
                b: 0.0,
                alpha: 1.0,
            },
        };
        let correction = |id: &str, text: &str| PdfEditCommand::CorrectOcrLine {
            id: id.to_string(),
            page: 4,
            line_id: "line-1".to_string(),
            rect: PdfRect {
                x: 1.0,
                y: 1.0,
                width: 100.0,
                height: 20.0,
            },
            text: text.to_string(),
            appearance: appearance.clone(),
            cover_color: PdfColor {
                r: 1.0,
                g: 1.0,
                b: 1.0,
                alpha: 1.0,
            },
            background_proof: PdfOcrBackgroundProof::NearUniform,
        };
        let checks = expected_text_checks(&[correction("old", "old"), correction("new", "new")]);
        assert_eq!(
            checks,
            vec![ExpectedTextCheck {
                page: 4,
                text: "new".to_string()
            }]
        );
    }
    // -----------------------------------------------------------------------------------
    // Second Astra read, 2026-10-11: findings 2, 5, 6 (save side)
    // -----------------------------------------------------------------------------------

    /// The source: `/Resources` (F1, Im1) on the `/Pages` node only.
    fn inherited_source() -> Vec<u8> {
        crate::test_fixtures::pdf_bytes(&crate::test_fixtures::inherited_resources_pdf(
            b"BT /F1 12 Tf 72 700 Td (Existing) Tj ET /Im1 Do",
        ))
    }

    /// What the old composer wrote for that page: page-local resources holding only a new font.
    fn candidate_that_hides_the_inherited_resources(source: &[u8]) -> Vec<u8> {
        let mut doc = lopdf::Document::load_mem(source).expect("source loads");
        let page_id = doc.get_pages()[&1];
        let some_object = *doc.objects.keys().next().expect("an object");
        if let Ok(lopdf::Object::Dictionary(page)) = doc.get_object_mut(page_id) {
            page.set(
                "Resources",
                lopdf::dictionary! { "Font" => lopdf::dictionary! { "VREdit1" => some_object } },
            );
        }
        crate::test_fixtures::pdf_bytes(&doc)
    }

    #[test]
    fn finding2_staging_against_the_base_refuses_a_page_that_lost_its_inherited_resources() {
        let source = inherited_source();
        let sha = document_sha256(&source);
        let hidden = candidate_that_hides_the_inherited_resources(&source);
        let store = PdfSaveTokenStore::default();

        let err = stage_prepared_save_against_base(
            &store,
            "/doc.pdf",
            &sha,
            &sha,
            &source,
            hidden.clone(),
            vec![1],
            vec![],
        )
        .unwrap_err();
        assert!(matches!(err, PdfEditError::VerificationFailed));
        assert_eq!(store.live_token_count("/doc.pdf"), 0, "no token for it");

        // The digest-only entry point cannot see the source, so it cannot tell: that is why the
        // composer checks too, and why the against-base entry point exists.
        stage_prepared_save(&store, "/doc.pdf", &sha, &sha, hidden, vec![1], vec![])
            .expect("structurally fine, which is all the digest-only path can check");
    }

    #[test]
    fn finding2_staging_against_the_base_accepts_a_candidate_that_changes_no_resource() {
        let source = inherited_source();
        let sha = document_sha256(&source);
        let store = PdfSaveTokenStore::default();
        stage_prepared_save_against_base(
            &store,
            "/doc.pdf",
            &sha,
            &sha,
            &source,
            source.clone(),
            vec![],
            vec![],
        )
        .expect("a candidate identical to its base");
    }

    #[test]
    fn finding2_an_unparseable_base_is_a_verification_failure() {
        let store = PdfSaveTokenStore::default();
        let err = stage_prepared_save_against_base(
            &store,
            "/doc.pdf",
            "sha",
            "sha",
            b"not a pdf",
            hello_pdf(),
            vec![],
            vec![],
        )
        .unwrap_err();
        assert!(matches!(err, PdfEditError::VerificationFailed));
    }

    #[test]
    fn finding6_the_recheck_runs_when_the_comparison_says_the_target_is_the_source() {
        let store = PdfSaveTokenStore::default();
        let sha = document_sha256(&hello_pdf());
        let changed = build_pdf(b"BT /F1 12 Tf 72 700 Td (Changed) Tj ET");

        // Plain string equality is fooled by an alias: no recheck, so a newer file is replaced.
        let token = store.insert("/tmp/doc.pdf", &sha, hello_pdf());
        resolve_commit(&store, &token, Some("/tmp/./doc.pdf".to_string()), |_| {
            panic!("string comparison skips the recheck for an alias")
        })
        .expect("the alias gets past string equality");

        // The same alias with a file-identity comparison is rechecked and refused.
        let token = store.insert("/tmp/doc.pdf", &sha, hello_pdf());
        let err = resolve_commit_with(
            &store,
            &token,
            Some("/tmp/./doc.pdf".to_string()),
            |source, target| {
                assert_eq!((source, target), ("/tmp/doc.pdf", "/tmp/./doc.pdf"));
                true
            },
            |_| Ok(changed.clone()),
        )
        .unwrap_err();
        assert!(matches!(err, PdfEditError::WriteConflict));

        // A comparison that says "different file" skips it, as Save As always has.
        let token = store.insert("/tmp/doc.pdf", &sha, hello_pdf());
        resolve_commit_with(
            &store,
            &token,
            Some("/tmp/other.pdf".to_string()),
            |_, _| false,
            |_| panic!("a different file is not rechecked"),
        )
        .expect("Save As");
    }

    #[test]
    fn finding5_the_store_reports_a_tokens_source_and_every_live_source() {
        let store = PdfSaveTokenStore::default();
        let t1 = store.insert("/a.pdf", "sha", hello_pdf());
        store.insert("/b.pdf", "sha", hello_pdf());
        assert_eq!(store.source_path_of(&t1).as_deref(), Some("/a.pdf"));
        assert_eq!(store.source_path_of("unknown"), None);
        let mut sources = store.source_paths();
        sources.sort();
        assert_eq!(sources, vec!["/a.pdf".to_string(), "/b.pdf".to_string()]);
        resolve_commit(&store, &t1, Some("/c.pdf".to_string()), |_| Ok(vec![])).expect("save as");
        assert_eq!(store.source_path_of(&t1), None, "consumed");
    }
}