mahbot 0.3.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Session persistence — Turso-backed store + native history decoding.

pub mod manager;
pub use manager::Session;

use crate::turso::{self, IntoParams, Row, TxGuard, Value, params};
use crate::{ChatMessage, ChatRole, Reasoning, ToolCall};
use anyhow::{Result, anyhow};
use chrono::{DateTime, Utc};

// ── Summarization constants ──────────────────────────────────
//
// The summarization LLM call lives in `crate::Agent::summarize` so that all
// parameters (model, temperature, reasoning_effort, tools, provider routing)
// are byte-identical to the agent's work loop.  This section keeps only the
// constants and helpers used by `Session::apply_summary`.

/// History-length threshold (in estimated tokens) that triggers summarization.
///
/// This is a conservative default chosen to work across models with varying
/// context window sizes (128K–1M).  The value of **65,000** estimated tokens
/// translates to roughly 260K characters of message content under the rough
/// `estimate_tokens` formula (~4 chars/token + 4 tokens per-message overhead).
///
/// ## Why 65K?
///
/// The actual token consumption at request time is higher than `estimate_tokens`
/// suggests for several reasons:
///
/// * **Tokenization ratio** — Code- and JSON-heavy agent conversations (tool
///   calls, structured outputs) can tokenize at ~2.5 chars/token rather than
///   the estimate's 4 chars/token, making the real token count ~1.6× higher.
/// * **Tool schemas** — The tool definitions injected by `build_chat_request`
///   consume ~10–20K actual tokens that are **not** counted by `estimate_tokens`
///   (they live in the `tools` field of the request, not in `messages`).
/// * **System prompt overhead** — The role instruction + workspace context +
///   ticket context are part of `history` and *are* counted, but for large
///   workspaces they add non-trivial context consumption.
/// * **Intra-turn growth** — After summarization the agent loop can add several
///   more tool-call rounds (each adding assistant + tool-result messages) before
///   the next threshold check at the start of the following turn.
///
/// ### Context window breakdown for 65K estimated tokens
///
/// | Model type         | Context | Effective margin |
/// |--------------------|---------|-----------------|
/// | 128K (e.g., GPT-4o) | ~100K actual + ~15K overhead = ~115K → **~13K headroom** |
/// | 200K (e.g., Claude 3.5) | ~160K actual + ~15K overhead = ~175K → **~25K headroom** |
/// | 1M (e.g., DeepSeek V4) | Triggers at ~6.5% of context — very early but cheap |
///
/// ## Configurability
///
/// Per-role overrides (via `RoleConfig.summarization_threshold`) can raise
/// or lower this value for models with unusually large or small context
/// windows without changing the global default.
pub const SUMMARIZATION_THRESHOLD: usize = 65_000;

/// Stored session rows and second `history` entry after compaction use this prefix so channel
/// orchestration can re-inject the summary on later turns (baseline `system` rows stay excluded).
pub const PREVIOUS_CONVERSATION_SUMMARY_PREFIX: &str = "Previous conversation summary:\n\n";

/// Rough token count for history (~4 chars/token + 4 tokens per-message overhead)
#[must_use]
pub fn estimate_tokens(messages: &[ChatMessage]) -> usize {
    messages
        .iter()
        .map(|m| m.content.len().div_ceil(4) + 4)
        .sum()
}

crate::define_store! {
    /// Global session store.
    pub static SESSIONS: SessionStore,
    db_name = "sessions",
    schema = SCHEMA,
    expect = "SESSIONS not initialized",
}

