trusty-common 0.49.0

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Content-addressed identity for a memory body — the ONE hashing entry point
//! `memory_core` owns (#5902).
//!
//! Why: the same fact written on two machines for one project must converge to
//! one memory once it is exported, committed to git, pulled, and imported
//! elsewhere. `Drawer.id` is a v4 UUID minted at write time, so nothing about it
//! derives from what the drawer says and two independent writes can never be
//! recognised as the same fact. A digest over the body is the only identity that
//! two machines can compute without talking to each other.
//!
//! Why this module rather than a fourth ad-hoc `Sha256::new()`: this crate
//! already has four independent sha256 call sites
//! (`error_capture::fingerprint`, `memory_core::semantic_consolidation::types`,
//! `symgraph::registry`, `symgraph::contracts`), none of which is a shared entry
//! point. Adding a fifth would put the normalization contract below in a place
//! no other caller can find. CLAUDE.md's common-entry-point rule applies: the
//! capability lands once.
//!
//! Why NOT `symgraph::SymbolRegistry::content_hash`: that is code-symbol
//! identity — a raw sha256 over source text with no normalization, whose whole
//! purpose is to change when the source bytes change, including on a re-indent
//! or a line-ending flip. Memory identity needs the opposite: two clients that
//! typed the same sentence must agree even when their editors disagree about
//! trailing newlines. Same primitive, opposite contract, so they must not share
//! a function. The domain separator in [`memory_content_hash`] makes the two
//! digest spaces provably disjoint rather than merely conventionally distinct.
//!
//! What: [`normalize_for_hash`] (the stable, versioned normalization contract),
//! [`ContentHash`] (a 32-byte digest that prints and parses as lowercase hex),
//! and [`memory_content_hash`] (the entry point).
//! Test: `normalize_*` and `hash_*` in this module's `tests`; the cross-machine
//! properties live in `memory_core::share::tests`.

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use sha2::{Digest, Sha256};
use unicode_normalization::UnicodeNormalization;

/// Version of the normalization + digest contract in this module.
///
/// Why: the digest IS the identity of a memory, so the normalization below is a
/// wire contract, not an implementation detail. Changing any rule re-mints every
/// id in every exported file in every repo that ever ran this code, and two
/// clients on different versions would stop converging — the exact failure this
/// module exists to prevent. Bumping this constant is therefore a BREAKING
/// change, and the version is folded into the digest preimage so a v2 hash can
/// never be mistaken for a v1 hash of different text.
/// What: `1`. Read by [`memory_content_hash`] as part of the domain separator.
/// Test: `domain_separator_pins_the_version`.
pub const CONTENT_HASH_VERSION: u32 = 1;

/// Domain separator prefix. The version is appended by [`memory_content_hash`].
const DOMAIN_PREFIX: &str = "trusty-memory/content-hash/v";

/// A memory body's content-addressed identity: the SHA-256 of its normalized
/// text under [`CONTENT_HASH_VERSION`].
///
/// Why: a `[u8; 32]` newtype rather than a `String` because every `Drawer`
/// carries one and the drawer table is cloned wholesale on every `list_drawers`
/// and every L1 refresh — a hex `String` would add an allocation per drawer per
/// clone for no gain. `Copy` keeps call sites free of borrow noise.
/// What: serializes and deserializes as a 64-character lowercase hex string, so
/// the JSONL export format is human-readable and greppable. [`Self::UNSET`] is
/// the all-zero sentinel a legacy record with no hash field decodes to; it is
/// never a real digest (SHA-256 of anything is all-zero with probability 2^-256)
/// and [`Self::is_unset`] is what the hydration paths branch on.
/// Test: `hash_hex_round_trips`, `unset_is_distinguishable_from_a_real_digest`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ContentHash([u8; 32]);

impl ContentHash {
    /// The all-zero sentinel meaning "no digest recorded".
    pub const UNSET: Self = Self([0u8; 32]);

    /// Whether this is the [`Self::UNSET`] sentinel rather than a real digest.
    pub fn is_unset(&self) -> bool {
        self.0 == [0u8; 32]
    }

