use std::{
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
pub fn current_epoch_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or_default()
}
pub fn current_log_timestamp() -> String {
format_log_timestamp(current_epoch_secs())
}
pub fn current_human_timestamp() -> String {
format_human_timestamp(current_epoch_secs())
}
pub fn current_local_date_ymd() -> String {
Command::new("date")
.args(["+%Y-%m-%d"])
.output()
.ok()
.and_then(|o| trimmed_date_stdout(&o.stdout))
.unwrap_or_else(|| "unknown-date".to_string())
}
fn trimmed_date_stdout(stdout: &[u8]) -> Option<String> {
let trimmed = String::from_utf8_lossy(stdout).trim().to_string();
(!trimmed.is_empty()).then_some(trimmed)
}
pub fn format_log_timestamp(secs: u64) -> String {
let days = (secs / 86_400) as i64;
let tod = secs % 86_400;
let (hh, mm, ss) = (tod / 3_600, (tod % 3_600) / 60, tod % 60);
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let year = if m <= 2 { y + 1 } else { y };
format!("{year:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}
pub fn format_human_timestamp(secs: u64) -> String {
let iso = format_log_timestamp(secs);
format!("{} {}", &iso[..10], &iso[11..19])
}
pub fn format_ops_log_tracking_suffix(
doc_stem: Option<&str>,
session: Option<&str>,
turn: Option<&str>,
) -> String {
let mut suffix = String::new();
if let Some(stem) = doc_stem {
suffix.push_str(" doc=");
suffix.push_str(stem);
}
if let Some(session) = session.filter(|session| !session.is_empty()) {
suffix.push_str(" session=");
suffix.push_str(session);
}
if let Some(turn) = turn.filter(|turn| !turn.is_empty()) {
suffix.push_str(" turn=");
suffix.push_str(turn);
}
suffix
}
pub fn format_ops_log_line(timestamp_secs: u64, message: &str, tracking_suffix: &str) -> String {
format!(
"[{}] {}{}",
format_log_timestamp(timestamp_secs),
message,
tracking_suffix
)
}
pub fn parse_log_timestamp(raw: &str) -> Option<u64> {
let s = raw.trim();
if let Ok(epoch) = s.parse::<u64>() {
return Some(epoch);
}
let s = s.strip_suffix('Z').unwrap_or(s);
let (date, time) = s.split_once('T')?;
let mut dp = date.split('-');
let year: i64 = dp.next()?.parse().ok()?;
let month: u64 = dp.next()?.parse().ok()?;
let day: u64 = dp.next()?.parse().ok()?;
if dp.next().is_some() || !(1..=12).contains(&month) || !(1..=31).contains(&day) {
return None;
}
let mut tp = time.split(':');
let hh: u64 = tp.next()?.parse().ok()?;
let mm: u64 = tp.next()?.parse().ok()?;
let ss: u64 = tp.next()?.parse().ok()?;
if tp.next().is_some() || hh > 23 || mm > 59 || ss > 60 {
return None;
}
let y = if month <= 2 { year - 1 } else { year };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = (y - era * 400) as u64; let mp = if month > 2 { month - 3 } else { month + 9 }; let doy = (153 * mp + 2) / 5 + day - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; let days = era * 146_097 + doe as i64 - 719_468;
let secs = days * 86_400 + (hh * 3_600 + mm * 60 + ss) as i64;
u64::try_from(secs).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_matches_known_iso8601_utc() {
assert_eq!(format_log_timestamp(1_781_771_180), "2026-06-18T08:26:20Z");
assert_eq!(format_log_timestamp(0), "1970-01-01T00:00:00Z");
assert_eq!(format_log_timestamp(1_709_164_800), "2024-02-29T00:00:00Z");
}
#[test]
fn human_timestamp_preserves_space_separated_shape() {
assert_eq!(format_human_timestamp(1_781_771_180), "2026-06-18 08:26:20");
assert_eq!(format_human_timestamp(0), "1970-01-01 00:00:00");
}
#[test]
fn local_date_stdout_trims_and_rejects_empty_output() {
assert_eq!(
trimmed_date_stdout(b"2026-07-02\n"),
Some("2026-07-02".to_string())
);
assert_eq!(trimmed_date_stdout(b"\n"), None);
}
#[test]
fn current_local_date_ymd_has_archive_shape() {
let date = current_local_date_ymd();
assert!(
date == "unknown-date"
|| (date.len() == 10 && date.as_bytes()[4] == b'-' && date.as_bytes()[7] == b'-'),
"unexpected archive date shape: {date:?}"
);
}
#[test]
fn parse_accepts_epoch_and_iso_and_round_trips() {
assert_eq!(parse_log_timestamp("1781771180"), Some(1_781_771_180));
assert_eq!(
parse_log_timestamp("2026-06-18T08:26:20Z"),
Some(1_781_771_180)
);
for secs in [0_u64, 1, 1_709_164_800, 1_781_915_847, 4_102_444_800] {
assert_eq!(
parse_log_timestamp(&format_log_timestamp(secs)),
Some(secs),
"round-trip failed for epoch {secs}"
);
}
assert_eq!(parse_log_timestamp("not-a-timestamp"), None);
assert_eq!(parse_log_timestamp("2026-13-01T00:00:00Z"), None);
}
#[test]
fn current_log_timestamp_is_parseable() {
let timestamp = current_log_timestamp();
assert!(
parse_log_timestamp(×tamp).is_some(),
"current timestamp should parse: {timestamp:?}"
);
}
#[test]
fn tracking_suffix_preserves_ops_log_wire_format() {
assert_eq!(
format_ops_log_tracking_suffix(Some("plan"), Some("sess-1"), Some("turn-2")),
" doc=plan session=sess-1 turn=turn-2"
);
assert_eq!(
format_ops_log_tracking_suffix(Some("plan"), None, Some("")),
" doc=plan"
);
}
#[test]
fn ops_log_line_uses_bracketed_iso_timestamp() {
assert_eq!(
format_ops_log_line(0, "event happened", " doc=plan"),
"[1970-01-01T00:00:00Z] event happened doc=plan"
);
}
}