Reconcile lifecycle metadata for a session record. Called from agent session start/end hooks. Creates the record if the session has no ledger entries yet; otherwise updates only the fields supplied, preserving ledger data (provenance links, turn count). `ended_at: None` on a re-entered (resumed) session clears a prior end. New `ended_at` values use Unix epoch milliseconds; legacy seconds are stil
(
&mut self,
session_id: &str,
json_path: &str,
view_name: Option<String>,
parent_view: Option<String>,
ended_at: Option<i64>,
)
| 890 | /// New `ended_at` values use Unix epoch milliseconds; legacy seconds are |
| 891 | /// still accepted without changing historical records. |
| 892 | pub fn upsert_session_lifecycle( |
| 893 | &mut self, |
| 894 | session_id: &str, |
| 895 | json_path: &str, |
| 896 | view_name: Option<String>, |
| 897 | parent_view: Option<String>, |
| 898 | ended_at: Option<i64>, |
| 899 | ) -> PristineResult<()> { |
| 900 | use crate::change::session::SessionRecord; |
| 901 | |
| 902 | let mut sessions = self.txn.open_table(SESSIONS)?; |
| 903 | let mut record = match sessions.get(session_id)? { |
| 904 | Some(value) => SessionRecord::from_bytes(value.value()).map_err(|e| { |
| 905 | PristineError::Serialization { |
| 906 | message: format!("session record decode: {}", e), |
| 907 | } |
| 908 | })?, |
| 909 | None => SessionRecord { |
| 910 | session_id: session_id.to_string(), |
| 911 | json_path: json_path.to_string(), |
| 912 | view_name: None, |
| 913 | parent_view: None, |
| 914 | first_provenance: None, |
| 915 | latest_provenance: None, |
| 916 | turn_count: 0, |
| 917 | started_at: chrono::Utc::now().timestamp_millis(), |
| 918 | ended_at: None, |
| 919 | status: crate::change::session::SessionStatus::Active, |
| 920 | }, |
| 921 | }; |
| 922 | |
| 923 | if record.json_path.is_empty() { |
| 924 | record.json_path = json_path.to_string(); |
| 925 | } |
| 926 | if view_name.is_some() { |
| 927 | record.view_name = view_name; |
| 928 | } |
| 929 | if parent_view.is_some() { |
| 930 | record.parent_view = parent_view; |
| 931 | } |
| 932 | // Explicit assignment: Some(ts) ends the session, None clears a |
| 933 | // stale end marker when a session is re-entered. An incomplete outcome |
| 934 | // is terminal until explicit recovery policy exists, so ordinary |
| 935 | // lifecycle callbacks must not erase it. |
| 936 | record.ended_at = ended_at; |
| 937 | if !matches!( |
| 938 | &record.status, |
| 939 | crate::change::session::SessionStatus::Incomplete(_) |
| 940 | ) { |
| 941 | record.status = if ended_at.is_some() { |
| 942 | crate::change::session::SessionStatus::Ended |
| 943 | } else { |
| 944 | crate::change::session::SessionStatus::Active |
| 945 | }; |
| 946 | } |
| 947 | |
| 948 | let bytes = record.to_bytes(); |
| 949 | sessions.insert(session_id, bytes.as_slice())?; |