diff --git a/CHANGELOG.md b/CHANGELOG.md index 58a036a..734bcbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes are listed here. Format follows [Keep a Changelog](https://k ## [Unreleased] +## [0.5.9] - 2026-11-18 + +### Changed + +- Dates and times are handled by jiff instead of chrono, which is no longer maintained. Your numbers don't change. +- `--since` explains itself plainly when it can't read a date. + +### Fixed + +- After **From now on**, choosing history that starts that same day now reads that day's earlier messages. + ## [0.5.8] - 2026-11-18 ### Added @@ -305,7 +316,8 @@ First release. - Per-source consent: nothing is read until you allow it, and Forget deletes a source's data - `noactually` command-line tool (`sources`, `allow`, `sync`, `stats`) -[Unreleased]: https://github.com/HTMLGuyLLC/NoActually/compare/v0.5.8...HEAD +[Unreleased]: https://github.com/HTMLGuyLLC/NoActually/compare/v0.5.9...HEAD +[0.5.9]: https://github.com/HTMLGuyLLC/NoActually/compare/v0.5.8...v0.5.9 [0.5.8]: https://github.com/HTMLGuyLLC/NoActually/compare/v0.5.7...v0.5.8 [0.5.7]: https://github.com/HTMLGuyLLC/NoActually/compare/v0.5.6...v0.5.7 [0.5.6]: https://github.com/HTMLGuyLLC/NoActually/compare/v0.5.5...v0.5.6 diff --git a/Cargo.lock b/Cargo.lock index 0f5ba3d..6b440df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2423,10 +2423,10 @@ dependencies = [ [[package]] name = "noactually-app" -version = "0.5.8" +version = "0.5.9" dependencies = [ - "chrono", "dirs 6.0.0", + "jiff", "log", "noactually-cli", "noactually-engine", @@ -2451,12 +2451,12 @@ dependencies = [ [[package]] name = "noactually-cli" -version = "0.5.8" +version = "0.5.9" dependencies = [ "anyhow", "auto-launch", - "chrono", "dirs 6.0.0", + "jiff", "log", "memchr", "noactually-engine", @@ -2469,7 +2469,7 @@ dependencies = [ [[package]] name = "noactually-engine" -version = "0.5.8" +version = "0.5.9" dependencies = [ "regex", "serde", @@ -2479,10 +2479,10 @@ dependencies = [ [[package]] name = "noactually-sources" -version = "0.5.8" +version = "0.5.9" dependencies = [ - "chrono", "dirs 6.0.0", + "jiff", "memchr", "noactually-engine", "ruzstd", @@ -2494,11 +2494,11 @@ dependencies = [ [[package]] name = "noactually-store" -version = "0.5.8" +version = "0.5.9" dependencies = [ - "chrono", "dirs 6.0.0", "getrandom 0.4.3", + "jiff", "log", "noactually-engine", "noactually-sources", diff --git a/Cargo.toml b/Cargo.toml index b1c44b5..8b65d4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["crates/engine", "crates/sources", "crates/store", "crates/cli", "app/src-tauri"] [workspace.package] -version = "0.5.8" +version = "0.5.9" edition = "2021" # Oldest Rust that builds the whole workspace, app included. CI's `msrv` job checks it. rust-version = "1.90" @@ -25,7 +25,7 @@ store = { path = "crates/store", package = "noactually-store" } regex = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" -chrono = { version = "0.4", default-features = false, features = ["std", "clock", "serde"] } +jiff = { version = "0.2.38", features = ["serde"] } rayon = "1" rusqlite = { version = "0.43", features = ["bundled", "fallible_uint"] } sha2 = "0.10" diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 3040a02..e237627 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -113,9 +113,9 @@ These are the direct runtime dependencies from the `Cargo.toml` files (versions | Crate | License | |---|---| | `tauri` 2.12.5 and the `tauri-plugin-*` crates (notification, autostart, positioner, dialog, single-instance, log, opener, updater) | Apache-2.0 OR MIT | -| `regex`, `serde`, `serde_json`, `chrono`, `anyhow`, `dirs`, `rayon`, `sha2`, `log` | MIT OR Apache-2.0 | +| `regex`, `serde`, `serde_json`, `anyhow`, `dirs`, `rayon`, `sha2`, `log` | MIT OR Apache-2.0 | | `thiserror` | MIT OR Apache-2.0 | -| `memchr` | Unlicense OR MIT | +| `memchr`, `jiff` | Unlicense OR MIT | | `ruzstd`, `rusqlite` | MIT | | `notify` | CC0-1.0 | diff --git a/app/package.json b/app/package.json index b49f5bb..1cb4bf0 100644 --- a/app/package.json +++ b/app/package.json @@ -1,7 +1,7 @@ { "name": "noactually-app", "private": true, - "version": "0.5.8", + "version": "0.5.9", "type": "module", "packageManager": "pnpm@10.32.1", "engines": { diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index 5d294cc..ee0eab5 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -29,7 +29,7 @@ cli = { path = "../../crates/cli", package = "noactually-cli" } serde.workspace = true # Used by the code `tauri::generate_context!` expands to. serde_json.workspace = true -chrono.workspace = true +jiff.workspace = true # The home folder, for the Codex files report cards add. dirs.workspace = true log.workspace = true diff --git a/app/src-tauri/src/commands.rs b/app/src-tauri/src/commands.rs index 03dad5c..cd1e4b3 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -6,7 +6,7 @@ use crate::updater::{self, UpdateStatus, Updates}; use crate::{lock, tracker::Msg, App, SyncStatus}; -use chrono::{Local, NaiveDate}; +use jiff::civil::Date; use serde::Serialize; use sources::{Kind, Source}; use std::path::Path; @@ -99,14 +99,14 @@ pub fn meta(app: State>) -> Meta { #[tauri::command(async)] pub fn stats(app: State>, filter: Filter) -> Res { - lock(&app.reader).stats(&filter, Local::now().date_naive()).map_err(err) + lock(&app.reader).stats(&filter, sources::time::today()).map_err(err) } /// The Improve tab: history for the filter, plus your goal, trophies and bests. Off the main /// thread: it reads every week of history. #[tauri::command(async)] pub fn progress(app: State>, filter: Filter) -> Res { - lock(&app.reader).progress(&filter, Local::now().date_naive()).map_err(err) + lock(&app.reader).progress(&filter, sources::time::today()).map_err(err) } /// The latest report cards under the model filter, newest first, for Improve's recent list. @@ -117,8 +117,8 @@ pub fn recent_report_cards(app: State>, filter: Filter) -> Res>, kind: GoalKind, target: i64) -> Res { - let now = chrono::Local::now(); - lock(&app.writer).set_goal(kind, target, now.date_naive(), now.timestamp_millis()).map_err(err) + let now = jiff::Zoned::now(); + lock(&app.writer).set_goal(kind, target, now.date(), now.timestamp().as_millisecond()).map_err(err) } #[tauri::command(async)] @@ -197,7 +197,7 @@ pub fn allow_source( handle: AppHandle, app: State>, id: String, - since: Option, + since: Option, from_now: Option, ) -> Res<()> { only_main(window.label())?; @@ -671,7 +671,7 @@ mod tests { assert_eq!(demo["meta"], meta, "demo.json `meta` differs from the `meta` command"); let db = store::Store::open_in_memory().unwrap(); - let stats = serde_json::to_value(db.stats(&Filter::default(), Local::now().date_naive()).unwrap()).unwrap(); + let stats = serde_json::to_value(db.stats(&Filter::default(), sources::time::today()).unwrap()).unwrap(); let keys = |v: &serde_json::Value| -> Vec { let mut k: Vec = v.as_object().unwrap().keys().cloned().collect(); k.sort(); @@ -692,8 +692,7 @@ mod tests { "demo.json `prompts.tip` keys differ" ); assert_eq!(keys(&demo["stats"]["overall"]), keys(&stats["overall"]), "demo.json `overall` keys differ"); - let progress = - serde_json::to_value(db.progress(&Filter::default(), Local::now().date_naive()).unwrap()).unwrap(); + let progress = serde_json::to_value(db.progress(&Filter::default(), sources::time::today()).unwrap()).unwrap(); assert_eq!(keys(&demo["progress"]), keys(&progress), "demo.json `progress` keys differ from `Progress`"); let week = serde_json::to_value(store::HistoryWeek::default()).unwrap(); for w in demo["progress"]["weeks"].as_array().unwrap() { @@ -730,7 +729,7 @@ mod tests { assert_eq!(keys(&shown["habit"]), keys(&trend["habit"]), "demo.json `insights.report_cards.habit` keys differ"); let recent = serde_json::to_value(store::RecentReportCard { day: String::new(), - graded_day: chrono::NaiveDate::default(), + graded_day: jiff::civil::Date::default(), source: String::new(), grade: String::new(), missing: Some(String::new()), diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index 0a0cd88..70d0679 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -76,7 +76,8 @@ pub fn apply_menu_bar(handle: &AppHandle, app: &App, enabled: bool) { #[derive(Debug, Clone, Default, Serialize)] pub struct SyncStatus { pub syncing: bool, - pub last_sync: Option>, + #[serde(with = "sources::time::json")] + pub last_sync: Option, pub last_error: Option, pub files_with_errors: usize, /// The pass in progress reads history again, so the numbers are partial until it ends. diff --git a/app/src-tauri/src/milestones.rs b/app/src-tauri/src/milestones.rs index a93fd08..0179937 100644 --- a/app/src-tauri/src/milestones.rs +++ b/app/src-tauri/src/milestones.rs @@ -4,7 +4,6 @@ //! so backfilling history never fires a pile of old milestones. use crate::{lock, App}; -use chrono::Local; use store::milestones::{crossed, goal_milestones, Milestone, Snapshot}; use store::GoalNews; use tauri::AppHandle; @@ -50,13 +49,13 @@ fn due( pub fn check(handle: &AppHandle, app: &App, quiet: Quiet) { let store = lock(&app.writer); - let Ok(stats) = store.stats(&store::Filter::default(), Local::now().date_naive()) else { return }; + let Ok(stats) = store.stats(&store::Filter::default(), sources::time::today()) else { return }; let now = Snapshot::of(&stats); let prev = store.advance_milestones(&now); // Like the goal's weeks, the report card baseline moves even on a quiet pass. - let cards = store.advance_card_milestones(Local::now().date_naive(), !quiet.goal); + let cards = store.advance_card_milestones(sources::time::today(), !quiet.goal); // Freeze the goal's finished weeks even on a quiet pass, so they're never re-judged later. - let goal = store.close_goal_weeks(Local::now().date_naive()); + let goal = store.close_goal_weeks(sources::time::today()); drop(store); let goal = goal.unwrap_or_else(|e| { log::warn!("couldn't close the goal's weeks: {e}"); @@ -107,7 +106,7 @@ mod tests { id: 1, kind: store::GoalKind::Tier { tier: Tier::Coworker }, target: 0, - start: chrono::NaiveDate::from_ymd_opt(2026, 10, 1).unwrap(), + start: jiff::civil::date(2026, 10, 1), }), } } diff --git a/app/src-tauri/src/report_cards.rs b/app/src-tauri/src/report_cards.rs index b37f922..eb14977 100644 --- a/app/src-tauri/src/report_cards.rs +++ b/app/src-tauri/src/report_cards.rs @@ -15,7 +15,7 @@ mod plugin_files; mod tests; use crate::{lock, App}; -use chrono::{DateTime, Local, NaiveDate}; +use jiff::civil::Date; use serde::{Deserialize, Serialize}; use std::fs; use std::io::{ErrorKind, Read}; @@ -422,7 +422,7 @@ fn plugin_source() -> String { /// anything. After that come a check that couldn't be made now, what an earlier check found wrong with the /// downloaded plugin (`claude::saved_problem`), and a move it left unfinished (`claude::Pending`), until /// a launch finishes it. -fn status(env: &Env, last_cards: &[(String, NaiveDate)], problem: Option) -> Status { +fn status(env: &Env, last_cards: &[(String, Date)], problem: Option) -> Status { let last = |tool: Tool| last_cards.iter().find(|(s, _)| s == tool.source()).map(|(_, day)| day.to_string()); let claude_installed = env.claude.is_some(); let codex_installed = codex::installed(env); @@ -621,7 +621,7 @@ pub async fn report_cards_status(window: tauri::Window, app: State<'_, Arc> let reader = lock(&app.reader); let state = reader.source_state(Tool::ClaudeCode.source()).ok().flatten(); let since = tips_since(&env, &shown).filter(|_| state.is_some_and(|s| s.allowed && !s.paused)); - let tip_activity = reader.tip_activity(Local::now().date_naive(), since).unwrap_or_else(|e| { + let tip_activity = reader.tip_activity(sources::time::today(), since).unwrap_or_else(|e| { log::warn!("report cards: couldn't read how tips are doing: {e}"); TipActivity::default() }); @@ -634,9 +634,9 @@ pub async fn report_cards_status(window: tauri::Window, app: State<'_, Arc> } /// The day tips were turned on, when they're on and able to reach a chat. -fn tips_since(env: &Env, shown: &Status) -> Option { +fn tips_since(env: &Env, shown: &Status) -> Option { let on = fs::metadata(env.tips_file()).and_then(|m| m.modified()).ok(); - on.filter(|_| shown.claude_code.on).map(|t| DateTime::::from(t).date_naive()) + on.filter(|_| shown.claude_code.on).and_then(|t| jiff::Timestamp::try_from(t).ok()).map(sources::time::local_day) } #[tauri::command] diff --git a/app/src-tauri/src/report_cards/codex.rs b/app/src-tauri/src/report_cards/codex.rs index da21714..b1762cb 100644 --- a/app/src-tauri/src/report_cards/codex.rs +++ b/app/src-tauri/src/report_cards/codex.rs @@ -416,7 +416,7 @@ fn read_hooks(path: &Path) -> Res> { /// Copies the hooks file as it is to `hooks.json.bak-YYYYMMDD-HHMMSS` beside it, never over an /// earlier copy (a second one in the same second gets `-1`, `-2`...). fn back_up(real: &Path) -> std::io::Result<()> { - let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S"); + let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S"); let mut src = std::fs::File::open(real)?; for n in 0.. { let name = if n == 0 { format!("hooks.json.bak-{stamp}") } else { format!("hooks.json.bak-{stamp}-{n}") }; diff --git a/app/src-tauri/src/report_cards/tests.rs b/app/src-tauri/src/report_cards/tests.rs index 8087f95..2613a7d 100644 --- a/app/src-tauri/src/report_cards/tests.rs +++ b/app/src-tauri/src/report_cards/tests.rs @@ -3083,14 +3083,14 @@ fn what_an_app_update_writes_is_written_like_a_fresh_turn_on() { assert_eq!(names, ["na"], "written through a temporary file that is gone"); } -fn day(text: &str) -> NaiveDate { +fn day(text: &str) -> Date { text.parse().unwrap() } #[test] fn the_latest_card_is_per_tool() { let lab = Lab::with_claude(); - let last: Vec<(String, NaiveDate)> = [ + let last: Vec<(String, Date)> = [ ("claude-code", "2026-10-28"), ("codex", "2026-10-20"), ("claude-cowork", "2026-10-29"), @@ -3162,7 +3162,7 @@ fn tips_since_is_the_day_they_went_on_only_while_claude_code_is_on() { }; assert_eq!(tips_since(&lab.env, &shown(true)), None, "tips are off"); set_tips(&lab.env, true).unwrap(); - assert_eq!(tips_since(&lab.env, &shown(true)), Some(Local::now().date_naive())); + assert_eq!(tips_since(&lab.env, &shown(true)), Some(sources::time::today())); assert_eq!(tips_since(&lab.env, &shown(false)), None, "the hook isn't there to give the rules"); } diff --git a/app/src-tauri/src/tracker.rs b/app/src-tauri/src/tracker.rs index aa093c9..888ef47 100644 --- a/app/src-tauri/src/tracker.rs +++ b/app/src-tauri/src/tracker.rs @@ -100,7 +100,7 @@ fn pass_started(status: &mut SyncStatus, rebuilding: bool) { } /// A pass ended well, with `errors` files skipped. -fn pass_succeeded(status: &mut SyncStatus, errors: usize, now: chrono::DateTime) { +fn pass_succeeded(status: &mut SyncStatus, errors: usize, now: jiff::Timestamp) { status.syncing = false; status.rebuilding = false; status.last_sync = Some(now); @@ -109,7 +109,7 @@ fn pass_succeeded(status: &mut SyncStatus, errors: usize, now: chrono::DateTime< } /// A pass failed: the last sync time still moves, so the window says when it last tried. -fn pass_failed(status: &mut SyncStatus, message: String, now: chrono::DateTime) { +fn pass_failed(status: &mut SyncStatus, message: String, now: jiff::Timestamp) { status.syncing = false; status.rebuilding = false; status.last_sync = Some(now); @@ -153,11 +153,11 @@ fn sync_once(handle: &AppHandle, app: &App, quiet: bool) { log::warn!("{line}"); } let changed = pass_changed(r.files_read, r.rescored, r.errors.len(), &status, rebuilding); - pass_succeeded(&mut status, r.errors.len(), chrono::Utc::now()); + pass_succeeded(&mut status, r.errors.len(), jiff::Timestamp::now()); drop(status); if r.rescored { // Kept so the window can say so after the popup is gone, or if popups are off. - let when = chrono::Utc::now().to_rfc3339(); + let when = sources::time::rfc3339(jiff::Timestamp::now()); if let Err(e) = lock(&app.writer).set_setting(crate::RESCORED_NOTICE_KEY, &when) { log::warn!("couldn't note that scores were rebuilt: {e}"); } @@ -172,7 +172,7 @@ fn sync_once(handle: &AppHandle, app: &App, quiet: bool) { } Err(e) => { log::error!("sync failed: {}", shorten_home_in(&format!("{e:#}"), std::env::home_dir().as_deref())); - pass_failed(&mut status, e.to_string(), chrono::Utc::now()); + pass_failed(&mut status, e.to_string(), jiff::Timestamp::now()); drop(status); let _ = handle.emit("sync-failed", e.to_string()); } @@ -181,7 +181,7 @@ fn sync_once(handle: &AppHandle, app: &App, quiet: bool) { /// Hovering the menu bar icon shows the score without opening anything. fn update_tray(handle: &AppHandle, app: &App) { - let Ok(o) = lock(&app.reader).overall(chrono::Local::now().date_naive()) else { return }; + let Ok(o) = lock(&app.reader).overall(sources::time::today()) else { return }; if let Some(tray) = handle.tray_by_id("tray") { let tip = match (o.score, o.tier) { (Some(score), Some(tier)) => format!("No, Actually... · {} · score {score}", tier.name()), @@ -269,10 +269,9 @@ pub fn spawn(handle: AppHandle, app: Arc, tx: mpsc::Sender, rx: mpsc:: #[cfg(test)] mod tests { use super::*; - use chrono::{TimeZone, Utc}; - fn at() -> chrono::DateTime { - Utc.with_ymd_and_hms(2026, 11, 1, 12, 0, 0).unwrap() + fn at() -> jiff::Timestamp { + "2026-11-01T12:00:00Z".parse().unwrap() } /// A stand-in for the tracking thread, which answers `Stop` after `pass`. diff --git a/app/src-tauri/src/updater.rs b/app/src-tauri/src/updater.rs index d245c3d..7ea1397 100644 --- a/app/src-tauri/src/updater.rs +++ b/app/src-tauri/src/updater.rs @@ -67,7 +67,8 @@ pub struct UpdateStatus { pub installing: bool, /// The newer version on offer, if any. pub available: Option, - pub last_check: Option>, + #[serde(with = "sources::time::json")] + pub last_check: Option, pub last_error: Option, } @@ -152,7 +153,7 @@ fn check(handle: &AppHandle, app: &App, updates: &Updates) { { let mut status = lock(&updates.status); status.checking = false; - status.last_check = Some(chrono::Utc::now()); + status.last_check = Some(jiff::Timestamp::now()); match found { Ok(update) => { status.last_error = None; diff --git a/app/src-tauri/tauri.conf.json b/app/src-tauri/tauri.conf.json index fc505a2..6de6c29 100644 --- a/app/src-tauri/tauri.conf.json +++ b/app/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "No, Actually...", - "version": "0.5.8", + "version": "0.5.9", "identifier": "app.noactually", "build": { "beforeDevCommand": "pnpm dev", diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index f3fa1d6..c23aa22 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -26,7 +26,7 @@ path = "src/main.rs" engine.workspace = true sources.workspace = true store.workspace = true -chrono.workspace = true +jiff.workspace = true serde.workspace = true serde_json.workspace = true anyhow.workspace = true diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index e5f1748..b079501 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -16,7 +16,7 @@ use helper::{is_helper, is_helper_command}; pub use helper::{QUIET_FILE, TIPS_FILE, TIPS_OFF_FILE}; use anyhow::{anyhow, bail, Context, Result}; -use chrono::{Local, NaiveDate}; +use jiff::civil::Date; use std::ffi::OsString; use std::io::{BufRead, IsTerminal, Write}; use std::path::PathBuf; @@ -63,7 +63,7 @@ enum Parsed { #[derive(Debug, PartialEq)] enum Command { Sources { json: bool }, - Allow { id: String, since: Option, from_now: bool }, + Allow { id: String, since: Option, from_now: bool }, Pause { id: String }, Resume { id: String }, Revoke { id: String }, @@ -128,6 +128,11 @@ fn no_positional(a: Args<'_>) -> Result> { } /// Parses the arguments after the program name. +/// `--since`, as a date. +fn since(a: &Args<'_>) -> Result> { + a.value("--since").map(|d| d.parse().map_err(|_| anyhow!("--since wants a date like 2026-10-01"))).transpose() +} + fn parse_args(args: &[String]) -> Result { let Some((cmd, rest)) = args.split_first() else { return Ok(Parsed::Help) }; // Asking for help must never run anything. `check` takes the whole rest as its prompt, so only @@ -144,8 +149,7 @@ fn parse_args(args: &[String]) -> Result { "sync" => Command::Sync { json: no_positional(Args::split(rest, &[], &["--json"])?)?.has("--json") }, "allow" => { let a = Args::split(rest, &["--since"], &["--from-now"])?; - let since = - a.value("--since").map(|d| d.parse::()).transpose().context("--since wants YYYY-MM-DD")?; + let since = since(&a)?; let from_now = a.has("--from-now"); if since.is_some() && from_now { bail!("use --since or --from-now, not both"); @@ -169,8 +173,7 @@ fn parse_args(args: &[String]) -> Result { &["--source", "--provider", "--family", "--version", "--since"], &["--json", "--report-cards"], )?; - let since = - a.value("--since").map(|d| d.parse::()).transpose().context("--since wants YYYY-MM-DD")?; + let since = since(&a)?; let filter = Filter { source: a.value("--source"), provider: a.value("--provider"), @@ -411,7 +414,7 @@ fn execute(cmd: Command, store: &mut Store, all: &[Box]) -> } Command::Stats { filter, json, report_cards: true } => print_report_cards(store, all, &filter, json)?, Command::Stats { filter, json, report_cards: false } => { - let s = store.stats(&filter, Local::now().date_naive())?; + let s = store.stats(&filter, sources::time::today())?; if json { println!("{}", serde_json::to_string_pretty(&s)?); } else { @@ -455,7 +458,7 @@ fn allowed_only(store: &Store, id: &str, what: &str) -> Result<()> { fn print_report_cards(store: &Store, all: &[Box], filter: &Filter, json: bool) -> Result<()> { let habits = store::meta(all).habits; let totals = store.report_card_totals(filter)?; - let (tip_trend, top_tip) = store.tip_summary(filter, Local::now().date_naive())?; + let (tip_trend, top_tip) = store.tip_summary(filter, sources::time::today())?; let left_out = all.iter().map(|src| store.report_cards_left_out(src.id())).sum::>()?; let s = report_cards::Summary { tip_trend, @@ -505,7 +508,7 @@ fn print_sources(store: &Store, all: &[Box], json: bool) -> Ok(()) } -fn print_card(s: &store::Stats, since: Option) { +fn print_card(s: &store::Stats, since: Option) { if s.messages == 0 { println!("No messages yet. Allow a source and run `noactually sync`."); return; @@ -546,13 +549,13 @@ fn print_card(s: &store::Stats, since: Option) { } /// Who corrected whom across all the stats cover: all time, or from `--since`. -fn totals_line(corrections: i64, humbled: i64, since: Option) -> String { +fn totals_line(corrections: i64, humbled: i64, since: Option) -> String { let span = since.map_or("All time".to_string(), |d| window_label(Some(d))); format!(" {span:<15} you corrected it {corrections} · it corrected you {humbled}") } /// The span the score looks at: from `--since` when given, else the last [`engine::WINDOW_DAYS`] days. -fn window_label(since: Option) -> String { +fn window_label(since: Option) -> String { since.map_or_else(|| format!("in the last {} days", engine::WINDOW_DAYS), |d| format!("since {d}")) } @@ -892,7 +895,7 @@ mod tests { assert!(err("import codex").starts_with("missing path")); assert!(err("pause").starts_with("missing source")); assert!(err("sync --jsno").starts_with("unknown option '--jsno'")); - assert_eq!(err("allow codex --since yesterday"), "--since wants YYYY-MM-DD: input contains invalid characters"); + assert_eq!(err("allow codex --since yesterday"), "--since wants a date like 2026-10-01"); assert_eq!(err("allow codex --since 2026-10-01 --from-now"), "use --since or --from-now, not both"); assert_eq!(err("stats --source"), "--source needs a value"); assert!(err("stats --sorce codex").starts_with("unknown option '--sorce'")); diff --git a/crates/cli/tests/helper.rs b/crates/cli/tests/helper.rs index a796496..3bbdef7 100644 --- a/crates/cli/tests/helper.rs +++ b/crates/cli/tests/helper.rs @@ -356,7 +356,7 @@ fn stats_report_cards_reports_a_card_from_a_synced_chat_as_text_and_json() { assert!(!text.contains("token"), "no counts of tokens in the text: {text}"); assert!(text.contains(" Most missed Finish line (1 of 1 task)\n"), "{text}"); // The day is shown in local time, so it moves with the zone (the chat is at 10:00 UTC). - let day = chrono::DateTime::parse_from_rfc3339(&at(0)).unwrap().with_timezone(&chrono::Local).date_naive(); + let day = sources::time::local_day(sources::time::parse(&at(0)).unwrap()); assert!( text.contains(&format!( "\n Latest\n {day} claude-code B left out: finish line about 2 extra minutes · about $0.07 at pay-as-you-go prices" diff --git a/crates/sources/Cargo.toml b/crates/sources/Cargo.toml index d40cf17..551eb39 100644 --- a/crates/sources/Cargo.toml +++ b/crates/sources/Cargo.toml @@ -24,7 +24,7 @@ test-support = [] engine.workspace = true serde.workspace = true serde_json.workspace = true -chrono.workspace = true +jiff.workspace = true thiserror.workspace = true memchr.workspace = true ruzstd.workspace = true diff --git a/crates/sources/src/claude_code.rs b/crates/sources/src/claude_code.rs index 8bd8c7f..918da14 100644 --- a/crates/sources/src/claude_code.rs +++ b/crates/sources/src/claude_code.rs @@ -6,8 +6,8 @@ use crate::{ contains, data_dir, home, pair_from, parse_ts, walk, ChatView, Error, Event, FileScan, Kind, Result, RulesSeen, Source, }; -use chrono::{DateTime, Utc}; use engine::{head_chars, is_tip_rules, is_tip_stop, Usage}; +use jiff::Timestamp; use serde::Deserialize; use std::collections::HashMap; use std::ffi::OsString; @@ -265,7 +265,7 @@ struct Read { /// What a reply cost, with its message id (only with `usage`). sample: Option<(Option, Sample)>, /// When the chat was given the tip rules. - rules: Option>, + rules: Option, /// The chat was told to stop giving tips. stopped: bool, /// The line looked wanted but wasn't JSON. @@ -326,7 +326,7 @@ fn hook_said(line: &Line, is_it: fn(&str) -> bool) -> Option { } /// When this record gave the chat the tip rules, if it did. -fn rules_at(line: &Line) -> Option> { +fn rules_at(line: &Line) -> Option { hook_said(line, is_tip_rules)?.then(|| line.timestamp.as_deref().and_then(parse_ts)).flatten() } @@ -375,7 +375,7 @@ fn sample(line: &Line, pos: u64) -> Option<(Option, Sample)> { } /// A person's message, unless it is injected context or only a pasted block. -fn human(text: String, ts: DateTime, line: &Line, pos: u64) -> Option { +fn human(text: String, ts: Timestamp, line: &Line, pos: u64) -> Option { if is_noise(&text) { return None; } @@ -784,14 +784,19 @@ mod tests { let v = view_str(&body); let scan = scan_str(&body, true); for (p, st) in v.prompts.iter().zip(&scan.turns) { - let want = - engine::message_key("claude-code", "abc", st.key.as_deref(), &st.ts.to_rfc3339(), &st.turn.human); + let want = engine::message_key( + "claude-code", + "abc", + st.key.as_deref(), + &crate::time::rfc3339(st.ts), + &st.turn.human, + ); assert_eq!(p.key, want); } assert_eq!(v.prompts.len(), 2, "the trailing unanswered message is included"); assert_eq!( v.prompts[1].key, - engine::message_key("claude-code", "abc", None, &v.prompts[1].ts.to_rfc3339(), "second, no uuid") + engine::message_key("claude-code", "abc", None, &crate::time::rfc3339(v.prompts[1].ts), "second, no uuid") ); } diff --git a/crates/sources/src/codex.rs b/crates/sources/src/codex.rs index 165e637..cbfc40e 100644 --- a/crates/sources/src/codex.rs +++ b/crates/sources/src/codex.rs @@ -576,8 +576,13 @@ mod tests { assert_eq!(v.prompts[1].seconds, 120); let scan = Codex.scan(&p, 0, true).unwrap(); for (pv, st) in v.prompts.iter().zip(&scan.turns) { - let want = - engine::message_key("codex", &st.session, st.key.as_deref(), &st.ts.to_rfc3339(), &st.turn.human); + let want = engine::message_key( + "codex", + &st.session, + st.key.as_deref(), + &crate::time::rfc3339(st.ts), + &st.turn.human, + ); assert_eq!(pv.key, want); } } diff --git a/crates/sources/src/export.rs b/crates/sources/src/export.rs index 7075d8c..b04977a 100644 --- a/crates/sources/src/export.rs +++ b/crates/sources/src/export.rs @@ -88,7 +88,7 @@ mod tests { } fn events(c: &Value) -> Vec { - let ts = chrono::DateTime::from_timestamp(1, 0).unwrap(); + let ts = jiff::Timestamp::from_second(1).unwrap(); let text = |k: &str| c[k].as_str().unwrap_or_default().to_string(); vec![ Event::Ai { text: text("ai"), model: None, ts: Some(ts), key: None, pos: 0 }, diff --git a/crates/sources/src/lib.rs b/crates/sources/src/lib.rs index becfdd4..4df4f60 100644 --- a/crates/sources/src/lib.rs +++ b/crates/sources/src/lib.rs @@ -19,13 +19,14 @@ mod jsonl; mod pair; #[cfg(any(test, feature = "test-support"))] pub mod testing; +pub mod time; mod view; pub use claude_code::has_tip_rules; pub use pair::{pair, pair_from, Event}; pub use view::{ChatView, PromptView, Sealed, SealedTask}; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use std::path::{Path, PathBuf}; /// What can go wrong reading a source. File errors always carry the path. @@ -88,7 +89,7 @@ pub struct SourceTurn { /// The chat this message belongs to, as the tool names it. pub session: String, /// When the person sent it. - pub ts: DateTime, + pub ts: Timestamp, /// Stable id of the human message, used to skip copies (resumed or forked sessions). /// /// Each adapter keeps the shape it shipped with: Claude Code uses the bare record uuid, Codex @@ -132,7 +133,7 @@ pub struct CardSeen { /// The tool's own id for the reply, if it gave one. pub key: Option, /// When the reply was written, if the tool said. - pub ts: Option>, + pub ts: Option, /// Where the reply starts in the file. pub pos: u64, /// The text between the fences, as written. @@ -147,7 +148,7 @@ pub struct TipSeen { /// The tool's own id for the reply, if it gave one. pub key: Option, /// When the reply was written. - pub ts: DateTime, + pub ts: Timestamp, /// Where the reply starts in the file. pub pos: u64, /// The raw model id, if the tool recorded one. @@ -162,7 +163,7 @@ pub struct RulesSeen { /// The chat, as the tool names it. pub session: String, /// When it got them. - pub ts: DateTime, + pub ts: Timestamp, } /// How a person asks Codex for a report card. Codex's skill is `grade-me`, called with a `$`. @@ -276,12 +277,12 @@ pub(crate) fn file_name(p: &Path) -> std::borrow::Cow<'_, str> { p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default() } -pub(crate) fn parse_ts(s: &str) -> Option> { - DateTime::parse_from_rfc3339(s).ok().map(|d| d.with_timezone(&Utc)) +pub(crate) fn parse_ts(s: &str) -> Option { + crate::time::parse(s) } -pub(crate) fn epoch_ts(secs: f64) -> Option> { - DateTime::from_timestamp_millis((secs * 1000.0) as i64) +pub(crate) fn epoch_ts(secs: f64) -> Option { + Timestamp::from_millisecond((secs * 1000.0) as i64).ok() } #[cfg(test)] diff --git a/crates/sources/src/pair.rs b/crates/sources/src/pair.rs index c8fb5dc..2c3da43 100644 --- a/crates/sources/src/pair.rs +++ b/crates/sources/src/pair.rs @@ -1,8 +1,8 @@ //! Shared pairing: a stream of human / AI events becomes turns, plus a safe resume point. use crate::{CardSeen, FileScan, SourceTurn, TipSeen}; -use chrono::{DateTime, Utc}; use engine::{find_cards, has_card, head_chars, parse_card, parse_tip, strip_tip, tail_chars, AiMsg, Turn}; +use jiff::Timestamp; const KEEP_PREV: usize = 600; // chars from the end of the reply you answered const KEEP_NEXT: usize = 2000; // chars from the start of the reply after you @@ -16,7 +16,7 @@ pub enum Event { /// The message. text: String, /// When it was sent. - ts: DateTime, + ts: Timestamp, /// The tool's id for it, for dedupe (see [`SourceTurn::key`]). key: Option, /// Where it starts. @@ -29,7 +29,7 @@ pub enum Event { /// The raw model id, if the tool recorded one. model: Option, /// When it was written, if the tool recorded that. - ts: Option>, + ts: Option, /// The tool's id for it (see [`CardSeen::key`]). key: Option, /// Where it starts. @@ -209,11 +209,11 @@ mod tests { thread_local! { /// One time for every reply here, so a re-read reply compares equal. - static TS: DateTime = Utc::now(); + static TS: Timestamp = Timestamp::now(); } fn h(text: &str, pos: u64) -> Event { - Event::Human { text: text.into(), ts: Utc::now(), key: Some(text.into()), pos } + Event::Human { text: text.into(), ts: Timestamp::now(), key: Some(text.into()), pos } } fn a(text: &str, pos: u64) -> Event { Event::Ai { text: text.into(), model: Some("m".into()), ts: Some(TS.with(|t| *t)), key: None, pos } @@ -259,7 +259,7 @@ mod tests { #[test] fn a_tip_with_no_time_or_on_a_card_is_left_out() { - let at = Some(Utc::now()); + let at = Some(Timestamp::now()); let timed = |text: &str, ts| Event::Ai { text: text.into(), model: None, ts, key: None, pos: 10 }; let block = r#"{"v":1,"k":"9c41e0aa","tasks":[{"at":"7f3a9c21","to":"e44a1b90"}]}"#; let card = format!("Report card: A\n\n```noactually\n{block}\n```\n\n{TIP}"); diff --git a/crates/sources/src/time.rs b/crates/sources/src/time.rs new file mode 100644 index 0000000..93764f4 --- /dev/null +++ b/crates/sources/src/time.rs @@ -0,0 +1,145 @@ +//! Dates and times, written the way the database and the app have always written them. +//! +//! Stored times and message keys hash [`rfc3339`]'s text, so its format must never change: a +//! different string for the same moment would count every old message again. + +use jiff::civil::Date; +use jiff::tz::TimeZone; +use jiff::{Timestamp, Zoned}; + +/// Today's date where the computer is. +pub fn today() -> Date { + Zoned::now().date() +} + +/// The date `ts` fell on where the computer is. +pub fn local_day(ts: Timestamp) -> Date { + ts.to_zoned(TimeZone::system()).date() +} + +/// The time zone the computer is in, to look up many times with [`Timestamp::to_zoned`]. +pub fn local_zone() -> TimeZone { + TimeZone::system() +} + +/// Reads a time that names its offset, like `2026-10-20T10:00:00.123Z` or `…+02:00`. +pub fn parse(s: &str) -> Option { + s.parse().ok() +} + +/// `2026-10-20T10:00:00.123+00:00`: UTC as `+00:00`, with 0, 3, 6 or 9 digits after the seconds, +/// whichever is the fewest that keeps every digit. What's stored, and what message keys hash. +pub fn rfc3339(ts: Timestamp) -> String { + stamp(ts, Fraction::Fewest, "+00:00") +} + +/// `2026-10-20T10:00:00.123Z`: always 3 digits, so stored times sort as text. +pub fn rfc3339_millis(ts: Timestamp) -> String { + stamp(ts, Fraction::Millis, "Z") +} + +/// Like [`rfc3339`] but ending in `Z`: what the app is sent. +pub fn rfc3339_z(ts: Timestamp) -> String { + stamp(ts, Fraction::Fewest, "Z") +} + +enum Fraction { + Fewest, + Millis, +} + +fn stamp(ts: Timestamp, fraction: Fraction, utc: &str) -> String { + let t = ts.to_zoned(TimeZone::UTC).datetime(); + let ns = t.subsec_nanosecond(); + let frac = match fraction { + Fraction::Millis => format!(".{:03}", ns / 1_000_000), + Fraction::Fewest if ns == 0 => String::new(), + Fraction::Fewest if ns % 1_000_000 == 0 => format!(".{:03}", ns / 1_000_000), + Fraction::Fewest if ns % 1_000 == 0 => format!(".{:06}", ns / 1_000), + Fraction::Fewest => format!(".{ns:09}"), + }; + format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{frac}{utc}", + t.year(), + t.month(), + t.day(), + t.hour(), + t.minute(), + t.second() + ) +} + +/// `#[serde(with = "sources::time::json")]` for an `Option`, sent as [`rfc3339_z`]. +pub mod json { + use jiff::Timestamp; + use serde::{de::Error, Deserialize, Deserializer, Serializer}; + + /// Writes the time as [`super::rfc3339_z`], or null. + pub fn serialize(ts: &Option, s: S) -> Result { + match ts { + Some(ts) => s.serialize_str(&super::rfc3339_z(*ts)), + None => s.serialize_none(), + } + } + + /// Reads a time with an offset, or null. + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + Option::::deserialize(d)? + .map(|s| super::parse(&s).ok_or_else(|| D::Error::custom(format!("not a time: {s}")))) + .transpose() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(s: &str) -> Timestamp { + s.parse().unwrap() + } + + #[test] + fn stored_times_keep_the_format_message_keys_were_built_from() { + // These strings are what chrono wrote before the move to jiff. Changing them would change + // every message key, and old messages would count again. + let cases = [ + ("2026-10-20T10:00:00Z", "2026-10-20T10:00:00+00:00"), + ("2026-10-20T10:00:00.5Z", "2026-10-20T10:00:00.500+00:00"), + ("2026-10-20T10:00:00.123Z", "2026-10-20T10:00:00.123+00:00"), + ("2026-10-20T10:00:00.1234Z", "2026-10-20T10:00:00.123400+00:00"), + ("2026-10-20T10:00:00.123456Z", "2026-10-20T10:00:00.123456+00:00"), + ("2026-10-20T10:00:00.1234567Z", "2026-10-20T10:00:00.123456700+00:00"), + ("2026-10-20T10:00:00.000000001Z", "2026-10-20T10:00:00.000000001+00:00"), + ("2026-10-20T12:30:00+02:30", "2026-10-20T10:00:00+00:00"), + ("1969-12-31T23:59:59.5Z", "1969-12-31T23:59:59.500+00:00"), + ]; + for (input, stored) in cases { + assert_eq!(rfc3339(at(input)), stored, "{input}"); + } + assert_eq!(rfc3339_millis(at("2026-10-20T10:00:00Z")), "2026-10-20T10:00:00.000Z"); + assert_eq!(rfc3339_millis(at("2026-10-20T10:00:00.9999Z")), "2026-10-20T10:00:00.999Z"); + assert_eq!(rfc3339_z(at("2026-10-20T10:00:00.25Z")), "2026-10-20T10:00:00.250Z"); + } + + #[test] + fn times_without_an_offset_are_refused() { + assert_eq!(parse("2026-10-20T10:00:00Z"), Some(at("2026-10-20T10:00:00Z"))); + assert_eq!(parse("2026-10-20T10:00:00"), None); + assert_eq!(parse("yesterday"), None); + } + + #[test] + fn times_go_to_the_app_and_back() { + #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)] + struct S { + #[serde(with = "json")] + t: Option, + } + let s = S { t: Some(at("2026-10-20T10:00:00.5Z")) }; + let text = serde_json::to_string(&s).unwrap(); + assert_eq!(text, r#"{"t":"2026-10-20T10:00:00.500Z"}"#); + assert_eq!(serde_json::from_str::(&text).unwrap(), s); + assert_eq!(serde_json::to_string(&S { t: None }).unwrap(), r#"{"t":null}"#); + assert!(serde_json::from_str::(r#"{"t":"soon"}"#).is_err()); + } +} diff --git a/crates/sources/src/view.rs b/crates/sources/src/view.rs index fae2c1e..17da66f 100644 --- a/crates/sources/src/view.rs +++ b/crates/sources/src/view.rs @@ -2,11 +2,11 @@ use crate::pair::holds_card; use crate::{pair, CardSeen, Event}; -use chrono::{DateTime, Utc}; use engine::{ classify, is_signoff, message_key, parse_card, read_prompt, seal, short_id, AiMsg, CardError, CardTask, Prompt, Turn, Usage, }; +use jiff::Timestamp; use std::collections::{BTreeMap, HashMap}; use std::slice::SliceIndex; @@ -127,7 +127,7 @@ pub struct PromptView { /// The short form of `key` a report card names it by. pub id: String, /// When it was sent. - pub ts: DateTime, + pub ts: Timestamp, /// The whole message. pub text: String, /// The message is only a sign-off ("thanks", "lgtm"): it closes a task and is not a round of work. @@ -149,7 +149,7 @@ pub struct PromptView { #[derive(Debug, Clone)] pub(crate) struct Sample { pub pos: u64, - pub ts: Option>, + pub ts: Option, pub model: Option, /// Tokens used here alone, not a running total. pub usage: Usage, @@ -160,7 +160,7 @@ pub(crate) struct Sample { #[derive(Debug, Clone)] pub(crate) struct Cut { pub pos: u64, - pub ts: Option>, + pub ts: Option, } /// What one round gathers: tokens, the answering model and the time of its last record. @@ -168,11 +168,11 @@ pub(crate) struct Cut { struct Round { usage: Usage, model: Option, - last: Option>, + last: Option, } impl Round { - fn see(&mut self, ts: Option>, model: Option<&String>) { + fn see(&mut self, ts: Option, model: Option<&String>) { self.last = self.last.max(ts); if let Some(m) = model.filter(|m| engine::is_real_model(m)) { self.model = Some(m.clone()); @@ -240,7 +240,7 @@ pub(crate) fn build( let mut has_task = mid_chat; let mut prompts = Vec::with_capacity(scan.turns.len()); for (i, st) in scan.turns.iter().enumerate() { - let key = message_key(source, &st.session, st.key.as_deref(), &st.ts.to_rfc3339(), &st.turn.human); + let key = message_key(source, &st.session, st.key.as_deref(), &crate::time::rfc3339(st.ts), &st.turn.human); let after_reply; let turn = if mid_chat && i == 0 && st.turn.prev_ai.is_none() { after_reply = Turn { prev_ai: Some(AiMsg::default()), ..st.turn.clone() }; @@ -256,7 +256,7 @@ pub(crate) fn build( None => scan.turns.get(i + 1).map(|n| n.ts).or(r.last), }; let stop = stop.unwrap_or(st.ts); - let seconds = (stop - st.ts).num_seconds().clamp(0, MAX_SECONDS); + let seconds = stop.duration_since(st.ts).as_secs().clamp(0, MAX_SECONDS); prompts.push(PromptView { id: short_id(&key).to_string(), key, diff --git a/crates/store/Cargo.toml b/crates/store/Cargo.toml index 6f77112..814ffd6 100644 --- a/crates/store/Cargo.toml +++ b/crates/store/Cargo.toml @@ -22,7 +22,7 @@ sources.workspace = true rusqlite.workspace = true serde.workspace = true serde_json.workspace = true -chrono.workspace = true +jiff.workspace = true rayon.workspace = true thiserror.workspace = true dirs.workspace = true diff --git a/crates/store/src/card_tests.rs b/crates/store/src/card_tests.rs index 305419e..dfa6398 100644 --- a/crates/store/src/card_tests.rs +++ b/crates/store/src/card_tests.rs @@ -4,10 +4,11 @@ use super::*; use crate::milestones::straight_as; use crate::rebuild::SCORE_TABLES; -use chrono::{NaiveDate, SecondsFormat, TimeZone, Utc}; use engine::{habit_bit, seal, Usage}; +use jiff::civil::Date; use serde_json::{json, Value}; use sources::testing::{cc_reply_with_usage, cc_user, line, set_mtime_ago}; +use sources::time::today; use sources::{ChatView, Kind, Source}; use std::io::Write; use std::path::PathBuf; @@ -20,11 +21,12 @@ use std::time::Duration as StdDuration; /// `m` minutes past local noon on October `day` 2026 (the 5th is a Monday), as a UTC time. Noon /// local is the same day in every timezone, which a fixed UTC hour isn't. fn at(day: u32, m: u32) -> String { - chrono::Local - .with_ymd_and_hms(2026, 10, day, 12, m, 0) + jiff::civil::date(2026, 10, day as i8) + .at(12, m as i8, 0, 0) + .to_zoned(sources::time::local_zone()) .unwrap() - .with_timezone(&Utc) - .to_rfc3339_opts(SecondsFormat::Secs, true) + .timestamp() + .to_string() } /// `at`, as the store keeps it. @@ -965,7 +967,7 @@ fn the_view_and_the_engine_agree_on_what_overlaps() { // ---- the numbers the Improve tab reads --------------------------------------------------------- -fn d(s: &str) -> NaiveDate { +fn d(s: &str) -> Date { s.parse().unwrap() } @@ -1881,13 +1883,13 @@ fn a_tip_where_the_ai_had_to_ask_is_kept_as_zero() { #[test] fn deleting_the_history_counts_tips_and_isnt_read_as_blocked_chats() { let s = Store::open_in_memory().unwrap(); - let today = chrono::Local::now().date_naive(); - let yesterday = today.pred_opt().unwrap(); + let today = today(); + let yesterday = today.yesterday().unwrap(); for id in ["a", "b", "c"] { seed_chat(&s, id, "claude-code", &yesterday.to_string(), &yesterday.to_string(), true); } seed_tip(&s, 0, "finish"); assert_eq!(s.delete_report_cards().unwrap(), 1, "tips count"); - let on = yesterday.pred_opt().unwrap(); + let on = yesterday.yesterday().ok().unwrap(); assert!(!s.tip_activity(today, Some(on)).unwrap().blocked, "their rules were deleted, not missing"); } diff --git a/crates/store/src/cards.rs b/crates/store/src/cards.rs index a13467e..70a564d 100644 --- a/crates/store/src/cards.rs +++ b/crates/store/src/cards.rs @@ -4,9 +4,10 @@ use crate::stats::View; use crate::{hash, put_setting, Result, SourceState, Store, NO_MODEL}; -use chrono::{DateTime, Local, NaiveDate, SecondsFormat, Utc}; use engine::{normalize_model, price, tasks_overlap, LetterGrade, Model, Usage}; +use jiff::{civil::Date, Timestamp}; use rusqlite::{params, Connection}; +use sources::time; use sources::{CardSeen, ChatView, SealedTask}; use std::collections::BTreeMap; @@ -25,14 +26,14 @@ pub(crate) const CLEARED_KEY: &str = "report_cards.cleared"; pub(crate) type Tokens = BTreeMap; /// A time as stored. A fixed shape, so comparing the text compares the times. -pub(crate) fn ts_str(ts: DateTime) -> String { - ts.to_rfc3339_opts(SecondsFormat::Millis, true) +pub(crate) fn ts_str(ts: Timestamp) -> String { + time::rfc3339_millis(ts) } /// The local day of a stored time. -pub(crate) fn local_day(stored: &str) -> Option { - let ts: DateTime = stored.parse().ok()?; - Some(ts.with_timezone(&Local).date_naive()) +pub(crate) fn local_day(stored: &str) -> Option { + let ts: Timestamp = stored.parse().ok()?; + Some(time::local_day(ts)) } /// One graded task, as stored. @@ -204,7 +205,7 @@ fn row(state: &SourceState, view: &ChatView, block: &Block, st: &SealedTask) -> source: source.to_string(), session: hash(&[source, &view.session]), first: first.key.clone(), - day: first.ts.with_timezone(&Local).date_naive().to_string(), + day: time::local_day(first.ts).to_string(), start_ts: ts_str(first.ts), end_ts: ts_str(prompts[to].ts), provider: provider.to_string(), @@ -372,7 +373,7 @@ impl Store { tx.execute("DELETE FROM kept_tips", [])?; tx.execute("DELETE FROM kept_tip_chats", [])?; clear_left_out(&tx, None)?; - put_setting(&tx, CLEARED_KEY, &ts_str(Utc::now()))?; + put_setting(&tx, CLEARED_KEY, &ts_str(Timestamp::now()))?; tx.commit()?; self.flush_deleted()?; Ok(n + tips) diff --git a/crates/store/src/consent.rs b/crates/store/src/consent.rs index 3704a60..b976158 100644 --- a/crates/store/src/consent.rs +++ b/crates/store/src/consent.rs @@ -5,9 +5,10 @@ use crate::cards::clear_left_out; use crate::ingest::{source_files, upsert_file, FileMeta, Pass}; use crate::rebuild::{KEPT_TABLES, SCORE_TABLES}; use crate::{files, Result, Store}; -use chrono::{DateTime, Local, NaiveDate, Utc}; +use jiff::{civil::Date, Timestamp}; use rusqlite::params; use serde::{Deserialize, Serialize}; +use sources::time::{local_day, rfc3339}; use sources::Source; use std::path::{Path, PathBuf}; @@ -38,12 +39,12 @@ pub struct SourceState { /// Allowed, but not read for now. pub paused: bool, /// Ignore history before this day. `None` means everything. - pub backfill_since: Option, + pub backfill_since: Option, /// When the user allowed it. - pub granted_at: Option>, + pub granted_at: Option, /// "From now on": ignore every message written before this moment. #[serde(default)] - pub start_after: Option>, + pub start_after: Option, /// Extra files or folders the user pointed this source at (exports live here). pub paths: Vec, } @@ -64,8 +65,8 @@ impl SourceState { /// False for a message this source's consent says to skip (before the backfill day, or /// before "From now on"). - pub(crate) fn wants(&self, ts: DateTime) -> bool { - let day = ts.with_timezone(&Local).date_naive(); + pub(crate) fn wants(&self, ts: Timestamp) -> bool { + let day = local_day(ts); !(self.backfill_since.is_some_and(|s| day < s) || self.start_after.is_some_and(|t| ts < t)) } } @@ -96,15 +97,16 @@ impl Store { } /// The user allowed reading this source. Nothing is read before this. - pub fn allow(&self, id: &str, backfill_since: Option) -> Result<()> { + pub fn allow(&self, id: &str, backfill_since: Option) -> Result<()> { // Reaching further back than before (say "All history" after "From now on") can't use // the old checkpoints: they sit at the end of files whose older messages were skipped. // The `seen` keys keep re-read messages from counting twice. if let Some(prev) = self.source_state(id)? { - let before = prev.start_after.map(|t| t.date_naive()).or(prev.backfill_since); - let reaches_back = match (backfill_since, before) { - (None, Some(_)) => true, - (Some(new), Some(old)) => new < old, + let reaches_back = match (backfill_since, prev.start_after, prev.backfill_since) { + (None, Some(_), _) | (None, None, Some(_)) => true, + // "From now on" skipped the earlier part of its own day too. + (Some(new), Some(at), _) => new <= local_day(at), + (Some(new), None, Some(old)) => new < old, _ => false, }; if reaches_back { @@ -115,7 +117,7 @@ impl Store { "INSERT INTO sources (id, allowed, paused, backfill_since, granted_at, paths) VALUES (?1, 1, 0, ?2, ?3, '[]') ON CONFLICT(id) DO UPDATE SET allowed = 1, paused = 0, backfill_since = excluded.backfill_since, granted_at = excluded.granted_at, start_after = NULL", - params![id, backfill_since.map(|d| d.to_string()), Utc::now().to_rfc3339()], + params![id, backfill_since.map(|d| d.to_string()), rfc3339(Timestamp::now())], )?; self.mark_stopped(id, false); Ok(()) @@ -159,8 +161,10 @@ impl Store { /// written after this moment count. Returns how many files were marked. pub fn start_from_now(&mut self, src: &dyn Source) -> Result { // The cutoff is what guarantees it; the checkpoints just save re-reading old bytes. - self.conn - .execute("UPDATE sources SET start_after = ?2 WHERE id = ?1", params![src.id(), Utc::now().to_rfc3339()])?; + self.conn.execute( + "UPDATE sources SET start_after = ?2 WHERE id = ?1", + params![src.id(), rfc3339(Timestamp::now())], + )?; let extra = self.source_state(src.id())?.map(|s| s.paths).unwrap_or_default(); let tx = self.conn.transaction()?; let mut marked = 0; diff --git a/crates/store/src/goals.rs b/crates/store/src/goals.rs index 151ef59..69c72b4 100644 --- a/crates/store/src/goals.rs +++ b/crates/store/src/goals.rs @@ -5,8 +5,8 @@ use crate::progress::{floor_pct, task_weeks, HistoryWeek, MIN_WEEK}; use crate::stats::{monday_of, View}; use crate::{Error, Result, Store}; -use chrono::{Duration, NaiveDate}; use engine::{Signal, Steer, Tier}; +use jiff::{civil::Date, ToSpan}; use rusqlite::{params, OptionalExtension}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -59,7 +59,7 @@ pub struct Goal { /// Percent: the floor for a habit, the ceiling for steering. Unused for a tier. pub target: i64, /// The day it was set. Only tasks from then on count. - pub start: NaiveDate, + pub start: Date, } impl Goal { @@ -111,7 +111,7 @@ impl WeekState { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct GoalWeek { /// The week's Monday. - pub week: NaiveDate, + pub week: Date, /// Prompts (habit) or continued tasks (steering) counted. pub count: i64, /// Percent of them that carried the signal (habit) or got that steering (steering). @@ -159,7 +159,7 @@ pub struct Trophy { /// The goal. pub goal: Goal, /// The day it was finished. - pub done: NaiveDate, + pub done: Date, } /// How a habit or steering goal did in `w`: (count, value). @@ -277,7 +277,7 @@ fn baseline(weeks: &[HistoryWeek]) -> Baseline { /// Every goal you could pick now: a habit for each signal, a ceiling for each kind of steering /// that's on you, and the tiers above yours. Targets come from your own numbers. -pub(crate) fn options(weeks: &[HistoryWeek], today: NaiveDate, tier: Option) -> Vec { +pub(crate) fn options(weeks: &[HistoryWeek], today: Date, tier: Option) -> Vec { let b = baseline(weeks); let goal = |kind, target| Goal { id: 0, kind, target, start: today }; let habits = @@ -292,7 +292,7 @@ pub(crate) fn options(weeks: &[HistoryWeek], today: NaiveDate, tier: Option) -> Goal { +pub(crate) fn suggest(weeks: &[HistoryWeek], today: Date, tier: Option) -> Goal { let b = baseline(weeks); let goal = |kind, target| Goal { id: 0, kind, target, start: today }; if b.tasks == 0 { @@ -318,7 +318,7 @@ impl Store { /// Sets the goal (replacing any other), starting today. Its id is `now_ms`. A tier you've /// already reached isn't a goal. - pub fn set_goal(&self, kind: GoalKind, target: i64, today: NaiveDate, now_ms: i64) -> Result { + pub fn set_goal(&self, kind: GoalKind, target: i64, today: Date, now_ms: i64) -> Result { let goal = Goal { id: now_ms, kind, target, start: today }; goal.validate()?; if let GoalKind::Tier { tier } = kind { @@ -337,14 +337,14 @@ impl Store { } /// Weeks of `goal` already frozen, by Monday. - fn frozen_weeks(&self, goal: &Goal) -> Result> { + fn frozen_weeks(&self, goal: &Goal) -> Result> { let mut stmt = self.conn().prepare("SELECT week, count, value, state FROM goal_weeks WHERE goal = ?1")?; let rows = stmt.query_map([goal.id], |r| Ok((r.get::<_, String>(0)?, r.get(1)?, r.get(2)?, r.get::<_, String>(3)?)))?; let mut out = BTreeMap::new(); for row in rows { let (week, count, value, state) = row?; - if let (Ok(week), Some(state)) = (week.parse::(), WeekState::parse(&state)) { + if let (Ok(week), Some(state)) = (week.parse::(), WeekState::parse(&state)) { out.insert(week, GoalWeek { week, count, value, state }); } } @@ -352,7 +352,7 @@ impl Store { } /// Where `goal` stands on `today`: frozen weeks as they were, the rest from current history. - pub(crate) fn goal_status(&self, goal: Goal, today: NaiveDate, score: Option) -> Result { + pub(crate) fn goal_status(&self, goal: Goal, today: Date, score: Option) -> Result { let mut status = GoalStatus { goal, weeks: vec![], @@ -384,7 +384,7 @@ impl Store { GoalWeek { week: w, count, value, state: week_state(&goal, count, value, w < this_week) } }; status.weeks.push(week); - w += Duration::days(7); + w += 7.days(); } status.met = status.weeks.iter().filter(|w| w.state == WeekState::Met).count() as i64; status.streak = streak(&status.weeks); @@ -400,7 +400,7 @@ impl Store { Ok(status) } - fn trophy_for(&self, goal: i64) -> Result> { + fn trophy_for(&self, goal: i64) -> Result> { let day: Option = self.conn().query_row("SELECT done FROM trophies WHERE id = ?1", [goal], |r| r.get(0)).optional()?; Ok(day.and_then(|d| d.parse().ok())) @@ -423,7 +423,7 @@ impl Store { /// Freezes the goal's finished weeks and records a trophy once it's done. Runs after each /// sync; returns what's new (weeks just met, and whether the goal was just finished) for /// popups. A finished goal is left alone: nothing more to freeze or announce. - pub fn close_goal_weeks(&self, today: NaiveDate) -> Result { + pub fn close_goal_weeks(&self, today: Date) -> Result { let Some(goal) = self.goal()? else { return Ok(GoalNews::default()) }; if self.trophy_for(goal.id)?.is_some() { return Ok(GoalNews::default()); diff --git a/crates/store/src/ingest.rs b/crates/store/src/ingest.rs index 092c8e0..372ea5c 100644 --- a/crates/store/src/ingest.rs +++ b/crates/store/src/ingest.rs @@ -4,9 +4,9 @@ use crate::cards::{self, set_left_out}; use crate::rebuild::level_after_rebuild; use crate::{card_secret, hash, tips, Level, Result, SourceState, Store, NO_MODEL}; -use chrono::Local; use engine::{classify, normalize_model, read_prompt, snippet, Label, Prompt}; use rusqlite::{params, Connection, OptionalExtension}; +use sources::time::{local_day, rfc3339}; use sources::{ChatView, Kind, Source, SourceTurn}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -219,7 +219,7 @@ fn count_turn( if rebuilding { tx.execute("INSERT OR IGNORE INTO rebuild_read (id, source) VALUES (?1, ?2)", params![session, source])?; } - let key = engine::message_key(source, &st.session, st.key.as_deref(), &st.ts.to_rfc3339(), &st.turn.human); + let key = engine::message_key(source, &st.session, st.key.as_deref(), &rfc3339(st.ts), &st.turn.human); let new = "INSERT OR IGNORE INTO seen (key, source, session) VALUES (?1, ?2, ?3)"; if tx.execute(new, params![key, source, session])? == 0 { return Ok(None); // a copy we've already counted (resumed or forked session, re-import) @@ -229,7 +229,7 @@ fn count_turn( let (provider, family, version) = model .as_ref() .map_or((NO_MODEL, NO_MODEL, ""), |m| (m.provider.as_str(), m.family.as_str(), m.version.as_str())); - let day = st.ts.with_timezone(&Local).date_naive().to_string(); + let day = local_day(st.ts).to_string(); let bump = |kind: &str, category: &str| { tx.execute( "INSERT INTO daily (day, source, provider, family, version, kind, category, n) VALUES (?1,?2,?3,?4,?5,?6,?7,1) @@ -259,7 +259,7 @@ fn count_turn( SELECT ?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15 WHERE NOT EXISTS (SELECT 1 FROM events WHERE seen_key = ?15)", params![ - st.ts.to_rfc3339(), + rfc3339(st.ts), day, source, session, diff --git a/crates/store/src/insights.rs b/crates/store/src/insights.rs index 4c3410e..e6d1f57 100644 --- a/crates/store/src/insights.rs +++ b/crates/store/src/insights.rs @@ -5,8 +5,8 @@ use crate::progress::{floor_pct, HistoryWeek, MIN_CARD_BEST, MIN_CARD_HALF, MIN_ use crate::stats::{steer_totals, task_groups, tip_for, View, CONTINUED, LANDED}; use crate::tips::{self, TipTrend, TopTip}; use crate::{Result, Tip}; -use chrono::NaiveDate; use engine::{habit_bits, Grade, Signal, Steer, MIN_PROMPTS}; +use jiff::civil::Date; use serde::Serialize; /// "What works for you" compares models only when each has this many continued tasks... @@ -43,13 +43,13 @@ pub struct CardTrend { #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] pub struct Bests { /// Best landed percent over any 4 weeks with enough tasks, and the last Monday of them. - pub landed: Option<(i64, NaiveDate)>, + pub landed: Option<(i64, Date)>, /// Best share of specific prompts in a week with enough of them. - pub sharp: Option<(i64, NaiveDate)>, + pub sharp: Option<(i64, Date)>, /// Longest run of goal weeks met. pub goal_streak: i64, /// Best share of graded tasks that got an A or B in a week with enough of them. - pub report_card: Option<(i64, NaiveDate)>, + pub report_card: Option<(i64, Date)>, } /// One model's landed rate, for comparing. @@ -118,7 +118,7 @@ pub(crate) fn card_best(weeks: &[HistoryWeek]) -> Best { } /// A percent and the week it happened. -type Best = Option<(i64, NaiveDate)>; +type Best = Option<(i64, Date)>; /// Best 4-week landed rate and best specific week. pub(crate) fn bests(weeks: &[HistoryWeek]) -> (Best, Best) { @@ -140,7 +140,7 @@ pub(crate) fn bests(weeks: &[HistoryWeek]) -> (Best, Best) { /// `cards` is the same filter without the range: the improvement headline and the tips cover all /// your history. -pub(crate) fn insights(v: &View, cards: &View, today: NaiveDate) -> Result { +pub(crate) fn insights(v: &View, cards: &View, today: Date) -> Result { let groups = task_groups(v)?; let signals = Signal::ALL.into_iter().map(|s| tip_for(&groups, s)).filter(|t| t.landed_with_without.is_some()).collect(); diff --git a/crates/store/src/milestones.rs b/crates/store/src/milestones.rs index aee4865..ac41741 100644 --- a/crates/store/src/milestones.rs +++ b/crates/store/src/milestones.rs @@ -5,8 +5,8 @@ use crate::progress::{card_weeks, floor_pct}; use crate::stats::{monday_of, View}; use crate::{put_setting, GoalWeek, Result, Stats, Store, GOAL_WEEKS, MIN_CARD_BEST}; -use chrono::{Duration, NaiveDate}; use engine::{LetterGrade, PromptTier, Tier, WINDOW_DAYS}; +use jiff::{civil::Date, ToSpan}; /// Correction totals worth announcing. pub const COUNTS: [i64; 9] = [1, 10, 25, 50, 100, 250, 500, 1000, 2500]; @@ -133,12 +133,12 @@ pub fn goal_milestones(newly_met: &[GoalWeek], met: i64, finished: bool) -> Vec< /// The popup for a first straight-A's week. `prev` is how many there were at the last check and /// `weeks` all there are now (Monday and graded tasks, oldest first). Only the first ever is news. /// It says "last week" when that's the week, which it nearly always is: a sync follows each week's end. -pub fn straight_as(prev: i64, weeks: &[(NaiveDate, i64)], today: NaiveDate) -> Option { +pub fn straight_as(prev: i64, weeks: &[(Date, i64)], today: Date) -> Option { let (week, _) = weeks.last().filter(|_| prev == 0)?; - let when = if *week + Duration::days(7) == monday_of(today) { + let when = if *week + 7.days() == monday_of(today) { "last week".to_string() } else { - format!("the week of {}", week.format("%b %-d")) + format!("the week of {}", week.strftime("%b %-d")) }; Some(Milestone { title: "Straight A's!".into(), body: format!("Every report card {when} was an A.") }) } @@ -166,7 +166,7 @@ fn best_tier( impl Store { /// Finished weeks (before `today`'s) with enough graded tasks, all of them an A, oldest first, as /// (Monday, graded tasks). Across all AI, since the milestone is about you. - pub fn straight_a_weeks(&self, today: NaiveDate) -> Result> { + pub fn straight_a_weeks(&self, today: Date) -> Result> { let this_week = monday_of(today); Ok(card_weeks(&View::all(self.conn()))? .into_iter() @@ -182,7 +182,7 @@ impl Store { /// the history was just read in bulk (a first sync, a source just allowed, a rebuild): the /// baseline still moves, so the old weeks that came in are never news later, but nothing is /// returned. - pub fn advance_card_milestones(&self, today: NaiveDate, announce: bool) -> Result> { + pub fn advance_card_milestones(&self, today: Date, announce: bool) -> Result> { let weeks = self.straight_a_weeks(today)?; let saved: Option = self.get_setting(STRAIGHT_AS_KEY)?.and_then(|v| v.parse().ok()); let now = weeks.len() as i64; diff --git a/crates/store/src/progress.rs b/crates/store/src/progress.rs index f41810e..d60c08a 100644 --- a/crates/store/src/progress.rs +++ b/crates/store/src/progress.rs @@ -8,8 +8,8 @@ use crate::insights::{bests, card_best, insights, Bests, Insights}; use crate::stats::{day_counts, monday_of, tally, View, CONTINUED, LANDED}; use crate::tips::{self, TipWeek}; use crate::{Error, Filter, Result, Store}; -use chrono::{Duration, NaiveDate}; use engine::{habit_bits, LetterGrade, Signals, Steer}; +use jiff::{civil::Date, ToSpan}; use serde::Serialize; use std::collections::BTreeMap; @@ -35,7 +35,7 @@ const LESSONS_MAX: usize = 200; #[derive(Debug, Clone, Default, PartialEq, Serialize)] pub struct HistoryWeek { /// The week's Monday. - pub week: NaiveDate, + pub week: Date, /// Messages sent. pub messages: i64, /// Times you corrected it. @@ -141,7 +141,7 @@ pub struct RecentReportCard { pub day: String, /// The day the card was written, in the local time zone: when it is "from". Settings shows the /// last card by this day. - pub graded_day: NaiveDate, + pub graded_day: Date, /// Source id. pub source: String, /// "A" to "F". @@ -182,7 +182,7 @@ type PerSteer = [i64; Steer::ALL.len()]; type TaskRow = (String, Signals, bool, bool, i64, PerSteer, PerSteer); /// Tasks per week (from `since`, when given), plus messages and corrections from `daily`. -pub(crate) fn task_weeks(v: &View, since: Option) -> Result> { +pub(crate) fn task_weeks(v: &View, since: Option) -> Result> { let sums: Vec = Steer::ALL.iter().map(|c| format!("SUM({})", c.as_str())).collect(); let any: Vec = Steer::ALL.iter().map(|c| format!("SUM({} > 0)", c.as_str())).collect(); let after = if since.is_some() { " AND day >= ?" } else { "" }; @@ -213,9 +213,9 @@ pub(crate) fn task_weeks(v: &View, since: Option) -> Result = BTreeMap::new(); + let mut weeks: BTreeMap = BTreeMap::new(); for (day, signals, continued, landed, n, steering, steered) in rows { - let Ok(d) = day.parse::() else { continue }; + let Ok(d) = day.parse::() else { continue }; let w = weeks.entry(monday_of(d)).or_insert_with(|| HistoryWeek { week: monday_of(d), ..HistoryWeek::default() }); w.tasks += n; @@ -231,10 +231,10 @@ pub(crate) fn task_weeks(v: &View, since: Option) -> Result Result> { +fn history(v: &View, today: Date) -> Result> { let mut weeks = task_weeks(v, None)?; for (day, messages, corrections, humbled) in day_counts(v)? { - let Ok(d) = day.parse::() else { continue }; + let Ok(d) = day.parse::() else { continue }; let w = weeks.entry(monday_of(d)).or_insert_with(|| HistoryWeek { week: monday_of(d), ..HistoryWeek::default() }); w.messages += messages; @@ -255,18 +255,18 @@ fn history(v: &View, today: NaiveDate) -> Result> { let mut w = first; while w <= this_week { out.push(weeks.remove(&w).unwrap_or_else(|| HistoryWeek { week: w, ..HistoryWeek::default() })); - w += Duration::days(7); + w += 7.days(); } Ok(out) } /// Report cards per week from the cards that still count, plus the tasks that could have one. -pub(crate) fn card_weeks(v: &View) -> Result> { - let mut weeks: BTreeMap = BTreeMap::new(); +pub(crate) fn card_weeks(v: &View) -> Result> { + let mut weeks: BTreeMap = BTreeMap::new(); let habits = habit_bits(); // In a fixed order, so the cost adds up the same way every time. for c in current(v, "ORDER BY start_ts, key")? { - let Ok(day) = c.day.parse::() else { continue }; + let Ok(day) = c.day.parse::() else { continue }; let w = weeks.entry(monday_of(day)).or_insert_with(ReportCardWeek::with_keys); w.graded += 1; *w.grades.entry(c.grade.as_str().to_string()).or_insert(0) += 1; @@ -287,7 +287,7 @@ pub(crate) fn card_weeks(v: &View) -> Result let sql = format!("SELECT day, COUNT(*) FROM tasks WHERE source IN ({}) {} GROUP BY day", sources.join(","), v.clause); for (day, n) in v.rows(&sql, &[], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { - if let Ok(day) = day.parse::() { + if let Ok(day) = day.parse::() { weeks.entry(monday_of(day)).or_default().gradable_tasks += n; // no keys until a task is graded } } @@ -312,7 +312,7 @@ fn valid_lesson_id(id: &str) -> bool { impl Store { /// Everything the Improve tab shows. History and insights follow `f`; the goal and personal /// bests are across all AI. - pub fn progress(&self, f: &Filter, today: NaiveDate) -> Result { + pub fn progress(&self, f: &Filter, today: Date) -> Result { let (clause, args) = f.sql(); let v = View { conn: self.conn(), clause, args }; let weeks = history(&v, today)?; @@ -379,7 +379,7 @@ impl Store { /// When each source last had a report card written, as the local day, by source id. Sources with /// no card aren't listed. Whatever the model filter, and counting every card kept, replaced or not. - pub fn last_report_card_days(&self) -> Result> { + pub fn last_report_card_days(&self) -> Result> { let mut stmt = self.conn().prepare("SELECT source, MAX(graded_at) FROM report_cards GROUP BY source ORDER BY source")?; let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; @@ -454,7 +454,7 @@ mod tests { assert_eq!(ReportCardWeek::default().count(LetterGrade::A), 0, "a missing key is zero"); } - fn d(s: &str) -> NaiveDate { + fn d(s: &str) -> Date { s.parse().unwrap() } diff --git a/crates/store/src/retention.rs b/crates/store/src/retention.rs index 9074fe7..de3a6fd 100644 --- a/crates/store/src/retention.rs +++ b/crates/store/src/retention.rs @@ -2,9 +2,10 @@ //! cleaning it with newer redaction, and clearing it from the write-ahead log and the backup. use crate::{files, put_setting, Error, Result, Store}; -use chrono::{DateTime, Duration, Utc}; +use jiff::{SignedDuration, Timestamp}; use rusqlite::params; use serde::{Deserialize, Serialize}; +use sources::time::rfc3339; use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -139,7 +140,7 @@ impl Store { pub fn set_retention(&self, r: Retention) -> Result<()> { r.validate()?; self.set_setting("retention", &serde_json::to_string(&r)?)?; - self.sweep(Utc::now())?; + self.sweep(Timestamp::now())?; Ok(()) } @@ -216,11 +217,11 @@ impl Store { /// Steps aging events down: full → snippet → category. Pinned events keep their text. /// An unreadable retention setting skips the sweep: deleting text can't be undone, so it /// waits until the user's choice is known again. - pub fn sweep(&self, now: DateTime) -> Result { + pub fn sweep(&self, now: Timestamp) -> Result { let Some(r) = self.saved_retention()? else { return Ok(0) }; // A stored value out of range (an older build allowed any number) means nothing is that old. let cutoff = |days: u32| { - now.checked_sub_signed(Duration::days(i64::from(days))).unwrap_or(DateTime::::MIN_UTC).to_rfc3339() + rfc3339(now.checked_sub(SignedDuration::from_hours(24 * i64::from(days))).unwrap_or(Timestamp::MIN)) }; let (full_cut, snip_cut) = (cutoff(r.full_days), cutoff(r.snippet_days)); let mut changed = self.conn.execute( diff --git a/crates/store/src/stats.rs b/crates/store/src/stats.rs index 33c6878..2c8f6b8 100644 --- a/crates/store/src/stats.rs +++ b/crates/store/src/stats.rs @@ -1,11 +1,11 @@ //! Read side: everything the scorecard, quick glance and model breakdown show. use crate::{Result, Store}; -use chrono::{DateTime, Datelike, Duration, Local, NaiveDate, Timelike}; use engine::{ Answer, CorrectionTier, Grade, Label, PromptTier, Score, Signal, Signals, Steer, Tier, Window, MIN_PROMPTS, WINDOW_DAYS, }; +use jiff::{civil::Date, ToSpan}; use rusqlite::{params_from_iter, Connection}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; @@ -45,7 +45,7 @@ pub struct Filter { /// Only days from this one on: counts and the score both follow it. Without it, counts cover /// all of history and the score the last [`WINDOW_DAYS`] days. "This week" never moves. #[serde(default)] - pub since: Option, + pub since: Option, } impl Filter { @@ -130,7 +130,7 @@ pub struct Overall { #[derive(Debug, Default, PartialEq, Eq, Serialize)] pub struct WeekRow { /// The week's Monday. - pub week: NaiveDate, + pub week: Date, /// Messages that week. pub messages: i64, /// Corrections that week. @@ -305,15 +305,15 @@ struct Totals { } /// The first day the score looks at: `since` when the view has one, else [`WINDOW_DAYS`] back. -fn score_start(since: Option, today: NaiveDate) -> NaiveDate { - since.unwrap_or(today - Duration::days(WINDOW_DAYS - 1)) +fn score_start(since: Option, today: Date) -> Date { + since.unwrap_or(today - (WINDOW_DAYS - 1).days()) } /// Counts over `v`; "this week" and the score's window (from `start`) over `scope`, the same /// filter without `since`. -fn totals(v: &View, scope: &View, today: NaiveDate, start: NaiveDate) -> Result { +fn totals(v: &View, scope: &View, today: Date, start: Date) -> Result { let kinds = CORRECTION_KINDS.as_str(); - let week_ago = (today - Duration::days(6)).to_string(); + let week_ago = (today - 6.days()).to_string(); let (window_corrections, window_humbled) = window_sums(scope, start)?; Ok(Totals { messages: v.sum("AND kind = 'message'", &[])?, @@ -326,7 +326,7 @@ fn totals(v: &View, scope: &View, today: NaiveDate, start: NaiveDate) -> Result< } /// (corrections, humbled) from `start` on. -fn window_sums(v: &View, start: NaiveDate) -> Result<(i64, i64)> { +fn window_sums(v: &View, start: Date) -> Result<(i64, i64)> { let from = start.to_string(); Ok(( v.sum(&format!("AND kind IN {} AND day >= ?", *CORRECTION_KINDS), &[&from])?, @@ -360,7 +360,7 @@ fn labels_and_categories(v: &View) -> Result<(BTreeMap, BTreeMap, since: Option) -> Result<(i64, i64)> { +fn real_chats(conn: &Connection, source: Option<&str>, since: Option) -> Result<(i64, i64)> { Ok(conn.query_row( "SELECT COUNT(*), COALESCE(SUM(corrections > 0), 0) FROM sessions WHERE messages >= ?1 AND (?2 IS NULL OR source = ?2) AND (?3 IS NULL OR last_day >= ?3)", @@ -371,9 +371,9 @@ fn real_chats(conn: &Connection, source: Option<&str>, since: Option) /// Sorted days you sent at least one message. A day with no corrections is a good day, so it /// keeps the streak going instead of breaking it. -fn active_days(v: &View) -> Result> { +fn active_days(v: &View) -> Result> { let sql = format!("SELECT DISTINCT day FROM daily WHERE kind = 'message' {} ORDER BY day", v.clause); - let mut days: Vec = + let mut days: Vec = v.rows(&sql, &[], |r| r.get::<_, String>(0))?.into_iter().filter_map(|d| d.parse().ok()).collect(); days.dedup(); Ok(days) @@ -381,14 +381,14 @@ fn active_days(v: &View) -> Result> { /// (best, current) runs of consecutive days in sorted `days`. The current run still counts if /// its last day was yesterday: today isn't over. -fn streaks(days: &[NaiveDate], today: NaiveDate) -> (i64, i64) { +fn streaks(days: &[Date], today: Date) -> (i64, i64) { let (mut best, mut run) = (0i64, 0i64); for (i, d) in days.iter().enumerate() { - run = if i > 0 && *d - days[i - 1] == Duration::days(1) { run + 1 } else { 1 }; + run = if i > 0 && days[i - 1].tomorrow().ok() == Some(*d) { run + 1 } else { 1 }; best = best.max(run); } let current = match days.last() { - Some(d) if today - *d <= Duration::days(1) => run, + Some(d) if (today - *d).get_days() <= 1 => run, _ => 0, }; (best, current) @@ -398,9 +398,10 @@ fn streaks(days: &[NaiveDate], today: NaiveDate) -> (i64, i64) { fn correction_hours(v: &View) -> Result<[i64; 24]> { let sql = format!("SELECT ts FROM events WHERE label IN {} {}", *CORRECTION_KINDS, v.clause); let mut hours = [0i64; 24]; + let zone = sources::time::local_zone(); for ts in v.rows(&sql, &[], |r| r.get::<_, String>(0))? { - if let Ok(t) = DateTime::parse_from_rfc3339(&ts) { - hours[t.with_timezone(&Local).hour() as usize] += 1; + if let Some(t) = sources::time::parse(&ts) { + hours[t.to_zoned(zone.clone()).hour() as usize] += 1; } } Ok(hours) @@ -412,8 +413,8 @@ fn peak_hour(hours: &[i64; 24]) -> Option { } /// The Monday starting `d`'s week. -pub(crate) fn monday_of(d: NaiveDate) -> NaiveDate { - d - Duration::days(i64::from(d.weekday().num_days_from_monday())) +pub(crate) fn monday_of(d: Date) -> Date { + d - i64::from(d.weekday().to_monday_zero_offset()).days() } /// Each day's (day, messages, corrections, humbled moments). @@ -428,9 +429,9 @@ pub(crate) fn day_counts(v: &View) -> Result> { } fn weekly(v: &View) -> Result> { - let mut weeks: BTreeMap = BTreeMap::new(); + let mut weeks: BTreeMap = BTreeMap::new(); let mut add = |day: String, f: &mut dyn FnMut(&mut WeekRow)| { - if let Ok(d) = day.parse::() { + if let Ok(d) = day.parse::() { let week = monday_of(d); f(weeks.entry(week).or_insert_with(|| WeekRow { week, ..WeekRow::default() })); } @@ -580,7 +581,7 @@ pub(crate) static LANDED: LazyLock = LazyLock::new(|| format!("({CONTINU pub(crate) type Group = (Signals, bool, bool, i64); /// Counts over `v`; the tier's window (from `start`) over `scope`, the same filter without `since`. -fn prompts(v: &View, scope: &View, start: NaiveDate) -> Result { +fn prompts(v: &View, scope: &View, start: Date) -> Result { let groups = task_groups(v)?; let mut p = Prompts::default(); for (signals, continued, landed, n) in &groups { @@ -637,7 +638,7 @@ pub(crate) fn tally(grades: &mut BTreeMap, carried: &mut BTreeMap Result<(i64, i64)> { +fn window_counts(v: &View, start: Date) -> Result<(i64, i64)> { let since = start.to_string(); let sql = format!( "SELECT COUNT(*), COALESCE(SUM({}), 0) FROM tasks WHERE {CONTINUED} {} AND day >= ?", @@ -704,7 +705,7 @@ fn overall_of(continued: i64, landed: i64, corrections: i64, humbled: i64, days: impl Store { /// Just the overall score across all AI: a few queries, for goals and the tray. - pub fn overall(&self, today: NaiveDate) -> Result { + pub fn overall(&self, today: Date) -> Result { let v = View::all(self.conn()); let start = score_start(None, today); let (continued, landed) = window_counts(&v, start)?; @@ -713,7 +714,7 @@ impl Store { } /// The scorecard for `f`, with "this week" ending on `today`. - pub fn stats(&self, f: &Filter, today: NaiveDate) -> Result { + pub fn stats(&self, f: &Filter, today: Date) -> Result { let (clause, args) = f.sql(); let v = View { conn: self.conn(), clause, args }; let (scope_clause, scope_args) = Filter { since: None, ..f.clone() }.sql(); @@ -733,7 +734,12 @@ impl Store { humbled: t.humbled, labels, corrections_last_7d: t.corrections_last_7d, - overall: overall(&prompts, t.window_corrections, t.window_humbled, (today - start).num_days() + 1), + overall: overall( + &prompts, + t.window_corrections, + t.window_humbled, + i64::from((today - start).get_days()) + 1, + ), messages_per_correction: (t.corrections > 0) .then(|| (t.messages as f64 / t.corrections as f64).round() as i64), real_chats, @@ -754,7 +760,7 @@ impl Store { mod tests { use super::*; - fn d(s: &str) -> NaiveDate { + fn d(s: &str) -> Date { s.parse().unwrap() } diff --git a/crates/store/src/sync.rs b/crates/store/src/sync.rs index 7663971..30a5dbe 100644 --- a/crates/store/src/sync.rs +++ b/crates/store/src/sync.rs @@ -109,7 +109,7 @@ pub fn sync(store: &mut Store, all: &[Box]) -> Result { } } store.finish_rebuild()?; - store.sweep(chrono::Utc::now())?; + store.sweep(jiff::Timestamp::now())?; Ok(report) } @@ -170,7 +170,7 @@ mod tests { let seen = TipSeen { session: "s".into(), key: None, - ts: chrono::Utc::now(), + ts: jiff::Timestamp::now(), pos: 0, model: None, tip: engine::parse_tip("Tip from No, Actually...: say more. [target, redid 50%]").unwrap(), diff --git a/crates/store/src/tests.rs b/crates/store/src/tests.rs index ae38f1e..346f95f 100644 --- a/crates/store/src/tests.rs +++ b/crates/store/src/tests.rs @@ -4,9 +4,10 @@ use super::*; use crate::paths::resolve_db_path; use crate::rebuild::REBUILDING_KEY; use crate::retention::REDACTION_KEY; -use chrono::{Duration, Local, NaiveDate, TimeZone, Utc}; use engine::{Answer, PromptTier, Signal, Signals}; +use jiff::{civil::Date, SignedDuration, Timestamp, ToSpan}; use sources::testing::{cc_ai, cc_correction, cc_user, set_mtime_ago}; +use sources::time::rfc3339; use sources::{FileScan, Source, SourceTurn}; use std::collections::BTreeMap; use std::ffi::OsString; @@ -43,12 +44,12 @@ fn ingest(s: &mut Store, path: &str, turns: Vec) { s.ingest(&test_source(), path, &scan(turns), None, Pass::new(FileMeta { size: 100, mtime: 1 }, false)).unwrap(); } -fn today() -> NaiveDate { - Local::now().date_naive() +fn today() -> Date { + sources::time::today() } fn now_ts(days_ago: i64) -> String { - (Utc::now() - Duration::days(days_ago)).to_rfc3339() + rfc3339(Timestamp::now() - SignedDuration::from_hours(24 * days_ago)) } fn stats(s: &Store) -> Stats { @@ -147,7 +148,11 @@ fn hall_names_known_sources() { fn weekly_buckets_split_on_monday() { let mut s = Store::open_in_memory().unwrap(); // Local noon is the same day in every timezone; a fixed UTC hour isn't. - let noon = |day: u32| Local.with_ymd_and_hms(2026, 10, day, 12, 0, 0).unwrap().with_timezone(&Utc).to_rfc3339(); + let noon = |day: i8| { + rfc3339( + jiff::civil::date(2026, 10, day).at(12, 0, 0, 0).to_zoned(sources::time::local_zone()).unwrap().timestamp(), + ) + }; let (sunday, monday) = (noon(25), noon(26)); ingest( &mut s, @@ -155,7 +160,7 @@ fn weekly_buckets_split_on_monday() { vec![turn("no, that's wrong", "You're right.", "m", &sunday, "a"), turn("thanks", "Sure.", "m", &monday, "b")], ); let w = s.stats(&Filter::default(), "2026-10-27".parse().unwrap()).unwrap().weekly; - let d = |s: &str| s.parse::().unwrap(); + let d = |s: &str| s.parse::().unwrap(); let row = |w: &WeekRow| (w.week, w.messages, w.corrections); assert_eq!(w.iter().map(row).collect::>(), vec![(d("2026-10-19"), 1, 1), (d("2026-10-26"), 1, 0)]); // The week's breakdown: which kind of correction it was, and steering on that week's tasks. @@ -167,7 +172,7 @@ fn weekly_buckets_split_on_monday() { #[test] fn streaks_count_days_you_used_ai_and_peak_hour_comes_from_corrections() { let mut s = Store::open_in_memory().unwrap(); - let at = |days_ago: i64| (Utc::now() - Duration::days(days_ago)).to_rfc3339(); + let at = |days_ago: i64| rfc3339(Timestamp::now() - SignedDuration::from_hours(24 * days_ago)); let corrections = [0, 2, 5].map(|d| turn("no, that's wrong", "You're right.", "m", &at(d), &d.to_string())); ingest(&mut s, "f", corrections.into()); // A day with nothing to correct is a good day: it keeps the streak instead of breaking it. @@ -191,7 +196,7 @@ fn copies_are_never_counted_twice() { #[test] fn backfill_window_is_respected() { let mut s = Store::open_in_memory().unwrap(); - let state = SourceState { backfill_since: Some(today() - Duration::days(7)), ..test_source() }; + let state = SourceState { backfill_since: Some(today() - 7.days()), ..test_source() }; let old = turn("no, that's wrong", "You're right.", "m", &now_ts(40), "x"); s.ingest(&state, "f", &scan(vec![old.clone()]), None, Pass::new(FileMeta::default(), false)).unwrap(); assert_eq!(stats(&s).messages, 0); @@ -218,7 +223,7 @@ fn retention_steps_down_and_pins_hold() { let pinned_id: i64 = s.conn.query_row("SELECT id FROM events WHERE human_full LIKE '%docs%'", [], |r| r.get(0)).unwrap(); s.pin(pinned_id, true).unwrap(); - s.sweep(Utc::now()).unwrap(); + s.sweep(Timestamp::now()).unwrap(); let level = |needle: &str| -> (String, Option, Option) { s.conn @@ -241,7 +246,7 @@ fn retention_steps_down_and_pins_hold() { assert_eq!(level("new"), ("category".into(), None, None)); assert_eq!(level("pinned").0, "full", "pins still hold"); s.pin(pinned_id, false).unwrap(); - s.sweep(Utc::now()).unwrap(); + s.sweep(Timestamp::now()).unwrap(); assert_eq!(level("pinned"), ("category".into(), None, None), "unpinned text steps down on the next sweep"); assert!(stats(&s).hall_of_fame.is_empty(), "no text left to show"); } @@ -269,7 +274,7 @@ fn retention_is_validated() { assert!(Retention { full_days: 36_500, snippet_days: 36_500, ..Retention::default() }.validate().is_ok()); // A bad value already on disk skips the sweep instead of panicking. s.set_setting("retention", r#"{"level":"snippet","full_days":30,"snippet_days":4000000000}"#).unwrap(); - assert_eq!(s.sweep(Utc::now()).unwrap(), 0); + assert_eq!(s.sweep(Timestamp::now()).unwrap(), 0); assert_eq!("snippet".parse::().unwrap(), Level::Snippet); assert!("everything".parse::().is_err()); } @@ -348,7 +353,7 @@ fn imports_are_read_from_their_paths() { fn nothing_is_read_without_consent_and_live_appends_count_once() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("abc.jsonl"); - let ts = Utc::now().to_rfc3339(); + let ts = rfc3339(Timestamp::now()); std::fs::write(&path, cc_ai("claude-opus-5-5", &ts, "Use /admin.") + &cc_user("u1", &ts, "that's not a real page")) .unwrap(); @@ -373,7 +378,7 @@ fn nothing_is_read_without_consent_and_live_appends_count_once() { fn quiet_files_count_their_last_unanswered_message() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("abc.jsonl"); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); std::fs::write(&path, cc_ai("claude-opus-5-5", &ts, "Done.") + &cc_user("u1", &ts, "you missed the tests")) .unwrap(); let mut s = Store::open_in_memory().unwrap(); @@ -390,7 +395,7 @@ fn quiet_files_count_their_last_unanswered_message() { fn rewritten_or_shrunk_files_never_double_count() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("abc.jsonl"); - let ts = (Utc::now() - Duration::hours(2)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(2)); let body = cc_ai("claude-opus-5-5", &ts, "Use /admin.") + &cc_user("u1", &ts, "that's not a real page") + &cc_ai("claude-opus-5-5", &ts, "You're right."); @@ -415,7 +420,7 @@ fn rewritten_or_shrunk_files_never_double_count() { #[test] fn unreadable_files_are_reported_not_fatal() { let dir = tempfile::tempdir().unwrap(); - let ts = Utc::now().to_rfc3339(); + let ts = rfc3339(Timestamp::now()); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u", &ts)); let mut s = Store::open_in_memory().unwrap(); s.import("chatgpt-export", &dir.path().join("conversations.json").to_string_lossy()).unwrap(); @@ -432,7 +437,7 @@ fn unreadable_files_are_reported_not_fatal() { #[test] fn paused_and_revoked_sources_are_not_read() { let dir = tempfile::tempdir().unwrap(); - let ts = Utc::now().to_rfc3339(); + let ts = rfc3339(Timestamp::now()); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -449,7 +454,7 @@ fn paused_and_revoked_sources_are_not_read() { #[test] fn rule_changes_rebuild_scores_but_keep_consent() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let body = cc_ai("claude-opus-5-5", &ts, "hi") + &cc_ai("", &ts, "API Error"); write_settled(&dir.path().join("a.jsonl"), body + &cc_correction("u", &ts)); let all = claude_code(&dir); @@ -478,14 +483,14 @@ fn from_now_on_skips_existing_history_but_counts_new_messages() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.jsonl"); // Written earlier today: must not count when the person picks "From now on". - std::fs::write(&path, cc_correction("old", &(Utc::now() - Duration::minutes(30)).to_rfc3339())).unwrap(); + std::fs::write(&path, cc_correction("old", &rfc3339(Timestamp::now() - SignedDuration::from_mins(30)))).unwrap(); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); s.allow("claude-code", None).unwrap(); assert_eq!(s.start_from_now(all[0].as_ref()).unwrap(), 1); assert_eq!(sync(&mut s, &all).unwrap().messages, 0); - append(&path, &cc_correction("new", &Utc::now().to_rfc3339())); + append(&path, &cc_correction("new", &rfc3339(Timestamp::now()))); let r = sync(&mut s, &all).unwrap(); assert_eq!((r.messages, r.corrections), (1, 1), "only the new message counts"); } @@ -494,7 +499,7 @@ fn from_now_on_skips_existing_history_but_counts_new_messages() { fn allowing_more_history_re_reads_old_files() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.jsonl"); - write_settled(&path, cc_correction("old", &(Utc::now() - Duration::hours(3)).to_rfc3339())); + write_settled(&path, cc_correction("old", &rfc3339(Timestamp::now() - SignedDuration::from_hours(3)))); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); s.allow("claude-code", None).unwrap(); @@ -510,16 +515,34 @@ fn allowing_more_history_re_reads_old_files() { assert_eq!(sync(&mut s, &all).unwrap().files_read, 0); } +#[test] +fn history_from_the_from_now_on_day_re_reads_that_day() { + // "From now on" skipped the part of today before it, so "since today" reaches back. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.jsonl"); + let midnight = today().to_zoned(sources::time::local_zone()).unwrap().timestamp(); + let earlier_today = (Timestamp::now() - SignedDuration::from_mins(1)).max(midnight); + write_settled(&path, cc_correction("old", &rfc3339(earlier_today))); + let all = claude_code(&dir); + let mut s = Store::open_in_memory().unwrap(); + s.allow("claude-code", None).unwrap(); + s.start_from_now(all[0].as_ref()).unwrap(); + assert_eq!(sync(&mut s, &all).unwrap().messages, 0); + + s.allow("claude-code", Some(today())).unwrap(); + assert_eq!(sync(&mut s, &all).unwrap().messages, 1); +} + #[test] fn from_now_on_survives_a_rules_rebuild() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.jsonl"); - write_settled(&path, cc_correction("old", &(Utc::now() - Duration::hours(3)).to_rfc3339())); + write_settled(&path, cc_correction("old", &rfc3339(Timestamp::now() - SignedDuration::from_hours(3)))); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); s.allow("claude-code", None).unwrap(); s.start_from_now(all[0].as_ref()).unwrap(); - append(&path, &cc_correction("new", &Utc::now().to_rfc3339())); + append(&path, &cc_correction("new", &rfc3339(Timestamp::now()))); sync(&mut s, &all).unwrap(); assert_eq!(stats(&s).messages, 1); @@ -566,7 +589,7 @@ fn kept_counts(s: &Store) -> (i64, i64, i64, i64) { #[test] fn a_rebuild_keeps_what_it_cant_read_again() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let file = dir.path().join("a.jsonl"); write_settled(&file, cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); @@ -599,7 +622,7 @@ fn a_rebuild_keeps_what_it_cant_read_again() { #[test] fn a_rebuild_drops_a_chat_that_no_longer_has_any_of_your_messages() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let file = dir.path().join("a.jsonl"); write_settled(&file, cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); @@ -622,7 +645,7 @@ fn a_rebuild_drops_a_chat_that_no_longer_has_any_of_your_messages() { #[test] fn a_day_with_some_of_its_chats_gone_keeps_them() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let chat = |n: &str| cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction(n, &ts); let (stays, goes) = (dir.path().join("stays.jsonl"), dir.path().join("goes.jsonl")); write_settled(&stays, chat("u1")); @@ -653,7 +676,7 @@ fn a_day_with_some_of_its_chats_gone_keeps_them() { #[test] fn a_rebuild_cut_short_loses_nothing_and_forget_reaches_what_it_set_aside() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -677,7 +700,7 @@ fn a_rebuild_cut_short_loses_nothing_and_forget_reaches_what_it_set_aside() { #[test] fn scores_from_newer_rules_are_left_alone() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -692,7 +715,7 @@ fn scores_from_newer_rules_are_left_alone() { #[test] fn pins_survive_a_rules_rebuild() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let file = dir.path().join("a.jsonl"); let correction = |n: &str| cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction(n, &ts); write_settled(&file, correction("u1") + &correction("u2")); @@ -745,7 +768,7 @@ fn an_unreadable_retention_setting_never_deletes_stored_text() { s.set_retention(Retention { level: Level::Full, ..Retention::default() }).unwrap(); ingest(&mut s, "f", vec![turn("no, that's wrong", "You're right.", "m", &now_ts(1), "k")]); s.set_setting("retention", r#"{"level":"everything"}"#).unwrap(); // e.g. saved by a newer version - assert_eq!(s.sweep(Utc::now()).unwrap(), 0); + assert_eq!(s.sweep(Timestamp::now()).unwrap(), 0); let (level, text): (String, Option) = s.conn.query_row("SELECT level, human_full FROM events", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap(); assert_eq!(level, "full"); @@ -906,7 +929,7 @@ fn live_tracking_reads_prompts_like_a_full_rebuild() { // Synced after every reply, as the app does: each follow-up must still know what it answered. let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("live.jsonl"); - let ts = Utc::now().to_rfc3339(); + let ts = rfc3339(Timestamp::now()); let steps = [ cc_user("u1", &ts, "add a CSV export to src/report.ts") + &cc_ai("claude-opus-5-5", &ts, "Done."), cc_user("u2", &ts, "still not working") + &cc_ai("claude-opus-5-5", &ts, "Fixed the header row."), @@ -945,8 +968,8 @@ fn no_tip_once_every_signal_is_common() { fn a_window_moves_the_counts_and_the_score() { let s = Store::open_in_memory().unwrap(); // A fixed Sunday, so the rows 1-3 days back stay in one Monday week whatever day the test runs. - let today = || "2026-11-01".parse::().unwrap(); - let day = |ago: i64| (today() - chrono::Duration::days(ago)).to_string(); + let today = || "2026-11-01".parse::().unwrap(); + let day = |ago: i64| (today() - ago.days()).to_string(); let count = |ago: i64, kind: &str, n: i64| { s.conn() .execute( @@ -970,8 +993,7 @@ fn a_window_moves_the_counts_and_the_score() { .unwrap(); } let all = s.stats(&Filter::default(), today()).unwrap(); - let week = - s.stats(&Filter { since: Some(today() - chrono::Duration::days(6)), ..Default::default() }, today()).unwrap(); + let week = s.stats(&Filter { since: Some(today() - 6.days()), ..Default::default() }, today()).unwrap(); assert_eq!((all.messages, all.corrections, all.prompts.tasks), (30, 6, 12)); assert_eq!((week.messages, week.corrections, week.prompts.tasks), (10, 2, 2), "counts follow the window"); assert_eq!(week.weekly.len(), 1); @@ -982,8 +1004,7 @@ fn a_window_moves_the_counts_and_the_score() { // The score follows the window too: 2 tasks this week, too few to score. assert_eq!((week.prompts.window_tasks, week.overall.score, week.overall.corrections), (2, None, 2)); assert_eq!(all.prompts.window_tasks, 11, "no window: the last 28 days"); - let year = - s.stats(&Filter { since: Some(today() - chrono::Duration::days(364)), ..Default::default() }, today()).unwrap(); + let year = s.stats(&Filter { since: Some(today() - 364.days()), ..Default::default() }, today()).unwrap(); assert_eq!((year.prompts.window_tasks, year.overall.corrections), (12, 6)); assert_eq!(week.corrections_last_7d, all.corrections_last_7d, "this week never moves"); } @@ -1103,7 +1124,7 @@ fn a_later_admission_is_the_text_kept() { fn a_message_waits_for_the_ai_to_finish_and_gets_its_later_admission() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.jsonl"); - let ts = Utc::now().to_rfc3339(); + let ts = rfc3339(Timestamp::now()); let body = cc_ai("claude-opus-5-5", &ts, "It's fixed.") + &cc_user("u1", &ts, "are you sure?") + &cc_ai("claude-opus-5-5", &ts, "Let me check."); @@ -1129,7 +1150,7 @@ fn corrections_in_daily(s: &Store) -> i64 { #[test] fn a_rebuild_doesnt_count_a_forked_chat_twice() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let opening = cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -1158,7 +1179,7 @@ fn a_rebuild_doesnt_count_a_forked_chat_twice() { #[test] fn a_day_read_again_takes_the_new_message_count() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -1178,7 +1199,7 @@ fn a_day_read_again_takes_the_new_message_count() { #[test] fn a_rebuild_never_keeps_more_text_than_a_correction_had() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -1197,7 +1218,7 @@ fn a_rebuild_never_keeps_more_text_than_a_correction_had() { #[test] fn stored_text_is_redacted_again_once_when_redaction_improves() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -1250,7 +1271,7 @@ fn a_backup_is_made_daily_and_goes_when_text_is_deleted() { #[test] fn a_pinned_correction_a_fork_read_again_counts_once() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let opening = cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts); let (original, fork) = (dir.path().join("z-original.jsonl"), dir.path().join("a-fork.jsonl")); let all = claude_code(&dir); @@ -1272,7 +1293,7 @@ fn a_pinned_correction_a_fork_read_again_counts_once() { #[test] fn the_backup_outlives_the_cleaning_of_stored_text_before_a_rebuild() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::hours(1)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(1)); let chats = dir.path().join("chats"); std::fs::create_dir(&chats).unwrap(); write_settled(&chats.join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); @@ -1307,7 +1328,7 @@ fn a_file_that_cant_be_read_is_tried_again_only_when_it_changes() { #[test] fn a_sync_steps_old_text_down_in_the_same_pass() { let dir = tempfile::tempdir().unwrap(); - let ts = (Utc::now() - Duration::days(40)).to_rfc3339(); + let ts = rfc3339(Timestamp::now() - SignedDuration::from_hours(24 * 40)); write_settled(&dir.path().join("a.jsonl"), cc_ai("claude-opus-5-5", &ts, "hi") + &cc_correction("u1", &ts)); let all = claude_code(&dir); let mut s = Store::open_in_memory().unwrap(); @@ -1333,7 +1354,7 @@ fn a_sweep_that_deletes_text_empties_the_write_ahead_log() { s.set_retention(Retention { level: Level::Full, full_days: 30, snippet_days: 365 }).unwrap(); ingest(&mut s, "f", vec![turn("no, that's wrong", "You're right.", "m", &now_ts(60), "old")]); assert!(wal() > 0, "the text is in the log before the sweep"); - assert_eq!(s.sweep(Utc::now()).unwrap(), 1, "the full text was stepped down"); + assert_eq!(s.sweep(Timestamp::now()).unwrap(), 1, "the full text was stepped down"); assert_eq!(wal(), 0, "and no copy of it lingers in the log"); } @@ -1464,20 +1485,19 @@ fn forget_clears_the_source_in_every_table_that_has_one_and_nothing_else() { #[test] fn a_message_on_the_backfill_day_is_kept_and_one_just_before_it_is_not() { - let day = NaiveDate::from_ymd_opt(2026, 6, 15).unwrap(); - let midnight = - Local.from_local_datetime(&day.and_hms_opt(0, 0, 0).unwrap()).earliest().unwrap().with_timezone(&Utc); + let day = jiff::civil::date(2026, 6, 15); + let midnight = day.to_zoned(sources::time::local_zone()).unwrap().timestamp(); let state = SourceState { backfill_since: Some(day), ..test_source() }; assert!(state.wants(midnight), "the first moment of the day counts"); - assert!(state.wants(midnight + Duration::hours(12))); - assert!(!state.wants(midnight - Duration::seconds(1)), "the last moment of the day before does not"); + assert!(state.wants(midnight + SignedDuration::from_hours(12))); + assert!(!state.wants(midnight - SignedDuration::from_secs(1)), "the last moment of the day before does not"); } #[test] fn a_message_at_the_from_now_on_moment_is_kept_and_one_just_before_it_is_not() { - let at = Utc.with_ymd_and_hms(2026, 6, 15, 12, 0, 0).unwrap(); + let at = "2026-06-15T12:00:00Z".parse::().unwrap(); let state = SourceState { start_after: Some(at), ..test_source() }; - assert!(!state.wants(at - Duration::seconds(1))); + assert!(!state.wants(at - SignedDuration::from_secs(1))); assert!(state.wants(at), "exactly at the moment counts"); - assert!(state.wants(at + Duration::seconds(1))); + assert!(state.wants(at + SignedDuration::from_secs(1))); } diff --git a/crates/store/src/tips.rs b/crates/store/src/tips.rs index bb606cb..67ff5f2 100644 --- a/crates/store/src/tips.rs +++ b/crates/store/src/tips.rs @@ -5,10 +5,11 @@ use crate::cards::{ts_str, CLEARED_KEY}; use crate::stats::{monday_of, View}; use crate::{hash, Filter, Result, SourceState, Store, NO_MODEL}; -use chrono::{DateTime, Days, Local, NaiveDate, Utc}; use engine::{habit_bits, normalize_model}; +use jiff::{civil::Date, Timestamp, ToSpan}; use rusqlite::{params, Connection}; use serde::Serialize; +use sources::time; use sources::{FileScan, TipSeen}; use std::collections::BTreeMap; @@ -68,15 +69,15 @@ pub struct TipActivity { pub blocked: bool, } -fn local_day(ts: DateTime) -> String { - ts.with_timezone(&Local).date_naive().to_string() +fn local_day(ts: Timestamp) -> String { + time::local_day(ts).to_string() } /// Writes what `scan` found, in the caller's transaction. Reading a reply again writes nothing new, /// and neither does a forked chat's copy of one, which keeps its id. Anything this source's consent /// skips, or from before the history was last deleted (`cleared`), stays out. pub(crate) fn save(conn: &Connection, state: &SourceState, scan: &FileScan, cleared: Option<&str>) -> Result<()> { - let counts = |ts: DateTime| state.wants(ts) && cleared.is_none_or(|t| ts_str(ts).as_str() > t); + let counts = |ts: Timestamp| state.wants(ts) && cleared.is_none_or(|t| ts_str(ts).as_str() > t); for seen in scan.tips.iter().filter(|t| counts(t.ts)) { save_tip(conn, &state.id, seen)?; // A chat can get here without its rules being seen: a scan that began after them, or a tool @@ -118,7 +119,7 @@ fn save_tip(conn: &Connection, source: &str, seen: &TipSeen) -> Result<()> { Ok(()) } -fn save_chat(conn: &Connection, source: &str, session: &str, ts: DateTime) -> Result<()> { +fn save_chat(conn: &Connection, source: &str, session: &str, ts: Timestamp) -> Result<()> { conn.execute( "INSERT INTO tip_chats (session, source, day) VALUES (?1,?2,?3) ON CONFLICT(session) DO UPDATE SET day = min(day, excluded.day)", @@ -128,12 +129,12 @@ fn save_chat(conn: &Connection, source: &str, session: &str, ts: DateTime) } /// Tips per week, and the tasks they're out of: those from the day a chat had the rules on. -pub(crate) fn weeks(v: &View) -> Result> { - let mut weeks: BTreeMap = BTreeMap::new(); +pub(crate) fn weeks(v: &View) -> Result> { + let mut weeks: BTreeMap = BTreeMap::new(); let by_day = |sql: &str| v.rows(sql, &[], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))); let tips = format!("SELECT day, COUNT(*) FROM tips WHERE 1=1 {} GROUP BY day", v.clause); for (day, n) in by_day(&tips)? { - if let Ok(day) = day.parse::() { + if let Ok(day) = day.parse::() { weeks.entry(monday_of(day)).or_default().tips += n; } } @@ -144,7 +145,7 @@ pub(crate) fn weeks(v: &View) -> Result> { v.clause ); for (day, n) in by_day(&tasks)? { - if let Ok(day) = day.parse::() { + if let Ok(day) = day.parse::() { weeks.entry(monday_of(day)).or_default().tasks += n; } } @@ -152,10 +153,10 @@ pub(crate) fn weeks(v: &View) -> Result> { } /// Last full week against the week before, once both have enough tasks to say. -pub(crate) fn trend(v: &View, today: NaiveDate) -> Result> { +pub(crate) fn trend(v: &View, today: Date) -> Result> { let weeks = weeks(v)?; - let week = |back: u64| { - let monday = monday_of(today).checked_sub_days(Days::new(7 * back))?; + let week = |back: i64| { + let monday = monday_of(today).checked_sub((7 * back).days()).ok()?; let w = weeks.get(&monday)?; // A task can take two tips, but "7 of 5 tasks" can't be read. (w.tasks >= MIN_TIP_WEEK).then(|| TipWeek { tips: w.tips.min(w.tasks), tasks: w.tasks }) @@ -183,7 +184,7 @@ pub(crate) fn top_tip(v: &View) -> Result> { impl Store { /// Whether tips are reaching your chats. `on_since` is the day they were turned on, if they're on. - pub fn tip_activity(&self, today: NaiveDate, on_since: Option) -> Result { + pub fn tip_activity(&self, today: Date, on_since: Option) -> Result { let conn = self.conn(); let active = conn.query_row( "SELECT COUNT(*) FROM tip_chats c JOIN sessions s ON s.id = c.session WHERE s.last_day >= ?1", @@ -193,8 +194,8 @@ impl Store { let tips = conn.query_row("SELECT COUNT(*) FROM tips", [], |r| r.get(0))?; let Some(on_since) = on_since else { return Ok(TipActivity { active, tips, blocked: false }) }; // Deleting the history also forgets which chats had the rules, so only what's after it can say. - let cleared = self.get_setting(CLEARED_KEY)?.and_then(|ts| ts.parse::>().ok()); - let since = cleared.map_or(on_since, |ts| on_since.max(ts.with_timezone(&Local).date_naive())); + let cleared = self.get_setting(CLEARED_KEY)?.and_then(|ts| ts.parse::().ok()); + let since = cleared.map_or(on_since, |ts| on_since.max(time::local_day(ts))); let last_told: Option = conn.query_row( "SELECT MAX(s.first_day) FROM sessions s JOIN tip_chats c ON c.session = s.id WHERE s.source = ?1 AND s.first_day >= ?2", @@ -213,7 +214,7 @@ impl Store { } /// The tip lines `stats --report-cards` prints, under `f`'s models and over all your history. - pub fn tip_summary(&self, f: &Filter, today: NaiveDate) -> Result<(Option, Option)> { + pub fn tip_summary(&self, f: &Filter, today: Date) -> Result<(Option, Option)> { let (clause, args) = Filter { since: None, ..f.clone() }.sql(); let v = View { conn: self.conn(), clause, args }; Ok((trend(&v, today)?, top_tip(&v)?)) diff --git a/deny.toml b/deny.toml index 99e3e68..19461c0 100644 --- a/deny.toml +++ b/deny.toml @@ -12,9 +12,6 @@ ignore = [ # glib 0.18's VariantStrIter is unsound. Tauri pins gtk-rs 0.18 on Linux, so it can't be # upgraded until Tauri moves; nothing here uses VariantStrIter. Drop this once glib >= 0.20. { id = "RUSTSEC-2024-0429", reason = "glib 0.18 is pinned by Tauri's GTK stack; VariantStrIter is unused" }, - # chrono is unmaintained (no known vulnerability). Moving to jiff touches every date in the app, - # so it gets its own change. Drop this once chrono is gone. - { id = "RUSTSEC-2026-0543", reason = "chrono unmaintained, no vulnerability; jiff migration planned separately" }, ] [licenses] diff --git a/plugins/grade/.claude-plugin/plugin.json b/plugins/grade/.claude-plugin/plugin.json index 284a748..d20c129 100644 --- a/plugins/grade/.claude-plugin/plugin.json +++ b/plugins/grade/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "grade", - "version": "0.5.8", + "version": "0.5.9", "description": "Report cards on how you prompt: type /grade:me for a letter grade, why, and how to ask so it's clear the first time. Works with the No, Actually... app to track your progress.", "author": { "name": "HTMLGuy LLC",