    /// The raw 32 digest bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Lowercase hex, 64 characters.
    pub fn to_hex(self) -> String {
        hex::encode(self.0)
    }

    /// Parse a 64-character lowercase-or-uppercase hex digest.
    ///
    /// Why: import reads the digest a producer wrote, so the parse has to reject
    /// anything that is not exactly 32 bytes rather than silently zero-padding —
    /// a short digest that parsed would compare unequal to every real one and
    /// turn every import into an insert.
    /// What: `Err` on any length other than 64 hex characters, or any non-hex
    /// character.
    /// Test: `hash_hex_round_trips`, `parse_rejects_a_short_or_non_hex_digest`.
    pub fn from_hex(s: &str) -> Result<Self, ContentHashParseError> {
        let bytes = hex::decode(s).map_err(|_| ContentHashParseError {
            got: s.chars().take(72).collect(),
        })?;
        let arr: [u8; 32] = bytes.try_into().map_err(|_| ContentHashParseError {
            got: s.chars().take(72).collect(),
        })?;
        Ok(Self(arr))
    }
}

/// A digest string that is not 32 bytes of hex.
#[derive(Debug, Clone, thiserror::Error)]
#[error("not a 64-character hex SHA-256 digest: {got:?}")]
pub struct ContentHashParseError {
    /// The offending input, truncated for the message.
    pub got: String,
}

impl std::fmt::Display for ContentHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl Default for ContentHash {
    fn default() -> Self {
        Self::UNSET
    }
}

impl Serialize for ContentHash {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.to_hex())
    }
}

impl<'de> Deserialize<'de> for ContentHash {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Self::from_hex(&s).map_err(de::Error::custom)
    }
}

/// Normalize `content` for hashing. STABLE CONTRACT — see
/// [`CONTENT_HASH_VERSION`] before changing a single rule.
///
/// Why: nothing normalizes memory text today — `PalaceHandle::remember_with_options`
/// stores `content: String` exactly as received, with no trim, no Unicode form,
/// and no line-ending policy. Two clients that recorded the same sentence
/// therefore hold bytes that differ in ways no reader would call a difference: a
/// Windows editor's `\r\n`, one heredoc's trailing blank line, a macOS
/// filesystem's decomposed `é`. Hashing raw bytes would fork identity on every
/// one of those, which defeats convergence entirely.
///
/// What, in order:
/// 1. Line endings: `\r\n` and lone `\r` both become `\n`.
/// 2. Invisible characters: U+200B (ZWSP), U+200C (ZWNJ), U+200D (ZWJ) and
///    U+FEFF (BOM) are REMOVED wherever they occur; U+00A0 (NBSP) folds to a
///    regular space. See the decision note below.
/// 3. Unicode: NFC (canonical composition), so `e` + U+0301 and U+00E9 agree.
///    Step 2 must precede this one: a zero-width character has canonical
///    combining class 0, so `e` + U+200B + U+0301 does not compose if NFC sees
///    the U+200B, and stripping afterwards cannot recover the composition.
/// 4. Per line: trailing whitespace removed (`str::trim_end`).
/// 5. Whole string: all trailing newlines and whitespace removed, so zero, one,
///    and five trailing blank lines are one identity.
///
/// Why rule 2 (#5902, review): NFC does not fold or remove any of these — they
/// are distinct codepoints canonical composition never touches — so without this
/// rule a fact pasted from a webpage, Slack, or Notion carrying a zero-width
/// space hashes differently from the same fact typed by hand. Two memories, no
/// convergence, and no error raised anywhere, on a difference no reader can see.
/// Invisible characters are noise in memory prose, and making identity depend on
/// how text was pasted is the exact failure this module exists to prevent.
/// The accepted cost: U+200D is also the emoji ZWJ joiner, so a body containing
/// a joined emoji sequence hashes the same as one containing its component
/// codepoints unjoined. Two memories differing ONLY in that are the same fact for
/// this purpose, and the alternative — identity that depends on an invisible
/// codepoint — is worse. Bidi controls (U+200E/U+200F and the U+202x/U+2066
/// families) are deliberately NOT stripped: they change how visible text reads.
///
/// What it deliberately does NOT do: leading whitespace is PRESERVED, per line
/// and for the string as a whole. Indentation carries meaning in a memory that
/// holds a code block or a nested list, and a rule that collapsed it would merge
/// two facts that a reader can tell apart. Interior blank lines are preserved for
/// the same reason. Case is preserved — this is not a fuzzy-match key.
///
/// Normalization is for HASHING ONLY. Nothing here touches what gets stored;
/// `Drawer.content` keeps the caller's bytes verbatim. Rewriting stored content
/// would be a silent data migration of every palace on disk.
/// Test: `normalize_collapses_line_endings`, `normalize_trims_trailing_space_per_line`,
/// `normalize_collapses_trailing_newlines`, `normalize_applies_nfc`,
/// `normalize_preserves_leading_whitespace_and_interior_blanks`,
/// `normalize_strips_zero_width_characters`, `normalize_folds_nbsp_to_a_space`,
/// `normalize_preserves_bidi_marks`, `normalize_preserves_non_bmp_codepoints`,
/// `a_zero_width_between_base_and_mark_still_composes` (the step order itself).
pub fn normalize_for_hash(content: &str) -> String {
    // Step 1: line endings. Done before NFC so the `\r` removal cannot be
    // perturbed by a composition that spans the boundary.
    let unix: String = content.replace("\r\n", "\n").replace('\r', "\n");
    // Step 2 (#5902): invisible characters, before NFC and before the trims.
    // Before NFC because a zero-width character has canonical combining class 0
    // and therefore BLOCKS composition: leave `e` U+200B U+0301 for NFC to see
    // and the mark never composes. Before the trims because an NBSP folded to a
    // space is then trimmable like any other trailing space, and a zero-width
    // character is not whitespace to `trim_end` at all. Reordering this against
    // step 3 re-mints ids — `a_zero_width_between_base_and_mark_still_composes`.
    let visible: String = unix
        .chars()
        .filter_map(|c| match c {
            '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{FEFF}' => None,
            '\u{00A0}' => Some(' '),
            other => Some(other),
        })
        .collect();
    // Step 3: NFC over the whole string.
    let composed: String = visible.nfc().collect();
    // Step 4: per-line trailing whitespace.
    let mut out = String::with_capacity(composed.len());
    for (i, line) in composed.split('\n').enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(line.trim_end());
    }
    // Step 5: trailing newlines / whitespace for the string as a whole.
    let trimmed_len = out.trim_end().len();
    out.truncate(trimmed_len);
    out
}

