llmtxt-core 2026.4.13

Core primitives for llmtxt: compression, patching, hashing, signing, and encoding
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
//! llmtxt-core: Portable primitives for the llmtxt content platform.
//!
//! This crate is the single source of truth for compression, hashing,
//! signing, and encoding functions used by both the Rust (SignalDock)
//! and TypeScript (npm `llmtxt` via WASM) consumers.
//!
//! # Features
//! - `wasm` (default): Enables `wasm-bindgen` exports for JavaScript consumption.
//!   Disable with `default-features = false` for native-only usage.
//!
//! # Native
//! All functions are available as regular Rust APIs regardless of features.

use flate2::Compression;
use flate2::read::{ZlibDecoder, ZlibEncoder};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use std::io::Cursor;
use std::io::Read;
use uuid::Uuid;

#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

#[cfg(not(target_arch = "wasm32"))]
mod native_signed_url;

#[cfg(not(target_arch = "wasm32"))]
pub use native_signed_url::{
    SignedUrlBuildRequest, SignedUrlParams, VerifyError, generate_signed_url, verify_signed_url,
};

mod diff;
mod diff_multi;
pub use diff::{
    DiffResult, MultiDiffLine, MultiDiffResult, MultiDiffStats, MultiDiffVariant,
    StructuredDiffLine, StructuredDiffResult, compute_diff, multi_way_diff, multi_way_diff_native,
    structured_diff, structured_diff_native,
};

mod patch;
pub use patch::{
    apply_patch, batch_diff_versions, compute_sections_modified, compute_sections_modified_native,
    create_patch, diff_versions, diff_versions_native, reconstruct_version,
    reconstruct_version_native, squash_patches, squash_patches_native,
};

mod cherry_pick;
pub use cherry_pick::cherry_pick_merge;

mod three_way_merge;
pub use three_way_merge::{
    Conflict, MergeStats, ThreeWayMergeResult, three_way_merge, three_way_merge_native,
};

#[cfg(feature = "wasm")]
pub mod wasm_bindings;

mod lifecycle;
pub use lifecycle::{
    DocumentState, is_editable, is_editable_str, is_terminal, is_terminal_str, is_valid_transition,
    is_valid_transition_str, validate_transition,
};

mod consensus;
pub use consensus::{
    ApprovalPolicy, ApprovalResult, Review, evaluate_approvals, evaluate_approvals_native,
    mark_stale_reviews, mark_stale_reviews_native,
};

pub mod crypto;
// S-01: Export constant-time hex comparison alongside the signing primitive. [T108.7]
pub use crypto::{constant_time_eq_hex, sign_webhook_payload};

pub mod normalize;
pub use normalize::{l2_normalize, l2_normalize_wasm};

pub mod rbac;
pub use rbac::{DocumentRole, OrgRole, Permission, role_has_permission, role_permissions};

pub mod slugify;
pub use slugify::slugify;

mod semantic;
pub use semantic::{
    EmbeddedReview, EmbeddedSection, ReviewCluster, SectionAlignment, SectionSimilarity,
    SemanticChange, SemanticConsensusResult, SemanticDiffResult, cosine_similarity,
    cosine_similarity_wasm, semantic_consensus, semantic_consensus_native, semantic_diff,
    semantic_diff_native,
};

pub mod validation;
pub use validation::{
    DEFAULT_MAX_CONTENT_BYTES, DEFAULT_MAX_LINE_BYTES, contains_binary_content,
    default_max_content_bytes, default_max_line_bytes, detect_format, find_overlong_line,
};

pub mod graph;
pub use graph::{
    GraphEdge, GraphNode, GraphStats, KnowledgeGraph, MessageInput, MessageMetadata, TopAgent,
    TopTopic, build_graph_native, build_graph_wasm, extract_directives, extract_directives_wasm,
    extract_mentions, extract_mentions_wasm, extract_tags, extract_tags_wasm, top_agents_native,
    top_agents_wasm, top_topics_native, top_topics_wasm,
};

pub mod similarity;
pub use similarity::{
    SimilarityResult, content_similarity, content_similarity_wasm, extract_ngrams,
    extract_ngrams_wasm, extract_word_shingles, extract_word_shingles_wasm, fingerprint_similarity,
    jaccard_similarity, jaccard_similarity_wasm, min_hash_fingerprint, min_hash_fingerprint_wasm,
    rank_by_similarity, rank_by_similarity_wasm, simple_hash, text_similarity_jaccard,
};

