1use std::collections::HashSet;
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
32#[serde(rename_all = "snake_case")]
33pub enum OutputFormat {
34 #[default]
36 Json,
37 Auto,
41 Table,
45}
46
47const CELL_TRUNCATE: usize = 120;
49
50const PROPERTY_HOIST_FIELDS: &[&str] = &["trigger_at", "due", "status"];
56
57pub fn render_format(value: Value, format: OutputFormat, presentation: PresentationMode) -> String {
73 match format {
74 OutputFormat::Json => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
75 OutputFormat::Auto | OutputFormat::Table => {
76 let verbose = presentation == PresentationMode::Verbose;
79 let reduced = if verbose {
80 value
81 } else {
82 apply_redundancy_drop(value)
83 };
84 render_auto(reduced, !verbose)
85 }
86 }
87}
88
89pub fn apply_redundancy_drop(value: Value) -> Value {
100 match value {
101 Value::Object(_) => drop_record(value),
102 Value::Array(arr) => Value::Array(
103 arr.into_iter()
104 .map(|v| if v.is_object() { drop_record(v) } else { v })
105 .collect(),
106 ),
107 other => other,
108 }
109}
110
111fn drop_record(value: Value) -> Value {
113 let Value::Object(mut map) = value else {
114 return value;
115 };
116
117 map.remove("full_id");
119
120 if map.get("namespace").and_then(Value::as_str) == Some("local") {
122 map.remove("namespace");
123 }
124
125 let props_val = map.remove("properties");
131 if let Some(Value::Object(props)) = props_val {
132 let mut new_props = Map::new();
133 for (k, v) in props {
134 if map.get(&k) == Some(&v) {
135 continue;
136 }
137 new_props.insert(k, v);
138 }
139 if !new_props.is_empty() {
140 map.insert("properties".to_string(), Value::Object(new_props));
141 }
142 } else if let Some(other) = props_val {
143 map.insert("properties".to_string(), other);
144 }
145
146 let out: Map<String, Value> = map
148 .into_iter()
149 .map(|(k, v)| {
150 let v = match v {
151 Value::Array(arr) => Value::Array(
152 arr.into_iter()
153 .map(|item| {
154 if item.is_object() {
155 drop_record(item)
156 } else {
157 item
158 }
159 })
160 .collect(),
161 ),
162 other => other,
163 };
164 (k, v)
165 })
166 .collect();
167 Value::Object(out)
168}
169
170struct RecordArray {
176 key: Option<String>,
177 records: Vec<Value>,
178 columns: Vec<String>,
179}
180
181fn render_auto(value: Value, truncate: bool) -> String {
189 match locate_record_array(&value) {
190 Some(found) => render_table_with_siblings(&value, &found, truncate),
191 None => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
192 }
193}
194
195fn locate_record_array(value: &Value) -> Option<RecordArray> {
201 let build = |key: Option<String>, arr: &[Value]| {
202 let records: Vec<Value> = arr.iter().cloned().map(hoist_table_scalars).collect();
203 let columns = collect_keys(&records);
204 RecordArray {
205 key,
206 records,
207 columns,
208 }
209 };
210 match value {
211 Value::Array(arr) if is_record_array(arr) => Some(build(None, arr)),
212 Value::Object(map) => map.iter().find_map(|(k, v)| match v {
213 Value::Array(arr) if is_record_array(arr) => Some(build(Some(k.clone()), arr)),
214 _ => None,
215 }),
216 _ => None,
217 }
218}
219
220fn hoist_table_scalars(record: Value) -> Value {
227 let Value::Object(mut map) = record else {
228 return record;
229 };
230 let mut props = match map.remove("properties") {
231 Some(Value::Object(props)) => props,
232 Some(other) => {
233 map.insert("properties".to_string(), other);
235 return Value::Object(map);
236 }
237 None => return Value::Object(map),
238 };
239 for field in PROPERTY_HOIST_FIELDS {
240 if map.contains_key(*field) {
241 continue;
242 }
243 if props
244 .get(*field)
245 .is_some_and(|v| !v.is_object() && !v.is_array())
246 {
247 let v = props.remove(*field).expect("checked above");
248 map.insert((*field).to_string(), v);
249 }
250 }
251 if !props.is_empty() {
252 map.insert("properties".to_string(), Value::Object(props));
253 }
254 Value::Object(map)
255}
256
257fn is_record_array(arr: &[Value]) -> bool {
259 arr.len() >= 2 && arr.iter().all(Value::is_object)
260}
261
262fn render_table_with_siblings(value: &Value, found: &RecordArray, truncate: bool) -> String {
267 let mut out = render_table(&found.records, &found.columns, truncate);
268 let (Value::Object(map), Some(array_key)) = (value, &found.key) else {
269 return out;
270 };
271 for (k, v) in map {
272 if k == array_key {
273 continue;
274 }
275 let text = match v {
276 Value::String(s) if !s.contains(['\n', '\r']) => s.clone(),
280 other => serde_json::to_string(other).unwrap_or_default(),
283 };
284 out.push_str(&format!("{k}: {text}\n"));
285 }
286 out
287}
288
289fn collect_keys(records: &[Value]) -> Vec<String> {
291 let mut seen = HashSet::new();
292 let mut keys = Vec::new();
293 for record in records {
294 if let Value::Object(map) = record {
295 for k in map.keys() {
296 if seen.insert(k.clone()) {
297 keys.push(k.clone());
298 }
299 }
300 }
301 }
302 keys
303}
304
305fn render_table(records: &[Value], keys: &[String], truncate: bool) -> String {
309 let mut out = String::new();
310
311 out.push('|');
312 for k in keys {
313 out.push(' ');
314 out.push_str(k);
315 out.push_str(" |");
316 }
317 out.push('\n');
318
319 out.push('|');
320 for _ in keys {
321 out.push_str("---|");
322 }
323 out.push('\n');
324
325 for record in records {
326 out.push('|');
327 for k in keys {
328 let cell = record.get(k).unwrap_or(&Value::Null);
329 let text = cell_text(k, cell, truncate);
330 out.push(' ');
331 out.push_str(&text);
332 out.push_str(" |");
333 }
334 out.push('\n');
335 }
336
337 out
338}
339
340fn truncation_exempt(key: &str) -> bool {
344 matches!(
345 key,
346 "id" | "kind"
347 | "status"
348 | "priority"
349 | "relation"
350 | "title"
351 | "name"
352 | "signature"
353 | "slug"
354 | "assignee"
355 | "from"
356 | "to"
357 | "due"
358 ) || key.ends_with("_id")
359 || key.ends_with("_at")
360 || key.starts_with("due")
361}
362
363fn cell_text(key: &str, value: &Value, truncate: bool) -> String {
370 let raw = match value {
371 Value::Null => String::new(),
372 Value::Bool(b) => b.to_string(),
373 Value::Number(n) => n.to_string(),
374 Value::String(s) => s.clone(),
375 Value::Object(_) => return "{…}".to_string(),
376 Value::Array(arr) => {
377 if arr.iter().any(|v| v.is_object() || v.is_array()) {
378 return "[…]".to_string();
379 }
380 serde_json::to_string(value).unwrap_or_default()
382 }
383 };
384
385 let escaped = raw.replace('|', "\\|").replace(['\n', '\r'], " ");
387
388 if !truncate || truncation_exempt(key) {
389 return escaped;
390 }
391
392 let char_count = escaped.chars().count();
395 if char_count > CELL_TRUNCATE {
396 let truncated: String = escaped.chars().take(CELL_TRUNCATE).collect();
397 format!("{truncated}...")
398 } else {
399 escaped
400 }
401}
402
403pub fn micros_to_iso(micros: i64) -> String {
410 chrono::DateTime::<chrono::Utc>::from_timestamp_micros(micros)
411 .unwrap_or_else(chrono::Utc::now)
412 .to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
413}
414
415pub fn rfc3339_to_utc_micros(raw: &str) -> Result<i64, chrono::ParseError> {
423 chrono::DateTime::parse_from_rfc3339(raw.trim()).map(|dt| dt.timestamp_micros())
424}
425
426#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
428#[serde(rename_all = "snake_case")]
429pub enum PresentationMode {
430 #[default]
436 Agent,
437 Verbose,
441 Human,
448}
449
450const LIFECYCLE_NULL_PRESERVE: &[&str] = &[
456 "completed_at",
457 "deleted_at",
458 "due_at",
459 "read_at",
460 "started_at",
461 "superseded_at",
462 "applied_at",
463 "withdrawn_at",
464 "reviewed_at",
465 "parent_id",
466 "superseded_by",
467 "replaced_by",
468 "poll_interval_secs",
469 "stalled",
470 "last_success_at",
471 "last_poll_attempt_at",
472 "last_failure_at",
473 "last_error",
474 "consecutive_failures",
475];
476
477const EMPTY_ARRAY_PRESERVE: &[&str] = &["items", "entities", "notes", "edges"];
482
483fn is_stable_list_envelope(map: &Map<String, Value>) -> bool {
484 map.contains_key("requested_limit")
485 && map.contains_key("effective_limit")
486 && map.contains_key("limit_clamped")
487 && EMPTY_ARRAY_PRESERVE
488 .iter()
489 .any(|field| map.contains_key(*field))
490}
491
492const PAYLOAD_TIMESTAMP_FIELDS: &[&str] = &["trigger_at", "due"];
509
510const ROUND_TRIP_FULL_UUID_FIELDS: &[&str] = &[
520 "context_entity_id",
521 "thread_id",
522 "outbound_ref",
523 "parent_id",
524 "session_id",
525 "project_id",
526];
527
528const SCORE_FIELDS: &[&str] = &[
530 "score",
531 "salience",
532 "decay_factor",
533 "rrf_score",
534 "similarity",
535 "cross_encoder_score",
536 "graph_proximity_score",
537];
538
539const UUID_CANONICAL_LEN: usize = 36;
541
542fn should_shorten_uuid_field(key: &str) -> bool {
550 if key == "full_id" || ROUND_TRIP_FULL_UUID_FIELDS.contains(&key) {
551 return false;
552 }
553 key == "id" || key.ends_with("_id") || matches!(key, "superseded_by" | "replaced_by")
554}
555
556pub fn present(value: Value, mode: PresentationMode, now_unix_seconds: i64) -> Value {
566 match mode {
567 PresentationMode::Verbose | PresentationMode::Human => value,
568 PresentationMode::Agent => {
569 let preserved_nulls: HashSet<&str> = LIFECYCLE_NULL_PRESERVE.iter().copied().collect();
570 let score_fields: HashSet<&str> = SCORE_FIELDS.iter().copied().collect();
571 let payload_timestamps: HashSet<&str> =
572 PAYLOAD_TIMESTAMP_FIELDS.iter().copied().collect();
573 transform_agent(
574 value,
575 &preserved_nulls,
576 &score_fields,
577 &payload_timestamps,
578 now_unix_seconds,
579 false,
580 )
581 }
582 }
583}
584
585fn transform_agent(
591 value: Value,
592 preserved_nulls: &HashSet<&str>,
593 scores: &HashSet<&str>,
594 payload_timestamps: &HashSet<&str>,
595 now: i64,
596 inside_properties: bool,
597) -> Value {
598 match value {
599 Value::Object(map) => {
600 let preserve_list_envelope = is_stable_list_envelope(&map);
601 let mut out = Map::new();
602 for (k, v) in map {
603 let child_inside_properties =
607 inside_properties || (k == "properties" && v.is_object());
608 let transformed = transform_field_agent(
609 &k,
610 v,
611 preserved_nulls,
612 scores,
613 payload_timestamps,
614 now,
615 AgentFieldContext {
616 inside_properties: child_inside_properties,
617 preserve_list_envelope,
618 },
619 );
620 match transformed {
621 None => {} Some(tv) => {
623 out.insert(k, tv);
624 }
625 }
626 }
627 Value::Object(out)
628 }
629 Value::Array(arr) => {
630 let items: Vec<Value> = arr
631 .into_iter()
632 .map(|v| {
633 transform_agent(
634 v,
635 preserved_nulls,
636 scores,
637 payload_timestamps,
638 now,
639 inside_properties,
640 )
641 })
642 .collect();
643 Value::Array(items)
644 }
645 other => other,
646 }
647}
648
649#[derive(Clone, Copy)]
661struct AgentFieldContext {
662 inside_properties: bool,
663 preserve_list_envelope: bool,
664}
665
666fn transform_field_agent(
667 key: &str,
668 value: Value,
669 preserved_nulls: &HashSet<&str>,
670 scores: &HashSet<&str>,
671 payload_timestamps: &HashSet<&str>,
672 now: i64,
673 context: AgentFieldContext,
674) -> Option<Value> {
675 match &value {
676 Value::Null => {
678 if preserved_nulls.contains(key)
679 || (context.preserve_list_envelope && key == "next_after")
680 {
681 Some(value)
682 } else {
683 None
684 }
685 }
686 Value::Array(a)
688 if context.preserve_list_envelope
689 && a.is_empty()
690 && EMPTY_ARRAY_PRESERVE.contains(&key) =>
691 {
692 Some(value)
693 }
694 Value::String(s) if s.is_empty() && context.inside_properties => Some(value),
700 Value::String(s) if s.is_empty() => None,
702 Value::Array(a) if a.is_empty() => None,
703 Value::Object(o) if o.is_empty() => None,
704 Value::Number(_) if scores.contains(key) => {
706 if let Some(f) = value.as_f64() {
707 Some(truncate_to_3_sig_figs(f))
708 } else {
709 Some(value)
710 }
711 }
712 Value::String(s) if is_canonical_uuid(s) && should_shorten_uuid_field(key) => {
714 Some(Value::String(s[..8].to_string()))
715 }
716 Value::String(s)
719 if !context.inside_properties
720 && !payload_timestamps.contains(key)
721 && looks_like_iso8601(s) =>
722 {
723 Some(Value::String(compact_timestamp(s, now)))
724 }
725 Value::Object(_) | Value::Array(_) => Some(transform_agent(
727 value,
728 preserved_nulls,
729 scores,
730 payload_timestamps,
731 now,
732 context.inside_properties,
733 )),
734 _ => Some(value),
736 }
737}
738
739fn is_canonical_uuid(s: &str) -> bool {
741 if s.len() != UUID_CANONICAL_LEN {
742 return false;
743 }
744 let b = s.as_bytes();
745 b[8] == b'-'
747 && b[13] == b'-'
748 && b[18] == b'-'
749 && b[23] == b'-'
750 && b[..8].iter().all(|c| c.is_ascii_hexdigit())
751 && b[9..13].iter().all(|c| c.is_ascii_hexdigit())
752 && b[14..18].iter().all(|c| c.is_ascii_hexdigit())
753 && b[19..23].iter().all(|c| c.is_ascii_hexdigit())
754 && b[24..].iter().all(|c| c.is_ascii_hexdigit())
755}
756
757fn looks_like_iso8601(s: &str) -> bool {
761 if s.len() < 16 {
762 return false;
763 }
764 let b = s.as_bytes();
765 b[4] == b'-'
766 && b[7] == b'-'
767 && b[10] == b'T'
768 && b[13] == b':'
769 && b[..4].iter().all(|c| c.is_ascii_digit())
770 && b[5..7].iter().all(|c| c.is_ascii_digit())
771 && b[8..10].iter().all(|c| c.is_ascii_digit())
772 && b[11..13].iter().all(|c| c.is_ascii_digit())
773}
774
775fn compact_timestamp(s: &str, now: i64) -> String {
780 if let Some(unix) = parse_iso8601_unix(s) {
782 let diff = now - unix;
783 if (0..86400).contains(&diff) {
784 return relative_time(diff);
785 }
786 }
787 s.chars().take(16).collect()
789}
790
791fn parse_iso8601_unix(s: &str) -> Option<i64> {
798 if s.len() < 19 {
800 return None;
801 }
802 let b = s.as_bytes();
803 let year: i64 = parse_digits(&b[0..4])?;
804 let month: i64 = parse_digits(&b[5..7])?;
805 let day: i64 = parse_digits(&b[8..10])?;
806 let hour: i64 = parse_digits(&b[11..13])?;
807 let minute: i64 = parse_digits(&b[14..16])?;
808 let second: i64 = parse_digits(&b[17..19])?;
809
810 let days_since_epoch = days_from_civil(year, month, day);
814 let local = days_since_epoch * 86400 + hour * 3600 + minute * 60 + second;
815 let offset_secs = parse_tz_offset_secs(&s[19..])?;
816 Some(local - offset_secs)
817}
818
819fn parse_tz_offset_secs(tail: &str) -> Option<i64> {
829 let mut rest = tail;
830 if let Some(after_dot) = rest.strip_prefix('.') {
831 let frac_len = after_dot.bytes().take_while(u8::is_ascii_digit).count();
832 if frac_len == 0 {
833 return None;
834 }
835 rest = &after_dot[frac_len..];
836 }
837
838 if rest.is_empty() || rest == "Z" {
839 return Some(0);
840 }
841
842 let sign: i64 = match rest.as_bytes().first()? {
843 b'+' => 1,
844 b'-' => -1,
845 _ => return None,
846 };
847 let digits = &rest[1..];
848 let (hh, mm) = match digits.len() {
849 5 if digits.as_bytes()[2] == b':' => (
851 parse_digits(&digits.as_bytes()[0..2])?,
852 parse_digits(&digits.as_bytes()[3..5])?,
853 ),
854 4 => (
856 parse_digits(&digits.as_bytes()[0..2])?,
857 parse_digits(&digits.as_bytes()[2..4])?,
858 ),
859 _ => return None,
860 };
861 if hh > 23 || mm > 59 {
862 return None;
863 }
864 Some(sign * (hh * 3600 + mm * 60))
865}
866
867fn parse_digits(b: &[u8]) -> Option<i64> {
868 let s = std::str::from_utf8(b).ok()?;
869 s.parse().ok()
870}
871
872fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
874 let y = if m <= 2 { y - 1 } else { y };
875 let era = y.div_euclid(400);
876 let yoe = y - era * 400;
877 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
878 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
879 era * 146097 + doe - 719468
880}
881
882fn relative_time(diff_secs: i64) -> String {
884 if diff_secs < 60 {
885 format!("{diff_secs}s ago")
886 } else if diff_secs < 3600 {
887 format!("{}m ago", diff_secs / 60)
888 } else {
889 format!("{}h ago", diff_secs / 3600)
890 }
891}
892
893fn truncate_to_3_sig_figs(f: f64) -> Value {
895 if f == 0.0 || !f.is_finite() {
896 return Value::from(f);
897 }
898 let magnitude = f.abs().log10().floor() as i32;
899 let factor = 10f64.powi(2 - magnitude);
900 let rounded = (f * factor).round() / factor;
901 serde_json::Number::from_f64(rounded)
903 .map(Value::Number)
904 .unwrap_or(Value::from(rounded))
905}
906
907#[cfg(test)]
908mod tests {
909 use super::*;
910 use serde_json::json;
911
912 const NOW: i64 = 1_748_016_480;
914
915 #[test]
916 fn rfc3339_to_utc_micros_round_trips_and_rejects_partial_forms() {
917 let micros = 1_748_016_480_000_000_i64;
918 assert_eq!(rfc3339_to_utc_micros(µs_to_iso(micros)), Ok(micros));
919 assert_eq!(
922 rfc3339_to_utc_micros(" 2025-05-23T12:08:00-04:00 "),
923 Ok(micros)
924 );
925 assert!(rfc3339_to_utc_micros("2026-05-23").is_err());
926 assert!(rfc3339_to_utc_micros("2026-05-23T16:18:00").is_err());
927 }
928
929 fn agent(v: Value) -> Value {
930 present(v, PresentationMode::Agent, NOW)
931 }
932
933 #[test]
934 fn agent_preserves_empty_string_under_properties() {
935 let v = json!({
940 "id": "a1b2c3d4",
941 "summary": "",
942 "properties": {"k": "", "nested": {"deep": ""}},
943 });
944 let out = agent(v);
945 assert_eq!(out["properties"]["k"], json!(""));
946 assert_eq!(out["properties"]["nested"]["deep"], json!(""));
947 assert!(out.get("summary").is_none());
949 }
950
951 #[test]
952 fn agent_drops_scalar_empty_properties_value() {
953 let v = json!({
957 "id": "a1b2c3d4",
958 "properties": "",
959 });
960 let out = agent(v);
961 assert!(out.get("properties").is_none());
962 }
963
964 #[test]
965 fn agent_still_drops_empty_containers_under_properties() {
966 let v = json!({
969 "id": "a1b2c3d4",
970 "properties": {"tags": [], "meta": {}, "kept": "x"},
971 });
972 let out = agent(v);
973 assert!(out["properties"].get("tags").is_none());
974 assert!(out["properties"].get("meta").is_none());
975 assert_eq!(out["properties"]["kept"], json!("x"));
976 }
977
978 #[test]
979 fn verbose_passthrough() {
980 let v = json!({"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "title": "X"});
981 let out = present(v.clone(), PresentationMode::Verbose, NOW);
982 assert_eq!(out, v);
983 }
984
985 #[test]
986 fn agent_shortens_uuid() {
987 let v = json!({"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"});
988 let out = agent(v);
989 assert_eq!(out["id"], json!("a1b2c3d4"));
990 }
991
992 #[test]
993 fn agent_drops_empty_string() {
994 let v = json!({"title": "ok", "description": ""});
995 let out = agent(v);
996 assert!(out.get("description").is_none());
997 assert_eq!(out["title"], json!("ok"));
998 }
999
1000 #[test]
1001 fn agent_drops_empty_array() {
1002 let v = json!({"tags": [], "title": "ok"});
1003 let out = agent(v);
1004 assert!(out.get("tags").is_none());
1005 }
1006
1007 #[test]
1008 fn agent_preserves_empty_list_page_arrays() {
1009 let v = json!({
1010 "items": [],
1011 "entities": [],
1012 "notes": [],
1013 "edges": [],
1014 "next_after": null,
1015 "requested_limit": 10,
1016 "effective_limit": 10,
1017 "limit_clamped": false,
1018 });
1019 let out = agent(v);
1020 for key in EMPTY_ARRAY_PRESERVE {
1021 assert_eq!(out[*key], json!([]), "missing structural key {key}");
1022 }
1023 assert_eq!(out["next_after"], json!(null));
1024 }
1025
1026 #[test]
1027 fn agent_still_drops_empty_arrays_outside_list_envelopes() {
1028 let out = agent(json!({"items": [], "entities": [], "title": "ordinary response"}));
1029 assert!(out.get("items").is_none());
1030 assert!(out.get("entities").is_none());
1031 }
1032
1033 #[test]
1034 fn agent_drops_empty_object() {
1035 let v = json!({"properties": {}, "title": "ok"});
1036 let out = agent(v);
1037 assert!(out.get("properties").is_none());
1038 }
1039
1040 #[test]
1041 fn agent_drops_non_lifecycle_null() {
1042 let v = json!({"result": null, "title": "ok"});
1043 let out = agent(v);
1044 assert!(out.get("result").is_none());
1045 }
1046
1047 #[test]
1048 fn agent_preserves_lifecycle_null() {
1049 let v = json!({"completed_at": null, "due_at": null, "title": "ok"});
1050 let out = agent(v);
1051 assert_eq!(out["completed_at"], json!(null));
1052 assert_eq!(out["due_at"], json!(null));
1053 }
1054
1055 #[test]
1056 fn agent_preserves_relationship_null() {
1057 let v = json!({"parent_id": null, "superseded_by": null});
1058 let out = agent(v);
1059 assert_eq!(out["parent_id"], json!(null));
1060 assert_eq!(out["superseded_by"], json!(null));
1061 }
1062
1063 #[test]
1064 fn agent_preserves_unknown_channel_heartbeat_nulls() {
1065 let v = json!({
1066 "channels": [{
1067 "poll_interval_secs": null,
1068 "stalled": null,
1069 "last_success_at": null,
1070 "last_poll_attempt_at": null,
1071 "last_failure_at": null,
1072 "last_error": null,
1073 "consecutive_failures": null,
1074 "quarantined_count": 1,
1075 }]
1076 });
1077 let out = agent(v);
1078 let channel = out["channels"][0].as_object().expect("channel object");
1079 for field in [
1080 "poll_interval_secs",
1081 "stalled",
1082 "last_success_at",
1083 "last_poll_attempt_at",
1084 "last_failure_at",
1085 "last_error",
1086 "consecutive_failures",
1087 ] {
1088 assert_eq!(
1089 channel.get(field),
1090 Some(&Value::Null),
1091 "Agent presentation must preserve unknown heartbeat fact `{field}`"
1092 );
1093 }
1094 }
1095
1096 #[test]
1097 fn agent_truncates_score_field() {
1098 let v = json!({"score": 0.12345678});
1099 let out = agent(v);
1100 let s = out["score"].as_f64().unwrap();
1101 assert!((s - 0.123).abs() < 1e-9, "expected ~0.123, got {s}");
1102 }
1103
1104 #[test]
1105 fn agent_compacts_old_timestamp_to_minutes() {
1106 let v = json!({"created_at": "2020-01-01T10:30:45.123456Z"});
1108 let out = agent(v);
1109 assert_eq!(out["created_at"], json!("2020-01-01T10:30"));
1110 }
1111
1112 #[test]
1113 fn agent_compacts_recent_timestamp_to_relative() {
1114 let ts_unix = NOW - 180;
1116 let ts = unix_to_iso8601(ts_unix);
1118 let v = json!({"updated_at": ts});
1119 let out = agent(v);
1120 assert_eq!(out["updated_at"], json!("3m ago"));
1121 }
1122
1123 #[test]
1124 fn agent_does_not_compact_top_level_trigger_at_field() {
1125 let at = "2026-07-11T19:00:00-04:00";
1134 let v = json!({
1135 "id": "a1b2c3d4",
1136 "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1137 "event_type": "remind",
1138 "trigger_at": at,
1139 "repeat": null,
1140 "status": "pending",
1141 });
1142 let out = agent(v);
1143 assert_eq!(out["trigger_at"], json!(at));
1144 }
1145
1146 #[test]
1147 fn agent_does_not_compact_top_level_trigger_at_utc() {
1148 let at = "2026-07-11T23:00:00Z";
1149 let v = json!({"trigger_at": at});
1150 let out = agent(v);
1151 assert_eq!(out["trigger_at"], json!(at));
1152 }
1153
1154 #[test]
1155 fn agent_does_not_compact_top_level_trigger_at_offset_less() {
1156 let at = "2026-07-11T23:00:00";
1157 let v = json!({"trigger_at": at});
1158 let out = agent(v);
1159 assert_eq!(out["trigger_at"], json!(at));
1160 }
1161
1162 #[test]
1163 fn agent_still_compacts_other_top_level_timestamps_alongside_trigger_at() {
1164 let v = json!({
1168 "trigger_at": "2026-07-11T19:00:00-04:00",
1169 "created_at": "2020-01-01T10:30:45.123456Z",
1170 });
1171 let out = agent(v);
1172 assert_eq!(out["trigger_at"], json!("2026-07-11T19:00:00-04:00"));
1173 assert_eq!(out["created_at"], json!("2020-01-01T10:30"));
1174 }
1175
1176 #[test]
1177 fn agent_does_not_compact_top_level_due() {
1178 let due = "2026-08-01T09:30:15-04:00";
1183 let v = json!({"due": due});
1184 let out = agent(v);
1185 assert_eq!(out["due"], json!(due));
1186 }
1187
1188 #[test]
1189 fn agent_still_protects_nested_trigger_at_under_properties() {
1190 let at = "2026-07-11T19:00:00-04:00";
1194 let v = json!({
1195 "id": "a1b2c3d4",
1196 "properties": {"trigger_at": at, "status": "pending"},
1197 });
1198 let out = agent(v);
1199 assert_eq!(out["properties"]["trigger_at"], json!(at));
1200 }
1201
1202 #[test]
1203 fn agent_recurses_into_nested_objects() {
1204 let v = json!({
1205 "items": [
1206 {
1207 "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1208 "tags": [],
1209 "score": 0.9999
1210 }
1211 ]
1212 });
1213 let out = agent(v);
1214 let item = &out["items"][0];
1215 assert_eq!(item["id"], json!("a1b2c3d4"));
1216 assert!(item.get("tags").is_none());
1217 let s = item["score"].as_f64().unwrap();
1218 assert!((s - 1.0).abs() < 1e-9);
1219 }
1220
1221 #[test]
1224 fn agent_preserves_full_id_as_36_chars() {
1225 let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
1226 let v = json!({"id": uuid, "full_id": uuid, "title": "X"});
1227 let out = agent(v);
1228 assert_eq!(
1230 out["id"],
1231 json!("a1b2c3d4"),
1232 "id should be 8-char short form"
1233 );
1234 assert_eq!(
1236 out["full_id"].as_str().unwrap().len(),
1237 36,
1238 "full_id must be 36 chars in agent mode"
1239 );
1240 assert_eq!(
1241 out["full_id"],
1242 json!(uuid),
1243 "full_id must equal the original UUID"
1244 );
1245 assert!(
1247 out["full_id"]
1248 .as_str()
1249 .unwrap()
1250 .starts_with(out["id"].as_str().unwrap()),
1251 "full_id must start with the short id prefix"
1252 );
1253 }
1254
1255 #[test]
1256 fn is_canonical_uuid_recognizes_valid() {
1257 assert!(is_canonical_uuid("a1b2c3d4-e5f6-7890-abcd-ef1234567890"));
1258 assert!(!is_canonical_uuid("a1b2c3d4"));
1259 assert!(!is_canonical_uuid("not-a-uuid-at-all-here---------"));
1260 }
1261
1262 #[test]
1263 fn looks_like_iso8601_recognizes_valid() {
1264 assert!(looks_like_iso8601("2026-05-23T16:18:15.234567Z"));
1265 assert!(!looks_like_iso8601("not a timestamp"));
1266 assert!(!looks_like_iso8601("2026-05-23"));
1267 }
1268
1269 fn unix_to_iso8601(unix: i64) -> String {
1271 let (y, mo, d, h, mi, s) = unix_to_civil(unix);
1272 format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
1273 }
1274
1275 fn unix_to_civil(unix: i64) -> (i64, i64, i64, i64, i64, i64) {
1276 let s = unix % 86400;
1277 let days = unix / 86400;
1278 let h = s / 3600;
1279 let m = (s % 3600) / 60;
1280 let sec = s % 60;
1281 let z = days + 719468;
1283 let era = z.div_euclid(146097);
1284 let doe = z - era * 146097;
1285 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1286 let y = yoe + era * 400;
1287 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1288 let mp = (5 * doy + 2) / 153;
1289 let d = doy - (153 * mp + 2) / 5 + 1;
1290 let mo = if mp < 10 { mp + 3 } else { mp - 9 };
1291 let y = if mo <= 2 { y + 1 } else { y };
1292 (y, mo, d, h, m, sec)
1293 }
1294
1295 #[test]
1296 fn agent_does_not_shorten_uuid_shaped_content_fields() {
1297 let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
1298 let out = agent(json!({
1299 "id": uuid,
1300 "full_id": uuid,
1301 "content": uuid,
1302 "description": uuid,
1303 "title": uuid,
1304 "query": uuid,
1305 }));
1306
1307 assert_eq!(out["id"], json!("a1b2c3d4"));
1308 assert_eq!(out["full_id"], json!(uuid));
1309 assert_eq!(out["content"], json!(uuid));
1310 assert_eq!(out["description"], json!(uuid));
1311 assert_eq!(out["title"], json!(uuid));
1312 assert_eq!(out["query"], json!(uuid));
1313 }
1314
1315 #[test]
1316 fn agent_shortens_suffix_id_fields() {
1317 let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
1318 let out = agent(json!({
1319 "note_id": uuid,
1320 "source_id": uuid,
1321 "target_id": uuid,
1322 }));
1323
1324 assert_eq!(out["note_id"], json!("a1b2c3d4"));
1325 assert_eq!(out["source_id"], json!("a1b2c3d4"));
1326 assert_eq!(out["target_id"], json!("a1b2c3d4"));
1327 }
1328
1329 #[test]
1330 fn agent_preserves_strict_round_trip_uuid_fields() {
1331 let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
1332 let out = agent(json!({
1333 "context_entity_id": uuid,
1334 "thread_id": uuid,
1335 "session_id": uuid,
1336 "project_id": uuid,
1337 "properties": {
1338 "context_entity_id": uuid,
1339 "thread_id": uuid,
1340 "outbound_ref": uuid,
1341 "parent_id": uuid,
1342 "session_id": uuid,
1343 "project_id": uuid,
1344 },
1345 "parent_id": uuid,
1346 }));
1347
1348 assert_eq!(out["context_entity_id"], json!(uuid));
1349 assert_eq!(out["thread_id"], json!(uuid));
1350 assert_eq!(out["session_id"], json!(uuid));
1351 assert_eq!(out["project_id"], json!(uuid));
1352 assert_eq!(out["properties"]["context_entity_id"], json!(uuid));
1353 assert_eq!(out["properties"]["thread_id"], json!(uuid));
1354 assert_eq!(out["properties"]["outbound_ref"], json!(uuid));
1355 assert_eq!(out["properties"]["parent_id"], json!(uuid));
1356 assert_eq!(out["properties"]["session_id"], json!(uuid));
1357 assert_eq!(out["properties"]["project_id"], json!(uuid));
1358 assert_eq!(out["parent_id"], json!(uuid));
1359 }
1360
1361 #[test]
1365 fn format_json_preserves_full_shape() {
1366 let v = json!({
1367 "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1368 "namespace": "local",
1369 "properties": {"k": "v"},
1370 "title": "test"
1371 });
1372 let rendered = render_format(v.clone(), OutputFormat::Json, PresentationMode::Agent);
1373 let parsed: Value = serde_json::from_str(&rendered).unwrap();
1374 assert!(
1376 parsed.get("full_id").is_some(),
1377 "json mode must keep full_id"
1378 );
1379 assert_eq!(
1381 parsed.get("namespace").and_then(Value::as_str),
1382 Some("local")
1383 );
1384 assert!(parsed.get("properties").is_some());
1386 }
1387
1388 #[test]
1390 fn format_auto_drops_versus_json_keeps() {
1391 let v = json!({
1392 "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1393 "namespace": "local",
1394 "title": "test"
1395 });
1396 let json_rendered = render_format(v.clone(), OutputFormat::Json, PresentationMode::Agent);
1397 let auto_rendered = render_format(v.clone(), OutputFormat::Auto, PresentationMode::Agent);
1398 let json_parsed: Value = serde_json::from_str(&json_rendered).unwrap();
1400 assert!(
1401 json_parsed.get("full_id").is_some(),
1402 "json must keep full_id"
1403 );
1404 assert_eq!(
1405 json_parsed.get("namespace").and_then(Value::as_str),
1406 Some("local")
1407 );
1408 assert!(!auto_rendered.contains("full_id"), "auto must drop full_id");
1411 assert!(
1412 !auto_rendered.contains("namespace"),
1413 "auto must elide namespace=local"
1414 );
1415 }
1416
1417 #[test]
1419 fn format_auto_homogeneous_array_renders_markdown_table() {
1420 let v = json!([
1421 {"id": "abc", "title": "First"},
1422 {"id": "def", "title": "Second"}
1423 ]);
1424 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1425 assert!(rendered.starts_with('|'), "must start with |");
1426 assert!(
1427 rendered.contains("| id |") || rendered.contains("| id"),
1428 "must have id column"
1429 );
1430 assert!(rendered.contains("title"), "must have title column");
1431 assert!(rendered.contains("|---|"), "must have separator row");
1432 assert!(rendered.contains("abc"), "must have first row data");
1433 assert!(rendered.contains("Second"), "must have second row data");
1434 }
1435
1436 #[test]
1438 fn format_auto_single_record_renders_compact_json() {
1439 let v = json!({"id": "abc", "title": "Hello World"});
1440 let rendered = render_format(v.clone(), OutputFormat::Auto, PresentationMode::Agent);
1441 let parsed: Value = serde_json::from_str(&rendered).expect("must be valid JSON");
1442 assert_eq!(parsed, v, "single record must round-trip losslessly");
1443 assert!(
1444 !rendered.starts_with('|'),
1445 "single record must not be a markdown table"
1446 );
1447 }
1448
1449 #[test]
1453 fn format_auto_single_record_large_payload_survives_whole() {
1454 let briefing = "line one\nline two\n".repeat(500); let v = json!({"id": "abc", "markdown": briefing.clone()});
1456 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1457 let parsed: Value = serde_json::from_str(&rendered).expect("must be valid JSON");
1458 assert_eq!(
1459 parsed.get("markdown").and_then(Value::as_str),
1460 Some(briefing.as_str()),
1461 "large payload field must survive untruncated"
1462 );
1463 }
1464
1465 #[test]
1468 fn format_auto_table_preserves_sibling_scalars() {
1469 let v = json!({
1470 "results": [
1471 {"id": "abc", "title": "First"},
1472 {"id": "def", "title": "Second"}
1473 ],
1474 "has_more": true,
1475 "offset": 20,
1476 "page_size": 2,
1477 "truncated": false
1478 });
1479 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1480 assert!(rendered.contains("| id"), "records must render as a table");
1481 assert!(
1482 rendered.contains("has_more: true"),
1483 "has_more sibling must survive: {rendered}"
1484 );
1485 assert!(
1486 rendered.contains("offset: 20"),
1487 "offset sibling must survive"
1488 );
1489 assert!(
1490 rendered.contains("page_size: 2"),
1491 "page_size sibling must survive"
1492 );
1493 assert!(
1494 rendered.contains("truncated: false"),
1495 "truncated sibling must survive"
1496 );
1497 }
1498
1499 #[test]
1502 fn format_auto_nested_cell_renders_elision_marker() {
1503 let big_nested: Value = json!({"k": "v".repeat(300), "other": {"deep": true}});
1504 let v = json!([
1505 {"id": "abc", "properties": big_nested},
1506 {"id": "def", "properties": {"x": 1}}
1507 ]);
1508 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1509 assert!(
1510 rendered.contains("{…}"),
1511 "nested object cell must render the elision marker: {rendered}"
1512 );
1513 assert!(
1514 !rendered.contains("..."),
1515 "no truncated pseudo-JSON in nested cells"
1516 );
1517 }
1518
1519 #[test]
1521 fn format_auto_scalar_array_cell_renders_compact_json() {
1522 let v = json!([
1523 {"id": "abc", "tags": ["lesson", "khive"]},
1524 {"id": "def", "tags": ["adr"]}
1525 ]);
1526 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1527 assert!(
1528 rendered.contains(r#"["lesson","khive"]"#),
1529 "scalar array cell must be compact JSON: {rendered}"
1530 );
1531 }
1532
1533 #[test]
1536 fn format_auto_identity_columns_not_truncated() {
1537 let long_title = "T".repeat(300);
1538 let long_note = "N".repeat(300);
1539 let v = json!([
1540 {"id": "abc", "title": long_title.clone(), "note": long_note.clone()},
1541 {"id": "def", "title": "short", "note": "short"}
1542 ]);
1543 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1544 assert!(
1545 rendered.contains(&long_title),
1546 "title column must not be truncated"
1547 );
1548 assert!(
1549 !rendered.contains(&long_note),
1550 "non-exempt column must still truncate"
1551 );
1552 }
1553
1554 #[test]
1556 fn format_auto_verbose_disables_truncation() {
1557 let long_note = "N".repeat(300);
1558 let v = json!([
1559 {"id": "abc", "note": long_note.clone()},
1560 {"id": "def", "note": "short"}
1561 ]);
1562 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Verbose);
1563 assert!(
1564 rendered.contains(&long_note),
1565 "verbose must render full cell content"
1566 );
1567 }
1568
1569 #[test]
1573 fn table_path_hoists_payload_scalars_to_columns() {
1574 let record = |n: u32| {
1578 json!({
1579 "id": format!("evt-{n}"),
1580 "properties": {
1581 "trigger_at": "2026-09-01T14:00:00-04:00",
1582 "status": "pending",
1583 "dispatch_receipt": {"state": "succeeded"}
1584 }
1585 })
1586 };
1587 let out = render_format(
1588 json!([record(1), record(2)]),
1589 OutputFormat::Auto,
1590 PresentationMode::Agent,
1591 );
1592 let header = out.lines().next().expect("table header");
1593 assert!(
1594 header.contains("trigger_at") && header.contains("status"),
1595 "hoisted scalars must appear as table columns, got header: {header}"
1596 );
1597 assert!(
1598 out.contains("2026-09-01T14:00:00-04:00") && out.contains("pending"),
1599 "hoisted values must render in cells:\n{out}"
1600 );
1601 }
1602
1603 #[test]
1604 fn redundancy_drop_no_longer_hoists_outside_tables() {
1605 let v = json!({
1609 "id": "abc",
1610 "properties": {
1611 "trigger_at": "2026-09-01T14:00:00-04:00",
1612 "status": "pending"
1613 }
1614 });
1615 let reduced = apply_redundancy_drop(v);
1616 assert!(
1617 reduced.get("trigger_at").is_none() && reduced.get("status").is_none(),
1618 "the pre-pass must not hoist; the hoist is table-path only"
1619 );
1620 let props = reduced.get("properties").expect("properties must remain");
1621 assert_eq!(
1622 props.get("status").and_then(Value::as_str),
1623 Some("pending"),
1624 "fallback shape keeps payload fields inside properties"
1625 );
1626 }
1627
1628 #[test]
1629 fn sibling_string_with_newline_renders_as_json_literal() {
1630 let v = json!({
1633 "items": [{"id": "a", "kind": "x"}, {"id": "b", "kind": "y"}],
1634 "note": "line one\nforged_key: forged_value",
1635 "has_more": true
1636 });
1637 let out = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1638 assert!(
1639 !out.contains("\nforged_key: forged_value"),
1640 "raw newline from a sibling string must not start a new line:\n{out}"
1641 );
1642 assert!(
1643 out.contains(r#"note: "line one\nforged_key: forged_value""#),
1644 "newline-bearing sibling renders as its JSON literal:\n{out}"
1645 );
1646 assert!(out.contains("has_more: true"), "siblings still preserved");
1647 }
1648
1649 #[test]
1650 fn carriage_return_in_cell_collapses_like_newline() {
1651 let v = json!([
1655 {"id": "a", "note": "before\rafter"},
1656 {"id": "b", "note": "one\r\ntwo"}
1657 ]);
1658 let out = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1659 assert!(
1660 !out.contains('\r'),
1661 "no raw carriage return may survive into rendered output:\n{out:?}"
1662 );
1663 assert!(
1664 out.contains("before after") && out.contains("one two"),
1665 "\\r and \\r\\n collapse to spaces inside cells:\n{out}"
1666 );
1667 }
1668
1669 #[test]
1671 fn redundancy_drop_hoist_does_not_overwrite_top_level() {
1672 let v = json!({
1673 "id": "abc",
1674 "status": "active",
1675 "properties": {"status": "pending"}
1676 });
1677 let reduced = apply_redundancy_drop(v);
1678 assert_eq!(
1679 reduced.get("status").and_then(Value::as_str),
1680 Some("active"),
1681 "existing top-level status must win"
1682 );
1683 assert_eq!(
1684 reduced
1685 .get("properties")
1686 .and_then(|p| p.get("status"))
1687 .and_then(Value::as_str),
1688 Some("pending"),
1689 "conflicting properties value must stay where it was"
1690 );
1691 }
1692
1693 #[test]
1695 fn format_auto_scalar_fallback_compact_json() {
1696 let v = json!(42);
1697 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1698 assert_eq!(rendered, "42");
1699 }
1700
1701 #[test]
1703 fn format_table_forces_markdown_when_array() {
1704 let v = json!({
1705 "items": [
1706 {"name": "A", "score": 1},
1707 {"name": "B", "score": 2}
1708 ]
1709 });
1710 let rendered = render_format(v, OutputFormat::Table, PresentationMode::Agent);
1711 assert!(
1712 rendered.contains("|"),
1713 "table format must produce markdown table"
1714 );
1715 assert!(rendered.contains("name"), "must have name column");
1716 assert!(rendered.contains("score"), "must have score column");
1717 }
1718
1719 #[test]
1721 fn format_table_falls_back_to_json_when_no_array() {
1722 let v = json!({"single": "value"});
1723 let rendered = render_format(v, OutputFormat::Table, PresentationMode::Agent);
1724 let parsed: Value = serde_json::from_str(&rendered).unwrap();
1726 assert_eq!(parsed["single"], json!("value"));
1727 }
1728
1729 #[test]
1731 fn format_auto_verbose_skips_redundancy_drop() {
1732 let v = json!({
1733 "full_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1734 "namespace": "local",
1735 "title": "test"
1736 });
1737 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Verbose);
1740 assert!(
1741 rendered.contains("full_id"),
1742 "verbose must preserve full_id"
1743 );
1744 assert!(
1745 rendered.contains("namespace"),
1746 "verbose must preserve namespace"
1747 );
1748 }
1749
1750 #[test]
1754 fn redundancy_drop_does_not_corrupt_error_shape() {
1755 let v = json!({"ok": false, "error": "something failed", "namespace": "local"});
1756 let reduced = apply_redundancy_drop(v.clone());
1761 assert!(
1762 reduced.get("error").is_some(),
1763 "redundancy drop must preserve error field"
1764 );
1765 assert_eq!(
1766 reduced.get("ok").and_then(Value::as_bool),
1767 Some(false),
1768 "redundancy drop must preserve ok=false"
1769 );
1770 }
1771
1772 #[test]
1774 fn redundancy_drop_properties_dedup() {
1775 let v = json!({
1776 "id": "abc",
1777 "title": "Same",
1778 "properties": {
1779 "title": "Same", "extra": "unique" }
1782 });
1783 let reduced = apply_redundancy_drop(v);
1784 let props = reduced.get("properties").expect("properties must remain");
1785 assert!(props.get("extra").is_some(), "unique property must be kept");
1786 assert!(
1787 props.get("title").is_none(),
1788 "duplicate top-level property must be removed"
1789 );
1790 }
1791
1792 #[test]
1794 fn cell_text_truncates_long_values() {
1795 let long = "X".repeat(200);
1796 let v = json!([
1797 {"col": long.clone()},
1798 {"col": "short"}
1799 ]);
1800 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1801 assert!(
1803 rendered.contains("..."),
1804 "long cell must be truncated with ..."
1805 );
1806 assert!(
1807 !rendered.contains(&long),
1808 "full long string must not appear in table"
1809 );
1810 }
1811
1812 #[test]
1818 fn cell_text_truncation_is_utf8_safe() {
1819 let prefix = "a".repeat(119);
1822 let suffix = "中".repeat(10); let long_multibyte = format!("{prefix}{suffix}trailing");
1824 let v = json!([
1825 {"col": long_multibyte.clone()},
1826 {"col": "ok"}
1827 ]);
1828 let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1830 assert!(
1831 rendered.contains("..."),
1832 "multibyte cell must be truncated with ..."
1833 );
1834 assert!(
1836 std::str::from_utf8(rendered.as_bytes()).is_ok(),
1837 "rendered output must be valid UTF-8"
1838 );
1839 }
1840
1841 #[test]
1844 fn parse_iso8601_unix_negative_offset_matches_equivalent_utc() {
1845 assert_eq!(
1847 parse_iso8601_unix("2026-07-09T11:55:00-04:00"),
1848 parse_iso8601_unix("2026-07-09T15:55:00Z")
1849 );
1850 }
1851
1852 #[test]
1853 fn parse_iso8601_unix_positive_offset_matches_equivalent_utc() {
1854 assert_eq!(
1856 parse_iso8601_unix("2026-05-23T20:15:00+04:00"),
1857 parse_iso8601_unix("2026-05-23T16:15:00Z")
1858 );
1859 }
1860
1861 #[test]
1862 fn parse_iso8601_unix_zero_offset_matches_z() {
1863 assert_eq!(
1864 parse_iso8601_unix("2026-07-09T15:55:00+00:00"),
1865 parse_iso8601_unix("2026-07-09T15:55:00Z")
1866 );
1867 }
1868
1869 #[test]
1870 fn parse_iso8601_unix_compact_offset_form_matches_colon_form() {
1871 assert_eq!(
1872 parse_iso8601_unix("2026-07-09T11:55:00-0400"),
1873 parse_iso8601_unix("2026-07-09T11:55:00-04:00")
1874 );
1875 }
1876
1877 #[test]
1878 fn parse_iso8601_unix_fractional_seconds_with_offset() {
1879 assert_eq!(
1882 parse_iso8601_unix("2026-07-09T11:55:00.123-04:00"),
1883 parse_iso8601_unix("2026-07-09T15:55:00Z")
1884 );
1885 }
1886
1887 #[test]
1888 fn parse_iso8601_unix_fractional_seconds_with_z() {
1889 assert_eq!(
1890 parse_iso8601_unix("2026-07-09T15:55:00.999Z"),
1891 parse_iso8601_unix("2026-07-09T15:55:00Z")
1892 );
1893 }
1894
1895 #[test]
1896 fn parse_iso8601_unix_bare_form_unchanged() {
1897 assert_eq!(
1899 parse_iso8601_unix("2026-07-09T15:55:00"),
1900 parse_iso8601_unix("2026-07-09T15:55:00Z")
1901 );
1902 }
1903
1904 #[test]
1905 fn parse_iso8601_unix_malformed_tail_returns_none() {
1906 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00X"), None);
1907 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+04"), None);
1908 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00."), None);
1909 }
1910
1911 #[test]
1912 fn parse_iso8601_unix_out_of_range_offset_returns_none() {
1913 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+24:00"), None);
1915 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+2400"), None);
1916 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+01:60"), None);
1918 assert_eq!(parse_iso8601_unix("2026-07-09T15:55:00+0160"), None);
1919 }
1920
1921 #[test]
1922 fn parse_iso8601_unix_max_valid_offset_boundary_is_accepted() {
1923 assert!(parse_iso8601_unix("2026-07-09T15:55:00+23:59").is_some());
1925 assert!(parse_iso8601_unix("2026-07-09T15:55:00-23:59").is_some());
1926 assert!(parse_iso8601_unix("2026-07-09T15:55:00+2359").is_some());
1927 }
1928
1929 #[test]
1930 fn compact_timestamp_offset_bearing_future_time_not_shown_as_ago() {
1931 let out = compact_timestamp("2025-05-23T16:08:00-02:00", NOW);
1935 assert_ne!(out, "0s ago");
1936 assert_eq!(out, "2025-05-23T16:08");
1937 }
1938
1939 #[test]
1940 fn compact_timestamp_offset_bearing_past_time_renders_relative() {
1941 let out = compact_timestamp("2025-05-23T20:05:00+04:00", NOW);
1947 assert_eq!(out, "3m ago");
1948 }
1949}