/// The content-addressed identity of a memory body (#5902).
///
/// Why: this is the join key that makes two machines' copies of one fact the
/// same memory. Decision: the digest covers the BODY ONLY — not tags, not
/// `room_id`, not `drawer_type`, not importance. The dream cycle rewrites both
/// content and tags during routine housekeeping
/// (`dream::helpers::merge_into` appends the loser's text and unions its tags;
/// `dream::cycle::apply_consolidation_result` writes an LLM-authored canonical
/// body with a rewritten tag set), so a metadata-inclusive digest would fork
/// identity on a consolidation pass that changed nothing a reader would call a
/// new fact.
///
/// What: `SHA-256("trusty-memory/content-hash/v<VERSION>" || 0x00 ||
/// normalize_for_hash(content))`. The domain separator makes this digest space
/// disjoint from every other sha256 in the workspace — notably
/// `symgraph::SymbolRegistry::content_hash`, which is a bare digest of raw
/// source — so no code-symbol digest can ever be mistaken for a memory id, and a
/// future [`CONTENT_HASH_VERSION`] bump lands in a different space rather than
/// silently overlapping v1.
/// Test: `hash_is_stable_for_a_known_body`, `hash_ignores_line_ending_and_trailing_newline`,
/// `hash_ignores_unicode_composition_form`, `hash_distinguishes_different_bodies`,
/// `hash_is_not_a_bare_sha256_of_the_body`.
pub fn memory_content_hash(content: &str) -> ContentHash {
    let mut hasher = Sha256::new();
    hasher.update(DOMAIN_PREFIX.as_bytes());
    hasher.update(CONTENT_HASH_VERSION.to_string().as_bytes());
    hasher.update([0u8]);
    hasher.update(normalize_for_hash(content).as_bytes());
    let digest = hasher.finalize();
    let mut out = [0u8; 32];
    out.copy_from_slice(&digest);
    ContentHash(out)
}

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

    #[test]
    fn normalize_collapses_line_endings() {
        assert_eq!(normalize_for_hash("a\r\nb"), "a\nb");
        assert_eq!(normalize_for_hash("a\rb"), "a\nb");
        assert_eq!(normalize_for_hash("a\nb"), "a\nb");
    }

    #[test]
    fn normalize_trims_trailing_space_per_line() {
        assert_eq!(normalize_for_hash("a   \nb\t\nc"), "a\nb\nc");
    }

    #[test]
    fn normalize_collapses_trailing_newlines() {
        assert_eq!(normalize_for_hash("fact"), "fact");
        assert_eq!(normalize_for_hash("fact\n"), "fact");
        assert_eq!(normalize_for_hash("fact\n\n\n"), "fact");
        assert_eq!(normalize_for_hash("fact\n  \n\t\n"), "fact");
    }

    #[test]
    fn normalize_applies_nfc() {
        // U+0065 U+0301 (decomposed) vs U+00E9 (composed).
        let decomposed = "caf\u{0065}\u{0301}";
        let composed = "caf\u{00e9}";
        assert_ne!(decomposed, composed, "the inputs must differ as bytes");
        assert_eq!(normalize_for_hash(decomposed), normalize_for_hash(composed));
    }

    /// Why: the contract's negative half is as load-bearing as its positive
    /// half. A rule that collapsed indentation would merge a memory holding a
    /// nested code block with one holding the same text flush-left, which are
    /// different facts.
    /// Test: This test.
    #[test]
    fn normalize_preserves_leading_whitespace_and_interior_blanks() {
        assert_eq!(normalize_for_hash("    indented"), "    indented");
        assert_eq!(normalize_for_hash("a\n\nb"), "a\n\nb");
        assert_ne!(normalize_for_hash("  a"), normalize_for_hash("a"));
    }

    #[test]
    fn normalize_of_only_whitespace_is_empty() {
        assert_eq!(normalize_for_hash("   \n\t\r\n  "), "");
        assert_eq!(normalize_for_hash(""), "");
    }

    /// Why (#5902, review): NFC does not fold or remove zero-width characters,
    /// so before rule 2 a fact pasted from a webpage carrying a U+200B and the
    /// same fact typed by hand produced two hashes, two memories, and no
    /// convergence — silently, with no error raised.
    /// Test: This test.
    #[test]
    fn normalize_strips_zero_width_characters() {
        let clean = "the daemon binds loopback only";
        // Each class, one at a time, interior and at both edges.
        assert_eq!(
            normalize_for_hash("the daemon\u{200B} binds"),
            "the daemon binds"
        );
        assert_eq!(normalize_for_hash("the\u{200C} daemon"), "the daemon");
        assert_eq!(normalize_for_hash("the\u{200D} daemon"), "the daemon");
        assert_eq!(normalize_for_hash("\u{FEFF}the daemon"), "the daemon");
        assert_eq!(normalize_for_hash("the daemon\u{FEFF}"), "the daemon");
        // And the whole sentence, one of each, hashes as the clean sentence.
        let pasted = "\u{FEFF}the\u{200B} daemon\u{200C} binds\u{200D} loopback only";
        assert_eq!(normalize_for_hash(pasted), clean);
        assert_eq!(memory_content_hash(pasted), memory_content_hash(clean));
        // A body that is nothing but invisible characters normalizes to empty.
        assert_eq!(normalize_for_hash("\u{200B}\u{200C}\u{200D}\u{FEFF}"), "");
    }

    /// Why: NBSP is the other invisible difference a paste introduces, and
    /// `str::trim_end` already treats it as whitespace — so leaving it unfolded
    /// made a trailing NBSP normalize away while an interior one forked the
    /// identity. Folding it to a space makes both cases agree.
    /// Test: This test.
    #[test]
    fn normalize_folds_nbsp_to_a_space() {
        assert_eq!(normalize_for_hash("a\u{00A0}b"), "a b");
        assert_eq!(
            memory_content_hash("MSRV\u{00A0}1.94"),
            memory_content_hash("MSRV 1.94")
        );
        // Folded before the trims, so a trailing NBSP is trimmed like a space.
        assert_eq!(normalize_for_hash("a\u{00A0}\nb\u{00A0}"), "a\nb");
        assert_eq!(normalize_for_hash("\u{00A0}\u{00A0}"), "");
        // Leading NBSP survives as leading whitespace, which rule 2's note says
        // is preserved — it is now indistinguishable from a leading space.
        assert_eq!(normalize_for_hash("\u{00A0}a"), " a");
    }

    /// Why: the strip list is deliberately narrow. Bidi marks change how visible
    /// text reads, so two bodies differing by one are not the same fact, and a
    /// rule that swept up "all format characters" would erase that distinction.
    /// Test: This test.
    #[test]
    fn normalize_preserves_bidi_marks() {
        assert_eq!(normalize_for_hash("a\u{200E}b"), "a\u{200E}b");
        assert_eq!(normalize_for_hash("a\u{200F}b"), "a\u{200F}b");
        assert_ne!(memory_content_hash("a\u{200E}b"), memory_content_hash("ab"));
    }

    /// Why: the filter runs per `char`, so a codepoint outside the BMP must pass
    /// through byte-identically — a `char`-level rule that corrupted a surrogate
    /// pair or a combining sequence would re-mint ids for every emoji or accented
    /// memory. Combining marks are the NFC case checked here against the strip
    /// rule, which must not disturb them.
    /// Test: This test.
    #[test]
    fn normalize_preserves_non_bmp_codepoints() {
        assert_eq!(normalize_for_hash("ship it 🚀"), "ship it 🚀");
        assert_eq!(normalize_for_hash("𝔘𝔫𝔦𝔠𝔬𝔡𝔢"), "𝔘𝔫𝔦𝔠𝔬𝔡𝔢");
        assert_eq!(normalize_for_hash("𝔘\u{200B}𝔫"), "𝔘𝔫");
        // Combining marks still compose, and a stripped zero-width character
        // between base and mark does not block the composition.
        assert_eq!(
            memory_content_hash("cafe\u{0301}\u{200B} time"),
            memory_content_hash("caf\u{00E9} time")
        );
    }

    /// Why (#5902, review): rule 2 runs BEFORE rule 3, and this is the only case
    /// that proves it. U+200B has canonical combining class 0, so it BLOCKS
    /// composition: with NFC first, `e` + U+200B + U+0301 stays decomposed and
    /// the later strip cannot put the mark back, leaving a digest different from
    /// the composed `é`. Every other test here passes under either order —
    /// including `normalize_preserves_non_bmp_codepoints`, whose zero-width
    /// character sits AFTER the mark, where it blocks nothing. Swap the two steps
    /// in [`normalize_for_hash`] and only this test goes red.
    /// Test: This test.
    #[test]
    fn a_zero_width_between_base_and_mark_still_composes() {
        // `e` U+200B U+0301 — the ZWSP is WEDGED BETWEEN the base and its mark.
        let wedged = "caf\u{0065}\u{200B}\u{0301} time";
        let composed = "caf\u{00E9} time";
        assert_ne!(wedged, composed, "the inputs must differ as bytes");
        assert_eq!(normalize_for_hash(wedged), composed);
        assert_eq!(memory_content_hash(wedged), memory_content_hash(composed));
        // The same wedge with each of the other stripped codepoints.
        for zw in ['\u{200C}', '\u{200D}', '\u{FEFF}'] {
            let body = format!("caf\u{0065}{zw}\u{0301} time");
            assert_eq!(
                memory_content_hash(&body),
                memory_content_hash(composed),
                "{zw:?} between base and mark blocked the composition"
            );
        }
    }

    /// Why: an empty or whitespace-only body must have ONE identity, whatever
    /// mix of invisible and visible whitespace produced it — otherwise a
    /// degenerate memory forks per paste.
    /// Test: This test.
    #[test]
    fn normalize_of_invisible_only_bodies_is_one_identity() {
        let empty = memory_content_hash("");
        for body in [
            "",
            "   ",
            "\n\n",
            "\u{200B}",
            "\u{FEFF}\u{00A0}\n\u{200D}  \r\n",
        ] {
            assert_eq!(
                memory_content_hash(body),
                empty,
                "body {body:?} must hash as the empty body"
            );
        }
    }

    #[test]
    fn hash_hex_round_trips() {
        let h = memory_content_hash("a fact");
        let hex = h.to_hex();
        assert_eq!(hex.len(), 64);
        assert_eq!(ContentHash::from_hex(&hex).unwrap(), h);
        assert_eq!(h.to_string(), hex);
    }

    #[test]
    fn parse_rejects_a_short_or_non_hex_digest() {
        assert!(ContentHash::from_hex("deadbeef").is_err());
        assert!(ContentHash::from_hex("").is_err());
        assert!(ContentHash::from_hex(&"z".repeat(64)).is_err());
    }

    #[test]
    fn unset_is_distinguishable_from_a_real_digest() {
        assert!(ContentHash::UNSET.is_unset());
        assert!(ContentHash::default().is_unset());
        assert!(!memory_content_hash("").is_unset());
        assert!(!memory_content_hash("x").is_unset());
    }

    /// Why: the digest is a wire contract, so a pinned expected value is what
    /// catches an accidental change to the preimage — a reordered `update`, a
    /// dropped separator, a normalization tweak — that every other test in this
    /// module would still pass.
    /// Test: This test.
    #[test]
    fn hash_is_stable_for_a_known_body() {
        assert_eq!(
            memory_content_hash("the daemon binds loopback only").to_hex(),
            "5b00cdfb7e5932bd483cdb66a70fbc680693a056d6bc708ef3182cfdff0f31da"
        );
    }

    #[test]
    fn hash_ignores_line_ending_and_trailing_newline() {
        let base = memory_content_hash("line one\nline two");
        assert_eq!(memory_content_hash("line one\r\nline two"), base);
        assert_eq!(memory_content_hash("line one\nline two\n"), base);
        assert_eq!(memory_content_hash("line one\r\nline two\r\n\r\n"), base);
        assert_eq!(memory_content_hash("line one   \nline two\t"), base);
    }

    #[test]
    fn hash_ignores_unicode_composition_form() {
        assert_eq!(
            memory_content_hash("caf\u{0065}\u{0301} rules"),
            memory_content_hash("caf\u{00e9} rules")
        );
    }

    #[test]
    fn hash_distinguishes_different_bodies() {
        assert_ne!(memory_content_hash("a"), memory_content_hash("b"));
        // Case is significant — this is identity, not a fuzzy match key.
        assert_ne!(memory_content_hash("Fact"), memory_content_hash("fact"));
        // Leading indentation is significant.
        assert_ne!(memory_content_hash("  fact"), memory_content_hash("fact"));
    }

    /// Why: the domain separator is what keeps this digest space disjoint from
    /// every other sha256 of the same text in the workspace —
    /// `symgraph::SymbolRegistry::content_hash` is exactly the bare digest
    /// computed below. If the separator were ever dropped, the two spaces would
    /// silently merge and nothing else here would fail.
    /// Test: This test.
    #[test]
    fn hash_is_not_a_bare_sha256_of_the_body() {
        let bare = {
            let mut h = Sha256::new();
            h.update(b"a fact");
            hex::encode(h.finalize())
        };
        assert_ne!(memory_content_hash("a fact").to_hex(), bare);
    }

    /// Why: [`CONTENT_HASH_VERSION`] is folded into the preimage precisely so a
    /// future bump lands in a different digest space. A test that only asserted
    /// the constant's value would not catch it being dropped from the preimage.
    /// Test: This test.
    #[test]
    fn domain_separator_pins_the_version() {
        assert_eq!(CONTENT_HASH_VERSION, 1);
        let expected = {
            let mut h = Sha256::new();
            h.update(b"trusty-memory/content-hash/v1");
            h.update([0u8]);
            h.update(b"a fact");
            hex::encode(h.finalize())
        };
        assert_eq!(memory_content_hash("a fact").to_hex(), expected);
    }
}