binscout 0.9.1

Headless, agent-first binary analysis: functions, CFGs, xrefs, strings, and IR over a JSON CLI or MCP server
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
//! Versioned, identity-checked annotation interchange.
//!
//! [`AnnotationDocument`] is the portable form of a project's renames and
//! comments: a format [`ANNOTATION_FORMAT_REVISION`], the binary's SHA-256
//! plus size, the effective loader [`mapping`](crate::db::StoredMapping),
//! and the sorted non-empty annotation rows. Host paths and analysis
//! snapshots are never included, so a document moves analyst work without
//! leaking machine layout or disposable derived rows.
//!
//! [`build_document`] serializes a project snapshot to capped JSON and
//! [`parse_document`] plus [`validate_document`] check a candidate before
//! anything is written: identity, mapping, duplicates, row/text/storage
//! budgets, rename targets, and merge conflicts. Callers persist only the
//! returned per-address changes in one transaction and update memory only
//! after that commit succeeds, so a failing final row leaves the DB and the
//! in-memory annotations untouched.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::db::{self, Annotation, StoredMapping};
use crate::error::{Error, Result};

/// Format revision of [`AnnotationDocument`]; imports reject anything else.
pub const ANNOTATION_FORMAT_REVISION: u32 = 1;
/// Cap on serialized interchange documents in both directions (16 MiB).
///
/// Export fails explicitly past this instead of emitting a document the
/// importer cannot accept; import rejects larger inputs before parsing.
pub const MAX_TRANSFER_BYTES: usize = 16 * 1024 * 1024;

/// Lowercase hex SHA-256 of `bytes` (64 chars, no extra dependency).
#[must_use]
pub fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut s = String::with_capacity(64);
    for b in digest {
        s.push(char::from_digit(u32::from(b >> 4), 16).expect("hex digit"));
        s.push(char::from_digit(u32::from(b & 0xf), 16).expect("hex digit"));
    }
    s
}

/// One portable annotation row: rename and/or comment at `addr`.
///
/// Missing/`null` fields are absent on import (existing values untouched);
/// an empty string clears the supplied field. Export emits only non-empty
/// fields of non-empty rows, sorted by address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnnotationRow {
    /// Annotated address (rename rows must be known function entries).
    pub addr: u64,
    /// Function rename (`None` = absent, `Some("")` = clear).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rename: Option<String>,
    /// Free-text comment at any address (`None` = absent, `Some("")` = clear).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

/// One portable function-seed row: an agent-asserted code address plus an
/// optional 32-bit ARM decode mode.
///
/// Exported for every stored [`crate::db::FuncSeed`], including excluded
/// rows: exclusion is analyst data ("this isn't a function") and must
/// survive transfers. Rows sort by address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FuncSeedRow {
    /// Asserted code address (any address, like comments).
    pub addr: u64,
    /// Decode-mode override (`"arm"`/`"thumb"`; absent = project arch).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<crate::analysis::SeedMode>,
    /// Whether the address is excluded from seeding (kept as data).
    #[serde(default)]
    pub excluded: bool,
}

/// Portable annotation set for one binary under one loader mapping.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnnotationDocument {
    /// Format revision (see [`ANNOTATION_FORMAT_REVISION`]).
    pub revision: u32,
    /// Lowercase hex SHA-256 of the analyzed binary.
    pub sha256: String,
    /// Binary size in bytes.
    pub size: u64,
    /// Effective loader mapping the rows were taken over.
    pub mapping: StoredMapping,
    /// Non-empty rows, sorted by address.
    pub annotations: Vec<AnnotationRow>,
    /// Stored function seeds, sorted by address (excluded rows included).
    ///
    /// Defaults to empty so documents written before seed transfer still
    /// import; the format revision is unchanged (additive field).
    #[serde(default)]
    pub func_seeds: Vec<FuncSeedRow>,
}

/// Marker prefix of a structured type-hint comment (see [`TypeHint`]).
///
/// A comment starting with this prefix carries JSON struct-layout/sizeof
/// metadata after it; any other comment is plain free text. The hint stays
/// an ordinary comment everywhere else: it counts against the same 8 KiB
/// text cap, exports/imports as an opaque string through
/// [`build_document`]/[`validate_document`], and is never enforced against
/// the binary.
pub const TYPE_HINT_PREFIX: &str = "type-hint:";

