forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_log.rs
More file actions
363 lines (318 loc) · 10.2 KB
/
memory_log.rs
File metadata and controls
363 lines (318 loc) · 10.2 KB
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
//! Persistent memory event log for post-session analysis.
//!
//! Writes structured JSONL (one JSON object per line) to:
//! `~/.jcode/logs/memory-events-YYYY-MM-DD.jsonl`
//!
//! Every memory pipeline event - embedding search, sidecar verification,
//! injection, extraction, maintenance, tool actions - is captured with
//! wall-clock timestamps, session ID, and full details.
//!
//! Logs are kept for 14 days (separate from general log rotation).
use crate::memory_types::MemoryEventKind;
use chrono::Local;
use serde::Serialize;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
static MEMORY_LOGGER: Mutex<Option<MemoryLogger>> = Mutex::new(None);
struct MemoryLogger {
file: File,
current_date: String,
}
impl MemoryLogger {
fn open(date: &str) -> Option<Self> {
let dir = log_dir()?;
fs::create_dir_all(&dir).ok()?;
let path = dir.join(format!("memory-events-{}.jsonl", date));
let file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.ok()?;
Some(Self {
file,
current_date: date.to_string(),
})
}
fn write_entry(&mut self, entry: &LogEntry) {
if let Ok(json) = serde_json::to_string(entry) {
let _ = writeln!(self.file, "{}", json);
let _ = self.file.flush();
}
}
}
fn log_dir() -> Option<PathBuf> {
dirs::home_dir().map(|h| h.join(".jcode").join("logs"))
}
fn ensure_logger(date: &str) -> bool {
if let Ok(mut guard) = MEMORY_LOGGER.lock() {
if let Some(ref logger) = *guard
&& logger.current_date == date
{
return true;
}
*guard = MemoryLogger::open(date);
guard.is_some()
} else {
false
}
}
#[derive(Serialize)]
struct LogEntry {
timestamp: String,
session_id: Option<String>,
event: String,
#[serde(skip_serializing_if = "Option::is_none")]
detail: Option<serde_json::Value>,
}
fn current_session_id() -> Option<String> {
crate::logging::current_session()
}
fn write_log(event: &str, detail: Option<serde_json::Value>) {
let now = Local::now();
let date = now.format("%Y-%m-%d").to_string();
if !ensure_logger(&date) {
return;
}
let entry = LogEntry {
timestamp: now.format("%Y-%m-%dT%H:%M:%S%.3f%z").to_string(),
session_id: current_session_id(),
event: event.to_string(),
detail,
};
if let Ok(mut guard) = MEMORY_LOGGER.lock()
&& let Some(logger) = guard.as_mut()
{
logger.write_entry(&entry);
}
}
/// Log a memory event from the in-memory event system.
pub fn log_event(kind: &MemoryEventKind) {
let (event, detail) = match kind {
MemoryEventKind::EmbeddingStarted => ("embedding_started", None),
MemoryEventKind::EmbeddingComplete { latency_ms, hits } => (
"embedding_complete",
Some(serde_json::json!({
"latency_ms": latency_ms,
"hits": hits,
})),
),
MemoryEventKind::SidecarStarted => ("sidecar_started", None),
MemoryEventKind::SidecarRelevant { memory_preview } => (
"sidecar_relevant",
Some(serde_json::json!({
"memory_preview": memory_preview,
})),
),
MemoryEventKind::SidecarNotRelevant => ("sidecar_not_relevant", None),
MemoryEventKind::SidecarComplete { latency_ms } => (
"sidecar_complete",
Some(serde_json::json!({
"latency_ms": latency_ms,
})),
),
MemoryEventKind::MemorySurfaced { memory_preview } => (
"memory_surfaced",
Some(serde_json::json!({
"memory_preview": memory_preview,
})),
),
MemoryEventKind::MemoryInjected {
count,
prompt_chars,
age_ms,
preview,
items,
} => (
"memory_injected",
Some(serde_json::json!({
"count": count,
"prompt_chars": prompt_chars,
"age_ms": age_ms,
"preview": preview,
"items": items.iter().map(|i| serde_json::json!({
"section": i.section,
"content": i.content,
})).collect::<Vec<_>>(),
})),
),
MemoryEventKind::MaintenanceStarted { verified, rejected } => (
"maintenance_started",
Some(serde_json::json!({
"verified": verified,
"rejected": rejected,
})),
),
MemoryEventKind::MaintenanceLinked { links } => (
"maintenance_linked",
Some(serde_json::json!({ "links": links })),
),
MemoryEventKind::MaintenanceConfidence { boosted, decayed } => (
"maintenance_confidence",
Some(serde_json::json!({
"boosted": boosted,
"decayed": decayed,
})),
),
MemoryEventKind::MaintenanceCluster { clusters, members } => (
"maintenance_cluster",
Some(serde_json::json!({
"clusters": clusters,
"members": members,
})),
),
MemoryEventKind::MaintenanceTagInferred { tag, applied } => (
"maintenance_tag_inferred",
Some(serde_json::json!({
"tag": tag,
"applied": applied,
})),
),
MemoryEventKind::MaintenanceGap { candidates } => (
"maintenance_gap",
Some(serde_json::json!({ "candidates": candidates })),
),
MemoryEventKind::MaintenanceComplete { latency_ms } => (
"maintenance_complete",
Some(serde_json::json!({ "latency_ms": latency_ms })),
),
MemoryEventKind::ExtractionStarted { reason } => (
"extraction_started",
Some(serde_json::json!({ "reason": reason })),
),
MemoryEventKind::ExtractionComplete { count } => (
"extraction_complete",
Some(serde_json::json!({ "count": count })),
),
MemoryEventKind::Error { message } => {
("error", Some(serde_json::json!({ "message": message })))
}
MemoryEventKind::ToolRemembered {
content,
scope,
category,
} => (
"tool_remembered",
Some(serde_json::json!({
"content": content,
"scope": scope,
"category": category,
})),
),
MemoryEventKind::ToolRecalled { query, count } => (
"tool_recalled",
Some(serde_json::json!({
"query": query,
"count": count,
})),
),
MemoryEventKind::ToolForgot { id } => {
("tool_forgot", Some(serde_json::json!({ "id": id })))
}
MemoryEventKind::ToolTagged { id, tags } => (
"tool_tagged",
Some(serde_json::json!({
"id": id,
"tags": tags,
})),
),
MemoryEventKind::ToolLinked { from, to } => (
"tool_linked",
Some(serde_json::json!({
"from": from,
"to": to,
})),
),
MemoryEventKind::ToolListed { count } => {
("tool_listed", Some(serde_json::json!({ "count": count })))
}
};
write_log(event, detail);
}
/// Log when a pending memory is prepared (before it's actually injected).
pub fn log_pending_prepared(session_id: &str, prompt: &str, count: usize, memory_ids: &[String]) {
write_log(
"pending_prepared",
Some(serde_json::json!({
"target_session": session_id,
"count": count,
"prompt_chars": prompt.chars().count(),
"prompt_preview": &prompt[..prompt.len().min(500)],
"memory_ids": memory_ids,
})),
);
}
/// Log when memories are marked as injected (dedup tracking).
pub fn log_marked_injected(session_id: &str, ids: &[String]) {
if ids.is_empty() {
return;
}
write_log(
"marked_injected",
Some(serde_json::json!({
"target_session": session_id,
"memory_ids": ids,
})),
);
}
/// Log when a pending memory is consumed (actually injected into context).
pub fn log_pending_consumed(session_id: &str, count: usize, age_ms: u64, prompt_chars: usize) {
write_log(
"pending_consumed",
Some(serde_json::json!({
"target_session": session_id,
"count": count,
"age_ms": age_ms,
"prompt_chars": prompt_chars,
})),
);
}
/// Log when a pending memory is discarded (stale, duplicate, etc.)
pub fn log_pending_discarded(session_id: &str, reason: &str) {
write_log(
"pending_discarded",
Some(serde_json::json!({
"target_session": session_id,
"reason": reason,
})),
);
}
/// Log topic change detection (which triggers extraction).
pub fn log_topic_change(session_id: &str, old_topic: &str, new_topic: &str) {
write_log(
"topic_change",
Some(serde_json::json!({
"target_session": session_id,
"old_topic": old_topic,
"new_topic": new_topic,
})),
);
}
/// Log final extraction trigger (session end).
pub fn log_final_extraction(session_id: &str, transcript_chars: usize) {
write_log(
"final_extraction_started",
Some(serde_json::json!({
"target_session": session_id,
"transcript_chars": transcript_chars,
})),
);
}
/// Log embedding candidate filtering results.
pub fn log_candidate_filter(
session_id: &str,
total_candidates: usize,
after_dedup: usize,
context_preview: &str,
) {
write_log(
"candidate_filter",
Some(serde_json::json!({
"target_session": session_id,
"total_candidates": total_candidates,
"after_dedup": after_dedup,
"context_preview": &context_preview[..context_preview.len().min(200)],
})),
);
}