1use std::fs::OpenOptions;
19use std::io::Write;
20use std::path::{Path, PathBuf};
21
22use serde::Serialize;
23
24use crate::cmd::CmdResult;
25
26const TRACE_DIR_ENV: &str = "TASKFAST_TRACE_DIR";
27const TRACE_TOGGLE_ENV: &str = "TASKFAST_TRACE";
28const AGENT_ENV: &str = "TASKFAST_AGENT";
29
30#[derive(Debug, Serialize, PartialEq, Eq)]
33pub struct TraceRecord {
34 pub at: String,
36 pub agent: String,
37 pub op: String,
39 pub kind: &'static str,
41 #[serde(skip_serializing_if = "Option::is_none")]
43 pub corr: Option<String>,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub task_id: Option<String>,
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub bid_id: Option<String>,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub escrow_id: Option<String>,
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub tx_hash: Option<String>,
52 pub exit: i32,
53 pub ok: bool,
54 #[serde(skip_serializing_if = "Option::is_none")]
57 pub error: Option<&'static str>,
58}
59
60pub fn subcommand_path(matches: &clap::ArgMatches) -> String {
64 let mut parts = Vec::new();
65 let mut cur = matches;
66 while let Some((name, sub)) = cur.subcommand() {
67 parts.push(name);
68 cur = sub;
69 }
70 parts.join(" ")
71}
72
73pub fn enabled(no_trace_flag: bool) -> bool {
76 !no_trace_flag && toggle_from_env(std::env::var(TRACE_TOGGLE_ENV).ok().as_deref())
77}
78
79fn toggle_from_env(value: Option<&str>) -> bool {
80 match value {
81 Some(v) => !matches!(
82 v.trim().to_ascii_lowercase().as_str(),
83 "0" | "false" | "off" | "no"
84 ),
85 None => true,
86 }
87}
88
89pub fn take_corr() -> Option<String> {
94 taskfast_client::take_last_corr()
95}
96
97pub fn emit(
99 config_path: &Path,
100 agent_id: Option<&str>,
101 op: &str,
102 result: &CmdResult,
103 corr: Option<&str>,
104) {
105 if let Err(e) = try_emit(config_path, agent_id, op, result, corr) {
106 tracing::debug!(error = %e, "cli trace write failed (ignored)");
107 }
108}
109
110fn try_emit(
111 config_path: &Path,
112 agent_id: Option<&str>,
113 op: &str,
114 result: &CmdResult,
115 corr: Option<&str>,
116) -> std::io::Result<()> {
117 let now = chrono::Utc::now();
118 let agent = resolve_agent(std::env::var(AGENT_ENV).ok().as_deref(), agent_id);
119 let record = build_record(
120 now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
121 agent.clone(),
122 op,
123 corr.map(str::to_string),
124 result,
125 );
126
127 let mut line = serde_json::to_string(&record)
128 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
129 line.push('\n');
130
131 let dir = resolve_dir(config_path, std::env::var(TRACE_DIR_ENV).ok().as_deref());
132 std::fs::create_dir_all(&dir)?;
133 let file = dir.join(format!(
134 "trace-{}-{}.jsonl",
135 sanitize(&agent),
136 now.format("%Y-%m-%d")
137 ));
138 let mut f = OpenOptions::new().create(true).append(true).open(file)?;
144 let written = f.write(line.as_bytes())?;
145 if written != line.len() {
146 return Err(std::io::Error::new(
147 std::io::ErrorKind::WriteZero,
148 "short trace append; dropped to preserve line atomicity",
149 ));
150 }
151 Ok(())
152}
153
154fn build_record(
155 at: String,
156 agent: String,
157 op: &str,
158 corr: Option<String>,
159 result: &CmdResult,
160) -> TraceRecord {
161 let (exit, ok, error, data) = match result {
162 Ok(env) => (0, true, None, env.data.as_ref()),
163 Err(e) => (e.exit_code() as i32, false, Some(e.code()), None),
164 };
165 TraceRecord {
166 at,
167 agent,
168 op: op.to_string(),
169 kind: "cli",
170 corr,
171 task_id: id_from(data, "task_id"),
172 bid_id: id_from(data, "bid_id"),
173 escrow_id: id_from(data, "escrow_id"),
174 tx_hash: tx_hash_from(data),
175 exit,
176 ok,
177 error,
178 }
179}
180
181fn id_from(data: Option<&serde_json::Value>, key: &str) -> Option<String> {
184 data?.get(key)?.as_str().map(str::to_string)
185}
186
187fn tx_hash_from(data: Option<&serde_json::Value>) -> Option<String> {
192 let obj = data?.as_object()?;
193 if let Some(v) = obj.get("tx_hash").and_then(serde_json::Value::as_str) {
194 return Some(v.to_string());
195 }
196 obj.iter()
197 .find(|(k, _)| k.ends_with("tx_hash"))
198 .and_then(|(_, v)| v.as_str())
199 .map(str::to_string)
200}
201
202fn resolve_dir(config_path: &Path, env_override: Option<&str>) -> PathBuf {
203 if let Some(dir) = env_override.filter(|d| !d.is_empty()) {
204 return PathBuf::from(dir);
205 }
206 config_path
207 .parent()
208 .filter(|p| !p.as_os_str().is_empty())
209 .unwrap_or_else(|| Path::new("."))
210 .join("traces")
211}
212
213fn resolve_agent(env_agent: Option<&str>, agent_id: Option<&str>) -> String {
214 env_agent
215 .filter(|s| !s.is_empty())
216 .or(agent_id.filter(|s| !s.is_empty()))
217 .unwrap_or("unknown")
218 .to_string()
219}
220
221fn sanitize(s: &str) -> String {
223 s.chars()
224 .map(|c| {
225 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
226 c
227 } else {
228 '-'
229 }
230 })
231 .collect()
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use crate::cmd::CmdError;
238 use crate::envelope::Envelope;
239 use crate::Environment;
240 use serde_json::json;
241
242 fn ok_envelope(data: serde_json::Value) -> Envelope {
243 Envelope::success(Environment::Staging, false, data)
244 }
245
246 #[test]
247 fn tx_hash_matches_prefixed_keys() {
248 let data = json!({ "submission_fee_tx_hash": "0xfee" });
250 assert_eq!(tx_hash_from(Some(&data)).as_deref(), Some("0xfee"));
251 let data = json!({ "tx_hash": "0xprimary", "approval_tx_hash": "0xappr" });
253 assert_eq!(tx_hash_from(Some(&data)).as_deref(), Some("0xprimary"));
254 assert_eq!(tx_hash_from(Some(&json!({ "other": 1 }))), None);
255 }
256
257 #[test]
258 fn op_is_subcommand_path_without_flag_values() {
259 let cmd = clap::Command::new("taskfast").subcommand(
260 clap::Command::new("escrow").subcommand(
261 clap::Command::new("sign")
262 .arg(clap::Arg::new("wallet-password").long("wallet-password")),
263 ),
264 );
265 let matches =
266 cmd.get_matches_from(["taskfast", "escrow", "sign", "--wallet-password", "hunter2"]);
267 let op = subcommand_path(&matches);
268 assert_eq!(op, "escrow sign");
269 assert!(!op.contains("hunter2"));
271 }
272
273 #[test]
274 fn success_record_pulls_allowlisted_ids_only() {
275 let record = build_record(
276 "2026-06-29T00:00:00.000Z".into(),
277 "poster-1".into(),
278 "post",
279 Some("req-9".into()),
280 &Ok(ok_envelope(json!({
281 "task_id": "task_abc",
282 "tx_hash": "0xdead",
283 "wallet_password": "should-never-appear",
284 "api_key": "am_live_secret",
285 }))),
286 );
287 assert_eq!(record.task_id.as_deref(), Some("task_abc"));
288 assert_eq!(record.tx_hash.as_deref(), Some("0xdead"));
289 assert_eq!(record.corr.as_deref(), Some("req-9"));
290 assert!(record.ok);
291 assert_eq!(record.exit, 0);
292 assert_eq!(record.kind, "cli");
293
294 let line = serde_json::to_string(&record).unwrap();
297 assert!(!line.contains("wallet_password"));
298 assert!(!line.contains("api_key"));
299 assert!(!line.contains("am_live_secret"));
300 }
301
302 #[test]
303 fn error_record_uses_stable_category_not_message() {
304 let err = CmdError::Auth("token rejected for user@example.com".into());
305 let code = err.code();
306 let exit = err.exit_code() as i32;
307 let record = build_record(
308 "2026-06-29T00:00:00.000Z".into(),
309 "poster-1".into(),
310 "me",
311 None,
312 &Err(err),
313 );
314 assert!(!record.ok);
315 assert_eq!(record.exit, exit);
316 assert_eq!(record.error, Some(code));
317 let line = serde_json::to_string(&record).unwrap();
319 assert!(!line.contains("user@example.com"));
320 }
321
322 #[test]
323 fn toggle_defaults_on_and_respects_opt_out() {
324 assert!(toggle_from_env(None));
325 assert!(toggle_from_env(Some("1")));
326 assert!(toggle_from_env(Some("yes")));
327 for off in ["0", "false", "off", "no", "OFF", " false "] {
328 assert!(!toggle_from_env(Some(off)), "{off} should disable");
329 }
330 assert!(!enabled(true)); }
332
333 #[test]
334 fn dir_and_agent_resolution() {
335 let cfg = Path::new(".taskfast/config.json");
336 assert_eq!(resolve_dir(cfg, None), PathBuf::from(".taskfast/traces"));
337 assert_eq!(
338 resolve_dir(cfg, Some("/custom/dir")),
339 PathBuf::from("/custom/dir")
340 );
341 assert_eq!(resolve_agent(Some("env-agent"), Some("cfg")), "env-agent");
342 assert_eq!(resolve_agent(None, Some("cfg-agent")), "cfg-agent");
343 assert_eq!(resolve_agent(None, None), "unknown");
344 assert_eq!(sanitize("agent/1:2"), "agent-1-2");
345 }
346}