Habit (v0.2.0): local day, streak, reminder, medals #2

Merged
mnovak merged 1 commits from feature/habit into main 2026-11-17 11:58:28 +01:00
15 changed files with 822 additions and 9 deletions
+3 -1
View File
@@ -11,11 +11,13 @@ crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> on
writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote)
crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge
(sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format
crates/liber-habit Day 2: the local day (the only day computation in Liber), days read, the forgiving streak,
the reminder schedule, the medal rules (a pure function of the log)
fixtures-fetch/ sha256-pinned hostile corpora -> fixtures/fetched/ (never in git; the tests generate theirs)
docs/ FORMATS.md (formats, limits, positions, DRM), DEPENDENCIES.md (every crate, its licence)
scripts/deps.mjs regenerates the crate table in DEPENDENCIES.md; exits 1 on a licence outside the allowed set
```
Direction: `liber-library -> liber-format`. Neither crate opens files, sockets or reads the clock: bytes in, values
Direction: `liber-habit -> liber-library -> liber-format`. Neither crate opens files, sockets or reads the clock: bytes in, values
out; time and ids are parameters (`tests/purity.rs` checks the sources).
## Commands
Generated
+12 -2
View File
@@ -297,7 +297,7 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "liber-format"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"base64",
"chardetng",
@@ -315,9 +315,19 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "liber-habit"
version = "0.2.0"
dependencies = [
"liber-library",
"proptest",
"serde",
"serde_json",
]
[[package]]
name = "liber-library"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"csv",
"encoding_rs",
+2 -2
View File
@@ -1,9 +1,9 @@
[workspace]
resolver = "3"
members = ["crates/liber-format", "crates/liber-library"]
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit"]
[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
+1
View File
@@ -40,6 +40,7 @@ fn sources_have_no_io() {
let mut hits = Vec::new();
scan(&root.join("liber-format/src"), &mut hits);
scan(&root.join("liber-library/src"), &mut hits);
scan(&root.join("liber-habit/src"), &mut hits);
assert!(hits.is_empty(), "{hits:#?}");
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "liber-habit"
description = "Liber Domi: the local day, days read, the forgiving streak, the reminder schedule and the medal rules"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
liber-library = { path = "../liber-library" }
serde.workspace = true
[dev-dependencies]
proptest.workspace = true
serde_json.workspace = true
+314
View File
@@ -0,0 +1,314 @@
//! Liber's reading habit (the app's `docs/02_habit.md`): the local day, days read, the forgiving streak, the reminder
//! schedule and the medal rules. Pure: the time, the UTC offset and the rollover hour are always parameters, and this
//! crate is the only place in Liber that turns a moment into a day.
use liber_library::Library;
use liber_library::library::{DailyKind, HabitGoal, Outcome};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
const DAY_MS: i64 = 86_400_000;
/// A local day: days since 1970-01-01 in the reader's calendar.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct Day(pub i64);
impl Day {
/// Monday = 0 … Sunday = 6 (1970-01-01 was a Thursday).
pub fn weekday(self) -> u8 {
(self.0 + 3).rem_euclid(7) as u8
}
/// The Monday of this day's week.
pub fn week(self) -> Day {
Day(self.0 - self.weekday() as i64)
}
pub fn plus(self, n: i64) -> Day {
Day(self.0 + n)
}
/// `YYYY-MM-DD`.
pub fn date(self) -> String {
let z = self.0 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02}")
}
pub fn parse(date: &str) -> Option<Day> {
let d = liber_library::parse_date(date)?;
let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?);
Some(Day(liber_library::days_from_civil(y, m, dd)))
}
}
/// The local day a moment belongs to: its local time (UTC + `offset_min`) minus `rollover_hour`, so reading at
/// 01:30 with a 03:00 rollover counts for the evening before. **The only day computation in Liber.**
pub fn local_day(utc_ms: i64, offset_min: i32, rollover_hour: u8) -> Day {
let local = utc_ms + offset_min as i64 * 60_000 - rollover_hour.min(23) as i64 * 3_600_000;
Day(local.div_euclid(DAY_MS))
}
/// The day a session counts for: the day it started (a session across the rollover counts once). Sessions from before
/// Day 2 carry no offset and keep their stored date.
pub fn session_day(s: &liber_library::library::Session, rollover_hour: u8) -> Option<Day> {
match s.offset_min {
Some(o) => Some(local_day(s.start as i64, o, rollover_hour)),
None => Day::parse(&s.date),
}
}
/// What the reader did on each day: pages turned and active minutes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct DayLog {
pub pages: u32,
pub active_ms: u64,
}
pub fn goal(lib: &Library) -> HabitGoal {
lib.habit.unwrap_or_default()
}
pub fn met(g: &HabitGoal, d: &DayLog) -> bool {
match g.kind {
DailyKind::Pages => d.pages >= g.amount.max(1),
DailyKind::Minutes => d.active_ms >= g.amount.max(1) as u64 * 60_000,
}
}
/// Every day with reading, summed over its sessions.
pub fn day_logs(lib: &Library) -> BTreeMap<Day, DayLog> {
let g = goal(lib);
let mut out: BTreeMap<Day, DayLog> = BTreeMap::new();
for s in lib.sessions.values() {
if let Some(d) = session_day(s, g.rollover_hour) {
let e = out.entry(d).or_default();
e.pages = e.pages.saturating_add(s.pages);
e.active_ms = e.active_ms.saturating_add(s.active_ms);
}
}
out
}
/// The days the goal was met.
pub fn days_read(lib: &Library) -> BTreeSet<Day> {
let g = goal(lib);
day_logs(lib).into_iter().filter(|(_, l)| met(&g, l)).map(|(d, _)| d).collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Mark {
Read,
/// A missed day the week forgives (the first in its week).
Forgiven,
/// A second missed day in a week: the streak ended here.
Missed,
/// Today, not read yet (not a miss until it is over).
Today,
/// Before the first day read, or after today.
None,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Habit {
pub today: String,
pub today_met: bool,
pub today_log: DayLog,
pub goal: HabitGoal,
/// Days read, ever. Never goes down.
pub total_days: u32,
/// Consecutive weeks (Monday–Sunday, this one included) with at most one missed day.
pub streak_weeks: u32,
/// The last weeks, oldest first, Monday first.
pub calendar: Vec<[Mark; 7]>,
}
fn mark(days: &BTreeSet<Day>, first: Option<Day>, today: Day, d: Day, misses_before: &mut u8) -> Mark {
let Some(first) = first else { return if d == today { Mark::Today } else { Mark::None } };
if d > today || d < first {
return Mark::None;
}
if days.contains(&d) {
return Mark::Read;
}
if d == today {
return Mark::Today;
}
*misses_before += 1;
if *misses_before == 1 { Mark::Forgiven } else { Mark::Missed }
}
/// The habit as of `today` (computed with [`local_day`]), with a calendar of the last `weeks` weeks.
pub fn habit(lib: &Library, today: Day, weeks: usize) -> Habit {
let g = goal(lib);
let logs = day_logs(lib);
let days: BTreeSet<Day> = logs.iter().filter(|(_, l)| met(&g, l)).map(|(d, _)| *d).collect();
let first = days.iter().next().copied();
// Streak: back from this week while a week has at most one missed day.
let mut streak = 0u32;
if let Some(f) = first {
let mut w = today.week();
while w.plus(6) >= f {
let mut misses = 0u8;
for i in 0..7 {
let d = w.plus(i);
if d >= f && d < today && !days.contains(&d) {
misses += 1;
}
}
if misses >= 2 {
break;
}
streak += 1;
w = w.plus(-7);
}
}
let mut calendar = Vec::with_capacity(weeks);
let start = today.week().plus(-7 * (weeks.max(1) as i64 - 1));
for k in 0..weeks.max(1) {
let w = start.plus(7 * k as i64);
let mut misses = 0u8;
let mut row = [Mark::None; 7];
for (i, slot) in row.iter_mut().enumerate() {
*slot = mark(&days, first, today, w.plus(i as i64), &mut misses);
}
calendar.push(row);
}
let today_log = logs.get(&today).copied().unwrap_or_default();
Habit {
today: today.date(),
today_met: met(&g, &today_log),
today_log,
goal: g,
total_days: days.len() as u32,
streak_weeks: streak,
calendar,
}
}
/// The reminder: one local notification at `minute` (0–1439) local time, off by default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct Reminder {
pub enabled: bool,
pub minute: u16,
}
/// When the next reminder should fire, as (day, minute of the local day): today if the goal is not met and the time is
/// still ahead, else tomorrow. `None` when the reminder is off. Never today when today's goal is met.
pub fn next_reminder(r: &Reminder, today: Day, now_minute: u16, today_met: bool) -> Option<(Day, u16)> {
if !r.enabled {
return None;
}
let m = r.minute.min(1439);
if !today_met && now_minute < m { Some((today, m)) } else { Some((today.plus(1), m)) }
}
/// The medals, in this order (docs/02_habit.md). `available: false`: earned from a later Liber version on.
pub const MEDALS: &[(&str, &str, bool)] = &[
("first-book", "First book finished", true),
("days-7", "Seven days read", true),
("days-30", "Thirty days read", true),
("days-100", "A hundred days read", true),
("days-365", "A year of days read", true),
("books-10", "Ten books", true),
("books-50", "Fifty books", true),
("books-100", "A hundred books", true),
("first-reread", "A book read again", true),
("let-go", "Let a book go", true),
("five-moods", "Five moods", true),
("other-language", "A book in another language", false),
("heard-aloud", "A chapter heard aloud", false),
("buddy-read", "Read with a friend", false),
];
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Medal {
pub id: &'static str,
pub name: &'static str,
pub available: bool,
/// The day it was earned (`YYYY-MM-DD`), `"earlier"` for an imported history without dates, `None` if not yet.
pub earned: Option<String>,
pub seen: bool,
}
/// The medals: a pure function of the library. Recomputing gives the same value, so medals never drift between devices
/// or versions; only "seen" is stored.
pub fn medals(lib: &Library) -> Vec<Medal> {
let days: Vec<Day> = days_read(lib).into_iter().collect();
// Finished reads, dated ones in date order, then undated (imported) ones.
struct Fin {
date: Option<String>,
book: String,
outcome: Outcome,
}
let mut fins: Vec<Fin> = Vec::new();
for b in lib.books.values() {
for r in &b.reads {
if let Some(o) = r.outcome {
fins.push(Fin { date: r.finished.clone(), book: b.id.clone(), outcome: o });
}
}
}
fins.sort_by(|a, b| match (&a.date, &b.date) {
(Some(x), Some(y)) => x.cmp(y).then(a.book.cmp(&b.book)),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => a.book.cmp(&b.book),
});
let when = |f: &Fin| Some(f.date.clone().unwrap_or_else(|| "earlier".into()));
let read: Vec<&Fin> = fins.iter().filter(|f| f.outcome == Outcome::Read).collect();
let nth_book = |n: usize| read.get(n - 1).and_then(|f| when(f));
let nth_day = |n: usize| days.get(n - 1).map(|d| d.date());
let reread = {
let mut seen = BTreeSet::new();
read.iter().find(|f| !seen.insert(f.book.clone())).and_then(|f| when(f))
};
let let_go = fins.iter().find(|f| f.outcome == Outcome::DidNotFinish).and_then(when);
let five_moods = {
let mut moods = BTreeSet::new();
let mut at = None;
for f in &read {
if let Some(b) = lib.books.get(&f.book) {
moods.extend(b.moods.iter().cloned());
}
if moods.len() >= 5 {
at = when(f);
break;
}
}
at
};
MEDALS
.iter()
.map(|&(id, name, available)| {
let earned = match id {
"first-book" => nth_book(1),
"days-7" => nth_day(7),
"days-30" => nth_day(30),
"days-100" => nth_day(100),
"days-365" => nth_day(365),
"books-10" => nth_book(10),
"books-50" => nth_book(50),
"books-100" => nth_book(100),
"first-reread" => reread.clone(),
"let-go" => let_go.clone(),
"five-moods" => five_moods.clone(),
_ => None,
};
Medal { id, name, available, earned, seen: lib.medals_seen.contains(id) }
})
.collect()
}
/// Medals earned and not shown yet: what the end of a reading session reveals (at most one at a time).
pub fn unseen(lib: &Library) -> Vec<Medal> {
medals(lib).into_iter().filter(|m| m.earned.is_some() && !m.seen).collect()
}
+84
View File
@@ -0,0 +1,84 @@
#![allow(dead_code)]
use liber_library::library::BookInfo;
use liber_library::{Clock, Event, Library, Op};
/// Europe/Prague's UTC offset at a moment (minutes): CEST from the last Sunday of March 01:00 UTC to the last Sunday of
/// October 01:00 UTC, CET otherwise. Written out here because the core has no time-zone database by design.
pub fn prague(utc_ms: i64) -> i32 {
let day = utc_ms.div_euclid(86_400_000);
let (y, _, _) = civil(day);
let last_sunday = |m: u32| {
let last = liber_library::days_from_civil(y, m, 31);
last - ((last + 3).rem_euclid(7) - 6).rem_euclid(7)
};
let start = last_sunday(3) * 86_400_000 + 3_600_000;
let end = last_sunday(10) * 86_400_000 + 3_600_000;
if utc_ms >= start && utc_ms < end { 120 } else { 60 }
}
pub fn civil(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(yoe + era * 400 + i64::from(m <= 2), m, d)
}
/// A library with one book and the given events after it.
pub struct Log {
pub events: Vec<Event>,
clock: Clock,
n: u32,
}
impl Log {
pub fn new() -> Log {
let mut l = Log { events: vec![], clock: Clock::default(), n: 0 };
l.push(Op::BookAdd {
book: "b".into(),
info: BookInfo { title: "Kniha".into(), ..BookInfo::default() },
restore: false,
});
l
}
pub fn push(&mut self, op: Op) {
self.n += 1;
let hlc = self.clock.tick(self.n as u64);
self.events.push(Event { id: format!("e{}", self.n), hlc, device: "d".into(), op });
}
/// A session starting at `utc_ms` in Prague, `pages` turned.
pub fn read_at(&mut self, utc_ms: i64, pages: u32) {
let n = self.n;
self.push(Op::Session {
id: format!("s{n}"),
book: "b".into(),
start: utc_ms as u64,
end: utc_ms as u64 + 600_000,
active_ms: 300_000,
pages,
date: String::new(),
offset_min: Some(prague(utc_ms)),
});
}
/// One page read at 20:00 Prague time on `day`.
pub fn read_day(&mut self, day: liber_habit::Day) {
let utc = day.0 * 86_400_000 + 20 * 3_600_000;
self.read_at(utc - prague(utc) as i64 * 60_000, 1);
}
pub fn lib(&self) -> Library {
Library::from_events(&self.events)
}
}
/// 2026-03-02 (a Monday) as a local day.
pub fn monday() -> liber_habit::Day {
liber_habit::Day::parse("2026-03-02").unwrap()
}
+88
View File
@@ -0,0 +1,88 @@
//! Mandatory test 1: every session maps to exactly one local day; DST changes in both directions (Europe/Prague)
//! neither skip nor double a day; a session spanning the rollover counts once.
mod common;
use common::*;
use liber_habit::{Day, local_day};
use proptest::prelude::*;
const H: i64 = 3_600_000;
#[test]
fn the_prague_model_switches_on_the_right_days() {
// 2026: summer time from 29 March 01:00 UTC to 25 October 01:00 UTC.
let at = |d: &str, h: i64| Day::parse(d).unwrap().0 * 86_400_000 + h * H;
assert_eq!(prague(at("2026-03-29", 0) + 59 * 60_000), 60);
assert_eq!(prague(at("2026-03-29", 1)), 120);
assert_eq!(prague(at("2026-10-25", 0) + 59 * 60_000), 120);
assert_eq!(prague(at("2026-10-25", 1)), 60);
}
#[test]
fn rollover_puts_after_midnight_on_the_evening_before() {
// 01:30 on 15 Nov (Prague, CET) is 00:30 UTC.
let t = Day::parse("2026-11-15").unwrap().0 * 86_400_000 + 30 * 60_000;
assert_eq!(local_day(t, 60, 3).date(), "2026-11-14");
assert_eq!(local_day(t, 60, 0).date(), "2026-11-15");
// 03:30 local is the new day.
assert_eq!(local_day(t + 2 * H, 60, 3).date(), "2026-11-15");
}
fn walk_hours(from_day: &str, days: i64, rollover: u8) {
let start = Day::parse(from_day).unwrap().0 * 86_400_000;
let mut prev: Option<Day> = None;
let mut hours_per_day = std::collections::BTreeMap::new();
for h in 0..days * 24 {
let t = start + h * H;
let d = local_day(t, prague(t), rollover);
if let Some(p) = prev {
assert!(
d.0 - p.0 == 0 || d.0 - p.0 == 1,
"{} → {} at hour {h}: a day was skipped or went back",
p.date(),
d.date()
);
}
*hours_per_day.entry(d).or_insert(0) += 1;
prev = Some(d);
}
let inner: Vec<_> = hours_per_day.iter().skip(1).take(hours_per_day.len().saturating_sub(2)).collect();
for (d, n) in inner {
assert!((23..=25).contains(n), "{} has {n} hours", d.date());
}
}
#[test]
fn dst_in_both_directions_skips_and_doubles_nothing() {
for rollover in [0, 3, 5] {
walk_hours("2026-03-26", 7, rollover); // spring forward
walk_hours("2026-10-22", 7, rollover); // fall back
}
}
#[test]
fn a_session_across_the_rollover_counts_once_for_its_start() {
let mut log = Log::new();
// 02:30 to 03:40 Prague (CET): starts before the 03:00 rollover.
let start = Day::parse("2026-11-15").unwrap().0 * 86_400_000 + (2 * 60 + 30 - 60) * 60_000;
log.read_at(start, 1);
let days = liber_habit::days_read(&log.lib());
assert_eq!(days.iter().map(|d| d.date()).collect::<Vec<_>>(), vec!["2026-11-14"]);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 2000, ..ProptestConfig::default() })]
#[test]
fn every_moment_has_exactly_one_day_and_it_is_consistent(ms in 0i64..4_102_444_800_000, rollover in 0u8..=6) {
let off = prague(ms);
let d = local_day(ms, off, rollover);
// The same moment always gives the same day, and the day contains the moment's shifted local time.
prop_assert_eq!(local_day(ms, off, rollover), d);
let local = ms + off as i64 * 60_000 - rollover as i64 * H;
prop_assert!(local >= d.0 * 86_400_000 && local < (d.0 + 1) * 86_400_000);
// An hour later is the same day or the next, never another.
let d2 = local_day(ms + H, prague(ms + H), rollover);
prop_assert!(d2.0 == d.0 || d2.0 == d.0 + 1);
prop_assert_eq!(Day::parse(&d.date()), Some(d));
}
}
+121
View File
@@ -0,0 +1,121 @@
//! Mandatory tests 3 and 4: medals recomputed give byte-identical results; an imported Goodreads history earns
//! book-count medals and no day medals; the reminder never fires when it is off or the goal is met.
mod common;
use common::*;
use liber_habit::{Reminder, medals, next_reminder, unseen};
use liber_library::Op;
use liber_library::library::{Field, Outcome};
use serde_json::json;
fn earned(lib: &liber_library::Library) -> Vec<(String, String)> {
medals(lib).into_iter().filter_map(|m| m.earned.map(|e| (m.id.to_owned(), e))).collect()
}
#[test]
fn recomputing_gives_byte_identical_medals() {
let mut log = Log::new();
let m = monday();
for d in 0..40 {
log.read_day(m.plus(d));
}
log.push(Op::ReadStart { book: "b".into(), read: "r1".into(), date: Some("2026-03-02".into()) });
log.push(Op::ReadEnd { read: "r1".into(), date: Some("2026-03-20".into()), outcome: Outcome::Read });
let a = serde_json::to_vec(&medals(&log.lib())).unwrap();
let b = serde_json::to_vec(&medals(&log.lib())).unwrap();
assert_eq!(a, b);
// Rebuilt from the same events in another order: the same bytes.
let mut rev = log.events.clone();
rev.reverse();
assert_eq!(serde_json::to_vec(&medals(&liber_library::Library::from_events(&rev))).unwrap(), a);
let e = earned(&log.lib());
assert!(e.contains(&("days-7".into(), m.plus(6).date())));
assert!(e.contains(&("days-30".into(), m.plus(29).date())));
assert!(e.contains(&("first-book".into(), "2026-03-20".into())));
assert!(!e.iter().any(|(id, _)| id == "days-100"));
}
#[test]
fn an_imported_history_earns_book_medals_and_no_day_medals() {
// Goodreads: twelve books read, one of them twice, one abandoned; no reading sessions at all.
let mut csv =
String::from("Book Id,Title,Author,ISBN,ISBN13,My Rating,Date Read,Date Added,Exclusive Shelf,Read Count\n");
for i in 0..12 {
csv.push_str(&format!(
"{i},Kniha {i},Autor {i},,,4,2024/0{}/1{i},2024/01/01,read,{}\n",
1 + i % 9,
if i == 3 { 2 } else { 1 }
));
}
csv.push_str("99,Opuštěná,Autor,,,0,,2024/01/01,read,1\n");
let mut n = 0;
let (ops, report) = liber_library::import::import_csv(
csv.as_bytes(),
&Default::default(),
&mut || {
n += 1;
format!("id{n}")
},
0,
)
.unwrap();
assert_eq!(report.imported, 13);
let mut log = Log::new();
for op in ops {
log.push(op);
}
// StoryGraph-style: one did-not-finish.
log.push(Op::ReadStart { book: "b".into(), read: "dnf".into(), date: None });
log.push(Op::ReadEnd { read: "dnf".into(), date: Some("2024-05-01".into()), outcome: Outcome::DidNotFinish });
let lib = log.lib();
let e = earned(&lib);
let ids: Vec<&str> = e.iter().map(|(i, _)| i.as_str()).collect();
assert!(ids.contains(&"first-book"), "{ids:?}");
assert!(ids.contains(&"books-10"));
assert!(ids.contains(&"first-reread"));
assert!(ids.contains(&"let-go"));
assert!(!ids.iter().any(|i| i.starts_with("days-")), "no fake days: {ids:?}");
assert_eq!(liber_habit::habit(&lib, monday(), 1).total_days, 0);
}
#[test]
fn five_moods_and_seen_medals() {
let mut log = Log::new();
log.push(Op::BookSet {
book: "b".into(),
field: Field::Moods,
value: json!(["dark", "tense", "sad", "funny", "hopeful"]),
base: None,
});
log.push(Op::ReadStart { book: "b".into(), read: "r".into(), date: None });
log.push(Op::ReadEnd { read: "r".into(), date: Some("2026-01-05".into()), outcome: Outcome::Read });
let lib = log.lib();
assert!(earned(&lib).contains(&("five-moods".into(), "2026-01-05".into())));
assert_eq!(unseen(&lib).len(), 2, "first book and five moods");
log.push(Op::MedalSeen { medal: "first-book".into() });
let lib = log.lib();
assert_eq!(unseen(&lib).iter().map(|m| m.id).collect::<Vec<_>>(), vec!["five-moods"]);
assert!(
medals(&lib).iter().filter(|m| !m.available).all(|m| m.earned.is_none()),
"later medals cannot be earned yet"
);
}
#[test]
fn the_reminder_is_quiet_when_off_or_when_the_goal_is_met() {
let today = monday();
let off = Reminder { enabled: false, minute: 20 * 60 };
let on = Reminder { enabled: true, minute: 20 * 60 };
for met in [false, true] {
for now in [0u16, 600, 1199, 1200, 1439] {
assert_eq!(next_reminder(&off, today, now, met), None);
let next = next_reminder(&on, today, now, met).unwrap();
if met {
assert_ne!(next.0, today, "never today when today's goal is met");
}
assert_eq!(next.1, 1200);
}
}
assert_eq!(next_reminder(&on, today, 600, false), Some((today, 1200)));
assert_eq!(next_reminder(&on, today, 1300, false), Some((today.plus(1), 1200)));
}
+106
View File
@@ -0,0 +1,106 @@
//! Mandatory test 2: one miss per week keeps the streak; two misses in one week end it; the total never decreases.
mod common;
use common::*;
use liber_habit::{Mark, habit};
use liber_library::Op;
use liber_library::library::{DailyKind, HabitGoal};
use proptest::prelude::*;
#[test]
fn one_miss_a_week_keeps_the_streak() {
let mut log = Log::new();
let m = monday();
// Four weeks, each missing one day (Wednesday).
for w in 0..4 {
for d in 0..7 {
if d != 2 {
log.read_day(m.plus(w * 7 + d));
}
}
}
let today = m.plus(4 * 7); // the next Monday, not read yet
let h = habit(&log.lib(), today, 5);
assert_eq!(h.streak_weeks, 5, "four weeks with one miss each, and this week so far");
assert_eq!(h.total_days, 24);
assert!(!h.today_met);
assert_eq!(h.calendar[0][2], Mark::Forgiven);
assert_eq!(h.calendar[4][0], Mark::Today, "today is not a miss");
}
#[test]
fn a_second_miss_in_a_week_ends_the_streak_but_not_the_total() {
let mut log = Log::new();
let m = monday();
for d in 0..14 {
if d != 9 && d != 10 {
log.read_day(m.plus(d));
}
}
let today = m.plus(14);
let h = habit(&log.lib(), today, 3);
assert_eq!(h.streak_weeks, 1, "only this week counts again");
assert_eq!(h.total_days, 12);
assert_eq!(h.calendar[1][2], Mark::Forgiven);
assert_eq!(h.calendar[1][3], Mark::Missed);
}
#[test]
fn days_before_the_first_day_are_not_misses() {
let mut log = Log::new();
let m = monday();
for d in 4..7 {
log.read_day(m.plus(d));
}
let h = habit(&log.lib(), m.plus(6), 1);
assert_eq!(h.streak_weeks, 1);
assert_eq!(h.calendar[0][0], Mark::None);
assert!(h.today_met);
}
#[test]
fn the_goal_decides_what_a_day_is() {
let mut log = Log::new();
let m = monday();
log.read_day(m); // one page, 5 active minutes
log.push(Op::HabitGoal { goal: HabitGoal { kind: DailyKind::Minutes, amount: 10, rollover_hour: 3 } });
assert_eq!(habit(&log.lib(), m, 1).total_days, 0, "5 minutes are not 10");
log.push(Op::HabitGoal { goal: HabitGoal { kind: DailyKind::Pages, amount: 1, rollover_hour: 3 } });
assert_eq!(habit(&log.lib(), m, 1).total_days, 1);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 300, ..ProptestConfig::default() })]
/// Adding reading, or letting time pass, never lowers the total.
#[test]
fn the_total_never_decreases(read in prop::collection::vec(any::<bool>(), 1..120), extra in 0usize..120, later in 0i64..60) {
let m = monday();
let mut log = Log::new();
for (i, r) in read.iter().enumerate() {
if *r { log.read_day(m.plus(i as i64)); }
}
let today = m.plus(read.len() as i64);
let before = habit(&log.lib(), today, 1).total_days;
prop_assert!(habit(&log.lib(), today.plus(later), 1).total_days >= before);
log.read_day(m.plus(extra as i64));
prop_assert!(habit(&log.lib(), today.plus(later), 1).total_days >= before);
// And the streak is never more than the weeks since the first day read.
let h = habit(&log.lib(), today, 1);
let weeks = (today.week().0 - m.week().0) / 7 + 1;
prop_assert!(h.streak_weeks as i64 <= weeks);
}
/// A random history with at most one miss in every week keeps the streak across all its weeks.
#[test]
fn one_miss_per_week_anywhere_keeps_it(misses in prop::collection::vec(0u8..8, 2..20)) {
let m = monday();
let mut log = Log::new();
for (w, miss) in misses.iter().enumerate() {
for d in 0..7u8 {
if *miss != d { log.read_day(m.plus(w as i64 * 7 + d as i64)); }
}
}
let today = m.plus(misses.len() as i64 * 7);
prop_assert_eq!(habit(&log.lib(), today, 1).streak_weeks as usize, misses.len() + 1);
}
}
+12 -1
View File
@@ -1,6 +1,6 @@
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person};
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, HabitGoal, Mark, Outcome, Person};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
@@ -151,10 +151,21 @@ pub enum Op {
active_ms: u64,
pages: u32,
date: String,
/// The device's UTC offset at `start`, in minutes (Day 2); `None` for older sessions.
#[serde(default, skip_serializing_if = "Option::is_none")]
offset_min: Option<i32>,
},
Goal {
year: i32,
kind: GoalKind,
target: u32,
},
/// The daily habit (Day 2): what counts as a day read, and when a day rolls over. Follows the person.
HabitGoal {
goal: HabitGoal,
},
/// A medal was shown (Day 2). Medals themselves are computed from the log, never stored.
MedalSeen {
medal: String,
},
}
+7
View File
@@ -177,11 +177,18 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
active_ms: s.active_ms,
pages: s.pages,
date: s.date.clone(),
offset_min: s.offset_min,
});
}
for g in lib.goals.values() {
ops.push(Op::Goal { year: g.year, kind: g.kind, target: g.target });
}
if let Some(h) = lib.habit {
ops.push(Op::HabitGoal { goal: h });
}
for m in &lib.medals_seen {
ops.push(Op::MedalSeen { medal: m.clone() });
}
ops
}
+50 -3
View File
@@ -278,8 +278,33 @@ pub struct Session {
pub end: u64,
pub active_ms: u64,
pub pages: u32,
/// The local day it counts for (`YYYY-MM-DD`, from the device).
/// The local day it counts for (`YYYY-MM-DD`): from `liber_habit::local_day` since Day 2.
pub date: String,
/// The device's UTC offset at `start`, minutes east of UTC (Day 2).
#[serde(default)]
pub offset_min: Option<i32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DailyKind {
Pages,
Minutes,
}
/// What counts as a day read (Day 2). Default: one page, days rolling over at 03:00.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HabitGoal {
pub kind: DailyKind,
pub amount: u32,
pub rollover_hour: u8,
}
impl Default for HabitGoal {
fn default() -> Self {
HabitGoal { kind: DailyKind::Pages, amount: 1, rollover_hour: 3 }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -297,6 +322,12 @@ pub struct Library {
pub highlights: BTreeMap<String, Highlight>,
pub sessions: BTreeMap<String, Session>,
pub goals: BTreeMap<i32, Goal>,
/// The daily habit; `None` means the default (one page, 03:00).
#[serde(default)]
pub habit: Option<HabitGoal>,
/// Medals already shown (the medals are computed, see `liber_habit::medals`).
#[serde(default)]
pub medals_seen: BTreeSet<String>,
#[serde(skip)]
aliases: BTreeMap<String, String>,
#[serde(skip)]
@@ -313,7 +344,12 @@ pub struct Library {
impl PartialEq for Library {
fn eq(&self, o: &Library) -> bool {
self.books == o.books && self.highlights == o.highlights && self.sessions == o.sessions && self.goals == o.goals
self.books == o.books
&& self.highlights == o.highlights
&& self.sessions == o.sessions
&& self.goals == o.goals
&& self.habit == o.habit
&& self.medals_seen == o.medals_seen
}
}
@@ -638,7 +674,7 @@ impl Library {
self.highlights.remove(id);
self.removed_highlights.insert(id.clone());
}
Op::Session { id, book, start, end, active_ms, pages, date } => {
Op::Session { id, book, start, end, active_ms, pages, date, offset_min } => {
let c = self.canonical(book);
if self.books.contains_key(&c) && end >= start {
self.sessions.entry(id.clone()).or_insert(Session {
@@ -649,12 +685,23 @@ impl Library {
active_ms: (*active_ms).min(end - start),
pages: *pages,
date: date.clone(),
offset_min: offset_min.filter(|o| (-14 * 60..=14 * 60).contains(o)),
});
}
}
Op::Goal { year, kind, target } => {
self.goals.insert(*year, Goal { year: *year, kind: *kind, target: *target });
}
Op::HabitGoal { goal } => {
if goal.amount >= 1 && goal.amount <= 10_000 && goal.rollover_hour <= 12 {
self.habit = Some(*goal);
}
}
Op::MedalSeen { medal } => {
if medal.len() <= 64 {
self.medals_seen.insert(medal.clone());
}
}
}
}
}
+1
View File
@@ -83,6 +83,7 @@ pub fn op(r: &mut Rng, dev: &str, n: usize) -> Op {
},
13 => Op::Return { loan: format!("l-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), date },
14 => Op::Session {
offset_min: None,
id: format!("s-{dev}-{n}"),
book,
start: 1000,
+2
View File
@@ -32,6 +32,7 @@ fn yearly_and_all_time() {
e(Op::ReadStart { book: "a".into(), read: "r4".into(), date: Some("2026-01-01".into()) }),
e(Op::ReadEnd { read: "r4".into(), date: Some("2026-01-20".into()), outcome: Outcome::Read }),
e(Op::Session {
offset_min: None,
id: "s1".into(),
book: "a".into(),
start: 0,
@@ -41,6 +42,7 @@ fn yearly_and_all_time() {
date: "2025-01-10".into(),
}),
e(Op::Session {
offset_min: None,
id: "s2".into(),
book: "b".into(),
start: 0,