pub mod disclosure;
pub use disclosure::code::parse_code_sections;
pub use disclosure::json::{extract_json_keys, parse_json_sections};
pub use disclosure::markdown::{extract_markdown_toc, parse_markdown_sections};
pub use disclosure::search::search_content;
pub use disclosure::text::parse_text_sections;
pub use disclosure::{
    DocumentOverview, JsonKey, LineRangeResult, SearchResult, Section, TocEntry,
    detect_document_format, generate_overview, get_line_range, get_section, query_json_path,
};
pub mod classify; // Wave-2: multi-modal document classification (T821)
pub mod tfidf;
pub use tfidf::{fnv1a_hash, tfidf_embed};

pub mod identity;
pub use identity::{body_hash, canonical_payload, keygen, sign_submission, verify_submission};

pub mod bft;
pub use bft::{
    ChainedEvent, bft_check, bft_max_faults, bft_quorum, hash_chain_extend, verify_chain,
};

pub mod a2a;
pub use a2a::A2AMessage;

#[cfg(feature = "crdt")]
pub mod crdt;

pub mod canonical;
pub use canonical::{FrontmatterMeta, canonical_frontmatter, canonical_frontmatter_wasm};

pub mod blob;
pub use blob::{BlobNameError, blob_name_validate, hash_blob};

pub mod merkle;
pub use merkle::{
    AuditEntry, hash_audit_entry, merkle_root, sign_merkle_root, verify_audit_chain,
    verify_merkle_proof, verify_merkle_root_signature,
};

pub mod billing;
pub use billing::{
    TierDecision, TierKind, TierLimits, UsageSnapshot, evaluate_tier_limits,
    evaluate_tier_limits_wasm, get_tier_limits_wasm, tier_limits,
};

pub mod export_archive;
pub use export_archive::{
    ARCHIVE_VERSION, ExportApiKey, ExportArchive, ExportAuditEntry, ExportDocument, ExportVersion,
    ExportWebhook, RetentionPolicy, deserialize_export_archive, deserialize_retention_policy,
    serialize_export_archive, serialize_retention_policy,
};

/// Retention policy DSL — T168.2 (richer than `export_archive::RetentionPolicy`).
pub mod retention;
pub use retention::{
    EvictionSet, LawfulBasis, RetentionAction, RetentionRow, RetentionTier, apply_retention,
    canonical_policies,
};
type HmacSha256 = Hmac<Sha256>;
const BASE62: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

// ── Base62 ──────────────────────────────────────────────────────

/// Encode a non-negative integer into a base62 string.
///
/// Uses the alphabet `0-9A-Za-z`. Zero encodes to `"0"`.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn encode_base62(mut num: u64) -> String {
    if num == 0 {
        return "0".to_string();
    }
    let mut result = Vec::new();
    while num > 0 {
        result.push(BASE62[(num % 62) as usize]);
        num /= 62;
    }
    result.reverse();
    String::from_utf8(result).unwrap_or_default()
}

/// Decode a base62-encoded string back into an integer.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn decode_base62(s: &str) -> u64 {
    let mut result: u64 = 0;
    for byte in s.bytes() {
        let val = match byte {
            b'0'..=b'9' => byte - b'0',
            b'A'..=b'Z' => byte - b'A' + 10,
            b'a'..=b'z' => byte - b'a' + 36,
            _ => 0,
        } as u64;
        result = result * 62 + val;
    }
    result
}

// ── Compression ─────────────────────────────────────────────────

/// Magic-byte prefix for zstd frames (RFC 8478 §3.1.1).
///
/// The zstd frame magic number `0xFD2FB528` is stored in little-endian byte
/// order at the start of every zstd frame: `[0x28, 0xB5, 0x2F, 0xFD]`.
const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD];

/// Compress a UTF-8 string using **zstd** (RFC 8478), level 3.
///
/// New writes use zstd. Existing zlib-stored data is still readable via
/// [`decompress`], which detects the codec by inspecting magic bytes.
///
/// # Errors
/// Returns an error string if compression fails.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn compress(data: &str) -> Result<Vec<u8>, String> {
    zstd_compress(data.as_bytes())
}

