use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::Digest as _;
use crate::partition::PartitionId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Direction {
Higher,
Lower,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ObservedDimension {
pub dimension: String,
pub direction: Direction,
pub since: NaiveDate,
pub days: u32,
}
impl ObservedDimension {
pub fn new(
dimension: impl Into<String>,
direction: Direction,
since: NaiveDate,
days: u32,
) -> Self {
Self { dimension: dimension.into(), direction, since, days }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum Phrasing {
Template,
Model {
model: String,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Observation {
pub id: String,
pub partition: PartitionId,
pub as_of: NaiveDate,
pub dimensions: Vec<ObservedDimension>,
pub windows: Vec<u32>,
pub question: String,
pub phrasing: Phrasing,
pub created_at: DateTime<Utc>,
}
impl Observation {
pub fn id_for(partition: &PartitionId, as_of: NaiveDate) -> String {
let digest = sha2::Sha256::digest(partition.as_str().as_bytes());
format!("obs-{}-{}", as_of.format("%Y%m%d"), hex::encode(&digest[..4]))
}
pub fn statement(&self) -> String {
let since =
self.dimensions.iter().map(|dimension| dimension.since).min().unwrap_or(self.as_of);
let clauses: Vec<String> = self
.dimensions
.iter()
.map(|dimension| {
let (subject, higher, lower) = wording(&dimension.dimension);
let comparison = match dimension.direction {
Direction::Higher => higher,
Direction::Lower => lower,
};
format!("{subject} has been {comparison}")
})
.collect();
let changed = match clauses.as_slice() {
[] => "the routine has changed".to_string(),
[one] => one.clone(),
[rest @ .., last] => format!("{}, and {last}", rest.join(", ")),
};
format!("Since {since}, compared with the 28 days before: {changed}.")
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PassState {
pub partition: PartitionId,
pub last_day: NaiveDate,
#[serde(default)]
pub drift: Value,
#[serde(default)]
pub baselines: Value,
pub updated_at: DateTime<Utc>,
}
impl PassState {
pub fn new(
partition: impl Into<PartitionId>,
last_day: NaiveDate,
updated_at: DateTime<Utc>,
) -> Self {
Self {
partition: partition.into(),
last_day,
drift: Value::Null,
baselines: Value::Null,
updated_at,
}
}
}
const NOT_NEUTRAL: &[&str] = &[
"diagnos",
"burnout",
"burn out",
"burning out",
"burned out",
"burnt out",
"depress",
"anxi",
"stress",
"exhaust",
"fatigue",
"tired",
"unhealthy",
"health",
"sick",
"illness",
"disorder",
"addict",
"obsess",
"lazy",
"overwork",
"worr",
"concern",
"alarm",
"problem",
"wrong",
"bad ",
"should",
"must",
"need to",
"you are",
"you're",
"you have",
"symptom",
];
pub fn is_neutral_question(text: &str) -> bool {
let text = text.trim();
let lower = text.to_lowercase();
(20..=400).contains(&text.chars().count())
&& text.ends_with('?')
&& !text.contains(['\n', '\r'])
&& !NOT_NEUTRAL.iter().any(|word| lower.contains(word))
}
fn wording(dimension: &str) -> (String, &'static str, &'static str) {
match dimension {
"activity.last_minute" => ("the day's last activity".into(), "later", "earlier"),
"activity.first_minute" => ("the day's first activity".into(), "later", "earlier"),
_ => {
let (kind, measure) = dimension.split_once('.').unwrap_or((dimension, "count"));
let kind = match kind {
"intent" => "requests".to_string(),
"tool_call" => "tool calls".to_string(),
"approval" => "approvals".to_string(),
"rejection" => "rejections".to_string(),
"denial" => "denied calls".to_string(),
"held" => "held calls".to_string(),
"turn" => "turns".to_string(),
"wake" => "wake-ups".to_string(),
"proposal" => "proposals".to_string(),
"process" => "process changes".to_string(),
"spend" => "spend".to_string(),
other => other.replace('_', " "),
};
match measure {
"count" => (format!("the number of {kind}"), "higher", "lower"),
"duration_ms" => (format!("how long {kind} take"), "longer", "shorter"),
other => {
let key = other.strip_prefix("meta.").unwrap_or(other).replace('_', " ");
(format!("{kind} {key}"), "higher", "lower")
}
}
}
}
}
pub fn template_question(dimensions: &[ObservedDimension], windows: &[u32]) -> String {
let period = match windows.iter().copied().max().unwrap_or(14) {
0..=7 => "week".to_string(),
days if days % 7 == 0 => {
let weeks = days / 7;
let words = ["", "one", "two", "three", "four"];
match words.get(weeks as usize) {
Some(word) => format!("{word} weeks"),
None => format!("{weeks} weeks"),
}
}
days => format!("{days} days"),
};
let clauses: Vec<String> = dimensions
.iter()
.map(|dimension| {
let (subject, higher, lower) = wording(&dimension.dimension);
let comparison = match dimension.direction {
Direction::Higher => higher,
Direction::Lower => lower,
};
format!("{subject} has been {comparison} than usual")
})
.collect();
let changed = match clauses.as_slice() {
[] => String::new(),
[one] => format!(": {one}"),
[rest @ .., last] => format!(": {}, and {last}", rest.join(", ")),
};
format!(
"Your routine has changed over the last {period}{changed}. Would you like to review \
what changed?"
)
}
#[cfg(test)]
mod tests {
use super::*;
fn day(d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 10, d).unwrap()
}
#[test]
fn the_template_is_a_neutral_question_for_every_dimension_shape() {
let dimensions = [
ObservedDimension::new("activity.first_minute", Direction::Lower, day(1), 3),
ObservedDimension::new("tool_call.count", Direction::Higher, day(1), 3),
ObservedDimension::new("tool_call.duration_ms", Direction::Lower, day(1), 3),
ObservedDimension::new("turn.meta.cost_micro_usd", Direction::Higher, day(1), 3),
ObservedDimension::new("review_item.count", Direction::Lower, day(1), 3),
];
for windows in [[7, 14], [7, 7], [14, 28], [5, 10]] {
for take in 1..=dimensions.len() {
let question = template_question(&dimensions[..take], &windows);
assert!(is_neutral_question(&question), "{question}");
}
}
let question = template_question(&dimensions[..2], &[7, 14]);
assert_eq!(
question,
"Your routine has changed over the last two weeks: the day's first activity has \
been earlier than usual, and the number of tool calls has been higher than usual. \
Would you like to review what changed?"
);
}
#[test]
fn a_diagnosis_a_statement_or_an_instruction_is_not_neutral() {
for text in [
"You have been working late; this looks like burnout?",
"Is something wrong with your schedule lately?",
"Your routine changed over the last two weeks.",
"Review it?",
"Your evenings look stressful lately — want to talk about it?",
"Two lines\nwould you like to review what changed?",
] {
assert!(!is_neutral_question(text), "{text}");
}
}
#[test]
fn ids_are_per_partition_and_day() {
assert_ne!(
Observation::id_for(&"work".into(), day(1)),
Observation::id_for(&"home".into(), day(1))
);
assert_ne!(
Observation::id_for(&"work".into(), day(1)),
Observation::id_for(&"work".into(), day(2))
);
}
}