tokmesh-core 0.1.5

Core library for tokmesh — session parsing, scanning, aggregation, pricing
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
//! MiMo Code session parser
//!
//! Parses messages from:
//! - SQLite database: ~/.local/share/mimocode/mimocode.db

use super::utils::open_readonly_sqlite;
use super::{
    normalize_opencode_agent_name, normalize_workspace_key, workspace_label_from_key,
    UnifiedMessage,
};
use crate::{provider_identity, TokenBreakdown};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;

/// MiMo Code message structure (from SQLite data column)
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct MiMoCodeMessage {
    #[serde(default)]
    pub id: Option<String>,
    pub role: String,
    #[serde(rename = "modelID")]
    pub model_id: Option<String>,
    #[serde(rename = "providerID")]
    pub provider_id: Option<String>,
    pub cost: Option<f64>,
    pub tokens: Option<MiMoCodeTokens>,
    pub time: MiMoCodeTime,
    pub agent: Option<String>,
    pub mode: Option<String>,
    #[serde(default, deserialize_with = "deserialize_micode_path")]
    pub path: Option<MiMoCodePath>,
}

#[derive(Debug, Deserialize)]
pub struct MiMoCodePath {
    pub root: Option<String>,
}

fn deserialize_micode_path<'de, D>(deserializer: D) -> Result<Option<MiMoCodePath>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = serde_json::Value::deserialize(deserializer)?;
    let root = value
        .get("root")
        .and_then(|root| root.as_str())
        .map(str::to_string);

    Ok(Some(MiMoCodePath { root }))
}

#[derive(Debug, Deserialize)]
pub struct MiMoCodeTokens {
    pub input: i64,
    pub output: i64,
    pub reasoning: Option<i64>,
    // MiMo assistant messages may omit `cache` (or its read/write); without a
    // default a missing field would fail deserialization and silently drop the
    // message in the parse loop's `Err(_) => continue` arm.
    #[serde(default)]
    pub cache: Option<MiMoCodeCache>,
}