/// Decompress bytes back to a UTF-8 string.
///
/// Codec is detected automatically from the magic bytes:
/// - `0xFD 0x2F 0xB5 0x28` → zstd (RFC 8478)
/// - `0x78 __` (zlib CMF byte) → zlib/deflate (RFC 1950, legacy)
///
/// This guarantees backward compatibility: all rows written before the zstd
/// migration continue to decode correctly without a schema change.
///
/// # Errors
/// Returns an error string if decompression or UTF-8 conversion fails.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn decompress(data: &[u8]) -> Result<String, String> {
    let bytes = decompress_bytes(data)?;
    String::from_utf8(bytes).map_err(|e| format!("invalid UTF-8: {e}"))
}

/// Compress arbitrary bytes using zstd at level 3.
///
/// Exposed for native consumers (benches, migration tooling) and used
/// internally by the WASM [`compress`] binding.
///
/// # Errors
/// Returns an error string if compression fails.
pub fn zstd_compress(data: &[u8]) -> Result<Vec<u8>, String> {
    zstd::encode_all(Cursor::new(data), 3).map_err(|e| format!("zstd compression failed: {e}"))
}

/// Decompress zstd bytes back to raw bytes.
///
/// Exposed for native consumers and used internally by [`decompress_bytes`].
///
/// # Errors
/// Returns an error string if decompression fails.
pub fn zstd_decompress(data: &[u8]) -> Result<Vec<u8>, String> {
    zstd::decode_all(Cursor::new(data)).map_err(|e| format!("zstd decompression failed: {e}"))
}

/// Decompress bytes, auto-detecting codec by magic bytes.
///
/// Supports:
/// - zstd (`0xFD 0x2F 0xB5 0x28`)
/// - zlib/deflate RFC 1950 (`0x78 __`)
///
/// # Errors
/// Returns an error string if decompression fails or codec is unknown.
pub fn decompress_bytes(data: &[u8]) -> Result<Vec<u8>, String> {
    if data.len() >= 4 && data[..4] == ZSTD_MAGIC {
        return zstd_decompress(data);
    }
    // zlib CMF byte: 0x78 (deflate, window size bits vary in low nibble)
    if data.len() >= 2 && data[0] == 0x78 {
        let mut decoder = ZlibDecoder::new(data);
        let mut out = Vec::new();
        decoder
            .read_to_end(&mut out)
            .map_err(|e| format!("zlib decompression failed: {e}"))?;
        return Ok(out);
    }
    Err(format!(
        "unknown compression codec (first bytes: {:02x?})",
        &data[..data.len().min(4)]
    ))
}

/// Compress bytes using legacy zlib/deflate (RFC 1950).
///
/// Use only for testing backward-compat paths or re-compression tooling.
/// New writes should use [`compress`] (zstd).
///
/// # Errors
/// Returns an error string if compression fails.
pub fn zlib_compress(data: &[u8]) -> Result<Vec<u8>, String> {
    let mut encoder = ZlibEncoder::new(data, Compression::default());
    let mut out = Vec::new();
    encoder
        .read_to_end(&mut out)
        .map_err(|e| format!("zlib compression failed: {e}"))?;
    Ok(out)
}

// ── ID Generation ───────────────────────────────────────────────

/// Generate an 8-character base62 ID from a UUID v4.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn generate_id() -> String {
    let uuid = Uuid::new_v4();
    let hex = uuid.simple().to_string();
    let hex_prefix = &hex[..16];
    let num = u64::from_str_radix(hex_prefix, 16).unwrap_or(0);
    let base62 = encode_base62(num);
    format!("{:0>8}", &base62[..base62.len().min(8)])
}

// ── Hashing ─────────────────────────────────────────────────────

/// Compute the SHA-256 hash of a UTF-8 string, returned as lowercase hex.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn hash_content(data: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data.as_bytes());
    hex::encode(hasher.finalize())
}

// ── Token Estimation ────────────────────────────────────────────

/// Estimate token count using the ~4 chars/token heuristic.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn calculate_tokens(text: &str) -> u32 {
    let len = text.len() as f64;
    (len / 4.0).ceil() as u32
}

// ── Compression Ratio ───────────────────────────────────────────

/// Calculate the compression ratio (original / compressed), rounded to 2 decimals.
/// Returns 1.0 when `compressed_size` is 0.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn calculate_compression_ratio(original_size: u32, compressed_size: u32) -> f64 {
    if compressed_size == 0 {
        return 1.0;
    }
    let ratio = original_size as f64 / compressed_size as f64;
    (ratio * 100.0).round() / 100.0
}

// ── HMAC Signing ────────────────────────────────────────────────

