Skip to main content

taskfast_cli/
trace.rs

1// SPDX-License-Identifier: MIT
2//! CLI-native JSONL command trace (gh#85).
3//!
4//! Appends one JSON line per invocation to a per-agent, per-day file under
5//! `traces/` (next to `config.json`, override with `TASKFAST_TRACE_DIR`). The
6//! line's `corr` is the server `x-request-id`, the join key back to
7//! `mix taskfast.trace <task_id>`.
8//!
9//! **Redaction is the whole point.** The CLI holds keystores, wallet passwords
10//! and signed payloads, so the record is a strict *allowlist*: subcommand path
11//! (never flag values), the server correlation id, response-derived ids, the
12//! exit class, and a stable error *category* (never a free-form message). A new
13//! field is opt-in by construction — nothing reaches disk unless added here.
14//!
15//! Writing is best-effort: any failure is logged at debug and swallowed so the
16//! trace can never change a command's outcome.
17
18use 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/// One redaction-safe trace line. Field order mirrors the AgentTrace
31/// vocabulary so server- and CLI-emitted lines align.
32#[derive(Debug, Serialize, PartialEq, Eq)]
33pub struct TraceRecord {
34    /// RFC3339 with millis, e.g. `2026-06-29T00:00:00.000Z`.
35    pub at: String,
36    pub agent: String,
37    /// Subcommand path only (e.g. `escrow sign`). Never argument values.
38    pub op: String,
39    /// Always `cli` for CLI-native lines (`http` is the server's vocabulary).
40    pub kind: &'static str,
41    /// Server `x-request-id`; absent on purely local commands / transport fail.
42    #[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    /// Stable error category from `CmdError::code()` (a fixed set of static
55    /// strings). Never a message — messages may echo user input.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub error: Option<&'static str>,
58}
59
60/// Walk clap's matched subcommand names into a space-joined path. This reads
61/// only subcommand *names*, never argument values — that is the redaction
62/// guarantee for `op`: `escrow sign --wallet-password X` yields `escrow sign`.
63pub 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
73/// Whether tracing is on. On by default; `--no-trace` or `TASKFAST_TRACE` in
74/// {0,false,off,no} turns it off.
75pub 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
89/// Take the last-captured server correlation id (`x-request-id`), if any.
90/// Consumes it — the caller must take it exactly once per invocation and
91/// share the value between the trace line and the stdout envelope (gh#91),
92/// since a second take always sees `None`.
93pub fn take_corr() -> Option<String> {
94    taskfast_client::take_last_corr()
95}
96
97/// Emit a trace line for one invocation. Best-effort: never propagates errors.
98pub 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    // O_APPEND makes a single write(2) atomic across processes (the line is
139    // ~200 B, well under PIPE_BUF = 4096). `write_all` could split into several
140    // write(2)s on a short write and interleave with a concurrent agent, so we
141    // issue exactly one write and treat a short write as an error — swallowed
142    // by `emit`, since the trace is best-effort.
143    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
181/// Pull a top-level string id out of a success envelope's `data`. Only the
182/// allowlisted keys are ever read — arbitrary response fields never leak.
183fn id_from(data: Option<&serde_json::Value>, key: &str) -> Option<String> {
184    data?.get(key)?.as_str().map(str::to_string)
185}
186
187/// Pull the transaction hash, which commands surface under varied keys
188/// (`tx_hash`, `submission_fee_tx_hash`, `approval_tx_hash`, ...). A tx hash is
189/// a public on-chain value — never secret — and a response carries one primary
190/// hash, so taking any top-level `*tx_hash` key is safe and unambiguous.
191fn 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
221/// Filesystem-safe label for the trace filename (the `agent` field stays raw).
222fn 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        // Commands surface the hash under varied keys; all must populate it.
249        let data = json!({ "submission_fee_tx_hash": "0xfee" });
250        assert_eq!(tx_hash_from(Some(&data)).as_deref(), Some("0xfee"));
251        // The canonical key wins when both are present.
252        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        // Redaction: the secret value must not appear anywhere in `op`.
270        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        // The serialized line must carry no non-allowlisted field, especially
295        // not secret-looking ones present in the response data.
296        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        // The free-form message (which could echo user input) must not leak.
318        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)); // --no-trace wins regardless of env
331    }
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}