1use crate::core::policy::diagnostics;
2use std::io::{Read, Seek, SeekFrom, Write};
3
4use lean_ctx_time::{LocalDateTime, UtcDateTime};
5
6const MAX_ACTIVE_JOURNAL_BYTES: u64 = 4 * 1024 * 1024;
10const JOURNAL_TAIL_BYTES: u64 = 8 * 1024;
11fn journal_target() -> Option<diagnostics::Target> {
12 diagnostics::target(crate::core::paths::state_dir().ok()?.join("journal.md"))
13}
14
15fn active_journal_needs_rotation(path: &std::path::Path) -> bool {
16 path.metadata()
17 .map(|metadata| metadata.len() >= MAX_ACTIVE_JOURNAL_BYTES)
18 .unwrap_or(false)
19}
20
21fn rotate_active_journal_if_needed(path: &std::path::Path) {
22 if !active_journal_needs_rotation(path) {
23 return;
24 }
25 let archive_name = format!(
26 "journal-{}.md",
27 UtcDateTime::now().format("%Y%m%dT%H%M%S%6fZ")
28 );
29 let archive = path.with_file_name(archive_name);
30 if std::fs::rename(path, archive).is_ok() {
31 let _ = std::fs::remove_file(path.with_extension("day"));
32 }
33}
34
35fn write_day_marker(path: &std::path::Path, today: &str) {
36 let marker = path.with_extension("day");
37 let Some(parent) = marker.parent() else {
39 return;
40 };
41 if let Ok(mut file) = tempfile::NamedTempFile::new_in(parent) {
42 if file.write_all(today.as_bytes()).is_ok() {
43 let _ = file.persist(marker);
44 }
45 }
46}
47
48fn journal_tail_contains(path: &std::path::Path, needle: &str) -> bool {
49 let Ok(mut file) = std::fs::File::open(path) else {
50 return false;
51 };
52 let start = file
53 .metadata()
54 .map(|metadata| metadata.len().saturating_sub(JOURNAL_TAIL_BYTES))
55 .unwrap_or(0);
56 if file.seek(SeekFrom::Start(start)).is_err() {
57 return false;
58 }
59 let mut tail = Vec::new();
60 file.read_to_end(&mut tail).is_ok() && String::from_utf8_lossy(&tail).contains(needle)
61}
62
63fn is_enabled() -> bool {
64 if let Ok(v) = std::env::var("LEAN_CTX_JOURNAL") {
65 return !matches!(v.trim(), "0" | "false" | "off");
66 }
67 super::config::Config::load().journal_enabled
68}
69
70pub fn log(category: &str, message: &str) {
72 log_inner(category, message, None);
73}
74
75fn log_inner(category: &str, message: &str, tool: Option<&str>) {
76 if !is_enabled() {
77 return;
78 }
79 let Some(target) = journal_target() else {
80 return;
81 };
82 target.with_lock(|| {
83 let Some(fields) = diagnostics::fields(
84 &[
85 ("category", category),
86 ("message", message),
87 ("tool", tool.unwrap_or_default()),
88 ],
89 None,
90 ) else {
91 return;
92 };
93 let Some(safe) = target.inspect(tool, &fields) else {
94 return;
95 };
96 let category = safe["category"].as_str().unwrap_or_default();
97 let message = safe["message"].as_str().unwrap_or_default();
98 let message = if tool.is_some() {
99 format!(
100 "`{}` — {}",
101 safe["tool"].as_str().unwrap_or_default(),
102 message.lines().next().unwrap_or_default()
103 )
104 } else {
105 message.to_owned()
106 };
107 let path = &target.path;
108 rotate_active_journal_if_needed(path);
109 let timestamp = LocalDateTime::now().format("%Y-%m-%d %H:%M");
110 let entry = format!("- **{timestamp}** [{category}] {message}\n");
111 let Some(serde_json::Value::String(entry)) =
112 target.inspect(tool, &serde_json::Value::String(entry))
113 else {
114 return;
115 };
116 let needs_header = !path.exists();
117 let file = diagnostics::open_append(path);
118
119 if let Ok(mut f) = file {
120 if needs_header {
121 let date = LocalDateTime::now().format("%Y-%m-%d").to_string();
122 let _ = writeln!(f, "# lean-ctx Activity Journal\n\n## {date}\n");
123 write_day_marker(path, &date);
124 }
125 let _ = f.write_all(entry.as_bytes());
126 }
127 });
128}
129
130pub fn maybe_day_separator() {
132 if !is_enabled() {
133 return;
134 }
135 let Some(target) = journal_target() else {
136 return;
137 };
138 target.with_lock(|| {
139 let path = &target.path;
140 if !path.exists() {
141 return;
142 }
143
144 let today = LocalDateTime::now().format("%Y-%m-%d").to_string();
145 if crate::core::policy::files::read(&path.with_extension("day"), false)
146 .ok()
147 .flatten()
148 .is_some_and(|stored| stored.trim() == today)
149 {
150 return;
151 }
152
153 let header = format!("## {today}");
154 if !journal_tail_contains(path, &header)
155 && let Ok(mut f) = diagnostics::open_append(path)
156 {
157 let _ = writeln!(f, "\n{header}\n");
158 }
159 write_day_marker(path, &today);
160 });
161}
162
163pub fn log_tool_call(tool_name: &str, summary: &str) {
165 if matches!(
166 tool_name,
167 "ctx_session" | "ctx_knowledge" | "ctx_context" | "ctx_radar"
168 ) {
169 return;
170 }
171 log_inner("tool", summary, Some(tool_name));
172}
173
174pub fn read_journal(tail_lines: usize) -> String {
176 let Some(target) = journal_target() else {
177 return "Journal unavailable under current policy.".into();
178 };
179 let path = &target.path;
180 if !path.exists() {
181 return "No journal entries yet.".to_string();
182 }
183 let Some(content) = target.read() else {
184 return "Journal withheld by current policy or storage checks.".into();
185 };
186 if tail_lines == 0 {
187 return content;
188 }
189 let lines: Vec<&str> = content.lines().collect();
190 let start = lines.len().saturating_sub(tail_lines);
191 lines[start..].join("\n")
192}
193
194#[cfg(test)]
195pub mod tests {
196 use super::*;
197
198 #[test]
199 fn journal_log_creates_file() {
200 let iso = crate::core::data_dir::isolated_data_dir();
203 crate::test_env::set_var("LEAN_CTX_JOURNAL", "1");
204
205 log("test", "hello world");
206
207 let path = iso.path().join("journal.md");
208 assert!(path.exists(), "journal.md should be created");
209 let content = std::fs::read_to_string(&path).unwrap();
210 assert!(content.contains("[test] hello world"));
211 assert!(content.contains("# lean-ctx Activity Journal"));
212
213 crate::test_env::remove_var("LEAN_CTX_JOURNAL");
214 }
215
216 #[test]
217 fn read_journal_tail() {
218 let _iso = crate::core::data_dir::isolated_data_dir();
219 crate::test_env::set_var("LEAN_CTX_JOURNAL", "1");
220
221 for i in 0..5 {
222 log("test", &format!("entry {i}"));
223 }
224
225 let tail = read_journal(2);
226 assert!(tail.contains("entry 4"), "should contain last entry");
227 assert!(
228 !tail.contains("Activity Journal"),
229 "should not contain header"
230 );
231
232 crate::test_env::remove_var("LEAN_CTX_JOURNAL");
233 }
234
235 #[test]
236 fn oversized_active_journal_rotates_before_append() {
237 let iso = crate::core::data_dir::isolated_data_dir();
238 crate::test_env::set_var("LEAN_CTX_JOURNAL", "1");
239 let journal = iso.path().join("journal.md");
240 std::fs::write(
241 &journal,
242 vec![b'x'; (MAX_ACTIVE_JOURNAL_BYTES + 1) as usize],
243 )
244 .expect("write oversized journal");
245
246 log("test", "after rotation");
247
248 assert!(
249 std::fs::read_to_string(&journal)
250 .expect("new active journal")
251 .contains("after rotation")
252 );
253 assert!(
254 std::fs::read_dir(iso.path())
255 .expect("journal directory")
256 .flatten()
257 .any(|entry| entry.file_name().to_string_lossy().starts_with("journal-"))
258 );
259 crate::test_env::remove_var("LEAN_CTX_JOURNAL");
260 }
261
262 #[test]
263 fn day_separator_uses_small_tail_and_persists_marker() {
264 let iso = crate::core::data_dir::isolated_data_dir();
265 crate::test_env::set_var("LEAN_CTX_JOURNAL", "1");
266 let today = LocalDateTime::now().format("%Y-%m-%d").to_string();
267 let journal = iso.path().join("journal.md");
268 std::fs::write(&journal, format!("{}\n## {today}\n", "x".repeat(16 * 1024)))
269 .expect("write journal");
270
271 maybe_day_separator();
272
273 assert_eq!(
274 std::fs::read_to_string(iso.path().join("journal.day"))
275 .expect("day marker")
276 .trim(),
277 today
278 );
279 crate::test_env::remove_var("LEAN_CTX_JOURNAL");
280 }
281}