Skip to main content

agent_engine/extensions/
audit.rs

1//! Append-only provider invocation audit log.
2//!
3//! Records minimal metadata for each provider routing event without
4//! storing prompts or tool payloads. File: `$SYNAPS_BASE_DIR/extensions/audit.jsonl`.
5//!
6//! Design constraints:
7//!
8//! - One JSON object per line; missing file is equivalent to no entries.
9//! - Append-only: each new entry uses `O_APPEND` so concurrent appenders
10//!   on Unix produce well-formed line records without locking.
11//! - Malformed lines (e.g. partial write from a crash) are skipped on read
12//!   with a `tracing::warn!` so a corrupt line cannot lock the user out.
13//! - Never contains prompt text, tool inputs, tool outputs, or tokens.
14
15use std::fs::OpenOptions;
16use std::io::Write;
17use std::path::{Path, PathBuf};
18
19#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
20pub struct ProviderAuditEntry {
21    /// RFC3339 UTC timestamp.
22    pub timestamp: String,
23    pub plugin_id: String,
24    pub provider_id: String,
25    pub model_id: String,
26    /// Whether Synaps exposed any tool schemas to this invocation.
27    pub tools_exposed: bool,
28    /// Number of tool calls the provider requested during this invocation.
29    /// 0 if no tool-use loop ran.
30    #[serde(default)]
31    pub tools_requested: u32,
32    /// Whether the invocation streamed (vs. provider.complete).
33    #[serde(default)]
34    pub streamed: bool,
35    /// "ok" | "error" | "blocked" — high-level outcome.
36    pub outcome: String,
37    /// Optional short error class (e.g. "trust_disabled", "ipc_error", "timeout").
38    /// MUST NOT contain prompt or tool content.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub error_class: Option<String>,
41}
42
43/// Path to the audit file under the active base dir. Caller is responsible for
44/// creating parent directories when writing.
45pub fn audit_file_path() -> PathBuf {
46    audit_file_path_for(&crate::config::base_dir())
47}
48
49/// Path to the audit file rooted at an explicit base dir (test helper / reuse).
50pub(crate) fn audit_file_path_for(base: &Path) -> PathBuf {
51    base.join("extensions").join("audit.jsonl")
52}
53
54/// Build a fresh entry with the current UTC timestamp.
55#[allow(clippy::too_many_arguments)]
56pub fn new_audit_entry(
57    plugin_id: impl Into<String>,
58    provider_id: impl Into<String>,
59    model_id: impl Into<String>,
60    tools_exposed: bool,
61    tools_requested: u32,
62    streamed: bool,
63    outcome: impl Into<String>,
64    error_class: Option<String>,
65) -> ProviderAuditEntry {
66    ProviderAuditEntry {
67        timestamp: chrono::Utc::now().to_rfc3339(),
68        plugin_id: plugin_id.into(),
69        provider_id: provider_id.into(),
70        model_id: model_id.into(),
71        tools_exposed,
72        tools_requested,
73        streamed,
74        outcome: outcome.into(),
75        error_class,
76    }
77}
78
79/// Append a single entry as one JSON line. Creates parent dirs and the file
80/// if missing. Atomic per-line via `O_APPEND` on Unix.
81pub fn append_audit_entry(entry: &ProviderAuditEntry) -> Result<(), String> {
82    append_audit_entry_to(&crate::config::base_dir(), entry)
83}
84
85/// Append an entry under an explicit base dir.
86pub(crate) fn append_audit_entry_to(base: &Path, entry: &ProviderAuditEntry) -> Result<(), String> {
87    let path = audit_file_path_for(base);
88    let parent = path
89        .parent()
90        .ok_or_else(|| format!("audit.jsonl path has no parent: {}", path.display()))?;
91    std::fs::create_dir_all(parent)
92        .map_err(|e| format!("failed to create dir {}: {}", parent.display(), e))?;
93
94    let mut line = serde_json::to_string(entry)
95        .map_err(|e| format!("failed to serialize audit entry: {}", e))?;
96    line.push('\n');
97
98    let mut file = OpenOptions::new()
99        .create(true)
100        .append(true)
101        .open(&path)
102        .map_err(|e| format!("failed to open {}: {}", path.display(), e))?;
103    file.write_all(line.as_bytes())
104        .map_err(|e| format!("failed to append to {}: {}", path.display(), e))?;
105    Ok(())
106}
107
108// ── Tool-output intercept audit (HookResult::Replace) ───────────────────────
109
110/// Audit record for an extension rewriting a tool's output via
111/// `HookResult::Replace`. Captures WHO rewrote WHICH tool's output and WHEN,
112/// plus sizes — never the content (privacy), matching the provider-audit policy.
113#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
114pub struct InterceptAuditEntry {
115    /// RFC3339 UTC timestamp.
116    pub timestamp: String,
117    pub plugin_id: String,
118    /// Hook that fired (e.g. "after_tool_call").
119    pub hook: String,
120    /// Tool whose output was rewritten, when tool-specific.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub tool_name: Option<String>,
123    /// Action taken (currently always "replace").
124    pub action: String,
125    /// Length (bytes) of the output the extension observed. For large outputs
126    /// this is the 32 KB event preview, not the full original.
127    pub observed_len: usize,
128    /// Length (bytes) of the replacement the extension returned.
129    pub replacement_len: usize,
130}
131
132/// Path to the intercept audit file (`$SYNAPS_BASE_DIR/extensions/intercept.jsonl`).
133pub fn intercept_file_path() -> PathBuf {
134    intercept_file_path_for(&crate::config::base_dir())
135}
136
137pub(crate) fn intercept_file_path_for(base: &Path) -> PathBuf {
138    base.join("extensions").join("intercept.jsonl")
139}
140
141/// Record that an extension replaced a tool's output. Best-effort and
142/// metadata-only — auditing must never break or alter the tool flow, so
143/// callers typically ignore the result.
144pub fn record_tool_output_replace(
145    plugin_id: impl Into<String>,
146    hook: impl Into<String>,
147    tool_name: Option<String>,
148    observed_len: usize,
149    replacement_len: usize,
150) -> Result<(), String> {
151    record_tool_output_replace_to(
152        &crate::config::base_dir(),
153        plugin_id,
154        hook,
155        tool_name,
156        observed_len,
157        replacement_len,
158    )
159}
160
161pub(crate) fn record_tool_output_replace_to(
162    base: &Path,
163    plugin_id: impl Into<String>,
164    hook: impl Into<String>,
165    tool_name: Option<String>,
166    observed_len: usize,
167    replacement_len: usize,
168) -> Result<(), String> {
169    let entry = InterceptAuditEntry {
170        timestamp: chrono::Utc::now().to_rfc3339(),
171        plugin_id: plugin_id.into(),
172        hook: hook.into(),
173        tool_name,
174        action: "replace".to_string(),
175        observed_len,
176        replacement_len,
177    };
178    let path = intercept_file_path_for(base);
179    let parent = path
180        .parent()
181        .ok_or_else(|| format!("intercept.jsonl path has no parent: {}", path.display()))?;
182    std::fs::create_dir_all(parent)
183        .map_err(|e| format!("failed to create dir {}: {}", parent.display(), e))?;
184    let mut line = serde_json::to_string(&entry)
185        .map_err(|e| format!("failed to serialize intercept entry: {}", e))?;
186    line.push('\n');
187    let mut file = OpenOptions::new()
188        .create(true)
189        .append(true)
190        .open(&path)
191        .map_err(|e| format!("failed to open {}: {}", path.display(), e))?;
192    file.write_all(line.as_bytes())
193        .map_err(|e| format!("failed to append to {}: {}", path.display(), e))?;
194    Ok(())
195}
196
197/// Read all entries (one per line). Missing file → empty Vec. Malformed
198/// lines are skipped with a `tracing::warn!`.
199pub fn read_audit_entries() -> Result<Vec<ProviderAuditEntry>, String> {
200    read_audit_entries_from(&crate::config::base_dir())
201}
202
203/// Read entries under an explicit base dir.
204pub(crate) fn read_audit_entries_from(base: &Path) -> Result<Vec<ProviderAuditEntry>, String> {
205    let path = audit_file_path_for(base);
206    let contents = match std::fs::read_to_string(&path) {
207        Ok(s) => s,
208        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
209        Err(e) => {
210            return Err(format!(
211                "failed to read audit.jsonl at {}: {}",
212                path.display(),
213                e
214            ));
215        }
216    };
217    let mut entries = Vec::new();
218    for (idx, raw) in contents.lines().enumerate() {
219        let line = raw.trim();
220        if line.is_empty() {
221            continue;
222        }
223        match serde_json::from_str::<ProviderAuditEntry>(line) {
224            Ok(entry) => entries.push(entry),
225            Err(e) => {
226                tracing::warn!(
227                    target: "synaps::extensions::audit",
228                    "skipping malformed audit.jsonl line {} at {}: {}",
229                    idx + 1,
230                    path.display(),
231                    e
232                );
233            }
234        }
235    }
236    Ok(entries)
237}
238
239/// Read only the last `n` entries from the audit log.  Reads the whole file
240/// but collects lines into a fixed-capacity ring so only the tail N lines are
241/// ever parsed by serde — O(file_size) bytes read but O(N) deserialisation.
242/// Missing file → empty Vec.  Malformed tail lines are skipped with a warn.
243pub fn read_audit_entries_tail(n: usize) -> Result<Vec<ProviderAuditEntry>, String> {
244    read_audit_entries_tail_from(&crate::config::base_dir(), n)
245}
246
247/// `read_audit_entries_tail` under an explicit base dir (test helper).
248pub(crate) fn read_audit_entries_tail_from(
249    base: &Path,
250    n: usize,
251) -> Result<Vec<ProviderAuditEntry>, String> {
252    if n == 0 {
253        return Ok(Vec::new());
254    }
255    let path = audit_file_path_for(base);
256    let contents = match std::fs::read_to_string(&path) {
257        Ok(s) => s,
258        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
259        Err(e) => {
260            return Err(format!(
261                "failed to read audit.jsonl at {}: {}",
262                path.display(),
263                e
264            ));
265        }
266    };
267    // Collect the last N non-empty lines without parsing them yet — avoids
268    // deserialising the entire history when only the tail is needed.
269    let tail_lines: Vec<&str> = contents
270        .lines()
271        .filter(|l| !l.trim().is_empty())
272        .collect::<Vec<_>>()
273        .into_iter()
274        .rev()
275        .take(n)
276        .collect::<Vec<_>>()
277        .into_iter()
278        .rev()
279        .collect();
280
281    let mut entries = Vec::with_capacity(tail_lines.len());
282    for raw in tail_lines {
283        let line = raw.trim();
284        match serde_json::from_str::<ProviderAuditEntry>(line) {
285            Ok(entry) => entries.push(entry),
286            Err(e) => {
287                tracing::warn!(
288                    target: "synaps::extensions::audit",
289                    "skipping malformed audit.jsonl tail line at {}: {}",
290                    path.display(),
291                    e
292                );
293            }
294        }
295    }
296    Ok(entries)
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use tempfile::TempDir;
303
304    fn sample(plugin: &str, outcome: &str) -> ProviderAuditEntry {
305        ProviderAuditEntry {
306            timestamp: "2025-01-01T00:00:00Z".to_string(),
307            plugin_id: plugin.to_string(),
308            provider_id: "p".to_string(),
309            model_id: "m".to_string(),
310            tools_exposed: false,
311            tools_requested: 0,
312            streamed: false,
313            outcome: outcome.to_string(),
314            error_class: None,
315        }
316    }
317
318    #[test]
319    fn audit_file_path_is_under_extensions_dir() {
320        let dir = TempDir::new().unwrap();
321        let p = audit_file_path_for(dir.path());
322        assert_eq!(p, dir.path().join("extensions").join("audit.jsonl"));
323    }
324
325    #[test]
326    fn append_two_entries_then_read_returns_them_in_order() {
327        let dir = TempDir::new().unwrap();
328        let a = sample("plug-a", "ok");
329        let b = sample("plug-b", "blocked");
330        append_audit_entry_to(dir.path(), &a).unwrap();
331        append_audit_entry_to(dir.path(), &b).unwrap();
332        let entries = read_audit_entries_from(dir.path()).unwrap();
333        assert_eq!(entries, vec![a, b]);
334    }
335
336    #[test]
337    fn read_missing_file_returns_empty() {
338        let dir = TempDir::new().unwrap();
339        let entries = read_audit_entries_from(dir.path()).unwrap();
340        assert!(entries.is_empty());
341    }
342
343    #[test]
344    fn intercept_path_is_under_extensions_dir() {
345        let dir = TempDir::new().unwrap();
346        assert_eq!(
347            intercept_file_path_for(dir.path()),
348            dir.path().join("extensions").join("intercept.jsonl")
349        );
350    }
351
352    #[test]
353    fn record_tool_output_replace_writes_metadata_only() {
354        let dir = TempDir::new().unwrap();
355        record_tool_output_replace_to(
356            dir.path(),
357            "headroom-bridge",
358            "after_tool_call",
359            Some("bash".to_string()),
360            45_000,
361            6_080,
362        )
363        .unwrap();
364        let raw = std::fs::read_to_string(intercept_file_path_for(dir.path())).unwrap();
365        let entry: InterceptAuditEntry = serde_json::from_str(raw.trim()).unwrap();
366        assert_eq!(entry.plugin_id, "headroom-bridge");
367        assert_eq!(entry.hook, "after_tool_call");
368        assert_eq!(entry.tool_name.as_deref(), Some("bash"));
369        assert_eq!(entry.action, "replace");
370        assert_eq!(entry.observed_len, 45_000);
371        assert_eq!(entry.replacement_len, 6_080);
372        // Privacy: the record carries sizes, never tool content.
373        assert!(
374            !raw.contains("tool_output"),
375            "audit line must not carry content"
376        );
377    }
378
379    #[test]
380    fn malformed_line_in_middle_is_skipped() {
381        let dir = TempDir::new().unwrap();
382        let a = sample("plug-a", "ok");
383        let c = sample("plug-c", "error");
384        append_audit_entry_to(dir.path(), &a).unwrap();
385        // Inject a malformed line.
386        let path = audit_file_path_for(dir.path());
387        let mut f = OpenOptions::new().append(true).open(&path).unwrap();
388        f.write_all(b"{ this is not valid json\n").unwrap();
389        drop(f);
390        append_audit_entry_to(dir.path(), &c).unwrap();
391
392        let entries = read_audit_entries_from(dir.path()).unwrap();
393        assert_eq!(entries, vec![a, c]);
394    }
395
396    #[test]
397    fn concurrent_appenders_produce_full_record_count() {
398        let dir = TempDir::new().unwrap();
399        let base = dir.path().to_path_buf();
400        let mut handles = Vec::new();
401        for t in 0..4u32 {
402            let base = base.clone();
403            handles.push(std::thread::spawn(move || {
404                for i in 0..10u32 {
405                    let mut e = sample(&format!("plug-{t}"), "ok");
406                    e.tools_requested = i;
407                    append_audit_entry_to(&base, &e).expect("append");
408                }
409            }));
410        }
411        for h in handles {
412            h.join().unwrap();
413        }
414        let entries = read_audit_entries_from(&base).unwrap();
415        assert_eq!(entries.len(), 40);
416    }
417
418    #[test]
419    fn new_audit_entry_produces_rfc3339_timestamp() {
420        let e = new_audit_entry("plug", "prov", "model", true, 0, false, "ok", None);
421        // Year-4-digits + 'T' separator + tz suffix ('Z' or '+'/'-' offset).
422        let ts = &e.timestamp;
423        assert!(ts.len() >= 20, "timestamp too short: {ts}");
424        assert!(
425            ts.chars().take(4).all(|c| c.is_ascii_digit()),
426            "expected 4-digit year: {ts}"
427        );
428        assert!(ts.contains('T'), "expected 'T' separator: {ts}");
429        assert!(
430            ts.ends_with('Z') || ts.contains('+') || ts[10..].contains('-'),
431            "expected timezone suffix: {ts}"
432        );
433        // chrono should be able to round-trip its own RFC3339 output.
434        chrono::DateTime::parse_from_rfc3339(ts)
435            .unwrap_or_else(|err| panic!("parse_from_rfc3339({ts}) failed: {err}"));
436    }
437
438    #[test]
439    fn round_trip_with_error_class_omitted_when_none() {
440        let dir = TempDir::new().unwrap();
441        let mut e = sample("plug", "ok");
442        e.error_class = None;
443        append_audit_entry_to(dir.path(), &e).unwrap();
444        let raw = std::fs::read_to_string(audit_file_path_for(dir.path())).unwrap();
445        assert!(
446            !raw.contains("error_class"),
447            "error_class should be skipped when None: {raw}"
448        );
449        let loaded = read_audit_entries_from(dir.path()).unwrap();
450        assert_eq!(loaded, vec![e]);
451    }
452}