1use std::collections::{BTreeMap, BTreeSet};
2
3use kmp_domain::{
4 BundleRelationship, DECLARED_FROM_RELATE_METHOD, DimensionSelection, KmpBundle,
5 MemoryRelationType, RelationSemanticClass, TemporalAxis, TemporalCoordinate, TemporalCursor,
6 TemporalDirection, TemporalWindow,
7};
8use serde::Serialize;
9use sha2::{Digest, Sha256};
10
11use crate::ApplicationError;
12
13use super::{TemporalIncludeOptions, TemporalMemoryQuery, TemporalMemoryResult, VisualLabel};
14
15pub const MAX_VISUAL_SOURCE_ENTRIES: usize = 65_536;
16pub const MAX_VISUAL_PAGE_ENTRIES: usize = 2_048;
17pub const MAX_VISUAL_BINS: usize = 512;
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "snake_case")]
21pub enum VisualLevelOfDetail {
22 #[default]
23 Atlas,
24 Episode,
25 Moment,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct VisualProjectionQuery {
30 pub about: String,
31 pub from: String,
32 pub to: String,
33 pub axis: TemporalAxis,
34 pub dimensions: DimensionSelection,
35 pub level_of_detail: VisualLevelOfDetail,
36 pub bin_count: usize,
37 pub page_entries: usize,
38 pub cursor: Option<String>,
39 pub depth: u32,
40}
41
42impl VisualProjectionQuery {
43 pub fn temporal_query(&self) -> Result<TemporalMemoryQuery, ApplicationError> {
44 Ok(TemporalMemoryQuery {
45 entry_selection: None,
46 about: self.about.clone(),
47 direction: TemporalDirection::Goto,
48 axis: self.axis,
49 cursor: Some(TemporalCursor::time(self.to.clone())?),
50 interval: None,
51 dimensions: self.dimensions.clone(),
52 window: TemporalWindow::new(0, 0),
53 limit_entries: Some(MAX_VISUAL_SOURCE_ENTRIES),
54 include: TemporalIncludeOptions {
55 dependencies: false,
56 evidence: false,
57 relations: true,
58 raw_refs: false,
59 },
60 token_budget: 262_144,
61 depth: self.depth.max(1),
62 max_tier: None,
63 })
64 }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68pub struct VisualRange {
69 pub from: String,
70 pub to: String,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct VisualBin {
78 pub dimension: String,
79 pub scope_id: String,
80 pub from: String,
81 pub to: String,
82 pub total: usize,
83 pub by_kind: BTreeMap<String, usize>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87pub struct VisualCluster {
88 pub dimension: String,
89 pub scope_id: String,
90 pub from: String,
91 pub to: String,
92 pub total: usize,
93 pub refs: Vec<String>,
94 pub by_kind: BTreeMap<String, usize>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
98pub struct VisualEntry {
99 pub ref_id: String,
100 pub kind: String,
101 pub text: String,
102 pub coordinates: Vec<TemporalCoordinateView>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
106pub struct TemporalCoordinateView {
107 pub dimension: String,
108 pub scope_id: String,
109 pub occurred_at: Option<String>,
110 pub observed_at: Option<String>,
111 pub ingested_at: Option<String>,
112 pub valid_from: Option<String>,
113 pub valid_until: Option<String>,
114 pub sequence: Option<u32>,
115 pub rank: Option<u32>,
116 #[serde(skip_serializing_if = "Option::is_none")]
119 pub method: Option<String>,
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub why: Option<String>,
122 #[serde(skip_serializing_if = "Option::is_none")]
123 pub motivation: Option<String>,
124}
125
126impl From<&TemporalCoordinate> for TemporalCoordinateView {
127 fn from(value: &TemporalCoordinate) -> Self {
128 Self {
129 dimension: value.dimension().to_string(),
130 scope_id: value.scope_id().to_string(),
131 occurred_at: value.occurred_at().map(ToString::to_string),
132 observed_at: value.observed_at().map(ToString::to_string),
133 ingested_at: value.ingested_at().map(ToString::to_string),
134 valid_from: value.valid_from().map(ToString::to_string),
135 valid_until: value.valid_until().map(ToString::to_string),
136 sequence: value.sequence(),
137 rank: value.rank(),
138 method: value.origin().method().map(ToString::to_string),
139 why: value.origin().rationale().map(ToString::to_string),
140 motivation: value.origin().motivation().map(ToString::to_string),
141 }
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
146pub struct VisualRelation {
147 #[serde(skip_serializing_if = "Option::is_none")]
148 pub clocks: Option<super::MemoryRelationClocks>,
149 pub from: String,
150 pub to: String,
151 pub rel: String,
152 pub class: String,
153 pub why: Option<String>,
154 pub evidence: Option<String>,
155 pub confidence: Option<String>,
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub method: Option<String>,
158}
159
160#[derive(Debug, Clone, PartialEq, Serialize)]
161pub struct VisualMetric {
162 pub name: String,
163 pub value: f64,
164 pub unit: String,
165 pub scope: String,
166}
167
168#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
169pub struct VisualProjectionPage {
170 pub returned: usize,
171 pub total: usize,
172 pub has_more: bool,
173 pub next_cursor: Option<String>,
174}
175
176#[derive(Debug, Clone, PartialEq, Serialize)]
177pub struct VisualProjectionResult {
178 pub contract: String,
179 pub about: String,
180 pub axis: TemporalAxisView,
181 pub level_of_detail: VisualLevelOfDetail,
182 pub range: VisualRange,
183 pub bins: Vec<VisualBin>,
184 pub clusters: Vec<VisualCluster>,
185 pub entries: Vec<VisualEntry>,
186 pub by_kind: BTreeMap<String, usize>,
189 pub relations: Vec<VisualRelation>,
190 pub metrics: Vec<VisualMetric>,
191 pub labels: Vec<VisualLabel>,
196 pub included_dimensions: Vec<String>,
197 pub missing_dimensions: Vec<String>,
198 pub revision: u64,
199 pub content_hash: String,
200 pub page: VisualProjectionPage,
201 pub truncated: bool,
202 pub missing: Vec<String>,
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
206#[serde(rename_all = "snake_case")]
207pub enum TemporalAxisView {
208 Default,
209 Occurred,
210 Observed,
211 Ingested,
212 Validity,
213}
214
215impl From<TemporalAxis> for TemporalAxisView {
216 fn from(value: TemporalAxis) -> Self {
217 match value {
218 TemporalAxis::Default => Self::Default,
219 TemporalAxis::Occurred => Self::Occurred,
220 TemporalAxis::Observed => Self::Observed,
221 TemporalAxis::Ingested => Self::Ingested,
222 TemporalAxis::Validity => Self::Validity,
223 }
224 }
225}
226
227#[derive(Debug, Clone)]
228struct PositionedEntry {
229 entry: VisualEntry,
230 position: i128,
231 position_text: String,
232 labels: BTreeSet<(String, String)>,
234}
235
236pub fn build_visual_projection(
240 query: &VisualProjectionQuery,
241 temporal: TemporalMemoryResult,
242 catalogue: Vec<VisualLabel>,
243) -> Result<VisualProjectionResult, ApplicationError> {
244 let from = timestamp_nanos(&query.from).ok_or_else(|| {
245 ApplicationError::Validation("visual projection `from` is not a timestamp".to_string())
246 })?;
247 let to = timestamp_nanos(&query.to).ok_or_else(|| {
248 ApplicationError::Validation("visual projection `to` is not a timestamp".to_string())
249 })?;
250 if to <= from {
251 return Err(ApplicationError::Validation(
252 "visual projection range requires `to` after `from`".to_string(),
253 ));
254 }
255 let bin_count = query.bin_count.clamp(1, MAX_VISUAL_BINS);
256 let page_entries = query.page_entries.clamp(1, MAX_VISUAL_PAGE_ENTRIES);
257 let revision = temporal.source_bundle.metadata().revision;
258 let content_hash = temporal.source_bundle.metadata().content_hash.clone();
259 let selection_hash = selection_hash(query, revision, &content_hash);
260 let offset = cursor_offset(query.cursor.as_deref(), &selection_hash)?;
261
262 let mut positioned = temporal
263 .traversal
264 .entries()
265 .iter()
266 .filter_map(|entry| {
267 let (position, position_text) = entry
268 .coordinates()
269 .iter()
270 .filter_map(|coordinate| {
271 let value = axis_time(coordinate, query.axis)?;
272 Some((timestamp_nanos(value)?, value.to_string()))
273 })
274 .min_by_key(|(position, _)| *position)?;
275 if position < from || position >= to {
276 return None;
277 }
278 let labels = entry
279 .coordinates()
280 .iter()
281 .map(|coordinate| {
282 (
283 coordinate.dimension().to_string(),
284 coordinate.scope_id().to_string(),
285 )
286 })
287 .collect();
288 Some(PositionedEntry {
289 entry: VisualEntry {
290 ref_id: entry.ref_id().to_string(),
291 kind: entry.kind().to_string(),
292 text: entry.text().to_string(),
293 coordinates: entry
294 .coordinates()
295 .iter()
296 .map(TemporalCoordinateView::from)
297 .collect(),
298 },
299 position,
300 position_text,
301 labels,
302 })
303 })
304 .collect::<Vec<_>>();
305 positioned.sort_by(|left, right| {
306 left.position
307 .cmp(&right.position)
308 .then_with(|| left.entry.ref_id.cmp(&right.entry.ref_id))
309 });
310
311 let by_kind = positioned
312 .iter()
313 .fold(BTreeMap::new(), |mut counts, entry| {
314 *counts.entry(entry.entry.kind.clone()).or_default() += 1;
315 counts
316 });
317 let bins = visual_bins(&positioned, from, to, bin_count);
318 let clusters = if query.level_of_detail == VisualLevelOfDetail::Episode {
319 visual_clusters(&positioned, from, to, bin_count)
320 } else {
321 Vec::new()
322 };
323 let total = positioned.len();
324 let end = offset.saturating_add(page_entries).min(total);
325 let entries = if query.level_of_detail == VisualLevelOfDetail::Moment {
326 positioned[offset.min(total)..end]
327 .iter()
328 .map(|entry| entry.entry.clone())
329 .collect()
330 } else {
331 Vec::new()
332 };
333 let page_returned = if query.level_of_detail == VisualLevelOfDetail::Moment {
334 entries.len()
335 } else {
336 total
337 };
338 let has_more = query.level_of_detail == VisualLevelOfDetail::Moment && end < total;
339 let next_cursor = has_more.then(|| format!("kmp-visual-v1:{selection_hash}:{end}"));
340 let page_refs = entries
341 .iter()
342 .map(|entry| entry.ref_id.clone())
343 .collect::<BTreeSet<_>>();
344 let relations = if query.level_of_detail == VisualLevelOfDetail::Moment {
345 visual_relations(&temporal, &page_refs)
346 } else {
347 Vec::new()
348 };
349 let included_dimensions = positioned
350 .iter()
351 .flat_map(|entry| entry.labels.iter().map(|(dimension, _)| dimension.clone()))
352 .collect::<BTreeSet<_>>()
353 .into_iter()
354 .collect::<Vec<_>>();
355 let labels = VisualLabel::counted(
356 catalogue,
357 positioned.iter().flat_map(|entry| entry.labels.iter()),
358 );
359 let causal = causal_relation_count(&relations);
360 let relation_count = relations.len();
361 let source_truncated = temporal.traversal.page().has_more();
362 let missing = if source_truncated {
363 vec!["visual_source_entries".to_string()]
364 } else {
365 Vec::new()
366 };
367
368 Ok(VisualProjectionResult {
369 contract: "kmp.visual.projection.v1".to_string(),
370 about: query.about.clone(),
371 axis: query.axis.into(),
372 level_of_detail: query.level_of_detail,
373 range: VisualRange {
374 from: query.from.clone(),
375 to: query.to.clone(),
376 },
377 bins,
378 clusters,
379 entries,
380 by_kind,
381 relations,
382 labels,
383 metrics: vec![
384 VisualMetric {
385 name: "entry_count".to_string(),
386 value: total as f64,
387 unit: "entries".to_string(),
388 scope: "selected_range".to_string(),
389 },
390 VisualMetric {
391 name: "relation_count".to_string(),
392 value: relation_count as f64,
393 unit: "relations".to_string(),
394 scope: "selected_subgraph".to_string(),
395 },
396 VisualMetric {
397 name: "causal_density".to_string(),
398 value: ratio(causal, relation_count),
399 unit: "ratio".to_string(),
400 scope: "selected_subgraph".to_string(),
401 },
402 ],
403 included_dimensions,
404 missing_dimensions: temporal.traversal.missing_dimensions().to_vec(),
405 revision,
406 content_hash,
407 page: VisualProjectionPage {
408 returned: page_returned,
409 total,
410 has_more,
411 next_cursor,
412 },
413 truncated: source_truncated || has_more,
414 missing,
415 })
416}
417
418fn visual_bins(entries: &[PositionedEntry], from: i128, to: i128, count: usize) -> Vec<VisualBin> {
419 let span = (to - from).max(1);
420 let mut bins = BTreeMap::<(String, String, usize), (usize, BTreeMap<String, usize>)>::new();
421 for entry in entries {
422 let index = (((entry.position - from) * count as i128) / span)
423 .clamp(0, count.saturating_sub(1) as i128) as usize;
424 for (dimension, scope_id) in &entry.labels {
425 let (total, by_kind) = bins
426 .entry((dimension.clone(), scope_id.clone(), index))
427 .or_default();
428 *total += 1;
429 *by_kind.entry(entry.entry.kind.clone()).or_default() += 1;
430 }
431 }
432 bins.into_iter()
433 .map(
434 |((dimension, scope_id, index), (total, by_kind))| VisualBin {
435 dimension,
436 scope_id,
437 from: nanos_timestamp(from + span * index as i128 / count as i128),
438 to: nanos_timestamp(from + span * (index + 1) as i128 / count as i128),
439 total,
440 by_kind,
441 },
442 )
443 .collect()
444}
445
446fn visual_clusters(
447 entries: &[PositionedEntry],
448 from: i128,
449 to: i128,
450 count: usize,
451) -> Vec<VisualCluster> {
452 let span = (to - from).max(1);
453 let mut clusters = BTreeMap::<(String, String, usize), Vec<&PositionedEntry>>::new();
454 for entry in entries {
455 let index = (((entry.position - from) * count as i128) / span)
456 .clamp(0, count.saturating_sub(1) as i128) as usize;
457 for (dimension, scope_id) in &entry.labels {
458 clusters
459 .entry((dimension.clone(), scope_id.clone(), index))
460 .or_default()
461 .push(entry);
462 }
463 }
464 clusters
465 .into_iter()
466 .map(|((dimension, scope_id, _), entries)| {
467 let mut by_kind = BTreeMap::new();
468 let mut refs = Vec::new();
469 for entry in &entries {
470 *by_kind.entry(entry.entry.kind.clone()).or_default() += 1;
471 refs.push(entry.entry.ref_id.clone());
472 }
473 VisualCluster {
474 dimension,
475 scope_id,
476 from: entries
477 .first()
478 .map(|entry| entry.position_text.clone())
479 .unwrap_or_default(),
480 to: entries
481 .last()
482 .map(|entry| entry.position_text.clone())
483 .unwrap_or_default(),
484 total: entries.len(),
485 refs,
486 by_kind,
487 }
488 })
489 .collect()
490}
491
492fn visual_relations(
493 temporal: &TemporalMemoryResult,
494 refs: &BTreeSet<String>,
495) -> Vec<VisualRelation> {
496 temporal
497 .source_bundle
498 .relationships()
499 .iter()
500 .filter(|relation| {
501 relation.explanation().semantic_class()
502 != &kmp_domain::RelationSemanticClass::Structural
503 && ((refs.contains(relation.source_node_id())
504 && refs.contains(relation.target_node_id()))
505 || (relation.relationship_type() == "supports"
506 && refs.contains(relation.target_node_id())))
507 })
508 .map(visual_relation)
509 .collect()
510}
511
512fn visual_relation(relation: &BundleRelationship) -> VisualRelation {
513 let explanation = relation.explanation();
514 let clocks = super::MemoryRelationClocks {
515 occurred_at: explanation.occurred_at().map(ToString::to_string),
516 observed_at: explanation.observed_at().map(ToString::to_string),
517 ingested_at: explanation.ingested_at().map(ToString::to_string),
518 valid_from: explanation.valid_from().map(ToString::to_string),
519 valid_until: explanation.valid_until().map(ToString::to_string),
520 };
521 VisualRelation {
522 clocks: (clocks != Default::default()).then_some(clocks),
523 from: relation.source_node_id().to_string(),
524 to: relation.target_node_id().to_string(),
525 rel: relation.relationship_type().to_string(),
526 class: relation.explanation().semantic_class().as_str().to_string(),
527 why: relation.explanation().rationale().map(ToString::to_string),
528 evidence: relation.explanation().evidence().map(ToString::to_string),
529 confidence: relation.explanation().confidence().map(ToString::to_string),
530 method: relation.explanation().method().map(ToString::to_string),
531 }
532}
533
534pub(super) fn declared_equivalences(bundle: &KmpBundle) -> Vec<VisualRelation> {
537 bundle
538 .relationships()
539 .iter()
540 .filter(|relation| {
541 let proof = relation.explanation();
542 MemoryRelationType::new(relation.relationship_type())
543 .is_ok_and(|kind| kind.may_cross_abouts())
544 && proof.semantic_class() == &RelationSemanticClass::Evidential
545 && proof
546 .method()
547 .is_some_and(|method| method.starts_with(DECLARED_FROM_RELATE_METHOD))
548 && proof.rationale().is_some_and(|why| !why.trim().is_empty())
549 && proof
550 .evidence()
551 .is_some_and(|evidence| !evidence.trim().is_empty())
552 })
553 .map(visual_relation)
554 .collect()
555}
556
557pub(super) fn include_owned_declarations(
558 projection: &mut VisualProjectionResult,
559 declarations: Vec<VisualRelation>,
560) {
561 let refs: BTreeSet<_> = projection
562 .entries
563 .iter()
564 .map(|entry| entry.ref_id.as_str())
565 .collect();
566 let mut keys: BTreeSet<_> = projection
567 .relations
568 .iter()
569 .map(|edge| (edge.from.clone(), edge.rel.clone(), edge.to.clone()))
570 .collect();
571 for relation in declarations {
572 if refs.contains(relation.from.as_str())
573 && keys.insert((
574 relation.from.clone(),
575 relation.rel.clone(),
576 relation.to.clone(),
577 ))
578 {
579 projection.relations.push(relation);
580 }
581 }
582 for metric in &mut projection.metrics {
583 match metric.name.as_str() {
584 "relation_count" => metric.value = projection.relations.len() as f64,
585 "causal_density" => {
586 metric.value = ratio(
587 causal_relation_count(&projection.relations),
588 projection.relations.len(),
589 )
590 }
591 _ => {}
592 }
593 }
594}
595
596fn axis_time(coordinate: &TemporalCoordinate, axis: TemporalAxis) -> Option<&str> {
597 match axis {
598 TemporalAxis::Default => coordinate
599 .occurred_at()
600 .or(coordinate.valid_from())
601 .or(coordinate.observed_at())
602 .or(coordinate.ingested_at()),
603 TemporalAxis::Occurred => coordinate.occurred_at(),
604 TemporalAxis::Observed => coordinate.observed_at(),
605 TemporalAxis::Ingested => coordinate.ingested_at(),
606 TemporalAxis::Validity => coordinate.valid_from().or(coordinate.valid_until()),
607 }
608}
609
610fn selection_hash(query: &VisualProjectionQuery, revision: u64, content_hash: &str) -> String {
611 let mut hasher = Sha256::new();
612 hasher.update(query.about.as_bytes());
613 hasher.update(query.from.as_bytes());
614 hasher.update(query.to.as_bytes());
615 hasher.update(format!("{:?}", query.axis).as_bytes());
616 hasher.update(format!("{:?}", query.dimensions).as_bytes());
617 hasher.update(format!("{:?}", query.level_of_detail).as_bytes());
618 hasher.update(query.bin_count.to_le_bytes());
619 hasher.update(revision.to_le_bytes());
620 hasher.update(content_hash.as_bytes());
621 format!("{:x}", hasher.finalize())[..24].to_string()
622}
623
624fn cursor_offset(cursor: Option<&str>, selection_hash: &str) -> Result<usize, ApplicationError> {
625 let Some(cursor) = cursor else {
626 return Ok(0);
627 };
628 let mut parts = cursor.split(':');
629 let valid = parts.next() == Some("kmp-visual-v1")
630 && parts.next() == Some(selection_hash)
631 && parts.clone().count() == 1;
632 let offset = parts.next().and_then(|value| value.parse::<usize>().ok());
633 if !valid || offset.is_none() {
634 return Err(ApplicationError::Validation(
635 "visual projection cursor is malformed or belongs to another selection".to_string(),
636 ));
637 }
638 Ok(offset.unwrap_or_default())
639}
640
641fn ratio(numerator: usize, denominator: usize) -> f64 {
642 if denominator == 0 {
643 0.0
644 } else {
645 numerator as f64 / denominator as f64
646 }
647}
648
649fn causal_relation_count(relations: &[VisualRelation]) -> usize {
650 relations
651 .iter()
652 .filter(|relation| relation.class == "causal")
653 .count()
654}
655
656fn timestamp_nanos(value: &str) -> Option<i128> {
657 if let Some(value) = value.strip_prefix("unix:") {
658 let (seconds, nanos) = value.split_once(':')?;
659 let seconds = seconds.parse::<i128>().ok()? - 100_000_000_000i128;
660 let nanos = nanos.parse::<i128>().ok()?;
661 return Some(seconds * 1_000_000_000 + nanos);
662 }
663 basic_rfc3339_nanos(value)
664}
665
666fn nanos_timestamp(value: i128) -> String {
667 let seconds = value.div_euclid(1_000_000_000);
668 let nanos = value.rem_euclid(1_000_000_000);
669 format!("unix:{:012}:{:09}", seconds + 100_000_000_000i128, nanos)
670}
671
672fn basic_rfc3339_nanos(value: &str) -> Option<i128> {
673 let value = value.trim();
674 if value.len() < 20 {
675 return None;
676 }
677 let number = |from: usize, to: usize| -> Option<i64> { value.get(from..to)?.parse().ok() };
678 let year = number(0, 4)?;
679 let month = number(5, 7)?;
680 let day = number(8, 10)?;
681 let hour = number(11, 13)?;
682 let minute = number(14, 16)?;
683 let second = number(17, 19)?;
684 if value.get(4..5)? != "-"
685 || value.get(7..8)? != "-"
686 || value.get(10..11)? != "T"
687 || value.get(13..14)? != ":"
688 || value.get(16..17)? != ":"
689 {
690 return None;
691 }
692 let tail = value.get(19..)?;
693 let timezone_start = tail
694 .char_indices()
695 .find_map(|(index, character)| matches!(character, 'Z' | '+' | '-').then_some(index))?;
696 let fraction = tail.get(..timezone_start)?;
697 let timezone = tail.get(timezone_start..)?;
698 let nanos = match fraction.strip_prefix('.') {
699 Some(digits) if !digits.is_empty() && digits.len() <= 9 => {
700 let padded = format!("{digits:0<9}");
701 padded.parse::<i128>().ok()?
702 }
703 None if fraction.is_empty() => 0,
704 _ => return None,
705 };
706 let offset_seconds = match timezone {
707 "Z" => 0,
708 offset if offset.len() == 6 && offset.get(3..4) == Some(":") => {
709 let sign = match offset.get(..1)? {
710 "+" => 1,
711 "-" => -1,
712 _ => return None,
713 };
714 let hours = offset.get(1..3)?.parse::<i64>().ok()?;
715 let minutes = offset.get(4..6)?.parse::<i64>().ok()?;
716 if hours > 23 || minutes > 59 {
717 return None;
718 }
719 sign * (hours * 3_600 + minutes * 60)
720 }
721 _ => return None,
722 };
723 let seconds = days_from_civil(year, month, day) * 86_400 + hour * 3_600 + minute * 60 + second
724 - offset_seconds;
725 Some(seconds as i128 * 1_000_000_000 + nanos)
726}
727
728fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
729 let year = if month <= 2 { year - 1 } else { year };
730 let era = if year >= 0 { year } else { year - 399 } / 400;
731 let year_of_era = year - era * 400;
732 let day_of_year = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
733 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
734 era * 146_097 + day_of_era - 719_468
735}
736
737#[cfg(test)]
738mod tests {
739 use super::*;
740
741 #[test]
742 fn sortable_and_rfc3339_timestamps_share_one_coordinate_space() {
743 assert_eq!(
744 timestamp_nanos("2026-08-27T12:00:00Z"),
745 timestamp_nanos("unix:101787832000:000000000")
746 );
747 assert_eq!(
748 timestamp_nanos("2026-08-27T14:00:00.125+02:00"),
749 timestamp_nanos("unix:101787832000:125000000")
750 );
751 }
752
753 #[test]
754 fn projection_cursor_is_bound_to_its_selection() {
755 assert_eq!(cursor_offset(None, "abc").expect("first page"), 0);
756 assert_eq!(
757 cursor_offset(Some("kmp-visual-v1:abc:12"), "abc").expect("same selection"),
758 12
759 );
760 assert!(cursor_offset(Some("kmp-visual-v1:def:12"), "abc").is_err());
761 }
762
763 #[test]
764 fn visual_causal_density_does_not_count_other_explanatory_classes() {
765 let relation = |class: &str| VisualRelation {
766 clocks: None,
767 from: "a".to_string(),
768 to: "b".to_string(),
769 rel: "rel".to_string(),
770 class: class.to_string(),
771 why: None,
772 evidence: None,
773 confidence: None,
774 method: None,
775 };
776 let relations = [
777 relation("causal"),
778 relation("evidential"),
779 relation("motivational"),
780 ];
781
782 assert_eq!(causal_relation_count(&relations), 1);
783 }
784}