Skip to main content

khive_runtime/
presentation.rs

1//! Verb response presentation modes and transformation.
2//!
3//! Transforms canonical handler output into caller-appropriate form after dispatch
4//! and before wire serialization. `Agent` mode abbreviates UUIDs/timestamps and drops
5//! empty fields; `Verbose` and `Human` pass through canonical JSON unchanged.
6//!
7//! This module also contains the `OutputFormat` axis (ADR-078) which governs how
8//! the resulting `serde_json::Value` is serialized or rendered to an output string.
9//! `PresentationMode` and `OutputFormat` compose independently.
10
11use std::collections::HashSet;
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16// ── OutputFormat ─────────────────────────────────────────────────────────────
17
18/// Output serialization format for verb results (ADR-078).
19///
20/// Orthogonal to [`PresentationMode`]: `PresentationMode` controls field-level
21/// transforms (UUID shortening, timestamp compaction, empty-field dropping);
22/// `OutputFormat` controls how the resulting `serde_json::Value` is serialized
23/// or rendered to the wire string.
24///
25/// Default is [`OutputFormat::Json`] on every surface: compact, lossless,
26/// shape-stable machine contract.
27///
28/// Note: `Yaml` is a clean follow-up — implemented as a 3-variant enum
29/// (`Json`, `Auto`, `Table`) per ADR-078 §"yaml" which permits omission when
30/// the in-tree emitter would balloon.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
32#[serde(rename_all = "snake_case")]
33pub enum OutputFormat {
34    /// Compact JSON (`serde_json::to_string`). Lossless machine contract. Default.
35    #[default]
36    Json,
37    /// Shape-aware: markdown table for homogeneous record arrays (with
38    /// envelope siblings preserved as trailing `key: value` lines),
39    /// compact-JSON fallback for every other shape.
40    Auto,
41    /// Force the markdown-table renderer regardless of detected shape.
42    /// Since the kv-block renderer was removed (ADR-078 §3 amendment),
43    /// `Table` and `Auto` share the same dispatch.
44    Table,
45}
46
47/// Cell truncation limit for markdown-table rendering (ADR-078 §3a).
48const CELL_TRUNCATE: usize = 120;
49
50/// Scalar payload fields hoisted from `properties` to the top level in the
51/// auto/table pre-pass, when no top-level sibling of that name exists.
52/// View-only (never applied to `json`): without the hoist, a table row for a
53/// scheduled event cannot say when it fires or whether it is pending —
54/// those fields exist only inside the nested `properties` bag.
55const PROPERTY_HOIST_FIELDS: &[&str] = &["trigger_at", "due", "status"];
56
57// ── Public render entry point ────────────────────────────────────────────────
58
59/// Render a successful verb result value to a wire string using the given format.
60///
61/// Called at the single serialization seam (ADR-078 §9) AFTER all `$prev` chain
62/// resolution and AFTER the [`PresentationMode`] transform.
63///
64/// Error envelopes (`ok=false`) are never passed here — the caller must handle
65/// them as compact JSON directly (ADR-078 §8.2).
66///
67/// When `format` is [`OutputFormat::Json`], returns compact JSON (`serde_json::to_string`).
68/// When `format` is [`OutputFormat::Auto`] or [`OutputFormat::Table`], applies the
69/// redundancy-reduction pre-pass (§7) — unless `presentation` is [`PresentationMode::Verbose`]
70/// — then dispatches to the shape-aware renderer. Verbose also disables cell
71/// truncation in the table renderer (§3a).
72pub 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            // Skip the redundancy-reduction pre-pass in Verbose mode: full
77            // canonical shape must pass through unchanged.
78            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
89// ── Redundancy-reduction pre-pass (ADR-078 §7) ──────────────────────────────
90
91/// Apply the view-only redundancy-reduction pre-pass (ADR-078 §7) to a value.
92///
93/// Applies at most ONE pass over the value. This function is the canonical
94/// entry for the pre-pass; the per-record logic lives in `drop_record`.
95///
96/// Applied only when `format` ∈ {`auto`, `table`} AND `presentation` ≠ `Verbose`.
97/// Callers are responsible for checking those conditions; this function applies
98/// unconditionally.
99pub 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
111/// Apply per-record redundancy rules (§7.1, §7.2, §7.3) to a single record object.
112fn drop_record(value: Value) -> Value {
113    let Value::Object(mut map) = value else {
114        return value;
115    };
116
117    // `full_id` is a chaining handle, not needed in view-only output.
118    map.remove("full_id");
119
120    // `"local"` is the common case, so only surface `namespace` when it isn't.
121    if map.get("namespace").and_then(Value::as_str) == Some("local") {
122        map.remove("namespace");
123    }
124
125    // Properties dedup: drop key-value pairs from `properties` that
126    // duplicate an identical top-level sibling. The scalar hoist for table
127    // columns lives in `hoist_table_scalars`, applied only on the table
128    // path: reshaping the compact-JSON fallback would move fields with no
129    // column to gain.
130    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    // Recurse into array values so nested record arrays are also reduced.
147    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
170// ── Shape-aware rendering (`auto`) ──────────────────────────────────────────
171
172/// A record array located inside a value: the records, their ordered column
173/// keys, and — when the array sat under an object key — that key's name, so
174/// the caller can enumerate the remaining (sibling) keys.
175struct RecordArray {
176    key: Option<String>,
177    records: Vec<Value>,
178    columns: Vec<String>,
179}
180
181/// Render a value using shape-aware dispatch (ADR-078 §3, as amended).
182///
183/// Shape (a): homogeneous record array → markdown table, with any envelope
184/// siblings preserved as trailing `key: value` lines.
185/// Every other shape → compact JSON, lossless by construction. The former
186/// kv-block renderer for single records is removed: its truncation destroyed
187/// single-record payloads (e.g. a compose briefing's `markdown` field).
188fn 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
195/// Find the first homogeneous record array in `value`.
196///
197/// Checks:
198/// 1. `value` itself is an array of 2+ objects.
199/// 2. `value` is an object with a key whose value is an array of 2+ objects.
200fn 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
220/// Hoist `PROPERTY_HOIST_FIELDS` scalars out of a record's `properties` bag
221/// to the top level (never overwriting a top-level sibling), so the table
222/// renderer can surface them as columns — a scheduled event's
223/// `trigger_at`/`status` live only inside `properties`, and a nested cell
224/// renders as `{…}`. Table path only (ADR-078 Amendment 2): the compact-JSON
225/// fallback keeps its shape.
226fn 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            // Non-object `properties` is not a bag to hoist from — restore it.
234            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
257/// An array of 2+ objects qualifies as a record array.
258fn is_record_array(arr: &[Value]) -> bool {
259    arr.len() >= 2 && arr.iter().all(Value::is_object)
260}
261
262/// Render the located record array as a table, then append one `key: value`
263/// line per remaining top-level key. Envelope fields (`has_more`, `offset`,
264/// counts) must survive rendering: dropping them made a truncated `query`
265/// page read as complete.
266fn 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            // A newline-bearing string renders as its JSON literal (one line,
277            // lossless) so a stored value cannot fabricate a sibling line or
278            // table row (ADR-078 Amendment 2 escaping contract).
279            Value::String(s) if !s.contains(['\n', '\r']) => s.clone(),
280            // Non-string scalars and nested values: compact JSON, untruncated
281            // — sibling fidelity is the point of this path.
282            other => serde_json::to_string(other).unwrap_or_default(),
283        };
284        out.push_str(&format!("{k}: {text}\n"));
285    }
286    out
287}
288
289/// Collect column names in first-seen order across all records.
290fn 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
305// ── Markdown table renderer (ADR-078 §3a) ───────────────────────────────────
306
307/// Render a record array as a GitHub-Flavored Markdown table.
308fn 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
340/// Column names exempt from cell truncation: identity and decision fields
341/// must arrive whole — a truncated id cannot be resolved and a truncated
342/// title cannot be selected on.
343fn 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
363/// Format a cell value: escape `|`, collapse newlines, truncate to ~120 chars
364/// unless `truncate` is off or the column is identity/decision-bearing.
365///
366/// Nested values are elided to a constant marker (`{…}` / `[…]`) rather than
367/// stringified and cut mid-JSON: truncated pseudo-JSON reads as data while
368/// silently missing fields. Full content is one `format=json` or `get` away.
369fn 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            // Arrays of scalars (tags, ids) stay compact JSON.
381            serde_json::to_string(value).unwrap_or_default()
382        }
383    };
384
385    // Escape literal `|` and collapse embedded newlines to a space.
386    let escaped = raw.replace('|', "\\|").replace(['\n', '\r'], " ");
387
388    if !truncate || truncation_exempt(key) {
389        return escaped;
390    }
391
392    // Truncate to approximately CELL_TRUNCATE *characters* (char boundary,
393    // not byte index — slicing on a byte offset can panic on multi-byte chars).
394    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
403/// Convert a microsecond epoch `i64` to an RFC 3339 / ISO-8601 string.
404///
405/// Entity and Note storage uses `i64` microseconds internally; this is the
406/// single conversion point before any field reaches the MCP boundary.
407///
408/// Format: `YYYY-MM-DDTHH:MM:SS.ffffffZ` (SecondsFormat::Micros, UTC `Z`).
409pub 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
415/// Parse an RFC 3339 timestamp (offset required) into microsecond epoch
416/// `i64` — the inverse of [`micros_to_iso`], and the single parse point for
417/// caller-supplied instants entering storage comparisons.
418///
419/// Leading/trailing whitespace is tolerated. Date-only and offset-less forms
420/// are rejected; callers own the verb-specific error context around the
421/// returned `ParseError`.
422pub 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/// How the response envelope is presented to the caller.
427#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
428#[serde(rename_all = "snake_case")]
429pub enum PresentationMode {
430    /// Token-efficient. Default for MCP callers (agents).
431    ///
432    /// Short UUIDs (8-char), compact timestamps (minute granularity or
433    /// relative), empty fields dropped, structural nulls preserved, score
434    /// fields truncated to 3 significant figures.
435    #[default]
436    Agent,
437    /// Full canonical shape. Default for `kkernel exec` and CI/scripted callers.
438    ///
439    /// No transformation — handler output passes through as-is.
440    Verbose,
441    /// Pretty-printed terminal output. Default for `khive` CLI.
442    ///
443    /// **At the MCP runtime level this is identical to `Verbose`** — the
444    /// canonical JSON is returned unchanged. Terminal formatting (relative
445    /// timestamps, glyph substitution, table layout) is applied by the CLI
446    /// layer (`khive-cli::format::pretty`), not the MCP response pipeline.
447    Human,
448}
449
450/// Lifecycle/operational `null` fields that are PRESERVED in Agent mode.
451///
452/// These fields carry state meaning (absent ≠ known-unknown) and must not be
453/// dropped. The channel-health fields distinguish a quarantine-only identity
454/// from a heartbeat row whose liveness facts were actually observed.
455const 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
477/// Empty collection fields that define a stable response envelope and must
478/// survive Agent-mode compaction. Dropping these turns an empty page into a
479/// different response type and leaves callers unable to distinguish an empty
480/// result from a missing/unsupported field.
481const 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
492/// Field names carrying caller-supplied payload timestamps that must never be
493/// compacted (relative-time or minute-truncated), regardless of nesting.
494///
495/// These encode domain semantics the caller needs to round-trip verbatim —
496/// e.g. `trigger_at` on a `schedule.remind`/`schedule.schedule` create
497/// response, returned as a top-level convenience field alongside `id` and
498/// `full_id`, not nested under `"properties"`. The `inside_properties` guard
499/// alone only protects fields nested under a literal `"properties"` key
500/// (as returned by `agenda`/`get`); it does not cover this top-level case,
501/// which `compact_timestamp` rewrote into either a relative string or a
502/// minute-truncated absolute form — either way discarding the seconds and
503/// offset the caller needs to round-trip the exact submitted value (#871).
504///
505/// `due` on `gtd.assign`/`gtd.tasks`/`gtd.next` responses is the same shape:
506/// a top-level convenience field mirroring `properties.due`, which
507/// `parse_due` already normalizes to full RFC 3339.
508const PAYLOAD_TIMESTAMP_FIELDS: &[&str] = &["trigger_at", "due"];
509
510/// UUID fields whose canonical value is itself a strict-verb input.
511///
512/// Shortening these would make a successful response fail when submitted back
513/// to the verb that produced or consumes it. `context_entity_id` and
514/// `thread_id` are explicit stable references rather than prefix searches;
515/// `outbound_ref` is the exact correlation key consumed by `comm.delivered`;
516/// `parent_id` is the explicit ancestry reference consumed by `propose`;
517/// `session_id` is an exact event-list filter; and `project_id` is the exact
518/// provenance anchor required by git issue and pull-request creation.
519const 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
528/// Score field names that are truncated to 3 significant figures in Agent mode.
529const 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
539/// UUID v4 canonical string length (8-4-4-4-12 = 32 hex + 4 dashes = 36).
540const UUID_CANONICAL_LEN: usize = 36;
541
542/// Return true for fields whose whole-string UUID values may be shortened in
543/// Agent mode. Content-like fields are intentionally excluded even when their
544/// value happens to be UUID-shaped.
545///
546/// `full_id` and strict round-trip fields are explicitly excluded: their
547/// purpose is to give callers a stable chaining handle, so shortening them
548/// would produce a value that the corresponding strict verb rejects.
549fn 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
556/// Transform a successful verb result value according to the given
557/// [`PresentationMode`].
558///
559/// - `Verbose` / `Human`: returns `value` unchanged.
560/// - `Agent`: applies UUID shortening, timestamp compaction, empty-field
561///   dropping, structural-null preservation, and score truncation.
562///
563/// `now_unix_seconds` is sampled once per response and passed through so all
564/// relative datetime renderings within a response use the same instant.
565pub 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
585/// Apply the Agent-mode transform to an arbitrary JSON value.
586///
587/// `inside_properties` is `true` when recursing inside a `"properties"` object.
588/// Caller-supplied payload timestamps (e.g. `trigger_at`) must not be compacted
589/// because they encode domain semantics the agent may need to round-trip.
590fn 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                // ADR-045 Amendment 3 scopes the empty-string carve-out to
604                // strings nested under an object-valued `properties`; a
605                // scalar or array `properties` value gets no carve-out.
606                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 => {} // drop
622                    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/// Transform a single named field value under Agent mode.
650///
651/// Returns `None` if the field should be dropped.
652///
653/// `inside_properties` suppresses timestamp compaction for caller-submitted
654/// payload values nested under a literal `"properties"` key (e.g. `trigger_at`
655/// as returned by `agenda`/`get`). `payload_timestamps` suppresses compaction
656/// by field name regardless of nesting, covering top-level convenience fields
657/// such as the `trigger_at` returned directly in a `schedule.remind`/
658/// `schedule.schedule` create response (#871). Metadata timestamps at the top
659/// level (`created_at`, `updated_at`) are still compacted.
660#[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        // Preserve lifecycle and stable-envelope nulls; drop other nulls.
677        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        // Stable page-envelope arrays remain present even when empty.
687        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        // Preserve empty strings under a record's `properties` object: those
695        // keys exist only because a caller wrote them, so `""` there is data
696        // (set-to-empty vs absent, ADR-045 Amendment 3, issue #1995). Empty
697        // arrays and objects under `properties` are still dropped per the
698        // amendment's scope note.
699        Value::String(s) if s.is_empty() && context.inside_properties => Some(value),
700        // Drop other empty strings, arrays, objects.
701        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        // Truncate score fields.
705        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        // Shorten UUIDs only in fields whose names carry ID semantics.
713        Value::String(s) if is_canonical_uuid(s) && should_shorten_uuid_field(key) => {
714            Some(Value::String(s[..8].to_string()))
715        }
716        // Compact ISO-8601 timestamps unless inside a caller-supplied payload
717        // object, or the field is a named payload timestamp at any nesting.
718        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        // Recurse into objects and arrays.
726        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        // Everything else passes through.
735        _ => Some(value),
736    }
737}
738
739/// Returns `true` if `s` looks like a canonical UUID (36 chars, standard form).
740fn is_canonical_uuid(s: &str) -> bool {
741    if s.len() != UUID_CANONICAL_LEN {
742        return false;
743    }
744    let b = s.as_bytes();
745    // Pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
746    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
757/// Returns `true` if `s` looks like an ISO-8601 datetime string.
758///
759/// Heuristic: starts with `YYYY-MM-DDTHH:` (16 chars, proper digit positions).
760fn 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
775/// Compact an ISO-8601 timestamp for Agent mode.
776///
777/// - Within the last 24 hours: relative form (e.g. `"3m ago"`, `"2h ago"`).
778/// - Older: minute-granularity absolute form `"YYYY-MM-DDTHH:MM"`.
779fn compact_timestamp(s: &str, now: i64) -> String {
780    // Parse Unix seconds from the timestamp if possible; fall back to truncation.
781    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    // Minute granularity: take the first 16 chars.
788    s.chars().take(16).collect()
789}
790
791/// Attempt to parse an ISO-8601 datetime string to Unix seconds.
792///
793/// Only handles the subset produced by khive handlers:
794/// `YYYY-MM-DDTHH:MM:SS[.frac][Z|±HH:MM|±HHMM]`. Returns `None` for anything
795/// we can't parse (graceful degradation — the timestamp is still compacted
796/// by truncation).
797fn parse_iso8601_unix(s: &str) -> Option<i64> {
798    // Minimum parseable: "YYYY-MM-DDTHH:MM:SS"
799    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    // Simple Gregorian → local-wall-clock Unix seconds, then adjust for any
811    // trailing timezone offset (see `parse_tz_offset_secs`) to get the
812    // actual UTC instant.
813    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
819/// Parse the tail of an ISO-8601 timestamp (everything from byte index 19
820/// onward, i.e. after the whole-seconds field) into a UTC offset in seconds.
821///
822/// Handles, in order: optional fractional seconds (`.nnn`, skipped — this
823/// parser only has whole-second precision), then one of:
824/// - empty string or `"Z"` → offset 0
825/// - `±HH:MM` or the compact `±HHMM` form → `sign * (hh*3600 + mm*60)`
826///
827/// Returns `None` for anything else (malformed tail).
828fn 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        // "HH:MM"
850        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        // "HHMM"
855        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
872/// Gregorian date → days since 1970-01-01. Algorithm: Howard Hinnant's civil.
873fn 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
882/// Format a duration in seconds as a relative time string (e.g. `"3m ago"`).
883fn 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
893/// Truncate a float to 3 significant figures, returning a `serde_json::Value`.
894fn 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    // Re-serialize through serde_json to avoid floating-point noise.
902    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    /// A fixed "now" for deterministic tests: 2026-05-23T16:18:00Z ≈ 1748016480.
913    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(&micros_to_iso(micros)), Ok(micros));
919        // Offset spellings resolve to the same instant; whitespace tolerated.
920        // (NOW's epoch value is 2025-05-23T16:08:00Z despite its comment.)
921        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        // ADR-045 Amendment 3 (issue #1995): a key under `properties` exists
936        // only because a caller wrote it, so `""` there distinguishes
937        // set-to-empty from absent and must survive Agent mode — at any
938        // nesting depth under `properties`.
939        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        // Control: outside `properties` the empty-string drop still applies.
948        assert!(out.get("summary").is_none());
949    }
950
951    #[test]
952    fn agent_drops_scalar_empty_properties_value() {
953        // The carve-out applies only to strings nested under an object-valued
954        // `properties`; a scalar `properties: ""` is the field's own value,
955        // not a caller-written key under it, and drops like any empty string.
956        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        // The amendment's scope note keeps the container drop: empty arrays
967        // and objects under `properties` are not carved out.
968        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        // Far past — not within 24h of NOW. Should be truncated to 16 chars.
1107        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        // 3 minutes before NOW: diff = 180s.
1115        let ts_unix = NOW - 180;
1116        // Format as ISO-8601.
1117        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        // Regression for #871: `schedule.remind`'s create response returns
1126        // `trigger_at` as a top-level convenience field (sibling to `id`,
1127        // `full_id`), not nested under `"properties"`. The pre-existing
1128        // `inside_properties` guard alone did not protect it, so Agent-mode
1129        // compaction rewrote it: `at` here is far outside the 24h relative
1130        // window, so pre-fix it would have been minute-truncated to
1131        // "2026-07-11T19:00", discarding the seconds and the "-04:00"
1132        // offset the caller needs to round-trip the exact value verbatim.
1133        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        // The `trigger_at` exemption is scoped to that field name only — a
1165        // sibling generic timestamp field must still be compacted, so the
1166        // fix does not blanket-disable Agent-mode compaction.
1167        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        // gtd.assign/gtd.tasks/gtd.next return the caller-supplied `due` as
1179        // a top-level convenience field mirroring `properties.due`; it must
1180        // round-trip verbatim through Agent-mode presentation, the same
1181        // guarantee already given to `trigger_at`.
1182        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        // Pre-existing protection (agenda/get responses nest trigger_at
1191        // under "properties") must remain intact alongside the new
1192        // top-level, field-name-based guard.
1193        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    // full_id must never be shortened in Agent mode: it's the caller's
1222    // stable chaining handle.
1223    #[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        // `id` is shortened to 8 chars
1229        assert_eq!(
1230            out["id"],
1231            json!("a1b2c3d4"),
1232            "id should be 8-char short form"
1233        );
1234        // `full_id` must remain the full 36-char UUID
1235        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        // Verify the invariant: full_id starts with the short id prefix
1246        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    /// Format Unix seconds as ISO-8601 for test construction.
1270    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        // Howard Hinnant civil_from_days
1282        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    // ── ADR-078: OutputFormat tests ───────────────────────────────────────────
1362
1363    /// (a) json format preserves full shape (no field dropped, no transformation).
1364    #[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        // full_id must not be dropped in json mode.
1375        assert!(
1376            parsed.get("full_id").is_some(),
1377            "json mode must keep full_id"
1378        );
1379        // namespace must NOT be elided in json mode.
1380        assert_eq!(
1381            parsed.get("namespace").and_then(Value::as_str),
1382            Some("local")
1383        );
1384        // properties must NOT be deduped in json mode.
1385        assert!(parsed.get("properties").is_some());
1386    }
1387
1388    /// (a-vs-auto) auto mode drops redundant fields that json mode preserves.
1389    #[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        // json keeps both; auto drops namespace="local" and full_id.
1399        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        // Auto mode elides namespace=local and drops full_id.
1409        // The value itself is a single record → rendered as compact JSON.
1410        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    /// (b1) homogeneous record array → markdown table with header + separator + rows.
1418    #[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    /// (b2) single record → compact JSON, lossless (kv-block renderer removed).
1437    #[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    /// (b2-lossless) a single record with a large payload field (a compose
1450    /// briefing's `markdown`) arrives whole — the former kv-block renderer
1451    /// truncated it.
1452    #[test]
1453    fn format_auto_single_record_large_payload_survives_whole() {
1454        let briefing = "line one\nline two\n".repeat(500); // ~9KB, newlines included
1455        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    /// Envelope siblings survive table rendering: a `query`-style page whose
1466    /// `has_more` is dropped reads as complete — fail-open.
1467    #[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    /// Nested table cells render a constant elision marker, never
1500    /// truncated pseudo-JSON that reads as data while missing fields.
1501    #[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    /// Arrays of scalars (tags) still render as compact JSON in cells.
1520    #[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    /// Identity/decision columns are exempt from truncation: a truncated
1534    /// title cannot be selected on, a truncated signature is unusable.
1535    #[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    /// Verbose presentation disables cell truncation entirely (ADR-078 §3a).
1555    #[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    /// The pre-pass hoists named scalar payload fields (`trigger_at`, `due`,
1570    /// `status`) out of `properties` so they can surface as table columns —
1571    /// a scheduled event carries them only inside `properties`.
1572    #[test]
1573    fn table_path_hoists_payload_scalars_to_columns() {
1574        // The hoist is table-path only (ADR-078 Amendment 2): two scheduled
1575        // events whose trigger_at/status live inside `properties` must gain
1576        // top-level columns in the rendered table.
1577        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        // Rule-separating control for the table-scoped hoist: the §7 pre-pass
1606        // alone must leave the properties bag in place, so a single record's
1607        // compact-JSON fallback keeps its shape.
1608        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        // Escaping contract: a newline-bearing sibling string must not be able
1631        // to fabricate an additional `key: value` line.
1632        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        // Escaping contract pin: cells collapse \r exactly like \n, so a
1652        // \r- or \r\n-bearing value cannot smuggle a raw line break into
1653        // the table body and forge row structure.
1654        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    /// The hoist never overwrites an existing top-level sibling.
1670    #[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    /// (b3) fallback: auto on heterogeneous/scalar value falls back to compact json.
1694    #[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    /// (c) table format forces markdown table even when shape would normally be kv.
1702    #[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    /// (c-fallback) table format falls back to compact json when no record array found.
1720    #[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        // No record array → compact JSON fallback.
1725        let parsed: Value = serde_json::from_str(&rendered).unwrap();
1726        assert_eq!(parsed["single"], json!("value"));
1727    }
1728
1729    /// (d) redundancy-drop: auto/table skipped in Verbose mode (§7).
1730    #[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        // In Verbose mode, redundancy drop must be skipped.
1738        // The value is a single object → compact JSON; full_id and namespace stay.
1739        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    /// Indirect check that the redundancy pre-pass doesn't corrupt an error
1751    /// envelope's shape; the actual ok=false bypass is enforced by
1752    /// `render_result`, not by this pre-pass.
1753    #[test]
1754    fn redundancy_drop_does_not_corrupt_error_shape() {
1755        let v = json!({"ok": false, "error": "something failed", "namespace": "local"});
1756        // apply_redundancy_drop is a pure value transform with no knowledge of
1757        // `ok`: bypassing it for error envelopes is the caller's job
1758        // (render_result in server.rs). This only checks the pre-pass itself
1759        // doesn't lose the error field.
1760        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    /// Properties dedup removes only keys that match a top-level sibling exactly.
1773    #[test]
1774    fn redundancy_drop_properties_dedup() {
1775        let v = json!({
1776            "id": "abc",
1777            "title": "Same",
1778            "properties": {
1779                "title": "Same",  // duplicate → removed
1780                "extra": "unique" // not at top level → kept
1781            }
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    /// Cell truncation: text > 120 chars gets `...` appended.
1793    #[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        // Cell must be truncated to ~120 chars + "..."
1802        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    /// Cell truncation must not panic on multi-byte UTF-8 characters.
1813    ///
1814    /// A string of 119 ASCII bytes followed by a 3-byte CJK character and more
1815    /// text has `len() > 120` but byte index 120 falls inside the CJK char.
1816    /// The old byte-slice truncation would panic; char-boundary truncation is safe.
1817    #[test]
1818    fn cell_text_truncation_is_utf8_safe() {
1819        // 119 ASCII 'a' bytes, then CJK char U+4E2D (3 bytes each), then more text.
1820        // Total byte length: 119 + 3 * 10 + 5 > 120, but byte 120 is inside a CJK char.
1821        let prefix = "a".repeat(119);
1822        let suffix = "中".repeat(10); // each '中' is 3 bytes
1823        let long_multibyte = format!("{prefix}{suffix}trailing");
1824        let v = json!([
1825            {"col": long_multibyte.clone()},
1826            {"col": "ok"}
1827        ]);
1828        // Must not panic — this was the bug.
1829        let rendered = render_format(v, OutputFormat::Auto, PresentationMode::Agent);
1830        assert!(
1831            rendered.contains("..."),
1832            "multibyte cell must be truncated with ..."
1833        );
1834        // The rendered string must be valid UTF-8 (no partial char slicing).
1835        assert!(
1836            std::str::from_utf8(rendered.as_bytes()).is_ok(),
1837            "rendered output must be valid UTF-8"
1838        );
1839    }
1840
1841    // --- parse_iso8601_unix / relative-time offset handling ---
1842
1843    #[test]
1844    fn parse_iso8601_unix_negative_offset_matches_equivalent_utc() {
1845        // "-04:00" is 4 hours behind UTC, so 11:55 local == 15:55Z.
1846        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        // "+04:00" is 4 hours ahead of UTC, so 20:15 local == 16:15Z.
1855        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        // Fractional seconds are dropped (whole-second precision only) but
1880        // must not prevent the trailing offset from being applied.
1881        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        // No trailing Z/offset at all: existing "no offset" behavior preserved.
1898        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        // Hour out of range (>23), colon and compact forms.
1914        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        // Minute out of range (>59), colon and compact forms.
1917        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        // +23:59 / -23:59 are the largest valid offsets and must still parse.
1924        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        // A wall-clock-identical-to-NOW timestamp carrying a "-02:00" offset
1932        // is actually 2h in the future; an offset-naive parser would misread
1933        // the wall-clock digits as UTC and report "0s ago".
1934        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        // "20:05+04:00" == "16:05Z", which is 3 minutes before NOW
1942        // (2025-05-23T16:08:00Z). Correct offset handling must produce
1943        // "3m ago"; the old offset-naive parser would compare wall-clock
1944        // 20:05 against NOW directly, landing outside the 24h window and
1945        // falling back to truncated absolute form instead.
1946        let out = compact_timestamp("2025-05-23T20:05:00+04:00", NOW);
1947        assert_eq!(out, "3m ago");
1948    }
1949}