/// Wire `kind` tag of [`TypeHint`] JSON; the only kind defined today.
const TYPE_HINT_STRUCT_KIND: &str = "struct";

/// One struct field of a [`TypeHint`]: byte `offset` and `size` within the
/// struct. Overlapping fields are allowed (unions); each field's end must
/// still lie within the struct size.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeField {
    /// Field name (non-empty).
    pub name: String,
    /// Byte offset of the field within the struct.
    pub offset: u64,
    /// Field size in bytes (non-zero).
    pub size: u64,
}

/// Structured struct-layout/sizeof hint stored as a comment.
///
/// There is no type system: this is documentation for agents, formatted by
/// [`format_type_hint`] into the comment channel (`comment` accepts any
/// address, [`Project::set_type_hint`](crate::Project::set_type_hint))
/// and read back with [`parse_type_hint`]. Nothing validates the layout
/// against the binary; a wrong hint misleads exactly like a wrong
/// free-text comment.
///
/// # Example
///
/// ```
/// use binscout::annotations::{
///     TypeField, TypeHint, build_document, format_type_hint, parse_document,
///     parse_type_hint, sha256_hex, validate_document,
/// };
/// use binscout::db::{Annotation, StoredMapping};
/// use std::collections::BTreeMap;
///
/// let hint = TypeHint {
///     name: "Foo".to_string(),
///     size: 24,
///     fields: vec![
///         TypeField { name: "a".to_string(), offset: 0, size: 8 },
///         TypeField { name: "b".to_string(), offset: 8, size: 4 },
///     ],
/// };
/// let comment = format_type_hint(&hint).expect("valid hint");
/// assert_eq!(parse_type_hint(&comment).expect("parses"), Some(hint.clone()));
///
/// // The hint rides the comment channel through export/import unchanged.
/// let bytes = b"fake-binary";
/// let sha = sha256_hex(bytes);
/// let mut annotations = BTreeMap::new();
/// annotations.insert(
///     0x1000u64,
///     Annotation { name: None, comment: Some(comment.clone()) },
/// );
/// let text =
///     build_document(
///         &sha,
///         bytes.len() as u64,
///         &StoredMapping::Auto,
///         &annotations,
///         &BTreeMap::new(),
///     )
///     .expect("export");
/// let doc = parse_document(&text).expect("parse");
/// let changes = validate_document(
///     &doc,
///     &sha,
///     bytes.len() as u64,
///     &StoredMapping::Auto,
///     &|_| false,
///     &BTreeMap::new(),
///     false,
/// )
/// .expect("valid");
/// assert_eq!(changes.len(), 1);
/// let back = changes[&0x1000u64].clone().expect("row stored");
/// assert_eq!(
///     parse_type_hint(back.comment.as_deref().expect("comment")).expect("parses"),
///     Some(hint)
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeHint {
    /// Struct name (non-empty).
    pub name: String,
    /// `sizeof` the struct in bytes (non-zero).
    pub size: u64,
    /// Field layouts; may be empty for an opaque struct with known size.
    pub fields: Vec<TypeField>,
}

/// Wire form of [`TypeHint`]: the same shape plus the `kind` tag, so
/// future hint kinds fail closed on parse instead of misdecoding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct WireHint {
    kind: String,
    name: String,
    size: u64,
    #[serde(default)]
    fields: Vec<TypeField>,
}

impl From<&TypeHint> for WireHint {
    fn from(h: &TypeHint) -> Self {
        Self {
            kind: TYPE_HINT_STRUCT_KIND.to_string(),
            name: h.name.clone(),
            size: h.size,
            fields: h.fields.clone(),
        }
    }
}

/// Check a hint's shape: names, sizes, and field bounds.
///
/// Overlapping fields are allowed (unions); each field's checked end must
/// lie within the struct size. Shape only: never consults the binary.
///
/// # Errors
/// [`Error::Invalid`] on empty names, zero sizes, integer overflow, or a
/// field ending past the struct size.
fn check_hint_shape(hint: &TypeHint) -> Result<()> {
    if hint.name.trim().is_empty() {
        return Err(Error::Invalid(
            "type hint needs a non-empty struct name".to_string(),
        ));
    }
    if hint.size == 0 {
        return Err(Error::Invalid(
            "type hint needs a non-zero struct size".to_string(),
        ));
    }
    for f in &hint.fields {
        if f.name.trim().is_empty() {
            return Err(Error::Invalid(
                "type hint needs a non-empty field name".to_string(),
            ));
        }
        if f.size == 0 {
            return Err(Error::Invalid(format!(
                "type hint field {:?} needs a non-zero size",
                f.name
            )));
        }
        let end = f.offset.checked_add(f.size).ok_or_else(|| {
            Error::Invalid(format!(
                "type hint field {:?} offset {:#x} plus size {:#x} overflows",
                f.name, f.offset, f.size
            ))
        })?;
        if end > hint.size {
            return Err(Error::Invalid(format!(
                "type hint field {:?} ends at {end} past struct size {}",
                f.name, hint.size
            )));
        }
    }
    Ok(())
}

