zeptoclaw 0.6.2

Ultra-lightweight personal AI assistant
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
//! Context builder for agent conversations
//!
//! This module provides the `ContextBuilder` for constructing the system prompt
//! and message history for LLM conversations. It also provides `RuntimeContext`
//! for injecting environment-awareness into the agent's system prompt.

use chrono::Local;

use crate::session::Message;

/// Format a timestamp envelope for a user message.
///
/// Returns a string like "[Mon 2026-02-16 12:51 +08:00]" to prepend to user messages.
/// Uses the system's local timezone via `chrono::Local`.
pub fn format_message_envelope() -> String {
    format!("[{}]", Local::now().format("%a %Y-%m-%d %H:%M %:z"))
}

/// Default system prompt for ZeptoClaw agent
const DEFAULT_SYSTEM_PROMPT: &str = r#"You are ZeptoClaw, an ultra-lightweight personal AI assistant.

You have access to tools to help accomplish tasks. Use them when needed.

Be concise but helpful. Focus on completing the user's request efficiently.

You have a longterm_memory tool. Use it proactively to:
- Save important facts, user preferences, and decisions for future recall
- Recall relevant information from past conversations by calling longterm_memory with action "search"
- Pin critical information that should always be available

## Scheduled & Background Messages

When a message begins with `Reminder:`, it was delivered by the scheduler on behalf of the user — not typed by them now. Respond with a friendly, concise notification of the reminder content, as if you're the reminder itself notifying the user.

When a message is the heartbeat prompt (checking workspace tasks), reply with `HEARTBEAT_OK` if there is nothing actionable to do, or take the requested action if there is."#;

/// System prompt suffix for first-run persona guidance.
// Wired in by the persona override extraction task (common.rs); suppress
// the dead_code lint until that integration step is complete.
#[allow(dead_code)]
pub const FIRST_RUN_PERSONA_PROMPT: &str = r#"

## First Conversation Setup

This appears to be a new chat. Take a moment to introduce yourself briefly and ask the user what kind of assistant they'd like you to be. Offer these options:

1. **Default** — balanced and helpful
2. **Concise** — short, direct answers
3. **Friendly** — warm and conversational
4. **Professional** — formal and structured
5. **Creative** — playful and imaginative
6. **Technical** — detailed expert mode

Say something like: "Hi! I'm your AI assistant. I can adapt my style to suit you. Would you like me to be concise, friendly, professional, creative, or technical? Or just say 'default' for a balanced approach. You can also describe any custom style you'd like!"

After the user responds, save their preference using longterm_memory with key "persona_pref:{chat_id}" and apply it going forward."#;

/// Runtime context injected into the system prompt to make agents environment-aware.
///
/// This struct captures information about the agent's runtime environment such as
/// the channel it is running on, available tools, current time, workspace path,
/// and OS/platform details. When rendered, it produces a `## Runtime Context`
/// section appended to the system prompt.
///
/// # Example
///
/// ```rust
/// use zeptoclaw::agent::RuntimeContext;
///
/// let ctx = RuntimeContext::new()
///     .with_channel("telegram")
///     .with_tools(vec!["shell".to_string(), "web_search".to_string()])
///     .with_workspace("/home/user/project")
///     .with_os_info();
///
/// let rendered = ctx.render().unwrap();
/// assert!(rendered.contains("Channel: telegram"));
/// assert!(rendered.contains("shell, web_search"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct RuntimeContext {
    /// The channel the agent is running on (e.g., "telegram", "cli", "whatsapp", "discord")
    pub channel: Option<String>,
    /// Names of available tools
    pub available_tools: Vec<String>,
    /// Timezone label (e.g., "Asia/Kuala_Lumpur"). When set, current time is
    /// computed **live** in `render()` via `chrono::Local` so it is never stale.
    /// The label is displayed in the system prompt for the LLM's awareness.
    pub timezone: Option<String>,
    /// Workspace path
    pub workspace: Option<String>,
    /// OS/platform info (e.g., "linux aarch64", "macos aarch64")
    pub os_info: Option<String>,
}

impl RuntimeContext {
    /// Create a new empty runtime context.
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::RuntimeContext;
    ///
    /// let ctx = RuntimeContext::new();
    /// assert!(ctx.is_empty());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the channel name.
    ///
    /// # Arguments
    /// * `channel` - The channel identifier (e.g., "telegram", "cli", "discord")
    pub fn with_channel(mut self, channel: &str) -> Self {
        self.channel = Some(channel.to_string());
        self
    }

    /// Set the list of available tool names.
    ///
    /// # Arguments
    /// * `tools` - Vector of tool name strings
    pub fn with_tools(mut self, tools: Vec<String>) -> Self {
        self.available_tools = tools;
        self
    }

