tdm_server_rust/utils/agent_debug.rs
1//! Agent Debug NDJSON 日志
2//!
3//! 输出结构化调试日志到 `agentlog/` 目录,用于 AI Agent 诊断和分析。
4//! 每行为一条 NDJSON (Newline Delimited JSON) 记录。
5//!
6//! ## 日志格式
7//!
8//! ```json
9//! {"sessionId":"b75d44","hypothesisId":"E1","location":"episode_repo.rs:insert",
10//! "message":"episode inserted","data":{...},"timestamp":1710000000000,"runId":"pre-fix"}
11//! ```
12
13use std::io::Write;
14use std::path::PathBuf;
15
16/// 写入一条 Agent debug 日志
17///
18/// 日志文件固定为 `{CARGO_MANIFEST_DIR}/../debug-b75d44.log`,
19/// 以 NDJSON 格式追加写入。
20///
21/// # 参数
22///
23/// - `hypothesis_id`: 假设编号(如 "E1"),用于追踪特定 Agent 行为
24/// - `location`: 代码位置标识(如 "episode_repo.rs:insert")
25/// - `message`: 日志消息简述
26/// - `data`: 附加的 JSON 数据(任意结构)
27///
28/// # 注意事项
29///
30/// - 文件写入失败时静默忽略(不 panic,不返回错误)
31/// - 日志仅在开发调试阶段使用,生产环境建议通过 feature flag 控制
32pub fn log(hypothesis_id: &str, location: &str, message: &str, data: serde_json::Value) {
33 // #region agent log
34 let log_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
35 .join("..")
36 .join("debug-b75d44.log");
37 let entry = serde_json::json!({
38 "sessionId": "b75d44",
39 "hypothesisId": hypothesis_id,
40 "location": location,
41 "message": message,
42 "data": data,
43 "timestamp": chrono::Utc::now().timestamp_millis(),
44 "runId": "pre-fix"
45 });
46 if let Ok(mut f) = std::fs::OpenOptions::new()
47 .create(true)
48 .append(true)
49 .open(log_path)
50 {
51 let _ = writeln!(f, "{entry}");
52 }
53 // #endregion
54}