/// Parse the wire JSON of a [`TypeHint`] (the object after [`TYPE_HINT_PREFIX`]).
///
/// Accepts the same `{"kind":"struct","name":..,"size":..,"fields":[..]}`
/// shape [`format_type_hint`] emits, so CLI `--json` and MCP `hint`
/// strings round-trip without the comment channel. Shape only: never
/// consults the binary.
///
/// # Errors
/// [`Error::Invalid`] on malformed JSON, a wrong `kind`, or shape
/// violations (see [`TypeHint`]).
pub fn parse_type_hint_json(json: &str) -> Result<TypeHint> {
    let wire: WireHint = serde_json::from_str(json.trim())
        .map_err(|e| Error::Invalid(format!("malformed type hint: {e}")))?;
    if wire.kind != TYPE_HINT_STRUCT_KIND {
        return Err(Error::Invalid(format!(
            "unsupported type hint kind {:?} (expected {TYPE_HINT_STRUCT_KIND:?})",
            wire.kind
        )));
    }
    let hint = TypeHint {
        name: wire.name,
        size: wire.size,
        fields: wire.fields,
    };
    check_hint_shape(&hint)?;
    Ok(hint)
}

/// Render a [`TypeHint`] as its wire JSON value.
///
/// The same `{"kind":"struct",..}` object [`format_type_hint`] stores
/// after [`TYPE_HINT_PREFIX`], so a `type-hint --get` / `get_type_hint`
/// `hint` accepts its own value back as `--json` / `hint`.
#[must_use]
pub fn type_hint_json(hint: &TypeHint) -> serde_json::Value {
    serde_json::to_value(WireHint::from(hint)).expect("type hint serializes")
}
/// Format `hint` as a comment-channel string: [`TYPE_HINT_PREFIX`] plus
/// compact JSON (`{"kind":"struct","name":..,"size":..,"fields":[..]}`).
///
/// The result stores via
/// [`Project::set_comment`](crate::Project::set_comment) (or
/// [`Project::set_type_hint`](crate::Project::set_type_hint)) under the
/// same any-address, 8 KiB-cap rules as any comment.
///
/// # Errors
/// [`Error::Invalid`] on shape violations (see [`TypeHint`]);
/// [`Error::Limit`] when the formatted hint exceeds
/// [`MAX_ANNOTATION_BYTES`](crate::db::MAX_ANNOTATION_BYTES);
/// [`Error::Storage`] on encoding failure.
pub fn format_type_hint(hint: &TypeHint) -> Result<String> {
    check_hint_shape(hint)?;
    let wire = WireHint::from(hint);
    let json = serde_json::to_string(&wire)
        .map_err(|e| Error::Storage(format!("encode type hint: {e}")))?;
    let text = format!("{TYPE_HINT_PREFIX}{json}");
    if text.len() > db::MAX_ANNOTATION_BYTES {
        return Err(Error::Limit(format!(
            "type hint of {} bytes exceeds {}",
            text.len(),
            db::MAX_ANNOTATION_BYTES
        )));
    }
    Ok(text)
}

/// Parse a comment that may carry a [`TypeHint`].
///
/// `None` (no error) for ordinary comments without the
/// [`TYPE_HINT_PREFIX`]; trailing free text after the hint's first line
/// (e.g. `format` output plus `"\nnoted by …"`) is ignored, so a hint and
/// a human note coexist at one address.
///
/// # Errors
/// [`Error::Invalid`] when the prefix is present but the JSON or the
/// shape is bad (wrong `kind`, malformed JSON, failed [`TypeHint`]
/// validation): a corrupt hint errors instead of decoding silently.
pub fn parse_type_hint(comment: &str) -> Result<Option<TypeHint>> {
    let Some(rest) = comment.strip_prefix(TYPE_HINT_PREFIX) else {
        return Ok(None);
    };
    let first = rest.lines().next().unwrap_or("");
    parse_type_hint_json(first).map(Some)
}