    /// Set the current time to now (UTC).
    #[deprecated(note = "Use with_timezone() instead for live time computation")]
    pub fn with_current_time(mut self) -> Self {
        self.timezone = Some("UTC".to_string());
        self
    }

    /// Set the timezone label and enable time display in the system prompt.
    ///
    /// When a timezone is set, `render()` computes the current local time
    /// dynamically via `chrono::Local` so it is always fresh. The timezone
    /// string is shown as an informational label for the LLM.
    ///
    /// # Arguments
    /// * `tz` - Timezone label (e.g., "Asia/Kuala_Lumpur", "US/Pacific", "UTC")
    pub fn with_timezone(mut self, tz: &str) -> Self {
        self.timezone = Some(tz.to_string());
        self
    }

    /// Set the workspace path.
    ///
    /// # Arguments
    /// * `workspace` - The workspace directory path
    pub fn with_workspace(mut self, workspace: &str) -> Self {
        self.workspace = Some(workspace.to_string());
        self
    }

    /// Set the OS/platform info from the current environment.
    pub fn with_os_info(mut self) -> Self {
        self.os_info = Some(format!(
            "{} {}",
            std::env::consts::OS,
            std::env::consts::ARCH
        ));
        self
    }

    /// Check if any context field is set.
    ///
    /// Returns `true` if no fields have been populated.
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::RuntimeContext;
    ///
    /// assert!(RuntimeContext::new().is_empty());
    /// assert!(!RuntimeContext::new().with_channel("cli").is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.channel.is_none()
            && self.available_tools.is_empty()
            && self.timezone.is_none()
            && self.workspace.is_none()
            && self.os_info.is_none()
    }

    /// Render the context as a markdown section for the system prompt.
    ///
    /// Returns `None` if no context fields are set.
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::RuntimeContext;
    ///
    /// let ctx = RuntimeContext::new().with_channel("cli");
    /// let rendered = ctx.render().unwrap();
    /// assert!(rendered.starts_with("## Runtime Context"));
    /// assert!(rendered.contains("Channel: cli"));
    /// ```
    pub fn render(&self) -> Option<String> {
        if self.is_empty() {
            return None;
        }

        let mut parts = Vec::new();
        if let Some(ref channel) = self.channel {
            parts.push(format!("- Channel: {}", channel));
        }
        if !self.available_tools.is_empty() {
            parts.push(format!(
                "- Available tools: {}",
                self.available_tools.join(", ")
            ));
        }
        // Compute current time LIVE via chrono::Local (never stale).
        // The timezone label comes from config (auto-detected IANA name),
        // but we always show the actual system offset to avoid contradictions.
        if self.timezone.is_some() {
            let now = Local::now();
            parts.push(format!(
                "- Current time: {}",
                now.format("%a %Y-%m-%d %H:%M %:z")
            ));
            parts.push(format!("- Timezone: {}", now.format("%:z")));
        }
        if let Some(ref workspace) = self.workspace {
            parts.push(format!("- Workspace: {}", workspace));
        }
        if let Some(ref os) = self.os_info {
            parts.push(format!("- Platform: {}", os));
        }

        Some(format!("## Runtime Context\n\n{}", parts.join("\n")))
    }
}

/// Builder for constructing conversation context for LLM calls.
///
/// The `ContextBuilder` helps construct the full message list including
/// system prompts, skills information, conversation history, and user input.
///
/// # Example
///
/// ```rust
/// use zeptoclaw::agent::ContextBuilder;
/// use zeptoclaw::session::Message;
///
/// let builder = ContextBuilder::new()
///     .with_skills("- /help: Show help information");
///
/// let messages = builder.build_messages(&[], "Hello!");
/// assert_eq!(messages.len(), 2); // system + user message
/// ```
pub struct ContextBuilder {
    /// The system prompt to use
    system_prompt: String,
    /// Optional SOUL.md content prepended before system prompt
    soul_prompt: Option<String>,
    /// Optional skills content to append to system prompt
    skills_prompt: Option<String>,
    /// Optional runtime context to append to system prompt
    runtime_context: Option<RuntimeContext>,
    /// Optional memory context to append to system prompt
    memory_context: Option<String>,
}

impl ContextBuilder {
    /// Create a new context builder with the default system prompt.
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    ///
    /// let builder = ContextBuilder::new();
    /// let system = builder.build_system_message();
    /// assert!(system.content.contains("ZeptoClaw"));
    /// ```
    pub fn new() -> Self {
        Self {
            system_prompt: DEFAULT_SYSTEM_PROMPT.to_string(),
            soul_prompt: None,
            skills_prompt: None,
            runtime_context: None,
            memory_context: None,
        }
    }