#[derive(Debug, Default, Deserialize)]
pub struct MiMoCodeCache {
    #[serde(default)]
    pub read: i64,
    #[serde(default)]
    pub write: i64,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct MiMoCodeTime {
    pub created: f64,
    pub completed: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct MiMoCodeSqliteFingerprint {
    created_bits: u64,
    completed_bits: Option<u64>,
    model_id: String,
    provider_id: String,
    input: i64,
    output: i64,
    reasoning: i64,
    cache_read: i64,
    cache_write: i64,
    cost_bits: u64,
    agent: Option<String>,
}

#[derive(Debug, Clone)]
struct MiMoCodeSqliteDedupState {
    has_embedded_message_id: bool,
    has_workspace_conflict: bool,
}

fn workspace_from_root(root: Option<&str>) -> (Option<String>, Option<String>) {
    let workspace_key = root.and_then(normalize_workspace_key);
    let workspace_label = workspace_key.as_deref().and_then(workspace_label_from_key);
    (workspace_key, workspace_label)
}

fn set_workspace_from_root(message: &mut UnifiedMessage, root: Option<&str>) {
    let (workspace_key, workspace_label) = workspace_from_root(root);
    message.set_workspace(workspace_key, workspace_label);
}

fn merge_duplicate_workspace(
    message: &mut UnifiedMessage,
    state: &mut MiMoCodeSqliteDedupState,
    root: Option<&str>,
) {
    if state.has_workspace_conflict {
        return;
    }

    let (candidate_key, candidate_label) = workspace_from_root(root);
    match (message.workspace_key.as_deref(), candidate_key) {
        (None, Some(key)) => message.set_workspace(Some(key), candidate_label),
        (Some(existing), Some(candidate)) if existing != candidate => {
            state.has_workspace_conflict = true;
            message.set_workspace(None, None);
        }
        _ => {}
    }
}

/// Normalize an epoch `time.created`/`time.completed` value to milliseconds.
///
/// MiMo Code is expected to store epoch milliseconds (matching OpenCode), but
/// some builds/channels have been observed writing epoch *seconds*, which made
/// dates land ~1000x in the past (1970-era). A recent epoch is ~1.7e12 in ms
/// versus ~1.7e9 in seconds, so a value at/under the `1e12` threshold is
/// treated as seconds and scaled up. This mirrors `timestamp_secs_to_ms` in the
/// goose/hermes parsers.
fn micode_timestamp_to_ms(timestamp: f64) -> f64 {
    if timestamp > 1e12 {
        timestamp
    } else {
        timestamp * 1000.0
    }
}

fn micode_duration_ms(time: &MiMoCodeTime) -> Option<i64> {
    // Normalize both endpoints so a seconds/ms mismatch (or both-in-seconds)
    // still yields a millisecond duration rather than a value 1000x too small.
    let duration = micode_timestamp_to_ms(time.completed?) - micode_timestamp_to_ms(time.created);
    if duration.is_finite() && duration > 0.0 {
        Some(duration as i64)
    } else {
        None
    }
}

pub fn parse_micode_sqlite(db_path: &Path) -> Vec<UnifiedMessage> {
    let Some(conn) = open_readonly_sqlite(db_path) else {
        return Vec::new();
    };

    let modern_query = r#"
        SELECT m.id, m.session_id, m.data, NULLIF(s.directory, '') AS workspace_root
        FROM message m
        LEFT JOIN session s ON s.id = m.session_id
        WHERE json_extract(m.data, '$.role') = 'assistant'
          AND json_extract(m.data, '$.tokens') IS NOT NULL
        ORDER BY m.id, m.session_id
    "#;

    let legacy_query = r#"
        SELECT m.id, m.session_id, m.data, NULL AS workspace_root
        FROM message m
        WHERE json_extract(m.data, '$.role') = 'assistant'
          AND json_extract(m.data, '$.tokens') IS NOT NULL
        ORDER BY m.id, m.session_id
    "#;

    let mut stmt = match conn
        .prepare(modern_query)
        .or_else(|_| conn.prepare(legacy_query))
    {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };

    let rows = match stmt.query_map([], |row| {
        let id: String = row.get(0)?;
        let session_id: String = row.get(1)?;
        let data_json: String = row.get(2)?;
        let workspace_root: Option<String> = row.get(3)?;
        Ok((id, session_id, data_json, workspace_root))
    }) {
        Ok(r) => r,
        Err(_) => return Vec::new(),
    };

    let mut messages: Vec<UnifiedMessage> = Vec::new();
    let mut fingerprint_indices: HashMap<MiMoCodeSqliteFingerprint, usize> = HashMap::new();
    let mut dedup_states: Vec<MiMoCodeSqliteDedupState> = Vec::new();

    // Namespace ONLY the row-id fallback by the database. MiMo Code uses
    // channel-suffixed databases (mimocode.db and mimocode-<channel>.db), and a
    // mid-session channel switch can write the SAME message to both files. The
    // embedded message id is globally unique, so it must stay un-namespaced to
    // collapse those duplicates across files. SQLite rowids, by contrast, are
    // per-database and not globally unique, so the fallback path namespaces them
    // to avoid falsely merging two different messages that share a rowid.
    let db_namespace = db_path.to_string_lossy().to_string();

    for row_result in rows {
        let (row_id, session_id, data_json, row_workspace_root) = match row_result {
            Ok(r) => r,
            Err(_) => continue,
        };

        let mut bytes = data_json.into_bytes();
        let msg: MiMoCodeMessage = match simd_json::from_slice(&mut bytes) {
            Ok(m) => m,
            Err(_) => continue,
        };

        if msg.role != "assistant" {
            continue;
        }

        let message_id = msg.id.clone();
        let embedded_workspace_root = msg
            .path
            .as_ref()
            .and_then(|path| path.root.as_deref())
            .map(str::to_string);

        let tokens = match msg.tokens {
            Some(t) => t,
            None => continue,
        };

        let model_id = match msg.model_id {
            Some(m) => m,
            None => continue,
        };

        let provider_id = msg.provider_id.unwrap_or_else(|| "unknown".to_string());
        let provider_id =
            provider_identity::canonical_provider(&provider_id).unwrap_or(provider_id);
        let agent_or_mode = msg.mode.or(msg.agent);
        let agent = agent_or_mode.map(|a| normalize_opencode_agent_name(&a));
        let input = tokens.input.max(0);
        let output = tokens.output.max(0);
        let reasoning = tokens.reasoning.unwrap_or(0).max(0);
        let cache = tokens.cache.unwrap_or_default();
        let cache_read = cache.read.max(0);
        let cache_write = cache.write.max(0);
        let cost = msg.cost.unwrap_or(0.0).max(0.0);
        // Normalize epoch values to milliseconds up front so the timestamp, the
        // dedup fingerprint, and the duration all agree even when MiMo writes
        // seconds instead of milliseconds.
        let created_ms = micode_timestamp_to_ms(msg.time.created);
        let completed_ms = msg.time.completed.map(micode_timestamp_to_ms);
        let dedup_key = match message_id.clone() {
            // Embedded ids are globally unique: keep them un-namespaced so the
            // same message in mimocode.db and mimocode-<channel>.db collapses.
            Some(id) => id,
            // Rowids are per-database: namespace to avoid false cross-DB merges.
            None => format!("{db_namespace}:{row_id}"),
        };
        let fingerprint = MiMoCodeSqliteFingerprint {
            created_bits: created_ms.to_bits(),
            completed_bits: completed_ms.map(f64::to_bits),
            model_id: model_id.clone(),
            provider_id: provider_id.clone(),
            input,
            output,
            reasoning,
            cache_read,
            cache_write,
            cost_bits: cost.to_bits(),
            agent: agent.clone(),
        };

        let mut unified = UnifiedMessage::new_with_agent(
            "micode",
            model_id,
            provider_id,
            session_id,
            // `time.created` is normalized to epoch milliseconds above (MiMo
            // matches OpenCode's ms, but some channels write seconds);
            // UnifiedMessage's timestamp_to_date treats it as ms.
            created_ms as i64,
            TokenBreakdown {
                input,
                output,
                cache_read,
                cache_write,
                reasoning,
            },
            cost,
            agent,
        );
        unified.duration_ms = micode_duration_ms(&msg.time);
        unified.dedup_key = Some(dedup_key);
        let workspace_root = row_workspace_root
            .as_deref()
            .or(embedded_workspace_root.as_deref());
        set_workspace_from_root(&mut unified, workspace_root);

        if let Some(index) = fingerprint_indices.get(&fingerprint).copied() {
            let dedup_state = &mut dedup_states[index];
            if message_id.is_some() && !dedup_state.has_embedded_message_id {
                dedup_state.has_embedded_message_id = true;
                messages[index].dedup_key = unified.dedup_key;
            }
            merge_duplicate_workspace(&mut messages[index], dedup_state, workspace_root);
            continue;
        }

        dedup_states.push(MiMoCodeSqliteDedupState {
            has_embedded_message_id: message_id.is_some(),
            has_workspace_conflict: false,
        });
        fingerprint_indices.insert(fingerprint, messages.len());
        messages.push(unified);
    }

    messages
}

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

    fn create_micode_sqlite_db(db_path: &Path) -> Connection {
        let conn = Connection::open(db_path).unwrap();
        conn.execute_batch(
            "CREATE TABLE message (
                id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL,
                data TEXT NOT NULL
            );",
        )
        .unwrap();
        conn
    }