/// Import outcome: document rows seen and stored addresses changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImportSummary {
    /// Rows in the imported document.
    pub rows: usize,
    /// Addresses whose stored annotation changed (upserts plus removals).
    pub changed: usize,
}

/// Serialize `annotations` and `seeds` to a capped interchange document.
///
/// Rows come out sorted by address (the maps' order) with empty
/// annotation rows and empty fields dropped; every seed row (including
/// excluded ones) is exported. Pure read: no sidecar or binary is touched.
///
/// # Errors
/// [`Error::Limit`] when a field exceeds
/// [`MAX_ANNOTATION_BYTES`](crate::db::MAX_ANNOTATION_BYTES), when live rows
/// exceed [`MAX_SNAPSHOT_ANNOTATIONS`](crate::db::MAX_SNAPSHOT_ANNOTATIONS)
/// or stored seeds exceed
/// [`MAX_SNAPSHOT_SEEDS`](crate::db::MAX_SNAPSHOT_SEEDS), or when the
/// serialized document exceeds [`MAX_TRANSFER_BYTES`]
/// (explicit failure, never truncation); [`Error::Storage`] on encoding
/// failure.
pub fn build_document(
    sha256: &str,
    size: u64,
    mapping: &StoredMapping,
    annotations: &BTreeMap<u64, Annotation>,
    seeds: &BTreeMap<u64, crate::db::FuncSeed>,
) -> Result<String> {
    let mut rows = Vec::new();
    for (&addr, ann) in annotations {
        if ann.is_empty() {
            continue;
        }
        let rename = ann.name.clone().filter(|s| !s.is_empty());
        let comment = ann.comment.clone().filter(|s| !s.is_empty());
        if rename.is_none() && comment.is_none() {
            continue;
        }
        if rows.len() >= db::MAX_SNAPSHOT_ANNOTATIONS {
            return Err(Error::Limit("annotation export exceeds cap".to_string()));
        }
        for (label, s) in [("rename", &rename), ("comment", &comment)] {
            if let Some(t) = s
                && t.len() > db::MAX_ANNOTATION_BYTES
            {
                return Err(Error::Limit(format!(
                    "annotation {label} of {} bytes exceeds {}",
                    t.len(),
                    db::MAX_ANNOTATION_BYTES
                )));
            }
        }
        rows.push(AnnotationRow {
            addr,
            rename,
            comment,
        });
    }
    let doc = AnnotationDocument {
        revision: ANNOTATION_FORMAT_REVISION,
        sha256: sha256.to_string(),
        size,
        mapping: mapping.clone(),
        annotations: rows,
        func_seeds: seeds
            .iter()
            .map(|(&addr, s)| FuncSeedRow {
                addr,
                mode: s.mode,
                excluded: s.excluded,
            })
            .collect(),
    };
    let text = serde_json::to_string(&doc)
        .map_err(|e| Error::Storage(format!("encode annotation document: {e}")))?;
    if text.len() > MAX_TRANSFER_BYTES {
        return Err(Error::Limit(format!(
            "annotation export of {} bytes exceeds the {MAX_TRANSFER_BYTES}-byte import cap; split or clear annotations instead of truncating",
            text.len()
        )));
    }
    Ok(text)
}

/// Parse and size-check a candidate interchange document.
///
/// # Errors
/// [`Error::Limit`] when the input exceeds [`MAX_TRANSFER_BYTES`];
/// [`Error::Invalid`] when it is not a JSON annotation document.
pub fn parse_document(text: &str) -> Result<AnnotationDocument> {
    if text.len() > MAX_TRANSFER_BYTES {
        return Err(Error::Limit(format!(
            "annotation document of {} bytes exceeds the {MAX_TRANSFER_BYTES}-byte cap",
            text.len()
        )));
    }
    serde_json::from_str(text)
        .map_err(|e| Error::Invalid(format!("malformed annotation document: {e}")))
}