const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS sessions (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    session_key TEXT NOT NULL,
    role        TEXT NOT NULL,
    content     TEXT NOT NULL,
    created_at  TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_key_id ON sessions(session_key, id);

CREATE TABLE IF NOT EXISTS session_metadata (
    session_key   TEXT PRIMARY KEY,
    created_at    TEXT NOT NULL,
    last_activity TEXT NOT NULL
);";

// ── Column index constants ──────────────────────────────────

// Session messages (2-column SELECT: role, content)
crate::columns! {
    SESSION_MESSAGE_COLUMNS [SM] {
        ROLE    => "role",
        CONTENT => "content",
    }
}

// Session list with metadata (3-column SELECT: sm.session_key, sm.last_activity,
// COUNT(s.id))
crate::columns! {
    SESSION_LIST_COLUMNS [SL] {
        SESSION_KEY    => "sm.session_key",
        LAST_ACTIVITY  => "sm.last_activity",
        MESSAGE_COUNT  => "COUNT(s.id)",
    }
}

/// Session key prefixes for transient (background-only, non-user-facing) sessions.
///
/// These sessions are created automatically by agents (analysts, engineers, maintainer,
/// discovery, etc.) and are cleaned up periodically by
/// [`cleanup_old_transient_sessions`].
///
/// User-facing sessions — those the user can directly converse with — persist
/// indefinitely and are intentionally excluded:
/// - Direct chat: `{channel}_{user_name}_{role}_{ws_name}`
/// - Manager: `manager_{ws_name}` — the Manager session carries both chat conversation
///   and notification context and must never be added here.
///
/// If a new agent role is added that can talk to users directly, its session key
/// must also be excluded from this list.
pub(crate) const TRANSIENT_SESSION_PREFIXES: &[&str] =
    &["ticket_", "ask_", "maintainer_", "discovery_"];

#[derive(Debug, Clone)]
pub(crate) struct SessionMetadata {
    pub key: String,
    pub last_activity: DateTime<Utc>,
    pub message_count: usize,
}

/// Parse an RFC 3339 timestamp string, falling back to `Utc::now()` on failure.
///
/// Logs a warning with the field name, the raw value, and the parse error
/// when falling back.
#[must_use]
fn parse_ts_or_now(s: &str, label: &str) -> DateTime<Utc> {
    turso::parse_utc_timestamp(s).unwrap_or_else(|e| {
        tracing::warn!(
            field = %label,
            value = %s,
            error = %e,
            "Failed to parse timestamp {label}, falling back to Utc::now()",
        );
        Utc::now()
    })
}

fn session_metadata_from_row(key: &str, activity_str: &str, count: i64) -> SessionMetadata {
    SessionMetadata {
        key: key.to_string(),
        last_activity: parse_ts_or_now(activity_str, "last_activity"),
        message_count: usize::try_from(count).unwrap_or(0),
    }
}

/// Insert messages into `sessions` and upsert `session_metadata` within an existing transaction.
/// Shared helper used by [`SessionStore::append_messages`].
async fn insert_messages_in_transaction(
    tx: &TxGuard<'_>,
    session_key: &str,
    messages: &[ChatMessage],
) -> Result<()> {
    let now = turso::now();
    for msg in messages {
        tx.execute(
            "INSERT INTO sessions (session_key, role, content, created_at) VALUES (?1, ?2, ?3, ?4)",
            params![
                session_key,
                msg.role.to_string(),
                msg.content.clone(),
                now.clone()
            ],
        )
        .await?;
    }
    tx.execute(
        "INSERT INTO session_metadata (session_key, created_at, last_activity) \
         VALUES (?1, ?2, ?3) \
         ON CONFLICT(session_key) DO UPDATE SET \
         last_activity = excluded.last_activity",
        params![session_key, now.clone(), now],
    )
    .await?;
    Ok(())
}

/// Execute a `query_map`, logging warnings on failure and skipping unparseable rows.
/// Returns an empty [`Vec`] on query error.
///
/// `session_key` is passed as a structured tracing field; when `None`, tracing
/// automatically suppresses it from the output.
async fn query_map_collect<T, E>(
    conn: &turso::Connection,
    sql: &str,
    params: impl IntoParams + Send + 'static,
    row_parser: impl FnMut(&Row) -> std::result::Result<T, E> + Send + 'static,
    warn_context: &str,
    session_key: Option<&str>,
) -> Vec<T>
where
    T: Send + 'static,
    E: std::fmt::Display + Send + Sync + 'static,
{
    let rows = match conn.query_map(sql, params, row_parser).await {
        Ok(rows) => rows,
        Err(e) => {
            tracing::warn!(error = %e, session_key, "{warn_context}: query failed, returning empty");
            return Vec::new();
        }
    };
    rows.into_iter()
        .filter_map(|r| match r {
            Ok(val) => Some(val),
            Err(e) => {
                tracing::warn!(error = %e, session_key, "{warn_context}: row decode failed, skipping");
                None
            }
        })
        .collect()
}

// ── Methods — callable on the static ──────────────────────────

impl SessionStore {
    pub(crate) async fn load(&self, session_key: &str) -> Vec<ChatMessage> {
        query_map_collect(
            &self.conn,
            &format!("SELECT {SESSION_MESSAGE_COLUMNS} FROM sessions WHERE session_key = ?1 ORDER BY id ASC"),
            params![session_key],
            |row| {
                Ok::<_, anyhow::Error>(ChatMessage {
                    role: row.get::<String>(COL_SM_ROLE)?.parse::<ChatRole>().map_err(|e| anyhow!(e))?,
                    content: row.get(COL_SM_CONTENT)?,
                })
            },
            "load session",
            Some(session_key),
        )
        .await
    }

    pub(crate) async fn append(&self, session_key: &str, message: &ChatMessage) -> Result<()> {
        self.batch_append(session_key, std::slice::from_ref(message))
            .await
    }

    async fn append_messages(
        &self,
        session_key: &str,
        messages: &[ChatMessage],
        replace: bool,
    ) -> Result<()> {
        let tx = self.conn.begin_tx().await?;
        if replace {
            tx.execute(
                "DELETE FROM sessions WHERE session_key = ?1",
                params![session_key],
            )
            .await?;
        }
        insert_messages_in_transaction(&tx, session_key, messages).await?;
        tx.commit().await?;
        Ok(())
    }

    pub(crate) async fn batch_append(
        &self,
        session_key: &str,
        messages: &[ChatMessage],
    ) -> Result<()> {
        self.append_messages(session_key, messages, false).await
    }

    pub(crate) async fn replace_messages(
        &self,
        session_key: &str,
        messages: &[ChatMessage],
    ) -> Result<()> {
        self.append_messages(session_key, messages, true).await
    }

    pub(crate) async fn delete(&self, session_key: &str) -> Result<bool> {
        let tx = self.conn.begin_tx().await?;
        let deleted = tx
            .execute(
                "DELETE FROM sessions WHERE session_key = ?1",
                params![session_key],
            )
            .await?;
        tx.execute(
            "DELETE FROM session_metadata WHERE session_key = ?1",
            params![session_key],
        )
        .await?;
        tx.commit().await?;
        Ok(deleted > 0)
    }

    pub(crate) async fn list_sessions_with_metadata(&self) -> Vec<SessionMetadata> {
        query_map_collect(
            &self.conn,
            &format!(
                "SELECT {SESSION_LIST_COLUMNS} \
                 FROM session_metadata sm \
                 LEFT JOIN sessions s ON s.session_key = sm.session_key \
                 GROUP BY sm.session_key \
                 ORDER BY sm.last_activity DESC",
            ),
            (),
            |row| {
                Ok::<_, anyhow::Error>(session_metadata_from_row(
                    &row.get::<String>(COL_SL_SESSION_KEY)?,
                    &row.get::<String>(COL_SL_LAST_ACTIVITY)?,
                    row.get::<i64>(COL_SL_MESSAGE_COUNT)?,
                ))
            },
            "list sessions",
            None,
        )
        .await
    }
}

/// Delete all transient (background-only) sessions whose `last_activity` is older than
/// the given RFC 3339 `cutoff`. Returns the number of deleted session metadata rows.
///
/// Transient session keys start with the prefixes listed in
/// `TRANSIENT_SESSION_PREFIXES`.
///
/// Both `sessions` and `session_metadata` tables are cleaned up in a single transaction.
pub async fn cleanup_old_transient_sessions(cutoff: &str) -> Result<u64> {
    let session_store = store();
    let tx = session_store.conn.begin_tx().await?;

    let likes = TRANSIENT_SESSION_PREFIXES
        .iter()
        .map(|_| "session_key LIKE ?")
        .collect::<Vec<_>>()
        .join(" OR ");
    let prefix_patterns = format!("({likes})");

    let build_params = {
        let mut p = vec![Value::Text(cutoff.to_string())];
        p.extend(
            TRANSIENT_SESSION_PREFIXES
                .iter()
                .map(|prefix| Value::Text(format!("{prefix}%"))),
        );
        p
    };

    // Delete session messages for matching transient sessions
    tx.execute(
        &format!(
            "DELETE FROM sessions WHERE session_key IN ( \
             SELECT session_key FROM session_metadata \
             WHERE last_activity < ? AND {prefix_patterns})"
        ),
        build_params.clone(),
    )
    .await?;

    // Delete the metadata entries themselves
    let deleted = tx
        .execute(
            &format!("DELETE FROM session_metadata WHERE last_activity < ? AND {prefix_patterns}"),
            build_params.clone(),
        )
        .await?;

    tx.commit().await?;

    Ok(deleted)
}

/// Construct a session key for direct (non-ticket) user ↔ agent conversations.
///
/// Format: `{channel}_{user_name}_{role}_{ws_name}`
#[must_use]
pub fn direct_session_key(channel: &str, user_name: &str, role: &str, ws_name: &str) -> String {
    format!("{channel}_{user_name}_{role}_{ws_name}")
}

/// Construct a base session key for ticket-driven agent work.
///
/// The base key format is `ticket_{ticket_id}_{role}`.
///
/// ## Usage
///
/// * **Singular dispatch** (e.g., Engineer at `dispatch_engineer`): the base
///   key is used directly — no suffix is appended.
///
/// * **Parallel agents** (analysts, reviewers, QA via
///   `run_parallel_agents`): the caller appends `_{index}_{suffix}`
///   for disambiguation, producing keys like
///   `ticket_{ticket_id}_{role}_0_nano`.
#[must_use]
pub(crate) fn ticket_session_key(ticket_id: &str, role: &str) -> String {
    format!("ticket_{ticket_id}_{role}")
}

/// Construct a session key for Manager agents (workspace-scoped).
///
/// Format: `manager_{ws_name}`
#[must_use]
pub fn manager_session_key(ws_name: &str) -> String {
    format!("manager_{ws_name}")
}

/// Construct a session key for a user message, dispatching to the appropriate
/// key format based on role.
///
/// - **Manager** sessions use workspace-scoped keys (`manager_{ws_name}`).
/// - **Non-Manager** sessions use channel-scoped keys
///   (`{channel}_{user_name}_{role}_{ws_name}`).
///
/// This is a convenience wrapper around [`manager_session_key`] and
/// [`direct_session_key`] that selects the right format based on
/// whether `role` is `"manager"`.
///
/// # Parameter order
///
/// Matches [`direct_session_key`]: `channel` first, then `user_name`,
/// `role`, and `ws_name` last.
#[must_use]
pub fn session_key(channel: &str, user_name: &str, role: &str, ws_name: &str) -> String {
    if role == "manager" {
        manager_session_key(ws_name)
    } else {
        direct_session_key(channel, user_name, role, ws_name)
    }
}

/// Construct a session key for Maintainer agents (workspace-scoped, unique per run).
///
/// Format: `maintainer_{ws_name}_{suffix}`
/// Each run gets a fresh key (via random suffix) — maintainer runs should not
/// accumulate conversation history across maintenance cycles.
#[must_use]
pub(crate) fn maintainer_session_key(ws_name: &str) -> String {
    format!("maintainer_{}_{}", ws_name, crate::generate_suffix())
}

/// Construct a session key for sub-agent asks (Engineer/Maintainer → sub-agent).
///
/// Format: `ask_{ws_name}_{role}_{suffix}`
#[must_use]
pub(crate) fn ask_session_key(ws_name: &str, role: &str) -> String {
    format!("ask_{}_{}_{}", ws_name, role, crate::generate_suffix())
}

/// Construct a session key for workspace role discovery.
///
/// Format: `discovery_{ws_name}_{role}_{suffix}`
#[must_use]
pub(crate) fn discovery_session_key(ws_name: &str, role: &str) -> String {
    format!(
        "discovery_{}_{}_{}",
        ws_name,
        role,
        crate::generate_suffix()
    )
}

// ── Existing tests ──────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static TEST_ID: AtomicU32 = AtomicU32::new(0);

    fn unique_key() -> String {
        format!("s{}", TEST_ID.fetch_add(1, Ordering::Relaxed))
    }

    #[tokio::test]
    async fn session_store_create_and_load() {
        crate::util::test::init_test_stores().await;
        let k = unique_key();
        store()
            .append(&k, &ChatMessage::user("hello"))
            .await
            .unwrap();
        let msgs = store().load(&k).await;
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].content, "hello");
    }

    #[tokio::test]
    async fn session_store_replace_messages() {
        crate::util::test::init_test_stores().await;
        let k = unique_key();
        store().append(&k, &ChatMessage::user("old")).await.unwrap();
        store()
            .replace_messages(&k, &[ChatMessage::user("new")])
            .await
            .unwrap();
        let msgs = store().load(&k).await;
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].content, "new");
    }

    #[tokio::test]
    async fn session_store_delete() {
        crate::util::test::init_test_stores().await;
        let k = unique_key();
        store().append(&k, &ChatMessage::user("a")).await.unwrap();
        assert!(store().delete(&k).await.unwrap());
        assert!(!store().delete(&k).await.unwrap());
    }
}

