schwab_cli/agent/
journal.rs1use std::fs::OpenOptions;
2use std::io::Write;
3use std::path::Path;
4
5use anyhow::{Context, Result};
6use chrono::{DateTime, Utc};
7use serde_json::Value;
8
9use super::paths::{journal_path, sim_journal_path};
10
11pub fn append_event(rules_path: &Path, simulate: bool, event_type: &str, payload: Value) -> Result<()> {
12 append_event_at(rules_path, simulate, Utc::now(), event_type, payload)
13}
14
15pub fn append_event_at(
16 rules_path: &Path,
17 simulate: bool,
18 at: DateTime<Utc>,
19 event_type: &str,
20 payload: Value,
21) -> Result<()> {
22 let path = if simulate {
23 sim_journal_path(rules_path)
24 } else {
25 journal_path(rules_path)
26 };
27 if let Some(parent) = path.parent() {
28 std::fs::create_dir_all(parent)?;
29 }
30 let line = serde_json::json!({
31 "ts": at.to_rfc3339(),
32 "type": event_type,
33 "payload": payload,
34 });
35 let mut file = OpenOptions::new()
36 .create(true)
37 .append(true)
38 .open(&path)
39 .with_context(|| format!("open journal {}", path.display()))?;
40 writeln!(file, "{line}")?;
41 Ok(())
42}