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/// Emit a trace line for one invocation. Best-effort: never propagates errors.
90pub fn emit(config_path: &Path, agent_id: Option<&str>, op: &str, result: &CmdResult) {
91    if let Err(e) = try_emit(config_path, agent_id, op, result) {
92        tracing::debug!(error = %e, "cli trace write failed (ignored)");
93    }
94}
95
96fn try_emit(
97    config_path: &Path,
98    agent_id: Option<&str>,
99    op: &str,
100    result: &CmdResult,
101) -> std::io::Result<()> {
102    let now = chrono::Utc::now();
103    let agent = resolve_agent(std::env::var(AGENT_ENV).ok().as_deref(), agent_id);
104    let record = build_record(
105        now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
106        agent.clone(),
107        op,
108        taskfast_client::take_last_corr(),
109        result,
110    );
111
112    let mut line = serde_json::to_string(&record)
113        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
114    line.push('\n');
115
116    let dir = resolve_dir(config_path, std::env::var(TRACE_DIR_ENV).ok().as_deref());
117    std::fs::create_dir_all(&dir)?;
118    let file = dir.join(format!(
119        "trace-{}-{}.jsonl",
120        sanitize(&agent),
121        now.format("%Y-%m-%d")
122    ));
123    // O_APPEND makes a single write(2) atomic across processes (the line is
124    // ~200 B, well under PIPE_BUF = 4096). `write_all` could split into several
125    // write(2)s on a short write and interleave with a concurrent agent, so we
126    // issue exactly one write and treat a short write as an error — swallowed
127    // by `emit`, since the trace is best-effort.
128    let mut f = OpenOptions::new().create(true).append(true).open(file)?;
129    let written = f.write(line.as_bytes())?;
130    if written != line.len() {
131        return Err(std::io::Error::new(
132            std::io::ErrorKind::WriteZero,
133            "short trace append; dropped to preserve line atomicity",
134        ));
135    }
136    Ok(())
137}
138
139fn build_record(
140    at: String,
141    agent: String,
142    op: &str,
143    corr: Option<String>,
144    result: &CmdResult,
145) -> TraceRecord {
146    let (exit, ok, error, data) = match result {
147        Ok(env) => (0, true, None, env.data.as_ref()),
148        Err(e) => (e.exit_code() as i32, false, Some(e.code()), None),
149    };
150    TraceRecord {
151        at,
152        agent,
153        op: op.to_string(),
154        kind: "cli",
155        corr,
156        task_id: id_from(data, "task_id"),
157        bid_id: id_from(data, "bid_id"),
158        escrow_id: id_from(data, "escrow_id"),
159        tx_hash: tx_hash_from(data),
160        exit,
161        ok,
162        error,
163    }
164}
165
166/// Pull a top-level string id out of a success envelope's `data`. Only the
167/// allowlisted keys are ever read — arbitrary response fields never leak.
168fn id_from(data: Option<&serde_json::Value>, key: &str) -> Option<String> {
169    data?.get(key)?.as_str().map(str::to_string)
170}
171
172/// Pull the transaction hash, which commands surface under varied keys
173/// (`tx_hash`, `submission_fee_tx_hash`, `approval_tx_hash`, ...). A tx hash is
174/// a public on-chain value — never secret — and a response carries one primary
175/// hash, so taking any top-level `*tx_hash` key is safe and unambiguous.
176fn tx_hash_from(data: Option<&serde_json::Value>) -> Option<String> {
177    let obj = data?.as_object()?;
178    if let Some(v) = obj.get("tx_hash").and_then(serde_json::Value::as_str) {
179        return Some(v.to_string());
180    }
181    obj.iter()
182        .find(|(k, _)| k.ends_with("tx_hash"))
183        .and_then(|(_, v)| v.as_str())
184        .map(str::to_string)
185}
186
187fn resolve_dir(config_path: &Path, env_override: Option<&str>) -> PathBuf {
188    if let Some(dir) = env_override.filter(|d| !d.is_empty()) {
189        return PathBuf::from(dir);
190    }
191    config_path
192        .parent()
193        .filter(|p| !p.as_os_str().is_empty())
194        .unwrap_or_else(|| Path::new("."))
195        .join("traces")
196}
197
198fn resolve_agent(env_agent: Option<&str>, agent_id: Option<&str>) -> String {
199    env_agent
200        .filter(|s| !s.is_empty())
201        .or(agent_id.filter(|s| !s.is_empty()))
202        .unwrap_or("unknown")
203        .to_string()
204}
205
206/// Filesystem-safe label for the trace filename (the `agent` field stays raw).
207fn sanitize(s: &str) -> String {
208    s.chars()
209        .map(|c| {
210            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
211                c
212            } else {
213                '-'
214            }
215        })
216        .collect()
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::cmd::CmdError;
223    use crate::envelope::Envelope;
224    use crate::Environment;
225    use serde_json::json;
226
227    fn ok_envelope(data: serde_json::Value) -> Envelope {
228        Envelope::success(Environment::Staging, false, data)
229    }
230
231    #[test]
232    fn tx_hash_matches_prefixed_keys() {
233        // Commands surface the hash under varied keys; all must populate it.
234        let data = json!({ "submission_fee_tx_hash": "0xfee" });
235        assert_eq!(tx_hash_from(Some(&data)).as_deref(), Some("0xfee"));
236        // The canonical key wins when both are present.
237        let data = json!({ "tx_hash": "0xprimary", "approval_tx_hash": "0xappr" });
238        assert_eq!(tx_hash_from(Some(&data)).as_deref(), Some("0xprimary"));
239        assert_eq!(tx_hash_from(Some(&json!({ "other": 1 }))), None);
240    }
241
242    #[test]
243    fn op_is_subcommand_path_without_flag_values() {
244        let cmd = clap::Command::new("taskfast").subcommand(
245            clap::Command::new("escrow").subcommand(
246                clap::Command::new("sign")
247                    .arg(clap::Arg::new("wallet-password").long("wallet-password")),
248            ),
249        );
250        let matches =
251            cmd.get_matches_from(["taskfast", "escrow", "sign", "--wallet-password", "hunter2"]);
252        let op = subcommand_path(&matches);
253        assert_eq!(op, "escrow sign");
254        // Redaction: the secret value must not appear anywhere in `op`.
255        assert!(!op.contains("hunter2"));
256    }
257
258    #[test]
259    fn success_record_pulls_allowlisted_ids_only() {
260        let record = build_record(
261            "2026-06-29T00:00:00.000Z".into(),
262            "poster-1".into(),
263            "post",
264            Some("req-9".into()),
265            &Ok(ok_envelope(json!({
266                "task_id": "task_abc",
267                "tx_hash": "0xdead",
268                "wallet_password": "should-never-appear",
269                "api_key": "am_live_secret",
270            }))),
271        );
272        assert_eq!(record.task_id.as_deref(), Some("task_abc"));
273        assert_eq!(record.tx_hash.as_deref(), Some("0xdead"));
274        assert_eq!(record.corr.as_deref(), Some("req-9"));
275        assert!(record.ok);
276        assert_eq!(record.exit, 0);
277        assert_eq!(record.kind, "cli");
278
279        // The serialized line must carry no non-allowlisted field, especially
280        // not secret-looking ones present in the response data.
281        let line = serde_json::to_string(&record).unwrap();
282        assert!(!line.contains("wallet_password"));
283        assert!(!line.contains("api_key"));
284        assert!(!line.contains("am_live_secret"));
285    }
286
287    #[test]
288    fn error_record_uses_stable_category_not_message() {
289        let err = CmdError::Auth("token rejected for user@example.com".into());
290        let code = err.code();
291        let exit = err.exit_code() as i32;
292        let record = build_record(
293            "2026-06-29T00:00:00.000Z".into(),
294            "poster-1".into(),
295            "me",
296            None,
297            &Err(err),
298        );
299        assert!(!record.ok);
300        assert_eq!(record.exit, exit);
301        assert_eq!(record.error, Some(code));
302        // The free-form message (which could echo user input) must not leak.
303        let line = serde_json::to_string(&record).unwrap();
304        assert!(!line.contains("user@example.com"));
305    }
306
307    #[test]
308    fn toggle_defaults_on_and_respects_opt_out() {
309        assert!(toggle_from_env(None));
310        assert!(toggle_from_env(Some("1")));
311        assert!(toggle_from_env(Some("yes")));
312        for off in ["0", "false", "off", "no", "OFF", " false "] {
313            assert!(!toggle_from_env(Some(off)), "{off} should disable");
314        }
315        assert!(!enabled(true)); // --no-trace wins regardless of env
316    }
317
318    #[test]
319    fn dir_and_agent_resolution() {
320        let cfg = Path::new(".taskfast/config.json");
321        assert_eq!(resolve_dir(cfg, None), PathBuf::from(".taskfast/traces"));
322        assert_eq!(
323            resolve_dir(cfg, Some("/custom/dir")),
324            PathBuf::from("/custom/dir")
325        );
326        assert_eq!(resolve_agent(Some("env-agent"), Some("cfg")), "env-agent");
327        assert_eq!(resolve_agent(None, Some("cfg-agent")), "cfg-agent");
328        assert_eq!(resolve_agent(None, None), "unknown");
329        assert_eq!(sanitize("agent/1:2"), "agent-1-2");
330    }
331}