/// Compute the HMAC-SHA256 signature for signed URL parameters.
/// Returns the first 16 hex characters of the digest (64 bits).
/// For longer signatures, use [`compute_signature_with_length`].
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn compute_signature(
    slug: &str,
    agent_id: &str,
    conversation_id: &str,
    expires_at: f64,
    secret: &str,
) -> String {
    compute_signature_with_length(slug, agent_id, conversation_id, expires_at, secret, 16)
}

/// Compute the HMAC-SHA256 signature with configurable output length.
///
/// `sig_length` controls how many hex characters to return (max 64).
/// Use 16 for short-lived URLs (backward compat), 32 for long-lived URLs (128 bits).
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn compute_signature_with_length(
    slug: &str,
    agent_id: &str,
    conversation_id: &str,
    expires_at: f64,
    secret: &str,
    sig_length: usize,
) -> String {
    let payload = format!(
        "{}:{}:{}:{}",
        slug, agent_id, conversation_id, expires_at as u64
    );
    let Ok(mut mac) = HmacSha256::new_from_slice(secret.as_bytes()) else {
        return String::new();
    };
    mac.update(payload.as_bytes());
    let result = mac.finalize();
    let hex_full = hex::encode(result.into_bytes());
    let len = sig_length.min(64);
    hex_full[..len].to_string()
}

/// Compute the HMAC-SHA256 signature for org-scoped signed URL parameters.
/// Includes `org_id` in the HMAC payload for organization-level access control.
/// Returns the first 32 hex characters (128 bits) by default.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn compute_org_signature(
    slug: &str,
    agent_id: &str,
    conversation_id: &str,
    org_id: &str,
    expires_at: f64,
    secret: &str,
) -> String {
    compute_org_signature_with_length(
        slug,
        agent_id,
        conversation_id,
        org_id,
        expires_at,
        secret,
        32,
    )
}

/// Compute org-scoped HMAC-SHA256 signature with configurable output length.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn compute_org_signature_with_length(
    slug: &str,
    agent_id: &str,
    conversation_id: &str,
    org_id: &str,
    expires_at: f64,
    secret: &str,
    sig_length: usize,
) -> String {
    let payload = format!(
        "{}:{}:{}:{}:{}",
        slug, agent_id, conversation_id, org_id, expires_at as u64
    );
    let Ok(mut mac) = HmacSha256::new_from_slice(secret.as_bytes()) else {
        return String::new();
    };
    mac.update(payload.as_bytes());
    let result = mac.finalize();
    let hex_full = hex::encode(result.into_bytes());
    let len = sig_length.min(64);
    hex_full[..len].to_string()
}

/// Derive a per-agent signing key from their API key.
/// Uses `HMAC-SHA256(api_key, "llmtxt-signing")`.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn derive_signing_key(api_key: &str) -> String {
    let Ok(mut mac) = HmacSha256::new_from_slice(api_key.as_bytes()) else {
        return String::new();
    };
    mac.update(b"llmtxt-signing");
    hex::encode(mac.finalize().into_bytes())
}

// ── Expiration ──────────────────────────────────────────────────

/// Check whether a timestamp (milliseconds) has expired.
/// Returns false for 0 (no expiration).
///
/// Uses `js_sys::Date::now()` in WASM, `std::time::SystemTime` natively.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn is_expired(expires_at_ms: f64) -> bool {
    if expires_at_ms == 0.0 {
        return false;
    }
    let now = current_time_ms();
    now > expires_at_ms
}

/// Get current time in milliseconds since epoch.
/// Uses `js_sys::Date::now()` when compiled to WASM, `SystemTime` natively.
#[cfg(target_arch = "wasm32")]
fn current_time_ms() -> f64 {
    js_sys::Date::now()
}