    /// Set a custom system prompt.
    ///
    /// # Arguments
    /// * `prompt` - The custom system prompt to use
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    ///
    /// let builder = ContextBuilder::new()
    ///     .with_system_prompt("You are a helpful assistant.");
    /// let system = builder.build_system_message();
    /// assert!(system.content.contains("helpful assistant"));
    /// ```
    pub fn with_system_prompt(mut self, prompt: &str) -> Self {
        self.system_prompt = prompt.to_string();
        self
    }

    /// Set SOUL.md identity content, prepended before the system prompt.
    ///
    /// SOUL.md defines the agent's personality, values, and behavioral
    /// constraints. Content is prepended to the system prompt so it takes
    /// priority in the LLM's context.
    ///
    /// # Arguments
    /// * `content` - The SOUL.md content to prepend
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    ///
    /// let builder = ContextBuilder::new()
    ///     .with_soul("You are kind and empathetic.");
    /// let system = builder.build_system_message();
    /// assert!(system.content.starts_with("You are kind"));
    /// ```
    pub fn with_soul(mut self, content: &str) -> Self {
        self.soul_prompt = Some(content.to_string());
        self
    }

    /// Add skills information to the system prompt.
    ///
    /// Skills content is appended to the system prompt under an
    /// "Available Skills" section.
    ///
    /// # Arguments
    /// * `skills_content` - The skills documentation to include
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    ///
    /// let builder = ContextBuilder::new()
    ///     .with_skills("- /search: Search the web\n- /help: Show help");
    /// let system = builder.build_system_message();
    /// assert!(system.content.contains("Available Skills"));
    /// assert!(system.content.contains("/search"));
    /// ```
    pub fn with_skills(mut self, skills_content: &str) -> Self {
        self.skills_prompt = Some(skills_content.to_string());
        self
    }

    /// Add runtime context to the system prompt.
    ///
    /// Runtime context provides the agent with awareness of its environment
    /// including the channel, available tools, current time, workspace, and
    /// platform information.
    ///
    /// If the provided context is empty (no fields set), it is ignored.
    ///
    /// # Arguments
    /// * `ctx` - The runtime context to inject
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::{ContextBuilder, RuntimeContext};
    ///
    /// let ctx = RuntimeContext::new()
    ///     .with_channel("discord")
    ///     .with_os_info();
    /// let builder = ContextBuilder::new().with_runtime_context(ctx);
    /// let system = builder.build_system_message();
    /// assert!(system.content.contains("Runtime Context"));
    /// assert!(system.content.contains("discord"));
    /// ```
    pub fn with_runtime_context(mut self, ctx: RuntimeContext) -> Self {
        if !ctx.is_empty() {
            self.runtime_context = Some(ctx);
        }
        self
    }

    /// Add memory context to the system prompt.
    ///
    /// Injects long-term memory content (pinned + relevant entries) as a
    /// `## Memory` section. If the provided string is empty, it is ignored.
    ///
    /// # Arguments
    /// * `memory_context` - Pre-built memory injection string
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    ///
    /// let builder = ContextBuilder::new()
    ///     .with_memory_context("## Memory\n\n### Pinned\n- user:name: Alice".to_string());
    /// let system = builder.build_system_message();
    /// assert!(system.content.contains("## Memory"));
    /// ```
    pub fn with_memory_context(mut self, memory_context: String) -> Self {
        if !memory_context.is_empty() {
            self.memory_context = Some(memory_context);
        }
        self
    }

    /// Append a suffix to the system prompt.
    ///
    /// Used for injecting additional instructions like first-run persona prompts.
    pub fn with_system_prompt_suffix(mut self, suffix: &str) -> Self {
        self.system_prompt.push_str(suffix);
        self
    }

    /// Build the system message with all configured content.
    ///
    /// # Returns
    /// A `Message` with role `System` containing the full system prompt.
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    /// use zeptoclaw::session::Role;
    ///
    /// let builder = ContextBuilder::new();
    /// let system = builder.build_system_message();
    /// assert_eq!(system.role, Role::System);
    /// ```
    pub fn build_system_message(&self) -> Message {
        let mut content = String::new();
        if let Some(ref soul) = self.soul_prompt {
            content.push_str(soul);
            content.push_str("\n\n");
        }
        content.push_str(&self.system_prompt);
        if let Some(ref skills) = self.skills_prompt {
            content.push_str("\n\n## Available Skills\n\n");
            content.push_str(skills);
        }
        if let Some(ref ctx) = self.runtime_context {
            if let Some(rendered) = ctx.render() {
                content.push_str("\n\n");
                content.push_str(&rendered);
            }
        }
        if let Some(ref mem) = self.memory_context {
            content.push_str("\n\n");
            content.push_str(mem);
        }
        Message::system(&content)
    }