    #[test]
    fn test_parse_micode_sqlite_basic() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");

        let conn = create_micode_sqlite_db(&db_path);

        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": {
                "input": 1000,
                "output": 500,
                "reasoning": 100,
                "cache": { "read": 200, "write": 50 }
            },
            "time": { "created": 1700000000000.0, "completed": 1700000001234.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_001", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].client, "micode");
        assert_eq!(messages[0].model_id, "mimo-v2.5-pro");
        assert_eq!(messages[0].provider_id, "mimo");
        assert_eq!(messages[0].tokens.input, 1000);
        assert_eq!(messages[0].tokens.output, 500);
        assert_eq!(messages[0].tokens.reasoning, 100);
        assert_eq!(messages[0].tokens.cache_read, 200);
        assert_eq!(messages[0].tokens.cache_write, 50);
        assert!((messages[0].cost - 0.05).abs() < 1e-9);
        assert_eq!(messages[0].duration_ms, Some(1234));
    }

    #[test]
    fn test_parse_micode_sqlite_skips_user_messages() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");

        let conn = create_micode_sqlite_db(&db_path);

        let user_msg = r#"{
            "role": "user",
            "modelID": "mimo-v2.5-pro",
            "time": { "created": 1700000000000.0 }
        }"#;

        let assistant_msg = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "tokens": { "input": 100, "output": 50, "reasoning": 0, "cache": { "read": 0, "write": 0 } },
            "time": { "created": 1700000001000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_user", "ses_001", user_msg],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_assistant", "ses_001", assistant_msg],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        // This message carries no embedded JSON id, so the dedup key falls back
        // to the SQLite row id and is namespaced by the database path.
        assert!(messages[0]
            .dedup_key
            .as_deref()
            .is_some_and(|key| key.ends_with(":msg_assistant")));
    }

    /// Regression: MiMo Code uses channel-suffixed databases (mimocode.db and
    /// mimocode-<channel>.db). A mid-session channel switch can write the SAME
    /// message (same embedded id) to both files. The embedded id must NOT be
    /// namespaced by the database, otherwise the cross-file dedup set produces
    /// two distinct keys and the message's cost + tokens get counted twice.
    #[test]
    fn embedded_message_id_is_not_namespaced_by_database() {
        let dir = tempfile::tempdir().unwrap();
        let db_a = dir.path().join("mimocode.db");
        let db_b = dir.path().join("mimocode-beta.db");
        // Embedded JSON "id" is the globally unique message id.
        let msg = r#"{
            "id": "msg_shared",
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": { "input": 10, "output": 5 },
            "time": { "created": 1700000000000.0 }
        }"#;
        // Different SQLite row ids prove the collapse is driven by the embedded
        // id (not the row id), exactly as a mid-session channel switch records.
        for (db, row_id) in [(&db_a, "row_a"), (&db_b, "row_b")] {
            let conn = create_micode_sqlite_db(db);
            conn.execute(
                "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
                rusqlite::params![row_id, "ses_1", msg],
            )
            .unwrap();
            drop(conn);
        }

        let a = parse_micode_sqlite(&db_a);
        let b = parse_micode_sqlite(&db_b);
        assert_eq!(a.len(), 1);
        assert_eq!(b.len(), 1);
        // Same embedded id across both channel databases yields IDENTICAL,
        // un-namespaced dedup keys, so a shared dedup set collapses the
        // duplicate to a single count.
        assert_eq!(a[0].dedup_key, Some("msg_shared".to_string()));
        assert_eq!(b[0].dedup_key, Some("msg_shared".to_string()));

        // Prove the collapse end-to-end with the same HashSet logic used by the
        // cross-file aggregation in lib.rs.
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        let kept: Vec<_> = a
            .into_iter()
            .chain(b)
            .filter(|m| m.dedup_key.as_ref().is_none_or(|k| seen.insert(k.clone())))
            .collect();
        assert_eq!(kept.len(), 1, "shared embedded id must be counted once");
    }

    /// Two DIFFERENT messages that happen to share a SQLite rowid across two
    /// databases (rowids are per-database, not globally unique) must NOT be
    /// collapsed by the cross-file dedup set. The row-id fallback path is
    /// namespaced by database precisely to keep them distinct.
    #[test]
    fn rowid_fallback_is_namespaced_by_database() {
        let dir = tempfile::tempdir().unwrap();
        let db_a = dir.path().join("a.db");
        let db_b = dir.path().join("b.db");
        // No embedded "id" field -> the parser falls back to the SQLite rowid.
        let msg = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": { "input": 10, "output": 5 },
            "time": { "created": 1700000000000.0 }
        }"#;
        for db in [&db_a, &db_b] {
            let conn = create_micode_sqlite_db(db);
            // Same SQLite row id ("id" column) in both databases. With no
            // embedded JSON id, the parser falls back to this row id.
            conn.execute(
                "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
                rusqlite::params!["row_shared", "ses_1", msg],
            )
            .unwrap();
            drop(conn);
        }

        let a = parse_micode_sqlite(&db_a);
        let b = parse_micode_sqlite(&db_b);
        assert_eq!(a.len(), 1);
        assert_eq!(b.len(), 1);
        // Same row id ("row_shared") in two databases must yield DISTINCT,
        // db-namespaced keys so the two unrelated messages are not merged.
        assert_ne!(a[0].dedup_key, b[0].dedup_key);
        assert!(a[0].dedup_key.as_deref().unwrap().ends_with(":row_shared"));
        assert!(b[0].dedup_key.as_deref().unwrap().ends_with(":row_shared"));

        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        let kept: Vec<_> = a
            .into_iter()
            .chain(b)
            .filter(|m| m.dedup_key.as_ref().is_none_or(|k| seen.insert(k.clone())))
            .collect();
        assert_eq!(
            kept.len(),
            2,
            "rowid collisions across DBs must stay distinct"
        );
    }

    #[test]
    fn test_parse_micode_sqlite_negative_values_clamped() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");

        let conn = create_micode_sqlite_db(&db_path);

        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": -0.05,
            "tokens": {
                "input": -100,
                "output": -50,
                "reasoning": -25,
                "cache": { "read": -200, "write": -10 }
            },
            "time": { "created": 1700000000000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_negative", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].tokens.input, 0);
        assert_eq!(messages[0].tokens.output, 0);
        assert_eq!(messages[0].tokens.cache_read, 0);
        assert_eq!(messages[0].tokens.cache_write, 0);
        assert_eq!(messages[0].tokens.reasoning, 0);
        assert!(messages[0].cost >= 0.0);
    }

    #[test]
    fn test_parse_micode_sqlite_dedup_forked_history() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");
        let conn = create_micode_sqlite_db(&db_path);

        let root_msg = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": {
                "input": 1000,
                "output": 500,
                "reasoning": 25,
                "cache": { "read": 200, "write": 50 }
            },
            "time": { "created": 1700000000000.0, "completed": 1700000000500.0 }
        }"#;

        let new_msg = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.08,
            "tokens": {
                "input": 1300,
                "output": 650,
                "reasoning": 40,
                "cache": { "read": 100, "write": 0 }
            },
            "time": { "created": 1700000001000.0, "completed": 1700000001500.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["root_row", "root_session", root_msg],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["fork_copy_row", "fork_session", root_msg],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["fork_new_row", "fork_session", new_msg],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].tokens.input, 1000);
        assert_eq!(messages[1].tokens.input, 1300);
    }

    #[test]
    fn test_parse_micode_sqlite_workspace_from_session() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");
        let conn = create_micode_sqlite_db(&db_path);
        conn.execute_batch(
            "CREATE TABLE session (
                id TEXT PRIMARY KEY,
                directory TEXT NOT NULL
            );",
        )
        .unwrap();
        conn.execute(
            "INSERT INTO session (id, directory) VALUES (?1, ?2)",
            rusqlite::params!["ses_001", "/Users/alice/micode-repo"],
        )
        .unwrap();

        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": {
                "input": 1000,
                "output": 500,
                "reasoning": 0,
                "cache": { "read": 200, "write": 50 }
            },
            "time": { "created": 1700000000000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_ws", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        assert_eq!(
            messages[0].workspace_key.as_deref(),
            Some("/Users/alice/micode-repo")
        );
        assert_eq!(messages[0].workspace_label.as_deref(), Some("micode-repo"));
    }

    #[test]
    fn test_parse_micode_sqlite_with_agent() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");
        let conn = create_micode_sqlite_db(&db_path);

        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "agent": "build",
            "cost": 0.05,
            "tokens": {
                "input": 1000,
                "output": 500,
                "reasoning": 100,
                "cache": { "read": 200, "write": 50 }
            },
            "time": { "created": 1700000000000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_agent", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].agent, Some("Build".to_string()));
    }

    /// `time.created` was hard-assumed to be epoch
    /// milliseconds. If MiMo writes epoch *seconds*, the date landed ~1000x in
    /// the past (1970-era). A ms-valued and a seconds-valued `time.created` that
    /// denote the SAME instant must normalize to the same date and the same
    /// (millisecond-scale) timestamp. Without `micode_timestamp_to_ms`, the
    /// seconds variant would yield 1970-01-20 instead of 2023-11-14.
    #[test]
    fn test_parse_micode_sqlite_normalizes_seconds_and_milliseconds() {
        let dir = tempfile::tempdir().unwrap();
        let db_ms = dir.path().join("ms.db");
        let db_secs = dir.path().join("secs.db");

        // 1_700_000_000 s == 1_700_000_000_000 ms == 2023-11-14T22:13:20Z.
        let msg_ms = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": { "input": 10, "output": 5 },
            "time": { "created": 1700000000000.0, "completed": 1700000001234.0 }
        }"#;
        // Same instant, expressed in epoch SECONDS (the bugged-input shape).
        let msg_secs = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": { "input": 10, "output": 5 },
            "time": { "created": 1700000000.0, "completed": 1700000001.234 }
        }"#;

        for (db, data) in [(&db_ms, msg_ms), (&db_secs, msg_secs)] {
            let conn = create_micode_sqlite_db(db);
            conn.execute(
                "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
                rusqlite::params!["msg_1", "ses_1", data],
            )
            .unwrap();
            drop(conn);
        }

        let ms = parse_micode_sqlite(&db_ms);
        let secs = parse_micode_sqlite(&db_secs);
        assert_eq!(ms.len(), 1);
        assert_eq!(secs.len(), 1);

        // Both inputs resolve to the SAME instant: identical timestamp (ms) and
        // identical, non-empty (i.e. not 1970-era-then-formatted) date.
        assert_eq!(ms[0].timestamp, 1_700_000_000_000);
        assert_eq!(secs[0].timestamp, 1_700_000_000_000);
        assert_eq!(ms[0].date, secs[0].date);
        assert!(!ms[0].date.is_empty());

        // Duration is in milliseconds for BOTH representations (~1234 ms), not
        // ~1 (which is what the seconds input would have produced unnormalized).
        assert_eq!(ms[0].duration_ms, Some(1234));
        assert_eq!(secs[0].duration_ms, Some(1234));
    }

    /// A non-object `path` field (e.g. a bare string instead of `{ "root": .. }`)
    /// must not crash deserialization or fail the whole message: the custom
    /// `deserialize_micode_path` extracts `root` defensively, leaving it `None`.
    /// The message must still parse and have no embedded-path workspace.
    #[test]
    fn test_parse_micode_sqlite_non_object_path_field() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");
        let conn = create_micode_sqlite_db(&db_path);

        // `path` is a string, not an object — the deserializer's `.get("root")`
        // returns None rather than erroring, so the message survives.
        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": { "input": 100, "output": 50 },
            "path": "/some/string/not/an/object",
            "time": { "created": 1700000000000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_badpath", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(
            messages.len(),
            1,
            "non-object path must not drop the message"
        );
        assert_eq!(messages[0].tokens.input, 100);
        // No usable root -> no workspace derived from the embedded path.
        assert_eq!(messages[0].workspace_key, None);
        assert_eq!(messages[0].workspace_label, None);
    }

    /// Legacy-query fallback: when the database has no `session` table, the
    /// modern query (which JOINs `session`) fails to prepare and the parser
    /// falls back to `legacy_query`. In that path `workspace_root` from the row
    /// is NULL, so the workspace must come from the message's EMBEDDED `path.root`.
    #[test]
    fn test_parse_micode_sqlite_legacy_fallback_embedded_path_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");
        // Note: create_micode_sqlite_db creates ONLY the `message` table, so the
        // modern query's `LEFT JOIN session` cannot prepare and we exercise the
        // legacy fallback.
        let conn = create_micode_sqlite_db(&db_path);

        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": { "input": 100, "output": 50 },
            "path": { "root": "/Users/bob/embedded-repo" },
            "time": { "created": 1700000000000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_embedded", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        // Row workspace_root is NULL on the legacy path, so the embedded
        // `path.root` supplies the workspace.
        assert_eq!(
            messages[0].workspace_key.as_deref(),
            Some("/Users/bob/embedded-repo")
        );
        assert_eq!(
            messages[0].workspace_label.as_deref(),
            Some("embedded-repo")
        );
    }

    #[test]
    fn test_parse_micode_sqlite_missing_cache_defaults_to_zero() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_micode.db");
        let conn = create_micode_sqlite_db(&db_path);

        // Assistant payload with no `cache` object at all — must parse (not be
        // dropped) with cache tokens defaulting to 0.
        let data_json = r#"{
            "role": "assistant",
            "modelID": "mimo-v2.5-pro",
            "providerID": "mimo",
            "cost": 0.05,
            "tokens": {
                "input": 1000,
                "output": 500,
                "reasoning": 100
            },
            "time": { "created": 1700000000000.0 }
        }"#;

        conn.execute(
            "INSERT INTO message (id, session_id, data) VALUES (?1, ?2, ?3)",
            rusqlite::params!["msg_no_cache", "ses_001", data_json],
        )
        .unwrap();
        drop(conn);

        let messages = parse_micode_sqlite(&db_path);
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].tokens.input, 1000);
        assert_eq!(messages[0].tokens.output, 500);
        assert_eq!(messages[0].tokens.cache_read, 0);
        assert_eq!(messages[0].tokens.cache_write, 0);
    }
}