/// Get current time in milliseconds since epoch.
#[cfg(not(target_arch = "wasm32"))]
fn current_time_ms() -> f64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as f64)
        .unwrap_or(0.0)
}

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

    #[test]
    fn test_base62_encode() {
        assert_eq!(encode_base62(0), "0");
        assert_eq!(encode_base62(1), "1");
        assert_eq!(encode_base62(61), "z");
        assert_eq!(encode_base62(62), "10");
        assert_eq!(encode_base62(3844), "100");
    }

    #[test]
    fn test_base62_decode() {
        assert_eq!(decode_base62("0"), 0);
        assert_eq!(decode_base62("z"), 61);
        assert_eq!(decode_base62("10"), 62);
        assert_eq!(decode_base62("100"), 3844);
    }

    #[test]
    fn test_base62_roundtrip() {
        for n in [0, 1, 42, 61, 62, 100, 3844, 999_999, u64::MAX / 2] {
            assert_eq!(
                decode_base62(&encode_base62(n)),
                n,
                "roundtrip failed for {n}"
            );
        }
    }

    #[test]
    fn test_hash_content() {
        assert_eq!(
            hash_content("hello"),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
        assert_eq!(
            hash_content(""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn test_calculate_tokens() {
        assert_eq!(calculate_tokens("Hello, world!"), 4);
        assert_eq!(calculate_tokens(""), 0);
        assert_eq!(calculate_tokens("a"), 1);
        assert_eq!(calculate_tokens("1234"), 1);
        assert_eq!(calculate_tokens("12345"), 2);
    }

    #[test]
    fn test_compression_ratio() {
        assert_eq!(calculate_compression_ratio(1000, 400), 2.5);
        assert_eq!(calculate_compression_ratio(100, 100), 1.0);
        assert_eq!(calculate_compression_ratio(100, 0), 1.0);
        assert_eq!(calculate_compression_ratio(500, 200), 2.5);
    }

    #[test]
    fn test_compress_decompress_roundtrip() {
        let input = "Hello, world! This is a test of the llmtxt compression.";
        let compressed = compress(input).expect("compress should succeed");
        // New writes must be zstd — verify magic bytes
        assert_eq!(
            &compressed[..4],
            &ZSTD_MAGIC,
            "compress() should produce zstd output"
        );
        let decompressed = decompress(&compressed).expect("decompress should succeed");
        assert_eq!(decompressed, input);
    }

    #[test]
    fn test_compress_empty() {
        let compressed = compress("").expect("compress empty should succeed");
        let decompressed = decompress(&compressed).expect("decompress should succeed");
        assert_eq!(decompressed, "");
    }

    #[test]
    fn test_zstd_roundtrip_bytes() {
        let data = b"zstd binary roundtrip test data 12345";
        let compressed = zstd_compress(data).expect("zstd_compress should succeed");
        assert_eq!(&compressed[..4], &ZSTD_MAGIC);
        let decompressed = zstd_decompress(&compressed).expect("zstd_decompress should succeed");
        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_zstd_better_ratio_than_zlib_on_repetitive_text() {
        // Repetitive text — zstd should compress at least as well as zlib
        let input = "the quick brown fox jumps over the lazy dog. ".repeat(200);
        let zstd_out = zstd_compress(input.as_bytes()).expect("zstd compress");
        let zlib_out = zlib_compress(input.as_bytes()).expect("zlib compress");
        // zstd level 3 should beat or match zlib default on repetitive content
        assert!(
            zstd_out.len() <= zlib_out.len() + 50, // allow tiny variance
            "zstd ({}) should be at most marginally larger than zlib ({}) on repetitive text",
            zstd_out.len(),
            zlib_out.len()
        );
    }

    #[test]
    fn test_backward_compat_zlib_still_decompresses() {
        // Simulate a legacy row that was compressed with zlib
        let input = "legacy document stored with zlib compression";
        let zlib_bytes = zlib_compress(input.as_bytes()).expect("zlib compress legacy");
        // Verify magic byte is 0x78 (zlib CMF)
        assert_eq!(zlib_bytes[0], 0x78, "zlib output should start with 0x78");
        // decompress() must detect and handle it
        let result = decompress(&zlib_bytes).expect("decompress should handle legacy zlib");
        assert_eq!(result, input);
    }

    #[test]
    fn test_decompress_bytes_zstd() {
        let input = b"test payload for decompress_bytes zstd path";
        let compressed = zstd_compress(input).expect("zstd compress");
        let out = decompress_bytes(&compressed).expect("decompress_bytes zstd");
        assert_eq!(out, input);
    }

    #[test]
    fn test_decompress_bytes_zlib() {
        let input = b"test payload for decompress_bytes zlib legacy path";
        let compressed = zlib_compress(input).expect("zlib compress");
        let out = decompress_bytes(&compressed).expect("decompress_bytes zlib");
        assert_eq!(out, input);
    }

    #[test]
    fn test_decompress_bytes_unknown_codec_errors() {
        let garbage = b"\x00\x01\x02\x03invalid";
        let result = decompress_bytes(garbage);
        assert!(result.is_err(), "unknown codec should return Err");
    }

    #[test]
    fn test_compute_signature() {
        let sig = compute_signature(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            1_700_000_000_000.0,
            "test-secret",
        );
        assert_eq!(sig, "650eb9dd6c396a45");
    }

    #[test]
    fn test_compute_signature_with_length() {
        let sig16 = compute_signature_with_length(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            1_700_000_000_000.0,
            "test-secret",
            16,
        );
        let sig32 = compute_signature_with_length(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            1_700_000_000_000.0,
            "test-secret",
            32,
        );
        assert_eq!(sig16, "650eb9dd6c396a45");
        assert_eq!(sig16.len(), 16);
        assert_eq!(sig32.len(), 32);
        assert!(sig32.starts_with(&sig16));
    }

    #[test]
    fn test_generate_signed_url_with_path_prefix() {
        let url = generate_signed_url(&SignedUrlBuildRequest {
            base_url: "https://api.example.com",
            path_prefix: "attachments",
            slug: "xK9mP2nQ",
            agent_id: "test-agent",
            conversation_id: "conv_123",
            expires_at: 1_700_000_000_000,
            secret: "test-secret",
            sig_length: 32,
        })
        .expect("signed URL should build");

        assert!(url.starts_with("https://api.example.com/attachments/xK9mP2nQ?"));
        assert!(url.contains("sig="));
    }

    #[test]
    fn test_derive_signing_key() {
        let key = derive_signing_key("sk_live_abc123");
        assert_eq!(
            key,
            "fb5f79640e9ed141d4949ccb36110c7aaf829c56d9870942dd77219a57575372"
        );
    }

    #[test]
    fn test_generate_id_format() {
        let id = generate_id();
        assert_eq!(id.len(), 8);
        assert!(id.chars().all(|c| c.is_ascii_alphanumeric()));
    }

    #[test]
    fn test_generate_id_uniqueness() {
        let ids: Vec<String> = (0..100).map(|_| generate_id()).collect();
        let unique: std::collections::HashSet<&String> = ids.iter().collect();
        assert_eq!(unique.len(), 100, "generated IDs should be unique");
    }

    #[test]
    fn test_compute_org_signature() {
        let sig = compute_org_signature(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            "org_456",
            1_700_000_000_000.0,
            "test-secret",
        );
        assert_eq!(sig.len(), 32);
        let non_org_sig = compute_signature_with_length(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            1_700_000_000_000.0,
            "test-secret",
            32,
        );
        assert_ne!(sig, non_org_sig);
    }

    #[test]
    fn test_compute_org_signature_with_length() {
        let sig16 = compute_org_signature_with_length(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            "org_456",
            1_700_000_000_000.0,
            "test-secret",
            16,
        );
        let sig32 = compute_org_signature_with_length(
            "xK9mP2nQ",
            "test-agent",
            "conv_123",
            "org_456",
            1_700_000_000_000.0,
            "test-secret",
            32,
        );
        assert_eq!(sig16.len(), 16);
        assert_eq!(sig32.len(), 32);
        assert!(sig32.starts_with(&sig16));
    }

    #[test]
    fn test_is_expired() {
        assert!(!is_expired(0.0));
        assert!(is_expired(1.0));
        assert!(!is_expired(f64::MAX));
    }

    #[test]
    fn test_verify_signed_url_accepts_32_char_signature_and_path_prefix() {
        let url = generate_signed_url(&SignedUrlBuildRequest {
            base_url: "https://api.example.com",
            path_prefix: "attachments",
            slug: "xK9mP2nQ",
            agent_id: "test-agent",
            conversation_id: "conv_123",
            expires_at: u64::MAX / 2,
            secret: "test-secret",
            sig_length: 32,
        })
        .expect("signed URL should build");

        let params = verify_signed_url(&url, "test-secret").expect("signed URL should verify");
        assert_eq!(params.slug, "xK9mP2nQ");
        assert_eq!(params.agent_id, "test-agent");
        assert_eq!(params.conversation_id, "conv_123");
    }

    #[test]
    fn test_verify_signed_url_exp_zero_never_expires() {
        let url = generate_signed_url(&SignedUrlBuildRequest {
            base_url: "https://api.example.com",
            path_prefix: "attachments",
            slug: "xK9mP2nQ",
            agent_id: "test-agent",
            conversation_id: "conv_123",
            expires_at: 0,
            secret: "test-secret",
            sig_length: 32,
        })
        .expect("signed URL should build");

        let params = verify_signed_url(&url, "test-secret").expect("exp=0 should never expire");
        assert_eq!(params.slug, "xK9mP2nQ");
        assert_eq!(params.expires_at, 0);
    }
}