    /// Build system message with an optional memory context override.
    ///
    /// When `memory_override` is `Some`, it replaces the stored
    /// `memory_context`. `Some("")` suppresses memory injection.
    fn build_system_message_with_memory_override(&self, memory_override: Option<&str>) -> Message {
        let mut content = String::new();
        if let Some(ref soul) = self.soul_prompt {
            content.push_str(soul);
            content.push_str("\n\n");
        }
        content.push_str(&self.system_prompt);
        if let Some(ref skills) = self.skills_prompt {
            content.push_str("\n\n## Available Skills\n\n");
            content.push_str(skills);
        }
        if let Some(ref ctx) = self.runtime_context {
            if let Some(rendered) = ctx.render() {
                content.push_str("\n\n");
                content.push_str(&rendered);
            }
        }

        let memory = match memory_override {
            Some("") => None,
            Some(memory) => Some(memory),
            None => self.memory_context.as_deref(),
        };
        if let Some(memory) = memory {
            content.push_str("\n\n");
            content.push_str(memory);
        }

        Message::system(&content)
    }

    /// Build the full message list for an LLM call.
    ///
    /// This constructs a message list with:
    /// 1. System message (with skills if configured)
    /// 2. Conversation history
    /// 3. New user input (if non-empty), with timestamp envelope when timezone is set
    ///
    /// # Arguments
    /// * `history` - The conversation history to include
    /// * `user_input` - The new user message (empty string is ignored)
    ///
    /// # Returns
    /// A vector of messages ready for the LLM.
    ///
    /// # Example
    /// ```rust
    /// use zeptoclaw::agent::ContextBuilder;
    /// use zeptoclaw::session::Message;
    ///
    /// let builder = ContextBuilder::new();
    /// let history = vec![
    ///     Message::user("Hello"),
    ///     Message::assistant("Hi there!"),
    /// ];
    /// let messages = builder.build_messages(&history, "How are you?");
    /// assert_eq!(messages.len(), 4); // system + 2 history + new user
    /// ```
    pub fn build_messages(&self, history: &[Message], user_input: &str) -> Vec<Message> {
        let mut messages = vec![self.build_system_message()];
        messages.extend(history.iter().cloned());
        if !user_input.is_empty() {
            // Prepend timestamp envelope to user message so the LLM knows
            // exactly when this message arrived (prevents stale-time bugs).
            let content = if let Some(ref ctx) = self.runtime_context {
                if ctx.timezone.is_some() {
                    let envelope = format_message_envelope();
                    format!("{} {}", envelope, user_input)
                } else {
                    user_input.to_string()
                }
            } else {
                user_input.to_string()
            };
            messages.push(Message::user(&content));
        }
        messages
    }

    /// Build the full message list with an optional per-message memory override.
    ///
    /// Works like `build_messages`, but `memory_override` can replace the
    /// stored memory section for this specific message build.
    pub fn build_messages_with_memory_override(
        &self,
        history: &[Message],
        user_input: &str,
        memory_override: Option<&str>,
    ) -> Vec<Message> {
        let mut messages = vec![self.build_system_message_with_memory_override(memory_override)];
        messages.extend(history.iter().cloned());
        if !user_input.is_empty() {
            let content = if let Some(ref ctx) = self.runtime_context {
                if ctx.timezone.is_some() {
                    let envelope = format_message_envelope();
                    format!("{} {}", envelope, user_input)
                } else {
                    user_input.to_string()
                }
            } else {
                user_input.to_string()
            };
            messages.push(Message::user(&content));
        }
        messages
    }

    /// Get the current system prompt.
    pub fn system_prompt(&self) -> &str {
        &self.system_prompt
    }

    /// Check if a SOUL.md identity is configured.
    pub fn has_soul(&self) -> bool {
        self.soul_prompt.is_some()
    }

    /// Check if skills are configured.
    pub fn has_skills(&self) -> bool {
        self.skills_prompt.is_some()
    }
}