// ── TRANSIENT SESSION PREFIX GUARDS ───────────────────────────
//
// [`TRANSIENT_SESSION_PREFIXES`] controls which sessions are cleaned up by
// [`cleanup_old_transient_sessions`] (SQL `LIKE '{prefix}%'`, equivalent to
// `key.starts_with(prefix)`).
//
// Two invariants:
// 1. **Forward (no collision)**: User-facing session keys must never start with
//    a transient prefix or the periodic cleanup would silently delete user history.
// 2. **Reverse (inclusion)**: Transient session key builders must produce keys
//    starting with a prefix registered in [`TRANSIENT_SESSION_PREFIXES`];
//    an unregistered prefix means transient sessions never get cleaned up (leak).
//
// Limitations: `forward_no_collision_with_user_facing_sessions` covers
// `direct_session_key()` and `manager_session_key()` patterns.
// `reverse_transient_builders_use_registered_prefixes` covers all transient
// builders (ticket, ask, maintainer, discovery). If a new transient role
// adds a session key builder, add it to the reverse test.
// Channel-name collision (a channel registered as "ticket" or "ask") is an
// orthogonal risk — `starts_with` matches the first key segment (channel
// name), which cannot be guarded by assertion because channel names are
// dynamic. Awareness during channel registration is required.
//
// All builders are pure string functions — these are cheap synchronous tests.
// Assertion `Fix:` messages guide corrective action when an invariant breaks.

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

    /// Known channel identifiers in the system. Must never produce keys
    /// matching a transient prefix.
    const SAFE_CHANNELS: &[&str] = &["telegram", "gui"];

    #[test]
    fn forward_no_collision_with_user_facing_sessions() {
        // For every transient prefix, verify that none of the user-facing
        // session key patterns start with it. Direct keys have the format
        // {channel}_{user}_{role}_{ws}, and `starts_with` only checks the
        // first segment (channel name). Since safe channels ("telegram",
        // "gui") don't match any transient prefix, the role segment (third)
        // has no effect on the assertion outcome — a single role suffices.
        for prefix in TRANSIENT_SESSION_PREFIXES {
            // Manager uses a separate key format (manager_{ws_name}).
            let manager_key = manager_session_key("test-ws");
            assert!(
                !manager_key.starts_with(prefix),
                "MANAGER SESSION KEY COLLISION: \
                 prefix='{prefix}' matches key='{manager_key}'. \
                 Fix: remove '{prefix}' from TRANSIENT_SESSION_PREFIXES \
                 or change the manager_session_key pattern.",
            );

            // Direct chat keys across all safe channels.
            for channel in SAFE_CHANNELS {
                let key = direct_session_key(channel, "testuser", "analyst", "test-ws");
                assert!(
                    !key.starts_with(prefix),
                    "DIRECT SESSION KEY COLLISION: prefix='{prefix}' \
                     matches key='{key}' (channel='{channel}'). \
                     Fix: remove '{prefix}' from TRANSIENT_SESSION_PREFIXES \
                     or change the session key pattern.",
                );
            }
        }
    }

    fn assert_transient_key(key: &str, expected_prefix: &str, builder_expr: &str) {
        assert!(
            key.starts_with(expected_prefix),
            "{builder_expr} = '{key}' does not start with '{expected_prefix}'.\n\
             Fix: update {builder_expr} to produce keys starting with '{expected_prefix}'.",
        );
        assert!(
            TRANSIENT_SESSION_PREFIXES.contains(&expected_prefix),
            "TRANSIENT_SESSION_PREFIXES is missing '{expected_prefix}' — \
             {builder_expr} sessions will never be cleaned up.\n\
             Fix: add \"{expected_prefix}\" to TRANSIENT_SESSION_PREFIXES.",
        );
    }

    #[test]
    fn reverse_transient_builders_use_registered_prefixes() {
        // Each transient key builder must produce keys starting with a
        // prefix that is actually registered in TRANSIENT_SESSION_PREFIXES.
        assert_transient_key(
            &ticket_session_key("abc123", "analyst"),
            "ticket_",
            "ticket_session_key('abc123', 'analyst')",
        );
        assert_transient_key(
            &ask_session_key("ws", "coder"),
            "ask_",
            "ask_session_key('ws', 'coder')",
        );
        assert_transient_key(
            &maintainer_session_key("ws"),
            "maintainer_",
            "maintainer_session_key('ws')",
        );
        assert_transient_key(
            &discovery_session_key("ws", "analyst"),
            "discovery_",
            "discovery_session_key('ws', 'analyst')",
        );
    }

    #[test]
    fn session_key_manager_dispatch() {
        // Manager role produces a manager-scoped key.
        let key = session_key("telegram", "alice", "manager", "my-workspace");
        assert_eq!(key, "manager_my-workspace");
    }

    #[test]
    fn session_key_non_manager_dispatch() {
        // Non-Manager role produces a direct channel-scoped key.
        let key = session_key("discord", "bob", "engineer", "my-workspace");
        assert_eq!(key, "discord_bob_engineer_my-workspace");
    }

    #[test]
    fn session_key_lowercase_manager() {
        // The dispatching uses string comparison `"manager"` — verify it works
        // (matches Role::Manager.as_str() which is lowercase).
        let key = session_key("gui", "carol", "Manager", "ws");
        assert_ne!(key, "manager_ws", "capital-M 'Manager' should NOT match");
        assert_eq!(key, "gui_carol_Manager_ws");
    }
}

