adk_kernel/proc/observation.rs
1//! Observations and the state a baseline pass carries between days (spec 3.2 §7.10,
2//! §9.2 K-I20).
3//!
4//! An observation is offered to the person as a question in neutral language, never a
5//! diagnosis. It names the dimensions that changed, which way and since when, and the
6//! comparison windows; it carries no value that identifies content (§9.3).
7
8use chrono::{DateTime, NaiveDate, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use sha2::Digest as _;
12
13use crate::partition::PartitionId;
14
15/// Which way a dimension moved from its baseline (spec 3.2 §7.10).
16///
17/// # Example
18///
19/// ```rust
20/// use adk_kernel::proc::Direction;
21///
22/// assert_eq!(serde_json::to_value(Direction::Higher).unwrap(), "higher");
23/// ```
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26#[non_exhaustive]
27pub enum Direction {
28 /// Above the baseline: later, more or longer.
29 Higher,
30 /// Below the baseline: earlier, fewer or shorter.
31 Lower,
32}
33
34/// One dimension an observation names (spec 3.2 §7.10).
35///
36/// # Example
37///
38/// ```rust
39/// use adk_kernel::proc::{Direction, ObservedDimension};
40/// use chrono::NaiveDate;
41///
42/// let since = NaiveDate::from_ymd_opt(2026, 10, 12).unwrap();
43/// let dimension = ObservedDimension::new("activity.last_minute", Direction::Higher, since, 10);
44/// assert_eq!(dimension.days, 10);
45/// ```
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "camelCase")]
48#[non_exhaustive]
49pub struct ObservedDimension {
50 /// The dimension, such as `activity.last_minute` or `tool_call.count`.
51 pub dimension: String,
52 /// Which way it moved.
53 pub direction: Direction,
54 /// The first day of its run of deviating days.
55 pub since: NaiveDate,
56 /// The run's length in days.
57 pub days: u32,
58}
59
60impl ObservedDimension {
61 /// A dimension that moved `direction` for `days` days from `since`.
62 pub fn new(
63 dimension: impl Into<String>,
64 direction: Direction,
65 since: NaiveDate,
66 days: u32,
67 ) -> Self {
68 Self { dimension: dimension.into(), direction, since, days }
69 }
70}
71
72/// Who worded an observation's question (spec 3.2 §7.10): the model phrases only what the
73/// deterministic detection found, and the kernel's template words it when the model is
74/// unavailable, over budget, or answers with anything but a neutral question.
75///
76/// # Example
77///
78/// ```rust
79/// use adk_kernel::proc::Phrasing;
80///
81/// let json = serde_json::to_value(Phrasing::Model { model: "gemini-3.5-flash-lite".into() }).unwrap();
82/// assert_eq!(json["model"]["model"], "gemini-3.5-flash-lite");
83/// assert_eq!(serde_json::to_value(Phrasing::Template).unwrap(), "template");
84/// ```
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
87#[non_exhaustive]
88pub enum Phrasing {
89 /// The kernel's template ([`template_question`]).
90 Template,
91 /// A model.
92 Model {
93 /// The model's name.
94 model: String,
95 },
96}
97
98/// A change in a partition's routine the kernel noticed, offered as a question (spec 3.2
99/// §7.10, K-I20).
100///
101/// It is recorded only after the warm-up, when the deviating dimensions are meaningful
102/// (two dimensions, or one for ten days) and out of their seven-day cooldown, and its
103/// [`question`](Self::question) passes [`is_neutral_question`].
104///
105/// # Example
106///
107/// ```rust
108/// use adk_kernel::proc::Observation;
109/// use chrono::NaiveDate;
110///
111/// let day = NaiveDate::from_ymd_opt(2026, 10, 22).unwrap();
112/// let id = Observation::id_for(&"work".into(), day);
113/// assert!(id.starts_with("obs-20261022-"));
114/// assert_eq!(id, Observation::id_for(&"work".into(), day));
115/// ```
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118#[non_exhaustive]
119pub struct Observation {
120 /// `obs-<yyyymmdd>-<partition digest>`: one per partition and day, so replicas that
121 /// both record it write one.
122 pub id: String,
123 /// The partition.
124 pub partition: PartitionId,
125 /// The local day the deviation test ran on.
126 pub as_of: NaiveDate,
127 /// The dimensions that changed, sorted by name.
128 pub dimensions: Vec<ObservedDimension>,
129 /// The comparison windows, in days.
130 pub windows: Vec<u32>,
131 /// The question offered to the person.
132 pub question: String,
133 /// Who worded it.
134 pub phrasing: Phrasing,
135 /// When the kernel recorded it.
136 pub created_at: DateTime<Utc>,
137}
138
139impl Observation {
140 /// The id of the observation of `partition` on `as_of`.
141 pub fn id_for(partition: &PartitionId, as_of: NaiveDate) -> String {
142 let digest = sha2::Sha256::digest(partition.as_str().as_bytes());
143 format!("obs-{}-{}", as_of.format("%Y%m%d"), hex::encode(&digest[..4]))
144 }
145
146 /// What the observation found, as a statement a person confirms (spec 3.2 §7.10): the
147 /// day the earliest deviating run began and each dimension's direction against the
148 /// 28-day baseline, built from the dimension names alone. A confirmed observation is
149 /// remembered as this text.
150 ///
151 /// # Example
152 ///
153 /// ```rust
154 /// use adk_kernel::proc::Observation;
155 ///
156 /// let observation: Observation = serde_json::from_value(serde_json::json!({
157 /// "id": "obs-20261022-37a8eec1",
158 /// "partition": "default",
159 /// "asOf": "2026-10-22",
160 /// "dimensions": [{ "dimension": "activity.last_minute", "direction": "higher", "since": "2026-10-13", "days": 10 }],
161 /// "windows": [7, 14],
162 /// "question": "Your routine has changed over the last two weeks. Would you like to review what changed?",
163 /// "phrasing": "template",
164 /// "createdAt": "2026-10-23T00:05:00Z",
165 /// }))
166 /// .unwrap();
167 /// assert_eq!(
168 /// observation.statement(),
169 /// "Since 2026-10-13, compared with the 28 days before: the day's last activity has been later."
170 /// );
171 /// ```
172 pub fn statement(&self) -> String {
173 let since =
174 self.dimensions.iter().map(|dimension| dimension.since).min().unwrap_or(self.as_of);
175 let clauses: Vec<String> = self
176 .dimensions
177 .iter()
178 .map(|dimension| {
179 let (subject, higher, lower) = wording(&dimension.dimension);
180 let comparison = match dimension.direction {
181 Direction::Higher => higher,
182 Direction::Lower => lower,
183 };
184 format!("{subject} has been {comparison}")
185 })
186 .collect();
187 let changed = match clauses.as_slice() {
188 [] => "the routine has changed".to_string(),
189 [one] => one.clone(),
190 [rest @ .., last] => format!("{}, and {last}", rest.join(", ")),
191 };
192 format!("Since {since}, compared with the 28 days before: {changed}.")
193 }
194}
195
196/// What a baseline pass carries for a partition from one day to the next (spec 3.2
197/// §7.10): the last day it tested, the drift state (each deviating dimension's run and
198/// each dimension's cooldown) and the baselines it last computed.
199///
200/// `drift` is `adk_eval::ledger::DriftState` and `baselines` the pass's baseline snapshot,
201/// both as JSON, so the stores hold them without the `proc-baselines` feature.
202///
203/// # Example
204///
205/// ```rust
206/// use adk_kernel::proc::PassState;
207/// use chrono::{NaiveDate, Utc};
208///
209/// let state = PassState::new("default", NaiveDate::from_ymd_opt(2026, 10, 22).unwrap(), Utc::now());
210/// assert!(state.drift.is_null());
211/// ```
212#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
213#[serde(rename_all = "camelCase")]
214#[non_exhaustive]
215pub struct PassState {
216 /// The partition.
217 pub partition: PartitionId,
218 /// The last local day the pass tested.
219 pub last_day: NaiveDate,
220 /// The drift state.
221 #[serde(default)]
222 pub drift: Value,
223 /// The baselines on `last_day`.
224 #[serde(default)]
225 pub baselines: Value,
226 /// When the pass wrote it.
227 pub updated_at: DateTime<Utc>,
228}
229
230impl PassState {
231 /// The state of `partition` after testing `last_day`, with no drift or baselines yet.
232 pub fn new(
233 partition: impl Into<PartitionId>,
234 last_day: NaiveDate,
235 updated_at: DateTime<Utc>,
236 ) -> Self {
237 Self {
238 partition: partition.into(),
239 last_day,
240 drift: Value::Null,
241 baselines: Value::Null,
242 updated_at,
243 }
244 }
245}
246
247/// Words that diagnose, judge or instruct; an observation never carries one (spec 3.2
248/// §7.10: "never a diagnosis").
249const NOT_NEUTRAL: &[&str] = &[
250 "diagnos",
251 "burnout",
252 "burn out",
253 "burning out",
254 "burned out",
255 "burnt out",
256 "depress",
257 "anxi",
258 "stress",
259 "exhaust",
260 "fatigue",
261 "tired",
262 "unhealthy",
263 "health",
264 "sick",
265 "illness",
266 "disorder",
267 "addict",
268 "obsess",
269 "lazy",
270 "overwork",
271 "worr",
272 "concern",
273 "alarm",
274 "problem",
275 "wrong",
276 "bad ",
277 "should",
278 "must",
279 "need to",
280 "you are",
281 "you're",
282 "you have",
283 "symptom",
284];
285
286/// Whether `text` is a question in neutral language (spec 3.2 §7.10, K-I20): one line of
287/// 20 to 400 characters ending in `?`, with no diagnosing, judging or instructing word.
288///
289/// # Example
290///
291/// ```rust
292/// use adk_kernel::proc::is_neutral_question;
293///
294/// assert!(is_neutral_question(
295/// "Your routine has changed over the last two weeks. Would you like to review what changed?"
296/// ));
297/// assert!(!is_neutral_question("Your routine has changed over the last two weeks."));
298/// assert!(!is_neutral_question("Are you burning out from working late every night?"));
299/// assert!(!is_neutral_question("You should stop working so late, don't you think?"));
300/// ```
301pub fn is_neutral_question(text: &str) -> bool {
302 let text = text.trim();
303 let lower = text.to_lowercase();
304 (20..=400).contains(&text.chars().count())
305 && text.ends_with('?')
306 && !text.contains(['\n', '\r'])
307 && !NOT_NEUTRAL.iter().any(|word| lower.contains(word))
308}
309
310/// How a dimension reads in a question: the subject, and the comparison for each
311/// direction.
312fn wording(dimension: &str) -> (String, &'static str, &'static str) {
313 match dimension {
314 "activity.last_minute" => ("the day's last activity".into(), "later", "earlier"),
315 "activity.first_minute" => ("the day's first activity".into(), "later", "earlier"),
316 _ => {
317 let (kind, measure) = dimension.split_once('.').unwrap_or((dimension, "count"));
318 let kind = match kind {
319 "intent" => "requests".to_string(),
320 "tool_call" => "tool calls".to_string(),
321 "approval" => "approvals".to_string(),
322 "rejection" => "rejections".to_string(),
323 "denial" => "denied calls".to_string(),
324 "held" => "held calls".to_string(),
325 "turn" => "turns".to_string(),
326 "wake" => "wake-ups".to_string(),
327 "proposal" => "proposals".to_string(),
328 "process" => "process changes".to_string(),
329 "spend" => "spend".to_string(),
330 other => other.replace('_', " "),
331 };
332 match measure {
333 "count" => (format!("the number of {kind}"), "higher", "lower"),
334 "duration_ms" => (format!("how long {kind} take"), "longer", "shorter"),
335 other => {
336 let key = other.strip_prefix("meta.").unwrap_or(other).replace('_', " ");
337 (format!("{kind} {key}"), "higher", "lower")
338 }
339 }
340 }
341 }
342}
343
344/// The kernel's own wording of an observation (spec 3.2 §7.10): a neutral question built
345/// from the dimension names and directions alone.
346///
347/// # Example
348///
349/// ```rust
350/// use adk_kernel::proc::{Direction, ObservedDimension, is_neutral_question, template_question};
351/// use chrono::NaiveDate;
352///
353/// let since = NaiveDate::from_ymd_opt(2026, 10, 12).unwrap();
354/// let question = template_question(
355/// &[ObservedDimension::new("activity.last_minute", Direction::Higher, since, 10)],
356/// &[7, 14],
357/// );
358/// assert_eq!(
359/// question,
360/// "Your routine has changed over the last two weeks: the day's last activity has been \
361/// later than usual. Would you like to review what changed?"
362/// );
363/// assert!(is_neutral_question(&question));
364/// ```
365pub fn template_question(dimensions: &[ObservedDimension], windows: &[u32]) -> String {
366 let period = match windows.iter().copied().max().unwrap_or(14) {
367 0..=7 => "week".to_string(),
368 days if days % 7 == 0 => {
369 let weeks = days / 7;
370 let words = ["", "one", "two", "three", "four"];
371 match words.get(weeks as usize) {
372 Some(word) => format!("{word} weeks"),
373 None => format!("{weeks} weeks"),
374 }
375 }
376 days => format!("{days} days"),
377 };
378 let clauses: Vec<String> = dimensions
379 .iter()
380 .map(|dimension| {
381 let (subject, higher, lower) = wording(&dimension.dimension);
382 let comparison = match dimension.direction {
383 Direction::Higher => higher,
384 Direction::Lower => lower,
385 };
386 format!("{subject} has been {comparison} than usual")
387 })
388 .collect();
389 let changed = match clauses.as_slice() {
390 [] => String::new(),
391 [one] => format!(": {one}"),
392 [rest @ .., last] => format!(": {}, and {last}", rest.join(", ")),
393 };
394 format!(
395 "Your routine has changed over the last {period}{changed}. Would you like to review \
396 what changed?"
397 )
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 fn day(d: u32) -> NaiveDate {
405 NaiveDate::from_ymd_opt(2026, 10, d).unwrap()
406 }
407
408 #[test]
409 fn the_template_is_a_neutral_question_for_every_dimension_shape() {
410 let dimensions = [
411 ObservedDimension::new("activity.first_minute", Direction::Lower, day(1), 3),
412 ObservedDimension::new("tool_call.count", Direction::Higher, day(1), 3),
413 ObservedDimension::new("tool_call.duration_ms", Direction::Lower, day(1), 3),
414 ObservedDimension::new("turn.meta.cost_micro_usd", Direction::Higher, day(1), 3),
415 ObservedDimension::new("review_item.count", Direction::Lower, day(1), 3),
416 ];
417 for windows in [[7, 14], [7, 7], [14, 28], [5, 10]] {
418 for take in 1..=dimensions.len() {
419 let question = template_question(&dimensions[..take], &windows);
420 assert!(is_neutral_question(&question), "{question}");
421 }
422 }
423 let question = template_question(&dimensions[..2], &[7, 14]);
424 assert_eq!(
425 question,
426 "Your routine has changed over the last two weeks: the day's first activity has \
427 been earlier than usual, and the number of tool calls has been higher than usual. \
428 Would you like to review what changed?"
429 );
430 }
431
432 #[test]
433 fn a_diagnosis_a_statement_or_an_instruction_is_not_neutral() {
434 for text in [
435 "You have been working late; this looks like burnout?",
436 "Is something wrong with your schedule lately?",
437 "Your routine changed over the last two weeks.",
438 "Review it?",
439 "Your evenings look stressful lately — want to talk about it?",
440 "Two lines\nwould you like to review what changed?",
441 ] {
442 assert!(!is_neutral_question(text), "{text}");
443 }
444 }
445
446 #[test]
447 fn ids_are_per_partition_and_day() {
448 assert_ne!(
449 Observation::id_for(&"work".into(), day(1)),
450 Observation::id_for(&"home".into(), day(1))
451 );
452 assert_ne!(
453 Observation::id_for(&"work".into(), day(1)),
454 Observation::id_for(&"work".into(), day(2))
455 );
456 }
457}