impl Default for ContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_context_builder_new() {
        let builder = ContextBuilder::new();
        assert!(builder.system_prompt().contains("ZeptoClaw"));
        assert!(!builder.has_skills());
    }

    #[test]
    fn test_context_builder_default() {
        let builder = ContextBuilder::default();
        assert!(builder.system_prompt().contains("ZeptoClaw"));
    }

    #[test]
    fn test_context_builder_custom_system_prompt() {
        let builder = ContextBuilder::new().with_system_prompt("Custom prompt here");
        assert_eq!(builder.system_prompt(), "Custom prompt here");
    }

    #[test]
    fn test_context_builder_with_skills() {
        let builder = ContextBuilder::new().with_skills("- /test: Test skill");
        assert!(builder.has_skills());

        let system = builder.build_system_message();
        assert!(system.content.contains("Available Skills"));
        assert!(system.content.contains("/test"));
    }

    #[test]
    fn test_build_system_message() {
        let builder = ContextBuilder::new();
        let system = builder.build_system_message();

        assert_eq!(system.role, Role::System);
        assert!(system.content.contains("ZeptoClaw"));
    }

    #[test]
    fn test_build_messages_empty_input() {
        let builder = ContextBuilder::new();
        let messages = builder.build_messages(&[], "");

        // Only system message when input is empty
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].role, Role::System);
    }

    #[test]
    fn test_build_messages_with_input() {
        let builder = ContextBuilder::new();
        let messages = builder.build_messages(&[], "Hello");

        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].role, Role::System);
        assert_eq!(messages[1].role, Role::User);
        assert_eq!(messages[1].content, "Hello");
    }

    #[test]
    fn test_build_messages_with_history() {
        let builder = ContextBuilder::new();
        let history = vec![
            Message::user("Previous message"),
            Message::assistant("Previous response"),
        ];
        let messages = builder.build_messages(&history, "New message");

        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0].role, Role::System);
        assert_eq!(messages[1].role, Role::User);
        assert_eq!(messages[1].content, "Previous message");
        assert_eq!(messages[2].role, Role::Assistant);
        assert_eq!(messages[3].role, Role::User);
        assert_eq!(messages[3].content, "New message");
    }

    #[test]
    fn test_build_messages_preserves_history_order() {
        let builder = ContextBuilder::new();
        let history = vec![
            Message::user("First"),
            Message::assistant("Second"),
            Message::user("Third"),
            Message::assistant("Fourth"),
        ];
        let messages = builder.build_messages(&history, "");

        // System + 4 history messages (no new input since it's empty)
        assert_eq!(messages.len(), 5);
        assert_eq!(messages[1].content, "First");
        assert_eq!(messages[2].content, "Second");
        assert_eq!(messages[3].content, "Third");
        assert_eq!(messages[4].content, "Fourth");
    }

    #[test]
    fn test_context_builder_with_soul() {
        let builder = ContextBuilder::new().with_soul("You are a pirate captain.");
        assert!(builder.has_soul());

        let system = builder.build_system_message();
        assert!(system.content.starts_with("You are a pirate captain."));
        assert!(system.content.contains("ZeptoClaw"));
    }

    #[test]
    fn test_soul_prepended_before_system_prompt() {
        let builder = ContextBuilder::new()
            .with_soul("SOUL: Be kind.")
            .with_system_prompt("SYSTEM: Do tasks.");
        let system = builder.build_system_message();

        let soul_pos = system.content.find("SOUL: Be kind.").unwrap();
        let system_pos = system.content.find("SYSTEM: Do tasks.").unwrap();
        assert!(soul_pos < system_pos);
    }

    #[test]
    fn test_soul_with_skills() {
        let builder = ContextBuilder::new()
            .with_soul("Identity: helper")
            .with_skills("- /test: Test");
        let system = builder.build_system_message();

        assert!(system.content.starts_with("Identity: helper"));
        assert!(system.content.contains("ZeptoClaw"));
        assert!(system.content.contains("Available Skills"));
        assert!(system.content.contains("/test"));
    }

    #[test]
    fn test_no_soul_by_default() {
        let builder = ContextBuilder::new();
        assert!(!builder.has_soul());

        let system = builder.build_system_message();
        assert!(system.content.starts_with("You are ZeptoClaw"));
    }

    #[test]
    fn test_context_builder_chaining() {
        let builder = ContextBuilder::new()
            .with_system_prompt("Custom prompt")
            .with_skills("- /skill1: Do something");

        let system = builder.build_system_message();
        assert!(system.content.contains("Custom prompt"));
        assert!(system.content.contains("/skill1"));
    }

    #[test]
    fn test_build_messages_with_tool_calls_in_history() {
        use crate::session::ToolCall;

        let builder = ContextBuilder::new();
        let history = vec![
            Message::user("Search for rust"),
            Message::assistant_with_tools(
                "Let me search for that.",
                vec![ToolCall::new("call_1", "search", r#"{"q": "rust"}"#)],
            ),
            Message::tool_result("call_1", "Found 100 results"),
            Message::assistant("I found 100 results about Rust."),
        ];
        let messages = builder.build_messages(&history, "Thanks!");

        // System + 4 history + new user message
        assert_eq!(messages.len(), 6);
        assert!(messages[2].has_tool_calls());
        assert!(messages[3].is_tool_result());
    }

    // ---- RuntimeContext tests ----

    #[test]
    fn test_runtime_context_empty() {
        let ctx = RuntimeContext::new();
        assert!(ctx.is_empty());
        assert!(ctx.render().is_none());
    }

    #[test]
    fn test_runtime_context_default() {
        let ctx = RuntimeContext::default();
        assert!(ctx.is_empty());
        assert!(ctx.channel.is_none());
        assert!(ctx.available_tools.is_empty());
        assert!(ctx.timezone.is_none());
        assert!(ctx.workspace.is_none());
        assert!(ctx.os_info.is_none());
    }

    #[test]
    fn test_runtime_context_with_channel() {
        let ctx = RuntimeContext::new().with_channel("telegram");
        assert!(!ctx.is_empty());
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("Channel: telegram"));
    }

    #[test]
    fn test_runtime_context_with_tools() {
        let ctx =
            RuntimeContext::new().with_tools(vec!["shell".to_string(), "web_search".to_string()]);
        assert!(!ctx.is_empty());
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("shell, web_search"));
    }

    #[test]
    fn test_runtime_context_with_empty_tools() {
        let ctx = RuntimeContext::new().with_tools(vec![]);
        assert!(ctx.is_empty());
        assert!(ctx.render().is_none());
    }

    #[test]
    fn test_runtime_context_with_timezone() {
        let ctx = RuntimeContext::new().with_timezone("Asia/Kuala_Lumpur");
        assert!(!ctx.is_empty());
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("Current time:"));
        // Timezone label now shows the actual system UTC offset (e.g. "+08:00")
        // instead of the config IANA name, to avoid contradictions.
        assert!(
            rendered.contains("Timezone: +") || rendered.contains("Timezone: -"),
            "should show UTC offset: {}",
            rendered
        );
    }

    #[test]
    fn test_runtime_context_with_utc_label() {
        let ctx = RuntimeContext::new().with_timezone("UTC");
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("Current time:"));
        // Even when config says "UTC", the displayed timezone is the actual
        // system offset from chrono::Local (e.g. "+08:00" or "+00:00").
        assert!(
            rendered.contains("Timezone: +") || rendered.contains("Timezone: -"),
            "should show UTC offset: {}",
            rendered
        );
    }

    #[test]
    fn test_runtime_context_time_format() {
        // Verify render produces expected format: "Day YYYY-MM-DD HH:MM +HH:MM"
        let ctx = RuntimeContext::new().with_timezone("UTC");
        let rendered = ctx.render().unwrap();
        // Extract the time line
        let time_line = rendered
            .lines()
            .find(|l| l.contains("Current time:"))
            .unwrap();
        // Should contain a 4-digit year
        assert!(
            time_line.contains("202"),
            "time should contain year: {}",
            time_line
        );
    }

    #[test]
    fn test_runtime_context_time_is_live() {
        // Verify render works — time is computed dynamically each call
        let ctx = RuntimeContext::new().with_timezone("local");
        let r1 = ctx.render().unwrap();
        assert!(r1.contains("Current time:"));
    }

    #[test]
    fn test_runtime_context_with_os_info() {
        let ctx = RuntimeContext::new().with_os_info();
        assert!(!ctx.is_empty());
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("Platform:"));
        // Should contain the current OS
        assert!(rendered.contains(std::env::consts::OS));
    }

    #[test]
    fn test_runtime_context_with_workspace() {
        let ctx = RuntimeContext::new().with_workspace("/home/user/project");
        assert!(!ctx.is_empty());
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("Workspace: /home/user/project"));
    }

    #[test]
    fn test_runtime_context_full() {
        let ctx = RuntimeContext::new()
            .with_channel("whatsapp")
            .with_tools(vec!["shell".to_string()])
            .with_workspace("/tmp/test")
            .with_os_info();
        let rendered = ctx.render().unwrap();
        assert!(rendered.contains("## Runtime Context"));
        assert!(rendered.contains("Channel: whatsapp"));
        assert!(rendered.contains("Available tools: shell"));
        assert!(rendered.contains("Workspace: /tmp/test"));
        assert!(rendered.contains("Platform:"));
    }

    #[test]
    fn test_runtime_context_render_ordering() {
        let ctx = RuntimeContext::new()
            .with_channel("cli")
            .with_tools(vec!["echo".to_string()])
            .with_workspace("/work");
        let rendered = ctx.render().unwrap();
        let channel_pos = rendered.find("Channel:").unwrap();
        let tools_pos = rendered.find("Available tools:").unwrap();
        let workspace_pos = rendered.find("Workspace:").unwrap();
        // Channel comes before tools, tools before workspace
        assert!(channel_pos < tools_pos);
        assert!(tools_pos < workspace_pos);
    }

    #[test]
    fn test_runtime_context_clone() {
        let ctx = RuntimeContext::new()
            .with_channel("discord")
            .with_workspace("/tmp");
        let cloned = ctx.clone();
        assert_eq!(ctx.channel, cloned.channel);
        assert_eq!(ctx.workspace, cloned.workspace);
    }

    // ---- Message envelope tests ----

    #[test]
    fn test_message_envelope_format() {
        let envelope = format_message_envelope();
        assert!(envelope.starts_with('['));
        assert!(envelope.ends_with(']'));
        // Should contain a date and UTC offset
        assert!(envelope.contains("202"), "should contain year");
        assert!(
            envelope.contains('+') || envelope.contains('-'),
            "should contain UTC offset sign"
        );
    }

    #[test]
    fn test_message_envelope_contains_time_components() {
        let envelope = format_message_envelope();
        // Format: [Day YYYY-MM-DD HH:MM +HH:MM]
        // Should contain a colon (from HH:MM time)
        assert!(envelope.contains(':'), "should contain time separator");
        // Should be bracketed
        assert!(envelope.len() > 10, "envelope should not be empty");
    }

    #[test]
    fn test_build_messages_with_timezone_envelope() {
        let ctx = RuntimeContext::new().with_timezone("UTC");
        let builder = ContextBuilder::new().with_runtime_context(ctx);
        let messages = builder.build_messages(&[], "Hello");
        assert_eq!(messages.len(), 2);
        // User message should start with timestamp envelope
        assert!(messages[1].content.starts_with('['));
        assert!(messages[1].content.contains("] Hello"));
    }

    #[test]
    fn test_build_messages_without_timezone_no_envelope() {
        let ctx = RuntimeContext::new().with_channel("cli");
        let builder = ContextBuilder::new().with_runtime_context(ctx);
        let messages = builder.build_messages(&[], "Hello");
        assert_eq!(messages[1].content, "Hello");
    }

    // ---- ContextBuilder + RuntimeContext integration tests ----

    #[test]
    fn test_context_builder_with_runtime_context() {
        let ctx = RuntimeContext::new().with_channel("discord");
        let builder = ContextBuilder::new().with_runtime_context(ctx);
        let system = builder.build_system_message();
        assert!(system.content.contains("Runtime Context"));
        assert!(system.content.contains("discord"));
    }

    #[test]
    fn test_context_builder_empty_runtime_context_adds_nothing() {
        let ctx = RuntimeContext::new();
        let builder = ContextBuilder::new().with_runtime_context(ctx);
        let system = builder.build_system_message();
        assert!(!system.content.contains("Runtime Context"));
    }

    #[test]
    fn test_context_builder_all_sections() {
        let ctx = RuntimeContext::new().with_channel("cli");
        let builder = ContextBuilder::new()
            .with_skills("- /help: Show help")
            .with_runtime_context(ctx);
        let system = builder.build_system_message();
        assert!(system.content.contains("ZeptoClaw"));
        assert!(system.content.contains("Available Skills"));
        assert!(system.content.contains("## Runtime Context"));
        assert!(system.content.contains("cli"));
    }

    #[test]
    fn test_context_builder_section_ordering() {
        let ctx = RuntimeContext::new().with_channel("slack");
        let builder = ContextBuilder::new()
            .with_skills("- /deploy: Deploy app")
            .with_runtime_context(ctx);
        let system = builder.build_system_message();
        let skills_pos = system.content.find("Available Skills").unwrap();
        let runtime_pos = system.content.find("Runtime Context").unwrap();
        // Skills section should come before runtime context
        assert!(skills_pos < runtime_pos);
    }

    #[test]
    fn test_context_builder_runtime_context_in_messages() {
        let ctx = RuntimeContext::new()
            .with_channel("telegram")
            .with_os_info();
        let builder = ContextBuilder::new().with_runtime_context(ctx);
        let messages = builder.build_messages(&[], "Hello");
        assert_eq!(messages.len(), 2);
        assert!(messages[0].content.contains("Runtime Context"));
        assert!(messages[0].content.contains("telegram"));
    }

    // ---- Memory context tests ----

    #[test]
    fn test_context_builder_with_memory_context() {
        let builder = ContextBuilder::new()
            .with_memory_context("## Memory\n\n### Pinned\n- user:name: Alice".to_string());
        let system = builder.build_system_message();
        assert!(system.content.contains("## Memory"));
        assert!(system.content.contains("user:name: Alice"));
    }

    #[test]
    fn test_context_builder_empty_memory_context_skipped() {
        let builder = ContextBuilder::new().with_memory_context(String::new());
        let system = builder.build_system_message();
        assert!(!system.content.contains("## Memory"));
    }

    #[test]
    fn test_context_builder_memory_after_runtime() {
        let ctx = RuntimeContext::new().with_channel("cli");
        let builder = ContextBuilder::new()
            .with_runtime_context(ctx)
            .with_memory_context("## Memory\n\n### Pinned\n- k: v".to_string());
        let system = builder.build_system_message();
        let runtime_pos = system.content.find("Runtime Context").unwrap();
        let memory_pos = system.content.find("## Memory").unwrap();
        assert!(runtime_pos < memory_pos);
    }

    #[test]
    fn test_build_messages_with_memory_override_some() {
        let builder = ContextBuilder::new()
            .with_memory_context("## Memory\n\n### Pinned\n- old: data".to_string());
        let override_ctx =
            "## Memory\n\n### Pinned\n- user:name: Alice\n\n### Relevant\n- fact:project: ZeptoClaw";
        let messages =
            builder.build_messages_with_memory_override(&[], "Hello", Some(override_ctx));
        assert!(messages[0].content.contains("fact:project: ZeptoClaw"));
        assert!(!messages[0].content.contains("old: data"));
        assert_eq!(messages.len(), 2);
    }

    #[test]
    fn test_build_messages_with_memory_override_none_falls_back() {
        let builder = ContextBuilder::new()
            .with_memory_context("## Memory\n\n### Pinned\n- stored: value".to_string());
        let messages = builder.build_messages_with_memory_override(&[], "Hello", None);
        assert!(messages[0].content.contains("stored: value"));
    }

    #[test]
    fn test_build_messages_with_memory_override_empty_string() {
        let builder = ContextBuilder::new()
            .with_memory_context("## Memory\n\n### Pinned\n- old: data".to_string());
        let messages = builder.build_messages_with_memory_override(&[], "Hello", Some(""));
        assert!(!messages[0].content.contains("## Memory"));
    }

    // ---- Memory system prompt tests ----

    #[test]
    fn test_system_prompt_mentions_memory() {
        // DEFAULT_SYSTEM_PROMPT must reference longterm_memory so the LLM
        // knows the tool exists and uses it proactively.
        assert!(
            DEFAULT_SYSTEM_PROMPT.contains("longterm_memory"),
            "DEFAULT_SYSTEM_PROMPT should mention longterm_memory tool"
        );
    }

    #[test]
    fn test_system_prompt_mentions_save_and_recall() {
        // The prompt must tell the LLM to both save and recall information.
        assert!(
            DEFAULT_SYSTEM_PROMPT.contains("Save") || DEFAULT_SYSTEM_PROMPT.contains("save"),
            "DEFAULT_SYSTEM_PROMPT should mention saving facts"
        );
        assert!(
            DEFAULT_SYSTEM_PROMPT.contains("Recall") || DEFAULT_SYSTEM_PROMPT.contains("recall"),
            "DEFAULT_SYSTEM_PROMPT should mention recalling information"
        );
    }

    #[test]
    fn test_system_prompt_memory_instructions_in_built_message() {
        // Verify the memory instructions survive into the built system message.
        let builder = ContextBuilder::new();
        let system = builder.build_system_message();
        assert!(
            system.content.contains("longterm_memory"),
            "Built system message should contain longterm_memory instructions"
        );
    }

    #[test]
    fn test_system_prompt_contains_reminder_guidance() {
        assert!(
            DEFAULT_SYSTEM_PROMPT.contains("Reminder:"),
            "System prompt must instruct how to handle cron-delivered 'Reminder:' messages"
        );
    }

    #[test]
    fn test_system_prompt_contains_heartbeat_guidance() {
        assert!(
            DEFAULT_SYSTEM_PROMPT.contains("HEARTBEAT_OK"),
            "System prompt must instruct how to handle heartbeat messages"
        );
    }

    #[test]
    fn test_with_system_prompt_suffix() {
        let builder = ContextBuilder::new().with_system_prompt_suffix("\n\nExtra instructions.");
        let system = builder.build_system_message();
        assert!(system.content.contains("ZeptoClaw"));
        assert!(system.content.contains("Extra instructions."));
    }

    #[test]
    fn test_first_run_persona_prompt_content() {
        assert!(FIRST_RUN_PERSONA_PROMPT.contains("First Conversation Setup"));
        assert!(FIRST_RUN_PERSONA_PROMPT.contains("concise"));
        assert!(FIRST_RUN_PERSONA_PROMPT.contains("persona_pref"));
    }
}