/// Whether `s` is a 64-char lowercase hex digest (malformed identity).
fn is_digest(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// Validate a parsed document against the open project and merge it over
/// `current`, returning the per-address changes to persist.
///
/// `None` values delete the stored row; only addresses whose stored state
/// changes are returned, so an idempotent re-import yields no writes. Pure:
/// `current` is never mutated, letting callers commit first and update
/// memory only on success.
///
/// Default (`overwrite == false`) fails on any supplied field that differs
/// from a present existing value; equal values are idempotent and absent
/// existing values fill freely. `overwrite == true` replaces supplied
/// fields only (absent fields untouched, empty strings clear). Rows outside
/// the document are never touched.
///
/// # Errors
/// [`Error::Invalid`] on unsupported revisions, malformed identity,
/// duplicate addresses, field-less rows, and default-mode conflicts;
/// [`Error::Storage`] on SHA-256/size/mapping mismatches;
/// [`Error::NotFound`] when a non-empty rename targets an unknown function
/// entry; [`Error::Limit`] past field/row budgets.
#[allow(clippy::too_many_arguments)]
pub fn validate_document(
    doc: &AnnotationDocument,
    expected_sha256: &str,
    expected_size: u64,
    expected_mapping: &StoredMapping,
    is_function: &dyn Fn(u64) -> bool,
    current: &BTreeMap<u64, Annotation>,
    overwrite: bool,
) -> Result<BTreeMap<u64, Option<Annotation>>> {
    if doc.revision != ANNOTATION_FORMAT_REVISION {
        return Err(Error::Invalid(format!(
            "unsupported annotation revision {} (expected {ANNOTATION_FORMAT_REVISION})",
            doc.revision
        )));
    }
    if !is_digest(&doc.sha256) {
        return Err(Error::Invalid(
            "malformed annotation identity: sha256 must be 64 hex chars".to_string(),
        ));
    }
    if doc.sha256 != expected_sha256 || doc.size != expected_size {
        return Err(Error::Storage(format!(
            "annotation identity mismatch: document is sha256 {} size {}, but project is sha256 {expected_sha256} size {expected_size}",
            doc.sha256, doc.size
        )));
    }
    if doc.mapping != *expected_mapping {
        return Err(Error::Storage(format!(
            "annotation mapping mismatch: document holds annotations under {}, but project uses {}; use the mapping the document was exported from (annotations are never remapped)",
            doc.mapping.describe(),
            expected_mapping.describe()
        )));
    }
    let mut seen = BTreeSet::new();
    for row in &doc.annotations {
        if !seen.insert(row.addr) {
            return Err(Error::Invalid(format!(
                "duplicate annotation address {:#x}",
                row.addr
            )));
        }
        if row.rename.is_none() && row.comment.is_none() {
            return Err(Error::Invalid(format!(
                "annotation row at {:#x} has neither rename nor comment",
                row.addr
            )));
        }
        for (label, s) in [("rename", &row.rename), ("comment", &row.comment)] {
            if let Some(t) = s
                && t.len() > db::MAX_ANNOTATION_BYTES
            {
                return Err(Error::Limit(format!(
                    "annotation {label} of {} bytes exceeds {}",
                    t.len(),
                    db::MAX_ANNOTATION_BYTES
                )));
            }
        }
        if let Some(name) = &row.rename
            && !name.is_empty()
            && !is_function(row.addr)
        {
            return Err(Error::NotFound(format!(
                "rename target {:#x} is not a known function",
                row.addr
            )));
        }
    }
    let mut changes: BTreeMap<u64, Option<Annotation>> = BTreeMap::new();
    let mut live_after: usize = current.values().filter(|a| !a.is_empty()).count();
    for row in &doc.annotations {
        let existing = current.get(&row.addr);
        let mut merged = existing.cloned().unwrap_or_default();
        for (label, supplied) in [("rename", &row.rename), ("comment", &row.comment)] {
            if let Some(v) = supplied {
                let new_val = (!v.is_empty()).then(|| v.clone());
                let old_val = if label == "rename" {
                    &merged.name
                } else {
                    &merged.comment
                };
                if !overwrite && old_val.is_some() && *old_val != new_val {
                    return Err(Error::Invalid(format!(
                        "annotation conflict at {:#x}: existing {label} differs (import with overwrite to replace supplied fields)",
                        row.addr
                    )));
                }
                if label == "rename" {
                    merged.name = new_val;
                } else {
                    merged.comment = new_val;
                }
            }
        }
        let next = (!merged.is_empty()).then_some(merged);
        if next.as_ref() != existing {
            match (&existing, &next) {
                (None, Some(_)) => live_after += 1,
                (Some(_), None) => live_after -= 1,
                _ => {}
            }
            if live_after > db::MAX_SNAPSHOT_ANNOTATIONS {
                return Err(Error::Limit("annotation import exceeds cap".to_string()));
            }
            changes.insert(row.addr, next);
        }
    }
    Ok(changes)
}

/// Apply validated `changes` to `annotations` (`None` deletes the row).
///
/// Call only after the backing transaction commits, so memory tracks the DB.
pub fn apply_changes(
    annotations: &mut BTreeMap<u64, Annotation>,
    changes: &BTreeMap<u64, Option<Annotation>>,
) {
    for (&addr, next) in changes {
        match next {
            Some(ann) => {
                annotations.insert(addr, ann.clone());
            }
            None => {
                annotations.remove(&addr);
            }
        }
    }
}

/// Validate a document's seed rows against the open project and merge them
/// over `current`, returning the per-address changes to persist.
///
/// Modes are only meaningful on 32-bit ARM projects (`Arm32`/`Thumb`):
/// any other project rejects a supplied mode with [`Error::Invalid`].
/// Default (`overwrite == false`) fails when an existing row differs in
/// mode or exclusion; `overwrite == true` replaces whole rows. Excluded
/// rows never seed analysis but persist as data. Pure: `current` is never
/// mutated, letting callers commit first and update memory only on success.
///
/// # Errors
/// [`Error::Invalid`] on duplicate addresses and default-mode conflicts;
/// [`Error::Limit`] past the seed row budget.
pub fn validate_seed_rows(
    rows: &[FuncSeedRow],
    project_arch: crate::disasm::Arch,
    current: &BTreeMap<u64, crate::db::FuncSeed>,
    overwrite: bool,
) -> Result<BTreeMap<u64, Option<crate::db::FuncSeed>>> {
    use crate::disasm::Arch;
    let arm = matches!(project_arch, Arch::Arm32 | Arch::Thumb);
    let mut seen = BTreeSet::new();
    for row in rows {
        if !seen.insert(row.addr) {
            return Err(Error::Invalid(format!(
                "duplicate func seed address {:#x}",
                row.addr
            )));
        }
        if row.mode.is_some() && !arm {
            return Err(Error::Invalid(format!(
                "func seed mode at {:#x} needs a 32-bit ARM project (arch {})",
                row.addr,
                crate::db::arch_name(project_arch),
            )));
        }
    }
    let mut changes: BTreeMap<u64, Option<crate::db::FuncSeed>> = BTreeMap::new();
    let mut total = current.len();
    for row in rows {
        let next = crate::db::FuncSeed {
            mode: row.mode,
            excluded: row.excluded,
        };
        match current.get(&row.addr) {
            Some(existing) if *existing == next => {}
            Some(_) if !overwrite => {
                return Err(Error::Invalid(format!(
                    "func seed conflict at {:#x} (import with overwrite to replace)",
                    row.addr
                )));
            }
            None => {
                total += 1;
                if total > db::MAX_SNAPSHOT_SEEDS {
                    return Err(Error::Limit("func seed import exceeds cap".to_string()));
                }
                changes.insert(row.addr, Some(next));
            }
            Some(_) => {
                changes.insert(row.addr, Some(next));
            }
        }
    }
    Ok(changes)
}

/// Apply validated seed `changes` to `seeds` (`None` deletes the row).
///
/// Call only after the backing transaction commits, so memory tracks the DB.
pub fn apply_seed_changes(
    seeds: &mut BTreeMap<u64, crate::db::FuncSeed>,
    changes: &BTreeMap<u64, Option<crate::db::FuncSeed>>,
) {
    for (&addr, next) in changes {
        match next {
            Some(seed) => {
                seeds.insert(addr, *seed);
            }
            None => {
                seeds.remove(&addr);
            }
        }
    }
}

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

    #[test]
    fn digest_is_stable_lowercase_hex() {
        let a = sha256_hex(b"abc");
        assert_eq!(a.len(), 64);
        assert!(a.bytes().all(|b| b.is_ascii_hexdigit()));
        assert_eq!(a, sha256_hex(b"abc"));
        assert_ne!(a, sha256_hex(b"abd"));
    }
}