#[test]
fn parse_ts_or_now_invalid_fallback() {
    let before = Utc::now();
    let ts = parse_ts_or_now("garbage-input", "test_invalid");
    let after = Utc::now();
    assert!(
        ts >= before - chrono::Duration::seconds(1),
        "fallback ts {ts} should not be before {before}",
    );
    assert!(
        ts <= after + chrono::Duration::seconds(1),
        "fallback ts {ts} should not be after {after}",
    );
}

// ── Native history decoding ────────────────────────────────────

#[derive(Debug)]
pub(crate) enum DecodedNativeHistoryMessage {
    Assistant {
        content: Option<String>,
        tool_calls: Option<Vec<ToolCall>>,
        reasoning: Option<Reasoning>,
    },
    ToolResult {
        tool_call_id: Option<String>,
        content: String,
    },
}

/// Decode a `ChatMessage` whose `content` is a JSON-wrapped native message.
/// Returns `None` if the message doesn't look like a native/session-persisted message.
pub(crate) fn decode_native_history_message(
    message: &ChatMessage,
) -> Option<DecodedNativeHistoryMessage> {
    let parsed = serde_json::from_str::<serde_json::Value>(&message.content).ok();

    if message.role == ChatRole::Assistant
        && let Some(value) = parsed.as_ref()
    {
        let content = value
            .get("content")
            .and_then(serde_json::Value::as_str)
            .map(ToString::to_string);

        // Extract reasoning fields for the Assistant variant.
        let (r, rc, rd) =
            crate::providers::reasoning_roundtrip::json_lossless_assistant_reasoning_fields(value);
        let reasoning = Reasoning::from_optional_parts(r, rc, rd);

        let tool_calls = value
            .get("tool_calls")
            .and_then(|v| serde_json::from_value::<Vec<ToolCall>>(v.clone()).ok())
            .map(|mut parsed_calls| {
                for call in &mut parsed_calls {
                    if let Some(s) = call.arguments.as_str()
                        && let Ok(v) = serde_json::from_str::<serde_json::Value>(s)
                    {
                        call.arguments = v;
                    }
                }
                parsed_calls
            });

        return Some(DecodedNativeHistoryMessage::Assistant {
            content,
            tool_calls,
            reasoning,
        });
    }

    if message.role == ChatRole::Tool
        && let Some(value) = parsed.as_ref()
    {
        return Some(DecodedNativeHistoryMessage::ToolResult {
            tool_call_id: value
                .get("tool_call_id")
                .and_then(serde_json::Value::as_str)
                .map(ToString::to_string),
            content: value
                .get("content")
                .and_then(serde_json::Value::as_str)
                .map_or_else(|| message.content.clone(), ToString::to_string),
        });
    }

    None
}